#!/usr/bin/env bash

# eac-status checks if the system is set up for Easy Anti-Cheat Linux v2.
# Run it in the linux-cachyos-eac boot entry to also check the running kernel.

EAC_CA="${EAC_CA:-/usr/share/cachyos-eac/cachyos-eac-ca.crt}"
EAC_CA_NAME="${EAC_CA_NAME:-CachyOS EAC CA}"
WIKI_URL=https://wiki.cachyos.org/configuration/easy_anti_cheat/#troubleshooting

die() {
    echo "Error: $*"
    exit 1
}

if [ "$(id -u)" -ne 0 ]; then
    die "This script must be run with root privileges."
fi

for cmd in sbctl sbverify tpm2_eventlog; do
    if ! command -v "$cmd" >/dev/null; then
        die "$cmd is missing, install sbctl, sbsigntools and tpm2-tools."
    fi
done

failed=0
warned=0
have_ca=0

ok() {
    echo "[ OK ] $*"
}

fail() {
    echo "[FAIL] $*"
    failed=$((failed + 1))
}

warn() {
    echo "[WARN] $*"
    warned=$((warned + 1))
}

# What to do about the line above
hint() {
    echo "       $*"
}

# Common name of a DER certificate
cn() {
    openssl x509 -inform DER -noout -subject -nameopt multiline 2>/dev/null \
        | sed -n 's/^ *commonName *= //p'
}

tmp=$(mktemp -d)
trap 'rm -rf "$tmp"' EXIT

check_secure_boot() {
    if sbctl status | grep -q 'Secure Boot:.*Enabled'; then
        ok "Secure Boot is enabled"
    else
        fail "Secure Boot is disabled"
    fi

    if sbctl status | grep -q 'Setup Mode:.*Disabled'; then
        ok "Setup Mode is disabled"
    else
        fail "Firmware is in Setup Mode"
    fi
}

check_tpm() {
    if [ "$(cat /sys/class/tpm/tpm0/tpm_version_major 2>/dev/null)" = 2 ]; then
        ok "TPM 2.0 found"
    else
        fail "No TPM 2.0 found"
        return
    fi

    # The kernel only lists the PCR banks that are active
    if [ -d /sys/class/tpm/tpm0/pcr-sha256 ]; then
        ok "SHA-256 PCR bank is active"
    else
        fail "SHA-256 PCR bank is not active, enable it in the firmware settings"
    fi
}

# The CA from cachyos-eac-signing-key, as DER to compare whole certificates.
# The checks that need it are skipped without it.
load_ca() {
    if openssl x509 -in "$EAC_CA" -outform DER -out "$tmp/eac.der" 2>/dev/null; then
        have_ca=1
        return
    fi
    fail "$EAC_CA is missing, install cachyos-eac-signing-key"
    hint "The checks of the signatures and of the certificate that verified the boot are skipped."
}

