FreeBSD SSH and Two Factor Authentication

It's 2018. There's pretty much no excuse for not having two factor authentication (2FA) setup on on all your accounts.

One of things you should have 2FA setup on is your servers that you SSH into. Of course, you should be disabling SSH password logins, and only use SSH keys. But you may have some bastion hosts that you allow password logins on, and on those server, you should setup TOTP authentication.

Here's how to do it on FreeBSD:

  • Install Google Authenticator (or some other TOTP-based 2FA program) on your phone or device.
  • Install the Google Authenticator PAM module:
$ sudo pkg install pam_google_authenticator
  • Next, generate a token for your server and answer some simple questions:
$ google-authenticator

Do you want authentication tokens to be time-based (y/n) y
https://www.google.com/chart?chs=200x200&chld=M|0&cht=qr&chl=otpauth....
Your new secret key is: SN6DNZ2W7Z2R56BL
Your verification code is 934157
Your emergency scratch codes are:
  38875904
  94027394
  76418491
  71483023
  75284805

Do you want me to update your "/home/user/.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) n

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
  • Go to the URL given, and you will see a QR code similar to the follow. Add it into your Google Authenticator app.
QR Code
  • Add the following line to /etc/pam.d/sshd:
auth  required  pam_google_authenticator.so
  • Restart SSH: sudo service sshd restart

You should know be prompt for your TOTP token when you log in now:

$ ssh example.org
Password for user@example.org:
Verification code:
Tagged , , ,