Skip to content

Program type BPF_PROG_TYPE_LSM

v5.7

BPF_PROG_TYPE_LSM are eBPF programs that can attach to LSM (Linux Security Module) hooks. These are the same hooks as used by programs such as SELinux and AppArmor.

Usage

The primary use case is to implement security software. For example, the socket_create hook is called when a process calls the socket syscall, if the eBPF program returns 0 the socket is allowed to be created, but the eBPF program can also return an error value to block the socket creation.

The list of all LSM hooks can be found in lsm_hook_defs.h, additional documentation for these hooks lives in lsm_hooks.h

// Copyright (C) 2020 Google LLC.
SEC("lsm/file_mprotect")
int BPF_PROG(mprotect_audit, struct vm_area_struct *vma,
            unsigned long reqprot, unsigned long prot, int ret)
{
    /* ret is the return value from the previous BPF program
        * or 0 if it's the first hook.
        */
    if (ret != 0)
        return ret;

    int is_heap;

    is_heap = (vma->vm_start >= vma->vm_mm->start_brk &&
            vma->vm_end <= vma->vm_mm->brk);

    /* Return an -EPERM or write information to the perf events buffer
        * for auditing
        */
    if (is_heap)
        return -EPERM;
}

Context

LSM programs are invoked with an array of __u64 values equal in length to the amount of arguments of the LSM hook, each index representing the arguments in order. The BPF_PROG macro defined in tools/lib/bpf/bpf_tracing.h is often used to make it easier to write LSM programs. The macro allows the user to write the arguments as declared on the hooks, the macro will cast the arguments. The actual arguments and their times are determined by the hook to which this program is attached.

Attachment

LSM programs are exclusively attached via bpf links. To do so the program must be loaded with the BPF_LSM_MAC expected attach type and use it as the parameter to attach_type. The target_btf_id parameter must be populated with the BTF ID of the LSM hook point which can be extracted from the SELinux BTF on the system.

Docs could be improved

This part of the docs is incomplete, contributions are very welcome

Helper functions

Not all helper functions are available in all program types. These are the helper calls available for LSM programs:

Supported helper functions

KFuncs

Supported kfuncs