ssh开启MFA双因素认证
为了防止咱服务器被嗨客囸穿咱可是煞费苦心,不过ssh没法不用,单用秘钥登录的话有急事电脑不在手上的话就不太方便,开密码登录右容易被暴力破解,在了解到有MFA这个好玩意后,觉得挺不错的,就想拿来用用。
在网上查到很多ssh开启mfa的教程,但是都不适合咱的服务器,没法子,照着翻译和百度把配置文件一条条捋,经过一番摸索,终于找到了能用的配置方法,在此记录一下防止以后遗忘。
此处只针对ubuntu22.04系统,其他系统搞毁了咱概不负责!记得整的时候备份好配置文件!
好了,开冲
一、安装Google Authenticator PAM模块
更新本机软件源和软件包
sudo apt update -y
sudo apt upgrade -y
安装libpam-google-authenticator
sudo apt install libpam-google-authenticator
二、生成身份验证令牌
在此之前,手机需要安装身份验证器,在此推荐使用 Google身份验证器或Microsoft Authenticator,你可以在Google Play或小米应用商店等手机应用商店里下载(首先,排除酷安,没想到你的浓眉大眼的这两个软件竟然都没有)
因为Google服务在国内基本算是个残废,这里咱用的是Microsoft Authenticator
执行生成身份令牌命令
google-authenticator
Do you want authentication tokens to be time-based (y/n) y
----------------------
此处二维码使用手机扫描
已验证ID->扫描QR码
----------------------
Your new secret key is:XXXXXXXXX
Enter code from app (-1 to skip):【输入手机上的六位数字】
Code confirmed
Your emergency scratch codes are:
XXXXXXXX
XXXXXXXX
XXXXXXXX
XXXXXXXX
XXXXXXXX
【剩下的步骤全都输入y即可】
Do you want me to update your "/home/XXXXXX/.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, a new token is generated every 30 seconds by the mobile app.
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. This allows for atime skew of up to 30 seconds between authentication server and client. If you
experience problems with poor time synchronization, you can increase the window
from its default size of 3 permitted codes (one previous code, the current
code, the next code) to 17 permitted codes (the 8 previous codes, the current
code, and the 8 next codes). This will permit for a time skew of up to 4 minutes
between client and server.
Do you want to do so? (y/n) y
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
三、配置ssh使用MFA
打开PAM配置文件/etc/pam.d/sshd
sudo nano /etc/pam.d/sshd
将以下行添加到文件底部
auth required pam_google_authenticator.so nullok
auth required pam_permit.so
打开SSH配置文件/etc/ssh/sshd_config
sudo nano /etc/ssh/sshd_config
找到以下配置参数
ChallengeResponseAuthentication no
将配置参数改为yes
ChallengeResponseAuthentication yes
如果找不到上面参数,直接将其复制粘贴到文件最底部也可
找到PasswordAuthentication
和KbdInteractiveAuthentication
两个配置,将其参数改为以下
(注意:基本上所有教程都没有说关于KbdInteractiveAuthentication
的配置,如果你的文件中默认这个配置是no的话,一定要把它改成yes,否则mfa将不生效!这个让我之前踩了很多的坑 )
PasswordAuthentication no
KbdInteractiveAuthentication yes
保存退出,然后重启ssh服务
sudo service ssh restart
至此,ssh已经成功设置MFA双因素认证登录
在此之后,在不使用密钥的情况下登录ssh,需要先输入ssh密码,再输入MFA动态口令。
这样即使是在别的电脑上登录安全性也有所保障,虽然多了这一步,但应应急够用了。
至于使用秘钥登录的话,该咋样还是咋样,么得如何影响。