Two-factor authentication, or 2FA, confirms a user’s identity via two different factors: something they know and something they have. 2FA is also known as multi-factor authentication, two-step verification, and two-step authentication. This guide explains how to use the Google Authenticator PAM module on Ubuntu for both SSH and sudo authentication.
Before you proceed with this guide, you need the following:
Log in to your Ubuntu server as a non-root user with sudo access. Install the Google Authenticator PAM module.
$ sudo apt install libpam-google-authenticator
Note: Each user connecting to the server will perform these steps.
Run the Google Authenticator setup program. You can run the program without command-line options for an interactive setup, or use the following options:
$ google-authenticator -t -f -d -w 3 -e 10 -r 3 -R 30
These options explained:
Use --help for more options.
The program will update your configuration files and display several values:
Important: Follow the instructions in your 2FA application to create a new entry with the QR code or secret key. Store your emergency codes in a secure location. If you need to reset your code, rerun the program.
These steps disable password authentication. Public/private SSH keys are required for login, and 2FA will be enabled.
$ sudo nano /etc/pam.d/sshd
auth required pam_google_authenticator.so nullok
# @include common-auth
$ sudo nano /etc/ssh/sshd_config
$ sudo systemctl restart ssh
Recovery tip: If there is an error in the SSH configuration and you are unable to log in, use the OneHost Cloud web console.
Configure sudo to require 2FA codes by following these steps.
$ sudo nano /etc/pam.d/common-auth
The 2FA option takes effect immediately. If a user has configured 2FA in Step 2 above, sudo will require 2FA codes in addition to the user password. Once all users have configured 2FA, you can remove the nullok option.
If you lose access to your authenticator app, use one of your emergency backup codes. The codes are one-time use only.
If you are locked out from SSH, you can use the OneHost Cloud web console. The configuration in this guide does not require 2FA for console access.
To disable 2FA for a specific user:
$ sudo rm /home/user/.google_authenticator
To disable 2FA for all users:
Links to download popular client apps:
Learn more about the Google Authenticator PAM module on GitHub.
Powered by BetterDocs