Two (2)-Factor-Authentication (2FA) for SSH

The following steps are system relevant (critical) and only recommended for advanced linux users. If the ssh configuration will fail, you won’t be able to login to your system via ssh anymore. The mandatory prerequisite is a ssh server that you can log on using private/public key only!



Install the software for 2FA (Two-Factor-Authentication) with googles authenticator app

sudo -s
apt install libpam-google-authenticator

Leave the root-Shell and run the following command as your user


You will be asked for:

Do you want authentication tokens to be time-based (y/n) y
Do you want me to update your "~/.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

Change to the root-Shell again

sudo -s

and configure your ssh server

vi /etc/pam.d/sshd

Change the file to

# PAM configuration for the Secure Shell service

# Standard Un*x authentication.
# @include common-auth
auth required

Save and quit (:wq!) the file.

Edit your SSH-config to examplarily mine

vi /etc/ssh/sshd_config
Port 22
Protocol 2
HostKey /etc/ssh/ssh_host_rsa_key
HostKey /etc/ssh/ssh_host_dsa_key
HostKey /etc/ssh/ssh_host_ecdsa_key
HostKey /etc/ssh/ssh_host_ed25519_key
UsePrivilegeSeparation yes
KeyRegenerationInterval 3600
ServerKeyBits 1024
SyslogFacility AUTH
LogLevel INFO
LoginGraceTime 30
PermitRootLogin no
StrictModes yes
RSAAuthentication yes
PubkeyAuthentication yes
IgnoreRhosts yes
RhostsRSAAuthentication no
HostbasedAuthentication no
IgnoreUserKnownHosts yes
PermitEmptyPasswords no
ChallengeResponseAuthentication yes
PasswordAuthentication no
X11Forwarding no
X11DisplayOffset 10
PrintMotd no
PrintLastLog no
TCPKeepAlive yes
Banner /etc/ssh/issue
AcceptEnv LANG LC_*
Subsystem sftp /usr/lib/openssh/sftp-server
UsePAM yes
AuthenticationMethods publickey,keyboard-interactive
AllowUsers your_ssh_user(s)

Restart your ssh server and re-logon to your server. You will be prompt for a second factor.

© 2016, rieger::CLOUD

Start your google authenticator app (on iOS or on android) and read your second factor.