blob: 8557efe096dc96018525b8ba62790a104a21b888 [file] [log] [blame]
Greg Kroah-Hartmanb2441312017-11-01 15:07:57 +01001/* SPDX-License-Identifier: GPL-2.0 */
Serge E. Hallyn08ce5f12008-04-29 01:00:10 -07002#include <linux/fs.h>
Roman Gushchinebc614f2017-11-05 08:15:32 -05003#include <linux/bpf-cgroup.h>
Serge E. Hallyn08ce5f12008-04-29 01:00:10 -07004
Roman Gushchinecf8fec2017-11-05 08:15:31 -05005#define DEVCG_ACC_MKNOD 1
6#define DEVCG_ACC_READ 2
7#define DEVCG_ACC_WRITE 4
8#define DEVCG_ACC_MASK (DEVCG_ACC_MKNOD | DEVCG_ACC_READ | DEVCG_ACC_WRITE)
9
10#define DEVCG_DEV_BLOCK 1
11#define DEVCG_DEV_CHAR 2
12#define DEVCG_DEV_ALL 4 /* this represents all devices */
13
Serge E. Hallyn08ce5f12008-04-29 01:00:10 -070014#ifdef CONFIG_CGROUP_DEVICE
Roman Gushchinecf8fec2017-11-05 08:15:31 -050015extern int __devcgroup_check_permission(short type, u32 major, u32 minor,
16 short access);
17#else
18static inline int __devcgroup_check_permission(short type, u32 major, u32 minor,
19 short access)
20{ return 0; }
21#endif
22
Roman Gushchinebc614f2017-11-05 08:15:32 -050023#if defined(CONFIG_CGROUP_DEVICE) || defined(CONFIG_CGROUP_BPF)
Roman Gushchinecf8fec2017-11-05 08:15:31 -050024static inline int devcgroup_check_permission(short type, u32 major, u32 minor,
25 short access)
26{
Roman Gushchinebc614f2017-11-05 08:15:32 -050027 int rc = BPF_CGROUP_RUN_PROG_DEVICE_CGROUP(type, major, minor, access);
28
29 if (rc)
30 return -EPERM;
31
Roman Gushchinecf8fec2017-11-05 08:15:31 -050032 return __devcgroup_check_permission(type, major, minor, access);
33}
34
Al Viro482e0cd2011-06-19 13:01:04 -040035static inline int devcgroup_inode_permission(struct inode *inode, int mask)
36{
Roman Gushchinecf8fec2017-11-05 08:15:31 -050037 short type, access = 0;
38
Al Viro482e0cd2011-06-19 13:01:04 -040039 if (likely(!inode->i_rdev))
40 return 0;
Roman Gushchinecf8fec2017-11-05 08:15:31 -050041
42 if (S_ISBLK(inode->i_mode))
43 type = DEVCG_DEV_BLOCK;
44 else if (S_ISCHR(inode->i_mode))
45 type = DEVCG_DEV_CHAR;
46 else
Al Viro482e0cd2011-06-19 13:01:04 -040047 return 0;
Roman Gushchinecf8fec2017-11-05 08:15:31 -050048
49 if (mask & MAY_WRITE)
50 access |= DEVCG_ACC_WRITE;
51 if (mask & MAY_READ)
52 access |= DEVCG_ACC_READ;
53
54 return devcgroup_check_permission(type, imajor(inode), iminor(inode),
55 access);
Al Viro482e0cd2011-06-19 13:01:04 -040056}
Roman Gushchinecf8fec2017-11-05 08:15:31 -050057
58static inline int devcgroup_inode_mknod(int mode, dev_t dev)
59{
60 short type;
61
62 if (!S_ISBLK(mode) && !S_ISCHR(mode))
63 return 0;
64
65 if (S_ISBLK(mode))
66 type = DEVCG_DEV_BLOCK;
67 else
68 type = DEVCG_DEV_CHAR;
69
70 return devcgroup_check_permission(type, MAJOR(dev), MINOR(dev),
71 DEVCG_ACC_MKNOD);
72}
73
Serge E. Hallyn08ce5f12008-04-29 01:00:10 -070074#else
75static inline int devcgroup_inode_permission(struct inode *inode, int mask)
76{ return 0; }
77static inline int devcgroup_inode_mknod(int mode, dev_t dev)
78{ return 0; }
79#endif