#!/bin/bash
# imaaudit - Audit target files for valid security.ima signatures
# Target files: executables, scripts, *.so, *.so.*, *.ko
# Requires: root, getfattr, find, ima-evm-utils (evmctl)

# Default configuration
EXCLUDE_USER=""

# Parse arguments
while [ $# -gt 0 ]; do
    case "$1" in
        -e|--exclude-user)
            EXCLUDE_USER="$2"
            shift 2
            ;;
        --ghostnet)
            EXCLUDE_USER="annode"
            shift 1
            ;;
        -h|--help)
            echo "Usage: $0 [OPTIONS]"
            echo "Options:"
            echo "  -e, --exclude-user USER   Exclude files owned by this user from the scan"
            echo "  --ghostnet                Preset to exclude the 'annode' user (Ghostnet edition)"
            echo "  -h, --help                Show this help"
            exit 0
            ;;
        *)
            echo "Unknown option: $1"
            exit 1
            ;;
    esac
done

# Ensure script is run as root
if [ "$EUID" -ne 0 ]; then
  echo -e "\e[31mError:\e[0m This script must be run as root to read security.ima attributes."
  exit 1
fi

# Check for required tools
if ! command -v evmctl >/dev/null 2>&1; then
  echo -e "\e[31mError:\e[0m evmctl (ima-evm-utils) is not installed. Cannot verify signatures."
  exit 1
fi
if [ ! -r /etc/keys/x509_ima.der ]; then
  echo -e "\e[31mError:\e[0m Public certificate /etc/keys/x509_ima.der not found."
  exit 1
fi
if ! command -v getfattr >/dev/null 2>&1; then
  echo -e "\e[31mError:\e[0m getfattr is not installed. Cannot read extended attributes."
  exit 1
fi

# Color definitions
C_RESET=$'\e[0m'
C_GREEN=$'\e[32m'
C_RED=$'\e[31m'
C_YELLOW=$'\e[33m'
C_CYAN=$'\e[36m'
C_BOLD=$'\e[1m'

echo -e "${C_BOLD}${C_CYAN}=== IMA Appraisal Audit ===${C_RESET}"
if [ -n "$EXCLUDE_USER" ]; then
    echo -e "Excluding files owned by: ${C_YELLOW}${EXCLUDE_USER}${C_RESET}"
fi
echo -e "Scanning root filesystem for executables, scripts, libraries, and modules..."
echo -e "Verifying signatures against /etc/keys/x509_ima.der\n"

missing=0
invalid=0
valid=0
scanned=0
target_count=0
spinner=("|" "/" "-" "\\")
idx=0

# Build the find command arguments dynamically.
# We ignore the package manager's backups, metadata, and .bak files.
FIND_ARGS=(
    "/" "-xdev" "-type" "f"
    "!" "-path" "/var/log/pkgtools/*"
    "!" "-path" "/var/lib/pkgtools/*"
    "!" "-path" "/etc/ld.so.cache"
    "!" "-path" "/etc/ld.so.conf"
    "!" "-name" "*.bak"
    "!" "-name" "*.new"
    "(" "-perm" "-u+x" "-o" "-name" "*.so" "-o" "-name" "*.so.*" "-o" "-name" "*.ko" ")"
)

if [ -n "$EXCLUDE_USER" ]; then
    FIND_ARGS+=("!" "-user" "$EXCLUDE_USER")
fi

# Use process substitution to keep variables in the current shell
while IFS= read -r -d '' file; do
    ((scanned++))
    
    ((target_count++))
    
    # 1. Check for the presence of the security.ima extended attribute
    if ! getfattr -m security.ima "$file" 2>/dev/null | grep -q "security.ima"; then
        ((missing++))
        echo -e "${C_RED}MISSING ATTR:${C_RESET} $file"
    else
        # 2. The attribute exists, now verify the cryptographic signature
        if evmctl ima_verify -k /etc/keys/x509_ima.der "$file" >/dev/null 2>&1; then
            ((valid++))
        else
            ((invalid++))
            echo -e "${C_RED}INVALID SIG:${C_RESET} $file"
        fi
    fi
    
    # Update progress spinner every 150 files scanned
    if (( scanned % 150 == 0 )); then
        printf "\r${C_YELLOW}[%s] Scanned: %d | Targets: %d | Valid: %d | Bad: %d${C_RESET}" \
            "${spinner[$idx]}" "$scanned" "$target_count" "$valid" "$((missing + invalid))"
        idx=$(( (idx + 1) % 4 ))
    fi
done < <(find "${FIND_ARGS[@]}" -print0 2>/dev/null)

# Clear the spinner line before printing final results
printf "\r\033[K"

echo -e "\n${C_BOLD}${C_CYAN}=== Audit Summary ===${C_RESET}"
echo -e "Total files scanned:       $scanned"
echo -e "Target files found:        $target_count"
echo -e "Valid signatures:          ${C_GREEN}$valid${C_RESET}"

if [ "$missing" -gt 0 ] || [ "$invalid" -gt 0 ]; then
    [ "$missing" -gt 0 ] && echo -e "Missing attributes:        ${C_RED}$missing${C_RESET}"
    [ "$invalid" -gt 0 ] && echo -e "Invalid signatures:        ${C_RED}$invalid${C_RESET}"
    echo -e "\n${C_RED}${C_BOLD}❌ FAILED: $((missing + invalid)) target file(s) failed IMA validation.${C_RESET}"
    exit 1
else
    echo -e "\n${C_GREEN}${C_BOLD}✅ OK: All $target_count target files have valid security.ima signatures.${C_RESET}"
    exit 0
fi