ima-add-sigs: Verify added IMA signature in case the file gets changed

Resolves: https://issues.redhat.com/browse/RHEL-100320

Upstream: Fedora
Conflict: None

Some IMA signatures from the RPM database may fail the verification
because they can be changed. For examples, the following files on F41
can't pass IMA signature verification,

    /usr/lib64/gconv/gconv-modules.cache
    /boot/grub2/grubenv
    /var/lib/selinux/targeted/active/commit_num
    /var/lib/selinux/targeted/active/file_contexts
    /etc/ssh/sshd_config
    /etc/yum.repos.d/fedora-updates.repo
    /etc/yum.repos.d/fedora.repo
    /etc/group
    /etc/gshadow

The kernel ima=fix mode won't generate IMA hash reference value for
files with IMA signature. As a result, users can be denied the access to
some files. So remove security.ima if a file fail the verification.
This commit is contained in:
Coiby Xu 2025-07-10 16:36:44 +08:00
parent 3d4dd401b1
commit be4e836e2f

View File

@ -53,12 +53,35 @@ abort() {
exit 1
}
get_system_ima_key() {
source /etc/os-release
local -A name_map=(['Fedora Linux']="fedora" ['Red Hat Enterprise Linux']="redhatimarelease" ['CentOS Stream']='centosimarelease')
local version_id
key_name=${name_map[$NAME]}
version_id=${VERSION_ID/.?/}
[[ $key_name == fedora ]] && name_suffix=-ima
key_path=/etc/keys/ima/${key_name}-${version_id}${name_suffix}.der
if [[ ! -e $key_path ]]; then
echo "Failed to get system IMA code verification key"
exit 1
fi
echo -n "$key_path"
}
# Add IMA signatures from RPM database
add_from_rpm_db() {
if ! command -v setfattr &>/dev/null; then
abort "Please install attr"
fi
if [[ -e "$ima_cert" ]]; then
verify_ima_cert=$ima_cert
else
verify_ima_cert=$(get_system_ima_key)
fi
# use "|" as deliminator since it won't be used in a filename or signature
while IFS="|" read -r path sig; do
# [[ -z "$sig" ]] somehow doesn't work for some files that don't have IMA
@ -72,16 +95,22 @@ add_from_rpm_db() {
continue
fi
# Skip some files that are created on the fly
if [[ $path == "/usr/share/mime/"* || $path == "/etc/pki/ca-trust/extracted/"* ]]; then
continue
fi
if ! setfattr -n security.ima "$path" -v "0x$sig"; then
echo "Failed to add IMA sig for $path"
fi
[[ -e "$ima_cert" ]] || continue
# TODO
# don't verify the modified files like /etc?
if ! evmctl ima_verify -k "$ima_cert" "$path" &>/dev/null; then
echo "Failed to verify $path"
if ! evmctl ima_verify -k "$verify_ima_cert" "$path" &>/dev/null; then
setfattr -x security.ima "$path"
# When ima_cert is set, shows the verfication result for users
[[ -e "$ima_cert" ]] && "Failed to verify $path"
continue
fi
done < <(rpm -q --queryformat "[%{FILENAMES}|%{FILESIGNATURES}\n]" "$package")
}