# Find the EAC certificate in db. The whole certificate has to match, a
# certificate that only has the same name does not verify the boot files.
check_db() {
    local der same_name=0

    [ "$have_ca" -eq 1 ] || return 0

    sbctl --disable-landlock --quiet export-enrolled-keys --dir "$tmp/keys" >/dev/null
    for der in "$tmp"/keys/DB/*.der; do
        # db is empty in Setup Mode
        [ -f "$der" ] || continue
        if cmp -s "$der" "$tmp/eac.der"; then
            ok "$EAC_CA_NAME is enrolled"
            return
        elif [ "$(cn < "$der")" = "$EAC_CA_NAME" ]; then
            same_name=1
        fi
    done

    if [ "$same_name" -eq 1 ]; then
        fail "A certificate named $EAC_CA_NAME is enrolled, but it is not the one from cachyos-eac-signing-key"
    else
        fail "$EAC_CA_NAME is not enrolled, see the wiki on how to enroll it"
    fi
}

# The file must only be signed by CachyOS. sbctl may sign it again with your
# own key, for example through its mkinitcpio hook.
check_signature() {
    local sigs

    [ "$have_ca" -eq 1 ] || return 0

    sigs=$(sbverify --list "$1" 2>/dev/null | grep -c '^signature')
    if sbverify --cert "$EAC_CA" "$1" >/dev/null 2>&1; then
        if [ "$sigs" -eq 1 ]; then
            ok "$1 is signed by CachyOS"
        else
            fail "$1 has $sigs signatures"
        fi
    else
        fail "$1 is not signed by CachyOS"
    fi
}

# The systemd-boot that starts the EAC kernel. In the EAC boot, systemd-boot
# reports the file it was started from. Otherwise it is the copy in
# EFI/cachyos-eac (Limine, rEFInd) or the one from bootctl install.
eac_boot_loader() {
    local esp="$1" file path
    local var=/sys/firmware/efi/efivars/LoaderImageIdentifier-4a67b082-0a4c-41cf-b6c7-440b29bb8c4f

    if [[ "$(uname -r)" == *-cachyos-eac ]] && [ -r "$var" ]; then
        # Skip the 4 byte attributes, the path is UTF-16 with backslashes
        path=$(tail -c +5 "$var" | iconv -f UTF-16LE -t UTF-8 | tr -d '\0')
        echo "$esp${path//\\//}"
        return
    fi
    for file in "$esp/EFI/cachyos-eac/systemd-bootx64.efi" "$esp/EFI/systemd/systemd-bootx64.efi"; do
        if [ -f "$file" ]; then
            echo "$file"
            return
        fi
    done
}

check_boot_files() {
    local esp file loader copy found=0

    esp=$(bootctl --print-esp-path 2>/dev/null || echo /boot)

    # systemd-boot and rEFInd use the kernel in /boot, Limine and GRUB a copy
    # on the EFI system partition
    for file in /boot/vmlinuz-linux-cachyos-eac \
                "$esp/$(cat /etc/machine-id)/linux-cachyos-eac/vmlinuz"; do
        [ -f "$file" ] || continue
        check_signature "$file"
        found=1
    done
    if [ "$found" -eq 0 ]; then
        fail "The EAC kernel is missing, install linux-cachyos-eac"
    fi

    # With GRUB, systemd-boot starts a copy of the kernel and its initramfs on
    # the EFI system partition. An old copy does not match the installed modules.
    # The hook from cachyos-eac-grub-hook keeps it up to date and is only
    # installed on GRUB systems.
    copy="$esp/$(cat /etc/machine-id)/linux-cachyos-eac"
    if [ -f /usr/lib/initcpio/post/cachyos-eac-esp ]; then
        if [ ! -f "$copy/vmlinuz" ] || [ ! -f "$copy/initramfs" ]; then
            fail "The copy of the EAC kernel in $copy is missing, run: sudo eac-setup"
        elif cmp -s /boot/vmlinuz-linux-cachyos-eac "$copy/vmlinuz" \
             && cmp -s /boot/initramfs-linux-cachyos-eac.img "$copy/initramfs"; then
            ok "The copy of the EAC kernel in $copy is up to date"
        else
            fail "The copy of the EAC kernel in $copy is out of date, run: sudo eac-setup"
        fi
    fi

    loader=$(eac_boot_loader "$esp")
    if [ -z "$loader" ]; then
        fail "No systemd-boot found for the EAC boot entry"
    elif [ -f "$loader" ]; then
        check_signature "$loader"
    else
        fail "$loader is missing"
    fi
}

# The last one counts if an option is given more than once
on_cmdline() {
    [ "$(tr ' ' '\n' < /proc/cmdline | grep "^${1%%=*}=" | tail -n1)" = "$1" ]
}

check_cmdline() {
    local opt
    local -a opts=(lockdown=integrity "lsm=landlock,lockdown,yama,integrity,bpf" iommu.passthrough=0)

    # intel_iommu= only exists for Intel VT-d, the AMD IOMMU is on by default
    # and check_iommu verifies the result on every vendor.
    if grep -qm1 '^vendor_id.*GenuineIntel' /proc/cpuinfo; then
        opts+=(intel_iommu=on)
    fi
    opts+=(module.sig_enforce=1 sysctl.kernel.kexec_load_disabled=1)

    # The EAC kernel was started from the menu of Limine or GRUB, or from the
    # entry that systemd-boot creates for it. These three options are only on
    # the command line of the EAC entry, the others can be part of the normal
    # boot entries as well.
    if ! on_cmdline lockdown=integrity && ! on_cmdline module.sig_enforce=1 \
       && ! on_cmdline sysctl.kernel.kexec_load_disabled=1; then
        fail "The EAC options are missing from the kernel command line, the wrong boot entry was started"
        hint "Reboot into the EAC entry with: sudo eac-setup boot"
        return
    fi

    for opt in "${opts[@]}"; do
        if on_cmdline "$opt"; then
            ok "$opt"
        else
            fail "$opt is missing from the kernel command line"
        fi
    done
}

check_kernel() {
    local config

    if grep -q '\[integrity\]' /sys/kernel/security/lockdown; then
        ok "Lockdown is in integrity mode"
    else
        fail "Lockdown is not in integrity mode"
    fi

    if grep -q 'bpf' /sys/kernel/security/lsm; then
        ok "BPF LSM is active"
    else
        fail "BPF LSM is not active"
    fi

    if [ "$(cat /sys/module/module/parameters/sig_enforce)" = Y ]; then
        ok "Module signatures are enforced"
    else
        fail "Module signatures are not enforced"
    fi

    if [ "$(cat /proc/sys/kernel/kexec_load_disabled)" = 1 ]; then
        ok "kexec is disabled"
    else
        fail "kexec is not disabled"
    fi

    if [ -r /sys/kernel/btf/vmlinux ]; then
        ok "BTF is available"
    else
        fail "BTF is not available (/sys/kernel/btf/vmlinux)"
    fi

    # Older EAC kernels load ACPI tables from the initramfs, which lockdown
    # does not stop
    if config=$(zcat /proc/config.gz 2>/dev/null); then
        if grep -qx 'CONFIG_ACPI_TABLE_UPGRADE=y' <<< "$config"; then
            fail "This EAC kernel loads ACPI tables from the initramfs, update it with: sudo pacman -Syu"
        else
            ok "The kernel does not load ACPI tables from the initramfs"
        fi
    fi
}

# The kernel lets AMD GPUs with PASID support bypass the IOMMU (identity domain)
# even with iommu.passthrough=0, so they only get a warning. Any other device
# that bypasses it fails the check.
check_iommu() {
    local group dev gpu devs
    local -a gpus=() others=()

    if ! ls /sys/kernel/iommu_groups/*/type >/dev/null 2>&1; then
        fail "IOMMU is disabled"
        return
    elif ! grep -qx -e DMA -e DMA-FQ /sys/kernel/iommu_groups/*/type; then
        fail "IOMMU is in passthrough mode"
        return
    fi

    for group in /sys/kernel/iommu_groups/*; do
        [ "$(cat "$group/type")" = identity ] || continue

        gpu='' devs=''
        for dev in "$group"/devices/*; do
            if [ "$(cat "$dev/vendor" 2>/dev/null)" = 0x1002 ] \
               && [[ "$(cat "$dev/class" 2>/dev/null)" == 0x03* ]]; then
                gpu=${dev##*/}
            fi
            devs+=" ${dev##*/}"
        done
        if [ -n "$gpu" ]; then
            gpus+=("$gpu")
        else
            others+=("${devs# }")
        fi
    done

    for devs in "${others[@]}"; do
        fail "IOMMU is bypassed by $devs"
    done
    if [ "${#others[@]}" -eq 0 ]; then
        ok "IOMMU is enabled"
    fi
    for gpu in "${gpus[@]}"; do
        warn "IOMMU is bypassed by the AMD GPU $gpu (kernel default for AMD GPUs)"
    done
}

