Two-Factor Authentication for Linux Login
Add 2FA to your Linux desktop for enhanced security.
This guide covers setting up Google Authenticator for:
- Desktop login (GDM)
- Screen unlock
- TTY login (Ctrl+Alt+F2, etc.)
Prerequisites
- Debian/Ubuntu Linux with GDM (GNOME Display Manager)
- A smartphone with an authenticator app (Google Authenticator, Aegis, etc.)
Keep a root terminal open while configuring. If something goes wrong, you could lock yourself out.
Install Google Authenticator
sudo apt update
sudo apt install libpam-google-authenticator -y
Configure Authenticator for Your User
Run the setup as your normal user (not root):
google-authenticator
Answer the prompts:
- Time-based tokens? Yes
- Update ~/.google_authenticator? Yes
- Disallow multiple uses? Yes
- Increase time window? No (unless you have clock sync issues)
- Rate limiting? Yes
Scan the QR code with your authenticator app and save the emergency backup codes.
Configure PAM for Desktop Login
Edit the GDM PAM configuration:
sudo vim /etc/pam.d/gdm-password
Add this line at the very top of the file:
auth required pam_google_authenticator.so
We use required without nullok to enforce 2FA for all users.
Configure PAM for TTY Login
Edit the login PAM configuration:
sudo vim /etc/pam.d/login
Add this line at the very top of the file:
auth required pam_google_authenticator.so
This protects console logins (Ctrl+Alt+F2, etc.).
Apply Changes
Restart GDM to apply (this will log you out):
sudo systemctl restart gdm
Login Process
- At the login screen, enter your verification code first
- Then enter your password
This applies to:
- Initial login
- Unlocking after screen lock
- TTY console login
Troubleshooting
Locked Out
If you're locked out, boot into recovery mode:
- Reboot and hold Shift (BIOS) or Esc (UEFI) during boot
- Select Advanced options → Recovery mode
- Choose Root shell
- Remount filesystem as writable:
mount -o remount,rw / - Remove the 2FA line from PAM configs:
nano /etc/pam.d/gdm-password nano /etc/pam.d/login - Reboot:
reboot
Clock Sync Issues
TOTP codes are time-sensitive. If codes aren't working:
sudo apt install ntp
sudo systemctl enable ntp
sudo systemctl start ntp
Multiple Users
Each user needs to run google-authenticator individually to set up their own 2FA.
Security Notes
- Required vs nullok: Using
requiredmeans 2FA is mandatory. Withnullok, users without 2FA configured can still log in with just a password. - Backup codes: Store your emergency backup codes securely offline.
- Recovery: Always have a backup way to access your system (recovery mode, live USB, etc.).