Skip to content

安全配置

本章将介绍 Linux 系统安全配置,包括 SSH 加固、防火墙配置、SELinux/AppArmor、安全审计等内容,帮助你构建安全的 Linux 系统。

SSH 安全加固

SSH 配置文件

bash
# SSH 配置文件
/etc/ssh/sshd_config

# 备份配置文件
sudo cp /etc/ssh/sshd_config /etc/ssh/sshd_config.bak

# 编辑配置
sudo vim /etc/ssh/sshd_config

SSH 安全配置

bash
# /etc/ssh/sshd_config 安全配置

# 禁止 root 登录
PermitRootLogin no

# 使用密钥认证
PubkeyAuthentication yes

# 禁用密码认证
PasswordAuthentication no
PermitEmptyPasswords no

# 修改默认端口
Port 2222

# 限制登录用户
AllowUsers user1 user2
AllowGroups ssh-users

# 登录超时
LoginGraceTime 60

# 最大尝试次数
MaxAuthTries 3

# 禁用空密码
PermitEmptyPasswords no

# 禁用 X11 转发
X11Forwarding no

# 禁用端口转发
AllowTcpForwarding no

# 限制会话
MaxSessions 2
MaxStartups 3

# 使用协议 2
Protocol 2

# 设置登录标语
Banner /etc/ssh/banner

# 禁用反向 DNS 解析(加快登录速度)
UseDNS no

# 重启 SSH 服务
sudo systemctl restart sshd

# 验证配置
sudo sshd -t

SSH 密钥管理

bash
# 生成 SSH 密钥对(推荐 ed25519)
ssh-keygen -t ed25519 -C "your_email@example.com"

# 或使用 RSA(兼容性更好)
ssh-keygen -t rsa -b 4096 -C "your_email@example.com"

# 指定密钥文件
ssh-keygen -t ed25519 -f ~/.ssh/server_key

# 添加密码保护密钥
ssh-keygen -p -f ~/.ssh/id_ed25519

# 复制公钥到服务器
ssh-copy-id -i ~/.ssh/id_ed25519.pub user@server

# 手动添加公钥
cat ~/.ssh/id_ed25519.pub | ssh user@server 'cat >> ~/.ssh/authorized_keys'

# 设置正确的权限
chmod 700 ~/.ssh
chmod 600 ~/.ssh/authorized_keys
chmod 600 ~/.ssh/id_ed25519
chmod 644 ~/.ssh/id_ed25519.pub

# 使用 ssh-agent 管理密钥
eval "$(ssh-agent -s)"
ssh-add ~/.ssh/id_ed25519

# 配置 ~/.ssh/config
Host myserver
    HostName 192.168.1.100
    User username
    Port 2222
    IdentityFile ~/.ssh/server_key
    ServerAliveInterval 60
    ServerAliveCountMax 3

SSH 安全工具

bash
# fail2ban - 防止暴力破解

# 安装
sudo apt install fail2ban    # Debian/Ubuntu
sudo dnf install fail2ban    # RHEL/CentOS

# 配置文件
/etc/fail2ban/jail.conf
/etc/fail2ban/jail.local    # 自定义配置

# 创建自定义配置
sudo vim /etc/fail2ban/jail.local

[sshd]
enabled = true
port = ssh
filter = sshd
logpath = /var/log/auth.log
maxretry = 3
findtime = 600
bantime = 3600
ignoreip = 127.0.0.1/8 192.168.1.0/24

# 启动服务
sudo systemctl enable --now fail2ban

# 查看状态
sudo fail2ban-client status sshd

# 解封 IP
sudo fail2ban-client set sshd unbanip 192.168.1.100

# 查看日志
sudo tail -f /var/log/fail2ban.log

防火墙配置

ufw 防火墙

bash
# ufw - Ubuntu 默认防火墙

# 查看状态
sudo ufw status verbose

# 启用防火墙
sudo ufw enable

# 设置默认策略
sudo ufw default deny incoming
sudo ufw default allow outgoing

# 允许端口
sudo ufw allow 22/tcp
sudo ufw allow 80/tcp
sudo ufw allow 443/tcp

# 允许服务
sudo ufw allow ssh
sudo ufw allow http
sudo ufw allow https

# 允许特定 IP
sudo ufw allow from 192.168.1.100

# 允许特定 IP 访问特定端口
sudo ufw allow from 192.168.1.100 to any port 22

# 允许网段
sudo ufw allow from 192.168.1.0/24

