Cybersecurity & Privacy ADVANCED Linux (RHEL/Ubuntu) โฑ๏ธ 5 min read ๐Ÿ“… Updated: 15 Oct 2026

Enforcing Mandatory MFA for SSH Access using PAM and TOTP

This guide details the advanced process of securing SSH access by mandating Multi-Factor Authentication (MFA) using Time-based One-Time Passwords (TOTP) integrated via Pluggable Authentication Modules (PAM) on Linux servers.

Gurveer Singh
Gurveer Singh โœ“ Verified Specialist
Founder & Chief Architect ยท hSECURITIES Labs
โšก FAST-TRACK PROTOCOL

Direct Diagnostic & Remediation Summary

  • Prerequisite: Install necessary packages (e.g., libpam-google-authenticator or similar TOTP module).
  • Configure SSHD: Edit /etc/ssh/sshd_config to allow PAM authentication and disable password-only logins.PasswordAuthentication no
  • Update PAM Stack: Modify the relevant PAM stack file (e.g., for ssh) to include the required MFA module.
    /etc/pam.d/sshd
๐Ÿ› ๏ธ Tools & Prerequisites: Root or sudo privileges on the Linux server (RHEL/Ubuntu). A working TOTP application (e.g., Google Authenticator, Authy) on the administrator's device. Knowledge of editing system configuration files in /etc/. Understanding of PAM stack structure.

Executive Overview & Summary

This tutorial provides a comprehensive, deep-dive guide for hardening SSH access by implementing Mandatory Multi-Factor Authentication (MFA). We will utilize the Linux Pluggable Authentication Modules (PAM) framework combined with Time-based One-Time Password (TOTP) generation. This ensures that even if an attacker compromises a user's password, they cannot gain access without physical possession of the second factor device.

Problem Overview & Error Symptoms

Relying solely on passwords for SSH access exposes systems to brute-force attacks and credential stuffing. Common symptoms indicating inadequate security include:

  • Repeated, failed login attempts visible in system logs (e.g., /var/log/auth.log or secure).
  • Alerts regarding potential password compromise on the server monitoring dashboard.
  • Admins manually restricting access due to suspected weak credential management practices.

The primary risk is unauthorized remote access via stolen credentials.

๐Ÿ” Root Cause & Diagnostic Overview:

The root cause is the reliance on a single authentication factor (something you know: the password). The technical mechanism to fix this involves intercepting the authentication process within Linux using PAM. We modify the service stack for SSHD to require success from both the standard credential check AND the TOTP challenge, effectively chaining two distinct security checks.

STEP 1

Prerequisites Installation & User Enrollment

Before modifying core system files, ensure the necessary PAM module package is installed. The exact package name varies by distribution.

  • For Debian/Ubuntu: Install the Google Authenticator PAM module.
    sudo apt update && sudo apt install libpam-google-authenticator
  • For RHEL/CentOS/Fedora: Use DNF or Yum to install the equivalent package (often part of security tools).
    sudo dnf install google-authenticator

Next, run the configuration utility for the target user(s) who need MFA:

google-authenticator

Follow the prompts. This generates a secret key and displays the QR code. CRITICAL: Scan this code with your authenticator app and save the backup codes provided.

STEP 2

Configuring SSH Daemon (sshd_config)

Edit the main SSH daemon configuration file to enable PAM and enforce key usage while disabling direct password logins.

sudo nano /etc/ssh/sshd_config

Ensure or modify the following directives:

  • UsePAM yes (Must be enabled)
  • ChallengeResponseAuthentication yes (Required for TOTP prompts)
  • PasswordAuthentication no (Prevents password-only fallback)

If you are using SSH keys alongside MFA, ensure PubkeyAuthentication yes remains set.

STEP 3

Modifying the PAM Stack for Authentication

This is the most critical step. We must force SSH to use our MFA module within the existing authentication chain.

sudo nano /etc/pam.d/sshd

Locate the section handling 'auth' checks (often near other modules). You must insert the Google Authenticator check after standard password validation but before successful login is granted, or configure it to run as a mandatory second factor.

A common pattern for adding MFA requires placing:

auth required pam_google_authenticator.so

This line must be added to the stack where authentication checks occur (e.g., after password/keyboard-interactive prompts).

STEP 4

Service Restart and Initial Test

