#!/bin/bash
#
# audit-ima.sh
#
# Scan every AM·OS package (.txz/.tgz/.tbz/.tlz) under a directory,
# extract each in turn with xattr support, and report on the IMA signing
# status of every target file it contains (executables, scripts, .so, .ko).
#
# A package is clean if every target file it ships carries a security.ima
# xattr. With --verify, the signature must also verify against the given
# IMA public cert.
#
# Usage:
#   audit-ima.sh [OPTIONS] [PACKAGE_DIR]
#
# Options:
#   -c, --cert PATH     IMA cert to verify against
#                       (default: /etc/keys/x509_ima.der)
#   -w, --workdir PATH  Where to extract packages
#                       (default: a fresh mktemp -d)
#   -v, --verify        Verify each signature with evmctl (slower)
#   -V, --verbose       Print a line for every package, not just failures
#   -q, --quiet         Print only the final summary
#   -l, --list          Print only the paths of unsigned target files
#   -h, --help          Show this help
#
# Exit status:
#   0   every target file in every package is signed (and verified if --verify)
#   1   one or more packages have unsigned or unverified target files
#   2   usage error, missing tool, or environment problem
#

set -u

PKG_DIR="/repo/amos64"
IMA_CERT="/etc/keys/x509_ima.der"
WORK_DIR=""
VERIFY=0
VERBOSE=0
QUIET=0
LIST_ONLY=0

usage() {
    sed -n '2,/^$/p' "$0" | sed 's/^# \{0,1\}//'
    exit 0
}

# ---- Option parsing ------------------------------------------------------
while [ $# -gt 0 ]; do
    case "$1" in
        -c|--cert)     IMA_CERT="$2" ; shift 2 ;;
        -w|--workdir)  WORK_DIR="$2" ; shift 2 ;;
        -v|--verify)   VERIFY=1      ; shift 1 ;;
        -V|--verbose)  VERBOSE=1     ; shift 1 ;;
        -q|--quiet)    QUIET=1       ; shift 1 ;;
        -l|--list)     LIST_ONLY=1 ; QUIET=1 ; shift 1 ;;
        -h|--help)     usage ;;
        -*)            echo "Unknown option: $1" >&2 ; usage >&2 ; exit 2 ;;
        *)             PKG_DIR="$1"  ; shift 1 ;;
    esac
done

# ---- Environment checks --------------------------------------------------
[ "$(id -u)" -eq 0 ] || {
    echo "ERROR: must run as root (tar --xattrs needs CAP_SYS_ADMIN)" >&2
    exit 2
}

[ -d "$PKG_DIR" ] || {
    echo "ERROR: package directory not found: $PKG_DIR" >&2
    exit 2
}

command -v getfattr >/dev/null 2>&1 || {
    echo "ERROR: getfattr not found (install the 'attr' package)" >&2
    exit 2
}

if [ "$VERIFY" = 1 ]; then
    command -v evmctl >/dev/null 2>&1 || {
        echo "ERROR: evmctl not found (needed for --verify)" >&2
        exit 2
    }
    [ -r "$IMA_CERT" ] || {
        echo "ERROR: IMA cert not readable: $IMA_CERT" >&2
        exit 2
    }
fi

# ---- Working directory and cleanup ---------------------------------------
if [ -z "$WORK_DIR" ]; then
    WORK_DIR=$(mktemp -d /tmp/ima-audit.XXXXXX) || exit 2
    CLEANUP_WORKDIR=1
else
    mkdir -p "$WORK_DIR" || exit 2
    CLEANUP_WORKDIR=0
fi

cleanup() {
    if [ "$CLEANUP_WORKDIR" = 1 ] && [ -n "$WORK_DIR" ] && [ -d "$WORK_DIR" ]; then
        rm -rf "$WORK_DIR"
    fi
    # Clear the progress line if we printed one
    [ -t 2 ] && printf '\r\033[K' >&2
}
trap cleanup EXIT

