Linux安全基础
Linux安全基础
安全原则
- 最小权限原则
- 纵深防御原则
- 默认拒绝原则
- 职责分离原则
用户安全
密码策略
# 设置密码过期策略
sudo chage -M 90 -m 7 -W 14 username
# 查看密码策略
sudo chage -l username
# 强制用户下次登录修改密码
sudo chage -d 0 username
PAM认证
# /etc/pam.d/common-password
# 密码复杂度要求
password requisite pam_pwquality.so retry=3 minlen=12 dcredit=-1 ucredit=-1 lcredit=-1 ocredit=-1
# 登录失败锁定
auth required pam_faillock.so preauth deny=5 unlock_time=900
禁用root登录
# /etc/ssh/sshd_config
PermitRootLogin no
# 锁定root账户
sudo passwd -l root
文件权限安全
查找异常权限文件
# 查找SUID文件
find / -type f -perm -4000 2>/dev/null
# 查找SGID文件
find / -type f -perm -2000 2>/dev/null
# 查找全局可写目录
find / -type d -perm -0002 2>/dev/null
# 查找无主文件
find / -nouser -o -nogroup 2>/dev/null
修复权限
# 修复关键目录权限
chmod 755 /etc
chmod 644 /etc/passwd
chmod 600 /etc/shadow
# 修复用户主目录
chmod 700 /home/*
服务安全
关闭不必要的服务
# 查看运行的服务
systemctl list-units --type=service --state=running
# 关闭不需要的服务
sudo systemctl disable cups
sudo systemctl stop cups
服务加固
# Nginx安全配置
server_tokens off;
# 禁用不必要的HTTP方法
if ($request_method !~ ^(GET|HEAD|POST)$) {
return 405;
}
网络安全
防火墙配置
# 仅开放必要端口
sudo firewall-cmd --permanent --add-service=ssh
sudo firewall-cmd --permanent --add-service=http
sudo firewall-cmd --permanent --add-service=https
sudo firewall-cmd --reload
端口安全
# 查看监听端口
ss -tulpn
# 禁止不必要的端口监听
# 在服务配置中绑定到特定IP
listen 127.0.0.1:3306;
日志安全
启用审计日志
# 安装auditd
sudo apt-get install auditd
# 启用审计规则
sudo auditctl -w /etc/passwd -p wa -k password_changes
sudo auditctl -w /var/log/auth.log -p wa -k auth_log
# 查看审计日志
sudo ausearch -k password_changes
监控异常登录
# 查看登录失败记录
sudo grep "Failed password" /var/log/auth.log
# 查看当前登录用户
w
# 查看最近登录记录
last
lastb
实践:安全加固脚本
#!/bin/bash
echo "=== Linux安全加固 ==="
# 1. 更新系统
sudo apt-get update
sudo apt-get upgrade -y
# 2. 配置防火墙
sudo apt-get install -y ufw
sudo ufw default deny incoming
sudo ufw default allow outgoing
sudo ufw allow ssh
sudo ufw allow http
sudo ufw allow https
sudo ufw enable
# 3. 安装安全工具
sudo apt-get install -y fail2ban
# 4. 配置SSH
sudo sed -i 's/#PermitRootLogin yes/PermitRootLogin no/' /etc/ssh/sshd_config
sudo sed -i 's/#PasswordAuthentication yes/PasswordAuthentication no/' /etc/ssh/sshd_config
sudo systemctl restart sshd
# 5. 设置密码策略
sudo apt-get install -y libpam-pwquality
echo "安全加固完成!"
总结
Linux安全是一个持续的过程。通过用户管理、文件权限、服务配置和日志监控等多个层面的防护,可以有效提高系统安全性。