Linux 安全策略完全指南
一、什么是 Linux 安全策略
1.1 Linux 安全策略的定义
Linux 安全策略是指在 Linux 操作系统(涵盖 RHEL、CentOS、Ubuntu、Debian、SUSE、OpenEuler、Anolis 等主流发行版)上,针对系统的账户、文件、网络、服务、内核、应用等各个层面实施的一系列主动、可度量、可审计的安全控制机制的总和。其目标是通过”最小权限、纵深防御、持续监控”三大原则,将系统的攻击面降到最低,并确保在遭受攻击时能够及时发现、隔离与恢复。
与 Windows 安全策略体系(基于 GPO / LGPO / secedit)不同,Linux 安全策略体系是基于**”配置文件 + 命令工具 + 框架(Framework)”**构建的。每个发行版都有其默认的安全机制(如 RHEL 的 SELinux、Ubuntu 的 AppArmor、Debian 的 Firejail),同时通过 PAM、SSH、SUDO、iptables、nftables、auditd、sysctl 等子系统可以深度定制安全行为。
1.2 Linux 安全策略的层次结构
1.3 Linux 安全模型的核心思想
Linux 安全模型建立在三个核心思想之上:
| 思想 | 描述 | 体现 |
|---|---|---|
| 最小权限原则 | 每个用户/进程只应拥有完成其任务所需的最小权限 | UID/GID、SUDO 白名单、Capabilities |
| 纵深防御原则 | 单层防御被攻破时,其他层仍能提供保护 | 多层防护(防火墙 + SELinux + SSH + auditd) |
| 职责分离原则 | 关键操作由多个独立角色共同完成 | 数据库 DBA、系统管理员、审计员三权分立 |
1.4 Linux 与 Windows 安全策略的核心差异
| 维度 | Windows | Linux |
|---|---|---|
| 策略管理 | GPO / LGPO / secedit | 配置文件 + 命令工具 |
| 访问控制模型 | ACL (DACL/SACL) | DAC (rwx) + MAC (SELinux/AppArmor) |
| 强制访问控制 | Integrity Levels | SELinux / AppArmor / Smack / TOMOYO |
| 账户数据库 | SAM / AD | /etc/passwd, /etc/shadow, LDAP, IPA |
| 认证模块 | LSASS + Kerberos | PAM (可插拔认证模块) |
| 防火墙 | Windows Defender Firewall | iptables / nftables / firewalld / ufw |
| 审计 | Event Log + ETW | auditd + syslog + journald |
| 服务管理 | Windows Service | systemd unit / SysV init |
二、账户与认证安全策略
2.1 用户与组管理
2.1.1 关键文件
/etc/passwd # 用户信息(UID、GID、Home、Shell)
/etc/shadow # 密码哈希、过期策略
/etc/group # 组信息
/etc/gshadow # 组密码(极少使用)
/etc/login.defs # 账户创建默认值
/etc/skel/ # 新用户 Home 目录模板
2.1.2 强密码策略
通过 /etc/login.defs 和 PAM 模块 pam_pwquality 实施强密码策略:
# /etc/login.defs
PASS_MAX_DAYS 90 # 密码最长使用期
PASS_MIN_DAYS 7 # 密码最短使用期
PASS_MIN_LEN 12 # 密码最小长度
PASS_WARN_AGE 14 # 密码过期前警告天数
UID_MIN 1000 # 普通用户最小 UID
UID_MAX 60000 # 普通用户最大 UID
ENCRYPT_METHOD SHA512 # 密码加密算法
# /etc/security/pwquality.conf
minlen = 12
dcredit = -1 # 至少 1 个数字
ucredit = -1 # 至少 1 个大写
lcredit = -1 # 至少 1 个小写
ocredit = -1 # 至少 1 个特殊字符
dictcheck = 1 # 启用字典检查
enforce_for_root # 强制 root 也遵守策略
2.1.3 账户锁定策略
通过 PAM 模块 pam_faillock 实施登录失败锁定:
# /etc/pam.d/system-auth 或 /etc/pam.d/login
auth required pam_faillock.so preauth deny=5 unlock_time=900 even_deny_root
auth [success=1 default=bad] pam_unix.so
auth [default=die] pam_faillock.so authfail deny=5 unlock_time=900 even_deny_root
account required pam_faillock.so
# 查看账户锁定状态
faillock --user alice
# 解锁
faillock --user alice --reset
2.1.4 禁用不必要的账户
# 锁定不需要登录的账户
usermod -L games
usermod -L news
usermod -L lp
usermod -L uucp
usermod -L proxy
# 设置 Shell 为 nologin
usermod -s /sbin/nologin games
# 删除默认无用账户(仅在评估后)
userdel games
userdel news
2.2 PAM 认证模块
PAM(Pluggable Authentication Modules)是 Linux 认证的核心框架。
PAM 配置示例:
# /etc/pam.d/sshd
auth required pam_sepermit.so
auth substack password-auth
auth include postlogin
-auth optional pam_reauthorize.so prepare
account required pam_nologin.so
account include password-auth
password include password-auth
session required pam_selinux.so close
session required pam_loginuid.so
session required pam_selinux.so open env_params
session required pam_namespace.so
session include password-auth
session include postlogin
2.3 SSH 安全加固
SSH 是 Linux 服务器最常用的远程管理入口,也是攻击者的主要目标。
2.3.1 sshd_config 关键配置
# /etc/ssh/sshd_config
# 禁用 root 登录
PermitRootLogin no
# 仅允许密钥认证
PubkeyAuthentication yes
PasswordAuthentication no
PermitEmptyPasswords no
ChallengeResponseAuthentication no
UsePAM yes
# 限制用户/组
AllowGroups sshusers
AllowUsers alice bob
# 修改默认端口(安全通过 obscurity)
Port 2222
# 协议与加密算法
Protocol 2
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
# 登录超时与尝试次数
LoginGraceTime 30
MaxAuthTries 3
MaxSessions 3
# 禁用 X11 转发(除非必须)
X11Forwarding no
# 禁用 TCP 转发
AllowTcpForwarding no
AllowAgentForwarding no
# 客户端存活探测
ClientAliveInterval 300
ClientAliveCountMax 2
# 显示登录 banner
Banner /etc/issue.net
2.3.2 SSH 密钥管理
# 生成强 ED25519 密钥对
ssh-keygen -t ed25519 -C "alice@workstation" -f ~/.ssh/id_ed25519
# 公钥复制到服务器
ssh-copy-id -i ~/.ssh/id_ed25519.pub alice@server
# 服务器端 authorized_keys 权限必须严格
chmod 700 ~/.ssh
chmod 600 ~/.ssh/authorized_keys
# 进一步限制密钥用途(推荐)
from="192.168.1.0/24",no-port-forwarding,no-X11-forwarding,no-agent-forwarding,no-pty ssh-ed25519 AAAA...
2.3.3 防御 SSH 暴力破解
方法一:fail2ban
# 安装
yum install -y fail2ban
# 或
apt install -y fail2ban
# 配置
cat > /etc/fail2ban/jail.local << 'EOF'
[sshd]
enabled = true
port = 2222
filter = sshd
logpath = /var/log/secure
maxretry = 3
bantime = 3600
findtime = 600
EOF
# 启动
systemctl enable --now fail2ban
# 查看状态
fail2ban-client status sshd
方法二:denyhosts
yum install -y denyhosts
# 配置 /etc/denyhosts.conf
SECURE_LOG = /var/log/secure
HOSTS_DENY = /etc/hosts.deny
PURGE_DENY = 1h
BLOCK_SERVICE = sshd
DENY_THRESHOLD_INVALID = 3
DENY_THRESHOLD_VALID = 5
方法三:SSH 黑名单(hosts.deny)
# /etc/hosts.deny
sshd: ALL EXCEPT 192.168.1.0/24: 10.0.0.0/8
2.3.4 SSH 多因素认证
使用 Google Authenticator 实现 MFA:
# 安装
yum install -y google-authenticator
# 或
apt install -y libpam-google-authenticator
# 用户配置
google-authenticator
# 回答问题:
# - Do you want authentication tokens to be time-based? y
# - 是否更新 ~/.google_authenticator? y
# - 是否禁止重复使用? y
# - 是否启用 rate-limiting? y
# 配置 PAM
# /etc/pam.d/sshd
auth required pam_google_authenticator.so
# 配置 sshd
# /etc/ssh/sshd_config
ChallengeResponseAuthentication yes
AuthenticationMethods publickey,keyboard-interactive
2.4 Sudo 精细化授权
Sudo 是 Linux 权限提升的核心,必须严格配置:
# /etc/sudoers(必须用 visudo 编辑)
# 禁止 root 登录 sudo
root ALL=(ALL) ALL
# 精细化授权:仅允许 alice 重启服务
alice ALL=(root) /usr/bin/systemctl restart nginx, /usr/bin/systemctl reload nginx
# 允许 wheel 组无密码 sudo
%wheel ALL=(ALL) NOPASSWD: ALL
# 记录所有 sudo 操作
Defaults logfile=/var/log/sudo.log
Defaults log_input, log_output
Defaults iolog_dir=/var/log/sudo-io/%{user}
Defaults passwd_timeout=1
Defaults env_reset
Defaults secure_path="/usr/local/sbin:/usr/local/bin:/usr/sbin:/usr/bin:/sbin:/bin"
# 验证 sudo 配置
visudo -c
# 查看用户 sudo 权限
sudo -l -U alice
三、权限与访问控制策略
3.1 文件权限(基础 DAC)
3.1.1 基础权限位
Linux 文件权限基于三个角色:
- Owner(u):文件所有者
- Group(g):文件所属组
- Other(o):其他用户
每种角色有三种权限:
- r(read)= 4
- w(write)= 2
- x(execute)= 1
# 设置标准权限
chmod 644 /etc/passwd # rw-r--r--
chmod 600 /etc/shadow # rw-------
chmod 755 /usr/bin/ls # rwxr-xr-x
chmod 750 /opt/app # rwxr-x---
# 修改所有者
chown root:root /etc/passwd
chown alice:sales /home/alice
# 设置 SUID/SGID/Sticky
chmod u+s /usr/bin/passwd # SUID - 以文件所有者身份执行
chmod g+s /opt/shared # SGID - 新建文件继承组
chmod +t /tmp # Sticky - 只能删除自己的文件
# 查找 SUID 文件(攻击者经常利用)
find / -perm -4000 -type f 2>/dev/null
3.1.2 umask 默认权限
# /etc/profile 或 /etc/bashrc
umask 027 # 新建文件默认 640,目录默认 750
# 用户级
echo "umask 027" >> ~/.bashrc
3.1.3 ACL 访问控制列表
# 安装 ACL 工具
yum install -y acl
# 设置 ACL
setfacl -m u:alice:rw file.txt
setfacl -m g:developers:rwx /opt/project
setfacl -m d:g:developers:rwx /opt/project # 默认 ACL
# 查看 ACL
getfacl file.txt
# 删除 ACL
setfacl -x u:alice file.txt
setfacl -b file.txt
3.2 SELinux 强制访问控制(MAC)
3.2.1 SELinux 架构
3.2.2 SELinux 模式与状态
# 查看 SELinux 状态
sestatus
getenforce
# 临时切换模式
setenforce 0 # permissive(仅记录,不阻止)
setenforce 1 # enforcing(强制执行)
# 永久修改
# /etc/selinux/config
SELINUX=enforcing
SELINUXTYPE=targeted
3.2.3 SELinux 上下文管理
# 查看文件上下文
ls -Z /var/www/html/
ps -eZ | grep httpd
# 修改文件上下文
chcon -t httpd_sys_content_t /var/www/html/index.html
chcon --reference=/var/www/html/ /var/www/html/new.html
# 恢复默认上下文
restorecon -Rv /var/www/html/
# 设置自定义上下文
semanage fcontext -a -t httpd_sys_content_t '/webroot(/.*)?'
restorecon -Rv /webroot
3.2.4 SELinux 布尔值
# 列出所有布尔值
getsebool -a
# 常用布尔值
setsebool -P httpd_can_network_connect on # 允许 Web 服务器联网
setsebool -P httpd_can_sendmail on # 允许 Web 服务器发邮件
setsebool -P allow_ypbind off # 禁用 NIS
setsebool -P ssh_sysadm_login off # 禁止 SSH 切换到 sysadm_r
# 查看布尔值含义
semanage boolean -l
3.2.5 SELinux 故障排查
# 查看 AVC 拒绝日志
ausearch -m avc -ts recent
grep AVC /var/log/audit/audit.log | tail -20
# 生成允许规则(不推荐直接部署,仅调试用)
audit2allow -M mymod < /var/log/audit/audit.log
semodule -i mymod.pp
# 排错工具
sealert -a /var/log/audit/audit.log
3.3 AppArmor(Ubuntu/Debian 风格)
# 查看状态
aa-status
# 启用/禁用
apparmor_parser -r /etc/apparmor.d/usr.bin.firefox
ln -s /etc/apparmor.d/usr.bin.firefox /etc/apparmor.d/disable/ # 禁用
# 创建自定义 profile
aa-genprof /usr/bin/myapp
# 跟随提示学习模式
aa-complain /usr/bin/myapp # 仅记录
aa-enforce /usr/bin/myapp # 强制
# 加载 profile
apparmor_parser -r /etc/apparmor.d/usr.bin.myapp
3.4 文件系统能力(Capabilities)
Capabilities 是对 SUID 的精细化替代:
# 查看文件能力
getcap -r / 2>/dev/null
# 设置能力
setcap cap_net_bind_service=+ep /usr/bin/nginx # 允许 nginx 绑定 80 端口
setcap cap_dac_override=+ep /usr/sbin/cron # 允许 cron 绕过 DAC
# 常用能力
cap_chown # 改变文件所有者
cap_dac_override # 绕过 DAC 权限检查
cap_dac_read_search # 绕过读权限检查
cap_fowner # 绕过所有者权限检查
cap_fsetid # 设置 SUID/SGID
cap_kill # 发送信号给其他进程
cap_setgid # 设置 GID
cap_setuid # 设置 UID
cap_setpcap # 允许进程能力修改
cap_net_bind_service # 绑定特权端口
cap_net_raw # 使用 RAW 套接字
cap_sys_admin # 各种管理操作(慎用)
cap_sys_ptrace # ptrace 任意进程
cap_sys_resource # 资源限制覆盖
四、网络与防火墙安全策略
4.1 iptables 防火墙
4.1.1 基础规则
# 默认策略
iptables -P INPUT DROP
iptables -P FORWARD DROP
iptables -P OUTPUT ACCEPT
# 允许已建立的连接
iptables -A INPUT -m state --state ESTABLISHED,RELATED -j ACCEPT
# 允许回环
iptables -A INPUT -i lo -j ACCEPT
# 允许 SSH(仅限内网)
iptables -A INPUT -p tcp -s 192.168.1.0/24 --dport 22 -j ACCEPT
# 允许 HTTP/HTTPS
iptables -A INPUT -p tcp --dport 80 -j ACCEPT
iptables -A INPUT -p tcp --dport 443 -j ACCEPT
# 防止 ICMP 泛洪
iptables -A INPUT -p icmp -m limit --limit 1/s --limit-burst 4 -j ACCEPT
# 防止端口扫描
iptables -A INPUT -m recent --name portscan --rcheck --seconds 60 -j DROP
iptables -A INPUT -m recent --name portscan --update --seconds 60 -j DROP
iptables -A INPUT -p tcp --tcp-flags SYN,ACK SYN,ACK -m recent --name portscan --set -j DROP
# SYN Flood 防护
iptables -A INPUT -p tcp --syn -m limit --limit 1/s --limit-burst 3 -j ACCEPT
# 保存规则
service iptables save
# 或
iptables-save > /etc/iptables.rules
4.1.2 高级规则示例
# 限制每 IP 的并发连接数
iptables -A INPUT -p tcp --syn --dport 80 -m connlimit --connlimit-above 20 -j DROP
# IP 黑名单
iptables -A INPUT -s 203.0.113.0/24 -j DROP
# 字符串匹配(阻止特定 User-Agent)
iptables -A INPUT -p tcp --dport 80 -m string --algo kmp --string "sqlmap" -j DROP
# 时间限制(仅工作时间允许 SSH)
iptables -A INPUT -p tcp --dport 22 -m time --timestart 09:00 --timestop 18:00 -j ACCEPT
4.2 nftables(新版本)
nftables 是 iptables/nftables 的继任者,统一了 IPv4/IPv6/ARP/bridge。
# /etc/nftables.conf
table inet filter {
chain input {
type filter hook input priority 0; policy drop;
# 允许已建立连接
ct state established,related accept
ct state invalid drop
# 允许回环
iif "lo" accept
# 允许 ICMP
ip protocol icmp accept
ip6 nexthdr icmpv6 accept
# SSH
tcp dport 22 accept
# HTTP/HTTPS
tcp dport { 80, 443 } accept
}
chain forward {
type filter hook forward priority 0; policy drop;
}
chain output {
type filter hook output priority 0; policy accept;
}
}
4.3 firewalld(RHEL 风格)
# 查看区域
firewall-cmd --get-default-zone
firewall-cmd --list-all
# 添加服务
firewall-cmd --permanent --add-service=ssh
firewall-cmd --permanent --add-service=http
firewall-cmd --permanent --add-service=https
# 添加自定义端口
firewall-cmd --permanent --add-port=8080/tcp
# 限制源 IP
firewall-cmd --permanent --add-rich-rule='rule family="ipv4" source address="192.168.1.0/24" service name="ssh" accept'
# 启用 panic 模式(紧急断网)
firewall-cmd --panic-on
# 重新加载
firewall-cmd --reload
4.4 TCP Wrappers
# /etc/hosts.allow
sshd: 192.168.1.0/24, 10.0.0.5
# /etc/hosts.deny
ALL: ALL
4.5 内核网络参数
# /etc/sysctl.conf 或 /etc/sysctl.d/99-hardening.conf
# IP 转发(路由器需要)
net.ipv4.ip_forward = 0
# 禁用 IP 源路由
net.ipv4.conf.all.accept_source_route = 0
net.ipv6.conf.all.accept_source_route = 0
# 禁用 ICMP 重定向
net.ipv4.conf.all.send_redirects = 0
net.ipv4.conf.default.send_redirects = 0
net.ipv4.conf.all.accept_redirects = 0
net.ipv6.conf.all.accept_redirects = 0
# 启用反向路径过滤
net.ipv4.conf.all.rp_filter = 1
net.ipv4.conf.default.rp_filter = 1
# 启用 SYN Cookies(防 SYN Flood)
net.ipv4.tcp_syncookies = 1
# 忽略 ICMP ping
net.ipv4.icmp_echo_ignore_broadcasts = 1
# 记录可疑包
net.ipv4.conf.all.log_martians = 1
# IPv6 增强
net.ipv6.conf.all.accept_ra = 0
# 应用
sysctl -p
五、服务与应用安全策略
5.1 服务最小化
# 列出已启用服务
systemctl list-unit-files --state=enabled
# 禁用不需要的服务
systemctl disable --now avahi-daemon
systemctl disable --now cups
systemctl disable --now bluetooth
systemctl disable --now rpcbind
# 通过 chkconfig(旧版)
chkconfig --list
chkconfig --del service_name
5.2 systemd 服务硬化
# /etc/systemd/system/myapp.service
[Unit]
Description=My Secure Application
After=network.target
[Service]
Type=simple
User=myapp
Group=myapp
WorkingDirectory=/opt/myapp
ExecStart=/opt/myapp/bin/myapp
Restart=on-failure
RestartSec=5
# 安全选项
NoNewPrivileges=true
PrivateTmp=true
PrivateDevices=true
PrivateNetwork=false
ProtectSystem=strict
ProtectHome=true
ProtectKernelTunables=true
ProtectKernelModules=true
ProtectControlGroups=true
RestrictAddressFamilies=AF_UNIX AF_INET AF_INET6
RestrictNamespaces=true
RestrictRealtime=true
RestrictSUIDSGID=true
SystemCallArchitectures=native
SystemCallFilter=@system-service
SystemCallFilter=~@privileged @resources
SystemCallFilter=~@module
LockPersonality=true
MemoryDenyWriteExecute=true
ReadWritePaths=/opt/myapp/data /var/log/myapp
ReadOnlyPaths=/opt/myapp
# 资源限制
LimitNOFILE=65536
LimitNPROC=4096
LimitCPU=600
LimitFSIZE=1G
[Install]
WantedBy=multi-user.target
5.3 Apache HTTP Server 加固
# /etc/httpd/conf.d/security.conf
ServerTokens Prod
ServerSignature Off
TraceEnable Off
# 禁用危险模块
# a2dismod autoindex status info
# 禁用 SSI
# 禁用 CGI(如果不是必须的)
# 目录权限
<Directory />
Options -Indexes -ExecCGI -FollowSymLinks
AllowOverride None
Require all denied
</Directory>
<Directory /var/www/html>
Options -Indexes -ExecCGI
AllowOverride None
Require all granted
</Directory>
# SSL/TLS 配置
SSLProtocol -all +TLSv1.2 +TLSv1.3
SSLCipherSuite HIGH:!aNULL:!MD5
SSLHonorCipherOrder on
SSLSessionTickets off
SSLCompression off
Header always set Strict-Transport-Security "max-age=31536000; includeSubDomains"
Header always set X-Content-Type-Options "nosniff"
Header always set X-Frame-Options "DENY"
Header always set X-XSS-Protection "1; mode=block"
Header always set Content-Security-Policy "default-src 'self'"
# 日志
LogLevel warn
ErrorLog /var/log/httpd/error.log
CustomLog /var/log/httpd/access.log combined
5.4 Nginx 加固
# /etc/nginx/nginx.conf
server_tokens off;
# SSL
ssl_protocols TLSv1.2 TLSv1.3;
ssl_ciphers 'ECDHE-ECDSA-AES256-GCM-SHA384:ECDHE-RSA-AES256-GCM-SHA384';
ssl_prefer_server_ciphers on;
ssl_session_cache shared:SSL:10m;
ssl_session_timeout 1d;
ssl_session_tickets off;
# 安全 Headers
add_header Strict-Transport-Security "max-age=31536000; includeSubDomains" always;
add_header X-Content-Type-Options "nosniff" always;
add_header X-Frame-Options "DENY" always;
add_header X-XSS-Protection "1; mode=block" always;
add_header Content-Security-Policy "default-src 'self'" always;
add_header Referrer-Policy "no-referrer" always;
add_header Permissions-Policy "geolocation=(), microphone=()" always;
# 限制方法
if ($request_method !~ ^(GET|HEAD|POST)$) {
return 405;
}
# 限制上传大小
client_max_body_size 10m;
# 隐藏文件
location ~ /\. { deny all; }
# 限速
limit_req_zone $binary_remote_addr zone=api:10m rate=10r/s;
location /api/ {
limit_req zone=api burst=20 nodelay;
}
5.5 MySQL 加固
# /etc/my.cnf
[mysqld]
# 禁用本地文件读写
local-infile=0
# 禁用符号链接
symbolic-links=0
# 禁用远程管理
skip-name-resolve
# 开启慢查询日志
slow_query_log=1
long_query_time=2
# 开启错误日志
log_error=/var/log/mysql/error.log
# 开启 binlog
log-bin=/var/log/mysql/binlog
server-id=1
binlog_format=ROW
expire_logs_days=7
-- 运行时加固
DELETE FROM mysql.user WHERE User='';
DELETE FROM mysql.user WHERE User='root' AND Host NOT IN ('localhost', '127.0.0.1', '::1');
DROP DATABASE IF EXISTS test;
DELETE FROM mysql.db WHERE Db='test' OR Db='test\\_%';
-- 强制密码复杂度
SET GLOBAL validate_password_policy = STRONG;
SET GLOBAL validate_password_length = 12;
-- 限制 root 远程登录
UPDATE mysql.user SET Host='localhost' WHERE User='root';
-- 每个应用使用独立账户
CREATE USER 'app_user'@'192.168.1.%' IDENTIFIED BY 'StrongP@ssw0rd!';
GRANT SELECT, INSERT, UPDATE ON appdb.* TO 'app_user'@'192.168.1.%';
FLUSH PRIVILEGES;
六、内核与系统安全策略
6.1 关键内核参数
# 内核模块签名验证(防 rootkit)
# /etc/modprobe.d/hardening.conf
install usb-storage /bin/true
install firewire-core /bin/true
install cramfs /bin/true
install freevxfs /bin/true
install jffs2 /bin/true
install hfs /bin/true
install hfsplus /bin/true
install squashfs /bin/true
install udf /bin/true
install dccp /bin/true
install sctp /bin/true
install rds /bin/true
install tipc /bin/true
install n-hdlc /bin/true
install ax25 /bin/true
install netrom /bin/true
install x25 /bin/true
install rose /bin/true
install decnet /bin/true
install econet /bin/true
install af_802154 /bin/true
install ipx /bin/true
install appletalk /bin/true
install psnap /bin/true
install p8023 /bin/true
install p8022 /bin/true
install can /bin/true
install atm /bin/true
install cipso /bin/true
install rds /bin/true
install ncpfs /bin/true
install ncp /bin/true
install nfs /bin/true
6.2 引导安全
# UEFI 密码
# 进入 BIOS/UEFI 设置 supervisor password
# GRUB 密码
grub2-mkpasswd-pbkdf2
# 复制生成的字符串到 /etc/grub.d/40_custom
set superusers="root"
password_pbkdf2 root grub.pbkdf2.sha512...
# 限制单用户模式
# /etc/sysconfig/init
SINGLE=/sbin/sulogin
# 禁止 Ctrl+Alt+Del 重启
# /etc/systemd/system/ctrl-alt-del.target 替换为屏蔽
systemctl mask ctrl-alt-del.target
6.3 进程隔离与沙箱
# Firejail 沙箱
yum install -y firejail
firejail --private firefox # 私有模式启动
firejail --net=none firefox # 禁用网络
firejail --whitelist=/tmp/deny=/etc firefox
# Bubblewrap
bwrap --ro-bind /usr /usr \
--bind /home/user /home/user \
--dev /dev \
--proc /proc \
--tmpfs /tmp \
--unshare-net \
firefox
# nsjail
nsjail --mode o --chroot / --user 1000 --group 1000 -- /bin/bash
6.4 资源限制
# /etc/security/limits.conf
* hard core 0 # 禁用 core dump
* soft nproc 1024
* hard nproc 4096
* soft nofile 1024
* hard nofile 65536
@developers hard cpu 600 # 10 分钟
@developers soft fsize 1G
# /etc/security/limits.d/10-disable-root.conf
root hard maxlogins 1
七、审计与监控策略
7.1 auditd 审计框架
# /etc/audit/rules.d/audit.rules
# 1. 审计时间变更
-w /etc/localtime -p wa -k time-change
# 2. 审计身份验证
-w /etc/pam.d/ -p wa -k auth
-w /etc/nsswitch.conf -p wa -k auth
-w /etc/pam_ldap.conf -p wa -k auth
# 3. 审计用户/组变更
-w /etc/group -p wa -k identity
-w /etc/passwd -p wa -k identity
-w /etc/shadow -p wa -k identity
-w /etc/sudoers -p wa -k identity
-w /etc/sudoers.d/ -p wa -k identity
# 4. 审计网络配置
-w /etc/issue -p wa -k system-locale
-w /etc/issue.net -p wa -k system-locale
-w /etc/hosts -p wa -k system-locale
-w /etc/sysconfig/network -p wa -k system-locale
-w /etc/sysconfig/network-scripts/ -p wa -k system-locale
# 5. 审计 sudoers
-w /etc/sudoers -p wa -k sudoers
-w /etc/sudoers.d/ -p wa -k sudoers
# 6. 审计 SSH 配置
-w /etc/ssh/sshd_config -p wa -k sshd
# 7. 审计关键系统调用
-a always,exit -F arch=b64 -S execve -k exec
-a always,exit -F arch=b64 -S adjtimex -S settimeofday -k time-change
-a always,exit -F arch=b64 -S mount -k mounts
-a always,exit -F arch=b64 -S sethostname -S setdomainname -k system-locale
-a always,exit -F arch=b64 -S setrlimit -k resources
-a always,exit -F arch=b64 -S adjtimex -S clock_settime -k time-change
# 8. 审计文件删除
-a always,exit -F arch=b64 -S unlink -S unlinkat -S rename -S renameat -F auid>=1000 -F auid!=4294967295 -k delete
# 9. 审计特权操作
-a always,exit -F arch=b64 -F euid=0 -S execve -k root-commands
# 10. 审计登录登出
-w /var/log/faillog -p wa -k logins
-w /var/log/lastlog -p wa -k logins
-w /var/log/tallylog -p wa -k logins
# 11. 审计模块加载
-w /sbin/insmod -p x -k modules
-w /sbin/rmmod -p x -k modules
-w /sbin/modprobe -p x -k modules
# 12. 不可变规则
-e 2
# 重启 auditd
service auditd restart
# 审计查询工具
ausearch -m avc # SELinux 拒绝
ausearch -m user_login # 登录事件
ausearch -k passwd_changes # 按 key 查询
ausearch -ts today # 今日事件
ausearch -ua 1000 # 用户 1000 的事件
# 报告
aureport --summary
aureport --failed
aureport --login
aureport --auth
7.2 日志管理
# rsyslog 配置
# /etc/rsyslog.d/00-secure.conf
auth,authpriv.* /var/log/secure
*.* @logserver.example.com:514 # 远程日志
*.* @@logserver.example.com:6514 # TLS 加密远程日志
# journald 远程转发
# /etc/systemd/journal-upload.conf
URL=https://logserver.example.com:19532
ServerKeyFile=/etc/ssl/private/journal-upload.key
ServerCertificateFile=/etc/ssl/certs/journal-upload.crt
TrustedCertificateFile=/etc/ssl/ca/trusted.pem
7.3 文件完整性监控
# AIDE
yum install -y aide
aide --init
mv /var/lib/aide/aide.db.new.gz /var/lib/aide/aide.db.gz
aide --check
# 配置 /etc/aide.conf
/etc Full
/bin Full
/sbin Full
/usr Full
/root Full
!/var/log
!/var/cache
# 定期运行
echo "0 5 * * * /usr/sbin/aide --check | mail -s 'AIDE Report' admin@example.com" >> /var/spool/cron/root
7.4 入侵检测
# OSSEC
yum install -y ossec-hids
/var/ossec/bin/ossec-control start
# ClamAV
yum install -y clamav clamav-update
freshclam
clamscan -r /home/ --infected --remove
# Rootkit Hunter
yum install -y rkhunter
rkhunter --update
rkhunter --check
# Lynis(系统审计)
yum install -y lynis
lynis audit system
八、Linux 安全策略部署实战
8.1 CIS Benchmark 加固
CIS(Center for Internet Security)发布的 Linux Benchmark 是业界公认的安全基线:
# 下载 CIS-CAT 工具
wget https://workbench.cisecurity.org/
# 常见 CIS 推荐项:
# - 1.1.1 禁用 USB 存储
# - 1.4.1 启用 AIDE
# - 1.5.1 启用 SELinux
# - 2.1.1 禁用 Telnet
# - 2.2.1 配置 SSH 安全
# - 3.1.1 禁用 IP 转发
# - 3.2.1 禁用源路由
# - 4.1.1 启用审计
# - 5.1.1 配置 cron 权限
# - 5.2.1 配置 SSH banner
# - 6.1.1 启用密码策略
# - 6.2.1 限制 su 命令
8.2 自动化加固工具
# OpenSCAP
yum install -y openscap-scanner openscap-utils
oscap info /usr/share/xml/scap/ssg/content/ssg-rhel8-ds.xml
oscap xccdf generate report /usr/share/xml/scap/ssg/content/ssg-rhel8-ds.xml
# 修复
oscap xccdf eval --remediate --profile xccdf_org.ssgproject.content_profile_standard \
/usr/share/xml/scap/ssg/content/ssg-rhel8-ds.xml
8.3 阶段式部署路线
8.4 故障排查 CheckList
| 问题 | 检查点 |
|---|---|
| SSH 无法登录 | /var/log/secure、sshd_config 语法(sshd -t)、SELinux 上下文 |
| 服务无法启动 | journalctl -u service、systemctl status、/var/log/messages |
| SELinux 拒绝 | ausearch -m avc、sealert、audit2allow |
| 防火墙阻断 | iptables -L -n -v、firewall-cmd –list-all |
| 性能问题 | top、vmstat、iostat、strace |
| 磁盘满 | df -h、du -sh、lsof |
九、Linux 安全策略与其他体系的关系
9.1 与 Windows 安全策略对比
| 维度 | Windows | Linux |
|---|---|---|
| 策略粒度 | 200+ GPO 设置 | 几乎无限(配置即可) |
| 集中管理 | AD GPO | Ansible/Puppet/Chef |
| 强制访问控制 | Integrity Levels | SELinux/AppArmor |
| 审计 | Event Log + ETW | auditd + syslog/journald |
| 认证 | Kerberos | PAM + 多种模块 |
9.2 与零信任架构
9.3 与等保 2.0 合规映射
| 等保 2.0 要求 | Linux 防护对应措施 |
|---|---|
| 8.1.4.1 身份鉴别 | PAM + MFA + 强密码策略 |
| 8.1.4.2 访问控制 | SELinux + 文件权限 + SUDO |
| 8.1.4.3 安全审计 | auditd + rsyslog + journald |
| 8.1.4.4 入侵防范 | AIDE + fail2ban + SELinux |
| 8.1.4.5 恶意代码防范 | ClamAV + rkhunter |
| 8.1.4.6 集中管控 | Ansible + Satellite + Spacewalk |
| 8.1.5.2 数据完整性 | AIDE + 数字签名 |
| 8.1.5.3 数据保密性 | LUKS 磁盘加密 + TLS |
| 8.1.6.2 集中管控 | 配置管理 + SIEM |
十、Linux 安全策略常见误区
10.1 误区一:装个杀毒软件就够了
Linux 系统虽然相对 Windows 病毒较少,但仍需:
- Rootkit 检测(rkhunter、chkrootkit)
- 恶意软件扫描(ClamAV)
- 入侵检测(OSSEC、Snort)
- 文件完整性监控(AIDE)
10.2 误区二:关闭 SELinux 解决所有问题
很多管理员遇到 SELinux 拒绝就直接 setenforce 0,这会严重削弱系统安全。正确做法:
- 使用
audit2why和audit2allow排查 - 设置正确的文件上下文
- 调整 SELinux 布尔值
- 仅在极端情况下才进入 permissive 模式
10.3 误区三:iptables 关闭就通
防火墙阻断访问时直接 systemctl stop firewalld 或 iptables -F 看似简单,但会导致:
- 暴露所有端口
- 失去连接追踪
- 失去 NAT 功能
10.4 误区四:SSH 改 22 端口就安全
改 SSH 端口(Security through obscurity):
- 仅降低被扫到的概率
- 不能阻止针对性攻击
- 必须配合密钥认证、fail2ban、SELinux
10.5 误区五:chmod 777 方便
chmod 777 是安全大忌:
- 任何用户都能修改文件
- 攻击者植入后门变得极容易
- 日志审计也无法判断修改者
10.6 误区六:审计日志本地就够了
本地审计日志可能被攻击者清除:
- 必须转发到远程 SIEM
- 启用日志完整性保护
- 设置日志文件为 append-only
十一、未来趋势
11.1 eBPF 安全监控
eBPF(extended Berkeley Packet Filter)允许在内核态安全地运行沙箱程序,未来将用于:
- 进程行为细粒度追踪
- 网络流量深度分析
- 系统调用拦截
- 实时异常检测
11.2 不可变基础设施
11.3 零信任 SSH
Teleport、Boundary 等工具正在重塑 SSH 访问:
- 临时凭证替代长期密钥
- 完整会话录屏
- 实时审计
- 设备合规性绑定
11.4 量子安全 SSH
OpenSSH 9.0+ 已支持混合 PQ 算法:
- sntrup761x25519-sha512@openssh.com
- 防范”先存储后解密”攻击
11.5 AI 驱动的安全运营
十二、总结
Linux 安全策略的核心是构建”预防-检测-响应“的完整闭环:
落地七步走:
- 第 1 步:资产与服务盘点(知道有什么)
- 第 2 步:基线对标 CIS Benchmark(差距分析)
- 第 3 步:基础加固(SSH、密码、防火墙、SELinux)
- 第 4 步:高级加固(SUDO 精细化、审计规则、文件完整性)
- 第 5 步:集成 SIEM,集中日志
- 第 6 步:定期漏洞扫描与渗透测试
- 第 7 步:持续运营与应急响应演练
只有将这七步形成计划-实施-检查-改进(PDCA)的循环,Linux 安全策略体系才能真正在企业安全运营中发挥价值。
附录:常用命令参考
# 1. 用户与认证
whoami, id, groups
last, lastb, lastlog
faillock --user alice
passwd -S alice # 查看密码状态
chage -l alice # 查看密码过期
# 2. 文件权限
ls -lZ file # SELinux 上下文
find / -perm -4000 -type f # SUID 文件
find / -perm -2000 -type f # SGID 文件
find / -perm -0002 -type f # world-writable 文件
getfacl /path # ACL
# 3. SELinux
sestatus, getenforce
semanage fcontext -l | grep httpd
restorecon -Rv /var/www
audit2allow -M mymod < /var/log/audit/audit.log
# 4. 防火墙
iptables -L -n -v
firewall-cmd --list-all
nft list ruleset
ip6tables -L -n -v
# 5. 服务管理
systemctl list-unit-files --state=enabled
systemctl status sshd
journalctl -u sshd --since today
# 6. 审计
ausearch -m avc
ausearch -k passwd_changes
aureport --summary
# 7. 文件完整性
aide --check
rpm -Va | grep -v 'not installed' # 校验所有 RPM 包
# 8. 性能与监控
top, htop, iotop, nethogs
vmstat 1
iostat -xz 1
ss -tunap # 替代 netstat
lsof -p PID
strace -p PID
# 9. 进程
ps auxf # 进程树
pstree -p
kill -9 PID
# 10. 应急响应检查
# 查看最近登录的账户
last | head
# 查看 sudo 操作
cat /var/log/sudo.log
# 查看计划任务
ls -la /etc/cron*
crontab -l
# 查看启动项
systemctl list-dependencies multi-user.target
# 检查 rootkit
rkhunter --check
chkrootkit
# 检查异常端口
ss -tunap | grep -E 'LISTEN|ESTAB'
研究文档(引用来源参考)
(no reference document available)