Commands.page Logo

How to Enable Two-Factor Authentication for Sudo on Ubuntu

Enhancing system security often involves adding layers of verification beyond simple passwords. This article provides a step-by-step guide to configuring the sudo command on Ubuntu to require two-factor authentication (2FA) using the Google Authenticator PAM module. You will learn how to install the necessary packages, generate secret keys, modify configuration files, and verify that the new security layer is active without locking yourself out of your system.

Prerequisites and Warnings

Before proceeding, ensure you have root access or a user account with sudo privileges. It is critical to keep an active root shell open in a separate terminal window while making these changes. If you misconfigure the authentication files, you may lock yourself out of sudo access permanently. Additionally, save the backup codes generated during the setup process in a secure location.

Install the Google Authenticator Package

Open your terminal and update your package list. Then, install the PAM module provided by Google.

sudo apt update
sudo apt install libpam-google-authenticator

Initialize the Google Authenticator

Run the initialization command for your user account. This process generates a secret key and QR code.

google-authenticator

When prompted, answer the configuration questions as follows: 1. Do you want authentication tokens to be time-based? Type y. 2. Do you want me to update your “~/.google_authenticator” file? Type y. 3. Do you want to disallow multiple uses of the same authentication token? Type y. 4. Do you want to increase the rate limiting chances? Type y. 5. Do you want to enable time-based token generation? Type y.

Scan the displayed QR code with your authenticator app (such as Google Authenticator or Authy) on your mobile device. Write down the emergency scratch codes provided in the terminal output.

Configure PAM for Sudo

You must now tell the Ubuntu authentication system to require the token when sudo is used. Open the sudo PAM configuration file with a text editor.

sudo nano /etc/pam.d/sudo

Add the following line at the top of the file, before any other auth lines:

auth required pam_google_authenticator.so

Save the file and exit the editor. This configuration ensures that the Google Authenticator module is checked first during sudo authentication.

Test the Configuration

Do not close your existing terminal sessions yet. Open a new terminal window and attempt to run a sudo command.

sudo ls

You will first be prompted for your verification code from your authenticator app. Enter the code, and then you will be prompted for your user password. If both are accepted, the configuration is successful. If you encounter an error, use the open root shell to revert the changes made to /etc/pam.d/sudo.