# 拒绝访问
sudo ufw deny 23/tcp
sudo ufw deny from 192.168.1.200

# 删除规则
sudo ufw delete allow 80/tcp
sudo ufw status numbered
sudo ufw delete 3

# 限制连接(防暴力破解)
sudo ufw limit ssh

# 重置防火墙
sudo ufw reset

# 日志
sudo ufw logging on
sudo ufw logging medium

firewalld 防火墙

bash
# firewalld - RHEL/CentOS 默认防火墙

# 查看状态
sudo systemctl status firewalld
sudo firewall-cmd --state

# 查看所有规则
sudo firewall-cmd --list-all

# 查看开放的端口
sudo firewall-cmd --list-ports

# 开放端口
sudo firewall-cmd --add-port=80/tcp
sudo firewall-cmd --add-port=443/tcp

# 永久开放端口
sudo firewall-cmd --permanent --add-port=80/tcp

# 开放服务
sudo firewall-cmd --add-service=http
sudo firewall-cmd --permanent --add-service=https

# 查看可用服务
sudo firewall-cmd --get-services

# 移除端口
sudo firewall-cmd --remove-port=80/tcp
sudo firewall-cmd --permanent --remove-port=80/tcp

# 允许特定 IP
sudo firewall-cmd --add-source=192.168.1.100

# 拒绝特定 IP
sudo firewall-cmd --add-source=192.168.1.200 --zone=block

# 端口转发
sudo firewall-cmd --add-forward-port=port=80:proto=tcp:toport=8080

# 重新加载配置
sudo firewall-cmd --reload

# 查看区域
sudo firewall-cmd --get-zones
sudo firewall-cmd --get-active-zones

# 设置默认区域
sudo firewall-cmd --set-default-zone=public

iptables 防火墙

bash
# iptables - 底层防火墙

# 查看规则
sudo iptables -L -n -v --line-numbers

# 允许本地回环
sudo iptables -A INPUT -i lo -j ACCEPT

# 允许已建立的连接
sudo iptables -A INPUT -m state --state ESTABLISHED,RELATED -j ACCEPT

# 允许 SSH
sudo iptables -A INPUT -p tcp --dport 22 -j ACCEPT

# 允许 HTTP/HTTPS
sudo iptables -A INPUT -p tcp --dport 80 -j ACCEPT
sudo iptables -A INPUT -p tcp --dport 443 -j ACCEPT

# 允许特定 IP
sudo iptables -A INPUT -s 192.168.1.100 -j ACCEPT

# 拒绝特定 IP
sudo iptables -A INPUT -s 192.168.1.200 -j DROP

# 设置默认策略
sudo iptables -P INPUT DROP
sudo iptables -P FORWARD DROP
sudo iptables -P OUTPUT ACCEPT

# 删除规则
sudo iptables -D INPUT 1

# 清空规则
sudo iptables -F

# 保存规则
sudo iptables-save > /etc/iptables/rules.v4
sudo iptables-restore < /etc/iptables/rules.v4

# 安装 iptables-persistent(Debian/Ubuntu)
sudo apt install iptables-persistent
sudo netfilter-persistent save

SELinux 和 AppArmor

SELinux

bash
# SELinux - Security-Enhanced Linux(RHEL/CentOS)

# 查看 SELinux 状态
getenforce
sestatus

# 临时设置模式
sudo setenforce 0    # Permissive(宽容模式)
sudo setenforce 1    # Enforcing(强制模式)

# 永久配置
sudo vim /etc/selinux/config
# SELINUX=enforcing    # 强制模式
# SELINUX=permissive   # 宽容模式
# SELINUX=disabled     # 禁用

# 查看 SELinux 上下文
ls -Z /var/www/html
ps -Z
id -Z

# 修改文件上下文
sudo chcon -t httpd_sys_content_t /var/www/html/file.html
sudo chcon -R -t httpd_sys_content_t /var/www/html/

# 恢复默认上下文
sudo restorecon -Rv /var/www/html/

# 查看 SELinux 布尔值
getsebool -a | grep httpd

# 设置布尔值
sudo setsebool -P httpd_can_network_connect 1

# 查看 SELinux 日志
sudo ausearch -m avc -ts recent
sudo tail -f /var/log/audit/audit.log

# 生成策略模块
sudo audit2allow -a -w    # 查看建议
sudo audit2allow -a -M mypolicy    # 生成模块
sudo semodule -i mypolicy.pp    # 安装模块

