#!/bin/bash
# Report whether this boot meets the Easy Anti-Cheat Linux v2 requirements.
# It changes nothing. Adapted from ublue-os/bazzite pull 6065
# (96-bazzite-anticheat.just). Hints name the AtropOS boot command line.
# They do not call rpm-ostree, and they do not set lsm=.
#
# SPDX-License-Identifier: Apache-2.0
# SPDX-FileCopyrightText: 2026 tedohayer
# SPDX-FileCopyrightText: 2026 ahjolinna <ahjolinna@yahoo.com>

set -uo pipefail

# Requirements, and the signing keys EAC Linux v2 treats as well-known:
# https://onlineservices.epicgames.com/news/introducing-easy-anti-cheat-linux-v2
REQUIREMENTS_URL="https://onlineservices.epicgames.com/news/introducing-easy-anti-cheat-linux-v2"
WELL_KNOWN_KEYS='Canonical Ltd\. Master Certificate Authority|Fedora Secure Boot CA|Universal Blue|Debian Secure Boot CA|openSUSE Secure Boot CA|SUSE Linux Enterprise Secure Boot CA|Rocky Linux Secure Boot Root CA|Microsoft (Corporation )?UEFI CA|AlmaLinux Secure Boot CA'

if [[ -t 1 ]]; then
    green=$'\033[32m'
    red=$'\033[31m'
    bold=$'\033[1m'
    normal=$'\033[0m'
else
    green=""
    red=""
    bold=""
    normal=""
fi

PASSED=0
FAILED=0
pass() {
    printf '%s[PASS]%s %s\n' "${green}${bold}" "${normal}" "$1"
    [[ -n ${2:-} ]] && printf '       %s\n' "$2"
    PASSED=$((PASSED + 1))
}
fail() {
    printf '%s[FAIL]%s %s\n' "${red}${bold}" "${normal}" "$1"
    [[ -n ${2:-} ]] && printf '       %s\n' "$2"
    FAILED=$((FAILED + 1))
}

CMDLINE=()
read -ra CMDLINE < /proc/cmdline
has_karg() {
    local arg
    for arg in "${CMDLINE[@]}"; do
        [[ $arg == "$1" ]] && return 0
    done
    return 1
}

SYS_VENDOR=$(cat /sys/class/dmi/id/sys_vendor 2>/dev/null || true)
CHASSIS=$(cat /sys/class/dmi/id/chassis_type 2>/dev/null || true)
HANDHELD=0
# SMBIOS chassis types 30-32 are tablet, convertible and detachable.
[[ $SYS_VENDOR == Valve || $CHASSIS =~ ^3[012]$ ]] && HANDHELD=1

echo "${bold}Easy Anti-Cheat Linux v2 readiness check${normal}"
echo "Requirements: ${REQUIREMENTS_URL}"
echo

# 1. Signed kernel and kernel modules.
KERNEL=""
for candidate in "/usr/lib/modules/$(uname -r)/vmlinuz" "/boot/vmlinuz-$(uname -r)"; do
    if [[ -r $candidate ]]; then
        KERNEL=$candidate
        break
    fi
done
if [[ -z $KERNEL ]]; then
    fail "Signed kernel" "Couldn't read the running kernel image for $(uname -r)"
elif ! command -v sbverify >/dev/null 2>&1; then
    fail "Signed kernel" "sbverify is not installed (package sbsigntools)"
elif ! SIGNERS=$(sbverify --list "$KERNEL" 2>&1); then
    fail "Signed kernel" "Couldn't read the kernel's signatures (sbverify says: ${SIGNERS//$'\n'/ })"
else
    SIGNER_CN=$(sed -n 's|^ *- subject: .*/CN=\([^/]*\).*|\1|p' <<<"$SIGNERS" | head -n1)
    if ! grep -q 'subject:' <<<"$SIGNERS"; then
        fail "Signed kernel" "Kernel $(uname -r) is not signed"
    elif grep -Eq "$WELL_KNOWN_KEYS" <<<"$SIGNERS"; then
        pass "Signed kernel" "Kernel $(uname -r) is signed by '${SIGNER_CN}'"
    else
        fail "Signed kernel" "Kernel $(uname -r) is signed by '${SIGNER_CN}', which is not a well-known key"
    fi
