Implementing Two-Factor Authentication
Implementing Two-Factor Authentication
Adding a second authentication factor significantly increases security by requiring something users have (token) in addition to something they know (password) or are (biometric). Time-based One-Time Passwords (TOTP) provide effective two-factor authentication for SSH.
Install and configure Google Authenticator PAM module:
# Install required packages
sudo apt-get install libpam-google-authenticator # Debian/Ubuntu
sudo yum install google-authenticator # RHEL/CentOS
# Configure PAM for SSH
# Edit /etc/pam.d/sshd
# Add at the beginning for 2FA requirement:
auth required pam_google_authenticator.so nullok
# Modify sshd_config
# ChallengeResponseAuthentication yes
# AuthenticationMethods publickey,keyboard-interactive
Set up 2FA for users:
# As each user, run:
google-authenticator
# Answer configuration questions:
# - Yes to time-based tokens
# - Yes to update .google_authenticator file
# - Yes to disallow multiple uses
# - No to time skew (unless needed)
# - Yes to rate limiting
# Save emergency codes securely!
Create helper script for 2FA enrollment:
#!/bin/bash
# setup_2fa.sh - Automated 2FA setup for users
setup_user_2fa() {
local user=$1
echo "Setting up 2FA for user: $user"
# Switch to user and configure
sudo -u "$user" google-authenticator \
--time-based \
--disallow-reuse \
--rate-limit=3 \
--rate-time=30 \
--window-size=3 \
--force \
--quiet
# Set proper permissions
sudo chmod 600 /home/"$user"/.google_authenticator
echo "2FA setup complete for $user"
}
# Process all SSH users
for user in $(getent group ssh-users | cut -d: -f4 | tr ',' ' '); do
setup_user_2fa "$user"
done