TL;DR
Yes! Adding One-Time Passwords (OTPs) to SSH connections significantly improves security by adding a second layer of verification. Even if someone steals your password, they’ll also need the OTP from your phone or authenticator app to log in.
How it Works
SSH normally relies on passwords or SSH keys for authentication. Passwords can be guessed or stolen. Keys can be compromised if your private key file is lost or copied. OTP adds another factor – something you *have* (like a code from an app) – making it much harder for attackers.
Setting up OTP with Google Authenticator
This guide uses Google Authenticator, but other apps like Authy work similarly.
Step 1: Install the necessary packages on your server
- Connect to your server via SSH.
- Update your package lists:
sudo apt update(Debian/Ubuntu) or
sudo yum update(CentOS/RHEL/Fedora).
- Install Google Authenticator PAM module and related tools:
sudo apt install libpam-google-authenticator(Debian/Ubuntu) or
sudo yum install google-authenticator(CentOS/RHEL/Fedora).
Step 2: Configure Google Authenticator for your user
- Run the configuration script:
google-authenticator - Answer the questions. Pay attention to these points:
- Time-based code? Answer ‘y’ (yes).
- Update secrets automatically? Answer ‘y’.
- You’ll be shown a QR code and a secret key. Scan the QR code with your Google Authenticator app on your phone. Keep the secret key safe – you’ll need it if you lose access to your authenticator app.
- The script will generate recovery codes. Store these in a secure place! They allow you to regain access if you lose your phone or can’t access the app.
Step 3: Modify SSH configuration
- Edit the SSH daemon configuration file:
sudo nano /etc/ssh/sshd_config - Add or modify these lines (remove any comments (#) at the beginning of the line):
ChallengeResponseAuthentication yesUsePAM yesAuthenticationMethods publickey,keyboard-interactive:pam(This allows both key and OTP authentication. If you *only* want OTP, remove ‘publickey’.)
- Save the file and exit the editor.
Step 4: Restart SSH service
sudo systemctl restart sshd
Testing the Setup
- Open a *new* SSH connection to your server.
- You should be prompted for your password as usual.
- After entering your password, you’ll now be asked for a verification code from Google Authenticator.
- Enter the current code displayed in the app.
Important Considerations
- Recovery Codes: Store these securely! Losing them and your phone means losing access to your server.
- Authenticator App Security: Protect your phone with a strong passcode/biometrics.
- Key-Based Authentication: Consider using key-based authentication *in addition* to OTP for even stronger security.
- Firewall Rules: Ensure your firewall only allows SSH connections from trusted sources.

