天天看點

給 SSH 啟用二次身份驗證

轉載自:https://mp.weixin.qq.com/s/ssuhFbfaHxxzGmLg6Y2MjA

目前來說,二次驗證(這裡就不做過多解釋了)是比較常用的安全手段,通過設定二次驗證(谷歌或其他工具),就可以有效的避免賬戶密碼的洩露導緻的安全問題。因為,每次登陸前都需要擷取一次性驗證碼,如果沒有驗證碼的話就無法成功登陸。

1、安裝 PAM 子產品

# 時間與用戶端進行校驗
$ ntpdate pool.ntp.org

# Ubuntu
$ sudo apt install -y libpam-google-authenticator

# CentOS7
$ yum install -y epel-release
$ yum install -y google-authenticator
           

2、生成二次驗證代碼

# 生成驗證碼, 哪個賬号需要動态驗證碼,請切換到該賬号下操作

# -t: 使用 TOTP 驗證
# -f: 将配置儲存到 ~/.google_authenticator 檔案裡面
# -d: 不允許重複使用以前使用的令牌
# -w 3: 使用令牌進行身份驗證以進行時鐘偏移
# -e 10: 生成 10 個緊急備用代碼
# -r 3 -R 30: 限速 - 每 30 秒允許 3 次登入

$ google-authenticator -t -f -d -w 3 -e 10 -r 3 -R 30
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/vagrant@vagrant%3Fsecret%3DKZ7QPA11115XTQJQGBFWAIUJBY%26issuer%3Dvagrant
Your new secret key is: KZ7xxx7EI5123xxx123
Your verification code is 90xx71
Your emergency scratch codes are:
  1571xx03
  9968xx56
  2319xx89
  8321xx97
  9730xx15
  3424xx23
  5667xx03
  9408xx86
  7502xx41
  4677xx14
           

3、配置 SSH 服務啟用兩步驗證

# 啟用兩步驗證
$ sudo vim /etc/pam.d/sshd
# @include common-auth  # 将禁用密碼身份驗證
auth required pam_google_authenticator.so  # 禁用密碼驗證

# 修改SSH配置檔案
$ sudo vim /etc/ssh/sshd_config
Port 1090
ChallengeResponseAuthentication yes
PubkeyAuthentication yes
PasswordAuthentication no
AuthenticationMethods publickey,keyboard-interactive

# 重新開機SSH服務
$ sudo systemctl restart ssh.service
           

4、配置 sudo 二次驗證

# 儲存并退出
$ sudo vim /etc/pam.d/common-auth
auth required pam_google_authenticator.so

# 重新開機SSH服務
$ sudo systemctl restart ssh.service
           

5、手機安裝 Google 身份驗證器

  1. 通過此工具掃描上一步生成的二維碼圖形,擷取動态驗證碼
  2. 之後,就可以使用手機進行二次認證了,才能登陸伺服器了

6、使用 Fail2ban 去屏蔽多次嘗試密碼的 IP

# 安裝軟體
$ 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    = 1090
action = %(action_mwl)s
logpath = /var/log/secure

# 重新開機服務
$ systemctl restart fail2ban
           

7、從二次驗證鎖定中恢複

# 禁用特定使用者的二步驗證(無法通路身份驗證器應用程式)
$ sudo vim /etc/ssh/sshd_config
AuthenticationMethods publickey,keyboard-interactive
AuthenticationMethods publickey

# 重新開機SSH服務
$ sudo systemctl restart ssh.service