# ---- Progress helper -----------------------------------------------------
progress() {
    [ -t 2 ] || return 0
    [ "$QUIET" = 1 ] && return 0
    [ "$VERBOSE" = 1 ] && return 0
    [ "$LIST_ONLY" = 1 ] && return 0
    printf '\r\033[K%s' "$1" >&2
}

clear_progress() {
    [ -t 2 ] && printf '\r\033[K' >&2
}

# ---- Count packages for the progress indicator ---------------------------
TOTAL_PKGS=$(find "$PKG_DIR" -type f -name '*.t[gblx]z' 2>/dev/null | wc -l)
if [ "$TOTAL_PKGS" = 0 ]; then
    echo "No packages found under $PKG_DIR" >&2
    exit 2
fi

# ---- Counters ------------------------------------------------------------
OK_PKGS=0
NOFILE_PKGS=0
FAIL_PKGS=0
BAD_PKGS=0

TOTAL_FILES=0
TOTAL_SIGNED=0
TOTAL_UNSIGNED=0
TOTAL_VERIFY_FAILED=0

declare -a FAIL_LIST=()
declare -a BAD_LIST=()

IDX=0

# ---- Main loop -----------------------------------------------------------
while IFS= read -r -d '' txz; do
    IDX=$((IDX + 1))
    rel="${txz#$PKG_DIR/}"
    name=$(basename "$txz")

    progress "[$IDX/$TOTAL_PKGS] $rel"

    extract_dir="$WORK_DIR/pkg.$$.$IDX"
    rm -rf "$extract_dir"
    mkdir -p "$extract_dir" || {
        BAD_PKGS=$((BAD_PKGS + 1))
        BAD_LIST+=("$rel (cannot create scratch dir)")
        continue
    }

    # Extract with xattr preservation.
    if ! tar --xattrs --xattrs-include='security.*' \
             --no-same-owner \
             -xf "$txz" -C "$extract_dir" 2>/dev/null ; then
        BAD_PKGS=$((BAD_PKGS + 1))
        BAD_LIST+=("$rel (extraction failed)")
        rm -rf "$extract_dir"
        continue
    fi

    pkg_files=0
    pkg_signed=0
    pkg_verified=0
    pkg_verify_failed=0

    declare -a pkg_unsigned=()

    while IFS= read -r -d '' f; do
        # Match the new makepkg logic: executables, .so, .so.*, .ko
        if [ ! -x "$f" ] && [[ "$f" != *.so ]] && [[ "$f" != *.so.* ]] && [[ "$f" != *.ko ]]; then
            continue
        fi
        
        pkg_files=$((pkg_files + 1))

        # xattr check.
        if getfattr -d -m 'security\.ima' "$f" 2>/dev/null \
                | grep -q '^security\.ima=' ; then
            pkg_signed=$((pkg_signed + 1))

            if [ "$VERIFY" = 1 ]; then
                if evmctl ima_verify --key "$IMA_CERT" "$f" >/dev/null 2>&1 ; then
                    pkg_verified=$((pkg_verified + 1))
                else
                    pkg_verify_failed=$((pkg_verify_failed + 1))
                fi
            fi
        else
            pkg_unsigned+=("${f#$extract_dir/}")
        fi
    done < <(find "$extract_dir" -type f -print0)

    TOTAL_FILES=$((TOTAL_FILES + pkg_files))
    TOTAL_SIGNED=$((TOTAL_SIGNED + pkg_signed))
    TOTAL_UNSIGNED=$((TOTAL_UNSIGNED + ${#pkg_unsigned[@]}))
    TOTAL_VERIFY_FAILED=$((TOTAL_VERIFY_FAILED + pkg_verify_failed))

    # ---- Classify -------------------------------------------------------
    if [ "$pkg_files" -eq 0 ]; then
        NOFILE_PKGS=$((NOFILE_PKGS + 1))
        if [ "$VERBOSE" = 1 ] && [ "$QUIET" = 0 ] && [ "$LIST_ONLY" = 0 ]; then
            clear_progress
            printf '[NONE] %s   (no executable/script/library files)\n' "$rel"
        fi
    elif [ "$pkg_signed" -eq "$pkg_files" ] && [ "$pkg_verify_failed" -eq 0 ]; then
        OK_PKGS=$((OK_PKGS + 1))
        if [ "$VERBOSE" = 1 ] && [ "$QUIET" = 0 ] && [ "$LIST_ONLY" = 0 ]; then
            clear_progress
            if [ "$VERIFY" = 1 ]; then
                printf '[OK  ] %s   Files=%d signed=%d verified=%d\n' \
                    "$rel" "$pkg_files" "$pkg_signed" "$pkg_verified"
            else
                printf '[OK  ] %s   Files=%d signed=%d\n' \
                    "$rel" "$pkg_files" "$pkg_signed"
            fi
        fi
    else
        FAIL_PKGS=$((FAIL_PKGS + 1))
        FAIL_LIST+=("$rel")

        if [ "$LIST_ONLY" = 1 ]; then
            clear_progress
            for u in "${pkg_unsigned[@]}"; do
                printf '%s  %s\n' "$rel" "$u"
            done
        else
            clear_progress
            if [ "$VERIFY" = 1 ]; then
                printf '[FAIL] %s   Files=%d signed=%d unsigned=%d verifyfail=%d\n' \
                    "$rel" "$pkg_files" "$pkg_signed" \
                    "${#pkg_unsigned[@]}" "$pkg_verify_failed"
            else
                printf '[FAIL] %s   Files=%d signed=%d unsigned=%d\n' \
                    "$rel" "$pkg_files" "$pkg_signed" "${#pkg_unsigned[@]}"
            fi
            if [ "$VERBOSE" = 1 ]; then
                for u in "${pkg_unsigned[@]}"; do
                    printf '         unsigned: %s\n' "$u"
                done
            fi
        fi
    fi

    rm -rf "$extract_dir"
done < <(find "$PKG_DIR" -type f -name '*.t[gblx]z' -print0 | sort -z)

clear_progress

# ---- Summary -------------------------------------------------------------
if [ "$LIST_ONLY" = 0 ]; then
    echo
    echo "==================================================================="
    echo " IMA audit summary"
    echo "==================================================================="
    printf ' Package directory:  %s\n' "$PKG_DIR"
    printf ' Packages scanned:   %d\n' "$TOTAL_PKGS"
    printf '   clean:            %d\n' "$OK_PKGS"
    printf '   no targets:       %d\n' "$NOFILE_PKGS"
    printf '   with problems:    %d\n' "$FAIL_PKGS"
    printf '   unreadable:       %d\n' "$BAD_PKGS"
    echo
    printf ' Target files found: %d\n' "$TOTAL_FILES"
    printf '   signed:           %d\n' "$TOTAL_SIGNED"
    printf '   unsigned:         %d\n' "$TOTAL_UNSIGNED"
    if [ "$VERIFY" = 1 ]; then
        printf '   verify failed:    %d\n' "$TOTAL_VERIFY_FAILED"
    fi
    echo "==================================================================="
fi

# ---- Detailed failure list -----------------------------------------------
if [ "$FAIL_PKGS" -gt 0 ] && [ "$LIST_ONLY" = 0 ]; then
    echo
    echo "Packages with unsigned or unverified target files:"
    for rel in "${FAIL_LIST[@]}"; do
        printf '  %s\n' "$rel"
    done
fi

if [ "$BAD_PKGS" -gt 0 ] && [ "$LIST_ONLY" = 0 ]; then
    echo
    echo "Packages that could not be scanned:"
    for rel in "${BAD_LIST[@]}"; do
        printf '  %s\n' "$rel"
    done
fi

# ---- Exit status ---------------------------------------------------------
if [ "$FAIL_PKGS" -gt 0 ] || [ "$BAD_PKGS" -gt 0 ]; then
    exit 1
fi
exit 0