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 VPS 安全加固實戰:從帳號管理、SSH 防護到防火牆策略全攻略

編輯:Linux 教學

雖然 Linux 架構本身較 Windows 更具安全優勢,但「裸奔」上線的 VPS 依然是自動化掃描腳本與暴力破解工具的首選目標。本文系統梳理從使用者權限最小化、SSH 服務硬化、防火牆精準放行到核心參數防護的完整加固流程,助您打造經得起實戰考驗的伺服器環境。

一、使用者權限最小化原則

1. 建立專屬管理帳號,禁用 Root 直接登入

# 新增一般使用者
useradd adminuser
passwd adminuser  # 設定強密碼

# 加入 wheel 群組以取得 sudo 權限
usermod -G wheel adminuser

2. 限制 su 僅允許 wheel 群組切換 Root

編輯 /etc/pam.d/su,取消註解:

auth required pam_wheel.so use_uid

編輯 /etc/login.defs 追加:

SU_WHEEL_ONLY yes

或單指令完成:

echo "SU_WHEEL_ONLY yes" >> /etc/login.defs

3. 清理預設無用帳號與群組

# 刪除不必要的系統帳號
for u in adm lp sync shutdown halt news uucp operator games gopher ftp; do userdel $u 2>/dev/null; done
# 刪除對應群組
for g in lp news uucp games dip pppusers; do groupdel $g 2>/dev/null; done

4. 鎖定關鍵認證檔案防竄改

chattr +i /etc/passwd /etc/shadow /etc/group /etc/gshadow

注意:新增使用者前需先 chattr -i 解鎖,操作完成後再加鎖。

二、SSH 服務硬化配置

編輯 /etc/ssh/sshd_config:

Port 23212 # 修改預設 22 埠,建議 >10000
PermitRootLogin no # 禁止 Root 遠端登入
PermitEmptyPasswords no # 禁止空密碼
UseDNS no # 加速連線建立
MaxAuthTries 3 # 限制嘗試次數
ClientAliveInterval 300 # 防止閒置連線佔用資源
ClientAliveCountMax 2

操作建議:先新增自定義埠位並保留 22,驗證新埠位連線成功後再移除 22。修改完成執行 systemctl restart sshd 生效。

三、防火牆精準放行策略

原則:預設拒絕,按需開放。以下腳本自動偵測 SSH 埠位並僅開放 HTTP(80) 與 SSH:

#!/bin/bash
ssh_port=$(netstat -nutlp | grep sshd | grep 0.0.0.0 | awk '{print $4}' | cut -d: -f2)

iptables -F
iptables -F -t nat
iptables -X
iptables -P INPUT DROP
iptables -P OUTPUT ACCEPT
iptables -P FORWARD DROP

iptables -A INPUT -i lo -j ACCEPT
iptables -A INPUT -m state --state ESTABLISHED,RELATED -j ACCEPT
iptables -A INPUT -p tcp -m multiport --dport 80,$ssh_port -j ACCEPT
iptables -A INPUT -p icmp --icmp-type 0 -j ACCEPT  # 僅允許回應封包

service iptables save
exit 0

防誤鎖技巧:執行腳本前先建立 5 分鐘自動關閉防火牆的排程:

crontab -e
# 加入:
*/5 * * * * root /etc/init.d/iptables stop

確認無誤後刪除該排程。

四、核心網絡參數防護

1. 啟用 TCP SYN Cookie 防禦 SYN Flood

echo 1 > /proc/sys/net/ipv4/tcp_syncookies

2. 禁 Ping(ICMP Echo Request)

防火牆層面已處理;若需核心層面雙重保障:

echo 1 > /proc/sys/net/ipv4/icmp_echo_ignore_all

五、持久化配置

將上述 /proc/sys/ 參數寫入 /etc/sysctl.conf,執行 sysctl -p 生效:

net.ipv4.tcp_syncookies = 1
net.ipv4.icmp_echo_ignore_all = 1

總結

安全是持續過程而非一次性動作。完成基礎加固後,建議定期:

  • 審計 /var/log/secure 與 journalctl -u sshd 異常登入
  • 更新系統補丁(yum update -y)
  • 部署入侵偵測(如 AIDE、Rkhunter)與日誌分析(Fail2ban + Logwatch)
  • 備份關鍵配置並演練災難恢復流程

參考延伸閱讀:《Linux VPS 核心參數調優與效能優化實戰》

Copyright © Windows教程網 All Rights Reserved