插件窝 干货文章 linux安全加固脚本怎么写

linux安全加固脚本怎么写

etc echo Security Log 655    来源:    2025-04-22

Linux安全加固脚本编写指南

作为IT工程师,我可以为您提供一个全面的Linux安全加固脚本编写方案。以下是一个结构化的脚本框架和关键安全措施:

基础脚本框架

#!/bin/bash

# Linux Security Hardening Script
# Version: 1.0
# Author: [Your Name]
# Date: $(date +%Y-%m-%d)

# Check if running as root
if [ "$(id -u)" -ne 0 ]; then
    echo "This script must be run as root" >&2
    exit 1
fi

# Log file setup
LOG_FILE="/var/log/security_hardening_$(date +%Y%m%d).log"
exec > >(tee -a "$LOG_FILE") 2>&1

echo "Starting Linux Security Hardening - $(date)"

# --------------------------
# 1. SYSTEM UPDATE SECTION
# --------------------------
echo "### 1. Updating System Packages ###"

update_system() {
    # For Debian/Ubuntu
    if [ -f /etc/debian_version ]; then
        apt-get update && apt-get upgrade -y
        apt-get dist-upgrade -y
        apt-get autoremove -y
    # For RHEL/CentOS
    elif [ -f /etc/redhat-release ]; then
        yum update -y
        yum upgrade -y
    # For SUSE
    elif [ -f /etc/SuSE-release ]; then
        zypper refresh
        zypper update -y
    else
        echo "Unsupported Linux distribution"
        exit 1
    fi
}

update_system

# --------------------------
# 2. USER ACCOUNT SECURITY
# --------------------------
echo "### 2. User Account Security ###"

# Password policy
echo "Setting password policies..."
sed -i 's/^PASS_MAX_DAYS.*/PASS_MAX_DAYS   90/' /etc/login.defs
sed -i 's/^PASS_MIN_DAYS.*/PASS_MIN_DAYS   7/' /etc/login.defs
sed -i 's/^PASS_WARN_AGE.*/PASS_WARN_AGE   14/' /etc/login.defs
sed -i 's/^UMASK.*/UMASK       077/' /etc/login.defs

# Install and configure cracklib for password complexity
apt-get install -y libpam-cracklib || yum install -y cracklib

# Configure password complexity
echo "password requisite pam_cracklib.so try_first_pass retry=3 minlen=14 lcredit=-1 ucredit=-1 dcredit=-1 ocredit=-1" >> /etc/pam.d/common-password

# Lock root account from direct login
echo "Locking root account from direct login..."
passwd -l root

# Create sudo users (example)
# useradd -m -s /bin/bash adminuser
# usermod -aG sudo adminuser
# passwd adminuser

# --------------------------
# 3. SSH SECURITY
# --------------------------
echo "### 3. SSH Security Hardening ###"

backup_config() {
    cp /etc/ssh/sshd_config /etc/ssh/sshd_config.bak_$(date +%Y%m%d)
}

harden_ssh() {
    backup_config

    sed -i 's/^#PermitRootLogin.*/PermitRootLogin no/' /etc/ssh/sshd_config
    sed -i 's/^PasswordAuthentication.*/PasswordAuthentication no/' /etc/ssh/sshd_config
    sed -i 's/^X11Forwarding.*/X11Forwarding no/' /etc/ssh/sshd_config
    sed -i 's/^#MaxAuthTries.*/MaxAuthTries 3/' /etc/ssh/sshd_config
    sed -i 's/^#ClientAliveInterval.*/ClientAliveInterval 300/' /etc/ssh/sshd_config
    sed -i 's/^#ClientAliveCountMax.*/ClientAliveCountMax 0/' /etc/ssh/sshd_config

    echo "AllowUsers adminuser" >> /etc/ssh/sshd_config
    echo "Protocol 2" >> /etc/ssh/sshd_config
    echo "UseDNS no" >> /etc/ssh/sshd_config

    # Restart SSH service
    systemctl restart sshd || service ssh restart
}

harden_ssh

# --------------------------
# 4. FIREWALL CONFIGURATION
# --------------------------
echo "### 4. Firewall Configuration ###"

configure_firewall() {
    # For UFW (Ubuntu)
    if command -v ufw >/dev/null; then
        ufw default deny incoming
        ufw default allow outgoing
        ufw allow ssh
        ufw enable
    # For firewalld (RHEL/CentOS)
    elif command -v firewall-cmd >/dev/null; then
        systemctl start firewalld
        systemctl enable firewalld
        firewall-cmd --permanent --remove-service=dhcpv6-client
        firewall-cmd --permanent --add-service=ssh
        firewall-cmd --reload
    # For iptables (legacy)
    else
        iptables -A INPUT -p tcp --dport 22 -j ACCEPT
        iptables -A INPUT -j DROP
        iptables-save > /etc/iptables.rules
    fi
}

