1 // SPDX-License-Identifier: GPL-2.0-only 2 /* Copyright (c) 2017 Facebook 3 */ 4 5 #include <stdio.h> 6 #include <stdlib.h> 7 #include <string.h> 8 #include <errno.h> 9 #include <assert.h> 10 #include <sys/time.h> 11 12 #include <linux/bpf.h> 13 #include <bpf/bpf.h> 14 #include <bpf/libbpf.h> 15 16 #include "cgroup_helpers.h" 17 #include "bpf_rlimit.h" 18 19 #define DEV_CGROUP_PROG "./dev_cgroup.o" 20 21 #define TEST_CGROUP "/test-bpf-based-device-cgroup/" 22 23 int main(int argc, char **argv) 24 { 25 struct bpf_object *obj; 26 int error = EXIT_FAILURE; 27 int prog_fd, cgroup_fd; 28 __u32 prog_cnt; 29 30 if (bpf_prog_load(DEV_CGROUP_PROG, BPF_PROG_TYPE_CGROUP_DEVICE, 31 &obj, &prog_fd)) { 32 printf("Failed to load DEV_CGROUP program\n"); 33 goto out; 34 } 35 36 if (setup_cgroup_environment()) { 37 printf("Failed to load DEV_CGROUP program\n"); 38 goto err; 39 } 40 41 /* Create a cgroup, get fd, and join it */ 42 cgroup_fd = create_and_get_cgroup(TEST_CGROUP); 43 if (cgroup_fd < 0) { 44 printf("Failed to create test cgroup\n"); 45 goto err; 46 } 47 48 if (join_cgroup(TEST_CGROUP)) { 49 printf("Failed to join cgroup\n"); 50 goto err; 51 } 52 53 /* Attach bpf program */ 54 if (bpf_prog_attach(prog_fd, cgroup_fd, BPF_CGROUP_DEVICE, 0)) { 55 printf("Failed to attach DEV_CGROUP program"); 56 goto err; 57 } 58 59 if (bpf_prog_query(cgroup_fd, BPF_CGROUP_DEVICE, 0, NULL, NULL, 60 &prog_cnt)) { 61 printf("Failed to query attached programs"); 62 goto err; 63 } 64 65 /* All operations with /dev/zero and and /dev/urandom are allowed, 66 * everything else is forbidden. 67 */ 68 assert(system("rm -f /tmp/test_dev_cgroup_null") == 0); 69 assert(system("mknod /tmp/test_dev_cgroup_null c 1 3")); 70 assert(system("rm -f /tmp/test_dev_cgroup_null") == 0); 71 72 /* /dev/zero is whitelisted */ 73 assert(system("rm -f /tmp/test_dev_cgroup_zero") == 0); 74 assert(system("mknod /tmp/test_dev_cgroup_zero c 1 5") == 0); 75 assert(system("rm -f /tmp/test_dev_cgroup_zero") == 0); 76 77 assert(system("dd if=/dev/urandom of=/dev/zero count=64") == 0); 78 79 /* src is allowed, target is forbidden */ 80 assert(system("dd if=/dev/urandom of=/dev/full count=64")); 81 82 /* src is forbidden, target is allowed */ 83 assert(system("dd if=/dev/random of=/dev/zero count=64")); 84 85 error = 0; 86 printf("test_dev_cgroup:PASS\n"); 87 88 err: 89 cleanup_cgroup_environment(); 90 91 out: 92 return error; 93 } 94