Windows XP Windows 7 Windows 2003 Windows Vista Windows 綜合教學 Linux 系統教學
Windows 10 Windows 8 Windows 2008 Windows NT Windows Server 電腦軟體教學
您现在的位置: Windows教程網 >> Windows教程 >  >> Linux 系統教學 >> Linux 教學

Linux 服務器防暴力破解四步走:改端口、禁 Root、強密碼、自動封 IP

編輯:Linux 教學

現狀檢測:是否已被暴力嘗試?

# 統計 SSH 登入失敗 IP 及次數
grep "Failed password" /var/log/secure | awk '{print $(NF-3)}' | sort | uniq -c | sort -nr | head -20
# 輸出範例:
#  1245 192.168.1.100
#   320 203.0.113.45
# 若出現大量失敗記錄,說明正在遭受暴力破解

四步硬化方案

1. 修改 SSH 端口 (避開自動掃描)

vim /etc/ssh/sshd_config
# 找到 #Port 22,改為
Port 2222
# 保留 Port 22 一行可暫時雙開,驗證無誤後註釋掉
systemctl restart sshd
# 之後連接:ssh -p 2222 user@host

2. 設置高強度密碼 / 強制密鑰登入

  • 密碼策略:/etc/security/pwquality.conf 設 minlen=14 dcredit=-1 ucredit=-1 ocredit=-1 lcredit=-1。
  • 最佳實踐:禁用密碼登入,僅允許密鑰:
    PasswordAuthentication no
    PubkeyAuthentication yes
    AuthorizedKeysFile .ssh/authorized_keys
    ChallengeResponseAuthentication no

3. 禁止 Root 遠程登入

vim /etc/ssh/sshd_config
PermitRootLogin no
# 確保前無 # 號
systemctl restart sshd

前提:已建立普通用戶並加入 wheel 組,可 sudo 提權:

useradd -m -G wheel opsadmin
passwd opsadmin
# 訪問時:ssh -p 2222 opsadmin@host → sudo -i

4. 自動封禁暴力破解 IP (Fail2Ban)

yum -y install epel-release
yum -y install fail2ban
vim /etc/fail2ban/jail.local
[sshd]
enabled = true
port = 2222
filter = sshd
logpath = /var/log/secure
maxretry = 3
bantime = 3600
findtime = 600
action = iptables-multiport[name=sshd, port="2222", protocol=tcp]
systemctl enable --now fail2ban
fail2ban-client status sshd

進階加固 (可選)

驗證清單

  1. ssh -p 2222 root@host → 拒絕 (Permission denied)。
  2. ssh -p 2222 opsadmin@host → 密鑰登入成功。
  3. 故意輸錯 3 次密碼/密鑰 → fail2ban-client status sshd 顯示 IP 被 Ban。
  4. iptables -L -n -v | grep 2222 見 DROP 規則。

總結

「改端口、禁 Root、強密鑰、自動封 IP」四步將 SSH 暴力破解成功率從 100% 降至接近 0。配合 Fail2Ban 動態封鎖,實現「攻擊即封鎖、封鎖即告警、告警即響應」的閉環防禦。

Copyright © Windows教程網 All Rights Reserved
措施配置
僅允許特定 IP 登入AllowUsers opsadmin@192.168.1.* 或 Match Address 10.0.0.0/8
啟用 Google Authenticator 2FAyum install google-authenticator + PAM 配置
端口敲門knockd 隱藏 SSH 端口,敲門序列後動態開放
審計所有登入LogLevel VERBOSE 記錄密鑰指紋、IP、時間