SSH from 2FA to MFA

In our previous discussion, we delved into implementing time-based tokens as a two-factor authentication (2FA) method for SSH. Now, let's take a stride forward and enable private/public keys for SSH authentication on Ubuntu 24 LTS. Additionally, if desired, we can enforce all three factors: time-based tokens, password, and password-protected keys.
Generate an SSH key pair
In your Shell or Powershell, execute the following command:
ssh-keygen -t ed25519
ssh-keygen -t rsa -b 4096
You'll be prompted to enter a password. Choose a robust password (minimum 16 characters, including numbers, lowercase, uppercase, and special characters) and refrain from generating keys without it.
Your keys are stored in your profile folder in .ssh
.
Copy the public key to your server (Windows)
Using Powershell, enter the following command with your server's IP or FQDN:
type $env:USERPROFILE\.ssh\id_rsa.pub | ssh USER@HOST "cat >> .ssh/authorized_keys"
Are you sure you want to continue connecting (yes/no)? yes
Copy the public key to your server (Linux / OSX)
Open your shell and use ssh-copy-id
with your server's IP or FQDN:
ssh-copy-id -i ~/.ssh/id_rsa.pub user@host
Are you sure you want to continue connecting (yes/no)? yes
Add AuthenticationMethods
SSH to your server and add the following line at the bottom of the file /etc/ssh/sshd_config
:
AuthenticationMethods publickey,password publickey,keyboard-interactive
/etc/ssh/sshd_config
publickey
(SSH key)password publickey
(password)keyboard-interactive
(verification code)Restart the SSH daemon:
sudo systemctl restart sshd.service
restart sshd service
Now we have a three-factor authentication setup, bolstering our defenses against brute force attacks =)
Optional - Remove Password Authentication
If you prefer to solely use a key + OTP, then comment out the following line in the file /etc/pam.d/sshd
:
# Standard Un*x authentication.
#@include common-auth
/etc/pam.d/sshd