#!/bin/bash set -euo pipefail # ================================================================= # Gitleaks 极致深度审计脚本 (修复输出混乱版) # ================================================================= REPORT_DIR="./gitleaks_deep_reports" TEMP_DIR="/tmp/gitleaks_audit" mkdir -p "$REPORT_DIR" "$TEMP_DIR" # 1. 安装 Gitleaks install_gitleaks() { if command -v gitleaks &> /dev/null; then echo "[!] Gitleaks 已安装,跳过下载。" return fi echo "[*] 未检测到 Gitleaks,开始自动安装..." ARCH=$(uname -m) case "$ARCH" in x86_64) GARCH="x64" ;; aarch64) GARCH="arm64" ;; *) echo "[-] 不支持的架构: $ARCH"; exit 1 ;; esac LATEST_URL=$(curl -s https://api.github.com/repos/gitleaks/gitleaks/releases/latest | \ grep "browser_download_url" | grep "linux_${GARCH}.tar.gz" | cut -d '"' -f 4) [ -z "$LATEST_URL" ] && { echo "[-] 无法获取下载链接"; exit 1; } curl -L "$LATEST_URL" -o "$TEMP_DIR/gitleaks.tar.gz" tar -xzf "$TEMP_DIR/gitleaks.tar.gz" -C "$TEMP_DIR" chmod +x "$TEMP_DIR/gitleaks" export PATH="$TEMP_DIR:$PATH" echo "[+] Gitleaks 安装成功: $(gitleaks version)" } install_gitleaks # 2. 扫描参数(禁用颜色,使用默认配置) LEAKS_OPTS="--no-color --max-archive-depth 100 --max-decode-depth 100 -v" # 3. 合并扫描路径 STATIC_PATHS=("/tmp" "/root" "/etc" "/var/log" "/var/spool/mail" "/opt" "/var/www" "/home") MOUNT_PATHS=$(df -h | grep -E '^/dev/|^[^ ]+:' | awk '{print $6}' | grep -vE '^/($|/boot|/dev|/sys|/proc)' || true) ALL_TARGETS=$(printf "%s\n" "${STATIC_PATHS[@]}" "$MOUNT_PATHS" | sort -u) for target in $ALL_TARGETS; do if [ -d "$target" ] || [ -f "$target" ]; then echo ">>> 深度扫描: $target" safe_name=$(echo "$target" | tr '/' '_') # 详细输出重定向到日志文件,终端只显示进度 gitleaks dir "$target" $LEAKS_OPTS \ --report-path "$REPORT_DIR/report_${safe_name}.json" \ > "$REPORT_DIR/log_${safe_name}.txt" 2>&1 fi done # 4. 环境变量 echo ">>> 分析系统环境变量" env > "$TEMP_DIR/env_dump.txt" gitleaks dir "$TEMP_DIR/env_dump.txt" $LEAKS_OPTS \ --report-path "$REPORT_DIR/report_env.json" >/dev/null 2>&1 # 5. Shell 历史 echo ">>> 扫描 Shell 历史记录" find /home /root -maxdepth 2 -name ".*history" 2>/dev/null | while read -r hist; do safe_hist=$(echo "$hist" | tr '/' '_') gitleaks dir "$hist" $LEAKS_OPTS \ --report-path "$REPORT_DIR/hist_${safe_hist}.json" >/dev/null 2>&1 done # 6. 进程环境变量 echo ">>> 扫描活跃进程环境变量" for pid_dir in /proc/[0-9]*; do pid=$(basename "$pid_dir") if [ -f "$pid_dir/environ" ]; then cat "$pid_dir/environ" | tr '\0' '\n' > "$TEMP_DIR/env_$pid.txt" 2>/dev/null if [ -s "$TEMP_DIR/env_$pid.txt" ]; then gitleaks detect --source "$TEMP_DIR/env_$pid.txt" --no-git $LEAKS_OPTS \ --report-path "$REPORT_DIR/proc_env_$pid.json" >/dev/null 2>&1 fi rm -f "$TEMP_DIR/env_$pid.txt" fi done # 7. 清理 rm -rf "$TEMP_DIR" echo "深度审计完成!报告目录: $REPORT_DIR"