SSH 安全:Linux 伺服器保安終極指南

## SSH 安全:Linux 伺服器保安終極指南 作為 IT 人,你部 Linux server 日日俾人撞 SSH 密碼㗎。只要睇下 `/var/log/auth.log` 就會發現成堆 bot 喺度 brute-force attack。SSH 安全唔係 optional,係 mandatory!今日同大家分享 SSH 安全嘅 5 個實用步驟,全部有 CLI command,copy 即用。...

## SSH 安全:Linux 伺服器保安終極指南

作為 IT 人,你部 Linux server 日日俾人撞 SSH 密碼㗎。只要睇下 `/var/log/auth.log` 就會發現成堆 bot 喺度 brute-force attack。SSH 安全唔係 optional,係 mandatory!今日同大家分享 SSH 安全嘅 5 個實用步驟,全部有 CLI command,copy 即用。

👉 延伸閱讀:Linux Server 安全加固 6 步搞掂 — Defense in Depth 實戰指南

### SSH 安全第一步:改用 Key-Based Authentication

Password authentication 係最弱嘅一環。改用 SSH key 係 SSH 安全嘅第一道防線。喺你 local machine run:

ssh-keygen -t ed25519 -C "your_email@example.com"
ssh-copy-id user@your-server

然後 disable password login。呢個係 SSH 安全最基本嘅設定:

sudo sed -i 's/#PasswordAuthentication yes/PasswordAuthentication no/' /etc/ssh/sshd_config
sudo sed -i 's/#ChallengeResponseAuthentication yes/ChallengeResponseAuthentication no/' /etc/ssh/sshd_config

### SSH 安全第二步:改 Default Port

雖然 security by obscurity 唔係萬能,但改 port 可以減少 99% 嘅 automated scan。SSH 安全嘅第二層就係令 attacker 搵唔到你:

sudo sed -i 's/#Port 22/Port 2222/' /etc/ssh/sshd_config

記得 firewall 都要開新 port:

sudo ufw allow 2222/tcp
sudo ufw delete allow 22/tcp

### SSH 安全第三步:安裝 Fail2Ban

Fail2Ban 會自動 ban 重複 fail login 嘅 IP。呢個係 SSH 安全嘅 active defense:

sudo apt install fail2ban -y
sudo cp /etc/fail2ban/jail.conf /etc/fail2ban/jail.local

喺 `/etc/fail2ban/jail.local` 搵到 `[sshd]` section,改設定:

[sshd]
enabled = true
port = 2222
maxretry = 3
bantime = 3600
findtime = 600

Restart Fail2Ban 令 SSH 安全設定生效:

sudo systemctl restart fail2ban
sudo fail2ban-client status sshd

### SSH 安全第四步:限制 SSH 用戶

唔係個個 user 都需要 SSH access。限制 SSH 安全嘅 access scope:

echo "AllowUsers admin deployuser" | sudo tee -a /etc/ssh/sshd_config

如果你有用 group 管理,可以咁做:

echo "AllowGroups sshusers" | sudo tee -a /etc/ssh/sshd_config
sudo groupadd sshusers
sudo usermod -aG sshusers admin

### SSH 安全第五步:啟用 2FA

最後一道 SSH 安全防線:two-factor authentication。裝 Google Authenticator:

sudo apt install libpam-google-authenticator -y
google-authenticator

Edit `/etc/pam.d/sshd`:

echo "auth required pam_google_authenticator.so" | sudo tee -a /etc/pam.d/sshd

然後改 sshd_config:

sudo sed -i 's/ChallengeResponseAuthentication no/ChallengeResponseAuthentication yes/' /etc/ssh/sshd_config
echo "AuthenticationMethods publickey,keyboard-interactive" | sudo tee -a /etc/ssh/sshd_config
sudo systemctl restart sshd

### SSH 安全總結

做好以上 5 步,你部 server 嘅 SSH 安全已經去到 enterprise grade。記住定時 `sudo apt update && sudo apt upgrade`,同埋定期 review `/var/log/auth.log`。SSH 安全係 ongoing process,唔係一次性 job。

記住:security 永遠係 layered approach,單靠一個 defense 係唔夠嘅。SSH 安全由基本嘅 key auth 到進階嘅 2FA,層層疊加先至穩陣。

🔗 參考資料:NVD NIST 漏洞資料庫

> 📌 SSH 安全係每位 IT admin 嘅基本功。由 key authentication、改 port、Fail2Ban、user restriction 到 2FA,五層防禦缺一不可。定期 audit 你嘅 SSH config,保持系統更新,先可以真正保護你嘅 server。

#SSH安全 #Linux保安 #Fail2Ban #伺服器安全 #ITAdmin