#!/bin/bash
echo "===== 麒麟系统勒索防护配置检查 ====="
echo "提示：部分检查需要root权限，建议使用sudo执行"
echo
# 权限检查函数
check_root() {
    if [ "$EUID" -ne 0 ]; then
        echo "[警告] 当前未使用root权限，部分检查受限"
        return 1
    fi
    return 0
}
# 通用配置检查函数
check_config_param() {
    local file=$1
    local param=$2
    local expect=$3
    local desc=${4:-$param}
    value=$(grep "^$param" "$file" 2>/dev/null | tail -1 | awk '{print $2}')
    if [ "$value" = "$expect" ]; then
        echo "[通过] $desc 已正确配置: $param=$value"
    else
        echo "[警告] $desc 配置不符: 当前值=$value | 建议值=$expect"
    fi
}
#--------- 基础安全配置检查 ---------#
echo "------ 密码策略检查 ------"
# 密码复杂度检查
pwquality_conf="/etc/security/pwquality.conf"
check_config_param "$pwquality_conf" "minlen" "8" "密码最小长度"
check_config_param "$pwquality_conf" "minclass" "3" "字符类别数"
check_config_param "$pwquality_conf" "dictcheck" "1" "字典检查"
# 失效策略检查
login_defs="/etc/login.defs"
check_config_param "$login_defs" "PASS_MAX_DAYS" "90" "密码最长有效期"
check_config_param "$login_defs" "PASS_WARN_AGE" "3" "过期提醒天数"
# 账户锁定策略（PAM策略）
pam_files=("/etc/pam.d/common-auth" "/etc/pam.d/system-auth")
for pam_file in "${pam_files[@]}"; do
    if [ -f "$pam_file" ]; then
        if grep -q "pam_faillock.*deny=5" "$pam_file"; then
            echo "[通过] 账户锁定策略在 $pam_file 中生效"
        else
            echo "[警告] $pam_file 中未配置登录失败锁定策略"
        fi
    fi
done
#--------- SSH服务检查 ---------#
echo
echo "------ SSH安全配置检查 ------"
sshd_conf="/etc/ssh/sshd_config"
check_config_param "$sshd_conf" "Port" "2217" "SSH端口"
check_config_param "$sshd_conf" "PermitRootLogin" "no" "Root登录限制"
check_config_param "$sshd_conf" "PasswordAuthentication" "no" "密码登录限制"
check_config_param "$sshd_conf" "AllowUsers" "admin01" "用户白名单"
#--------- 服务管控检查 ---------#
echo
echo "------ 系统服务检查 ------"
danger_services=("telnet" "rlogin" "rexec" "nfs" "ftp" "tftp")
for service in "${danger_services[@]}"; do
    if systemctl is-active --quiet "$service"; then
        echo "[高危] 风险服务运行中: $service"
    else
        echo "[正常] 服务已禁用: $service" 
    fi
done
#--------- 文件权限检查 ---------#
echo
echo "------ 关键文件权限检查 ------"
declare -A file_list=(
    ["/etc/passwd"]="644"
    ["/etc/shadow"]="600" 
    ["/etc/group"]="644"
)
for file in "${!file_list[@]}"; do
    perm=$(stat -c %a "$file" 2>/dev/null)
    if [ "$perm" != "${file_list[$file]}" ]; then
        echo "[警告] 文件权限异常: $file 当前权限: $perm"
    else
        echo "[正常] 文件权限正常: $file"
    fi
done
#--------- Kysec安全管控检查 ---------#
echo
echo "------ Kysec安全检查 ------"
if command -v getstatus &> /dev/null; then
    kysec_status=$(getstatus 2>&1)
    if [[ $kysec_status == *"enabled"* ]]; then
        echo "[通过] Kysec安全机制已启用"
    else
        echo "[高危] Kysec安全机制未启用"
    fi
else
    echo "[警告] Kysec组件未安装"
fi
#--------- 总结报告 ---------#
echo
echo "===== 检查完成 ====="
echo "请根据提示处理[警告]和[高危]项"
echo "完整加固方案参考《麒麟软件操作系统勒索病毒防护指引》"
