Back to home page

OSCL-LXR

 
 

    


0001 // SPDX-License-Identifier: GPL-2.0-only
0002 /* Copyright (c) 2017 Facebook
0003  */
0004 
0005 #include <stdio.h>
0006 #include <stdlib.h>
0007 #include <string.h>
0008 #include <errno.h>
0009 #include <assert.h>
0010 #include <sys/time.h>
0011 
0012 #include <linux/bpf.h>
0013 #include <bpf/bpf.h>
0014 #include <bpf/libbpf.h>
0015 
0016 #include "cgroup_helpers.h"
0017 #include "testing_helpers.h"
0018 
0019 #define DEV_CGROUP_PROG "./dev_cgroup.o"
0020 
0021 #define TEST_CGROUP "/test-bpf-based-device-cgroup/"
0022 
0023 int main(int argc, char **argv)
0024 {
0025     struct bpf_object *obj;
0026     int error = EXIT_FAILURE;
0027     int prog_fd, cgroup_fd;
0028     __u32 prog_cnt;
0029 
0030     /* Use libbpf 1.0 API mode */
0031     libbpf_set_strict_mode(LIBBPF_STRICT_ALL);
0032 
0033     if (bpf_prog_test_load(DEV_CGROUP_PROG, BPF_PROG_TYPE_CGROUP_DEVICE,
0034               &obj, &prog_fd)) {
0035         printf("Failed to load DEV_CGROUP program\n");
0036         goto out;
0037     }
0038 
0039     cgroup_fd = cgroup_setup_and_join(TEST_CGROUP);
0040     if (cgroup_fd < 0) {
0041         printf("Failed to create test cgroup\n");
0042         goto out;
0043     }
0044 
0045     /* Attach bpf program */
0046     if (bpf_prog_attach(prog_fd, cgroup_fd, BPF_CGROUP_DEVICE, 0)) {
0047         printf("Failed to attach DEV_CGROUP program");
0048         goto err;
0049     }
0050 
0051     if (bpf_prog_query(cgroup_fd, BPF_CGROUP_DEVICE, 0, NULL, NULL,
0052                &prog_cnt)) {
0053         printf("Failed to query attached programs");
0054         goto err;
0055     }
0056 
0057     /* All operations with /dev/zero and and /dev/urandom are allowed,
0058      * everything else is forbidden.
0059      */
0060     assert(system("rm -f /tmp/test_dev_cgroup_null") == 0);
0061     assert(system("mknod /tmp/test_dev_cgroup_null c 1 3"));
0062     assert(system("rm -f /tmp/test_dev_cgroup_null") == 0);
0063 
0064     /* /dev/zero is whitelisted */
0065     assert(system("rm -f /tmp/test_dev_cgroup_zero") == 0);
0066     assert(system("mknod /tmp/test_dev_cgroup_zero c 1 5") == 0);
0067     assert(system("rm -f /tmp/test_dev_cgroup_zero") == 0);
0068 
0069     assert(system("dd if=/dev/urandom of=/dev/zero count=64") == 0);
0070 
0071     /* src is allowed, target is forbidden */
0072     assert(system("dd if=/dev/urandom of=/dev/full count=64"));
0073 
0074     /* src is forbidden, target is allowed */
0075     assert(system("dd if=/dev/random of=/dev/zero count=64"));
0076 
0077     error = 0;
0078     printf("test_dev_cgroup:PASS\n");
0079 
0080 err:
0081     cleanup_cgroup_environment();
0082 
0083 out:
0084     return error;
0085 }