# Certificates the firmware used to verify the boot files, recorded in PCR 7
check_pcr7() {
    local data name verified=0
    local -a others=()

    [ "$have_ca" -eq 1 ] || return 0

    # tpm2_eventlog stops at an event that it cannot parse. It has printed the
    # events before it, which are often enough, so only its output counts.
    tpm2_eventlog /sys/kernel/security/tpm0/binary_bios_measurements > "$tmp/eventlog" 2>/dev/null
    if [ ! -s "$tmp/eventlog" ]; then
        fail "The TPM event log could not be read, it tells which certificate verified the boot"
        return
    fi

    while read -r data; do
        # 16 bytes owner GUID, then the certificate or hash
        [ "${#data}" -gt 32 ] || continue
        echo "${data:32}" | tr a-f A-F | basenc --base16 -d > "$tmp/authority.der" 2>/dev/null
        if cmp -s "$tmp/authority.der" "$tmp/eac.der"; then
            verified=1
            continue
        fi
        name=$(cn < "$tmp/authority.der")
        if [ -z "$name" ]; then
            name="an entry without a name (a hash or a certificate without a common name)"
        elif [ "$name" = "$EAC_CA_NAME" ]; then
            name="another certificate named $EAC_CA_NAME"
        fi
        others+=("$name")
    done < <(awk '/EventNum:/ {f=0} /EV_EFI_VARIABLE_AUTHORITY/ {f=1} f && /VariableData:/ {print $2; f=0}' \
                "$tmp/eventlog" | tr -d '"')

    if [ "$verified" -eq 1 ]; then
        ok "Boot was verified by $EAC_CA_NAME"
    elif [ "${#others[@]}" -eq 0 ]; then
        # A firmware that verifies the boot files records at least one certificate
        fail "Boot was not verified by $EAC_CA_NAME, the firmware recorded no certificate at all"
        hint "The firmware probably starts boot files without verifying them."
        if grep -qi 'micro-star' /sys/class/dmi/id/board_vendor 2>/dev/null; then
            hint "On MSI boards, set 'Secure Boot Preset' to 'Maximum Security' in the firmware setup,"
            hint "or 'Image Execution Policy' to 'Deny Execute' on older firmware."
        fi
    else
        fail "Boot was not verified by $EAC_CA_NAME"
    fi

    for name in "${others[@]}"; do
        [[ "$name" == Microsoft* ]] || warn "Boot was also verified by $name"
    done
}

# Print the result and exit with 1 if a check failed. The checks only cover this
# system, whether a game starts is still up to Easy Anti-Cheat.
summary() {
    echo
    if [ "$failed" -eq 1 ]; then
        echo "1 check failed, see $WIKI_URL"
    elif [ "$failed" -gt 1 ]; then
        echo "$failed checks failed, see $WIKI_URL"
    elif [ "$1" = boot-files ]; then
        echo "The boot files are ready. Boot the EAC entry to check the running kernel."
    elif [ "$warned" -gt 0 ]; then
        echo "No check failed, but Easy Anti-Cheat may not accept the warnings above."
    else
        echo "All checks passed. This boot meets the requirements of Easy Anti-Cheat Linux v2."
    fi
    exit $((failed > 0))
}

check_secure_boot
check_tpm
load_ca
check_db
check_boot_files

if [[ "$(uname -r)" != *-cachyos-eac ]]; then
    summary boot-files
fi

check_cmdline
check_kernel
check_iommu
check_pcr7

summary
