SSH 登录添加 Google Authenticator 两步验证 双因子认证

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
  • 1
    点赞
  • 4
    收藏
    觉得还不错? 一键收藏
  • 打赏
    打赏
  • 3
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论 3
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包

打赏作者

hiwb

您的鼓励是我创作最大的动力!

¥1 ¥2 ¥4 ¥6 ¥10 ¥20
扫码支付:¥1
获取中
扫码支付

您的余额不足,请更换扫码支付或充值

打赏作者

实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值