一、安全理念与方法论
1.1 安全原则
| 原则 | 描述 |
|---|
| 最小权限原则 | 用户和程序只拥有完成工作所需的最小权限 |
| 纵深防御 | 多层安全措施,单一防线被突破时仍有其他保护 |
| 默认拒绝 | 一切访问默认拒绝,只开放必要的 |
| 安全设计 | 安全是系统设计的一部分,不是事后添加的 |
| 持续改进 | 安全是持续的过程,不是一次性的项目 |
1.2 安全加固流程
规划 → 评估 → 实施 → 测试 → 监控 → 优化
↓ ↓ ↓ ↓ ↓ ↓
需求分析 风险评估 配置加固 渗透测试 安全监控 持续改进
二、系统初始化安全
2.1 系统更新与补丁管理
# 更新软件源
apt update && apt upgrade -y
# 仅安装安全更新
apt install unattended-upgrades -y
dpkg-reconfigure -plow unattended-upgrades
# 配置自动安全更新
cat > /etc/apt/apt.conf.d/50unattended-upgrades << 'EOF'
Unattended-Upgrade::Allowed-Origins {
"${distro_id}:${distro_codename}";
"${distro_id}:${distro_codename}-security";
};
Unattended-Upgrade::AutoFixInterruptedDpkg "true";
Unattended-Upgrade::Remove-Unused-Kernel-Packages "true";
Unattended-Upgrade::Remove-Unused-Dependencies "true";
Unattended-Upgrade::Automatic-Reboot "false";
EOF
2.2 主机名与网络配置
# 设置主机名
hostnamectl set-hostname prod-web-01
# 配置 /etc/hosts
cat > /etc/hosts << 'EOF'
127.0.0.1 localhost
127.0.1.1 prod-web-01
::1 localhost ip6-localhost ip6-loopback
ff02::1 ip6-allnodes
ff02::2 ip6-allrouters
EOF
# 禁用不必要的网络协议
echo 'install dccp /bin/true' >> /etc/modprobe.d/CIS.conf
echo 'install sctp /bin/true' >> /etc/modprobe.d/CIS.conf
echo 'install rds /bin/true' >> /etc/modprobe.d/CIS.conf
echo 'install tipc /bin/true' >> /etc/modprobe.d/CIS.conf
2.3 内核参数调优
# 配置内核安全参数
cat > /etc/sysctl.d/99-security.conf << 'EOF'
# 防止 IP 欺骗
net.ipv4.conf.all.rp_filter =1
net.ipv4.conf.default.rp_filter =1
# 防止 ICMP 重定向
net.ipv4.conf.all.accept_redirects =0
net.ipv4.conf.default.accept_redirects =0
net.ipv4.conf.all.secure_redirects =0
net.ipv4.conf.default.secure_redirects =0
# 禁用 IP 源路由
net.ipv4.conf.all.accept_source_route =0
net.ipv4.conf.default.accept_source_route =0
# 启用 SYN 洪水保护
net.ipv4.tcp_syncookies =1
# 禁用 IPv6(如不需要)
net.ipv6.conf.all.disable_ipv6 =1
net.ipv6.conf.default.disable_ipv6 =1
# 减少缓冲区溢出风险
kernel.randomize_va_space =2
# 限制 core dump
fs.suid_dumpable =0
# 保护 procfs
kernel.kptr_restrict =2
kernel.yama.ptrace_scope =1
EOF
# 应用内核参数
sysctl -p /etc/sysctl.d/99-security.conf
三、用户认证与授权安全
3.1 用户管理
# 创建专用管理员账户
useradd -m-s /bin/bash security_admin
usermod -aGsudo security_admin
# 配置 sudoers
cat > /etc/sudoers.d/security_admin << 'EOF'
security_admin ALL=(ALL) ALL
EOF
chmod0440 /etc/sudoers.d/security_admin
# 禁用 root 账户
passwd -l root
# 检查并删除不必要的账户
awk-F: '($3 < 1000) {print $1}' /etc/passwd
# 手动审核系统账户,删除不需要的账户
3.2 密码策略
# 安装密码质量检查模块
apt install libpam-pwquality -y
# 配置密码策略
cat > /etc/pam.d/common-password << 'EOF'
password requisite pam_pwquality.so retry=3minlen=14difok=4ucredit=-1lcredit=-1dcredit=-1ocredit=-1maxrepeat=3 reject_username
password [success=1default=ignore] pam_unix.so obscure use_authtok try_first_pass sha512
password requisite pam_deny.so
password required pam_permit.so
EOF
# 配置密码过期策略
cat > /etc/login.defs << 'EOF'
PASS_MAX_DAYS 90
PASS_MIN_DAYS 7
PASS_WARN_AGE 14
LOGIN_RETRIES 5
LOGIN_TIMEOUT 60
EOF
# 为现有用户设置密码过期
chage -M90-m7-W14 security_admin
3.3 PAM 安全配置
# 配置账户锁定
cat > /etc/pam.d/common-auth << 'EOF'
auth required pam_tally2.so onerr=fail deny=5unlock_time=1800 even_deny_root
auth [success=1default=ignore] pam_unix.so nullok_secure
auth requisite pam_deny.so
auth required pam_permit.so
EOF
# 配置会话超时
cat > /etc/profile.d/autologout.sh << 'EOF'
TMOUT=300
readonly TMOUT
export TMOUT
EOF
chmod755 /etc/profile.d/autologout.sh
四、SSH 安全加固(企业级)
4.1 SSH 服务配置
# 备份原始配置
cp /etc/ssh/sshd_config /etc/ssh/sshd_config.bak.$(date +%Y%m%d)
# 企业级 SSH 配置
cat > /etc/ssh/sshd_config << 'EOF'
# 基础配置
Protocol 2
Port 2222
AddressFamily inet
ListenAddress 0.0.0.0
# 身份认证
PermitRootLogin no
PubkeyAuthentication yes
PasswordAuthentication no
HostbasedAuthentication no
PermitEmptyPasswords no
# 用户访问控制
AllowUsers security_admin
AllowGroups sudo
# 会话安全
ClientAliveInterval 300
ClientAliveCountMax 2
LoginGraceTime 60
MaxAuthTries 3
MaxSessions 5
# 转发配置
X11Forwarding no
AllowTcpForwarding no
AllowAgentForwarding no
PermitTunnel no
GatewayPorts no
# 其他安全设置
UseDNS no
PrintMotd no
PrintLastLog yes
TCPKeepAlive yes
StrictModes yes
MaxStartups 10:30:60
# 加密算法(现代安全算法)
KexAlgorithms curve25519-sha256@libssh.org,diffie-hellman-group-exchange-sha256
Ciphers chacha20-poly1305@openssh.com,aes256-gcm@openssh.com,aes128-gcm@openssh.com
MACs hmac-sha2-512-etm@openssh.com,hmac-sha2-256-etm@openssh.com
EOF
# 生成现代 SSH 密钥(Ed25519)
ssh-keygen -t ed25519 -f /etc/ssh/ssh_host_ed25519_key -N""
ssh-keygen -t rsa -b4096-f /etc/ssh/ssh_host_rsa_key -N""
# 设置正确的权限
chmod 600 /etc/ssh/sshd_config
chmod 600 /etc/ssh/ssh_host_*_key
chmod 644 /etc/ssh/ssh_host_*.pub
# 重启 SSH 服务
sshd -t# 测试配置
systemctl restart sshd
systemctl enable sshd
4.2 客户端 SSH 密钥配置
在客户端执行(不在服务器上):
# 生成 Ed25519 密钥对(推荐)
ssh-keygen -t ed25519 -C"security_admin@prod-web-01"-f ~/.ssh/id_ed25519_prod
# 复制公钥到服务器
ssh-copy-id -i ~/.ssh/id_ed25519_prod.pub -p2222 security_admin@server-ip
# 配置 SSH 客户端
cat >> ~/.ssh/config << 'EOF'
Host prod-web-01
HostName server-ip
Port 2222
User security_admin
IdentityFile ~/.ssh/id_ed25519_prod
IdentitiesOnly yes
ServerAliveInterval 60
ServerAliveCountMax 3
EOF
五、防火墙与网络安全
5.1 UFW 防火墙配置
# 安装 UFW
apt install ufw -y
# 设置默认策略
ufw default deny incoming
ufw default allow outgoing
# 允许必要的服务
ufw allow 2222/tcp comment "SSH"
ufw allow 80/tcp comment "HTTP"
ufw allow 443/tcp comment "HTTPS"
# 限制访问频率(防暴力破解)
ufw limit 2222/tcp comment "SSH with rate limit"
# 启用 UFW
ufw enable
ufw status verbose
# 查看规则
ufw show added
5.2 iptables 高级配置(可选)
对于需要更精细控制的环境:
# 安装 iptables-persistent
apt install iptables-persistent -y
# 企业级 iptables 规则
cat > /etc/iptables/rules.v4 << 'EOF'
*filter
:INPUT DROP [0:0]
:FORWARD DROP [0:0]
:OUTPUT ACCEPT [0:0]
:SSH - [0:0]
# 允许本地回环
-A INPUT -i lo -j ACCEPT
-A OUTPUT -o lo -j ACCEPT
# 允许已建立的连接
-A INPUT -m conntrack --ctstate ESTABLISHED,RELATED -j ACCEPT
# SSH 防护(使用自定义链)
-A INPUT -p tcp --dport2222-m conntrack --ctstate NEW -j SSH
-A SSH -m recent --set--name SSH
-A SSH -m recent --update--seconds60--hitcount4--name SSH -j DROP
-A SSH -j ACCEPT
# 允许 HTTP/HTTPS
-A INPUT -p tcp --dport80-j ACCEPT
-A INPUT -p tcp --dport443-j ACCEPT
# 记录并拒绝其他流量
-A INPUT -m limit --limit5/min -j LOG --log-prefix"iptables denied: "--log-level7
-A INPUT -j DROP
COMMIT
EOF
# 应用规则
netfilter-persistent reload
六、服务与应用安全
6.1 最小化服务
# 查看所有运行的服务
systemctl list-units --type=service--state=running
# 查看所有监听端口
ss -tuln
# 停止并禁用不必要的服务
systemctl stop rpcbind
systemctl disable rpcbind
systemctl stop avahi-daemon
systemctl disable avahi-daemon
systemctl stop cups
systemctl disable cups
6.2 Web 服务器安全(Nginx 示例)
# 安装 Nginx
apt install nginx -y
# 安全配置
cat > /etc/nginx/conf.d/security.conf << 'EOF'
# 隐藏 Nginx 版本
server_tokens off;
# 安全头
add_header X-Frame-Options "DENY" always;
add_header X-Content-Type-Options "nosniff" always;
add_header X-XSS-Protection "1; mode=block" always;
add_header Referrer-Policy "strict-origin-when-cross-origin" always;
add_header Content-Security-Policy "default-src 'self'; script-src 'self' 'unsafe-inline' 'unsafe-eval'; style-src 'self' 'unsafe-inline'; img-src 'self' data:; font-src 'self'; connect-src 'self'; frame-ancestors 'none'; base-uri 'self'; form-action 'self';" always;
add_header Permissions-Policy "geolocation=(), microphone=(), camera=()" always;
# 限制请求大小
client_max_body_size 10M;
# 超时设置
client_body_timeout 10s;
client_header_timeout 10s;
keepalive_timeout 55;
send_timeout 10s;
EOF
# 测试并重启 Nginx
nginx -t
systemctl restart nginx
systemctl enable nginx
6.3 数据库安全(MySQL/MariaDB 示例)
# 安装 MariaDB
apt install mariadb-server -y
# 运行安全加固脚本
mysql_secure_installation
# 创建专用数据库用户
mysql -u root -p << 'EOF'
CREATE USER 'app_user'@'localhost' IDENTIFIED BY 'StrongPassword123!';
CREATE DATABASE app_db;
GRANT SELECT, INSERT, UPDATE, DELETE ON app_db.* TO 'app_user'@'localhost';
FLUSH PRIVILEGES;
EOF
# 配置 MySQL 安全
cat > /etc/mysql/mariadb.conf.d/50-server.cnf << 'EOF'
[mysqld]
bind-address =127.0.0.1
skip-name-resolve
max_connections =100
max_connect_errors =5
default_authentication_plugin = mysql_native_password
local-infile =0
symbolic-links =0
secure-file-priv = /var/lib/mysql-files
EOF
# 重启 MySQL
systemctl restart mariadb
systemctl enable mariadb
七、入侵检测与防护
7.1 Fail2Ban 配置
# 安装 Fail2Ban
apt install fail2ban -y
# 复制配置文件
cp /etc/fail2ban/jail.conf /etc/fail2ban/jail.local
# 配置 Fail2Ban
cat > /etc/fail2ban/jail.local << 'EOF'
[DEFAULT]
bantime =3600
findtime =600
maxretry =3
destemail = security@company.com
sender = fail2ban@server-01
action = %(action_mwl)s
[sshd]
enabled =true
port =2222
logpath = %(sshd_log)s
maxretry =3
bantime =86400
[nginx-http-auth]
enabled =true
port = http,https
logpath = %(nginx_error_log)s
[nginx-botsearch]
enabled =true
port = http,https
logpath = %(nginx_access_log)s
maxretry =2
EOF
# 启用并启动 Fail2Ban
systemctl enable fail2ban
systemctl start fail2ban
# 查看状态
fail2ban-client status
fail2ban-client status sshd
7.2 OSSEC 入侵检测(可选)
# 安装依赖
apt install build-essential makegcc-y
# 下载并安装 OSSEC
wget https://github.com/ossec/ossec-hids/archive/3.7.0.tar.gz
tar -xzf3.7.0.tar.gz
cd ossec-hids-3.7.0
./install.sh
八、文件系统安全
8.1 文件权限加固
# 创建权限检查脚本
cat > /usr/local/bin/check_permissions.sh << 'EOF'
#!/bin/bash
echo"检查关键文件权限..."
# 检查 /etc/passwd
if [ "$(stat -c %a /etc/passwd)" !="644" ]; then
echo"警告: /etc/passwd 权限不正确,修复中..."
chmod644 /etc/passwd
fi
# 检查 /etc/shadow
if [ "$(stat -c %a /etc/shadow)" !="600" ]; then
echo"警告: /etc/shadow 权限不正确,修复中..."
chmod600 /etc/shadow
fi
# 检查 /etc/sudoers
if [ "$(stat -c %a /etc/sudoers)" !="440" ]; then
echo"警告: /etc/sudoers 权限不正确,修复中..."
chmod440 /etc/sudoers
fi
echo"权限检查完成"
EOF
chmod+x /usr/local/bin/check_permissions.sh
8.2 查找 SUID/SGID 文件
# 查找 SUID 文件
echo"SUID 文件:"
find / -type f -perm-40002>/dev/null | grep-v'^/proc'
# 查找 SGID 文件
echo"SGID 文件:"
find / -type f -perm-20002>/dev/null | grep-v'^/proc'
8.3 挂载点安全
# 编辑 /etc/fstab
cat > /etc/fstab << 'EOF'
UUID=xxx / ext4 errors=remount-ro 01
UUID=yyy /boot ext4 defaults 02
tmpfs /tmp tmpfs defaults,nodev,nosuid,noexec 00
tmpfs /var/tmp tmpfs defaults,nodev,nosuid,noexec 00
tmpfs /dev/shm tmpfs defaults,nodev,nosuid,noexec 00
EOF
# 重新挂载
mount -o remount /tmp
mount -o remount /var/tmp
mount -o remount /dev/shm
九、日志与审计
9.1 系统日志配置
# 配置 rsyslog
cat > /etc/rsyslog.d/50-security.conf << 'EOF'
# 认证日志
auth,authpriv.* /var/log/auth.log
# 内核日志
kern.* /var/log/kern.log
# 系统日志
*.=info;*.=notice;*.=warn;\
auth,authpriv.none;\
cron,daemon.none;\
mail,news.none -/var/log/messages
# 所有紧急消息
*.emerg :omusrmsg:*
EOF
# 重启 rsyslog
systemctl restart rsyslog
9.2 Auditd 审计
# 安装 auditd
apt install auditd -y
# 配置审计规则
cat > /etc/audit/rules.d/security.rules << 'EOF'
# 文件系统审计
-w /etc/passwd -p wa -k identity
-w /etc/group -p wa -k identity
-w /etc/shadow -p wa -k identity
-w /etc/gshadow -p wa -k identity
-w /etc/sudoers -p wa -k actions
-w /etc/sudoers.d/ -p wa -k actions
# 系统调用审计
-a always,exit -Farch=b64 -S execve -k executions
-a always,exit -Farch=b32 -S execve -k executions
-a always,exit -Farch=b64 -S connect -k network
-a always,exit -Farch=b32 -S connect -k network
# 权限变更审计
-a always,exit -Farch=b64 -Schmod-S fchmod -S fchmodat -k perm_mod
-a always,exit -Farch=b32 -Schmod-S fchmod -S fchmodat -k perm_mod
-a always,exit -Farch=b64 -Schown-S fchown -S fchownat -S lchown -k perm_mod
-a always,exit -Farch=b32 -Schown-S fchown -S fchownat -S lchown -k perm_mod
# 配置审计
-w /etc/audit/ -p wa -k config_changes
-w /etc/sysctl.conf -p wa -k sysctl
EOF
# 重启 auditd
systemctl restart auditd
systemctl enable auditd
十、备份与恢复
10.1 系统配置备份
# 创建配置备份脚本
cat > /usr/local/bin/backup-configs.sh << 'EOF'
#!/bin/bash
BACKUP_DIR="/backup/configs/$(date +%Y%m%d_%H%M%S)"
mkdir-p"$BACKUP_DIR"
# 备份重要目录
tar -czf"$BACKUP_DIR/etc.tar.gz" /etc
tar -czf"$BACKUP_DIR/home-security_admin.tar.gz" /home/security_admin
tar -czf"$BACKUP_DIR/var-spool-cron.tar.gz" /var/spool/cron
# 备份磁盘分区表
sfdisk -d /dev/sda > "$BACKUP_DIR/partition_table.txt"
# 备份已安装包列表
dpkg --get-selections > "$BACKUP_DIR/packages.list"
# 保留最近 30 天的备份
find /backup/configs -type d -mtime+30-execrm-rf {} \;
find /backup/configs -type f -name"*.tar.gz"-mtime+30-delete
echo"配置备份完成: $BACKUP_DIR"
EOF
chmod+x /usr/local/bin/backup-configs.sh
# 添加到 crontab,每天凌晨 1 点执行
(crontab -l2>/dev/null; echo"0 1 * * * /usr/local/bin/backup-configs.sh") | crontab -
10.2 数据备份
# 创建数据备份脚本(以 MySQL 为例)
cat > /usr/local/bin/backup-mysql.sh << 'EOF'
#!/bin/bash
BACKUP_DIR="/backup/mysql/$(date +%Y%m%d_%H%M%S)"
mkdir-p"$BACKUP_DIR"
# 备份所有数据库
mysqldump --all-databases--single-transaction--quick--lock-tables=false \
--master-data=2--flush-logs \
| gzip > "$BACKUP_DIR/all-databases.sql.gz"
# 保留最近 7 天的备份
find /backup/mysql -type d -mtime+7-execrm-rf {} \;
find /backup/mysql -type f -name"*.sql.gz"-mtime+7-delete
echo"MySQL 备份完成: $BACKUP_DIR"
EOF
chmod+x /usr/local/bin/backup-mysql.sh
(crontab -l2>/dev/null; echo"30 1 * * * /usr/local/bin/backup-mysql.sh") | crontab -
十一、持续安全实践
11.1 安全检查清单
创建每日安全检查脚本:
cat > /usr/local/bin/daily-security-check.sh << 'EOF'
#!/bin/bash
REPORT="/tmp/security-report-$(date +%Y%m%d).txt"
echo"=== 每日安全检查报告 - $(date) ===" > "$REPORT"
echo"" >> "$REPORT"
echo"1. 系统更新检查:" >> "$REPORT"
apt list --upgradable2>/dev/null | head -20 >> "$REPORT"
echo"" >> "$REPORT"
echo"2. SSH 登录检查:" >> "$REPORT"
grep"Accepted" /var/log/auth.log | tail -20 >> "$REPORT"
echo"" >> "$REPORT"
echo"3. 失败的登录尝试:" >> "$REPORT"
grep"Failed password" /var/log/auth.log | tail -20 >> "$REPORT"
echo"" >> "$REPORT"
echo"4. Fail2Ban 状态:" >> "$REPORT"
fail2ban-client status >> "$REPORT"
echo"" >> "$REPORT"
echo"5. 磁盘使用情况:" >> "$REPORT"
df -h >> "$REPORT"
echo"" >> "$REPORT"
echo"6. 监听端口:" >> "$REPORT"
ss -tuln >> "$REPORT"
echo"" >> "$REPORT"
echo"7. 系统负载:" >> "$REPORT"
uptime >> "$REPORT"
echo"" >> "$REPORT"
echo"8. 最近修改的关键文件:" >> "$REPORT"
find /etc -type f -mtime-12>/dev/null | head -20 >> "$REPORT"
echo"" >> "$REPORT"
echo"安全检查完成,报告已保存到: $REPORT"
EOF
chmod+x /usr/local/bin/daily-security-check.sh
(crontab -l2>/dev/null; echo"0 8 * * * /usr/local/bin/daily-security-check.sh | mail -s '每日安全检查报告' security@company.com") | crontab -
11.2 定期安全审计
# 安装安全审计工具
apt install lynis -y
apt install rkhunter -y
# 运行 Lynis 审计
lynis audit system
# 运行 Rootkit Hunter
rkhunter --update
rkhunter --check