Linux 伺服器上線前必須進行基線加固,降低被入侵風險。本文依據等保、CIS Benchmark 等標準,整理五大維度加固清單,附帶檢查、備份、加固命令,可直接用於生產環境基線核查。
檢查: cat /etc/passwd、cat /etc/shadow 核對保留帳號(bin、daemon、adm、lp、sync、shutdown、halt、mail、operator、games、ftp、nobody 等)。
備份: cp -p /etc/passwd /etc/passwd_bak && cp -p /etc/shadow /etc/shadow_bak
加固: passwd -l <username> 鎖定;passwd -u <username> 解鎖。
檢查: grep PASS /etc/login.defs
備份: cp -p /etc/login.defs /etc/login.defs_bak
加固(編輯 /etc/login.defs):
PASS_MAX_DAYS 90 # 密碼最長使用天數
PASS_MIN_DAYS 0 # 密碼最短使用天數
PASS_WARN_AGE 7 # 到期前警告天數
PASS_MIN_LEN 9 # 最小長度(需 PAM 支援)
檢查: awk -F: '$3==0 {print $1}' /etc/passwd 僅應輸出 root。
加固: 鎖定或刪除多餘 UID 0 帳號。
檢查: cat /etc/pam.d/su 確認含 auth required pam_wheel.so use_uid 或 group=wheel。
加固:
echo "auth required pam_wheel.so group=wheel" >> /etc/pam.d/su
usermod -G wheel adminuser # 將管理員加入 wheel 組
檢查: awk -F: '($2=="") {print $1}' /etc/shadow
加固: 鎖定或強制設置密碼:passwd -l user 或 passwd user。
檢查: systemctl list-unit-files --state=enabled(CentOS 7+)或 chkconfig --list(CentOS 6)。
加固: systemctl disable --now servicename 禁用並停止。常見可關閉:postfix、avahi-daemon、cups、bluetooth、rpcbind 等。
檢查: grep umask /etc/profile /etc/bashrc
加固: 在 /etc/profile 末尾添加 umask 027(新建文件 640、目錄 750)。Web 伺服器慎用,可能影響應用讀寫。
加固: systemctl enable --now sshd,確保 telnet、rsh 未安裝或已禁用。
編輯 /etc/ssh/sshd_config:
AllowUsers *@10.10.0.* # 僅允許 10.10.0.0/16 網段
# 或
AllowUsers admin@192.168.1.100
重啟: systemctl restart sshd
PermitRootLogin no
# 或僅允許金鑰
PermitRootLogin prohibit-password
檢查: cat /etc/hosts.equiv、cat ~/.rhosts
加固: 清空或刪除非必要條目。
# /etc/ssh/sshd_config
Banner none
# 清空 /etc/motd
> /etc/motd
CentOS 6: 註釋 /etc/inittab 中 ca::ctrlaltdel:/sbin/shutdown -t3 -r now
CentOS 7+: systemctl mask ctrl-alt-del.target
編輯 /etc/pam.d/system-auth(或 password-auth):
auth required pam_faillock.so preauth silent deny=5 unlock_time=300
auth required pam_faillock.so authfail deny=5 unlock_time=300
account required pam_faillock.so
解鎖:faillock --user <user> --reset
echo "TMOUT=600" >> /etc/profile # 600 秒無操作自動退出
source /etc/profile
生成加密密碼:grub2-mkpasswd-pbkdf2,將輸出寫入 /etc/grub.d/40_custom,再 grub2-mkconfig -o /boot/grub2/grub.cfg。
編輯 /etc/vsftpd/user_list、/etc/vsftpd/ftpusers 禁止高權限帳號登入 FTP;啟用 chroot_local_user=YES 限制用戶在家目錄。
/var/log/secure、/var/log/audit/audit.log。安全加固非一次性工作,需持續監控、定期複核、隨業務變更調整策略。