fi

UNSIGNED=()
MODULES=0
while read -r mod _; do
    [[ -n $mod ]] || continue
    MODULES=$((MODULES + 1))
    [[ $(cat "/sys/module/$mod/taint" 2>/dev/null || true) == *E* ]] && UNSIGNED+=("$mod")
done < /proc/modules
TAINTED=$(cat /proc/sys/kernel/tainted 2>/dev/null || echo 0)
if (( ${#UNSIGNED[@]} )); then
    fail "Signed kernel modules" "Unsigned modules loaded: ${UNSIGNED[*]}"
elif (( TAINTED & 8192 )); then
    fail "Signed kernel modules" "An unsigned module was loaded during this boot (reboot to clear)"
else
    pass "Signed kernel modules" "All ${MODULES} loaded modules are signed"
fi

# 2. TPM 2.0
if [[ $(cat /sys/class/tpm/tpm0/tpm_version_major 2>/dev/null || true) == 2 ]]; then
    pass "TPM 2.0"
elif [[ -e /sys/class/tpm/tpm0 ]]; then
    fail "TPM 2.0" "Found a TPM, but it isn't version 2.0"
else
    fail "TPM 2.0" "No TPM found. Enable it in the firmware (often called fTPM, PTT or Security Device)"
fi

# 3. Secure Boot, and only well-known Machine Owner Keys.
if ! command -v mokutil >/dev/null 2>&1; then
    fail "Secure Boot enabled" "mokutil is not installed"
    fail "Only well-known Machine Owner Keys" "mokutil is not installed"
else
    SB_STATE=$(mokutil --sb-state 2>&1 || true)
    if [[ $SB_STATE == *"SecureBoot enabled"* && $SB_STATE != *"validation is disabled"* ]]; then
        pass "Secure Boot enabled"
    else
        fail "Secure Boot enabled" "Enable Secure Boot in the firmware (mokutil says: ${SB_STATE//$'\n'/ })"
    fi

    MOK_DIR=$(mktemp -d)
    trap 'rm -rf "$MOK_DIR"' EXIT
    MOK_ERR=$(cd "$MOK_DIR" && mokutil --export 2>&1 >/dev/null)
    MOK_STATUS=$?
    UNKNOWN_MOKS=()
    for der in "$MOK_DIR"/MOK-*.der; do
        [[ -e $der ]] || continue
        CERT=$(openssl x509 -inform DER -in "$der" -noout -subject -issuer 2>/dev/null || true)
        if ! grep -Eq "$WELL_KNOWN_KEYS" <<<"$CERT"; then
            CN=$(sed -n 's/^subject=.*CN *= *\([^,]*\).*/\1/p' <<<"$CERT")
            UNKNOWN_MOKS+=("'${CN:-unknown}'")
        fi
    done
    if (( MOK_STATUS )); then
        fail "Only well-known Machine Owner Keys" "Couldn't read the enrolled keys (mokutil says: ${MOK_ERR//$'\n'/ }). Run this as root."
    elif (( ${#UNKNOWN_MOKS[@]} )); then
        fail "Only well-known Machine Owner Keys" "Not well-known: ${UNKNOWN_MOKS[*]}. Export them with 'mokutil --export', then remove each with 'sudo mokutil --delete MOK-000N.der'"
    else
        pass "Only well-known Machine Owner Keys"
    fi
fi

# 4. Measured boot. systemd-boot records PCR 11 and 12.
EVENT_LOG=/sys/kernel/security/tpm0/binary_bios_measurements
if [[ ! -e $EVENT_LOG ]]; then
    fail "Measured boot" "No TPM boot measurements found"
elif [[ ! -r $EVENT_LOG ]]; then
    fail "Measured boot" "The TPM boot log is not readable. Run atropos-check eac as root."
elif ! command -v tpm2_eventlog >/dev/null 2>&1; then
    fail "Measured boot" "tpm2_eventlog is not installed (package tpm2.0-tools)"
elif ! PCRS=$(tpm2_eventlog "$EVENT_LOG" 2>/dev/null); then
    fail "Measured boot" "Couldn't read the TPM boot log"
elif grep -Eq '^[[:space:]]*PCRIndex: (8|9|11|12)$' <<<"$PCRS"; then
    pass "Measured boot" "The boot manager recorded its measurements"
else
    fail "Measured boot" "The firmware measured the boot, but the boot manager didn't"
fi

# 5. IOMMU on, passthrough off. Handhelds are exempt.
PASSTHROUGH=""
for arg in iommu=pt iommu=off iommu.passthrough=1 amd_iommu=pt amd_iommu=off intel_iommu=off; do
    has_karg "$arg" && PASSTHROUGH="$arg"
done
CONFIG="/usr/lib/modules/$(uname -r)/config"
if [[ -z $PASSTHROUGH ]] && ! has_karg iommu.passthrough=0 &&
    [[ -r $CONFIG ]] && grep -q '^CONFIG_IOMMU_DEFAULT_PASSTHROUGH=y' "$CONFIG"; then
    PASSTHROUGH="the kernel's default"
fi
if compgen -G '/sys/class/iommu/*' >/dev/null && [[ -z $PASSTHROUGH ]]; then
    pass "IOMMU enabled, passthrough disabled"
elif (( HANDHELD )); then
    pass "IOMMU enabled, passthrough disabled" "Not required on handheld devices"
elif [[ -n $PASSTHROUGH ]]; then
    fail "IOMMU enabled, passthrough disabled" "Passthrough is on (${PASSTHROUGH}). The boot command line needs iommu.passthrough=0. atropos-performance ships that token."
elif grep -q GenuineIntel /proc/cpuinfo; then
    fail "IOMMU enabled, passthrough disabled" "Enable VT-d in the firmware. The boot command line needs intel_iommu=on when the kernel leaves it off."
else
    fail "IOMMU enabled, passthrough disabled" "Enable AMD-Vi in the firmware."
fi

# 6. Lockdown integrity. confidentiality is a superset.
# kernel-longterm enables integrity lockdown when Secure Boot is on.
LOCKDOWN=$(sed -n 's/.*\[\(.*\)\].*/\1/p' /sys/kernel/security/lockdown 2>/dev/null || true)
if [[ $LOCKDOWN == integrity || $LOCKDOWN == confidentiality ]]; then
    pass "Kernel lockdown integrity mode" "Lockdown mode is '${LOCKDOWN}'"
else
    fail "Kernel lockdown integrity mode" "Lockdown mode is '${LOCKDOWN:-unavailable}'. Enable Secure Boot. kernel-longterm turns integrity lockdown on with it."
fi

# 7. kexec off from boot. A missing sysctl means the kernel has no kexec.
KEXEC=$(cat /proc/sys/kernel/kexec_load_disabled 2>/dev/null || echo 1)
if [[ $KEXEC == 1 ]]; then
    pass "Kexec disabled"
else
    fail "Kexec disabled" "The boot command line needs kexec_load_disabled=1. atropos-performance ships that token. The sysctl applies only after userspace starts."
fi

# 8. BPF LSM. lsm= stays unset: it replaces kernel-longterm's list.
LSMS=$(cat /sys/kernel/security/lsm 2>/dev/null || true)
if [[ ,$LSMS, == *,bpf,* ]]; then
    pass "BPF LSM active"
else
    fail "BPF LSM active" "Active LSMs: ${LSMS:-unknown}. bpf is not in that list. Leave lsm= unset. Setting it replaces kernel-longterm's list and selects AppArmor."
fi

echo
if (( FAILED )); then
    echo "${red}${bold}${FAILED} of $((PASSED + FAILED)) checks failed.${normal} Fix the items above, then reboot and run this again."
    echo "Boot command line changes take effect after the next snapshot is booted."
    exit 1
fi
echo "${green}${bold}All $((PASSED + FAILED)) checks passed.${normal} This system meets the EAC Linux v2 requirements."
exit 0
