#include "vmlinux.h"
#include <errno.h>
#include <bpf/bpf_helpers.h>
#include <bpf/bpf_tracing.h>
#include "bpf_kfuncs.h"
#include "err.h"
char _license[] SEC("license") = "GPL";
#ifndef SHA256_DIGEST_SIZE
#define SHA256_DIGEST_SIZE 32
#endif
#define MAX_SIG_SIZE 1024
#define MAGIC_SIZE 8
#define SIZEOF_STRUCT_FSVERITY_DIGEST 4
char digest[MAGIC_SIZE + SIZEOF_STRUCT_FSVERITY_DIGEST + SHA256_DIGEST_SIZE];
__u32 monitored_pid;
char sig[MAX_SIG_SIZE];
__u32 sig_size;
__s32 user_keyring_serial;
SEC("lsm.s/file_open")
int BPF_PROG(test_file_open, struct file *f)
{
struct bpf_dynptr digest_ptr, sig_ptr;
struct bpf_key *trusted_keyring;
__u32 pid;
int ret;
pid = bpf_get_current_pid_tgid() >> 32;
if (pid != monitored_pid)
return 0;
bpf_dynptr_from_mem(digest + MAGIC_SIZE, sizeof(digest) - MAGIC_SIZE, 0, &digest_ptr);
ret = bpf_get_fsverity_digest(f, &digest_ptr);
if (ret < 0)
return 0;
bpf_dynptr_from_mem(digest, sizeof(digest), 0, &digest_ptr);
bpf_dynptr_from_mem(sig, sizeof(sig), 0, &sig_ptr);
ret = bpf_get_file_xattr(f, "user.sig", &sig_ptr);
if (ret < 0)
return -EPERM;
trusted_keyring = bpf_lookup_user_key(user_keyring_serial, 0);
if (!trusted_keyring)
return -ENOENT;
ret = bpf_verify_pkcs7_signature(&digest_ptr, &sig_ptr, trusted_keyring);
bpf_key_put(trusted_keyring);
set_if_not_errno_or_zero(ret, -EFAULT);
return ret;
}