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