萬盛學電腦網

您现在的位置: 萬盛學電腦網 >> 程式設計 >  >> 伺服器教學

Linux SSH 服務埠修改與安全強化配置實戰

雙重防護策略:TCP Wrappers + 埠口修改

步驟一:TCP Wrappers 限制存取 IP

# 1. 拒絕所有 SSH 連線
echo "sshd:ALL" >> /etc/hosts.deny

# 2. 允許特定 IP/網段
echo "sshd:192.168.1.16" >> /etc/hosts.allow
# 或允許網段
echo "sshd:192.168.1.0/255.255.255.0" >> /etc/hosts.allow
# 或允許主機名
echo "sshd:trusted.host.domain" >> /etc/hosts.allow

生效順序:hosts.allow 優先 → hosts.deny → 未匹配則允許

步驟二:修改 SSH 預設埠口 22

1. 編輯 sshd_config

vim /etc/ssh/sshd_config

# 找到 #Port 22,修改為雙埠過渡期:
Port 22
Port 9999

# 過渡期驗證無誤後,僅保留新埠:
# Port 9999

2. 重啟 SSH 服務

/etc/init.d/sshd restart
# 或
systemctl restart sshd

3. 防火牆開放新埠

# iptables
iptables -A INPUT -p tcp --dport 9999 -j ACCEPT
service iptables save

# firewalld
firewall-cmd --permanent --add-port=9999/tcp
firewall-cmd --reload

# ufw
ufw allow 9999/tcp

4. 客戶端連線驗證

ssh -p 9999 user@server
# 或配置 ~/.ssh/config
Host myserver
    HostName server.ip
    Port 9999
    User myuser

5. 確認無誤後關閉埠 22

# 移除 sshd_config 中的 Port 22
# 移除防火牆 22 埠規則
iptables -D INPUT -p tcp --dport 22 -j ACCEPT
service iptables save
/etc/init.d/sshd restart

為何採用雙埠過渡期?

防止修改配置過程中斷線、配置錯誤導致完全無法連線,必須跑機房掛顯示器鍵盤修復。雙埠並行驗證成功後再關閉舊埠,風險為零。

進階 SSH 安全強化(配合埠口修改)

1. 禁用 Root 直接登入

PermitRootLogin no
# 或僅允許金鑰
PermitRootLogin prohibit-password

2. 僅允許特定用戶/群組

AllowUsers admin deploy@192.168.1.*
AllowGroups sshusers

3. 強制金鑰認證

PasswordAuthentication no
PubkeyAuthentication yes
AuthorizedKeysFile .ssh/authorized_keys

4. 協議版本限制

Protocol 2

5. 閒置超時斷線

ClientAliveInterval 300
ClientAliveCountMax 2
# 5分鐘無回應斷線

6. 登入橫幅告知

# 建立 /etc/ssh/banner.txt
echo "*** Authorized Access Only ***" > /etc/ssh/banner.txt

# sshd_config
Banner /etc/ssh/banner.txt

7. 失敗嘗試限制

MaxAuthTries 3
MaxSessions 2

完整配置檢查清單

# 語法檢查
sshd -t

# 顯示生效配置
sshd -T | grep -E 'port|permitroot|passwordauth|pubkey|protocol|banner|clientalive|maxauth'

# 連線測試
ssh -vvv -p 9999 user@server

緊急救援方案

  • VNC/IPMI/KVM 遠程主控台
  • 單用戶模式啟動修復
  • LiveCD 掛載根分區修改配置
  • 雲端廠商 Serial Console
copyright © 萬盛學電腦網 all rights reserved