lsm-nobpf: Check for presence of BPF LSM before loading

If the BPF LSM is compiled-in but not enabled, the loading of the BPF
program will succeed, but it won't actually do anything. Detect this
and abort rather than silently not working.

Signed-off-by: Toke Høiland-Jørgensen <toke@toke.dk>
This commit is contained in:
Toke Høiland-Jørgensen
2020-10-12 16:48:22 +02:00
parent 54259af20a
commit 40706ad9fa
2 changed files with 38 additions and 4 deletions

View File

@ -17,4 +17,6 @@ mountpoint (or protecting it in some other way) serves as a way to make this
permanent. Alternatively, the userspace program can keep running and hold on to
the link FD to prevent detachment.
To use, just compile and run =./lsm-nobpf= as root.
To use, just compile and run =./lsm-nobpf= as root. Note that you need to build
the BPF LSM (CONFIG_BPF_LSM=y) *and* enable it in the running kernel (include
'bpf' in =CONFIG_LSM= at compile time, or by the =lsm= kernel parameter at boot).

View File

@ -1,16 +1,48 @@
#include <bpf/libbpf.h>
#include <unistd.h>
#include <errno.h>
#include <string.h>
#include <sys/stat.h>
#include <fcntl.h>
int main(int argc, char **argv)
{
struct bpf_object *obj = NULL;
struct bpf_link *link = NULL;
struct bpf_program *prog;
struct bpf_object *obj;
int err = 0, fd;
char buf[100];
int err = 0;
ssize_t len;
char *c;
obj = bpf_object__open_file("lsm-nobpf-kern.o", NULL);
fd = open("/sys/kernel/security/lsm", O_RDONLY);
if (fd < 0) {
err = -errno;
printf("Error opening /sys/kernel/security/lsm ('%s') - securityfs "
"not mounted?\n",
strerror(-err));
goto out;
}
len = read(fd, buf, sizeof(buf));
if (len == -1) {
err = -errno;
printf("Error reading /sys/kernel/security/lsm: %s\n",
strerror(-err));
close(fd);
goto out;
}
close(fd);
buf[sizeof(buf)-1] = '\0';
c = strstr(buf, "bpf");
if (!c) {
printf("BPF LSM not loaded - make sure CONFIG_LSM or lsm kernel "
"param includes 'bpf'!\n");
err = -EINVAL;
goto out;
}
obj = bpf_object__open_file("lsm-nobpf-kern.o", NULL);
err = libbpf_get_error(obj);
if (err) {
libbpf_strerror(err, buf, sizeof(buf));