SSH 登录添加 Google Authenticator 两步验证 双因子认证
安装 Google Authenticator
# 时间与客户端进行校验,确保服务器时间与手机时间一致,避免时差导致严重失败问题
$ ntpdate pool.ntp.org
# Ubuntu
sudo apt install libpam-google-authenticator -y
# CentOS
yum install -y epel-release
yum install -y google-authenticator
修改相关 sshd 文件配置
sudo vim /etc/pam.d/sshd
# @include common-auth # 禁用密码身份验证,在这之前需要配置好 ssh 免密登录
# 在末尾添加如下内容
# Google Authenticator
auth required pam_google_authenticator.so
sudo vim /etc/ssh/sshd_config
Port 8398 # 修改 ssh 端口号
ChallengeResponseAuthentication yes # 默认是 no 改为 yes
PubkeyAuthentication yes # 取消掉注释
PasswordAuthentication no # 取消掉注释,并改为 no
# 文件末尾添加
AuthenticationMethods publickey,keyboard-interactive # 身份验证方式
# 重启 ssh 服务
sudo systemctl restart ssh.service
验证码默认生成方案,全选 y
google-authenticator
通过 Google Authenticator App 扫描生成的二维码或输入生成的秘钥来添加验证权限。
自定义验证码生成方案:
想为哪个用户配置双因子认证,就切换到这个账号下操作。
# 如我的用户名是 hiwb 就 su 用户名 切换过去
su hiwb
# 生成验证码
# -t: 使用 TOTP 验证
# -f: 将配置保存到 ~/.google_authenticator 文件里面
# -d: 不允许重复使用以前使用的令牌
# -w 3: 使用令牌进行身份验证以进行时钟偏移
# -e 5: 生成 5 个紧急备用代码
# -r 3 -R 30: 限速 - 每 30 秒允许 3 次登录
google-authenticator -t -f -d -w 3 -e 5 -r 3 -R 30
# 上方命令回车后显示信息
Do you want authentication tokens to be time-based (y/n) y
Warning: pasting the following URL into your browser exposes the OTP secret to Google:
https://www.google.com/chart?chs=200x200&chld=M|0&cht=qr&chl=otpauth://totp/root@DLSJ-SERVER%3Fsecret%3D3HCXG6DXXCLC6ER4XF5WNEJMBM%26issuer%3DDLSJ-SERVER
# 这里显示二维码图片
Your new secret key is: 3HCXG6DXXCLC6ER4XF5WNEJMBM
Your verification code is 146688
Your emergency scratch codes are:
80036582
98200866
41888657
32910480
27947702
sudo 操作开启二次验证
$ sudo vim /etc/pam.d/common-auth
auth required pam_google_authenticator.so
# 重启SSH服务
sudo systemctl restart ssh.service
使用 Fail2ban 去屏蔽多次尝试密码的 IP
# 安装 fail2ban 软件
sudo apt install -y fail2ban
# 修改配置文件
$ vim /etc/fail2ban/jail.local
[DEFAULT]
ignoreip = 127.0.0.1/8
bantime = 86400
findtime = 600
maxretry = 5
banaction = firewallcmd-ipset
action = %(action_mwl)s
[sshd]
enabled = true
filter = sshd
port = 8398 # 与 /etc/ssh/sshd_config 中 Port 保持一致
action = %(action_mwl)s
logpath = /var/log/secure
# 重启服务
systemctl restart fail2ban