Setting Up Two-Factor Authentication (2FA) for SSH
Add an extra layer of security to your SSH logins by requiring a time-based one-time password (TOTP) in addition to your SSH key.
Step 1: Install Google Authenticator Module
sudo apt-get install libpam-google-authenticator -y
CopyStep 2: Configure 2FA for Your User
While logged in as the user you want to enable 2FA for, run:
google-authenticator
CopyAnswer "yes" to the questions and scan the QR code with your authenticator app (e.g., Google Authenticator, Authy).
Step 3: Configure SSH to Use 2FA
Edit `/etc/pam.d/sshd` and add this line at the top:
auth required pam_google_authenticator.so
CopyEdit `/etc/ssh/sshd_config` and ensure these values are set:
ChallengeResponseAuthentication yes
AuthenticationMethods publickey,keyboard-interactive
CopyFinally, restart the SSH service: `sudo systemctl restart sshd`.