Two Factor Authentication with Google Authenticator
You can enable 2FA for SFTP Gateway using Google Authenticator. The instructions are based on this article, but are slightly adapted for use with SFTP Gateway.
Installing Google Authenticator
Install Google Authenticator:
sudo yum install google-authenticator -y
Set EC2-User Authenticator
Run the following command as the ec2-user
(do not run it as root
):
google-authenticator <<< $'y\ny\ny\nn\ny\n'
This will generate a file /home/ec2-user/.google_authenticator
.
It also uses an answer file that answers 5 questions as y
(except for the 4th question).
You should also see a URL that looks like this: https://www.google.com/chart?chs=200x200&chld=M|0&cht=qr&chl=otpauth://totp/ec2-user@ip-172-31-11-130%3Fsecret%3DHA774ARZXPMD6VBC
Navigate to this url, and scan the barcode with your Google Authenticator app.
Next, run this command to edit the file:
sudo vi /etc/pam.d/sshd
Comment out the second line:
#auth substack password-auth
And append this line to the end:
auth required pam_google_authenticator.so secret=/home/${USER}/key/.google_authenticator
This line basically says to look for the file /home/<username>/key/.google_authenticator
when performing 2FA. The
key
directory is the secret to making this all work, which I'll explain later on.
Next, move the .google_authenticator
file to the key
subdirectory:
cd /home/ec2-user
mkdir key && mv .google_authenticator $_
Make sure newly created users inherit this file as well:
sudo mkdir /etc/skel/key
sudo cp -a /home/ec2-user/key/.google_authenticator /etc/skel/key
(Note: if there are any existing users, make sure the ./key/.google_authenticator
is copied to their home directory
as well)
Next, edit the sshd_config
file:
sudo vi /etc/ssh/sshd_config
(Un)comment the following lines, so that it looks like this:
ChallengeResponseAuthentication yes
#ChallengeResponseAuthentication no
And add the following line above the Match group sftponly
section:
AuthenticationMethods publickey,keyboard-interactive
Note: This line needs to be above the Match group sftponly
section!
Finally, restart sshd
:
sudo service sshd restart
Now, try to SSH in as the ec2-user
. You should be prompted for a Verification code
.
Then, create an SFTP user (addsftpuser
). When you try to connect, it should prompt you for a Verification code
as
well:
sftp -i robtest.key robtest@<ip_address>
Verification code:
Connected to <ip_address>.
sftp>
Explanation about the key subfolder
SFTP over OpenSSH requires that root
have sole ownership of the ChrootDirectory
.
Google Authenticator requires that the <user>
own the .google_authenticator
file, as well as its parent folder.
To avoid this conflict, we place the .google_authenticator
file within a subfolder called key
, which is owned by
the user.