Protect SSH With Two-Factor Authentication

To extra protect your SSH server with an two-factor authentication, you can use the Google Authenticator PAM module.

Every time you login ssh to server you have to enter extra the code from your smartphone.

note: If you activate the google-authenticator for a normal user but not for root you can’t login with the root user directly anymore. You will need to login as the new user first, then switch to the super user with the su or sudo command to get root.

Before you do anything on your server, install the Google Authenticator application. It is available for Android, iOS and BlackBerry. Install the App using the market place or use your mobile browser to go to After this connect to your VPS and switch to the root user.

1. Install Dependencies

# apt-get install libpam-google-authenticator

2. Edit sshd Configuration Files

# nano -w /etc/pam.d/sshd

Add line to end:

auth required

Edit also:

# nano -w /etc/ssh/sshd_config

Change line:

ChallengeResponseAuthentication yes

3. Activate the Two-Factor Authentication For a User

Activate the google-authenticator for the root user or any other user. Switch to the user who should use the two-factor authentication and type in:

# google-authenticator

You can answer the next questions according to your needs.

Do you want authentication tokens to be time-based (y/n): Y


Do you want me to update your "/home/käyttäjätunnus/.google_authenticator" file (y/n): Y


Do you want to disallow multiple uses of the same authentication token? This restricts you to one login about every 30s, but it increases your chances to notice or even prevent man-in-the-middle attacks (y/n): Y


By default, tokens are good for 30 seconds and in order to compensate for possible time-skew between the client and the server, we allow an extra token before and after the current time. If you experience problems with poor time synchronization, you can increase the window from its default size of 1:30min to about 4min. Do you want to do so (y/n): Y


If the computer that you are logging into isn't hardened against brute-force login attempts, you can enable rate-limiting for the authentication module. By default, this limits attackers to no more than 3 login attempts every 30s.


Do you want to enable rate-limiting (y/n): Y

SSH Terminal print QR-Code, Secret Key and Verification code. You can read QR-Code smartphone with Google Authenticator program, if it fail you can manually add with Secret Key.

Dont save these anywhere, these needed only once when account added.

Note: Same time you get emergency scratch code, keep this and put in safe place! You can override google authenticator, if phone missing or something fails!

4. Restart ssh server

# /etc/init.d/ssh restart

You should now have a SSH server with an two-factor authentication!