Hop
Search…
SSH 2FA
Set up SSH 2FA with google authenticator
This article goes over installing google authenticator on an Ubuntu server to enable 2FA authentication when performing SSH
Note: It's recommdend that you try setting up 2FA on a test server first, so you are not locked out of your server in case something goes wrong. It's also important to fully test the authentication before going live since a misconfiguration could leave your server less secure.

Install google authenticator

1
sudo apt install libpam-google-authenticator -y
Copied!

Edit pam config

1
sudo vim /etc/pam.d/sshd
Copied!
Add to bottom of pam sshd file
1
auth required pam_google_authenticator.so
2
auth required pam_permit.so
Copied!
Comment @include common-auth so it looks like this
1
# Standard Un*x authentication.
2
# @include common-auth
Copied!

Edit sshd config

1
sudo vim /etc/ssh/sshd_config
Copied!
Make sure to have these settings enabled
1
ChallengeResponseAuthentication yes
2
UsePAM yes
Copied!
Add to bottom of sshd_config file
1
AuthenticationMethods publickey,keyboard-interactive
Copied!

Restart SSH service

1
sudo systemctl restart sshd.service
Copied!

Setup 2FA for user

Run the google-authenticator command and follow the on-screen prompts
1
google-authenticator
Copied!
First, it will ask you about time-based tokens. Say y to this question:
1
Do you want authentication tokens to be time-based: y
Copied!
You will now see a big QR code on your screen, scan it with your Google Authenticator app to add it. You will also see your secret and a few backup codes looking like this:
1
Your new secret key is: IRG2TALMR5U2LK5VQ5AQIG3HA4
2
Your verification code is 282436
3
Your emergency scratch codes are:
4
29778030
5
86888537
6
50553659
7
41403052
8
82649596
9
Copied!
Record the emergency scratch codes somewhere safe in case you need to log into the machine but don't have your 2FA app handy. Without the app, you will no longer be able to SSH into the machine!
Finally, it will ask you for some more parameters; the recommended defaults are as follows:
1
Do you want me to update your "/<username>/.google_authenticator" file: y
2
Do you want to disallow multiple uses of the same authentication token: y
3
By default... < long story about time skew > ... Do you want to do so: n
4
Do you want to enable rate-limiting: y
Copied!

Disable google authenticator

Edit pam config

1
sudo vim /etc/pam.d/sshd
Copied!
Uncomment @include common-auth so it looks like this
1
# Standard Un*x authentication.
2
@include common-auth
Copied!
Comment these lines so it looks like this
1
# auth required pam_google_authenticator.so
2
# auth required pam_permit.so
Copied!

Edit sshd config

1
sudo vim /etc/ssh/sshd_config
Copied!
Change AuthenticationMethods to only allow publickey
1
AuthenticationMethods publickey
Copied!

Restart SSH service

1
sudo systemctl restart sshd.service
Copied!