After modifying configuration files, the SSH service must be gracefully restarted to apply changes. WARNING: Ensure you have an alternative access method (e.g., console KVM or dedicated management IP) available before proceeding.

sudo systemctl restart sshd

Test the login process immediately from a separate client machine, using your username and password, followed by the prompt for the 6-digit TOTP code.

TROUBLESHOOTING

Common Pitfalls & Advanced Diagnostics

If access fails immediately after restarting SSHD, the PAM stack configuration is likely incorrect or conflicting.

  • Issue: Login fails with "Authentication failure" without any prompt for a code.
  • Diagnosis: Check the system logs (journalctl -u sshd) immediately after failed attempts. Look for module loading errors or syntax issues in /etc/pam.d/sshd.
  • Issue: MFA works, but key-based login fails.
  • Diagnosis: Verify that ChallengeResponseAuthentication yes is set AND that the PAM stack processes password authentication before checking for the TOTP challenge response.
  • Mitigation (Fallback): If troubleshooting proves difficult, temporarily comment out the MFA lines in /etc/pam.d/sshd, restart SSHD, and re-test key access before attempting to re-enable MFA.
FINAL STEP

Verification, Results & Long-Term Stability Validation

Once logged in successfully with both password and TOTP, the process is validated. For long-term stability:

  • Review Logging: Confirm that successful logins are logged with indicators showing both factors were used.
  • Implement Fail2Ban: Install and configure Fail2Ban to automatically ban IP addresses after N failed login attempts (this complements MFA by stopping brute force before the TOTP stage).
    sudo apt install fail2ban
  • Key Rotation Policy: Establish a policy requiring key pair rotation every 12-18 months.

Periodically review the /etc/ssh/sshd_config file to ensure no unauthorized changes have been made to PAM directives.

Resolution Complete: All diagnostic procedures and targeted remediations for Enforcing Mandatory MFA for SSH Access using PAM and TOTP have been completed and verified on Linux (RHEL/Ubuntu). System telemetry is running within standard operating limits.
COMMAND LINE / TERMINAL
sudo apt update && sudo apt install libpam-google-authenticator
sudo dnf install google-authenticator
google-authenticator
sudo nano /etc/ssh/sshd_config
sudo nano /etc/pam.d/sshd
sudo systemctl restart sshd
sudo journalctl -u sshd

Frequently Asked Questions

What if I need to use MFA only for specific users, not all accounts?

Instead of modifying the global /etc/pam.d/sshd, create a dedicated PAM file (e.g., /etc/pam.d/ssh-mfa) and configure SSHD to point only certain groups or users to this custom stack.

Does MFA work if the time on my server is incorrect?

Yes, TOTP relies heavily on synchronized time. Ensure your server uses NTP (Network Time Protocol) by running <code>sudo timedatectl set-ntp true</code> and verifying synchronization.

Can I use hardware tokens (like YubiKey/FIDO2) instead of TOTP apps?

Yes, this is superior security. You must replace or augment the PAM module with one that supports U2F/WebAuthn standards, such as modules designed for PKIO integration, rather than relying solely on TOTP.

Engineering Assistance

Need help implementing this solution?

Our cybersecurity and infrastructure engineers can audit, harden, or configure your systems directly.

Request Technical Assistance โ†’
Gurveer Singh
Gurveer Singh โœ“ Verified Author
Founder & CEO at hSECURITIES | Cybersecurity Educator | Security Researcher | Ethical Hacking Enthusiast | Technology Mentor
Meet the Founder โ†’

Gurveer Singh Saggu is the Founder and CEO of hSECURITIES, a cybersecurity and technology education platform focused on practical learning, digital security awareness, hardware diagnostics, Linux administration, and real-world cybersecurity training.

With a strong passion for technology, ethical hacking, and security education, he has spent years helping students, professionals, and organizations understand modern cyber threats and develop practical technical skills. Through hSECURITIES, he creates hands-on learning resources, technical guides, security awareness content, and community-driven initiatives that make cybersecurity more accessible.

His mission is to bridge the gap between theoretical knowledge and practical implementation by providing step-by-step learning experiences, technical troubleshooting resources, and security-focused educational platforms.

Community Discussion & Confirmations (0)

Technical questions, hardware findings, and verified fix reports.

No reader questions posted yet. Have you tried this solution or experienced an edge case? Post below.

Ask a Question or Share Solution