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 <linux/bpf.h>
9 #include <linux/version.h>
10 #include "bpf_helpers.h"
11 
12 SEC("cgroup/dev")
13 int bpf_prog1(struct bpf_cgroup_dev_ctx *ctx)
14 {
15 	short type = ctx->access_type & 0xFFFF;
16 #ifdef DEBUG
17 	short access = ctx->access_type >> 16;
18 	char fmt[] = "  %d:%d    \n";
19 
20 	switch (type) {
21 	case BPF_DEVCG_DEV_BLOCK:
22 		fmt[0] = 'b';
23 		break;
24 	case BPF_DEVCG_DEV_CHAR:
25 		fmt[0] = 'c';
26 		break;
27 	default:
28 		fmt[0] = '?';
29 		break;
30 	}
31 
32 	if (access & BPF_DEVCG_ACC_READ)
33 		fmt[8] = 'r';
34 
35 	if (access & BPF_DEVCG_ACC_WRITE)
36 		fmt[9] = 'w';
37 
38 	if (access & BPF_DEVCG_ACC_MKNOD)
39 		fmt[10] = 'm';
40 
41 	bpf_trace_printk(fmt, sizeof(fmt), ctx->major, ctx->minor);
42 #endif
43 
44 	/* Allow access to /dev/zero and /dev/random.
45 	 * Forbid everything else.
46 	 */
47 	if (ctx->major != 1 || type != BPF_DEVCG_DEV_CHAR)
48 		return 0;
49 
50 	switch (ctx->minor) {
51 	case 5: /* 1:5 /dev/zero */
52 	case 9: /* 1:9 /dev/urandom */
53 		return 1;
54 	}
55 
56 	return 0;
57 }
58 
59 char _license[] SEC("license") = "GPL";
60 __u32 _version SEC("version") = LINUX_VERSION_CODE;
61