系统安全加固

最后更新: 2026-01-16 作者: Linux Team
页面目录
目录

安全加固概述

Linux系统安全需要从多个层面进行防护,包括账户安全、服务安全、网络安全、文件系统安全等。

┌─────────────────────────────────────────────────────────────┐
│                    安全加固层次                              │
├─────────────────────────────────────────────────────────────┤
│                                                             │
│   应用层 ── 服务配置、Web安全                                │
│   用户层 ── 账户策略、权限控制                               │
│   网络层 ── 防火墙、SSH安全                                  │
│   内核层 ── 内核参数、SELinux                               │
│   文件层 ── 权限、ACL、SUID管理                             │
│                                                             │
└─────────────────────────────────────────────────────────────┘

账户安全

密码策略

# 安装libpam-pwquality
sudo apt install libpam-pwquality

# /etc/security/pwquality.conf
minlen = 12                    # 最小长度
dcredit = -1                   # 至少1位数字
ucredit = -1                   # 至少1位大写
lcredit = -1                   # 至少1位小写
ocredit = -1                   # 至少1位特殊字符
maxrepeat = 2                  # 最多连续相同字符
difok = 3                      # 与旧密码至少3个字符不同

# /etc/login.defs
PASS_MAX_DAYS 90               # 密码最长使用天数
PASS_MIN_DAYS 7                # 密码最小使用天数
PASS_WARN_AGE 7                # 密码过期警告天数

账户锁定

# 锁定账户
sudo passwd -l username

# 解锁账户
sudo passwd -u username

# 强制首次登录改密码
sudo chage -d 0 username

# 查看账户状态
sudo chage -l username

# 自动锁定(连续失败5次后锁定30分钟)
sudo apt install libpam-cracklib

# /etc/pam.d/common-auth 添加
auth required pam_tally2.so onerr=fail deny=5 unlock_time=1800

清理无用账户

# 查看所有账户
cut -d: -f1 /etc/passwd

# 检查可登录账户
grep -E "^(root|ubuntu|admin):" /etc/passwd

# 删除不需要的系统账户
sudo userdel games
sudo userdel lp
sudo userdel news
sudo userdel uucp
sudo userdel ftp

# 禁用guest账户(Ubuntu)
sudo passwd -l guest
sudo rm -rf /home/guest

sudo权限审计

# 查看sudoers配置
sudo visudo -c

# 查看用户sudo权限
sudo -l -U username

# 查看sudo使用日志
sudo grep sudo /var/log/auth.log | tail -50
sudo cat /var/log/auth.log | grep "sudoers"

# 允许特定命令
username ALL=(ALL) /usr/bin/systemctl status nginx
username ALL=(ALL) /usr/bin/systemctl restart nginx, /usr/bin/systemctl stop nginx
username ALL=(ALL) NOPASSWD: /bin/systemctl restart network

文件系统安全

重要文件权限

# 设置关键文件权限
sudo chmod 600 /etc/shadow
sudo chmod 644 /etc/passwd
sudo chmod 644 /etc/group
sudo chmod 600 /etc/gshadow
sudo chmod 000 /etc/shadow-

# SSH密钥权限
chmod 700 ~/.ssh
chmod 600 ~/.ssh/authorized_keys
chmod 600 ~/.ssh/id_rsa
chmod 644 ~/.ssh/id_rsa.pub

# 审计SUID文件
find / -perm -4000 -type f 2>/dev/null

# 移除不必要的SUID
sudo chmod -s /usr/bin/passwd        # 注意:passwd需要保留SUID
sudo chmod -s /usr/bin/sudo
sudo chmod -s /usr/bin/chfn
sudo chmod -s /usr/bin/newgrp
sudo chmod -s /usr/bin/gpasswd

文件系统挂载选项

# /etc/fstab 配置
# noexec - 禁止执行程序
# nosuid - 忽略SUID位
# nodev - 禁止设备文件

# /tmp 分区
tmpfs /tmp tmpfs defaults,noexec,nosuid,nodev 0 0

# /var/tmp
/tmp /var/tmp none bind,noexec,nosuid,nodev 0 0

# 检查当前挂载
mount | grep noexec
mount | grep nosuid

目录访问控制

# 设置目录权限
chmod 750 /home
chmod 700 /root
chmod 755 /var/log

# ACL配置
setfacl -m u:apache:rx /var/log/httpd
setfacl -m g:developers:rw /project

