#!/bin/sh -efu

IMA_POLICY_ADMIN=/etc/integrity/policy
IMA_POLICY_DEFAULT=/usr/share/integrity/policy
SECFS=/sys/kernel/security

if ! grep -qs 'ima_appraise=enforce' /proc/cmdline; then
    echo "Skip the check: IMA enforce disabled." >&2
    exit 0
fi

need_unmount=
cleanup() {
    if [ -n "$need_unmount" ]; then
	umount "$SECFS"
    fi
}
trap cleanup EXIT

if ! grep -q  "$SECFS" /proc/mounts; then
    mount -n -t securityfs securityfs "$SECFS"
    need_unmount=1
fi

if [ -f "$IMA_POLICY_ADMIN" ]; then
    IMA_POLICY="$IMA_POLICY_ADMIN"
elif [ -f "$IMA_POLICY_DEFAULT" ]; then
    IMA_POLICY="$IMA_POLICY_DEFAULT"
fi

if diff -w "$IMA_POLICY" "$SECFS"/ima/policy 1>/dev/null; then
    echo "IMA policy check OK." >&2
else
    echo "IMA policy check failed!" >&2
    exit 1
fi

normalize_evm() {
    printf '0x%x' "$(($1 & ~0x80000000 ))"
}

if [ \
     -e /etc/keys/x509_evm.der -a \
     -e /etc/keys/kmk-user.blob -a \
     -e /etc/keys/evm-key.blob \
    ]
then
    if [ "$(normalize_evm "$(cat "$SECFS"/evm)")" = "$(normalize_evm "$(cat /etc/integrity/evm_mode 2>/dev/null)")" ]; then
	echo "EVM check OK: EVM enabled." >&2
    else
	echo "EVM check failed: EVM disabled!" >&2
	exit 1
    fi
fi