configure_firewall

# --------------------------
# 5. FILE SYSTEM SECURITY
# --------------------------
echo "### 5. File System Security ###"

# Set sticky bit on world-writable directories
find / -type d \( -perm -0002 -a ! -perm -1000 \) -exec chmod +t {} \;

# Disable SUID/SGID for unnecessary files
find / -type f \( -perm -4000 -o -perm -2000 \) -exec chmod u-s,g-s {} \;

# Secure critical files
chmod 600 /etc/passwd /etc/shadow /etc/group /etc/gshadow
chmod 644 /etc/passwd /etc/group
chown root:root /etc/passwd /etc/shadow /etc/group /etc/gshadow

# --------------------------
# 6. KERNEL HARDENING
# --------------------------
echo "### 6. Kernel Hardening ###"

# Configure sysctl settings
echo "Configuring kernel parameters..."
cat << EOF > /etc/sysctl.d/99-security.conf
# IP Spoofing protection
net.ipv4.conf.all.rp_filter=1
net.ipv4.conf.default.rp_filter=1

# Ignore ICMP broadcast requests
net.ipv4.icmp_echo_ignore_broadcasts=1

# Disable source packet routing
net.ipv4.conf.all.accept_source_route=0
net.ipv6.conf.all.accept_source_route=0
net.ipv4.conf.default.accept_source_route=0
net.ipv6.conf.default.accept_source_route=0

# Ignore send redirects
net.ipv4.conf.all.send_redirects=0
net.ipv4.conf.default.send_redirects=0

# Block SYN attacks
net.ipv4.tcp_syncookies=1
net.ipv4.tcp_max_syn_backlog=2048
net.ipv4.tcp_synack_retries=2
net.ipv4.tcp_syn_retries=5

# Log Martians
net.ipv4.conf.all.log_martians=1
net.ipv4.icmp_ignore_bogus_error_responses=1

# Ignore ICMP redirects
net.ipv4.conf.all.accept_redirects=0
net.ipv6.conf.all.accept_redirects=0
net.ipv4.conf.default.accept_redirects=0
net.ipv6.conf.default.accept_redirects=0

# Ignore Directed pings
net.ipv4.icmp_echo_ignore_all=1
EOF

sysctl -p /etc/sysctl.d/99-security.conf

# --------------------------
# 7. DISABLE UNNECESSARY SERVICES
# --------------------------
echo "### 7. Disabling Unnecessary Services ###"

disable_services() {
    # List of services to disable (adjust based on your needs)
    local services=(
        "telnet"
        "ftp"
        "rsh"
        "rlogin"
        "rexec"
        "nfs"
        "nis"
        "tftp"
        "snmp"
        "xinetd"
        "chargen"
        "daytime"
        "echo"
        "discard"
        "time"
        "rpcbind"
    )

    for service in "${services[@]}"; do
        if systemctl list-unit-files | grep -q "^${service}\."; then
            systemctl stop "$service"
            systemctl disable "$service"
            echo "Disabled service: $service"
        fi
    done
}

disable_services

# --------------------------
# 8. AUDIT AND LOGGING
# --------------------------
echo "### 8. Audit and Logging Configuration ###"

# Install auditd if not present
if ! command -v auditctl >/dev/null; then
    apt-get install -y auditd || yum install -y audit
fi

# Configure auditd
cat << EOF > /etc/audit/audit.rules
# Delete all existing rules
-D

# Set buffer size
-b 8192

# Make the configuration immutable
-e 2

# System audit rules
-a always,exit -F arch=b64 -S adjtimex -S settimeofday -k time-change
-a always,exit -F arch=b32 -S adjtimex -S settimeofday -S stime -k time-change
-a always,exit -F arch=b64 -S clock_settime -k time-change
-a always,exit -F arch=b32 -S clock_settime -k time-change
-w /etc/localtime -p wa -k time-change

# User and group changes
-w /etc/group -p wa -k identity
-w /etc/passwd -p wa -k identity
-w /etc/gshadow -p wa -k identity
-w /etc/shadow -p wa -k identity
-w /etc/security/opasswd -p wa -k identity

# System network configuration changes
-w /etc/hosts -p wa -k hosts
-w /etc/sysconfig/network -p wa -k network

# Login and logout events
-w /var/log/faillog -p wa -k logins
-w /var/log/lastlog -p wa -k logins
-w /var/log/tallylog -p wa -k logins

# Process and session initiation
-w /var/run/utmp -p wa -k session
-w /var/log/btmp -p wa -k session
-w /var/log/wtmp -p wa -k session

