1 /* Copyright (c) 2017 Facebook
3 * This program is free software; you can redistribute it and/or
4 * modify it under the terms of version 2 of the GNU General Public
5 * License as published by the Free Software Foundation.
15 #include <linux/bpf.h>
17 #include <bpf/libbpf.h>
19 #include "cgroup_helpers.h"
20 #include "bpf_rlimit.h"
22 #define DEV_CGROUP_PROG "./dev_cgroup.o"
24 #define TEST_CGROUP "/test-bpf-based-device-cgroup/"
26 int main(int argc
, char **argv
)
28 struct bpf_object
*obj
;
29 int error
= EXIT_FAILURE
;
30 int prog_fd
, cgroup_fd
;
33 if (bpf_prog_load(DEV_CGROUP_PROG
, BPF_PROG_TYPE_CGROUP_DEVICE
,
35 printf("Failed to load DEV_CGROUP program\n");
39 if (setup_cgroup_environment()) {
40 printf("Failed to load DEV_CGROUP program\n");
44 /* Create a cgroup, get fd, and join it */
45 cgroup_fd
= create_and_get_cgroup(TEST_CGROUP
);
47 printf("Failed to create test cgroup\n");
51 if (join_cgroup(TEST_CGROUP
)) {
52 printf("Failed to join cgroup\n");
56 /* Attach bpf program */
57 if (bpf_prog_attach(prog_fd
, cgroup_fd
, BPF_CGROUP_DEVICE
, 0)) {
58 printf("Failed to attach DEV_CGROUP program");
62 if (bpf_prog_query(cgroup_fd
, BPF_CGROUP_DEVICE
, 0, NULL
, NULL
,
64 printf("Failed to query attached programs");
68 /* All operations with /dev/zero and and /dev/urandom are allowed,
69 * everything else is forbidden.
71 assert(system("rm -f /tmp/test_dev_cgroup_null") == 0);
72 assert(system("mknod /tmp/test_dev_cgroup_null c 1 3"));
73 assert(system("rm -f /tmp/test_dev_cgroup_null") == 0);
75 /* /dev/zero is whitelisted */
76 assert(system("rm -f /tmp/test_dev_cgroup_zero") == 0);
77 assert(system("mknod /tmp/test_dev_cgroup_zero c 1 5") == 0);
78 assert(system("rm -f /tmp/test_dev_cgroup_zero") == 0);
80 assert(system("dd if=/dev/urandom of=/dev/zero count=64") == 0);
82 /* src is allowed, target is forbidden */
83 assert(system("dd if=/dev/urandom of=/dev/full count=64"));
85 /* src is forbidden, target is allowed */
86 assert(system("dd if=/dev/random of=/dev/zero count=64"));
89 printf("test_dev_cgroup:PASS\n");
92 cleanup_cgroup_environment();