# 默认ACL
setfacl -m d:o::--- /secure_dir
setfacl -m d:g:group:rx /shared_dir

服务安全

禁用不必要的服务

# 列出所有服务
systemctl list-unit-files --type=service --state=enabled

# 禁用不需要的服务
sudo systemctl disable telnet
sudo systemctl disable rsh
sudo systemctl disable rlogin
sudo systemctl disable vsftpd
sudo systemctl disable cups
sudo systemctl disable bluetooth

# 停止服务
sudo systemctl stop cups
sudo systemctl stop bluetooth

服务配置检查

# Apache安全配置
sudo vim /etc/apache2/conf-available/security.conf

# 设置
ServerTokens Prod
ServerSignature Off
TraceEnable Off
Header set X-Content-Type-Options: "nosniff"
Header set X-Frame-Options: "DENY"
Header set X-XSS-Protection: "1; mode=block"

# Nginx安全配置
sudo vim /etc/nginx/nginx.conf

# 添加
add_header X-Frame-Options "DENY";
add_header X-Content-Type-Options "nosniff";
add_header X-XSS-Protection "1; mode=block";
add_header Referrer-Policy "no-referrer-when-downgrade";

数据库安全

# MySQL安全初始化
sudo mysql_secure_installation

# PostgreSQL安全配置
sudo vim /etc/postgresql/*/main/pg_hba.conf

# 本地使用md5,其他拒绝
local   all             all                                     md5
host    all             all             127.0.0.1/32            md5
host    all             all             ::1/128                 md5
host    all             all             0.0.0.0/0                reject

# 重载配置
sudo systemctl reload postgresql

网络安全

内核参数加固

# /etc/sysctl.conf

# IP转发(按需开启)
net.ipv4.ip_forward = 0                    # 关闭转发
net.ipv6.conf.all.forwarding = 0

# ICMP设置
net.ipv4.icmp_echo_ignore_broadcasts = 1    # 忽略广播ping
net.ipv4.icmp_ignore_bogus_error_responses = 1
net.ipv4.icmp_ratelimit = 100

# TCP加固
net.ipv4.tcp_syncookies = 1                 # SYN flood防护
net.ipv4.tcp_syn_retries = 2
net.ipv4.tcp_synack_retries = 2
net.ipv4.tcp_max_syn_backlog = 8192

# 禁用源路由
net.ipv4.conf.all.accept_source_route = 0
net.ipv6.conf.all.accept_source_route = 0

# 禁用ICMP重定向
net.ipv4.conf.all.accept_redirects = 0
net.ipv6.conf.all.accept_redirects = 0

# 禁用发送重定向
net.ipv4.conf.all.send_redirects = 0

# 禁用路由记录
net.ipv4.conf.all.accept_source_route = 0

# 日志可疑包
net.ipv4.conf.all.log_martians = 1
net.ipv4.conf.default.log_martians = 1

# 应用配置
sudo sysctl -p

网络访问控制

# /etc/hosts.allow
sshd: 192.168.1.0/24, 10.0.0.0/8
mysqld: 127.0.0.1

# /etc/hosts.deny
ALL: ALL

# 应用配置
sudo systemctl restart sshd
sudo systemctl restart mysql

SSH安全加固

# /etc/ssh/sshd_config 安全配置

# 基础设置
Port 2222
Protocol 2
ListenAddress 0.0.0.0

# 认证设置
PermitRootLogin no
PubkeyAuthentication yes
PasswordAuthentication no
PermitEmptyPasswords no
MaxAuthTries 3
MaxSessions 10

# 安全设置
ClientAliveInterval 300
ClientAliveCountMax 2
LoginGraceTime 60
StrictModes yes
UsePrivilegeSeparation sandbox

# 允许用户
AllowUsers user1 user2

# 超时设置
ClientAliveInterval 600
ClientAliveCountMax 3

# X11转发
X11Forwarding no

# 重启SSH
sudo systemctl restart sshd

日志审计

配置审计日志

# /etc/rsyslog.conf

# 记录所有auth日志
auth.* /var/log/auth.log
authpriv.* /var/log/auth.log

# 记录cron
cron.* /var/log/cron.log

# 记录内核
kern.* /var/log/kern.log

# 远程日志收集
*.* @@logserver.example.com:514

# 重启服务
sudo systemctl restart rsyslog

auditd配置

# 安装
sudo apt install auditd

# /etc/audit/auditd.conf
log_file = /var/log/audit/audit.log
max_log_file = 100
max_log_file_action = ROTATE
space_left = 75
space_left_action = SYSLOG
admin_space_left = 50
admin_space_left_action = SUSPEND
disk_full_action = SUSPEND
disk_error_action = SUSPEND

# 添加审计规则
sudo vim /etc/audit/rules.d/audit.rules

# 监控配置文件变更
-w /etc/passwd -p wa -k identity
-w /etc/shadow -p wa -k identity
-w /etc/group -p wa -k identity
-w /etc/gshadow -p wa -k identity

# 监控网络配置
-w /etc/sysctl.conf -p wa -k system_mod
-w /etc/network/ -p wa -k network

# 监控SSH配置
-w /etc/ssh/sshd_config -p wa -k sshd_config

# 监控敏感命令
-a always,exit -F arch=b64 -S execve -F path=/usr/bin/wget -k command_wget
-a always,exit -F arch=b64 -S execve -F path=/usr/bin/curl -k command_curl

# 重新加载规则
sudo auditctl -R /etc/audit/rules.d/audit.rules

# 查看审计日志
sudo aureport -au | head -20    # 认证事件
sudo aureport -f | head -20     # 文件访问
sudo aureport -t today          # 今日报告
sudo ausearch -k sshd_config    # 搜索特定key

SELinux配置

# CentOS/RHEL SELinux配置
# 检查状态
sestatus
getenforce

# 模式
# Enforcing - 强制执行
# Permissive - 仅记录
# Disabled - 禁用

# 临时设置
sudo setenforce Enforcing
sudo setenforce Permissive

# 永久设置
sudo vim /etc/selinux/config
SELINUX=enforcing
SELINUXTYPE=targeted

# 管理布尔值
semanage boolean -l | grep httpd
setsebool -P httpd_can_network_connect 1

# 管理端口
semanage port -l | grep http
semanage port -a -t http_port_t -p tcp 8080

# 查看日志
sudo tail -f /var/log/audit/audit.log | grep denied
sudo sealert -a /var/log/audit/audit.log

安全扫描

Lynis安全审计

# 安装
sudo apt install lynis

# 运行审计
sudo lynis audit system

# 只显示警告
sudo lynis audit system --quick

# 输出到文件
sudo lynis audit system > lynis_report.txt

RKHunter检测

# 安装
sudo apt install rkhunter

# 配置
sudo vim /etc/rkhunter.conf

# 更新数据库
sudo rkhunter --update
sudo rkhunter --propupd

# 运行检查
sudo rkhunter --checkall

# 只显示警告
sudo rkhunter --checkall --rwo

ClamAV病毒扫描

# 安装
sudo apt install clamav clamav-daemon

# 更新病毒库
sudo systemctl stop clamav-freshclam
sudo freshclam
sudo systemctl start clamav-freshclam

# 扫描
sudo clamscan -r /home
sudo clamscan -r /home --remove=yes
sudo clamscan -r / --exclude-dir=/sys --exclude-dir=/proc

安全检查清单

┌─────────────────────────────────────────────────────────────┐
│                    安全检查清单                              │
├─────────────────────────────────────────────────────────────┤
│                                                             │
│   □ 更改默认SSH端口                                          │
│   □ 禁用root直接登录                                        │
│   □ 配置SSH密钥认证                                         │
│   □ 设置强密码策略                                          │
│   □ 禁用不必要的账户                                        │
│   □ 配置sudo权限审计                                        │
│   □ 设置SUID文件监控                                        │
│   □ 配置防火墙规则                                          │
│   □ 关闭不必要的服务                                         │
│   □ 配置内核安全参数                                         │
│   □ 启用审计日志                                            │
│   □ 定期安全更新                                            │
│   □ 备份重要数据                                            │
│   □ 配置入侵检测                                            │
│   □ 网络安全扫描                                            │
│                                                             │
└─────────────────────────────────────────────────────────────┘

课后练习

实践任务
  1. 配置密码复杂度策略
  2. 加固SSH配置,禁用密码登录
  3. 配置系统审计规则
  4. 使用lynis进行安全审计
  5. 配置内核安全参数
  6. 建立完整的安全加固脚本

下一篇预告:我们将学习性能监控与优化,掌握系统调优技能。