#!/bin/bash

# 备份原配置文件
backup_file() {
    if [ -f "/etc/pam.d/system-auth" ]; then
        cp /etc/pam.d/system-auth /etc/pam.d/system-auth.bak.$(date +%Y%m%d%H%M%S)
        echo "已备份原文件: /etc/pam.d/system-auth.bak.$(date +%Y%m%d%H%M%S)"
    else
        echo "错误: /etc/pam.d/system-auth 文件不存在"
        exit 1
    fi
}

# 检查并安装pam_pwquality模块
check_pam_module() {
    if ! rpm -q pam 1>/dev/null 2>&1; then
        echo "安装pam模块..."
        yum install -y pam 2>/dev/null || apt-get install -y libpam-modules 2>/dev/null
    fi
}

# 修改密码复杂度策略
set_password_policy() {
    local config_line="password requisite pam_pwquality.so try_first_pass local_users_only retry=5 minlen=12 ucredit=-1 lcredit=-1 dcredit=-1 ocredit=-1 enforce_for_root"
    
    # 删除现有的pam_pwquality配置（如果存在）
    sed -i '/pam_pwquality\.so/d' /etc/pam.d/system-auth
    
    # 在password开头的行之后插入新配置
    sed -i '/^password[[:space:]]*requisite[[:space:]]*pam_pwquality\.so/!{/^password[[:space:]]*/{s/^password[[:space:]].*/'"$config_line"'\n&/;:a;n;ba}}' /etc/pam.d/system-auth
    
    # 如果没有找到password行，添加到文件末尾
    if ! grep -q "pam_pwquality.so" /etc/pam.d/system-auth; then
        echo "$config_line" >> /etc/pam.d/system-auth
    fi
    
    echo "密码复杂度策略已设置: 最小12位，包含大小写字母、数字、特殊字符"
}

# 设置登录失败锁定策略
set_login_lockout() {
    local auth_config="auth required pam_faillock.so preauth silent audit deny=5 unlock_time=1800"
    local account_config="account required pam_faillock.so"
    
    # 删除现有的pam_faillock配置
    sed -i '/pam_faillock\.so/d' /etc/pam.d/system-auth
    
    # 在auth section添加配置
    sed -i '/^auth[[:space:]]*required[[:space:]]*pam_env\.so/a '"$auth_config" /etc/pam.d/system-auth
    
    # 在account section添加配置
    sed -i '/^account[[:space:]]*required[[:space:]]*pam_unix\.so/i '"$account_config" /etc/pam.d/system-auth
    
    # 可选：创建faillock目录（某些系统需要）
    mkdir -p /var/run/faillock
    
    echo "登录失败锁定策略已设置: 失败5次锁定30分钟"
}

# 验证配置
verify_config() {
    echo "=== 验证当前配置 ==="
    echo "1. 密码策略:"
    grep -E "pam_pwquality|minlen|credit" /etc/pam.d/system-auth || echo "未找到密码策略配置"
    
    echo -e "\n2. 登录锁定策略:"
    grep -E "pam_faillock|deny=|unlock_time" /etc/pam.d/system-auth || echo "未找到登录锁定配置"
    
    echo -e "\n3. 完整的相关配置:"
    grep -A2 -B2 -E "pam_pwquality|pam_faillock" /etc/pam.d/system-auth
}

# 显示策略说明
show_policy() {
    echo "=== 策略说明 ==="
    echo "密码复杂度要求:"
    echo "  - 最小长度: 12 字符"
    echo "  - 至少包含: 1个大写字母(ucredit=-1)"
    echo "  - 至少包含: 1个小写字母(lcredit=-1)" 
    echo "  - 至少包含: 1个数字(dcredit=-1)"
    echo "  - 至少包含: 1个特殊字符(ocredit=-1)"
    echo "  - 最大重试次数: 5次"
    echo ""
    echo "登录安全策略:"
    echo "  - 连续失败次数: 5次"
    echo "  - 锁定时间: 1800秒(30分钟)"
    echo "  - 对root用户同样生效"
}

# 主函数
main() {
    echo "开始设置系统密码和登录安全策略..."
    
    # 检查root权限
    if [ "$EUID" -ne 0 ]; then
        echo "错误: 需要root权限执行此脚本"
        echo "请使用: sudo $0 或切换到root用户"
        exit 1
    fi
    
    # 执行各步骤
    backup_file
    check_pam_module
    set_password_policy
    set_login_lockout
    verify_config
    show_policy
    
    echo -e "\n=== 设置完成 ==="
    echo "注意: 新策略将在下次认证时生效"
    echo "建议测试配置是否正确，避免被锁定"
}

# 执行主函数
main "$@"
