Passwordless ssh and 2FA

Doing a passwordless ssh connection from known to known machines, while asking for 2 factor authentication from unknown machines.

First insttall a 2 Facto Authenticator like The one from LastPass

Configure for passwordless authentication

Run the following commands on the local-machine. The first is needed only once.

ssh-copy-id remote-machine
ssh remote-machine

Configuring 2FA

Run the following on the remote-machine (or the local machine if that is where you want 2FA). Default settings are used.
su -
apt install libpam-google-authenticator libqrencode3
echo "auth required pam_google_authenticator.so" >> /etc/pam.d/sshd
sed -i 's/ChallengeResponseAuthentication no/ChallengeResponseAuthentication yes/g' /etc/ssh/sshd_config 
service ssh restart
google-authenticator -tfD -w 17 -r 3 -R 30 -Q UTF8
Open the App on your phone and scan the QRcode from the terminal or the URL that is given. Now you need to restart the ssh server.

You are now able to connect to a machine using ssh and no password from the machine and user that has a key. From any other machine, you will be asked for an authentication. Use your phone for that.

Extra things that you can do

In sshd_conf you can disallow the root to login with " PermitRootLogin no" and allow only a specific user to login, with "AllowUsers user_name".

You can copy the .google_authenticator on the remote_machine to other places where google authenticator is installed, so you need only one key.

Use the Authenticator for Amazon and other services as well for e.g. you website.