Linux 4.19.133
[linux/fpc-iii.git] / tools / testing / selftests / bpf / test_dev_cgroup.c
blob9c8b50bac7e01fd60dc436a5f986e384e2343b43
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.
6 */
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>
15 #include <linux/bpf.h>
16 #include <bpf/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;
31 __u32 prog_cnt;
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;
39 if (setup_cgroup_environment()) {
40 printf("Failed to load DEV_CGROUP program\n");
41 goto err;
44 /* Create a cgroup, get fd, and join it */
45 cgroup_fd = create_and_get_cgroup(TEST_CGROUP);
46 if (!cgroup_fd) {
47 printf("Failed to create test cgroup\n");
48 goto err;
51 if (join_cgroup(TEST_CGROUP)) {
52 printf("Failed to join cgroup\n");
53 goto err;
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;
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;
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"));
88 error = 0;
89 printf("test_dev_cgroup:PASS\n");
91 err:
92 cleanup_cgroup_environment();
94 out:
95 return error;