# Privilege escalation
-a always,exit -F arch=b64 -S setuid -S setgid -F euid=0 -F auid>=1000 -F auid!=4294967295 -k privileged
-a always,exit -F arch=b32 -S setuid -S setgid -F euid=0 -F auid>=1000 -F auid!=4294967295 -k privileged

# File deletion
-a always,exit -F arch=b64 -S unlink -S unlinkat -S rename -S renameat -F auid>=1000 -F auid!=4294967295 -k delete
-a always,exit -F arch=b32 -S unlink -S unlinkat -S rename -S renameat -F auid>=1000 -F auid!=4294967295 -k delete

# System administration actions
-w /etc/sudoers -p wa -k scope
-w /etc/sudoers.d/ -p wa -k scope

# Kernel module loading and unloading
-w /sbin/insmod -p x -k modules
-w /sbin/rmmod -p x -k modules
-w /sbin/modprobe -p x -k modules
-a always,exit -F arch=b64 -S init_module -S delete_module -k modules
EOF

service auditd restart

# Configure logrotate
cat << EOF > /etc/logrotate.d/security
/var/log/secure
/var/log/auth.log
/var/log/audit/audit.log
/var/log/wtmp
/var/log/btmp
/var/log/lastlog {
    missingok
    weekly
    rotate 4
    compress
    delaycompress
    notifempty
    create 0600 root root
}
EOF

# --------------------------
# 9. MALWARE PROTECTION
# --------------------------
echo "### 9. Malware Protection ###"

# Install and configure rkhunter
if ! command -v rkhunter >/dev/null; then
    apt-get install -y rkhunter || yum install -y rkhunter
fi

rkhunter --update
rkhunter --propupd
rkhunter --check --sk

# Install and configure ClamAV
if ! command -v clamscan >/dev/null; then
    apt-get install -y clamav clamav-daemon || yum install -y clamav clamav-update
    freshclam
fi

# Schedule daily scans
echo "0 3 * * * root /usr/bin/clamscan -r / --exclude-dir=/sys/ --quiet --infected --log=/var/log/clamav/scan.log" > /etc/cron.daily/clamav-scan
chmod +x /etc/cron.daily/clamav-scan

# --------------------------
# 10. FINAL CHECKS
# --------------------------
echo "### 10. Final Security Checks ###"

# Check for world-writable files
echo "Checking for world-writable files..."
find / -xdev -type f -perm -0002 -exec ls -ld {} \; > /tmp/world_writable_files.txt

# Check for unowned files
echo "Checking for unowned files..."
find / -xdev \( -nouser -o -nogroup \) -exec ls -ld {} \; > /tmp/unowned_files.txt

# Check SUID/SGID files
echo "Checking SUID/SGID files..."
find / -xdev \( -perm -4000 -o -perm -2000 \) -type f -exec ls -ld {} \; > /tmp/suid_sgid_files.txt

echo "Security hardening completed. Review the following files:"
echo "- /tmp/world_writable_files.txt"
echo "- /tmp/unowned_files.txt"
echo "- /tmp/suid_sgid_files.txt"
echo "- Full log at $LOG_FILE"

exit 0

关键安全措施说明

  1. 系统更新

    • 确保所有软件包都是最新版本
    • 自动删除不再需要的依赖项
  2. 用户账户安全

    • 设置密码策略(复杂性、有效期)
    • 禁用root直接登录
    • 限制sudo权限
  3. SSH加固

    • 禁用root SSH登录
    • 禁用密码认证(强制使用密钥)
    • 限制连接尝试次数
    • 设置空闲会话超时
  4. 防火墙配置

    • 默认拒绝所有入站连接
    • 仅允许必要的服务(如SSH)
    • 支持UFW、firewalld和iptables
  5. 文件系统安全

    • 设置正确的文件和目录权限
    • 保护关键系统文件
    • 限制SUID/SGID程序
  6. 内核加固

    • 防止IP欺骗
    • 防止SYN洪水攻击
    • 禁用ICMP重定向
  7. 服务管理

    • 禁用不必要的网络服务
    • 减少系统攻击面
  8. 审计和日志

    • 配置auditd进行详细系统监控
    • 设置日志轮转策略
    • 监控关键系统文件更改
  9. 恶意软件防护

    • 安装rootkit检测工具
    • 配置防病毒扫描
    • 设置定期扫描任务

使用建议

  1. 测试环境验证:先在非生产环境测试脚本
  2. 定制化修改:根据具体发行版和需求调整
  3. 备份配置:脚本会自动备份关键配置文件
  4. 定期运行:建议定期执行安全检查
  5. 日志审查:检查生成的日志文件以验证更改

您可以根据具体需求扩展或修改此脚本,添加更多安全措施或调整现有参数。