# 查看 SELinux 策略
sudo seinfo -t
sudo sesearch --allow -s httpd_t

AppArmor

bash
# AppArmor - Application Armor(Debian/Ubuntu)

# 查看状态
sudo aa-status
sudo apparmor_status

# 查看配置文件
ls /etc/apparmor.d/

# 查看模式
# enforce - 强制模式(阻止违规行为)
# complain - 投诉模式(只记录不阻止)

# 切换模式
sudo aa-enforce /etc/apparmor.d/usr.sbin.nginx
sudo aa-complain /etc/apparmor.d/usr.sbin.nginx

# 禁用配置
sudo aa-disable /etc/apparmor.d/usr.sbin.nginx

# 重新加载配置
sudo apparmor_parser -r /etc/apparmor.d/usr.sbin.nginx

# 查看日志
sudo tail -f /var/log/syslog | grep apparmor
sudo tail -f /var/log/kern.log | grep apparmor

# 创建配置文件
sudo aa-genprof /usr/bin/myapp

# 更新配置文件
sudo aa-logprof

# AppArmor 配置文件示例
# /etc/apparmor.d/usr.sbin.nginx

#include <tunables/global>

/usr/sbin/nginx {
  #include <abstractions/base>
  #include <abstractions/nameservice>

  capability net_bind_service,
  capability setgid,
  capability setuid,

  /usr/sbin/nginx mr,
  /etc/nginx/** r,
  /var/log/nginx/** rw,
  /var/www/** r,

  network inet tcp,
}

安全审计

auditd 审计系统

bash
# auditd - Linux 审计系统

# 安装
sudo apt install auditd    # Debian/Ubuntu
sudo dnf install audit     # RHEL/CentOS

# 启动服务
sudo systemctl enable --now auditd

# 配置文件
/etc/audit/auditd.conf
/etc/audit/rules.d/audit.rules

# 添加审计规则
# 监控文件访问
sudo auditctl -w /etc/passwd -p wa -k passwd_changes

# 监控目录
sudo auditctl -w /etc/ -p wa -k etc_changes

# 监控系统调用
sudo auditctl -a always,exit -F arch=b64 -S open -F exit=-EACCES -k access_denied

# 监控特定用户
sudo auditctl -a always,exit -F arch=b64 -S execve -F uid=1000 -k user_commands

# 查看规则
sudo auditctl -l

# 删除所有规则
sudo auditctl -D

# 查看日志
sudo ausearch -k passwd_changes
sudo ausearch -ts today
sudo ausearch -ui 1000

# 生成报告
sudo aureport
sudo aureport --file
sudo aureport --user
sudo aureport --summary

# 永久规则(添加到 /etc/audit/rules.d/custom.rules)
-w /etc/passwd -p wa -k passwd_changes
-w /etc/shadow -p wa -k shadow_changes
-w /etc/sudoers -p wa -k sudoers_changes
-a always,exit -F arch=b64 -S chmod -S chown -S chgrp -k perm_changes

# 重启服务应用规则
sudo systemctl restart auditd

日志监控

bash
# 查看认证日志
sudo tail -f /var/log/auth.log    # Debian/Ubuntu
sudo tail -f /var/log/secure      # RHEL/CentOS

# 查看失败的登录
sudo grep "Failed password" /var/log/auth.log
sudo grep "authentication failure" /var/log/auth.log

# 查看成功的 sudo
sudo grep "COMMAND" /var/log/auth.log

# 查看用户登录历史
last
lastb    # 失败的登录

# 查看当前登录用户
w
who

# 使用 logwatch 生成报告
sudo apt install logwatch
sudo logwatch --output stdout --detail high

# 使用 logcheck 检查异常
sudo apt install logcheck
sudo logcheck

系统加固

用户和权限

bash
# 锁定不需要的账户
sudo passwd -l daemon
sudo passwd -l bin
sudo passwd -l sys

# 检查空密码账户
sudo awk -F: '($2 == "") {print $1}' /etc/shadow

# 检查 UID 为 0 的账户
sudo awk -F: '($3 == 0) {print $1}' /etc/passwd

# 设置密码策略
sudo vim /etc/login.defs
# PASS_MAX_DAYS   90
# PASS_MIN_DAYS   7
# PASS_WARN_AGE   14

# 设置密码复杂度
sudo apt install libpam-pwquality
sudo vim /etc/pam.d/common-password
# password requisite pam_pwquality.so minlen=12 ucredit=-1 lcredit=-1 dcredit=-1 ocredit=-1

# 限制 su 命令
sudo vim /etc/pam.d/su
# auth required pam_wheel.so group=sudo

# 设置 umask
echo "umask 027" >> /etc/profile

网络安全

bash
# 禁用不必要的服务
sudo systemctl disable bluetooth
sudo systemctl disable cups

# 检查监听端口
sudo ss -tlnp
sudo netstat -tlnp

# 检查开放端口
sudo nmap -sT localhost

# 禁用 IPv6(如果不需要)
sudo vim /etc/sysctl.conf
# net.ipv6.conf.all.disable_ipv6 = 1
# net.ipv6.conf.default.disable_ipv6 = 1

# 应用设置
sudo sysctl -p

# 内核安全参数
sudo vim /etc/sysctl.conf

# 禁用 IP 转发
net.ipv4.ip_forward = 0

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

# 启用反向路径过滤
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.send_redirects = 0
net.ipv4.conf.default.send_redirects = 0

# 启用 TCP SYN Cookie
net.ipv4.tcp_syncookies = 1

# 应用设置
sudo sysctl -p

文件系统安全

bash
# 查找 SUID 文件
sudo find / -type f -perm -4000 -ls

# 查找 SGID 文件
sudo find / -type f -perm -2000 -ls

# 查找可写文件
sudo find / -type f -perm -0002 -ls

# 查找无主文件
sudo find / -nouser -o -nogroup

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

# 检查文件完整性
sudo apt install aide
sudo aideinit
sudo aide --update
sudo aide --check

安全检查工具

安全扫描

bash
# Lynis - 安全审计工具
sudo apt install lynis
sudo lynis audit system

# chkrootkit - 检测 rootkit
sudo apt install chkrootkit
sudo chkrootkit

# rkhunter - 检测 rootkit
sudo apt install rkhunter
sudo rkhunter --update
sudo rkhunter --check

# ClamAV - 杀毒软件
sudo apt install clamav clamav-daemon
sudo freshclam
sudo clamscan -r /home

# OpenVAS - 漏洞扫描
sudo apt install openvas
sudo gvm-setup
sudo gvm-start

安全基线检查

bash
# 使用脚本检查安全配置

#!/bin/bash
# 安全基线检查脚本

echo "========== 安全基线检查 =========="

# 检查 SSH 配置
echo -e "\n--- SSH 配置 ---"
grep "^PermitRootLogin" /etc/ssh/sshd_config
grep "^PasswordAuthentication" /etc/ssh/sshd_config
grep "^Port" /etc/ssh/sshd_config

# 检查防火墙状态
echo -e "\n--- 防火墙状态 ---"
sudo ufw status || sudo firewall-cmd --state

# 检查开放端口
echo -e "\n--- 开放端口 ---"
sudo ss -tlnp

# 检查用户
echo -e "\n--- UID 为 0 的用户 ---"
awk -F: '($3 == 0) {print $1}' /etc/passwd

# 检查空密码用户
echo -e "\n--- 空密码用户 ---"
sudo awk -F: '($2 == "") {print $1}' /etc/shadow

# 检查 SUID 文件
echo -e "\n--- SUID 文件 ---"
sudo find / -type f -perm -4000 2>/dev/null

# 检查最近登录
echo -e "\n--- 最近登录 ---"
last | head -10

# 检查失败登录
echo -e "\n--- 失败登录 ---"
lastb | head -10

echo -e "\n========== 检查完成 =========="

小结

本章介绍了 Linux 安全配置:

内容工具功能
SSH 加固sshd_config, fail2ban保护远程访问
防火墙ufw, firewalld, iptables网络访问控制
强制访问控制SELinux, AppArmor进程权限控制
安全审计auditd系统行为审计
系统加固各种配置减少攻击面

安全检查清单

bash
# 1. SSH 安全
# - 禁用 root 登录
# - 使用密钥认证
# - 修改默认端口
# - 安装 fail2ban

# 2. 防火墙
# - 启用防火墙
# - 只开放必要端口
# - 设置默认拒绝策略

# 3. 用户管理
# - 删除不必要的账户
# - 设置密码策略
# - 限制 su 权限

# 4. 服务管理
# - 关闭不必要的服务
# - 更新软件包
# - 配置日志

# 5. 文件安全
# - 设置正确的权限
# - 检查 SUID/SGID
# - 使用文件完整性检查

下一步

下一章我们将学习 故障排查,了解如何诊断和解决 Linux 系统问题。