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 #include <sys/resource.h>
15 
16 #include <linux/bpf.h>
17 #include <bpf/bpf.h>
18 #include <bpf/libbpf.h>
19 
20 #include "cgroup_helpers.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 rlimit limit  = { RLIM_INFINITY, RLIM_INFINITY };
29 	struct bpf_object *obj;
30 	int error = EXIT_FAILURE;
31 	int prog_fd, cgroup_fd;
32 	__u32 prog_cnt;
33 
34 	if (setrlimit(RLIMIT_MEMLOCK, &limit) < 0)
35 		perror("Unable to lift memlock rlimit");
36 
37 	if (bpf_prog_load(DEV_CGROUP_PROG, BPF_PROG_TYPE_CGROUP_DEVICE,
38 			  &obj, &prog_fd)) {
39 		printf("Failed to load DEV_CGROUP program\n");
40 		goto out;
41 	}
42 
43 	if (setup_cgroup_environment()) {
44 		printf("Failed to load DEV_CGROUP program\n");
45 		goto err;
46 	}
47 
48 	/* Create a cgroup, get fd, and join it */
49 	cgroup_fd = create_and_get_cgroup(TEST_CGROUP);
50 	if (!cgroup_fd) {
51 		printf("Failed to create test cgroup\n");
52 		goto err;
53 	}
54 
55 	if (join_cgroup(TEST_CGROUP)) {
56 		printf("Failed to join cgroup\n");
57 		goto err;
58 	}
59 
60 	/* Attach bpf program */
61 	if (bpf_prog_attach(prog_fd, cgroup_fd, BPF_CGROUP_DEVICE, 0)) {
62 		printf("Failed to attach DEV_CGROUP program");
63 		goto err;
64 	}
65 
66 	if (bpf_prog_query(cgroup_fd, BPF_CGROUP_DEVICE, 0, NULL, NULL,
67 			   &prog_cnt)) {
68 		printf("Failed to query attached programs");
69 		goto err;
70 	}
71 
72 	/* All operations with /dev/zero and and /dev/urandom are allowed,
73 	 * everything else is forbidden.
74 	 */
75 	assert(system("rm -f /tmp/test_dev_cgroup_null") == 0);
76 	assert(system("mknod /tmp/test_dev_cgroup_null c 1 3"));
77 	assert(system("rm -f /tmp/test_dev_cgroup_null") == 0);
78 
79 	/* /dev/zero is whitelisted */
80 	assert(system("rm -f /tmp/test_dev_cgroup_zero") == 0);
81 	assert(system("mknod /tmp/test_dev_cgroup_zero c 1 5") == 0);
82 	assert(system("rm -f /tmp/test_dev_cgroup_zero") == 0);
83 
84 	assert(system("dd if=/dev/urandom of=/dev/zero count=64") == 0);
85 
86 	/* src is allowed, target is forbidden */
87 	assert(system("dd if=/dev/urandom of=/dev/full count=64"));
88 
89 	/* src is forbidden, target is allowed */
90 	assert(system("dd if=/dev/random of=/dev/zero count=64"));
91 
92 	error = 0;
93 	printf("test_dev_cgroup:PASS\n");
94 
95 err:
96 	cleanup_cgroup_environment();
97 
98 out:
99 	return error;
100 }
101