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 "testing_helpers.h"
18 #include "bpf_rlimit.h"
19 
20 #define DEV_CGROUP_PROG "./dev_cgroup.o"
21 
22 #define TEST_CGROUP "/test-bpf-based-device-cgroup/"
23 
24 int main(int argc, char **argv)
25 {
26 	struct bpf_object *obj;
27 	int error = EXIT_FAILURE;
28 	int prog_fd, cgroup_fd;
29 	__u32 prog_cnt;
30 
31 	if (bpf_prog_test_load(DEV_CGROUP_PROG, BPF_PROG_TYPE_CGROUP_DEVICE,
32 			  &obj, &prog_fd)) {
33 		printf("Failed to load DEV_CGROUP program\n");
34 		goto out;
35 	}
36 
37 	cgroup_fd = cgroup_setup_and_join(TEST_CGROUP);
38 	if (cgroup_fd < 0) {
39 		printf("Failed to create test cgroup\n");
40 		goto out;
41 	}
42 
43 	/* Attach bpf program */
44 	if (bpf_prog_attach(prog_fd, cgroup_fd, BPF_CGROUP_DEVICE, 0)) {
45 		printf("Failed to attach DEV_CGROUP program");
46 		goto err;
47 	}
48 
49 	if (bpf_prog_query(cgroup_fd, BPF_CGROUP_DEVICE, 0, NULL, NULL,
50 			   &prog_cnt)) {
51 		printf("Failed to query attached programs");
52 		goto err;
53 	}
54 
55 	/* All operations with /dev/zero and and /dev/urandom are allowed,
56 	 * everything else is forbidden.
57 	 */
58 	assert(system("rm -f /tmp/test_dev_cgroup_null") == 0);
59 	assert(system("mknod /tmp/test_dev_cgroup_null c 1 3"));
60 	assert(system("rm -f /tmp/test_dev_cgroup_null") == 0);
61 
62 	/* /dev/zero is whitelisted */
63 	assert(system("rm -f /tmp/test_dev_cgroup_zero") == 0);
64 	assert(system("mknod /tmp/test_dev_cgroup_zero c 1 5") == 0);
65 	assert(system("rm -f /tmp/test_dev_cgroup_zero") == 0);
66 
67 	assert(system("dd if=/dev/urandom of=/dev/zero count=64") == 0);
68 
69 	/* src is allowed, target is forbidden */
70 	assert(system("dd if=/dev/urandom of=/dev/full count=64"));
71 
72 	/* src is forbidden, target is allowed */
73 	assert(system("dd if=/dev/random of=/dev/zero count=64"));
74 
75 	error = 0;
76 	printf("test_dev_cgroup:PASS\n");
77 
78 err:
79 	cleanup_cgroup_environment();
80 
81 out:
82 	return error;
83 }
84