1 // SPDX-License-Identifier: GPL-2.0-only
2 /*
3 * Security-Enhanced Linux (SELinux) security module
4 *
5 * This file contains the SELinux hook function implementations.
6 *
7 * Authors: Stephen Smalley, <stephen.smalley.work@gmail.com>
8 * Chris Vance, <cvance@nai.com>
9 * Wayne Salamon, <wsalamon@nai.com>
10 * James Morris <jmorris@redhat.com>
11 *
12 * Copyright (C) 2001,2002 Networks Associates Technology, Inc.
13 * Copyright (C) 2003-2008 Red Hat, Inc., James Morris <jmorris@redhat.com>
14 * Eric Paris <eparis@redhat.com>
15 * Copyright (C) 2004-2005 Trusted Computer Solutions, Inc.
16 * <dgoeddel@trustedcs.com>
17 * Copyright (C) 2006, 2007, 2009 Hewlett-Packard Development Company, L.P.
18 * Paul Moore <paul@paul-moore.com>
19 * Copyright (C) 2007 Hitachi Software Engineering Co., Ltd.
20 * Yuichi Nakamura <ynakam@hitachisoft.jp>
21 * Copyright (C) 2016 Mellanox Technologies
22 */
23
24 #include <linux/init.h>
25 #include <linux/kd.h>
26 #include <linux/kernel.h>
27 #include <linux/kernel_read_file.h>
28 #include <linux/errno.h>
29 #include <linux/sched/signal.h>
30 #include <linux/sched/task.h>
31 #include <linux/lsm_hooks.h>
32 #include <linux/xattr.h>
33 #include <linux/capability.h>
34 #include <linux/unistd.h>
35 #include <linux/mm.h>
36 #include <linux/mman.h>
37 #include <linux/slab.h>
38 #include <linux/pagemap.h>
39 #include <linux/proc_fs.h>
40 #include <linux/swap.h>
41 #include <linux/spinlock.h>
42 #include <linux/syscalls.h>
43 #include <linux/dcache.h>
44 #include <linux/file.h>
45 #include <linux/fdtable.h>
46 #include <linux/namei.h>
47 #include <linux/mount.h>
48 #include <linux/fs_context.h>
49 #include <linux/fs_parser.h>
50 #include <linux/netfilter_ipv4.h>
51 #include <linux/netfilter_ipv6.h>
52 #include <linux/tty.h>
53 #include <net/icmp.h>
54 #include <net/ip.h> /* for local_port_range[] */
55 #include <net/tcp.h> /* struct or_callable used in sock_rcv_skb */
56 #include <net/inet_connection_sock.h>
57 #include <net/net_namespace.h>
58 #include <net/netlabel.h>
59 #include <linux/uaccess.h>
60 #include <asm/ioctls.h>
61 #include <linux/atomic.h>
62 #include <linux/bitops.h>
63 #include <linux/interrupt.h>
64 #include <linux/netdevice.h> /* for network interface checks */
65 #include <net/netlink.h>
66 #include <linux/tcp.h>
67 #include <linux/udp.h>
68 #include <linux/sctp.h>
69 #include <net/sctp/structs.h>
70 #include <linux/quota.h>
71 #include <linux/un.h> /* for Unix socket types */
72 #include <net/af_unix.h> /* for Unix socket types */
73 #include <linux/parser.h>
74 #include <linux/nfs_mount.h>
75 #include <net/ipv6.h>
76 #include <linux/hugetlb.h>
77 #include <linux/personality.h>
78 #include <linux/audit.h>
79 #include <linux/string.h>
80 #include <linux/mutex.h>
81 #include <linux/posix-timers.h>
82 #include <linux/syslog.h>
83 #include <linux/user_namespace.h>
84 #include <linux/export.h>
85 #include <linux/msg.h>
86 #include <linux/shm.h>
87 #include <uapi/linux/shm.h>
88 #include <linux/bpf.h>
89 #include <linux/kernfs.h>
90 #include <linux/stringhash.h> /* for hashlen_string() */
91 #include <uapi/linux/mount.h>
92 #include <linux/fsnotify.h>
93 #include <linux/fanotify.h>
94 #include <linux/io_uring/cmd.h>
95 #include <uapi/linux/lsm.h>
96 #include <linux/memfd.h>
97 #include <uapi/linux/inet_diag.h>
98
99 #include "initcalls.h"
100 #include "avc.h"
101 #include "objsec.h"
102 #include "netif.h"
103 #include "netnode.h"
104 #include "netport.h"
105 #include "ibpkey.h"
106 #include "xfrm.h"
107 #include "netlabel.h"
108 #include "audit.h"
109 #include "avc_ss.h"
110 #include "ima.h"
111
112 #define SELINUX_INODE_INIT_XATTRS 1
113
114 struct selinux_state selinux_state;
115
116 /* SECMARK reference count */
117 static atomic_t selinux_secmark_refcount = ATOMIC_INIT(0);
118
119 #ifdef CONFIG_SECURITY_SELINUX_DEVELOP
120 static int selinux_enforcing_boot __initdata;
121
enforcing_setup(char * str)122 static int __init enforcing_setup(char *str)
123 {
124 unsigned long enforcing;
125 if (!kstrtoul(str, 0, &enforcing))
126 selinux_enforcing_boot = enforcing ? 1 : 0;
127 return 1;
128 }
129 __setup("enforcing=", enforcing_setup);
130 #else
131 #define selinux_enforcing_boot 1
132 #endif
133
134 int selinux_enabled_boot __initdata = 1;
135 #ifdef CONFIG_SECURITY_SELINUX_BOOTPARAM
selinux_enabled_setup(char * str)136 static int __init selinux_enabled_setup(char *str)
137 {
138 unsigned long enabled;
139 if (!kstrtoul(str, 0, &enabled))
140 selinux_enabled_boot = enabled ? 1 : 0;
141 return 1;
142 }
143 __setup("selinux=", selinux_enabled_setup);
144 #endif
145
checkreqprot_setup(char * str)146 static int __init checkreqprot_setup(char *str)
147 {
148 unsigned long checkreqprot;
149
150 if (!kstrtoul(str, 0, &checkreqprot)) {
151 if (checkreqprot)
152 pr_err("SELinux: checkreqprot set to 1 via kernel parameter. This is no longer supported.\n");
153 }
154 return 1;
155 }
156 __setup("checkreqprot=", checkreqprot_setup);
157
158 /**
159 * selinux_secmark_enabled - Check to see if SECMARK is currently enabled
160 *
161 * Description:
162 * This function checks the SECMARK reference counter to see if any SECMARK
163 * targets are currently configured, if the reference counter is greater than
164 * zero SECMARK is considered to be enabled. Returns true (1) if SECMARK is
165 * enabled, false (0) if SECMARK is disabled. If the always_check_network
166 * policy capability is enabled, SECMARK is always considered enabled.
167 *
168 */
selinux_secmark_enabled(void)169 static int selinux_secmark_enabled(void)
170 {
171 return (selinux_policycap_alwaysnetwork() ||
172 atomic_read(&selinux_secmark_refcount));
173 }
174
175 /**
176 * selinux_peerlbl_enabled - Check to see if peer labeling is currently enabled
177 *
178 * Description:
179 * This function checks if NetLabel or labeled IPSEC is enabled. Returns true
180 * (1) if any are enabled or false (0) if neither are enabled. If the
181 * always_check_network policy capability is enabled, peer labeling
182 * is always considered enabled.
183 *
184 */
selinux_peerlbl_enabled(void)185 static int selinux_peerlbl_enabled(void)
186 {
187 return (selinux_policycap_alwaysnetwork() ||
188 netlbl_enabled() || selinux_xfrm_enabled());
189 }
190
selinux_netcache_avc_callback(u32 event)191 static int selinux_netcache_avc_callback(u32 event)
192 {
193 if (event == AVC_CALLBACK_RESET) {
194 sel_netif_flush();
195 sel_netnode_flush();
196 sel_netport_flush();
197 synchronize_net();
198 }
199 return 0;
200 }
201
selinux_lsm_notifier_avc_callback(u32 event)202 static int selinux_lsm_notifier_avc_callback(u32 event)
203 {
204 if (event == AVC_CALLBACK_RESET) {
205 sel_ib_pkey_flush();
206 call_blocking_lsm_notifier(LSM_POLICY_CHANGE, NULL);
207 }
208
209 return 0;
210 }
211
212 /*
213 * initialise the security for the init task
214 */
cred_init_security(void)215 static void cred_init_security(void)
216 {
217 struct cred_security_struct *crsec;
218
219 /* NOTE: the lsm framework zeros out the buffer on allocation */
220
221 crsec = selinux_cred(unrcu_pointer(current->real_cred));
222 crsec->osid = crsec->sid = SECINITSID_KERNEL;
223 }
224
225 /*
226 * get the security ID of a set of credentials
227 */
cred_sid(const struct cred * cred)228 static inline u32 cred_sid(const struct cred *cred)
229 {
230 const struct cred_security_struct *crsec;
231
232 crsec = selinux_cred(cred);
233 return crsec->sid;
234 }
235
__ad_net_init(struct common_audit_data * ad,struct lsm_network_audit * net,int ifindex,struct sock * sk,u16 family)236 static void __ad_net_init(struct common_audit_data *ad,
237 struct lsm_network_audit *net,
238 int ifindex, struct sock *sk, u16 family)
239 {
240 ad->type = LSM_AUDIT_DATA_NET;
241 ad->u.net = net;
242 net->netif = ifindex;
243 net->sk = sk;
244 net->family = family;
245 }
246
ad_net_init_from_sk(struct common_audit_data * ad,struct lsm_network_audit * net,struct sock * sk)247 static void ad_net_init_from_sk(struct common_audit_data *ad,
248 struct lsm_network_audit *net,
249 struct sock *sk)
250 {
251 __ad_net_init(ad, net, 0, sk, 0);
252 }
253
ad_net_init_from_iif(struct common_audit_data * ad,struct lsm_network_audit * net,int ifindex,u16 family)254 static void ad_net_init_from_iif(struct common_audit_data *ad,
255 struct lsm_network_audit *net,
256 int ifindex, u16 family)
257 {
258 __ad_net_init(ad, net, ifindex, NULL, family);
259 }
260
261 /*
262 * get the objective security ID of a task
263 */
task_sid_obj(const struct task_struct * task)264 static inline u32 task_sid_obj(const struct task_struct *task)
265 {
266 u32 sid;
267
268 rcu_read_lock();
269 sid = cred_sid(__task_cred(task));
270 rcu_read_unlock();
271 return sid;
272 }
273
274 static int inode_doinit_with_dentry(struct inode *inode, struct dentry *opt_dentry);
275
276 /*
277 * Try reloading inode security labels that have been marked as invalid. The
278 * @may_sleep parameter indicates when sleeping and thus reloading labels is
279 * allowed; when set to false, returns -ECHILD when the label is
280 * invalid. The @dentry parameter should be set to a dentry of the inode.
281 */
__inode_security_revalidate(struct inode * inode,struct dentry * dentry,bool may_sleep)282 static int __inode_security_revalidate(struct inode *inode,
283 struct dentry *dentry,
284 bool may_sleep)
285 {
286 if (!selinux_initialized())
287 return 0;
288
289 if (may_sleep)
290 might_sleep();
291 else
292 return -ECHILD;
293
294 /*
295 * Check to ensure that an inode's SELinux state is valid and try
296 * reloading the inode security label if necessary. This will fail if
297 * @dentry is NULL and no dentry for this inode can be found; in that
298 * case, continue using the old label.
299 */
300 inode_doinit_with_dentry(inode, dentry);
301 return 0;
302 }
303
inode_security_novalidate(struct inode * inode)304 static struct inode_security_struct *inode_security_novalidate(struct inode *inode)
305 {
306 return selinux_inode(inode);
307 }
308
inode_security_rcu(struct inode * inode,bool rcu)309 static inline struct inode_security_struct *inode_security_rcu(struct inode *inode,
310 bool rcu)
311 {
312 int rc;
313 struct inode_security_struct *isec = selinux_inode(inode);
314
315 /* check below is racy, but revalidate will recheck with lock held */
316 if (data_race(likely(isec->initialized == LABEL_INITIALIZED)))
317 return isec;
318 rc = __inode_security_revalidate(inode, NULL, !rcu);
319 if (rc)
320 return ERR_PTR(rc);
321 return isec;
322 }
323
324 /*
325 * Get the security label of an inode.
326 */
inode_security(struct inode * inode)327 static inline struct inode_security_struct *inode_security(struct inode *inode)
328 {
329 struct inode_security_struct *isec = selinux_inode(inode);
330
331 /* check below is racy, but revalidate will recheck with lock held */
332 if (data_race(likely(isec->initialized == LABEL_INITIALIZED)))
333 return isec;
334 __inode_security_revalidate(inode, NULL, true);
335 return isec;
336 }
337
backing_inode_security_novalidate(struct dentry * dentry)338 static inline struct inode_security_struct *backing_inode_security_novalidate(struct dentry *dentry)
339 {
340 return selinux_inode(d_backing_inode(dentry));
341 }
342
343 /*
344 * Get the security label of a dentry's backing inode.
345 */
backing_inode_security(struct dentry * dentry)346 static inline struct inode_security_struct *backing_inode_security(struct dentry *dentry)
347 {
348 struct inode *inode = d_backing_inode(dentry);
349 struct inode_security_struct *isec = selinux_inode(inode);
350
351 /* check below is racy, but revalidate will recheck with lock held */
352 if (data_race(likely(isec->initialized == LABEL_INITIALIZED)))
353 return isec;
354 __inode_security_revalidate(inode, dentry, true);
355 return isec;
356 }
357
inode_free_security(struct inode * inode)358 static void inode_free_security(struct inode *inode)
359 {
360 struct inode_security_struct *isec = selinux_inode(inode);
361 struct superblock_security_struct *sbsec;
362
363 if (!isec)
364 return;
365 sbsec = selinux_superblock(inode->i_sb);
366 /*
367 * As not all inode security structures are in a list, we check for
368 * empty list outside of the lock to make sure that we won't waste
369 * time taking a lock doing nothing.
370 *
371 * The list_del_init() function can be safely called more than once.
372 * It should not be possible for this function to be called with
373 * concurrent list_add(), but for better safety against future changes
374 * in the code, we use list_empty_careful() here.
375 */
376 if (!list_empty_careful(&isec->list)) {
377 spin_lock(&sbsec->isec_lock);
378 list_del_init(&isec->list);
379 spin_unlock(&sbsec->isec_lock);
380 }
381 }
382
383 struct selinux_mnt_opts {
384 u32 fscontext_sid;
385 u32 context_sid;
386 u32 rootcontext_sid;
387 u32 defcontext_sid;
388 };
389
selinux_free_mnt_opts(void * mnt_opts)390 static void selinux_free_mnt_opts(void *mnt_opts)
391 {
392 kfree(mnt_opts);
393 }
394
395 enum {
396 Opt_error = -1,
397 Opt_context = 0,
398 Opt_defcontext = 1,
399 Opt_fscontext = 2,
400 Opt_rootcontext = 3,
401 Opt_seclabel = 4,
402 };
403
404 #define A(s, has_arg) {#s, sizeof(#s) - 1, Opt_##s, has_arg}
405 static const struct {
406 const char *name;
407 int len;
408 int opt;
409 bool has_arg;
410 } tokens[] = {
411 A(context, true),
412 A(fscontext, true),
413 A(defcontext, true),
414 A(rootcontext, true),
415 A(seclabel, false),
416 };
417 #undef A
418
match_opt_prefix(char * s,int l,char ** arg)419 static int match_opt_prefix(char *s, int l, char **arg)
420 {
421 unsigned int i;
422
423 for (i = 0; i < ARRAY_SIZE(tokens); i++) {
424 size_t len = tokens[i].len;
425 if (len > l || memcmp(s, tokens[i].name, len))
426 continue;
427 if (tokens[i].has_arg) {
428 if (len == l || s[len] != '=')
429 continue;
430 *arg = s + len + 1;
431 } else if (len != l)
432 continue;
433 return tokens[i].opt;
434 }
435 return Opt_error;
436 }
437
438 #define SEL_MOUNT_FAIL_MSG "SELinux: duplicate or incompatible mount options\n"
439
may_context_mount_sb_relabel(u32 sid,struct superblock_security_struct * sbsec,const struct cred * cred)440 static int may_context_mount_sb_relabel(u32 sid,
441 struct superblock_security_struct *sbsec,
442 const struct cred *cred)
443 {
444 const struct cred_security_struct *crsec = selinux_cred(cred);
445 int rc;
446
447 rc = avc_has_perm(crsec->sid, sbsec->sid, SECCLASS_FILESYSTEM,
448 FILESYSTEM__RELABELFROM, NULL);
449 if (rc)
450 return rc;
451
452 rc = avc_has_perm(crsec->sid, sid, SECCLASS_FILESYSTEM,
453 FILESYSTEM__RELABELTO, NULL);
454 return rc;
455 }
456
may_context_mount_inode_relabel(u32 sid,struct superblock_security_struct * sbsec,const struct cred * cred)457 static int may_context_mount_inode_relabel(u32 sid,
458 struct superblock_security_struct *sbsec,
459 const struct cred *cred)
460 {
461 const struct cred_security_struct *crsec = selinux_cred(cred);
462 int rc;
463 rc = avc_has_perm(crsec->sid, sbsec->sid, SECCLASS_FILESYSTEM,
464 FILESYSTEM__RELABELFROM, NULL);
465 if (rc)
466 return rc;
467
468 rc = avc_has_perm(sid, sbsec->sid, SECCLASS_FILESYSTEM,
469 FILESYSTEM__ASSOCIATE, NULL);
470 return rc;
471 }
472
selinux_is_genfs_special_handling(struct super_block * sb)473 static int selinux_is_genfs_special_handling(struct super_block *sb)
474 {
475 /* Special handling. Genfs but also in-core setxattr handler */
476 return !strcmp(sb->s_type->name, "sysfs") ||
477 !strcmp(sb->s_type->name, "pstore") ||
478 !strcmp(sb->s_type->name, "debugfs") ||
479 !strcmp(sb->s_type->name, "tracefs") ||
480 !strcmp(sb->s_type->name, "rootfs") ||
481 (selinux_policycap_cgroupseclabel() &&
482 (!strcmp(sb->s_type->name, "cgroup") ||
483 !strcmp(sb->s_type->name, "cgroup2"))) ||
484 (selinux_policycap_functionfs_seclabel() &&
485 !strcmp(sb->s_type->name, "functionfs"));
486 }
487
selinux_is_sblabel_mnt(struct super_block * sb)488 static int selinux_is_sblabel_mnt(struct super_block *sb)
489 {
490 struct superblock_security_struct *sbsec = selinux_superblock(sb);
491
492 /*
493 * IMPORTANT: Double-check logic in this function when adding a new
494 * SECURITY_FS_USE_* definition!
495 */
496 BUILD_BUG_ON(SECURITY_FS_USE_MAX != 7);
497
498 switch (sbsec->behavior) {
499 case SECURITY_FS_USE_XATTR:
500 case SECURITY_FS_USE_TRANS:
501 case SECURITY_FS_USE_TASK:
502 case SECURITY_FS_USE_NATIVE:
503 return 1;
504
505 case SECURITY_FS_USE_GENFS:
506 return selinux_is_genfs_special_handling(sb);
507
508 /* Never allow relabeling on context mounts */
509 case SECURITY_FS_USE_MNTPOINT:
510 case SECURITY_FS_USE_NONE:
511 default:
512 return 0;
513 }
514 }
515
sb_check_xattr_support(struct super_block * sb)516 static int sb_check_xattr_support(struct super_block *sb)
517 {
518 struct superblock_security_struct *sbsec = selinux_superblock(sb);
519 struct dentry *root = sb->s_root;
520 struct inode *root_inode = d_backing_inode(root);
521 u32 sid;
522 int rc;
523
524 /*
525 * Make sure that the xattr handler exists and that no
526 * error other than -ENODATA is returned by getxattr on
527 * the root directory. -ENODATA is ok, as this may be
528 * the first boot of the SELinux kernel before we have
529 * assigned xattr values to the filesystem.
530 */
531 if (!(root_inode->i_opflags & IOP_XATTR)) {
532 pr_warn("SELinux: (dev %s, type %s) has no xattr support\n",
533 sb->s_id, sb->s_type->name);
534 goto fallback;
535 }
536
537 rc = __vfs_getxattr(root, root_inode, XATTR_NAME_SELINUX, NULL, 0);
538 if (rc < 0 && rc != -ENODATA) {
539 if (rc == -EOPNOTSUPP) {
540 pr_warn("SELinux: (dev %s, type %s) has no security xattr handler\n",
541 sb->s_id, sb->s_type->name);
542 goto fallback;
543 } else {
544 pr_warn("SELinux: (dev %s, type %s) getxattr errno %d\n",
545 sb->s_id, sb->s_type->name, -rc);
546 return rc;
547 }
548 }
549 return 0;
550
551 fallback:
552 /* No xattr support - try to fallback to genfs if possible. */
553 rc = security_genfs_sid(sb->s_type->name, "/",
554 SECCLASS_DIR, &sid);
555 if (rc)
556 return -EOPNOTSUPP;
557
558 pr_warn("SELinux: (dev %s, type %s) falling back to genfs\n",
559 sb->s_id, sb->s_type->name);
560 sbsec->behavior = SECURITY_FS_USE_GENFS;
561 sbsec->sid = sid;
562 return 0;
563 }
564
sb_finish_set_opts(struct super_block * sb)565 static int sb_finish_set_opts(struct super_block *sb)
566 {
567 struct superblock_security_struct *sbsec = selinux_superblock(sb);
568 struct dentry *root = sb->s_root;
569 struct inode *root_inode = d_backing_inode(root);
570 int rc = 0;
571
572 if (sbsec->behavior == SECURITY_FS_USE_XATTR) {
573 rc = sb_check_xattr_support(sb);
574 if (rc)
575 return rc;
576 }
577
578 sbsec->flags |= SE_SBINITIALIZED;
579
580 /*
581 * Explicitly set or clear SBLABEL_MNT. It's not sufficient to simply
582 * leave the flag untouched because sb_clone_mnt_opts might be handing
583 * us a superblock that needs the flag to be cleared.
584 */
585 if (selinux_is_sblabel_mnt(sb))
586 sbsec->flags |= SBLABEL_MNT;
587 else
588 sbsec->flags &= ~SBLABEL_MNT;
589
590 /* Initialize the root inode. */
591 rc = inode_doinit_with_dentry(root_inode, root);
592
593 /* Initialize any other inodes associated with the superblock, e.g.
594 inodes created prior to initial policy load or inodes created
595 during get_sb by a pseudo filesystem that directly
596 populates itself. */
597 spin_lock(&sbsec->isec_lock);
598 while (!list_empty(&sbsec->isec_head)) {
599 struct inode_security_struct *isec =
600 list_first_entry(&sbsec->isec_head,
601 struct inode_security_struct, list);
602 struct inode *inode = isec->inode;
603 list_del_init(&isec->list);
604 spin_unlock(&sbsec->isec_lock);
605 inode = igrab(inode);
606 if (inode) {
607 if (!IS_PRIVATE(inode))
608 inode_doinit_with_dentry(inode, NULL);
609 iput(inode);
610 }
611 spin_lock(&sbsec->isec_lock);
612 }
613 spin_unlock(&sbsec->isec_lock);
614 return rc;
615 }
616
bad_option(struct superblock_security_struct * sbsec,char flag,u32 old_sid,u32 new_sid)617 static int bad_option(struct superblock_security_struct *sbsec, char flag,
618 u32 old_sid, u32 new_sid)
619 {
620 char mnt_flags = sbsec->flags & SE_MNTMASK;
621
622 /* check if the old mount command had the same options */
623 if (sbsec->flags & SE_SBINITIALIZED)
624 if (!(sbsec->flags & flag) ||
625 (old_sid != new_sid))
626 return 1;
627
628 /* check if we were passed the same options twice,
629 * aka someone passed context=a,context=b
630 */
631 if (!(sbsec->flags & SE_SBINITIALIZED))
632 if (mnt_flags & flag)
633 return 1;
634 return 0;
635 }
636
637 /*
638 * Allow filesystems with binary mount data to explicitly set mount point
639 * labeling information.
640 */
selinux_set_mnt_opts(struct super_block * sb,void * mnt_opts,unsigned long kern_flags,unsigned long * set_kern_flags)641 static int selinux_set_mnt_opts(struct super_block *sb,
642 void *mnt_opts,
643 unsigned long kern_flags,
644 unsigned long *set_kern_flags)
645 {
646 const struct cred *cred = current_cred();
647 struct superblock_security_struct *sbsec = selinux_superblock(sb);
648 struct dentry *root = sb->s_root;
649 struct selinux_mnt_opts *opts = mnt_opts;
650 struct inode_security_struct *root_isec;
651 u32 fscontext_sid = 0, context_sid = 0, rootcontext_sid = 0;
652 u32 defcontext_sid = 0;
653 int rc = 0;
654
655 /*
656 * Specifying internal flags without providing a place to
657 * place the results is not allowed
658 */
659 if (kern_flags && !set_kern_flags)
660 return -EINVAL;
661
662 mutex_lock(&sbsec->lock);
663
664 if (!selinux_initialized()) {
665 if (!opts) {
666 /* Defer initialization until selinux_complete_init,
667 after the initial policy is loaded and the security
668 server is ready to handle calls. */
669 if (kern_flags & SECURITY_LSM_NATIVE_LABELS) {
670 sbsec->flags |= SE_SBNATIVE;
671 *set_kern_flags |= SECURITY_LSM_NATIVE_LABELS;
672 }
673 goto out;
674 }
675 rc = -EINVAL;
676 pr_warn("SELinux: Unable to set superblock options "
677 "before the security server is initialized\n");
678 goto out;
679 }
680
681 /*
682 * Binary mount data FS will come through this function twice. Once
683 * from an explicit call and once from the generic calls from the vfs.
684 * Since the generic VFS calls will not contain any security mount data
685 * we need to skip the double mount verification.
686 *
687 * This does open a hole in which we will not notice if the first
688 * mount using this sb set explicit options and a second mount using
689 * this sb does not set any security options. (The first options
690 * will be used for both mounts)
691 */
692 if ((sbsec->flags & SE_SBINITIALIZED) && (sb->s_type->fs_flags & FS_BINARY_MOUNTDATA)
693 && !opts)
694 goto out;
695
696 root_isec = backing_inode_security_novalidate(root);
697
698 /*
699 * parse the mount options, check if they are valid sids.
700 * also check if someone is trying to mount the same sb more
701 * than once with different security options.
702 */
703 if (opts) {
704 if (opts->fscontext_sid) {
705 fscontext_sid = opts->fscontext_sid;
706 if (bad_option(sbsec, FSCONTEXT_MNT, sbsec->sid,
707 fscontext_sid))
708 goto out_double_mount;
709 sbsec->flags |= FSCONTEXT_MNT;
710 }
711 if (opts->context_sid) {
712 context_sid = opts->context_sid;
713 if (bad_option(sbsec, CONTEXT_MNT, sbsec->mntpoint_sid,
714 context_sid))
715 goto out_double_mount;
716 sbsec->flags |= CONTEXT_MNT;
717 }
718 if (opts->rootcontext_sid) {
719 rootcontext_sid = opts->rootcontext_sid;
720 if (bad_option(sbsec, ROOTCONTEXT_MNT, root_isec->sid,
721 rootcontext_sid))
722 goto out_double_mount;
723 sbsec->flags |= ROOTCONTEXT_MNT;
724 }
725 if (opts->defcontext_sid) {
726 defcontext_sid = opts->defcontext_sid;
727 if (bad_option(sbsec, DEFCONTEXT_MNT, sbsec->def_sid,
728 defcontext_sid))
729 goto out_double_mount;
730 sbsec->flags |= DEFCONTEXT_MNT;
731 }
732 }
733
734 if (sbsec->flags & SE_SBINITIALIZED) {
735 /* previously mounted with options, but not on this attempt? */
736 if ((sbsec->flags & SE_MNTMASK) && !opts)
737 goto out_double_mount;
738 rc = 0;
739 goto out;
740 }
741
742 sbsec->creator_sid = current_sid();
743
744 if (strcmp(sb->s_type->name, "proc") == 0)
745 sbsec->flags |= SE_SBPROC | SE_SBGENFS;
746
747 if (!strcmp(sb->s_type->name, "debugfs") ||
748 !strcmp(sb->s_type->name, "tracefs") ||
749 !strcmp(sb->s_type->name, "binder") ||
750 !strcmp(sb->s_type->name, "bpf") ||
751 !strcmp(sb->s_type->name, "pstore") ||
752 !strcmp(sb->s_type->name, "securityfs") ||
753 (selinux_policycap_functionfs_seclabel() &&
754 !strcmp(sb->s_type->name, "functionfs")))
755 sbsec->flags |= SE_SBGENFS;
756
757 if (!strcmp(sb->s_type->name, "sysfs") ||
758 !strcmp(sb->s_type->name, "cgroup") ||
759 !strcmp(sb->s_type->name, "cgroup2"))
760 sbsec->flags |= SE_SBGENFS | SE_SBGENFS_XATTR;
761
762 if (!sbsec->behavior) {
763 /*
764 * Determine the labeling behavior to use for this
765 * filesystem type.
766 */
767 rc = security_fs_use(sb);
768 if (rc) {
769 pr_warn("%s: security_fs_use(%s) returned %d\n",
770 __func__, sb->s_type->name, rc);
771 goto out;
772 }
773 }
774
775 /*
776 * If this is a user namespace mount and the filesystem type is not
777 * explicitly whitelisted, then no contexts are allowed on the command
778 * line and security labels must be ignored.
779 */
780 if (sb->s_user_ns != &init_user_ns &&
781 strcmp(sb->s_type->name, "tmpfs") &&
782 strcmp(sb->s_type->name, "ramfs") &&
783 strcmp(sb->s_type->name, "devpts") &&
784 strcmp(sb->s_type->name, "overlay")) {
785 if (context_sid || fscontext_sid || rootcontext_sid ||
786 defcontext_sid) {
787 rc = -EACCES;
788 goto out;
789 }
790 if (sbsec->behavior == SECURITY_FS_USE_XATTR) {
791 sbsec->behavior = SECURITY_FS_USE_MNTPOINT;
792 rc = security_transition_sid(current_sid(),
793 current_sid(),
794 SECCLASS_FILE, NULL,
795 &sbsec->mntpoint_sid);
796 if (rc)
797 goto out;
798 }
799 goto out_set_opts;
800 }
801
802 /* sets the context of the superblock for the fs being mounted. */
803 if (fscontext_sid) {
804 rc = may_context_mount_sb_relabel(fscontext_sid, sbsec, cred);
805 if (rc)
806 goto out;
807
808 sbsec->sid = fscontext_sid;
809 }
810
811 /*
812 * Switch to using mount point labeling behavior.
813 * sets the label used on all file below the mountpoint, and will set
814 * the superblock context if not already set.
815 */
816 if (sbsec->flags & SE_SBNATIVE) {
817 /*
818 * This means we are initializing a superblock that has been
819 * mounted before the SELinux was initialized and the
820 * filesystem requested native labeling. We had already
821 * returned SECURITY_LSM_NATIVE_LABELS in *set_kern_flags
822 * in the original mount attempt, so now we just need to set
823 * the SECURITY_FS_USE_NATIVE behavior.
824 */
825 sbsec->behavior = SECURITY_FS_USE_NATIVE;
826 } else if (kern_flags & SECURITY_LSM_NATIVE_LABELS && !context_sid) {
827 sbsec->behavior = SECURITY_FS_USE_NATIVE;
828 *set_kern_flags |= SECURITY_LSM_NATIVE_LABELS;
829 }
830
831 if (context_sid) {
832 if (!fscontext_sid) {
833 rc = may_context_mount_sb_relabel(context_sid, sbsec,
834 cred);
835 if (rc)
836 goto out;
837 sbsec->sid = context_sid;
838 } else {
839 rc = may_context_mount_inode_relabel(context_sid, sbsec,
840 cred);
841 if (rc)
842 goto out;
843 }
844 if (!rootcontext_sid)
845 rootcontext_sid = context_sid;
846
847 sbsec->mntpoint_sid = context_sid;
848 sbsec->behavior = SECURITY_FS_USE_MNTPOINT;
849 }
850
851 if (rootcontext_sid) {
852 rc = may_context_mount_inode_relabel(rootcontext_sid, sbsec,
853 cred);
854 if (rc)
855 goto out;
856
857 root_isec->sid = rootcontext_sid;
858 root_isec->initialized = LABEL_INITIALIZED;
859 }
860
861 if (defcontext_sid) {
862 if (sbsec->behavior != SECURITY_FS_USE_XATTR &&
863 sbsec->behavior != SECURITY_FS_USE_NATIVE) {
864 rc = -EINVAL;
865 pr_warn("SELinux: defcontext option is "
866 "invalid for this filesystem type\n");
867 goto out;
868 }
869
870 if (defcontext_sid != sbsec->def_sid) {
871 rc = may_context_mount_inode_relabel(defcontext_sid,
872 sbsec, cred);
873 if (rc)
874 goto out;
875 }
876
877 sbsec->def_sid = defcontext_sid;
878 }
879
880 out_set_opts:
881 rc = sb_finish_set_opts(sb);
882 out:
883 mutex_unlock(&sbsec->lock);
884 return rc;
885 out_double_mount:
886 rc = -EINVAL;
887 pr_warn("SELinux: mount invalid. Same superblock, different "
888 "security settings for (dev %s, type %s)\n", sb->s_id,
889 sb->s_type->name);
890 goto out;
891 }
892
selinux_cmp_sb_context(const struct super_block * oldsb,const struct super_block * newsb)893 static int selinux_cmp_sb_context(const struct super_block *oldsb,
894 const struct super_block *newsb)
895 {
896 struct superblock_security_struct *old = selinux_superblock(oldsb);
897 struct superblock_security_struct *new = selinux_superblock(newsb);
898 char oldflags = old->flags & SE_MNTMASK;
899 char newflags = new->flags & SE_MNTMASK;
900
901 if (oldflags != newflags)
902 goto mismatch;
903 if ((oldflags & FSCONTEXT_MNT) && old->sid != new->sid)
904 goto mismatch;
905 if ((oldflags & CONTEXT_MNT) && old->mntpoint_sid != new->mntpoint_sid)
906 goto mismatch;
907 if ((oldflags & DEFCONTEXT_MNT) && old->def_sid != new->def_sid)
908 goto mismatch;
909 if (oldflags & ROOTCONTEXT_MNT) {
910 struct inode_security_struct *oldroot = backing_inode_security(oldsb->s_root);
911 struct inode_security_struct *newroot = backing_inode_security(newsb->s_root);
912 if (oldroot->sid != newroot->sid)
913 goto mismatch;
914 }
915 if (old->creator_sid != new->creator_sid)
916 goto mismatch;
917 return 0;
918 mismatch:
919 pr_warn("SELinux: mount invalid. Same superblock, "
920 "different security settings for (dev %s, "
921 "type %s)\n", newsb->s_id, newsb->s_type->name);
922 return -EBUSY;
923 }
924
selinux_sb_clone_mnt_opts(const struct super_block * oldsb,struct super_block * newsb,unsigned long kern_flags,unsigned long * set_kern_flags)925 static int selinux_sb_clone_mnt_opts(const struct super_block *oldsb,
926 struct super_block *newsb,
927 unsigned long kern_flags,
928 unsigned long *set_kern_flags)
929 {
930 int rc = 0;
931 const struct superblock_security_struct *oldsbsec =
932 selinux_superblock(oldsb);
933 struct superblock_security_struct *newsbsec = selinux_superblock(newsb);
934
935 int set_fscontext = (oldsbsec->flags & FSCONTEXT_MNT);
936 int set_context = (oldsbsec->flags & CONTEXT_MNT);
937 int set_rootcontext = (oldsbsec->flags & ROOTCONTEXT_MNT);
938
939 /*
940 * Specifying internal flags without providing a place to
941 * place the results is not allowed.
942 */
943 if (kern_flags && !set_kern_flags)
944 return -EINVAL;
945
946 mutex_lock(&newsbsec->lock);
947
948 /*
949 * if the parent was able to be mounted it clearly had no special lsm
950 * mount options. thus we can safely deal with this superblock later
951 */
952 if (!selinux_initialized()) {
953 if (kern_flags & SECURITY_LSM_NATIVE_LABELS) {
954 newsbsec->flags |= SE_SBNATIVE;
955 *set_kern_flags |= SECURITY_LSM_NATIVE_LABELS;
956 }
957 goto out;
958 }
959
960 /* how can we clone if the old one wasn't set up?? */
961 BUG_ON(!(oldsbsec->flags & SE_SBINITIALIZED));
962
963 /* if fs is reusing a sb, make sure that the contexts match */
964 if (newsbsec->flags & SE_SBINITIALIZED) {
965 mutex_unlock(&newsbsec->lock);
966 if ((kern_flags & SECURITY_LSM_NATIVE_LABELS) && !set_context)
967 *set_kern_flags |= SECURITY_LSM_NATIVE_LABELS;
968 return selinux_cmp_sb_context(oldsb, newsb);
969 }
970
971 newsbsec->flags = oldsbsec->flags;
972
973 newsbsec->sid = oldsbsec->sid;
974 newsbsec->def_sid = oldsbsec->def_sid;
975 newsbsec->behavior = oldsbsec->behavior;
976 newsbsec->creator_sid = oldsbsec->creator_sid;
977
978 if (newsbsec->behavior == SECURITY_FS_USE_NATIVE &&
979 !(kern_flags & SECURITY_LSM_NATIVE_LABELS) && !set_context) {
980 rc = security_fs_use(newsb);
981 if (rc)
982 goto out;
983 }
984
985 if (kern_flags & SECURITY_LSM_NATIVE_LABELS && !set_context) {
986 newsbsec->behavior = SECURITY_FS_USE_NATIVE;
987 *set_kern_flags |= SECURITY_LSM_NATIVE_LABELS;
988 }
989
990 if (set_context) {
991 u32 sid = oldsbsec->mntpoint_sid;
992
993 if (!set_fscontext)
994 newsbsec->sid = sid;
995 if (!set_rootcontext) {
996 struct inode_security_struct *newisec = backing_inode_security(newsb->s_root);
997 newisec->sid = sid;
998 }
999 newsbsec->mntpoint_sid = sid;
1000 }
1001 if (set_rootcontext) {
1002 const struct inode_security_struct *oldisec = backing_inode_security(oldsb->s_root);
1003 struct inode_security_struct *newisec = backing_inode_security(newsb->s_root);
1004
1005 newisec->sid = oldisec->sid;
1006 }
1007
1008 sb_finish_set_opts(newsb);
1009 out:
1010 mutex_unlock(&newsbsec->lock);
1011 return rc;
1012 }
1013
1014 /*
1015 * NOTE: the caller is responsible for freeing the memory even if on error.
1016 */
selinux_add_opt(int token,const char * s,void ** mnt_opts)1017 static int selinux_add_opt(int token, const char *s, void **mnt_opts)
1018 {
1019 struct selinux_mnt_opts *opts = *mnt_opts;
1020 u32 *dst_sid;
1021 int rc;
1022
1023 if (token == Opt_seclabel)
1024 /* eaten and completely ignored */
1025 return 0;
1026 if (!s)
1027 return -EINVAL;
1028
1029 if (!selinux_initialized()) {
1030 pr_warn("SELinux: Unable to set superblock options before the security server is initialized\n");
1031 return -EINVAL;
1032 }
1033
1034 if (!opts) {
1035 opts = kzalloc_obj(*opts);
1036 if (!opts)
1037 return -ENOMEM;
1038 *mnt_opts = opts;
1039 }
1040
1041 switch (token) {
1042 case Opt_context:
1043 if (opts->context_sid || opts->defcontext_sid)
1044 goto err;
1045 dst_sid = &opts->context_sid;
1046 break;
1047 case Opt_fscontext:
1048 if (opts->fscontext_sid)
1049 goto err;
1050 dst_sid = &opts->fscontext_sid;
1051 break;
1052 case Opt_rootcontext:
1053 if (opts->rootcontext_sid)
1054 goto err;
1055 dst_sid = &opts->rootcontext_sid;
1056 break;
1057 case Opt_defcontext:
1058 if (opts->context_sid || opts->defcontext_sid)
1059 goto err;
1060 dst_sid = &opts->defcontext_sid;
1061 break;
1062 default:
1063 WARN_ON(1);
1064 return -EINVAL;
1065 }
1066 rc = security_context_str_to_sid(s, dst_sid, GFP_KERNEL);
1067 if (rc)
1068 pr_warn("SELinux: security_context_str_to_sid (%s) failed with errno=%d\n",
1069 s, rc);
1070 return rc;
1071
1072 err:
1073 pr_warn(SEL_MOUNT_FAIL_MSG);
1074 return -EINVAL;
1075 }
1076
show_sid(struct seq_file * m,u32 sid)1077 static int show_sid(struct seq_file *m, u32 sid)
1078 {
1079 char *context = NULL;
1080 u32 len;
1081 int rc;
1082
1083 rc = security_sid_to_context(sid, &context, &len);
1084 if (!rc) {
1085 bool has_comma = strchr(context, ',');
1086
1087 seq_putc(m, '=');
1088 if (has_comma)
1089 seq_putc(m, '\"');
1090 seq_escape(m, context, "\"\n\\");
1091 if (has_comma)
1092 seq_putc(m, '\"');
1093 }
1094 kfree(context);
1095 return rc;
1096 }
1097
selinux_sb_show_options(struct seq_file * m,struct super_block * sb)1098 static int selinux_sb_show_options(struct seq_file *m, struct super_block *sb)
1099 {
1100 struct superblock_security_struct *sbsec = selinux_superblock(sb);
1101 int rc;
1102
1103 if (!(sbsec->flags & SE_SBINITIALIZED))
1104 return 0;
1105
1106 if (!selinux_initialized())
1107 return 0;
1108
1109 if (sbsec->flags & FSCONTEXT_MNT) {
1110 seq_putc(m, ',');
1111 seq_puts(m, FSCONTEXT_STR);
1112 rc = show_sid(m, sbsec->sid);
1113 if (rc)
1114 return rc;
1115 }
1116 if (sbsec->flags & CONTEXT_MNT) {
1117 seq_putc(m, ',');
1118 seq_puts(m, CONTEXT_STR);
1119 rc = show_sid(m, sbsec->mntpoint_sid);
1120 if (rc)
1121 return rc;
1122 }
1123 if (sbsec->flags & DEFCONTEXT_MNT) {
1124 seq_putc(m, ',');
1125 seq_puts(m, DEFCONTEXT_STR);
1126 rc = show_sid(m, sbsec->def_sid);
1127 if (rc)
1128 return rc;
1129 }
1130 if (sbsec->flags & ROOTCONTEXT_MNT) {
1131 struct dentry *root = sb->s_root;
1132 struct inode_security_struct *isec = backing_inode_security(root);
1133 seq_putc(m, ',');
1134 seq_puts(m, ROOTCONTEXT_STR);
1135 rc = show_sid(m, isec->sid);
1136 if (rc)
1137 return rc;
1138 }
1139 if (sbsec->flags & SBLABEL_MNT) {
1140 seq_putc(m, ',');
1141 seq_puts(m, SECLABEL_STR);
1142 }
1143 return 0;
1144 }
1145
inode_mode_to_security_class(umode_t mode)1146 static inline u16 inode_mode_to_security_class(umode_t mode)
1147 {
1148 switch (mode & S_IFMT) {
1149 case S_IFSOCK:
1150 return SECCLASS_SOCK_FILE;
1151 case S_IFLNK:
1152 return SECCLASS_LNK_FILE;
1153 case S_IFREG:
1154 return SECCLASS_FILE;
1155 case S_IFBLK:
1156 return SECCLASS_BLK_FILE;
1157 case S_IFDIR:
1158 return SECCLASS_DIR;
1159 case S_IFCHR:
1160 return SECCLASS_CHR_FILE;
1161 case S_IFIFO:
1162 return SECCLASS_FIFO_FILE;
1163
1164 }
1165
1166 return SECCLASS_FILE;
1167 }
1168
default_protocol_stream(int protocol)1169 static inline int default_protocol_stream(int protocol)
1170 {
1171 return (protocol == IPPROTO_IP || protocol == IPPROTO_TCP ||
1172 protocol == IPPROTO_MPTCP);
1173 }
1174
default_protocol_dgram(int protocol)1175 static inline int default_protocol_dgram(int protocol)
1176 {
1177 return (protocol == IPPROTO_IP || protocol == IPPROTO_UDP);
1178 }
1179
socket_type_to_security_class(int family,int type,int protocol)1180 static inline u16 socket_type_to_security_class(int family, int type, int protocol)
1181 {
1182 bool extsockclass = selinux_policycap_extsockclass();
1183
1184 switch (family) {
1185 case PF_UNIX:
1186 switch (type) {
1187 case SOCK_STREAM:
1188 case SOCK_SEQPACKET:
1189 return SECCLASS_UNIX_STREAM_SOCKET;
1190 case SOCK_DGRAM:
1191 case SOCK_RAW:
1192 return SECCLASS_UNIX_DGRAM_SOCKET;
1193 }
1194 break;
1195 case PF_INET:
1196 case PF_INET6:
1197 switch (type) {
1198 case SOCK_STREAM:
1199 case SOCK_SEQPACKET:
1200 if (default_protocol_stream(protocol))
1201 return SECCLASS_TCP_SOCKET;
1202 else if (extsockclass && protocol == IPPROTO_SCTP)
1203 return SECCLASS_SCTP_SOCKET;
1204 else
1205 return SECCLASS_RAWIP_SOCKET;
1206 case SOCK_DGRAM:
1207 if (default_protocol_dgram(protocol))
1208 return SECCLASS_UDP_SOCKET;
1209 else if (extsockclass && (protocol == IPPROTO_ICMP ||
1210 protocol == IPPROTO_ICMPV6))
1211 return SECCLASS_ICMP_SOCKET;
1212 else
1213 return SECCLASS_RAWIP_SOCKET;
1214 default:
1215 return SECCLASS_RAWIP_SOCKET;
1216 }
1217 break;
1218 case PF_NETLINK:
1219 switch (protocol) {
1220 case NETLINK_ROUTE:
1221 return SECCLASS_NETLINK_ROUTE_SOCKET;
1222 case NETLINK_SOCK_DIAG:
1223 return SECCLASS_NETLINK_TCPDIAG_SOCKET;
1224 case NETLINK_NFLOG:
1225 return SECCLASS_NETLINK_NFLOG_SOCKET;
1226 case NETLINK_XFRM:
1227 return SECCLASS_NETLINK_XFRM_SOCKET;
1228 case NETLINK_SELINUX:
1229 return SECCLASS_NETLINK_SELINUX_SOCKET;
1230 case NETLINK_ISCSI:
1231 return SECCLASS_NETLINK_ISCSI_SOCKET;
1232 case NETLINK_AUDIT:
1233 return SECCLASS_NETLINK_AUDIT_SOCKET;
1234 case NETLINK_FIB_LOOKUP:
1235 return SECCLASS_NETLINK_FIB_LOOKUP_SOCKET;
1236 case NETLINK_CONNECTOR:
1237 return SECCLASS_NETLINK_CONNECTOR_SOCKET;
1238 case NETLINK_NETFILTER:
1239 return SECCLASS_NETLINK_NETFILTER_SOCKET;
1240 case NETLINK_DNRTMSG:
1241 return SECCLASS_NETLINK_DNRT_SOCKET;
1242 case NETLINK_KOBJECT_UEVENT:
1243 return SECCLASS_NETLINK_KOBJECT_UEVENT_SOCKET;
1244 case NETLINK_GENERIC:
1245 return SECCLASS_NETLINK_GENERIC_SOCKET;
1246 case NETLINK_SCSITRANSPORT:
1247 return SECCLASS_NETLINK_SCSITRANSPORT_SOCKET;
1248 case NETLINK_RDMA:
1249 return SECCLASS_NETLINK_RDMA_SOCKET;
1250 case NETLINK_CRYPTO:
1251 return SECCLASS_NETLINK_CRYPTO_SOCKET;
1252 default:
1253 return SECCLASS_NETLINK_SOCKET;
1254 }
1255 case PF_PACKET:
1256 return SECCLASS_PACKET_SOCKET;
1257 case PF_KEY:
1258 return SECCLASS_KEY_SOCKET;
1259 case PF_APPLETALK:
1260 return SECCLASS_APPLETALK_SOCKET;
1261 }
1262
1263 if (extsockclass) {
1264 switch (family) {
1265 case PF_AX25:
1266 return SECCLASS_AX25_SOCKET;
1267 case PF_IPX:
1268 return SECCLASS_IPX_SOCKET;
1269 case PF_NETROM:
1270 return SECCLASS_NETROM_SOCKET;
1271 case PF_ATMPVC:
1272 return SECCLASS_ATMPVC_SOCKET;
1273 case PF_X25:
1274 return SECCLASS_X25_SOCKET;
1275 case PF_ROSE:
1276 return SECCLASS_ROSE_SOCKET;
1277 case PF_DECnet:
1278 return SECCLASS_DECNET_SOCKET;
1279 case PF_ATMSVC:
1280 return SECCLASS_ATMSVC_SOCKET;
1281 case PF_RDS:
1282 return SECCLASS_RDS_SOCKET;
1283 case PF_IRDA:
1284 return SECCLASS_IRDA_SOCKET;
1285 case PF_PPPOX:
1286 return SECCLASS_PPPOX_SOCKET;
1287 case PF_LLC:
1288 return SECCLASS_LLC_SOCKET;
1289 case PF_CAN:
1290 return SECCLASS_CAN_SOCKET;
1291 case PF_TIPC:
1292 return SECCLASS_TIPC_SOCKET;
1293 case PF_BLUETOOTH:
1294 return SECCLASS_BLUETOOTH_SOCKET;
1295 case PF_IUCV:
1296 return SECCLASS_IUCV_SOCKET;
1297 case PF_RXRPC:
1298 return SECCLASS_RXRPC_SOCKET;
1299 case PF_ISDN:
1300 return SECCLASS_ISDN_SOCKET;
1301 case PF_PHONET:
1302 return SECCLASS_PHONET_SOCKET;
1303 case PF_IEEE802154:
1304 return SECCLASS_IEEE802154_SOCKET;
1305 case PF_CAIF:
1306 return SECCLASS_CAIF_SOCKET;
1307 case PF_ALG:
1308 return SECCLASS_ALG_SOCKET;
1309 case PF_NFC:
1310 return SECCLASS_NFC_SOCKET;
1311 case PF_VSOCK:
1312 return SECCLASS_VSOCK_SOCKET;
1313 case PF_KCM:
1314 return SECCLASS_KCM_SOCKET;
1315 case PF_QIPCRTR:
1316 return SECCLASS_QIPCRTR_SOCKET;
1317 case PF_SMC:
1318 return SECCLASS_SMC_SOCKET;
1319 case PF_XDP:
1320 return SECCLASS_XDP_SOCKET;
1321 case PF_MCTP:
1322 return SECCLASS_MCTP_SOCKET;
1323 #if PF_MAX > 46
1324 #error New address family defined, please update this function.
1325 #endif
1326 }
1327 }
1328
1329 return SECCLASS_SOCKET;
1330 }
1331
selinux_genfs_get_sid(struct dentry * dentry,u16 tclass,u16 flags,u32 * sid)1332 static int selinux_genfs_get_sid(struct dentry *dentry,
1333 u16 tclass,
1334 u16 flags,
1335 u32 *sid)
1336 {
1337 int rc;
1338 struct super_block *sb = dentry->d_sb;
1339 char *buffer, *path;
1340
1341 buffer = kmalloc(PATH_MAX, GFP_KERNEL);
1342 if (!buffer)
1343 return -ENOMEM;
1344
1345 path = dentry_path_raw(dentry, buffer, PATH_MAX);
1346 if (IS_ERR(path))
1347 rc = PTR_ERR(path);
1348 else {
1349 if (flags & SE_SBPROC) {
1350 /* each process gets a /proc/PID/ entry. Strip off the
1351 * PID part to get a valid selinux labeling.
1352 * e.g. /proc/1/net/rpc/nfs -> /net/rpc/nfs */
1353 while (path[1] >= '0' && path[1] <= '9') {
1354 path[1] = '/';
1355 path++;
1356 }
1357 }
1358 rc = security_genfs_sid(sb->s_type->name,
1359 path, tclass, sid);
1360 if (rc == -ENOENT) {
1361 /* No match in policy, mark as unlabeled. */
1362 *sid = SECINITSID_UNLABELED;
1363 rc = 0;
1364 }
1365 }
1366 kfree(buffer);
1367 return rc;
1368 }
1369
inode_doinit_use_xattr(struct inode * inode,struct dentry * dentry,u32 def_sid,u32 * sid)1370 static int inode_doinit_use_xattr(struct inode *inode, struct dentry *dentry,
1371 u32 def_sid, u32 *sid)
1372 {
1373 #define INITCONTEXTLEN 255
1374 char *context;
1375 unsigned int len;
1376 int rc;
1377
1378 len = INITCONTEXTLEN;
1379 context = kmalloc(len + 1, GFP_NOFS);
1380 if (!context)
1381 return -ENOMEM;
1382
1383 context[len] = '\0';
1384 rc = __vfs_getxattr(dentry, inode, XATTR_NAME_SELINUX, context, len);
1385 if (rc == -ERANGE) {
1386 kfree(context);
1387
1388 /* Need a larger buffer. Query for the right size. */
1389 rc = __vfs_getxattr(dentry, inode, XATTR_NAME_SELINUX, NULL, 0);
1390 if (rc < 0)
1391 return rc;
1392
1393 len = rc;
1394 context = kmalloc(len + 1, GFP_NOFS);
1395 if (!context)
1396 return -ENOMEM;
1397
1398 context[len] = '\0';
1399 rc = __vfs_getxattr(dentry, inode, XATTR_NAME_SELINUX,
1400 context, len);
1401 }
1402 if (rc < 0) {
1403 kfree(context);
1404 if (rc != -ENODATA) {
1405 pr_warn("SELinux: %s: getxattr returned %d for dev=%s ino=%llu\n",
1406 __func__, -rc, inode->i_sb->s_id, inode->i_ino);
1407 return rc;
1408 }
1409 *sid = def_sid;
1410 return 0;
1411 }
1412
1413 rc = security_context_to_sid_default(context, rc, sid,
1414 def_sid, GFP_NOFS);
1415 if (rc) {
1416 char *dev = inode->i_sb->s_id;
1417 u64 ino = inode->i_ino;
1418
1419 if (rc == -EINVAL) {
1420 pr_notice_ratelimited("SELinux: inode=%llu on dev=%s was found to have an invalid context=%s. This indicates you may need to relabel the inode or the filesystem in question.\n",
1421 ino, dev, context);
1422 } else {
1423 pr_warn("SELinux: %s: context_to_sid(%s) returned %d for dev=%s ino=%llu\n",
1424 __func__, context, -rc, dev, ino);
1425 }
1426 }
1427 kfree(context);
1428 return 0;
1429 }
1430
1431 /* The inode's security attributes must be initialized before first use. */
inode_doinit_with_dentry(struct inode * inode,struct dentry * opt_dentry)1432 static int inode_doinit_with_dentry(struct inode *inode, struct dentry *opt_dentry)
1433 {
1434 struct superblock_security_struct *sbsec = NULL;
1435 struct inode_security_struct *isec = selinux_inode(inode);
1436 u32 task_sid, sid = 0;
1437 u16 sclass;
1438 struct dentry *dentry;
1439 int rc = 0;
1440
1441 /* check below is racy, but we will recheck with lock held */
1442 if (data_race(isec->initialized == LABEL_INITIALIZED))
1443 return 0;
1444
1445 spin_lock(&isec->lock);
1446 if (isec->initialized == LABEL_INITIALIZED)
1447 goto out_unlock;
1448
1449 if (isec->sclass == SECCLASS_FILE)
1450 isec->sclass = inode_mode_to_security_class(inode->i_mode);
1451
1452 sbsec = selinux_superblock(inode->i_sb);
1453 if (!(sbsec->flags & SE_SBINITIALIZED)) {
1454 /* Defer initialization until selinux_complete_init,
1455 after the initial policy is loaded and the security
1456 server is ready to handle calls. */
1457 spin_lock(&sbsec->isec_lock);
1458 if (list_empty(&isec->list))
1459 list_add(&isec->list, &sbsec->isec_head);
1460 spin_unlock(&sbsec->isec_lock);
1461 goto out_unlock;
1462 }
1463
1464 sclass = isec->sclass;
1465 task_sid = isec->task_sid;
1466 sid = isec->sid;
1467 isec->initialized = LABEL_PENDING;
1468 spin_unlock(&isec->lock);
1469
1470 switch (sbsec->behavior) {
1471 /*
1472 * In case of SECURITY_FS_USE_NATIVE we need to re-fetch the labels
1473 * via xattr when called from delayed_superblock_init().
1474 */
1475 case SECURITY_FS_USE_NATIVE:
1476 case SECURITY_FS_USE_XATTR:
1477 if (!(inode->i_opflags & IOP_XATTR)) {
1478 sid = sbsec->def_sid;
1479 break;
1480 }
1481 /* Need a dentry, since the xattr API requires one.
1482 Life would be simpler if we could just pass the inode. */
1483 if (opt_dentry) {
1484 /* Called from d_instantiate or d_splice_alias. */
1485 dentry = dget(opt_dentry);
1486 } else {
1487 /*
1488 * Called from selinux_complete_init, try to find a dentry.
1489 * Some filesystems really want a connected one, so try
1490 * that first. We could split SECURITY_FS_USE_XATTR in
1491 * two, depending upon that...
1492 */
1493 dentry = d_find_alias(inode);
1494 if (!dentry)
1495 dentry = d_find_any_alias(inode);
1496 }
1497 if (!dentry) {
1498 /*
1499 * this is can be hit on boot when a file is accessed
1500 * before the policy is loaded. When we load policy we
1501 * may find inodes that have no dentry on the
1502 * sbsec->isec_head list. No reason to complain as these
1503 * will get fixed up the next time we go through
1504 * inode_doinit with a dentry, before these inodes could
1505 * be used again by userspace.
1506 */
1507 goto out_invalid;
1508 }
1509
1510 rc = inode_doinit_use_xattr(inode, dentry, sbsec->def_sid,
1511 &sid);
1512 dput(dentry);
1513 if (rc)
1514 goto out;
1515 break;
1516 case SECURITY_FS_USE_TASK:
1517 sid = task_sid;
1518 break;
1519 case SECURITY_FS_USE_TRANS:
1520 /* Default to the fs SID. */
1521 sid = sbsec->sid;
1522
1523 /* Try to obtain a transition SID. */
1524 rc = security_transition_sid(task_sid, sid,
1525 sclass, NULL, &sid);
1526 if (rc)
1527 goto out;
1528 break;
1529 case SECURITY_FS_USE_MNTPOINT:
1530 sid = sbsec->mntpoint_sid;
1531 break;
1532 default:
1533 /* Default to the fs superblock SID. */
1534 sid = sbsec->sid;
1535
1536 if ((sbsec->flags & SE_SBGENFS) &&
1537 (!S_ISLNK(inode->i_mode) ||
1538 selinux_policycap_genfs_seclabel_symlinks())) {
1539 /* We must have a dentry to determine the label on
1540 * procfs inodes */
1541 if (opt_dentry) {
1542 /* Called from d_instantiate or
1543 * d_splice_alias. */
1544 dentry = dget(opt_dentry);
1545 } else {
1546 /* Called from selinux_complete_init, try to
1547 * find a dentry. Some filesystems really want
1548 * a connected one, so try that first.
1549 */
1550 dentry = d_find_alias(inode);
1551 if (!dentry)
1552 dentry = d_find_any_alias(inode);
1553 }
1554 /*
1555 * This can be hit on boot when a file is accessed
1556 * before the policy is loaded. When we load policy we
1557 * may find inodes that have no dentry on the
1558 * sbsec->isec_head list. No reason to complain as
1559 * these will get fixed up the next time we go through
1560 * inode_doinit() with a dentry, before these inodes
1561 * could be used again by userspace.
1562 */
1563 if (!dentry)
1564 goto out_invalid;
1565 rc = selinux_genfs_get_sid(dentry, sclass,
1566 sbsec->flags, &sid);
1567 if (rc) {
1568 dput(dentry);
1569 goto out;
1570 }
1571
1572 if ((sbsec->flags & SE_SBGENFS_XATTR) &&
1573 (inode->i_opflags & IOP_XATTR)) {
1574 rc = inode_doinit_use_xattr(inode, dentry,
1575 sid, &sid);
1576 if (rc) {
1577 dput(dentry);
1578 goto out;
1579 }
1580 }
1581 dput(dentry);
1582 }
1583 break;
1584 }
1585
1586 out:
1587 spin_lock(&isec->lock);
1588 if (isec->initialized == LABEL_PENDING) {
1589 if (rc) {
1590 isec->initialized = LABEL_INVALID;
1591 goto out_unlock;
1592 }
1593 isec->initialized = LABEL_INITIALIZED;
1594 isec->sid = sid;
1595 }
1596
1597 out_unlock:
1598 spin_unlock(&isec->lock);
1599 return rc;
1600
1601 out_invalid:
1602 spin_lock(&isec->lock);
1603 if (isec->initialized == LABEL_PENDING) {
1604 isec->initialized = LABEL_INVALID;
1605 isec->sid = sid;
1606 }
1607 spin_unlock(&isec->lock);
1608 return 0;
1609 }
1610
1611 /* Convert a Linux signal to an access vector. */
signal_to_av(int sig)1612 static inline u32 signal_to_av(int sig)
1613 {
1614 u32 perm = 0;
1615
1616 switch (sig) {
1617 case SIGCHLD:
1618 /* Commonly granted from child to parent. */
1619 perm = PROCESS__SIGCHLD;
1620 break;
1621 case SIGKILL:
1622 /* Cannot be caught or ignored */
1623 perm = PROCESS__SIGKILL;
1624 break;
1625 case SIGSTOP:
1626 /* Cannot be caught or ignored */
1627 perm = PROCESS__SIGSTOP;
1628 break;
1629 default:
1630 /* All other signals. */
1631 perm = PROCESS__SIGNAL;
1632 break;
1633 }
1634
1635 return perm;
1636 }
1637
1638 #if CAP_LAST_CAP > 63
1639 #error Fix SELinux to handle capabilities > 63.
1640 #endif
1641
1642 /* Check whether a task is allowed to use a capability. */
cred_has_capability(const struct cred * cred,int cap,unsigned int opts,bool initns)1643 static int cred_has_capability(const struct cred *cred,
1644 int cap, unsigned int opts, bool initns)
1645 {
1646 struct common_audit_data ad;
1647 struct av_decision avd;
1648 u16 sclass;
1649 u32 sid = cred_sid(cred);
1650 u32 av = CAP_TO_MASK(cap);
1651 int rc;
1652
1653 ad.type = LSM_AUDIT_DATA_CAP;
1654 ad.u.cap = cap;
1655
1656 switch (CAP_TO_INDEX(cap)) {
1657 case 0:
1658 sclass = initns ? SECCLASS_CAPABILITY : SECCLASS_CAP_USERNS;
1659 break;
1660 case 1:
1661 sclass = initns ? SECCLASS_CAPABILITY2 : SECCLASS_CAP2_USERNS;
1662 break;
1663 default:
1664 pr_err("SELinux: out of range capability %d\n", cap);
1665 return -EINVAL;
1666 }
1667
1668 rc = avc_has_perm_noaudit(sid, sid, sclass, av, 0, &avd);
1669 if (!(opts & CAP_OPT_NOAUDIT)) {
1670 int rc2 = avc_audit(sid, sid, sclass, av, &avd, rc, &ad);
1671 if (rc2)
1672 return rc2;
1673 }
1674 return rc;
1675 }
1676
1677 /*
1678 * Check whether a SID has a particular permission to an inode. The 'adp'
1679 * parameter is optional and allows other audit data to be passed (e.g. the
1680 * dentry).
1681 */
inode_sid_has_perm(u32 sid,struct inode * inode,u32 perms,struct common_audit_data * adp)1682 static int inode_sid_has_perm(u32 sid, struct inode *inode, u32 perms,
1683 struct common_audit_data *adp)
1684 {
1685 struct inode_security_struct *isec;
1686
1687 if (unlikely(IS_PRIVATE(inode)))
1688 return 0;
1689
1690 isec = selinux_inode(inode);
1691
1692 return avc_has_perm(sid, isec->sid, isec->sclass, perms, adp);
1693 }
1694
inode_has_perm(const struct cred * cred,struct inode * inode,u32 perms,struct common_audit_data * adp)1695 static int inode_has_perm(const struct cred *cred,
1696 struct inode *inode,
1697 u32 perms,
1698 struct common_audit_data *adp)
1699 {
1700 return inode_sid_has_perm(cred_sid(cred), inode, perms, adp);
1701 }
1702
1703 /* Same as inode_has_perm, but pass explicit audit data containing
1704 the dentry to help the auditing code to more easily generate the
1705 pathname if needed. */
dentry_has_perm(const struct cred * cred,struct dentry * dentry,u32 av)1706 static inline int dentry_has_perm(const struct cred *cred,
1707 struct dentry *dentry,
1708 u32 av)
1709 {
1710 struct common_audit_data ad;
1711 struct inode *inode = d_backing_inode(dentry);
1712 struct inode_security_struct *isec = selinux_inode(inode);
1713
1714 ad.type = LSM_AUDIT_DATA_DENTRY;
1715 ad.u.dentry = dentry;
1716 /* check below is racy, but revalidate will recheck with lock held */
1717 if (data_race(unlikely(isec->initialized != LABEL_INITIALIZED)))
1718 __inode_security_revalidate(inode, dentry, true);
1719 return inode_has_perm(cred, inode, av, &ad);
1720 }
1721
1722 /* Same as inode_has_perm, but pass explicit audit data containing
1723 the path to help the auditing code to more easily generate the
1724 pathname if needed. */
path_has_perm(const struct cred * cred,const struct path * path,u32 av)1725 static inline int path_has_perm(const struct cred *cred,
1726 const struct path *path,
1727 u32 av)
1728 {
1729 struct common_audit_data ad;
1730 struct inode *inode = d_backing_inode(path->dentry);
1731 struct inode_security_struct *isec = selinux_inode(inode);
1732
1733 ad.type = LSM_AUDIT_DATA_PATH;
1734 ad.u.path = *path;
1735 /* check below is racy, but revalidate will recheck with lock held */
1736 if (data_race(unlikely(isec->initialized != LABEL_INITIALIZED)))
1737 __inode_security_revalidate(inode, path->dentry, true);
1738 return inode_has_perm(cred, inode, av, &ad);
1739 }
1740
1741 /* Same as path_has_perm, but uses the inode from the file struct. */
file_path_has_perm(const struct cred * cred,struct file * file,u32 av)1742 static inline int file_path_has_perm(const struct cred *cred,
1743 struct file *file,
1744 u32 av)
1745 {
1746 struct common_audit_data ad;
1747
1748 ad.type = LSM_AUDIT_DATA_FILE;
1749 ad.u.file = file;
1750 return inode_has_perm(cred, file_inode(file), av, &ad);
1751 }
1752
1753 #ifdef CONFIG_BPF_SYSCALL
1754 static int bpf_fd_pass(const struct file *file, u32 sid);
1755 #endif
1756
__file_has_perm(const struct cred * cred,const struct file * file,u32 av,bool bf_user_file)1757 static int __file_has_perm(const struct cred *cred, const struct file *file,
1758 u32 av, bool bf_user_file)
1759
1760 {
1761 struct common_audit_data ad;
1762 struct inode *inode;
1763 u32 ssid = cred_sid(cred);
1764 u32 tsid_fd;
1765 int rc;
1766
1767 if (bf_user_file) {
1768 struct backing_file_security_struct *bfsec;
1769 const struct path *path;
1770
1771 if (WARN_ON(!(file->f_mode & FMODE_BACKING)))
1772 return -EIO;
1773
1774 bfsec = selinux_backing_file(file);
1775 path = backing_file_user_path(file);
1776 tsid_fd = bfsec->uf_sid;
1777 inode = d_inode(path->dentry);
1778
1779 ad.type = LSM_AUDIT_DATA_PATH;
1780 ad.u.path = *path;
1781 } else {
1782 struct file_security_struct *fsec = selinux_file(file);
1783
1784 tsid_fd = fsec->sid;
1785 inode = file_inode(file);
1786
1787 ad.type = LSM_AUDIT_DATA_FILE;
1788 ad.u.file = file;
1789 }
1790
1791 if (ssid != tsid_fd) {
1792 rc = avc_has_perm(ssid, tsid_fd, SECCLASS_FD, FD__USE, &ad);
1793 if (rc)
1794 return rc;
1795 }
1796
1797 #ifdef CONFIG_BPF_SYSCALL
1798 /* regardless of backing vs user file, use the underlying file here */
1799 rc = bpf_fd_pass(file, ssid);
1800 if (rc)
1801 return rc;
1802 #endif
1803
1804 /* av is zero if only checking access to the descriptor. */
1805 if (av)
1806 return inode_has_perm(cred, inode, av, &ad);
1807
1808 return 0;
1809 }
1810
1811 /* Check whether a task can use an open file descriptor to
1812 access an inode in a given way. Check access to the
1813 descriptor itself, and then use dentry_has_perm to
1814 check a particular permission to the file.
1815 Access to the descriptor is implicitly granted if it
1816 has the same SID as the process. If av is zero, then
1817 access to the file is not checked, e.g. for cases
1818 where only the descriptor is affected like seek. */
file_has_perm(const struct cred * cred,const struct file * file,u32 av)1819 static inline int file_has_perm(const struct cred *cred,
1820 const struct file *file, u32 av)
1821 {
1822 return __file_has_perm(cred, file, av, false);
1823 }
1824
1825 /*
1826 * Determine the label for an inode that might be unioned.
1827 */
1828 static int
selinux_determine_inode_label(const struct cred_security_struct * crsec,struct inode * dir,const struct qstr * name,u16 tclass,u32 * _new_isid)1829 selinux_determine_inode_label(const struct cred_security_struct *crsec,
1830 struct inode *dir,
1831 const struct qstr *name, u16 tclass,
1832 u32 *_new_isid)
1833 {
1834 const struct superblock_security_struct *sbsec =
1835 selinux_superblock(dir->i_sb);
1836
1837 if ((sbsec->flags & SE_SBINITIALIZED) &&
1838 (sbsec->behavior == SECURITY_FS_USE_MNTPOINT)) {
1839 *_new_isid = sbsec->mntpoint_sid;
1840 } else if ((sbsec->flags & SBLABEL_MNT) &&
1841 crsec->create_sid) {
1842 *_new_isid = crsec->create_sid;
1843 } else {
1844 const struct inode_security_struct *dsec = inode_security(dir);
1845 return security_transition_sid(crsec->sid,
1846 dsec->sid, tclass,
1847 name, _new_isid);
1848 }
1849
1850 return 0;
1851 }
1852
1853 /* Check whether a task can create a file. */
may_create(struct inode * dir,struct dentry * dentry,u16 tclass)1854 static int may_create(struct inode *dir,
1855 struct dentry *dentry,
1856 u16 tclass)
1857 {
1858 const struct cred_security_struct *crsec = selinux_cred(current_cred());
1859 struct inode_security_struct *dsec;
1860 struct superblock_security_struct *sbsec;
1861 u32 sid, newsid;
1862 struct common_audit_data ad;
1863 int rc;
1864
1865 dsec = inode_security(dir);
1866 sbsec = selinux_superblock(dir->i_sb);
1867
1868 sid = crsec->sid;
1869
1870 ad.type = LSM_AUDIT_DATA_DENTRY;
1871 ad.u.dentry = dentry;
1872
1873 rc = avc_has_perm(sid, dsec->sid, SECCLASS_DIR,
1874 DIR__ADD_NAME | DIR__SEARCH,
1875 &ad);
1876 if (rc)
1877 return rc;
1878
1879 rc = selinux_determine_inode_label(crsec, dir, &dentry->d_name, tclass,
1880 &newsid);
1881 if (rc)
1882 return rc;
1883
1884 rc = avc_has_perm(sid, newsid, tclass, FILE__CREATE, &ad);
1885 if (rc)
1886 return rc;
1887
1888 return avc_has_perm(newsid, sbsec->sid,
1889 SECCLASS_FILESYSTEM,
1890 FILESYSTEM__ASSOCIATE, &ad);
1891 }
1892
1893 #define MAY_LINK 0
1894 #define MAY_UNLINK 1
1895 #define MAY_RMDIR 2
1896
1897 /* Check whether a task can link, unlink, or rmdir a file/directory. */
may_link(struct inode * dir,struct dentry * dentry,int kind)1898 static int may_link(struct inode *dir,
1899 struct dentry *dentry,
1900 int kind)
1901
1902 {
1903 struct inode_security_struct *dsec, *isec;
1904 struct common_audit_data ad;
1905 u32 sid = current_sid();
1906 u32 av;
1907 int rc;
1908
1909 dsec = inode_security(dir);
1910 isec = backing_inode_security(dentry);
1911
1912 ad.type = LSM_AUDIT_DATA_DENTRY;
1913 ad.u.dentry = dentry;
1914
1915 av = DIR__SEARCH;
1916 av |= (kind ? DIR__REMOVE_NAME : DIR__ADD_NAME);
1917 rc = avc_has_perm(sid, dsec->sid, SECCLASS_DIR, av, &ad);
1918 if (rc)
1919 return rc;
1920
1921 switch (kind) {
1922 case MAY_LINK:
1923 av = FILE__LINK;
1924 break;
1925 case MAY_UNLINK:
1926 av = FILE__UNLINK;
1927 break;
1928 case MAY_RMDIR:
1929 av = DIR__RMDIR;
1930 break;
1931 default:
1932 pr_warn("SELinux: %s: unrecognized kind %d\n",
1933 __func__, kind);
1934 return 0;
1935 }
1936
1937 rc = avc_has_perm(sid, isec->sid, isec->sclass, av, &ad);
1938 return rc;
1939 }
1940
may_rename(struct inode * old_dir,struct dentry * old_dentry,struct inode * new_dir,struct dentry * new_dentry)1941 static inline int may_rename(struct inode *old_dir,
1942 struct dentry *old_dentry,
1943 struct inode *new_dir,
1944 struct dentry *new_dentry)
1945 {
1946 struct inode_security_struct *old_dsec, *new_dsec, *old_isec, *new_isec;
1947 struct common_audit_data ad;
1948 u32 sid = current_sid();
1949 u32 av;
1950 int old_is_dir, new_is_dir;
1951 int rc;
1952
1953 old_dsec = inode_security(old_dir);
1954 old_isec = backing_inode_security(old_dentry);
1955 old_is_dir = d_is_dir(old_dentry);
1956 new_dsec = inode_security(new_dir);
1957
1958 ad.type = LSM_AUDIT_DATA_DENTRY;
1959
1960 ad.u.dentry = old_dentry;
1961 rc = avc_has_perm(sid, old_dsec->sid, SECCLASS_DIR,
1962 DIR__REMOVE_NAME | DIR__SEARCH, &ad);
1963 if (rc)
1964 return rc;
1965 rc = avc_has_perm(sid, old_isec->sid,
1966 old_isec->sclass, FILE__RENAME, &ad);
1967 if (rc)
1968 return rc;
1969 if (old_is_dir && new_dir != old_dir) {
1970 rc = avc_has_perm(sid, old_isec->sid,
1971 old_isec->sclass, DIR__REPARENT, &ad);
1972 if (rc)
1973 return rc;
1974 }
1975
1976 ad.u.dentry = new_dentry;
1977 av = DIR__ADD_NAME | DIR__SEARCH;
1978 if (d_is_positive(new_dentry))
1979 av |= DIR__REMOVE_NAME;
1980 rc = avc_has_perm(sid, new_dsec->sid, SECCLASS_DIR, av, &ad);
1981 if (rc)
1982 return rc;
1983 if (d_is_positive(new_dentry)) {
1984 new_isec = backing_inode_security(new_dentry);
1985 new_is_dir = d_is_dir(new_dentry);
1986 rc = avc_has_perm(sid, new_isec->sid,
1987 new_isec->sclass,
1988 (new_is_dir ? DIR__RMDIR : FILE__UNLINK), &ad);
1989 if (rc)
1990 return rc;
1991 }
1992
1993 return 0;
1994 }
1995
1996 /* Check whether a task can perform a filesystem operation. */
superblock_has_perm(const struct cred * cred,const struct super_block * sb,u32 perms,struct common_audit_data * ad)1997 static int superblock_has_perm(const struct cred *cred,
1998 const struct super_block *sb,
1999 u32 perms,
2000 struct common_audit_data *ad)
2001 {
2002 struct superblock_security_struct *sbsec;
2003 u32 sid = cred_sid(cred);
2004
2005 sbsec = selinux_superblock(sb);
2006 return avc_has_perm(sid, sbsec->sid, SECCLASS_FILESYSTEM, perms, ad);
2007 }
2008
2009 /* Convert a Linux mode and permission mask to an access vector. */
file_mask_to_av(int mode,int mask)2010 static inline u32 file_mask_to_av(int mode, int mask)
2011 {
2012 u32 av = 0;
2013
2014 if (!S_ISDIR(mode)) {
2015 if (mask & MAY_EXEC)
2016 av |= FILE__EXECUTE;
2017 if (mask & MAY_READ)
2018 av |= FILE__READ;
2019
2020 if (mask & MAY_APPEND)
2021 av |= FILE__APPEND;
2022 else if (mask & MAY_WRITE)
2023 av |= FILE__WRITE;
2024
2025 } else {
2026 if (mask & MAY_EXEC)
2027 av |= DIR__SEARCH;
2028 if (mask & MAY_WRITE)
2029 av |= DIR__WRITE;
2030 if (mask & MAY_READ)
2031 av |= DIR__READ;
2032 }
2033
2034 return av;
2035 }
2036
2037 /* Convert a Linux file to an access vector. */
file_to_av(const struct file * file)2038 static inline u32 file_to_av(const struct file *file)
2039 {
2040 u32 av = 0;
2041
2042 if (file->f_mode & FMODE_READ)
2043 av |= FILE__READ;
2044 if (file->f_mode & FMODE_WRITE) {
2045 if (file->f_flags & O_APPEND)
2046 av |= FILE__APPEND;
2047 else
2048 av |= FILE__WRITE;
2049 }
2050 if (!av) {
2051 /*
2052 * Special file opened with flags 3 for ioctl-only use.
2053 */
2054 av = FILE__IOCTL;
2055 }
2056
2057 return av;
2058 }
2059
2060 /*
2061 * Convert a file to an access vector and include the correct
2062 * open permission.
2063 */
open_file_to_av(struct file * file)2064 static inline u32 open_file_to_av(struct file *file)
2065 {
2066 u32 av = file_to_av(file);
2067 struct inode *inode = file_inode(file);
2068
2069 if (selinux_policycap_openperm() &&
2070 inode->i_sb->s_magic != SOCKFS_MAGIC)
2071 av |= FILE__OPEN;
2072
2073 return av;
2074 }
2075
2076 /* Hook functions begin here. */
2077
selinux_binder_set_context_mgr(const struct cred * mgr)2078 static int selinux_binder_set_context_mgr(const struct cred *mgr)
2079 {
2080 return avc_has_perm(current_sid(), cred_sid(mgr), SECCLASS_BINDER,
2081 BINDER__SET_CONTEXT_MGR, NULL);
2082 }
2083
selinux_binder_transaction(const struct cred * from,const struct cred * to)2084 static int selinux_binder_transaction(const struct cred *from,
2085 const struct cred *to)
2086 {
2087 u32 mysid = current_sid();
2088 u32 fromsid = cred_sid(from);
2089 u32 tosid = cred_sid(to);
2090 int rc;
2091
2092 if (mysid != fromsid) {
2093 rc = avc_has_perm(mysid, fromsid, SECCLASS_BINDER,
2094 BINDER__IMPERSONATE, NULL);
2095 if (rc)
2096 return rc;
2097 }
2098
2099 return avc_has_perm(fromsid, tosid,
2100 SECCLASS_BINDER, BINDER__CALL, NULL);
2101 }
2102
selinux_binder_transfer_binder(const struct cred * from,const struct cred * to)2103 static int selinux_binder_transfer_binder(const struct cred *from,
2104 const struct cred *to)
2105 {
2106 return avc_has_perm(cred_sid(from), cred_sid(to),
2107 SECCLASS_BINDER, BINDER__TRANSFER,
2108 NULL);
2109 }
2110
selinux_binder_transfer_file(const struct cred * from,const struct cred * to,const struct file * file)2111 static int selinux_binder_transfer_file(const struct cred *from,
2112 const struct cred *to,
2113 const struct file *file)
2114 {
2115 u32 sid = cred_sid(to);
2116 struct file_security_struct *fsec = selinux_file(file);
2117 struct dentry *dentry = file->f_path.dentry;
2118 struct inode_security_struct *isec;
2119 struct common_audit_data ad;
2120 int rc;
2121
2122 ad.type = LSM_AUDIT_DATA_PATH;
2123 ad.u.path = file->f_path;
2124
2125 if (sid != fsec->sid) {
2126 rc = avc_has_perm(sid, fsec->sid,
2127 SECCLASS_FD,
2128 FD__USE,
2129 &ad);
2130 if (rc)
2131 return rc;
2132 }
2133
2134 #ifdef CONFIG_BPF_SYSCALL
2135 rc = bpf_fd_pass(file, sid);
2136 if (rc)
2137 return rc;
2138 #endif
2139
2140 if (unlikely(IS_PRIVATE(d_backing_inode(dentry))))
2141 return 0;
2142
2143 isec = backing_inode_security(dentry);
2144 return avc_has_perm(sid, isec->sid, isec->sclass, file_to_av(file),
2145 &ad);
2146 }
2147
selinux_ptrace_access_check(struct task_struct * child,unsigned int mode)2148 static int selinux_ptrace_access_check(struct task_struct *child,
2149 unsigned int mode)
2150 {
2151 u32 sid = current_sid();
2152 u32 csid = task_sid_obj(child);
2153
2154 if (mode & PTRACE_MODE_READ)
2155 return avc_has_perm(sid, csid, SECCLASS_FILE, FILE__READ,
2156 NULL);
2157
2158 return avc_has_perm(sid, csid, SECCLASS_PROCESS, PROCESS__PTRACE,
2159 NULL);
2160 }
2161
selinux_ptrace_traceme(struct task_struct * parent)2162 static int selinux_ptrace_traceme(struct task_struct *parent)
2163 {
2164 return avc_has_perm(task_sid_obj(parent), task_sid_obj(current),
2165 SECCLASS_PROCESS, PROCESS__PTRACE, NULL);
2166 }
2167
selinux_capget(const struct task_struct * target,kernel_cap_t * effective,kernel_cap_t * inheritable,kernel_cap_t * permitted)2168 static int selinux_capget(const struct task_struct *target, kernel_cap_t *effective,
2169 kernel_cap_t *inheritable, kernel_cap_t *permitted)
2170 {
2171 return avc_has_perm(current_sid(), task_sid_obj(target),
2172 SECCLASS_PROCESS, PROCESS__GETCAP, NULL);
2173 }
2174
selinux_capset(struct cred * new,const struct cred * old,const kernel_cap_t * effective,const kernel_cap_t * inheritable,const kernel_cap_t * permitted)2175 static int selinux_capset(struct cred *new, const struct cred *old,
2176 const kernel_cap_t *effective,
2177 const kernel_cap_t *inheritable,
2178 const kernel_cap_t *permitted)
2179 {
2180 return avc_has_perm(cred_sid(old), cred_sid(new), SECCLASS_PROCESS,
2181 PROCESS__SETCAP, NULL);
2182 }
2183
2184 /*
2185 * (This comment used to live with the selinux_task_setuid hook,
2186 * which was removed).
2187 *
2188 * Since setuid only affects the current process, and since the SELinux
2189 * controls are not based on the Linux identity attributes, SELinux does not
2190 * need to control this operation. However, SELinux does control the use of
2191 * the CAP_SETUID and CAP_SETGID capabilities using the capable hook.
2192 */
2193
selinux_capable(const struct cred * cred,struct user_namespace * ns,int cap,unsigned int opts)2194 static int selinux_capable(const struct cred *cred, struct user_namespace *ns,
2195 int cap, unsigned int opts)
2196 {
2197 return cred_has_capability(cred, cap, opts, ns == &init_user_ns);
2198 }
2199
selinux_quotactl(int cmds,int type,int id,const struct super_block * sb)2200 static int selinux_quotactl(int cmds, int type, int id, const struct super_block *sb)
2201 {
2202 const struct cred *cred = current_cred();
2203 int rc = 0;
2204
2205 if (!sb)
2206 return 0;
2207
2208 switch (cmds) {
2209 case Q_SYNC:
2210 case Q_QUOTAON:
2211 case Q_QUOTAOFF:
2212 case Q_SETINFO:
2213 case Q_SETQUOTA:
2214 case Q_XQUOTAOFF:
2215 case Q_XQUOTAON:
2216 case Q_XSETQLIM:
2217 rc = superblock_has_perm(cred, sb, FILESYSTEM__QUOTAMOD, NULL);
2218 break;
2219 case Q_GETFMT:
2220 case Q_GETINFO:
2221 case Q_GETQUOTA:
2222 case Q_XGETQUOTA:
2223 case Q_XGETQSTAT:
2224 case Q_XGETQSTATV:
2225 case Q_XGETNEXTQUOTA:
2226 rc = superblock_has_perm(cred, sb, FILESYSTEM__QUOTAGET, NULL);
2227 break;
2228 default:
2229 rc = 0; /* let the kernel handle invalid cmds */
2230 break;
2231 }
2232 return rc;
2233 }
2234
selinux_quota_on(struct dentry * dentry)2235 static int selinux_quota_on(struct dentry *dentry)
2236 {
2237 const struct cred *cred = current_cred();
2238
2239 return dentry_has_perm(cred, dentry, FILE__QUOTAON);
2240 }
2241
selinux_syslog(int type)2242 static int selinux_syslog(int type)
2243 {
2244 switch (type) {
2245 case SYSLOG_ACTION_READ_ALL: /* Read last kernel messages */
2246 case SYSLOG_ACTION_SIZE_BUFFER: /* Return size of the log buffer */
2247 return avc_has_perm(current_sid(), SECINITSID_KERNEL,
2248 SECCLASS_SYSTEM, SYSTEM__SYSLOG_READ, NULL);
2249 case SYSLOG_ACTION_CONSOLE_OFF: /* Disable logging to console */
2250 case SYSLOG_ACTION_CONSOLE_ON: /* Enable logging to console */
2251 /* Set level of messages printed to console */
2252 case SYSLOG_ACTION_CONSOLE_LEVEL:
2253 return avc_has_perm(current_sid(), SECINITSID_KERNEL,
2254 SECCLASS_SYSTEM, SYSTEM__SYSLOG_CONSOLE,
2255 NULL);
2256 }
2257 /* All other syslog types */
2258 return avc_has_perm(current_sid(), SECINITSID_KERNEL,
2259 SECCLASS_SYSTEM, SYSTEM__SYSLOG_MOD, NULL);
2260 }
2261
2262 /*
2263 * Check permission for allocating a new virtual mapping. Returns
2264 * 0 if permission is granted, negative error code if not.
2265 *
2266 * Do not audit the selinux permission check, as this is applied to all
2267 * processes that allocate mappings.
2268 */
selinux_vm_enough_memory(struct mm_struct * mm,long pages)2269 static int selinux_vm_enough_memory(struct mm_struct *mm, long pages)
2270 {
2271 return cred_has_capability(current_cred(), CAP_SYS_ADMIN,
2272 CAP_OPT_NOAUDIT, true);
2273 }
2274
2275 /* binprm security operations */
2276
ptrace_parent_sid(void)2277 static u32 ptrace_parent_sid(void)
2278 {
2279 u32 sid = 0;
2280 struct task_struct *tracer;
2281
2282 rcu_read_lock();
2283 tracer = ptrace_parent(current);
2284 if (tracer)
2285 sid = task_sid_obj(tracer);
2286 rcu_read_unlock();
2287
2288 return sid;
2289 }
2290
check_nnp_nosuid(const struct linux_binprm * bprm,const struct cred_security_struct * old_crsec,const struct cred_security_struct * new_crsec)2291 static int check_nnp_nosuid(const struct linux_binprm *bprm,
2292 const struct cred_security_struct *old_crsec,
2293 const struct cred_security_struct *new_crsec)
2294 {
2295 int nnp = (bprm->unsafe & LSM_UNSAFE_NO_NEW_PRIVS);
2296 int nosuid = !mnt_may_suid(bprm->file->f_path.mnt);
2297 int rc;
2298 u32 av;
2299
2300 if (!nnp && !nosuid)
2301 return 0; /* neither NNP nor nosuid */
2302
2303 if (new_crsec->sid == old_crsec->sid)
2304 return 0; /* No change in credentials */
2305
2306 /*
2307 * If the policy enables the nnp_nosuid_transition policy capability,
2308 * then we permit transitions under NNP or nosuid if the
2309 * policy allows the corresponding permission between
2310 * the old and new contexts.
2311 */
2312 if (selinux_policycap_nnp_nosuid_transition()) {
2313 av = 0;
2314 if (nnp)
2315 av |= PROCESS2__NNP_TRANSITION;
2316 if (nosuid)
2317 av |= PROCESS2__NOSUID_TRANSITION;
2318 rc = avc_has_perm(old_crsec->sid, new_crsec->sid,
2319 SECCLASS_PROCESS2, av, NULL);
2320 if (!rc)
2321 return 0;
2322 }
2323
2324 /*
2325 * We also permit NNP or nosuid transitions to bounded SIDs,
2326 * i.e. SIDs that are guaranteed to only be allowed a subset
2327 * of the permissions of the current SID.
2328 */
2329 rc = security_bounded_transition(old_crsec->sid,
2330 new_crsec->sid);
2331 if (!rc)
2332 return 0;
2333
2334 /*
2335 * On failure, preserve the errno values for NNP vs nosuid.
2336 * NNP: Operation not permitted for caller.
2337 * nosuid: Permission denied to file.
2338 */
2339 if (nnp)
2340 return -EPERM;
2341 return -EACCES;
2342 }
2343
selinux_bprm_creds_for_exec(struct linux_binprm * bprm)2344 static int selinux_bprm_creds_for_exec(struct linux_binprm *bprm)
2345 {
2346 const struct cred_security_struct *old_crsec;
2347 struct cred_security_struct *new_crsec;
2348 struct inode_security_struct *isec;
2349 struct common_audit_data ad;
2350 struct inode *inode = file_inode(bprm->file);
2351 int rc;
2352
2353 /* SELinux context only depends on initial program or script and not
2354 * the script interpreter */
2355
2356 old_crsec = selinux_cred(current_cred());
2357 new_crsec = selinux_cred(bprm->cred);
2358 isec = inode_security(inode);
2359
2360 if (WARN_ON(isec->sclass != SECCLASS_FILE &&
2361 isec->sclass != SECCLASS_MEMFD_FILE))
2362 return -EACCES;
2363
2364 /* Default to the current task SID. */
2365 new_crsec->sid = old_crsec->sid;
2366 new_crsec->osid = old_crsec->sid;
2367
2368 /* Reset fs, key, and sock SIDs on execve. */
2369 new_crsec->create_sid = 0;
2370 new_crsec->keycreate_sid = 0;
2371 new_crsec->sockcreate_sid = 0;
2372
2373 /*
2374 * Before policy is loaded, label any task outside kernel space
2375 * as SECINITSID_INIT, so that any userspace tasks surviving from
2376 * early boot end up with a label different from SECINITSID_KERNEL
2377 * (if the policy chooses to set SECINITSID_INIT != SECINITSID_KERNEL).
2378 */
2379 if (!selinux_initialized()) {
2380 new_crsec->sid = SECINITSID_INIT;
2381 /* also clear the exec_sid just in case */
2382 new_crsec->exec_sid = 0;
2383 return 0;
2384 }
2385
2386 if (old_crsec->exec_sid) {
2387 new_crsec->sid = old_crsec->exec_sid;
2388 /* Reset exec SID on execve. */
2389 new_crsec->exec_sid = 0;
2390
2391 /* Fail on NNP or nosuid if not an allowed transition. */
2392 rc = check_nnp_nosuid(bprm, old_crsec, new_crsec);
2393 if (rc)
2394 return rc;
2395 } else {
2396 /* Check for a default transition on this program. */
2397 rc = security_transition_sid(old_crsec->sid,
2398 isec->sid, SECCLASS_PROCESS, NULL,
2399 &new_crsec->sid);
2400 if (rc)
2401 return rc;
2402
2403 /*
2404 * Fallback to old SID on NNP or nosuid if not an allowed
2405 * transition.
2406 */
2407 rc = check_nnp_nosuid(bprm, old_crsec, new_crsec);
2408 if (rc)
2409 new_crsec->sid = old_crsec->sid;
2410 }
2411
2412 ad.type = LSM_AUDIT_DATA_FILE;
2413 ad.u.file = bprm->file;
2414
2415 if (new_crsec->sid == old_crsec->sid) {
2416 rc = avc_has_perm(old_crsec->sid, isec->sid, isec->sclass,
2417 FILE__EXECUTE_NO_TRANS, &ad);
2418 if (rc)
2419 return rc;
2420 } else {
2421 /* Check permissions for the transition. */
2422 rc = avc_has_perm(old_crsec->sid, new_crsec->sid,
2423 SECCLASS_PROCESS, PROCESS__TRANSITION, &ad);
2424 if (rc)
2425 return rc;
2426
2427 rc = avc_has_perm(new_crsec->sid, isec->sid, isec->sclass,
2428 FILE__ENTRYPOINT, &ad);
2429 if (rc)
2430 return rc;
2431
2432 /* Check for shared state */
2433 if (bprm->unsafe & LSM_UNSAFE_SHARE) {
2434 rc = avc_has_perm(old_crsec->sid, new_crsec->sid,
2435 SECCLASS_PROCESS, PROCESS__SHARE,
2436 NULL);
2437 if (rc)
2438 return -EPERM;
2439 }
2440
2441 /* Make sure that anyone attempting to ptrace over a task that
2442 * changes its SID has the appropriate permit */
2443 if (bprm->unsafe & LSM_UNSAFE_PTRACE) {
2444 u32 ptsid = ptrace_parent_sid();
2445 if (ptsid != 0) {
2446 rc = avc_has_perm(ptsid, new_crsec->sid,
2447 SECCLASS_PROCESS,
2448 PROCESS__PTRACE, NULL);
2449 if (rc)
2450 return -EPERM;
2451 }
2452 }
2453
2454 /* Clear any possibly unsafe personality bits on exec: */
2455 bprm->per_clear |= PER_CLEAR_ON_SETID;
2456
2457 /* Enable secure mode for SIDs transitions unless
2458 the noatsecure permission is granted between
2459 the two SIDs, i.e. ahp returns 0. */
2460 rc = avc_has_perm(old_crsec->sid, new_crsec->sid,
2461 SECCLASS_PROCESS, PROCESS__NOATSECURE,
2462 NULL);
2463 bprm->secureexec |= !!rc;
2464 }
2465
2466 return 0;
2467 }
2468
match_file(const void * p,struct file * file,unsigned fd)2469 static int match_file(const void *p, struct file *file, unsigned fd)
2470 {
2471 return file_has_perm(p, file, file_to_av(file)) ? fd + 1 : 0;
2472 }
2473
2474 /* Derived from fs/exec.c:flush_old_files. */
flush_unauthorized_files(const struct cred * cred,struct files_struct * files)2475 static inline void flush_unauthorized_files(const struct cred *cred,
2476 struct files_struct *files)
2477 {
2478 struct file *file, *devnull = NULL;
2479 struct tty_struct *tty;
2480 int drop_tty = 0;
2481 unsigned n;
2482
2483 tty = get_current_tty();
2484 if (tty) {
2485 spin_lock(&tty->files_lock);
2486 if (!list_empty(&tty->tty_files)) {
2487 struct tty_file_private *file_priv;
2488
2489 /* Revalidate access to controlling tty.
2490 Use file_path_has_perm on the tty path directly
2491 rather than using file_has_perm, as this particular
2492 open file may belong to another process and we are
2493 only interested in the inode-based check here. */
2494 file_priv = list_first_entry(&tty->tty_files,
2495 struct tty_file_private, list);
2496 file = file_priv->file;
2497 if (file_path_has_perm(cred, file, FILE__READ | FILE__WRITE))
2498 drop_tty = 1;
2499 }
2500 spin_unlock(&tty->files_lock);
2501 tty_kref_put(tty);
2502 }
2503 /* Reset controlling tty. */
2504 if (drop_tty)
2505 no_tty();
2506
2507 /* Revalidate access to inherited open files. */
2508 n = iterate_fd(files, 0, match_file, cred);
2509 if (!n) /* none found? */
2510 return;
2511
2512 devnull = dentry_open(&selinux_null, O_RDWR, cred);
2513 if (IS_ERR(devnull))
2514 devnull = NULL;
2515 /* replace all the matching ones with this */
2516 do {
2517 replace_fd(n - 1, devnull, 0);
2518 } while ((n = iterate_fd(files, n, match_file, cred)) != 0);
2519 if (devnull)
2520 fput(devnull);
2521 }
2522
2523 /*
2524 * Prepare a process for imminent new credential changes due to exec
2525 */
selinux_bprm_committing_creds(const struct linux_binprm * bprm)2526 static void selinux_bprm_committing_creds(const struct linux_binprm *bprm)
2527 {
2528 struct cred_security_struct *new_crsec;
2529 struct rlimit *rlim, *initrlim;
2530 int rc, i;
2531
2532 new_crsec = selinux_cred(bprm->cred);
2533 if (new_crsec->sid == new_crsec->osid)
2534 return;
2535
2536 /* Close files for which the new task SID is not authorized. */
2537 flush_unauthorized_files(bprm->cred, current->files);
2538
2539 /* Always clear parent death signal on SID transitions. */
2540 current->pdeath_signal = 0;
2541
2542 /* Check whether the new SID can inherit resource limits from the old
2543 * SID. If not, reset all soft limits to the lower of the current
2544 * task's hard limit and the init task's soft limit.
2545 *
2546 * Note that the setting of hard limits (even to lower them) can be
2547 * controlled by the setrlimit check. The inclusion of the init task's
2548 * soft limit into the computation is to avoid resetting soft limits
2549 * higher than the default soft limit for cases where the default is
2550 * lower than the hard limit, e.g. RLIMIT_CORE or RLIMIT_STACK.
2551 */
2552 rc = avc_has_perm(new_crsec->osid, new_crsec->sid, SECCLASS_PROCESS,
2553 PROCESS__RLIMITINH, NULL);
2554 if (rc) {
2555 /* protect against do_prlimit() */
2556 task_lock(current);
2557 for (i = 0; i < RLIM_NLIMITS; i++) {
2558 rlim = current->signal->rlim + i;
2559 initrlim = init_task.signal->rlim + i;
2560 rlim->rlim_cur = min(rlim->rlim_max, initrlim->rlim_cur);
2561 }
2562 task_unlock(current);
2563 if (IS_ENABLED(CONFIG_POSIX_TIMERS))
2564 update_rlimit_cpu(current, rlimit(RLIMIT_CPU));
2565 }
2566 }
2567
2568 /*
2569 * Clean up the process immediately after the installation of new credentials
2570 * due to exec
2571 */
selinux_bprm_committed_creds(const struct linux_binprm * bprm)2572 static void selinux_bprm_committed_creds(const struct linux_binprm *bprm)
2573 {
2574 const struct cred_security_struct *crsec = selinux_cred(current_cred());
2575 u32 osid, sid;
2576 int rc;
2577
2578 osid = crsec->osid;
2579 sid = crsec->sid;
2580
2581 if (sid == osid)
2582 return;
2583
2584 /* Check whether the new SID can inherit signal state from the old SID.
2585 * If not, clear itimers to avoid subsequent signal generation and
2586 * flush and unblock signals.
2587 *
2588 * This must occur _after_ the task SID has been updated so that any
2589 * kill done after the flush will be checked against the new SID.
2590 */
2591 rc = avc_has_perm(osid, sid, SECCLASS_PROCESS, PROCESS__SIGINH, NULL);
2592 if (rc) {
2593 clear_itimer();
2594
2595 spin_lock_irq(&unrcu_pointer(current->sighand)->siglock);
2596 if (!fatal_signal_pending(current)) {
2597 flush_sigqueue(¤t->pending);
2598 flush_sigqueue(¤t->signal->shared_pending);
2599 flush_signal_handlers(current, 1);
2600 sigemptyset(¤t->blocked);
2601 recalc_sigpending();
2602 }
2603 spin_unlock_irq(&unrcu_pointer(current->sighand)->siglock);
2604 }
2605
2606 /* Wake up the parent if it is waiting so that it can recheck
2607 * wait permission to the new task SID. */
2608 read_lock(&tasklist_lock);
2609 __wake_up_parent(current, unrcu_pointer(current->real_parent));
2610 read_unlock(&tasklist_lock);
2611 }
2612
2613 /* superblock security operations */
2614
selinux_sb_alloc_security(struct super_block * sb)2615 static int selinux_sb_alloc_security(struct super_block *sb)
2616 {
2617 struct superblock_security_struct *sbsec = selinux_superblock(sb);
2618
2619 mutex_init(&sbsec->lock);
2620 INIT_LIST_HEAD(&sbsec->isec_head);
2621 spin_lock_init(&sbsec->isec_lock);
2622 sbsec->sid = SECINITSID_UNLABELED;
2623 sbsec->def_sid = SECINITSID_FILE;
2624 sbsec->mntpoint_sid = SECINITSID_UNLABELED;
2625 sbsec->creator_sid = SECINITSID_UNLABELED;
2626
2627 return 0;
2628 }
2629
opt_len(const char * s)2630 static inline int opt_len(const char *s)
2631 {
2632 bool open_quote = false;
2633 int len;
2634 char c;
2635
2636 for (len = 0; (c = s[len]) != '\0'; len++) {
2637 if (c == '"')
2638 open_quote = !open_quote;
2639 if (c == ',' && !open_quote)
2640 break;
2641 }
2642 return len;
2643 }
2644
selinux_sb_eat_lsm_opts(char * options,void ** mnt_opts)2645 static int selinux_sb_eat_lsm_opts(char *options, void **mnt_opts)
2646 {
2647 char *from = options;
2648 char *to = options;
2649 bool first = true;
2650 int rc;
2651
2652 while (1) {
2653 int len = opt_len(from);
2654 int token;
2655 char *arg = NULL;
2656
2657 token = match_opt_prefix(from, len, &arg);
2658
2659 if (token != Opt_error) {
2660 char *p, *q;
2661
2662 /* strip quotes */
2663 if (arg) {
2664 for (p = q = arg; p < from + len; p++) {
2665 char c = *p;
2666 if (c != '"')
2667 *q++ = c;
2668 }
2669 arg = kmemdup_nul(arg, q - arg, GFP_KERNEL);
2670 if (!arg) {
2671 rc = -ENOMEM;
2672 goto free_opt;
2673 }
2674 }
2675 rc = selinux_add_opt(token, arg, mnt_opts);
2676 kfree(arg);
2677 arg = NULL;
2678 if (unlikely(rc)) {
2679 goto free_opt;
2680 }
2681 } else {
2682 if (!first) { // copy with preceding comma
2683 from--;
2684 len++;
2685 }
2686 if (to != from)
2687 memmove(to, from, len);
2688 to += len;
2689 first = false;
2690 }
2691 if (!from[len])
2692 break;
2693 from += len + 1;
2694 }
2695 *to = '\0';
2696 return 0;
2697
2698 free_opt:
2699 if (*mnt_opts) {
2700 selinux_free_mnt_opts(*mnt_opts);
2701 *mnt_opts = NULL;
2702 }
2703 return rc;
2704 }
2705
selinux_sb_mnt_opts_compat(struct super_block * sb,void * mnt_opts)2706 static int selinux_sb_mnt_opts_compat(struct super_block *sb, void *mnt_opts)
2707 {
2708 struct selinux_mnt_opts *opts = mnt_opts;
2709 struct superblock_security_struct *sbsec = selinux_superblock(sb);
2710
2711 /*
2712 * Superblock not initialized (i.e. no options) - reject if any
2713 * options specified, otherwise accept.
2714 */
2715 if (!(sbsec->flags & SE_SBINITIALIZED))
2716 return opts ? 1 : 0;
2717
2718 /*
2719 * Superblock initialized and no options specified - reject if
2720 * superblock has any options set, otherwise accept.
2721 */
2722 if (!opts)
2723 return (sbsec->flags & SE_MNTMASK) ? 1 : 0;
2724
2725 if (opts->fscontext_sid) {
2726 if (bad_option(sbsec, FSCONTEXT_MNT, sbsec->sid,
2727 opts->fscontext_sid))
2728 return 1;
2729 }
2730 if (opts->context_sid) {
2731 if (bad_option(sbsec, CONTEXT_MNT, sbsec->mntpoint_sid,
2732 opts->context_sid))
2733 return 1;
2734 }
2735 if (opts->rootcontext_sid) {
2736 struct inode_security_struct *root_isec;
2737
2738 root_isec = backing_inode_security(sb->s_root);
2739 if (bad_option(sbsec, ROOTCONTEXT_MNT, root_isec->sid,
2740 opts->rootcontext_sid))
2741 return 1;
2742 }
2743 if (opts->defcontext_sid) {
2744 if (bad_option(sbsec, DEFCONTEXT_MNT, sbsec->def_sid,
2745 opts->defcontext_sid))
2746 return 1;
2747 }
2748 return 0;
2749 }
2750
selinux_sb_remount(struct super_block * sb,void * mnt_opts)2751 static int selinux_sb_remount(struct super_block *sb, void *mnt_opts)
2752 {
2753 struct selinux_mnt_opts *opts = mnt_opts;
2754 struct superblock_security_struct *sbsec = selinux_superblock(sb);
2755
2756 if (!(sbsec->flags & SE_SBINITIALIZED))
2757 return 0;
2758
2759 if (!opts)
2760 return 0;
2761
2762 if (opts->fscontext_sid) {
2763 if (bad_option(sbsec, FSCONTEXT_MNT, sbsec->sid,
2764 opts->fscontext_sid))
2765 goto out_bad_option;
2766 }
2767 if (opts->context_sid) {
2768 if (bad_option(sbsec, CONTEXT_MNT, sbsec->mntpoint_sid,
2769 opts->context_sid))
2770 goto out_bad_option;
2771 }
2772 if (opts->rootcontext_sid) {
2773 struct inode_security_struct *root_isec;
2774 root_isec = backing_inode_security(sb->s_root);
2775 if (bad_option(sbsec, ROOTCONTEXT_MNT, root_isec->sid,
2776 opts->rootcontext_sid))
2777 goto out_bad_option;
2778 }
2779 if (opts->defcontext_sid) {
2780 if (bad_option(sbsec, DEFCONTEXT_MNT, sbsec->def_sid,
2781 opts->defcontext_sid))
2782 goto out_bad_option;
2783 }
2784 return 0;
2785
2786 out_bad_option:
2787 pr_warn("SELinux: unable to change security options "
2788 "during remount (dev %s, type=%s)\n", sb->s_id,
2789 sb->s_type->name);
2790 return -EINVAL;
2791 }
2792
selinux_sb_kern_mount(const struct super_block * sb)2793 static int selinux_sb_kern_mount(const struct super_block *sb)
2794 {
2795 const struct cred *cred = current_cred();
2796 struct common_audit_data ad;
2797
2798 ad.type = LSM_AUDIT_DATA_DENTRY;
2799 ad.u.dentry = sb->s_root;
2800 return superblock_has_perm(cred, sb, FILESYSTEM__MOUNT, &ad);
2801 }
2802
selinux_sb_statfs(struct dentry * dentry)2803 static int selinux_sb_statfs(struct dentry *dentry)
2804 {
2805 const struct cred *cred = current_cred();
2806 struct common_audit_data ad;
2807
2808 ad.type = LSM_AUDIT_DATA_DENTRY;
2809 ad.u.dentry = dentry->d_sb->s_root;
2810 return superblock_has_perm(cred, dentry->d_sb, FILESYSTEM__GETATTR, &ad);
2811 }
2812
selinux_mount(const char * dev_name,const struct path * path,const char * type,unsigned long flags,void * data)2813 static int selinux_mount(const char *dev_name,
2814 const struct path *path,
2815 const char *type,
2816 unsigned long flags,
2817 void *data)
2818 {
2819 const struct cred *cred = current_cred();
2820
2821 if (flags & MS_REMOUNT)
2822 return superblock_has_perm(cred, path->dentry->d_sb,
2823 FILESYSTEM__REMOUNT, NULL);
2824 else
2825 return path_has_perm(cred, path, FILE__MOUNTON);
2826 }
2827
selinux_move_mount(const struct path * from_path,const struct path * to_path)2828 static int selinux_move_mount(const struct path *from_path,
2829 const struct path *to_path)
2830 {
2831 const struct cred *cred = current_cred();
2832
2833 return path_has_perm(cred, to_path, FILE__MOUNTON);
2834 }
2835
selinux_umount(struct vfsmount * mnt,int flags)2836 static int selinux_umount(struct vfsmount *mnt, int flags)
2837 {
2838 const struct cred *cred = current_cred();
2839
2840 return superblock_has_perm(cred, mnt->mnt_sb,
2841 FILESYSTEM__UNMOUNT, NULL);
2842 }
2843
selinux_fs_context_submount(struct fs_context * fc,struct super_block * reference)2844 static int selinux_fs_context_submount(struct fs_context *fc,
2845 struct super_block *reference)
2846 {
2847 const struct superblock_security_struct *sbsec = selinux_superblock(reference);
2848 struct selinux_mnt_opts *opts;
2849
2850 /*
2851 * Ensure that fc->security remains NULL when no options are set
2852 * as expected by selinux_set_mnt_opts().
2853 */
2854 if (!(sbsec->flags & (FSCONTEXT_MNT|CONTEXT_MNT|DEFCONTEXT_MNT)))
2855 return 0;
2856
2857 opts = kzalloc_obj(*opts);
2858 if (!opts)
2859 return -ENOMEM;
2860
2861 if (sbsec->flags & FSCONTEXT_MNT)
2862 opts->fscontext_sid = sbsec->sid;
2863 if (sbsec->flags & CONTEXT_MNT)
2864 opts->context_sid = sbsec->mntpoint_sid;
2865 if (sbsec->flags & DEFCONTEXT_MNT)
2866 opts->defcontext_sid = sbsec->def_sid;
2867 fc->security = opts;
2868 return 0;
2869 }
2870
selinux_fs_context_dup(struct fs_context * fc,struct fs_context * src_fc)2871 static int selinux_fs_context_dup(struct fs_context *fc,
2872 struct fs_context *src_fc)
2873 {
2874 const struct selinux_mnt_opts *src = src_fc->security;
2875
2876 if (!src)
2877 return 0;
2878
2879 fc->security = kmemdup(src, sizeof(*src), GFP_KERNEL);
2880 return fc->security ? 0 : -ENOMEM;
2881 }
2882
2883 static const struct fs_parameter_spec selinux_fs_parameters[] = {
2884 fsparam_string(CONTEXT_STR, Opt_context),
2885 fsparam_string(DEFCONTEXT_STR, Opt_defcontext),
2886 fsparam_string(FSCONTEXT_STR, Opt_fscontext),
2887 fsparam_string(ROOTCONTEXT_STR, Opt_rootcontext),
2888 fsparam_flag (SECLABEL_STR, Opt_seclabel),
2889 {}
2890 };
2891
selinux_fs_context_parse_param(struct fs_context * fc,struct fs_parameter * param)2892 static int selinux_fs_context_parse_param(struct fs_context *fc,
2893 struct fs_parameter *param)
2894 {
2895 struct fs_parse_result result;
2896 int opt;
2897
2898 opt = fs_parse(fc, selinux_fs_parameters, param, &result);
2899 if (opt < 0)
2900 return opt;
2901
2902 return selinux_add_opt(opt, param->string, &fc->security);
2903 }
2904
2905 /* inode security operations */
2906
selinux_inode_alloc_security(struct inode * inode)2907 static int selinux_inode_alloc_security(struct inode *inode)
2908 {
2909 struct inode_security_struct *isec = selinux_inode(inode);
2910 u32 sid = current_sid();
2911
2912 spin_lock_init(&isec->lock);
2913 INIT_LIST_HEAD(&isec->list);
2914 isec->inode = inode;
2915 isec->sid = SECINITSID_UNLABELED;
2916 isec->sclass = SECCLASS_FILE;
2917 isec->task_sid = sid;
2918 isec->initialized = LABEL_INVALID;
2919
2920 return 0;
2921 }
2922
selinux_inode_free_security(struct inode * inode)2923 static void selinux_inode_free_security(struct inode *inode)
2924 {
2925 inode_free_security(inode);
2926 }
2927
selinux_dentry_init_security(struct dentry * dentry,int mode,const struct qstr * name,const char ** xattr_name,struct lsm_context * cp)2928 static int selinux_dentry_init_security(struct dentry *dentry, int mode,
2929 const struct qstr *name,
2930 const char **xattr_name,
2931 struct lsm_context *cp)
2932 {
2933 u32 newsid;
2934 int rc;
2935
2936 rc = selinux_determine_inode_label(selinux_cred(current_cred()),
2937 d_inode(dentry->d_parent), name,
2938 inode_mode_to_security_class(mode),
2939 &newsid);
2940 if (rc)
2941 return rc;
2942
2943 if (xattr_name)
2944 *xattr_name = XATTR_NAME_SELINUX;
2945
2946 cp->id = LSM_ID_SELINUX;
2947 return security_sid_to_context(newsid, &cp->context, &cp->len);
2948 }
2949
selinux_dentry_create_files_as(struct dentry * dentry,int mode,const struct qstr * name,const struct cred * old,struct cred * new)2950 static int selinux_dentry_create_files_as(struct dentry *dentry, int mode,
2951 const struct qstr *name,
2952 const struct cred *old,
2953 struct cred *new)
2954 {
2955 u32 newsid;
2956 int rc;
2957 struct cred_security_struct *crsec;
2958
2959 rc = selinux_determine_inode_label(selinux_cred(old),
2960 d_inode(dentry->d_parent), name,
2961 inode_mode_to_security_class(mode),
2962 &newsid);
2963 if (rc)
2964 return rc;
2965
2966 crsec = selinux_cred(new);
2967 crsec->create_sid = newsid;
2968 return 0;
2969 }
2970
selinux_inode_init_security(struct inode * inode,struct inode * dir,const struct qstr * qstr,struct xattr * xattrs,int * xattr_count)2971 static int selinux_inode_init_security(struct inode *inode, struct inode *dir,
2972 const struct qstr *qstr,
2973 struct xattr *xattrs, int *xattr_count)
2974 {
2975 const struct cred_security_struct *crsec = selinux_cred(current_cred());
2976 struct superblock_security_struct *sbsec;
2977 struct xattr *xattr;
2978 u32 newsid, clen;
2979 u16 newsclass;
2980 int rc;
2981 char *context;
2982
2983 sbsec = selinux_superblock(dir->i_sb);
2984
2985 if (!selinux_initialized() ||
2986 !(sbsec->flags & SBLABEL_MNT))
2987 return -EOPNOTSUPP;
2988
2989 newsid = crsec->create_sid;
2990 newsclass = inode_mode_to_security_class(inode->i_mode);
2991 rc = selinux_determine_inode_label(crsec, dir, qstr, newsclass, &newsid);
2992 if (rc)
2993 return rc;
2994
2995 /* Possibly defer initialization to selinux_complete_init. */
2996 if (sbsec->flags & SE_SBINITIALIZED) {
2997 struct inode_security_struct *isec = selinux_inode(inode);
2998 isec->sclass = newsclass;
2999 isec->sid = newsid;
3000 isec->initialized = LABEL_INITIALIZED;
3001 }
3002
3003 xattr = lsm_get_xattr_slot(xattrs, xattr_count);
3004 if (xattr) {
3005 rc = security_sid_to_context_force(newsid,
3006 &context, &clen);
3007 if (rc)
3008 return rc;
3009 xattr->value = context;
3010 xattr->value_len = clen;
3011 xattr->name = XATTR_SELINUX_SUFFIX;
3012 }
3013
3014 return 0;
3015 }
3016
selinux_inode_init_security_anon(struct inode * inode,const struct qstr * name,const struct inode * context_inode)3017 static int selinux_inode_init_security_anon(struct inode *inode,
3018 const struct qstr *name,
3019 const struct inode *context_inode)
3020 {
3021 u32 sid = current_sid();
3022 struct common_audit_data ad;
3023 struct inode_security_struct *isec;
3024 int rc;
3025 bool is_memfd = false;
3026
3027 if (unlikely(!selinux_initialized()))
3028 return 0;
3029
3030 if (name != NULL && name->name != NULL &&
3031 !strcmp(name->name, MEMFD_ANON_NAME)) {
3032 if (!selinux_policycap_memfd_class())
3033 return 0;
3034 is_memfd = true;
3035 }
3036
3037 isec = selinux_inode(inode);
3038
3039 /*
3040 * We only get here once per ephemeral inode. The inode has
3041 * been initialized via inode_alloc_security but is otherwise
3042 * untouched.
3043 */
3044
3045 if (context_inode) {
3046 struct inode_security_struct *context_isec =
3047 selinux_inode(context_inode);
3048 if (context_isec->initialized != LABEL_INITIALIZED) {
3049 pr_err("SELinux: context_inode is not initialized\n");
3050 return -EACCES;
3051 }
3052
3053 isec->sclass = context_isec->sclass;
3054 isec->sid = context_isec->sid;
3055 } else {
3056 if (is_memfd)
3057 isec->sclass = SECCLASS_MEMFD_FILE;
3058 else
3059 isec->sclass = SECCLASS_ANON_INODE;
3060 rc = security_transition_sid(
3061 sid, sid,
3062 isec->sclass, name, &isec->sid);
3063 if (rc)
3064 return rc;
3065 }
3066
3067 isec->initialized = LABEL_INITIALIZED;
3068 /*
3069 * Now that we've initialized security, check whether we're
3070 * allowed to actually create this type of anonymous inode.
3071 */
3072
3073 ad.type = LSM_AUDIT_DATA_ANONINODE;
3074 ad.u.anonclass = name ? (const char *)name->name : "?";
3075
3076 return avc_has_perm(sid,
3077 isec->sid,
3078 isec->sclass,
3079 FILE__CREATE,
3080 &ad);
3081 }
3082
selinux_inode_create(struct inode * dir,struct dentry * dentry,umode_t mode)3083 static int selinux_inode_create(struct inode *dir, struct dentry *dentry, umode_t mode)
3084 {
3085 return may_create(dir, dentry, SECCLASS_FILE);
3086 }
3087
selinux_inode_link(struct dentry * old_dentry,struct inode * dir,struct dentry * new_dentry)3088 static int selinux_inode_link(struct dentry *old_dentry, struct inode *dir, struct dentry *new_dentry)
3089 {
3090 return may_link(dir, old_dentry, MAY_LINK);
3091 }
3092
selinux_inode_unlink(struct inode * dir,struct dentry * dentry)3093 static int selinux_inode_unlink(struct inode *dir, struct dentry *dentry)
3094 {
3095 return may_link(dir, dentry, MAY_UNLINK);
3096 }
3097
selinux_inode_symlink(struct inode * dir,struct dentry * dentry,const char * name)3098 static int selinux_inode_symlink(struct inode *dir, struct dentry *dentry, const char *name)
3099 {
3100 return may_create(dir, dentry, SECCLASS_LNK_FILE);
3101 }
3102
selinux_inode_mkdir(struct inode * dir,struct dentry * dentry,umode_t mask)3103 static int selinux_inode_mkdir(struct inode *dir, struct dentry *dentry, umode_t mask)
3104 {
3105 return may_create(dir, dentry, SECCLASS_DIR);
3106 }
3107
selinux_inode_rmdir(struct inode * dir,struct dentry * dentry)3108 static int selinux_inode_rmdir(struct inode *dir, struct dentry *dentry)
3109 {
3110 return may_link(dir, dentry, MAY_RMDIR);
3111 }
3112
selinux_inode_mknod(struct inode * dir,struct dentry * dentry,umode_t mode,dev_t dev)3113 static int selinux_inode_mknod(struct inode *dir, struct dentry *dentry, umode_t mode, dev_t dev)
3114 {
3115 return may_create(dir, dentry, inode_mode_to_security_class(mode));
3116 }
3117
selinux_inode_rename(struct inode * old_inode,struct dentry * old_dentry,struct inode * new_inode,struct dentry * new_dentry)3118 static int selinux_inode_rename(struct inode *old_inode, struct dentry *old_dentry,
3119 struct inode *new_inode, struct dentry *new_dentry)
3120 {
3121 return may_rename(old_inode, old_dentry, new_inode, new_dentry);
3122 }
3123
selinux_inode_readlink(struct dentry * dentry)3124 static int selinux_inode_readlink(struct dentry *dentry)
3125 {
3126 const struct cred *cred = current_cred();
3127
3128 return dentry_has_perm(cred, dentry, FILE__READ);
3129 }
3130
selinux_inode_follow_link(struct dentry * dentry,struct inode * inode,bool rcu)3131 static int selinux_inode_follow_link(struct dentry *dentry, struct inode *inode,
3132 bool rcu)
3133 {
3134 struct common_audit_data ad;
3135 struct inode_security_struct *isec;
3136 u32 sid = current_sid();
3137
3138 ad.type = LSM_AUDIT_DATA_DENTRY;
3139 ad.u.dentry = dentry;
3140 isec = inode_security_rcu(inode, rcu);
3141 if (IS_ERR(isec))
3142 return PTR_ERR(isec);
3143
3144 return avc_has_perm(sid, isec->sid, isec->sclass, FILE__READ, &ad);
3145 }
3146
audit_inode_permission(struct inode * inode,u32 perms,u32 audited,u32 denied,int result)3147 static noinline int audit_inode_permission(struct inode *inode,
3148 u32 perms, u32 audited, u32 denied,
3149 int result)
3150 {
3151 struct common_audit_data ad;
3152 struct inode_security_struct *isec = selinux_inode(inode);
3153
3154 ad.type = LSM_AUDIT_DATA_INODE;
3155 ad.u.inode = inode;
3156
3157 return slow_avc_audit(current_sid(), isec->sid, isec->sclass, perms,
3158 audited, denied, result, &ad);
3159 }
3160
3161 /**
3162 * task_avdcache_reset - Reset the task's AVD cache
3163 * @tsec: the task's security state
3164 *
3165 * Clear the task's AVD cache in @tsec and reset it to the current policy's
3166 * and task's info.
3167 */
task_avdcache_reset(struct task_security_struct * tsec)3168 static inline void task_avdcache_reset(struct task_security_struct *tsec)
3169 {
3170 memset(&tsec->avdcache.dir, 0, sizeof(tsec->avdcache.dir));
3171 tsec->avdcache.sid = current_sid();
3172 tsec->avdcache.seqno = avc_policy_seqno();
3173 tsec->avdcache.dir_spot = TSEC_AVDC_DIR_SIZE - 1;
3174 }
3175
3176 /**
3177 * task_avdcache_search - Search the task's AVD cache
3178 * @tsec: the task's security state
3179 * @isec: the inode to search for in the cache
3180 * @avdc: matching avd cache entry returned to the caller
3181 *
3182 * Search @tsec for a AVD cache entry that matches @isec and return it to the
3183 * caller via @avdc. Returns 0 if a match is found, negative values otherwise.
3184 */
task_avdcache_search(struct task_security_struct * tsec,struct inode_security_struct * isec,struct avdc_entry ** avdc)3185 static inline int task_avdcache_search(struct task_security_struct *tsec,
3186 struct inode_security_struct *isec,
3187 struct avdc_entry **avdc)
3188 {
3189 int orig, iter;
3190
3191 /* focused on path walk optimization, only cache directories */
3192 if (isec->sclass != SECCLASS_DIR)
3193 return -ENOENT;
3194
3195 if (unlikely(current_sid() != tsec->avdcache.sid ||
3196 tsec->avdcache.seqno != avc_policy_seqno())) {
3197 task_avdcache_reset(tsec);
3198 return -ENOENT;
3199 }
3200
3201 orig = iter = tsec->avdcache.dir_spot;
3202 do {
3203 if (tsec->avdcache.dir[iter].isid == isec->sid) {
3204 /* cache hit */
3205 tsec->avdcache.dir_spot = iter;
3206 *avdc = &tsec->avdcache.dir[iter];
3207 return 0;
3208 }
3209 iter = (iter - 1) & (TSEC_AVDC_DIR_SIZE - 1);
3210 } while (iter != orig);
3211
3212 return -ENOENT;
3213 }
3214
3215 /**
3216 * task_avdcache_update - Update the task's AVD cache
3217 * @tsec: the task's security state
3218 * @isec: the inode associated with the cache entry
3219 * @avd: the AVD to cache
3220 *
3221 * Update the AVD cache in @tsec with the @avd info associated
3222 * with @isec.
3223 */
task_avdcache_update(struct task_security_struct * tsec,struct inode_security_struct * isec,struct av_decision * avd)3224 static inline void task_avdcache_update(struct task_security_struct *tsec,
3225 struct inode_security_struct *isec,
3226 struct av_decision *avd)
3227 {
3228 int spot;
3229
3230 /* focused on path walk optimization, only cache directories */
3231 if (isec->sclass != SECCLASS_DIR)
3232 return;
3233
3234 /* update cache */
3235 spot = (tsec->avdcache.dir_spot + 1) & (TSEC_AVDC_DIR_SIZE - 1);
3236 tsec->avdcache.dir_spot = spot;
3237 tsec->avdcache.dir[spot].isid = isec->sid;
3238 tsec->avdcache.dir[spot].avd = *avd;
3239 tsec->avdcache.permissive_neveraudit =
3240 (avd->flags == (AVD_FLAGS_PERMISSIVE|AVD_FLAGS_NEVERAUDIT));
3241 }
3242
3243 /**
3244 * selinux_inode_permission - Check if the current task can access an inode
3245 * @inode: the inode that is being accessed
3246 * @requested: the accesses being requested
3247 *
3248 * Check if the current task is allowed to access @inode according to
3249 * @requested. Returns 0 if allowed, negative values otherwise.
3250 */
selinux_inode_permission(struct inode * inode,int requested)3251 static int selinux_inode_permission(struct inode *inode, int requested)
3252 {
3253 int mask;
3254 u32 perms;
3255 u32 sid = current_sid();
3256 struct task_security_struct *tsec;
3257 struct inode_security_struct *isec;
3258 struct avdc_entry *avdc;
3259 struct av_decision avd, *avdp = &avd;
3260 int rc, rc2;
3261 u32 audited, denied;
3262
3263 mask = requested & (MAY_READ|MAY_WRITE|MAY_EXEC|MAY_APPEND);
3264
3265 /* No permission to check. Existence test. */
3266 if (!mask)
3267 return 0;
3268
3269 tsec = selinux_task(current);
3270 if (task_avdcache_permnoaudit(tsec, sid))
3271 return 0;
3272
3273 isec = inode_security_rcu(inode, requested & MAY_NOT_BLOCK);
3274 if (IS_ERR(isec))
3275 return PTR_ERR(isec);
3276 perms = file_mask_to_av(inode->i_mode, mask);
3277
3278 rc = task_avdcache_search(tsec, isec, &avdc);
3279 if (likely(!rc)) {
3280 /* Cache hit. */
3281 avdp = &avdc->avd;
3282 denied = perms & ~avdp->allowed;
3283 if (unlikely(denied) && enforcing_enabled() &&
3284 !(avdp->flags & AVD_FLAGS_PERMISSIVE))
3285 rc = -EACCES;
3286 } else {
3287 /* Cache miss. */
3288 rc = avc_has_perm_noaudit(sid, isec->sid, isec->sclass,
3289 perms, 0, avdp);
3290 task_avdcache_update(tsec, isec, avdp);
3291 }
3292
3293 audited = avc_audit_required(perms, avdp, rc,
3294 (requested & MAY_ACCESS) ?
3295 FILE__AUDIT_ACCESS : 0, &denied);
3296 if (likely(!audited))
3297 return rc;
3298
3299 rc2 = audit_inode_permission(inode, perms, audited, denied, rc);
3300 if (rc2)
3301 return rc2;
3302
3303 return rc;
3304 }
3305
selinux_inode_setattr(struct mnt_idmap * idmap,struct dentry * dentry,struct iattr * iattr)3306 static int selinux_inode_setattr(struct mnt_idmap *idmap, struct dentry *dentry,
3307 struct iattr *iattr)
3308 {
3309 const struct cred *cred = current_cred();
3310 struct inode *inode = d_backing_inode(dentry);
3311 unsigned int ia_valid = iattr->ia_valid;
3312 u32 av = FILE__WRITE;
3313
3314 /* ATTR_FORCE is just used for ATTR_KILL_S[UG]ID. */
3315 if (ia_valid & ATTR_FORCE) {
3316 ia_valid &= ~(ATTR_KILL_SUID | ATTR_KILL_SGID | ATTR_MODE |
3317 ATTR_FORCE);
3318 if (!ia_valid)
3319 return 0;
3320 }
3321
3322 if (ia_valid & (ATTR_MODE | ATTR_UID | ATTR_GID |
3323 ATTR_ATIME_SET | ATTR_MTIME_SET | ATTR_TIMES_SET))
3324 return dentry_has_perm(cred, dentry, FILE__SETATTR);
3325
3326 if (selinux_policycap_openperm() &&
3327 inode->i_sb->s_magic != SOCKFS_MAGIC &&
3328 (ia_valid & ATTR_SIZE) &&
3329 !(ia_valid & ATTR_FILE))
3330 av |= FILE__OPEN;
3331
3332 return dentry_has_perm(cred, dentry, av);
3333 }
3334
selinux_inode_getattr(const struct path * path)3335 static int selinux_inode_getattr(const struct path *path)
3336 {
3337 struct task_security_struct *tsec;
3338
3339 tsec = selinux_task(current);
3340
3341 if (task_avdcache_permnoaudit(tsec, current_sid()))
3342 return 0;
3343
3344 return path_has_perm(current_cred(), path, FILE__GETATTR);
3345 }
3346
has_cap_mac_admin(bool audit)3347 static bool has_cap_mac_admin(bool audit)
3348 {
3349 const struct cred *cred = current_cred();
3350 unsigned int opts = audit ? CAP_OPT_NONE : CAP_OPT_NOAUDIT;
3351
3352 if (cap_capable(cred, &init_user_ns, CAP_MAC_ADMIN, opts))
3353 return false;
3354 if (cred_has_capability(cred, CAP_MAC_ADMIN, opts, true))
3355 return false;
3356 return true;
3357 }
3358
3359 /**
3360 * selinux_inode_xattr_skipcap - Skip the xattr capability checks?
3361 * @name: name of the xattr
3362 *
3363 * Returns 1 to indicate that SELinux "owns" the access control rights to xattrs
3364 * named @name; the LSM layer should avoid enforcing any traditional
3365 * capability based access controls on this xattr. Returns 0 to indicate that
3366 * SELinux does not "own" the access control rights to xattrs named @name and is
3367 * deferring to the LSM layer for further access controls, including capability
3368 * based controls.
3369 */
selinux_inode_xattr_skipcap(const char * name)3370 static int selinux_inode_xattr_skipcap(const char *name)
3371 {
3372 /* require capability check if not a selinux xattr */
3373 return !strcmp(name, XATTR_NAME_SELINUX);
3374 }
3375
selinux_inode_setxattr(struct mnt_idmap * idmap,struct dentry * dentry,const char * name,const void * value,size_t size,int flags)3376 static int selinux_inode_setxattr(struct mnt_idmap *idmap,
3377 struct dentry *dentry, const char *name,
3378 const void *value, size_t size, int flags)
3379 {
3380 struct inode *inode = d_backing_inode(dentry);
3381 struct inode_security_struct *isec;
3382 struct superblock_security_struct *sbsec;
3383 struct common_audit_data ad;
3384 u32 newsid, sid = current_sid();
3385 int rc = 0;
3386
3387 /* if not a selinux xattr, only check the ordinary setattr perm */
3388 if (strcmp(name, XATTR_NAME_SELINUX))
3389 return dentry_has_perm(current_cred(), dentry, FILE__SETATTR);
3390
3391 if (!selinux_initialized())
3392 return (inode_owner_or_capable(idmap, inode) ? 0 : -EPERM);
3393
3394 sbsec = selinux_superblock(inode->i_sb);
3395 if (!(sbsec->flags & SBLABEL_MNT))
3396 return -EOPNOTSUPP;
3397
3398 if (!inode_owner_or_capable(idmap, inode))
3399 return -EPERM;
3400
3401 ad.type = LSM_AUDIT_DATA_DENTRY;
3402 ad.u.dentry = dentry;
3403
3404 isec = backing_inode_security(dentry);
3405 rc = avc_has_perm(sid, isec->sid, isec->sclass,
3406 FILE__RELABELFROM, &ad);
3407 if (rc)
3408 return rc;
3409
3410 rc = security_context_to_sid(value, size, &newsid,
3411 GFP_KERNEL);
3412 if (rc == -EINVAL) {
3413 if (!has_cap_mac_admin(true)) {
3414 struct audit_buffer *ab;
3415 size_t audit_size;
3416
3417 /* We strip a nul only if it is at the end, otherwise the
3418 * context contains a nul and we should audit that */
3419 if (value) {
3420 const char *str = value;
3421
3422 if (str[size - 1] == '\0')
3423 audit_size = size - 1;
3424 else
3425 audit_size = size;
3426 } else {
3427 audit_size = 0;
3428 }
3429 ab = audit_log_start(audit_context(),
3430 GFP_ATOMIC, AUDIT_SELINUX_ERR);
3431 if (!ab)
3432 return rc;
3433 audit_log_format(ab, "op=setxattr invalid_context=");
3434 audit_log_n_untrustedstring(ab, value, audit_size);
3435 audit_log_end(ab);
3436
3437 return rc;
3438 }
3439 rc = security_context_to_sid_force(value,
3440 size, &newsid);
3441 }
3442 if (rc)
3443 return rc;
3444
3445 rc = avc_has_perm(sid, newsid, isec->sclass,
3446 FILE__RELABELTO, &ad);
3447 if (rc)
3448 return rc;
3449
3450 rc = security_validate_transition(isec->sid, newsid,
3451 sid, isec->sclass);
3452 if (rc)
3453 return rc;
3454
3455 return avc_has_perm(newsid,
3456 sbsec->sid,
3457 SECCLASS_FILESYSTEM,
3458 FILESYSTEM__ASSOCIATE,
3459 &ad);
3460 }
3461
selinux_inode_set_acl(struct mnt_idmap * idmap,struct dentry * dentry,const char * acl_name,struct posix_acl * kacl)3462 static int selinux_inode_set_acl(struct mnt_idmap *idmap,
3463 struct dentry *dentry, const char *acl_name,
3464 struct posix_acl *kacl)
3465 {
3466 return dentry_has_perm(current_cred(), dentry, FILE__SETATTR);
3467 }
3468
selinux_inode_get_acl(struct mnt_idmap * idmap,struct dentry * dentry,const char * acl_name)3469 static int selinux_inode_get_acl(struct mnt_idmap *idmap,
3470 struct dentry *dentry, const char *acl_name)
3471 {
3472 return dentry_has_perm(current_cred(), dentry, FILE__GETATTR);
3473 }
3474
selinux_inode_remove_acl(struct mnt_idmap * idmap,struct dentry * dentry,const char * acl_name)3475 static int selinux_inode_remove_acl(struct mnt_idmap *idmap,
3476 struct dentry *dentry, const char *acl_name)
3477 {
3478 return dentry_has_perm(current_cred(), dentry, FILE__SETATTR);
3479 }
3480
selinux_inode_post_setxattr(struct dentry * dentry,const char * name,const void * value,size_t size,int flags)3481 static void selinux_inode_post_setxattr(struct dentry *dentry, const char *name,
3482 const void *value, size_t size,
3483 int flags)
3484 {
3485 struct inode *inode = d_backing_inode(dentry);
3486 struct inode_security_struct *isec;
3487 u32 newsid;
3488 int rc;
3489
3490 if (strcmp(name, XATTR_NAME_SELINUX)) {
3491 /* Not an attribute we recognize, so nothing to do. */
3492 return;
3493 }
3494
3495 if (!selinux_initialized()) {
3496 /* If we haven't even been initialized, then we can't validate
3497 * against a policy, so leave the label as invalid. It may
3498 * resolve to a valid label on the next revalidation try if
3499 * we've since initialized.
3500 */
3501 return;
3502 }
3503
3504 rc = security_context_to_sid_force(value, size,
3505 &newsid);
3506 if (rc) {
3507 pr_err("SELinux: unable to map context to SID"
3508 "for (%s, %llu), rc=%d\n",
3509 inode->i_sb->s_id, inode->i_ino, -rc);
3510 return;
3511 }
3512
3513 isec = backing_inode_security(dentry);
3514 spin_lock(&isec->lock);
3515 isec->sclass = inode_mode_to_security_class(inode->i_mode);
3516 isec->sid = newsid;
3517 isec->initialized = LABEL_INITIALIZED;
3518 spin_unlock(&isec->lock);
3519 }
3520
selinux_inode_getxattr(struct dentry * dentry,const char * name)3521 static int selinux_inode_getxattr(struct dentry *dentry, const char *name)
3522 {
3523 const struct cred *cred = current_cred();
3524
3525 return dentry_has_perm(cred, dentry, FILE__GETATTR);
3526 }
3527
selinux_inode_listxattr(struct dentry * dentry)3528 static int selinux_inode_listxattr(struct dentry *dentry)
3529 {
3530 const struct cred *cred = current_cred();
3531
3532 return dentry_has_perm(cred, dentry, FILE__GETATTR);
3533 }
3534
selinux_inode_removexattr(struct mnt_idmap * idmap,struct dentry * dentry,const char * name)3535 static int selinux_inode_removexattr(struct mnt_idmap *idmap,
3536 struct dentry *dentry, const char *name)
3537 {
3538 /* if not a selinux xattr, only check the ordinary setattr perm */
3539 if (strcmp(name, XATTR_NAME_SELINUX))
3540 return dentry_has_perm(current_cred(), dentry, FILE__SETATTR);
3541
3542 if (!selinux_initialized())
3543 return 0;
3544
3545 /* No one is allowed to remove a SELinux security label.
3546 You can change the label, but all data must be labeled. */
3547 return -EACCES;
3548 }
3549
selinux_inode_file_setattr(struct dentry * dentry,struct file_kattr * fa)3550 static int selinux_inode_file_setattr(struct dentry *dentry,
3551 struct file_kattr *fa)
3552 {
3553 return dentry_has_perm(current_cred(), dentry, FILE__SETATTR);
3554 }
3555
selinux_inode_file_getattr(struct dentry * dentry,struct file_kattr * fa)3556 static int selinux_inode_file_getattr(struct dentry *dentry,
3557 struct file_kattr *fa)
3558 {
3559 return dentry_has_perm(current_cred(), dentry, FILE__GETATTR);
3560 }
3561
selinux_path_notify(const struct path * path,u64 mask,unsigned int obj_type)3562 static int selinux_path_notify(const struct path *path, u64 mask,
3563 unsigned int obj_type)
3564 {
3565 int ret;
3566 u32 perm;
3567
3568 struct common_audit_data ad;
3569
3570 ad.type = LSM_AUDIT_DATA_PATH;
3571 ad.u.path = *path;
3572
3573 /*
3574 * Set permission needed based on the type of mark being set.
3575 * Performs an additional check for sb watches.
3576 */
3577 switch (obj_type) {
3578 case FSNOTIFY_OBJ_TYPE_VFSMOUNT:
3579 perm = FILE__WATCH_MOUNT;
3580 break;
3581 case FSNOTIFY_OBJ_TYPE_SB:
3582 perm = FILE__WATCH_SB;
3583 ret = superblock_has_perm(current_cred(), path->dentry->d_sb,
3584 FILESYSTEM__WATCH, &ad);
3585 if (ret)
3586 return ret;
3587 break;
3588 case FSNOTIFY_OBJ_TYPE_INODE:
3589 perm = FILE__WATCH;
3590 break;
3591 case FSNOTIFY_OBJ_TYPE_MNTNS:
3592 perm = FILE__WATCH_MOUNTNS;
3593 break;
3594 default:
3595 return -EINVAL;
3596 }
3597
3598 /* blocking watches require the file:watch_with_perm permission */
3599 if (mask & (ALL_FSNOTIFY_PERM_EVENTS))
3600 perm |= FILE__WATCH_WITH_PERM;
3601
3602 /* watches on read-like events need the file:watch_reads permission */
3603 if (mask & (FS_ACCESS | FS_ACCESS_PERM | FS_PRE_ACCESS |
3604 FS_CLOSE_NOWRITE))
3605 perm |= FILE__WATCH_READS;
3606
3607 return path_has_perm(current_cred(), path, perm);
3608 }
3609
3610 /*
3611 * Copy the inode security context value to the user.
3612 *
3613 * Permission check is handled by selinux_inode_getxattr hook.
3614 */
selinux_inode_getsecurity(struct mnt_idmap * idmap,struct inode * inode,const char * name,void ** buffer,bool alloc)3615 static int selinux_inode_getsecurity(struct mnt_idmap *idmap,
3616 struct inode *inode, const char *name,
3617 void **buffer, bool alloc)
3618 {
3619 u32 size;
3620 int error;
3621 char *context = NULL;
3622 struct inode_security_struct *isec;
3623
3624 /*
3625 * If we're not initialized yet, then we can't validate contexts, so
3626 * just let vfs_getxattr fall back to using the on-disk xattr.
3627 */
3628 if (!selinux_initialized() ||
3629 strcmp(name, XATTR_SELINUX_SUFFIX))
3630 return -EOPNOTSUPP;
3631
3632 /*
3633 * If the caller has CAP_MAC_ADMIN, then get the raw context
3634 * value even if it is not defined by current policy; otherwise,
3635 * use the in-core value under current policy.
3636 * Use the non-auditing forms of the permission checks since
3637 * getxattr may be called by unprivileged processes commonly
3638 * and lack of permission just means that we fall back to the
3639 * in-core context value, not a denial.
3640 */
3641 isec = inode_security(inode);
3642 if (has_cap_mac_admin(false))
3643 error = security_sid_to_context_force(isec->sid, &context,
3644 &size);
3645 else
3646 error = security_sid_to_context(isec->sid,
3647 &context, &size);
3648 if (error)
3649 return error;
3650 error = size;
3651 if (alloc) {
3652 *buffer = context;
3653 goto out_nofree;
3654 }
3655 kfree(context);
3656 out_nofree:
3657 return error;
3658 }
3659
selinux_inode_setsecurity(struct inode * inode,const char * name,const void * value,size_t size,int flags)3660 static int selinux_inode_setsecurity(struct inode *inode, const char *name,
3661 const void *value, size_t size, int flags)
3662 {
3663 struct inode_security_struct *isec = inode_security_novalidate(inode);
3664 struct superblock_security_struct *sbsec;
3665 u32 newsid;
3666 int rc;
3667
3668 if (strcmp(name, XATTR_SELINUX_SUFFIX))
3669 return -EOPNOTSUPP;
3670
3671 sbsec = selinux_superblock(inode->i_sb);
3672 if (!(sbsec->flags & SBLABEL_MNT))
3673 return -EOPNOTSUPP;
3674
3675 if (!value || !size)
3676 return -EACCES;
3677
3678 rc = security_context_to_sid(value, size, &newsid,
3679 GFP_KERNEL);
3680 if (rc)
3681 return rc;
3682
3683 spin_lock(&isec->lock);
3684 isec->sclass = inode_mode_to_security_class(inode->i_mode);
3685 isec->sid = newsid;
3686 isec->initialized = LABEL_INITIALIZED;
3687 spin_unlock(&isec->lock);
3688 return 0;
3689 }
3690
selinux_inode_listsecurity(struct inode * inode,char ** buffer,ssize_t * remaining_size)3691 static int selinux_inode_listsecurity(struct inode *inode, char **buffer,
3692 ssize_t *remaining_size)
3693 {
3694 if (!selinux_initialized())
3695 return 0;
3696 return xattr_list_one(buffer, remaining_size, XATTR_NAME_SELINUX);
3697 }
3698
selinux_inode_getlsmprop(struct inode * inode,struct lsm_prop * prop)3699 static void selinux_inode_getlsmprop(struct inode *inode, struct lsm_prop *prop)
3700 {
3701 struct inode_security_struct *isec = inode_security_novalidate(inode);
3702
3703 prop->selinux.secid = isec->sid;
3704 }
3705
selinux_inode_copy_up(struct dentry * src,struct cred ** new)3706 static int selinux_inode_copy_up(struct dentry *src, struct cred **new)
3707 {
3708 struct lsm_prop prop;
3709 struct cred_security_struct *crsec;
3710 struct cred *new_creds = *new;
3711
3712 if (new_creds == NULL) {
3713 new_creds = prepare_creds();
3714 if (!new_creds)
3715 return -ENOMEM;
3716 }
3717
3718 crsec = selinux_cred(new_creds);
3719 /* Get label from overlay inode and set it in create_sid */
3720 selinux_inode_getlsmprop(d_inode(src), &prop);
3721 crsec->create_sid = prop.selinux.secid;
3722 *new = new_creds;
3723 return 0;
3724 }
3725
selinux_inode_copy_up_xattr(struct dentry * dentry,const char * name)3726 static int selinux_inode_copy_up_xattr(struct dentry *dentry, const char *name)
3727 {
3728 /* The copy_up hook above sets the initial context on an inode, but we
3729 * don't then want to overwrite it by blindly copying all the lower
3730 * xattrs up. Instead, filter out SELinux-related xattrs following
3731 * policy load.
3732 */
3733 if (selinux_initialized() && !strcmp(name, XATTR_NAME_SELINUX))
3734 return -ECANCELED; /* Discard */
3735 /*
3736 * Any other attribute apart from SELINUX is not claimed, supported
3737 * by selinux.
3738 */
3739 return -EOPNOTSUPP;
3740 }
3741
3742 /* kernfs node operations */
3743
selinux_kernfs_init_security(struct kernfs_node * kn_dir,struct kernfs_node * kn)3744 static int selinux_kernfs_init_security(struct kernfs_node *kn_dir,
3745 struct kernfs_node *kn)
3746 {
3747 const struct cred_security_struct *crsec = selinux_cred(current_cred());
3748 u32 parent_sid, newsid, clen;
3749 int rc;
3750 char *context;
3751
3752 rc = kernfs_xattr_get(kn_dir, XATTR_NAME_SELINUX, NULL, 0);
3753 if (rc == -ENODATA)
3754 return 0;
3755 else if (rc < 0)
3756 return rc;
3757
3758 clen = (u32)rc;
3759 context = kmalloc(clen, GFP_KERNEL);
3760 if (!context)
3761 return -ENOMEM;
3762
3763 rc = kernfs_xattr_get(kn_dir, XATTR_NAME_SELINUX, context, clen);
3764 if (rc < 0) {
3765 kfree(context);
3766 return rc;
3767 }
3768
3769 rc = security_context_to_sid(context, clen, &parent_sid,
3770 GFP_KERNEL);
3771 kfree(context);
3772 if (rc)
3773 return rc;
3774
3775 if (crsec->create_sid) {
3776 newsid = crsec->create_sid;
3777 } else {
3778 u16 secclass = inode_mode_to_security_class(kn->mode);
3779 const char *kn_name;
3780 struct qstr q;
3781
3782 /* kn is fresh, can't be renamed, name goes not away */
3783 kn_name = rcu_dereference_check(kn->name, true);
3784 q.name = kn_name;
3785 q.hash_len = hashlen_string(kn_dir, kn_name);
3786
3787 rc = security_transition_sid(crsec->sid,
3788 parent_sid, secclass, &q,
3789 &newsid);
3790 if (rc)
3791 return rc;
3792 }
3793
3794 rc = security_sid_to_context_force(newsid,
3795 &context, &clen);
3796 if (rc)
3797 return rc;
3798
3799 rc = kernfs_xattr_set(kn, XATTR_NAME_SELINUX, context, clen,
3800 XATTR_CREATE);
3801 kfree(context);
3802 return rc;
3803 }
3804
3805
3806 /* file security operations */
3807
selinux_revalidate_file_permission(struct file * file,int mask)3808 static int selinux_revalidate_file_permission(struct file *file, int mask)
3809 {
3810 const struct cred *cred = current_cred();
3811 struct inode *inode = file_inode(file);
3812
3813 /* file_mask_to_av won't add FILE__WRITE if MAY_APPEND is set */
3814 if ((file->f_flags & O_APPEND) && (mask & MAY_WRITE))
3815 mask |= MAY_APPEND;
3816
3817 return file_has_perm(cred, file,
3818 file_mask_to_av(inode->i_mode, mask));
3819 }
3820
selinux_file_permission(struct file * file,int mask)3821 static int selinux_file_permission(struct file *file, int mask)
3822 {
3823 struct inode *inode = file_inode(file);
3824 struct file_security_struct *fsec = selinux_file(file);
3825 struct inode_security_struct *isec;
3826 u32 sid = current_sid();
3827
3828 if (!mask)
3829 /* No permission to check. Existence test. */
3830 return 0;
3831
3832 isec = inode_security(inode);
3833 if (sid == fsec->sid && fsec->isid == isec->sid &&
3834 fsec->pseqno == avc_policy_seqno())
3835 /* No change since file_open check. */
3836 return 0;
3837
3838 return selinux_revalidate_file_permission(file, mask);
3839 }
3840
selinux_file_alloc_security(struct file * file)3841 static int selinux_file_alloc_security(struct file *file)
3842 {
3843 struct file_security_struct *fsec = selinux_file(file);
3844 u32 sid = current_sid();
3845
3846 fsec->sid = sid;
3847 fsec->fown_sid = sid;
3848
3849 return 0;
3850 }
3851
selinux_file_user_sid(const struct file * file)3852 static inline u32 selinux_file_user_sid(const struct file *file)
3853 {
3854 if (unlikely(file->f_mode & FMODE_BACKING))
3855 return selinux_backing_file(file)->uf_sid;
3856 return selinux_file(file)->sid;
3857 }
3858
selinux_backing_file_alloc(struct file * backing_file,const struct file * user_file)3859 static int selinux_backing_file_alloc(struct file *backing_file,
3860 const struct file *user_file)
3861 {
3862 struct backing_file_security_struct *bfsec;
3863 const struct backing_file_security_struct *ubfsec;
3864 struct backing_file_security_layer *layer;
3865 u32 i;
3866
3867 bfsec = selinux_backing_file(backing_file);
3868 bfsec->uf_sid = selinux_file_user_sid(user_file);
3869 if (!(user_file->f_mode & FMODE_BACKING))
3870 return 0;
3871
3872 ubfsec = selinux_backing_file(user_file);
3873 /* a wrapped count would make kmalloc_array() return ZERO_SIZE_PTR */
3874 if (unlikely(ubfsec->layer_count == U32_MAX))
3875 return -EOVERFLOW;
3876
3877 /*
3878 * The final VMA only retains the lowest backing file, so record the
3879 * whole chain here rather than in the mmap hook, where concurrent
3880 * mappings would have to be serialized. Size it dynamically: erofs
3881 * inode sharing adds a backing file without bumping s_stack_depth.
3882 */
3883 bfsec->layers = kmalloc_array(ubfsec->layer_count + 1,
3884 sizeof(*bfsec->layers), GFP_KERNEL);
3885 if (!bfsec->layers)
3886 return -ENOMEM;
3887
3888 for (i = 0; i < ubfsec->layer_count; i++) {
3889 layer = &bfsec->layers[i];
3890 *layer = ubfsec->layers[i];
3891 path_get(&layer->path);
3892 }
3893
3894 /* f_path, not file_user_path(): this layer, not the top-level file */
3895 layer = &bfsec->layers[i];
3896 layer->path = user_file->f_path;
3897 layer->mounter_sid = cred_sid(user_file->f_cred);
3898 layer->fd_sid = selinux_file(user_file)->sid;
3899 path_get(&layer->path);
3900 bfsec->layer_count = ubfsec->layer_count + 1;
3901
3902 return 0;
3903 }
3904
selinux_backing_file_free(struct file * backing_file)3905 static void selinux_backing_file_free(struct file *backing_file)
3906 {
3907 struct backing_file_security_struct *bfsec;
3908
3909 /* security_backing_file_free() may be called twice after an error */
3910 if (!backing_file_security(backing_file))
3911 return;
3912
3913 bfsec = selinux_backing_file(backing_file);
3914 while (bfsec->layer_count)
3915 path_put(&bfsec->layers[--bfsec->layer_count].path);
3916 kfree(bfsec->layers);
3917 bfsec->layers = NULL;
3918 }
3919
3920 /*
3921 * Check whether a task has the ioctl permission and cmd
3922 * operation to an inode.
3923 */
ioctl_has_perm(const struct cred * cred,struct file * file,u32 requested,u16 cmd)3924 static int ioctl_has_perm(const struct cred *cred, struct file *file,
3925 u32 requested, u16 cmd)
3926 {
3927 struct common_audit_data ad;
3928 struct file_security_struct *fsec = selinux_file(file);
3929 struct inode *inode = file_inode(file);
3930 struct inode_security_struct *isec;
3931 struct lsm_ioctlop_audit ioctl;
3932 u32 ssid = cred_sid(cred);
3933 int rc;
3934 u8 driver = cmd >> 8;
3935 u8 xperm = cmd & 0xff;
3936
3937 ad.type = LSM_AUDIT_DATA_IOCTL_OP;
3938 ad.u.op = &ioctl;
3939 ad.u.op->cmd = cmd;
3940 ad.u.op->path = file->f_path;
3941
3942 if (ssid != fsec->sid) {
3943 rc = avc_has_perm(ssid, fsec->sid,
3944 SECCLASS_FD,
3945 FD__USE,
3946 &ad);
3947 if (rc)
3948 goto out;
3949 }
3950
3951 if (unlikely(IS_PRIVATE(inode)))
3952 return 0;
3953
3954 isec = inode_security(inode);
3955 rc = avc_has_extended_perms(ssid, isec->sid, isec->sclass, requested,
3956 driver, AVC_EXT_IOCTL, xperm, &ad);
3957 out:
3958 return rc;
3959 }
3960
selinux_file_ioctl(struct file * file,unsigned int cmd,unsigned long arg)3961 static int selinux_file_ioctl(struct file *file, unsigned int cmd,
3962 unsigned long arg)
3963 {
3964 const struct cred *cred = current_cred();
3965 int error = 0;
3966
3967 switch (cmd) {
3968 case FIONREAD:
3969 case FIBMAP:
3970 case FIGETBSZ:
3971 case FS_IOC_GETFLAGS:
3972 case FS_IOC_GETVERSION:
3973 error = file_has_perm(cred, file, FILE__GETATTR);
3974 break;
3975
3976 case FS_IOC_SETFLAGS:
3977 case FS_IOC_SETVERSION:
3978 error = file_has_perm(cred, file, FILE__SETATTR);
3979 break;
3980
3981 /* sys_ioctl() checks */
3982 case FIONBIO:
3983 case FIOASYNC:
3984 error = file_has_perm(cred, file, 0);
3985 break;
3986
3987 case KDSKBENT:
3988 case KDSKBSENT:
3989 error = cred_has_capability(cred, CAP_SYS_TTY_CONFIG,
3990 CAP_OPT_NONE, true);
3991 break;
3992
3993 case FIOCLEX:
3994 case FIONCLEX:
3995 if (!selinux_policycap_ioctl_skip_cloexec())
3996 error = ioctl_has_perm(cred, file, FILE__IOCTL, (u16) cmd);
3997 break;
3998
3999 /* default case assumes that the command will go
4000 * to the file's ioctl() function.
4001 */
4002 default:
4003 error = ioctl_has_perm(cred, file, FILE__IOCTL, (u16) cmd);
4004 }
4005 return error;
4006 }
4007
selinux_file_ioctl_compat(struct file * file,unsigned int cmd,unsigned long arg)4008 static int selinux_file_ioctl_compat(struct file *file, unsigned int cmd,
4009 unsigned long arg)
4010 {
4011 /*
4012 * If we are in a 64-bit kernel running 32-bit userspace, we need to
4013 * make sure we don't compare 32-bit flags to 64-bit flags.
4014 */
4015 switch (cmd) {
4016 case FS_IOC32_GETFLAGS:
4017 cmd = FS_IOC_GETFLAGS;
4018 break;
4019 case FS_IOC32_SETFLAGS:
4020 cmd = FS_IOC_SETFLAGS;
4021 break;
4022 case FS_IOC32_GETVERSION:
4023 cmd = FS_IOC_GETVERSION;
4024 break;
4025 case FS_IOC32_SETVERSION:
4026 cmd = FS_IOC_SETVERSION;
4027 break;
4028 default:
4029 break;
4030 }
4031
4032 return selinux_file_ioctl(file, cmd, arg);
4033 }
4034
4035 static int default_noexec __ro_after_init;
4036
file_map_prot_to_av(unsigned long prot,bool shared)4037 static u32 file_map_prot_to_av(unsigned long prot, bool shared)
4038 {
4039 u32 av = FILE__READ;
4040
4041 if (shared && (prot & PROT_WRITE))
4042 av |= FILE__WRITE;
4043 if (prot & PROT_EXEC)
4044 av |= FILE__EXECUTE;
4045
4046 return av;
4047 }
4048
backing_mounters_has_perm(const struct file * file,u32 av)4049 static int backing_mounters_has_perm(const struct file *file, u32 av)
4050 {
4051 const struct backing_file_security_struct *bfsec;
4052 const struct backing_file_security_layer *layer;
4053 struct common_audit_data ad;
4054 struct inode *inode;
4055 u32 i;
4056 int rc;
4057
4058 if (WARN_ON_ONCE(!(file->f_mode & FMODE_BACKING)))
4059 return -EIO;
4060
4061 bfsec = selinux_backing_file(file);
4062 for (i = 0; i < bfsec->layer_count; i++) {
4063 layer = &bfsec->layers[i];
4064 inode = d_inode(layer->path.dentry);
4065
4066 ad.type = LSM_AUDIT_DATA_PATH;
4067 ad.u.path = layer->path;
4068
4069 if (layer->mounter_sid != layer->fd_sid) {
4070 rc = avc_has_perm(layer->mounter_sid, layer->fd_sid,
4071 SECCLASS_FD, FD__USE, &ad);
4072 if (rc)
4073 return rc;
4074 }
4075
4076 rc = inode_sid_has_perm(layer->mounter_sid, inode, av, &ad);
4077 if (rc)
4078 return rc;
4079 }
4080
4081 return 0;
4082 }
4083
__file_map_prot_check(const struct file * file,unsigned long prot,bool shared,bool mounter_check,bool bf_user_file)4084 static int __file_map_prot_check(const struct file *file, unsigned long prot,
4085 bool shared, bool mounter_check,
4086 bool bf_user_file)
4087 {
4088 struct inode *inode = NULL;
4089 bool prot_exec = prot & PROT_EXEC;
4090 bool prot_write = prot & PROT_WRITE;
4091
4092 if (file) {
4093 if (bf_user_file)
4094 inode = d_inode(backing_file_user_path(file)->dentry);
4095 else
4096 inode = file_inode(file);
4097 }
4098
4099 if (!mounter_check && default_noexec && prot_exec &&
4100 (!file || IS_PRIVATE(inode) || (!shared && prot_write))) {
4101 int rc;
4102 u32 sid = current_sid();
4103
4104 /*
4105 * We are making executable an anonymous mapping or a private
4106 * file mapping that will also be writable.
4107 */
4108 rc = avc_has_perm(sid, sid, SECCLASS_PROCESS, PROCESS__EXECMEM,
4109 NULL);
4110 if (rc)
4111 return rc;
4112 }
4113
4114 if (file) {
4115 const struct cred *cred = mounter_check ?
4116 file->f_cred : current_cred();
4117
4118 return __file_has_perm(cred, file,
4119 file_map_prot_to_av(prot, shared),
4120 bf_user_file);
4121 }
4122
4123 return 0;
4124 }
4125
file_map_prot_check(const struct file * file,unsigned long prot,bool shared,bool mounter_check)4126 static inline int file_map_prot_check(const struct file *file,
4127 unsigned long prot, bool shared,
4128 bool mounter_check)
4129 {
4130 return __file_map_prot_check(file, prot, shared, mounter_check, false);
4131 }
4132
selinux_mmap_addr(unsigned long addr)4133 static int selinux_mmap_addr(unsigned long addr)
4134 {
4135 int rc = 0;
4136
4137 if (addr < CONFIG_LSM_MMAP_MIN_ADDR) {
4138 u32 sid = current_sid();
4139 rc = avc_has_perm(sid, sid, SECCLASS_MEMPROTECT,
4140 MEMPROTECT__MMAP_ZERO, NULL);
4141 }
4142
4143 return rc;
4144 }
4145
selinux_mmap_file_common(struct file * file,unsigned long prot,bool shared,bool mounter_check)4146 static int selinux_mmap_file_common(struct file *file, unsigned long prot,
4147 bool shared, bool mounter_check)
4148 {
4149 if (file) {
4150 int rc;
4151 struct common_audit_data ad;
4152 const struct cred *cred = mounter_check ?
4153 file->f_cred : current_cred();
4154
4155 ad.type = LSM_AUDIT_DATA_FILE;
4156 ad.u.file = file;
4157 rc = inode_has_perm(cred, file_inode(file), FILE__MAP, &ad);
4158 if (rc)
4159 return rc;
4160 }
4161
4162 return file_map_prot_check(file, prot, shared, mounter_check);
4163 }
4164
selinux_mmap_file(struct file * file,unsigned long reqprot __always_unused,unsigned long prot,unsigned long flags)4165 static int selinux_mmap_file(struct file *file,
4166 unsigned long reqprot __always_unused,
4167 unsigned long prot, unsigned long flags)
4168 {
4169 return selinux_mmap_file_common(file, prot,
4170 (flags & MAP_TYPE) == MAP_SHARED,
4171 false);
4172 }
4173
4174 /**
4175 * selinux_mmap_backing_file - Check mmap permissions on a backing file
4176 * @vma: memory region
4177 * @backing_file: stacked filesystem backing file
4178 * @user_file: user visible file
4179 *
4180 * This is called after selinux_mmap_file() on stacked filesystems, and it
4181 * is this function's responsibility to verify access to @backing_file and
4182 * setup the SELinux state for possible later use in the mprotect() code path.
4183 *
4184 * By the time this function is called, mmap() access to @user_file has already
4185 * been authorized and @vma->vm_file has been set to point to @backing_file.
4186 *
4187 * Return zero on success, negative values otherwise.
4188 */
selinux_mmap_backing_file(struct vm_area_struct * vma,struct file * backing_file,struct file * user_file __always_unused)4189 static int selinux_mmap_backing_file(struct vm_area_struct *vma,
4190 struct file *backing_file,
4191 struct file *user_file __always_unused)
4192 {
4193 unsigned long prot = 0;
4194
4195 /* translate vma->vm_flags perms into PROT perms */
4196 if (vma->vm_flags & VM_READ)
4197 prot |= PROT_READ;
4198 if (vma->vm_flags & VM_WRITE)
4199 prot |= PROT_WRITE;
4200 if (vma->vm_flags & VM_EXEC)
4201 prot |= PROT_EXEC;
4202
4203 return selinux_mmap_file_common(backing_file, prot,
4204 vma->vm_flags & VM_SHARED,
4205 true);
4206 }
4207
selinux_file_mprotect(struct vm_area_struct * vma,unsigned long reqprot __always_unused,unsigned long prot)4208 static int selinux_file_mprotect(struct vm_area_struct *vma,
4209 unsigned long reqprot __always_unused,
4210 unsigned long prot)
4211 {
4212 int rc;
4213 const struct cred *cred = current_cred();
4214 u32 sid = cred_sid(cred);
4215 u32 av;
4216 const struct file *file = vma->vm_file;
4217 bool backing_file;
4218 bool shared = vma->vm_flags & VM_SHARED;
4219
4220 /* check if we need to trigger the "backing files are awful" mode */
4221 backing_file = file && (file->f_mode & FMODE_BACKING);
4222
4223 if (default_noexec &&
4224 (prot & PROT_EXEC) && !(vma->vm_flags & VM_EXEC)) {
4225 /*
4226 * We don't use the vma_is_initial_heap() helper as it has
4227 * a history of problems and is currently broken on systems
4228 * where there is no heap, e.g. brk == start_brk. Before
4229 * replacing the conditional below with vma_is_initial_heap(),
4230 * or something similar, please ensure that the logic is the
4231 * same as what we have below or you have tested every possible
4232 * corner case you can think to test.
4233 */
4234 if (vma->vm_start >= vma->vm_mm->start_brk &&
4235 vma->vm_end <= vma->vm_mm->brk) {
4236 rc = avc_has_perm(sid, sid, SECCLASS_PROCESS,
4237 PROCESS__EXECHEAP, NULL);
4238 if (rc)
4239 return rc;
4240 } else if (!file && (vma_is_initial_stack(vma) ||
4241 vma_is_stack_for_current(vma))) {
4242 rc = avc_has_perm(sid, sid, SECCLASS_PROCESS,
4243 PROCESS__EXECSTACK, NULL);
4244 if (rc)
4245 return rc;
4246 } else if (file && vma->anon_vma) {
4247 /*
4248 * We are making executable a file mapping that has
4249 * had some COW done. Since pages might have been
4250 * written, check ability to execute the possibly
4251 * modified content. This typically should only
4252 * occur for text relocations.
4253 */
4254 rc = __file_has_perm(cred, file, FILE__EXECMOD,
4255 backing_file);
4256 if (rc)
4257 return rc;
4258 if (backing_file) {
4259 rc = backing_mounters_has_perm(file,
4260 FILE__EXECMOD);
4261 if (rc)
4262 return rc;
4263 rc = file_has_perm(file->f_cred, file,
4264 FILE__EXECMOD);
4265 if (rc)
4266 return rc;
4267 }
4268 }
4269 }
4270
4271 rc = __file_map_prot_check(file, prot, shared, false, backing_file);
4272 if (rc)
4273 return rc;
4274 if (backing_file) {
4275 av = file_map_prot_to_av(prot, shared);
4276 rc = backing_mounters_has_perm(file, av);
4277 if (rc)
4278 return rc;
4279 rc = file_map_prot_check(file, prot, shared, true);
4280 if (rc)
4281 return rc;
4282 }
4283
4284 return 0;
4285 }
4286
selinux_file_lock(struct file * file,unsigned int cmd)4287 static int selinux_file_lock(struct file *file, unsigned int cmd)
4288 {
4289 const struct cred *cred = current_cred();
4290
4291 return file_has_perm(cred, file, FILE__LOCK);
4292 }
4293
selinux_file_fcntl(struct file * file,unsigned int cmd,unsigned long arg)4294 static int selinux_file_fcntl(struct file *file, unsigned int cmd,
4295 unsigned long arg)
4296 {
4297 const struct cred *cred = current_cred();
4298 int err = 0;
4299
4300 switch (cmd) {
4301 case F_SETFL:
4302 if ((file->f_flags & O_APPEND) && !(arg & O_APPEND)) {
4303 err = file_has_perm(cred, file, FILE__WRITE);
4304 break;
4305 }
4306 fallthrough;
4307 case F_SETOWN:
4308 case F_SETSIG:
4309 case F_GETFL:
4310 case F_GETOWN:
4311 case F_GETSIG:
4312 case F_GETOWNER_UIDS:
4313 /* Just check FD__USE permission */
4314 err = file_has_perm(cred, file, 0);
4315 break;
4316 case F_GETLK:
4317 case F_SETLK:
4318 case F_SETLKW:
4319 case F_OFD_GETLK:
4320 case F_OFD_SETLK:
4321 case F_OFD_SETLKW:
4322 #if BITS_PER_LONG == 32
4323 case F_GETLK64:
4324 case F_SETLK64:
4325 case F_SETLKW64:
4326 #endif
4327 err = file_has_perm(cred, file, FILE__LOCK);
4328 break;
4329 }
4330
4331 return err;
4332 }
4333
selinux_file_set_fowner(struct file * file)4334 static void selinux_file_set_fowner(struct file *file)
4335 {
4336 struct file_security_struct *fsec;
4337
4338 fsec = selinux_file(file);
4339 fsec->fown_sid = current_sid();
4340 }
4341
selinux_file_send_sigiotask(struct task_struct * tsk,struct fown_struct * fown,int signum)4342 static int selinux_file_send_sigiotask(struct task_struct *tsk,
4343 struct fown_struct *fown, int signum)
4344 {
4345 struct file *file;
4346 u32 sid = task_sid_obj(tsk);
4347 u32 perm;
4348 struct file_security_struct *fsec;
4349
4350 /* struct fown_struct is never outside the context of a struct file */
4351 file = fown->file;
4352
4353 fsec = selinux_file(file);
4354
4355 if (!signum)
4356 perm = signal_to_av(SIGIO); /* as per send_sigio_to_task */
4357 else
4358 perm = signal_to_av(signum);
4359
4360 return avc_has_perm(fsec->fown_sid, sid,
4361 SECCLASS_PROCESS, perm, NULL);
4362 }
4363
selinux_file_receive(struct file * file)4364 static int selinux_file_receive(struct file *file)
4365 {
4366 const struct cred *cred = current_cred();
4367
4368 return file_has_perm(cred, file, file_to_av(file));
4369 }
4370
selinux_file_open(struct file * file)4371 static int selinux_file_open(struct file *file)
4372 {
4373 struct file_security_struct *fsec;
4374 struct inode_security_struct *isec;
4375
4376 fsec = selinux_file(file);
4377 isec = inode_security(file_inode(file));
4378 /*
4379 * Save inode label and policy sequence number
4380 * at open-time so that selinux_file_permission
4381 * can determine whether revalidation is necessary.
4382 * Task label is already saved in the file security
4383 * struct as its SID.
4384 */
4385 fsec->isid = isec->sid;
4386 fsec->pseqno = avc_policy_seqno();
4387 /*
4388 * Since the inode label or policy seqno may have changed
4389 * between the selinux_inode_permission check and the saving
4390 * of state above, recheck that access is still permitted.
4391 * Otherwise, access might never be revalidated against the
4392 * new inode label or new policy.
4393 * This check is not redundant - do not remove.
4394 */
4395 return file_path_has_perm(file->f_cred, file, open_file_to_av(file));
4396 }
4397
4398 /* task security operations */
4399
selinux_task_alloc(struct task_struct * task,u64 clone_flags)4400 static int selinux_task_alloc(struct task_struct *task,
4401 u64 clone_flags)
4402 {
4403 u32 sid = current_sid();
4404 struct task_security_struct *old_tsec = selinux_task(current);
4405 struct task_security_struct *new_tsec = selinux_task(task);
4406
4407 *new_tsec = *old_tsec;
4408 return avc_has_perm(sid, sid, SECCLASS_PROCESS, PROCESS__FORK, NULL);
4409 }
4410
4411 /*
4412 * prepare a new set of credentials for modification
4413 */
selinux_cred_prepare(struct cred * new,const struct cred * old,gfp_t gfp)4414 static int selinux_cred_prepare(struct cred *new, const struct cred *old,
4415 gfp_t gfp)
4416 {
4417 const struct cred_security_struct *old_crsec = selinux_cred(old);
4418 struct cred_security_struct *crsec = selinux_cred(new);
4419
4420 *crsec = *old_crsec;
4421 return 0;
4422 }
4423
4424 /*
4425 * transfer the SELinux data to a blank set of creds
4426 */
selinux_cred_transfer(struct cred * new,const struct cred * old)4427 static void selinux_cred_transfer(struct cred *new, const struct cred *old)
4428 {
4429 const struct cred_security_struct *old_crsec = selinux_cred(old);
4430 struct cred_security_struct *crsec = selinux_cred(new);
4431
4432 *crsec = *old_crsec;
4433 }
4434
selinux_cred_getsecid(const struct cred * c,u32 * secid)4435 static void selinux_cred_getsecid(const struct cred *c, u32 *secid)
4436 {
4437 *secid = cred_sid(c);
4438 }
4439
selinux_cred_getlsmprop(const struct cred * c,struct lsm_prop * prop)4440 static void selinux_cred_getlsmprop(const struct cred *c, struct lsm_prop *prop)
4441 {
4442 prop->selinux.secid = cred_sid(c);
4443 }
4444
4445 /*
4446 * set the security data for a kernel service
4447 * - all the creation contexts are set to unlabelled
4448 */
selinux_kernel_act_as(struct cred * new,u32 secid)4449 static int selinux_kernel_act_as(struct cred *new, u32 secid)
4450 {
4451 struct cred_security_struct *crsec = selinux_cred(new);
4452 u32 sid = current_sid();
4453 int ret;
4454
4455 ret = avc_has_perm(sid, secid,
4456 SECCLASS_KERNEL_SERVICE,
4457 KERNEL_SERVICE__USE_AS_OVERRIDE,
4458 NULL);
4459 if (ret == 0) {
4460 crsec->sid = secid;
4461 crsec->create_sid = 0;
4462 crsec->keycreate_sid = 0;
4463 crsec->sockcreate_sid = 0;
4464 }
4465 return ret;
4466 }
4467
4468 /*
4469 * set the file creation context in a security record to the same as the
4470 * objective context of the specified inode
4471 */
selinux_kernel_create_files_as(struct cred * new,struct inode * inode)4472 static int selinux_kernel_create_files_as(struct cred *new, struct inode *inode)
4473 {
4474 struct inode_security_struct *isec = inode_security(inode);
4475 struct cred_security_struct *crsec = selinux_cred(new);
4476 u32 sid = current_sid();
4477 int ret;
4478
4479 ret = avc_has_perm(sid, isec->sid,
4480 SECCLASS_KERNEL_SERVICE,
4481 KERNEL_SERVICE__CREATE_FILES_AS,
4482 NULL);
4483
4484 if (ret == 0)
4485 crsec->create_sid = isec->sid;
4486 return ret;
4487 }
4488
selinux_kernel_module_request(char * kmod_name)4489 static int selinux_kernel_module_request(char *kmod_name)
4490 {
4491 struct common_audit_data ad;
4492
4493 ad.type = LSM_AUDIT_DATA_KMOD;
4494 ad.u.kmod_name = kmod_name;
4495
4496 return avc_has_perm(current_sid(), SECINITSID_KERNEL, SECCLASS_SYSTEM,
4497 SYSTEM__MODULE_REQUEST, &ad);
4498 }
4499
selinux_kernel_load_from_file(struct file * file,u32 requested)4500 static int selinux_kernel_load_from_file(struct file *file, u32 requested)
4501 {
4502 struct common_audit_data ad;
4503 struct inode_security_struct *isec;
4504 struct file_security_struct *fsec;
4505 u32 sid = current_sid();
4506 int rc;
4507
4508 if (file == NULL)
4509 return avc_has_perm(sid, sid, SECCLASS_SYSTEM, requested, NULL);
4510
4511 ad.type = LSM_AUDIT_DATA_FILE;
4512 ad.u.file = file;
4513
4514 fsec = selinux_file(file);
4515 if (sid != fsec->sid) {
4516 rc = avc_has_perm(sid, fsec->sid, SECCLASS_FD, FD__USE, &ad);
4517 if (rc)
4518 return rc;
4519 }
4520
4521 isec = inode_security(file_inode(file));
4522 return avc_has_perm(sid, isec->sid, SECCLASS_SYSTEM, requested, &ad);
4523 }
4524
selinux_kernel_read_file(struct file * file,enum kernel_read_file_id id,bool contents)4525 static int selinux_kernel_read_file(struct file *file,
4526 enum kernel_read_file_id id,
4527 bool contents)
4528 {
4529 int rc = 0;
4530
4531 BUILD_BUG_ON_MSG(READING_MAX_ID > 8,
4532 "New kernel_read_file_id introduced; update SELinux!");
4533
4534 switch (id) {
4535 case READING_FIRMWARE:
4536 rc = selinux_kernel_load_from_file(file, SYSTEM__FIRMWARE_LOAD);
4537 break;
4538 case READING_MODULE:
4539 case READING_MODULE_COMPRESSED:
4540 rc = selinux_kernel_load_from_file(file, SYSTEM__MODULE_LOAD);
4541 break;
4542 case READING_KEXEC_IMAGE:
4543 rc = selinux_kernel_load_from_file(file,
4544 SYSTEM__KEXEC_IMAGE_LOAD);
4545 break;
4546 case READING_KEXEC_INITRAMFS:
4547 rc = selinux_kernel_load_from_file(file,
4548 SYSTEM__KEXEC_INITRAMFS_LOAD);
4549 break;
4550 case READING_POLICY:
4551 rc = selinux_kernel_load_from_file(file, SYSTEM__POLICY_LOAD);
4552 break;
4553 case READING_X509_CERTIFICATE:
4554 rc = selinux_kernel_load_from_file(file,
4555 SYSTEM__X509_CERTIFICATE_LOAD);
4556 break;
4557 default:
4558 break;
4559 }
4560
4561 return rc;
4562 }
4563
selinux_kernel_load_data(enum kernel_load_data_id id,bool contents)4564 static int selinux_kernel_load_data(enum kernel_load_data_id id, bool contents)
4565 {
4566 int rc = 0;
4567
4568 BUILD_BUG_ON_MSG(LOADING_MAX_ID > 8,
4569 "New kernel_load_data_id introduced; update SELinux!");
4570
4571 switch (id) {
4572 case LOADING_FIRMWARE:
4573 rc = selinux_kernel_load_from_file(NULL, SYSTEM__FIRMWARE_LOAD);
4574 break;
4575 case LOADING_MODULE:
4576 rc = selinux_kernel_load_from_file(NULL, SYSTEM__MODULE_LOAD);
4577 break;
4578 case LOADING_KEXEC_IMAGE:
4579 rc = selinux_kernel_load_from_file(NULL,
4580 SYSTEM__KEXEC_IMAGE_LOAD);
4581 break;
4582 case LOADING_KEXEC_INITRAMFS:
4583 rc = selinux_kernel_load_from_file(NULL,
4584 SYSTEM__KEXEC_INITRAMFS_LOAD);
4585 break;
4586 case LOADING_POLICY:
4587 rc = selinux_kernel_load_from_file(NULL,
4588 SYSTEM__POLICY_LOAD);
4589 break;
4590 case LOADING_X509_CERTIFICATE:
4591 rc = selinux_kernel_load_from_file(NULL,
4592 SYSTEM__X509_CERTIFICATE_LOAD);
4593 break;
4594 default:
4595 break;
4596 }
4597
4598 return rc;
4599 }
4600
selinux_task_setpgid(struct task_struct * p,pid_t pgid)4601 static int selinux_task_setpgid(struct task_struct *p, pid_t pgid)
4602 {
4603 return avc_has_perm(current_sid(), task_sid_obj(p), SECCLASS_PROCESS,
4604 PROCESS__SETPGID, NULL);
4605 }
4606
selinux_task_getpgid(struct task_struct * p)4607 static int selinux_task_getpgid(struct task_struct *p)
4608 {
4609 return avc_has_perm(current_sid(), task_sid_obj(p), SECCLASS_PROCESS,
4610 PROCESS__GETPGID, NULL);
4611 }
4612
selinux_task_getsid(struct task_struct * p)4613 static int selinux_task_getsid(struct task_struct *p)
4614 {
4615 return avc_has_perm(current_sid(), task_sid_obj(p), SECCLASS_PROCESS,
4616 PROCESS__GETSESSION, NULL);
4617 }
4618
selinux_current_getlsmprop_subj(struct lsm_prop * prop)4619 static void selinux_current_getlsmprop_subj(struct lsm_prop *prop)
4620 {
4621 prop->selinux.secid = current_sid();
4622 }
4623
selinux_task_getlsmprop_obj(struct task_struct * p,struct lsm_prop * prop)4624 static void selinux_task_getlsmprop_obj(struct task_struct *p,
4625 struct lsm_prop *prop)
4626 {
4627 prop->selinux.secid = task_sid_obj(p);
4628 }
4629
selinux_task_setnice(struct task_struct * p,int nice)4630 static int selinux_task_setnice(struct task_struct *p, int nice)
4631 {
4632 return avc_has_perm(current_sid(), task_sid_obj(p), SECCLASS_PROCESS,
4633 PROCESS__SETSCHED, NULL);
4634 }
4635
selinux_task_setioprio(struct task_struct * p,int ioprio)4636 static int selinux_task_setioprio(struct task_struct *p, int ioprio)
4637 {
4638 return avc_has_perm(current_sid(), task_sid_obj(p), SECCLASS_PROCESS,
4639 PROCESS__SETSCHED, NULL);
4640 }
4641
selinux_task_getioprio(struct task_struct * p)4642 static int selinux_task_getioprio(struct task_struct *p)
4643 {
4644 return avc_has_perm(current_sid(), task_sid_obj(p), SECCLASS_PROCESS,
4645 PROCESS__GETSCHED, NULL);
4646 }
4647
selinux_task_prlimit(const struct cred * cred,const struct cred * tcred,unsigned int flags)4648 static int selinux_task_prlimit(const struct cred *cred, const struct cred *tcred,
4649 unsigned int flags)
4650 {
4651 u32 av = 0;
4652
4653 if (!flags)
4654 return 0;
4655 if (flags & LSM_PRLIMIT_WRITE)
4656 av |= PROCESS__SETRLIMIT;
4657 if (flags & LSM_PRLIMIT_READ)
4658 av |= PROCESS__GETRLIMIT;
4659 return avc_has_perm(cred_sid(cred), cred_sid(tcred),
4660 SECCLASS_PROCESS, av, NULL);
4661 }
4662
selinux_task_setrlimit(struct task_struct * p,unsigned int resource,struct rlimit * new_rlim)4663 static int selinux_task_setrlimit(struct task_struct *p, unsigned int resource,
4664 struct rlimit *new_rlim)
4665 {
4666 struct rlimit *old_rlim = p->signal->rlim + resource;
4667
4668 /* Control the ability to change the hard limit (whether
4669 lowering or raising it), so that the hard limit can
4670 later be used as a safe reset point for the soft limit
4671 upon context transitions. See selinux_bprm_committing_creds. */
4672 if (old_rlim->rlim_max != new_rlim->rlim_max)
4673 return avc_has_perm(current_sid(), task_sid_obj(p),
4674 SECCLASS_PROCESS, PROCESS__SETRLIMIT, NULL);
4675
4676 return 0;
4677 }
4678
selinux_task_setscheduler(struct task_struct * p)4679 static int selinux_task_setscheduler(struct task_struct *p)
4680 {
4681 return avc_has_perm(current_sid(), task_sid_obj(p), SECCLASS_PROCESS,
4682 PROCESS__SETSCHED, NULL);
4683 }
4684
selinux_task_getscheduler(struct task_struct * p)4685 static int selinux_task_getscheduler(struct task_struct *p)
4686 {
4687 return avc_has_perm(current_sid(), task_sid_obj(p), SECCLASS_PROCESS,
4688 PROCESS__GETSCHED, NULL);
4689 }
4690
selinux_task_movememory(struct task_struct * p)4691 static int selinux_task_movememory(struct task_struct *p)
4692 {
4693 return avc_has_perm(current_sid(), task_sid_obj(p), SECCLASS_PROCESS,
4694 PROCESS__SETSCHED, NULL);
4695 }
4696
selinux_task_kill(struct task_struct * p,struct kernel_siginfo * info,int sig,const struct cred * cred)4697 static int selinux_task_kill(struct task_struct *p, struct kernel_siginfo *info,
4698 int sig, const struct cred *cred)
4699 {
4700 u32 secid;
4701 u32 perm;
4702
4703 if (!sig)
4704 perm = PROCESS__SIGNULL; /* null signal; existence test */
4705 else
4706 perm = signal_to_av(sig);
4707 if (!cred)
4708 secid = current_sid();
4709 else
4710 secid = cred_sid(cred);
4711 return avc_has_perm(secid, task_sid_obj(p), SECCLASS_PROCESS, perm, NULL);
4712 }
4713
selinux_task_to_inode(struct task_struct * p,struct inode * inode)4714 static void selinux_task_to_inode(struct task_struct *p,
4715 struct inode *inode)
4716 {
4717 struct inode_security_struct *isec = selinux_inode(inode);
4718 u32 sid = task_sid_obj(p);
4719
4720 spin_lock(&isec->lock);
4721 isec->sclass = inode_mode_to_security_class(inode->i_mode);
4722 isec->sid = sid;
4723 isec->initialized = LABEL_INITIALIZED;
4724 spin_unlock(&isec->lock);
4725 }
4726
selinux_userns_create(const struct cred * cred)4727 static int selinux_userns_create(const struct cred *cred)
4728 {
4729 u32 sid = current_sid();
4730
4731 return avc_has_perm(sid, sid, SECCLASS_USER_NAMESPACE,
4732 USER_NAMESPACE__CREATE, NULL);
4733 }
4734
4735 /* Returns error only if unable to parse addresses */
selinux_parse_skb_ipv4(struct sk_buff * skb,struct common_audit_data * ad,u8 * proto)4736 static int selinux_parse_skb_ipv4(struct sk_buff *skb,
4737 struct common_audit_data *ad, u8 *proto)
4738 {
4739 int offset, ihlen, ret = -EINVAL;
4740 struct iphdr _iph, *ih;
4741
4742 offset = skb_network_offset(skb);
4743 ih = skb_header_pointer(skb, offset, sizeof(_iph), &_iph);
4744 if (ih == NULL)
4745 goto out;
4746
4747 ihlen = ih->ihl * 4;
4748 if (ihlen < sizeof(_iph))
4749 goto out;
4750
4751 ad->u.net->v4info.saddr = ih->saddr;
4752 ad->u.net->v4info.daddr = ih->daddr;
4753 ret = 0;
4754
4755 if (proto)
4756 *proto = ih->protocol;
4757
4758 switch (ih->protocol) {
4759 case IPPROTO_TCP: {
4760 struct tcphdr _tcph, *th;
4761
4762 if (ntohs(ih->frag_off) & IP_OFFSET)
4763 break;
4764
4765 offset += ihlen;
4766 th = skb_header_pointer(skb, offset, sizeof(_tcph), &_tcph);
4767 if (th == NULL)
4768 break;
4769
4770 ad->u.net->sport = th->source;
4771 ad->u.net->dport = th->dest;
4772 break;
4773 }
4774
4775 case IPPROTO_UDP: {
4776 struct udphdr _udph, *uh;
4777
4778 if (ntohs(ih->frag_off) & IP_OFFSET)
4779 break;
4780
4781 offset += ihlen;
4782 uh = skb_header_pointer(skb, offset, sizeof(_udph), &_udph);
4783 if (uh == NULL)
4784 break;
4785
4786 ad->u.net->sport = uh->source;
4787 ad->u.net->dport = uh->dest;
4788 break;
4789 }
4790
4791 #if IS_ENABLED(CONFIG_IP_SCTP)
4792 case IPPROTO_SCTP: {
4793 struct sctphdr _sctph, *sh;
4794
4795 if (ntohs(ih->frag_off) & IP_OFFSET)
4796 break;
4797
4798 offset += ihlen;
4799 sh = skb_header_pointer(skb, offset, sizeof(_sctph), &_sctph);
4800 if (sh == NULL)
4801 break;
4802
4803 ad->u.net->sport = sh->source;
4804 ad->u.net->dport = sh->dest;
4805 break;
4806 }
4807 #endif
4808 default:
4809 break;
4810 }
4811 out:
4812 return ret;
4813 }
4814
4815 #if IS_ENABLED(CONFIG_IPV6)
4816
4817 /* Returns error only if unable to parse addresses */
selinux_parse_skb_ipv6(struct sk_buff * skb,struct common_audit_data * ad,u8 * proto)4818 static int selinux_parse_skb_ipv6(struct sk_buff *skb,
4819 struct common_audit_data *ad, u8 *proto)
4820 {
4821 u8 nexthdr;
4822 int ret = -EINVAL, offset;
4823 struct ipv6hdr _ipv6h, *ip6;
4824 __be16 frag_off;
4825
4826 offset = skb_network_offset(skb);
4827 ip6 = skb_header_pointer(skb, offset, sizeof(_ipv6h), &_ipv6h);
4828 if (ip6 == NULL)
4829 goto out;
4830
4831 ad->u.net->v6info.saddr = ip6->saddr;
4832 ad->u.net->v6info.daddr = ip6->daddr;
4833 ret = 0;
4834
4835 nexthdr = ip6->nexthdr;
4836 offset += sizeof(_ipv6h);
4837 offset = ipv6_skip_exthdr(skb, offset, &nexthdr, &frag_off);
4838 if (offset < 0)
4839 goto out;
4840
4841 if (proto)
4842 *proto = nexthdr;
4843
4844 switch (nexthdr) {
4845 case IPPROTO_TCP: {
4846 struct tcphdr _tcph, *th;
4847
4848 th = skb_header_pointer(skb, offset, sizeof(_tcph), &_tcph);
4849 if (th == NULL)
4850 break;
4851
4852 ad->u.net->sport = th->source;
4853 ad->u.net->dport = th->dest;
4854 break;
4855 }
4856
4857 case IPPROTO_UDP: {
4858 struct udphdr _udph, *uh;
4859
4860 uh = skb_header_pointer(skb, offset, sizeof(_udph), &_udph);
4861 if (uh == NULL)
4862 break;
4863
4864 ad->u.net->sport = uh->source;
4865 ad->u.net->dport = uh->dest;
4866 break;
4867 }
4868
4869 #if IS_ENABLED(CONFIG_IP_SCTP)
4870 case IPPROTO_SCTP: {
4871 struct sctphdr _sctph, *sh;
4872
4873 sh = skb_header_pointer(skb, offset, sizeof(_sctph), &_sctph);
4874 if (sh == NULL)
4875 break;
4876
4877 ad->u.net->sport = sh->source;
4878 ad->u.net->dport = sh->dest;
4879 break;
4880 }
4881 #endif
4882 /* includes fragments */
4883 default:
4884 break;
4885 }
4886 out:
4887 return ret;
4888 }
4889
4890 #endif /* IPV6 */
4891
selinux_parse_skb(struct sk_buff * skb,struct common_audit_data * ad,char ** _addrp,int src,u8 * proto)4892 static int selinux_parse_skb(struct sk_buff *skb, struct common_audit_data *ad,
4893 char **_addrp, int src, u8 *proto)
4894 {
4895 char *addrp;
4896 int ret;
4897
4898 switch (ad->u.net->family) {
4899 case PF_INET:
4900 ret = selinux_parse_skb_ipv4(skb, ad, proto);
4901 if (ret)
4902 goto parse_error;
4903 addrp = (char *)(src ? &ad->u.net->v4info.saddr :
4904 &ad->u.net->v4info.daddr);
4905 goto okay;
4906
4907 #if IS_ENABLED(CONFIG_IPV6)
4908 case PF_INET6:
4909 ret = selinux_parse_skb_ipv6(skb, ad, proto);
4910 if (ret)
4911 goto parse_error;
4912 addrp = (char *)(src ? &ad->u.net->v6info.saddr :
4913 &ad->u.net->v6info.daddr);
4914 goto okay;
4915 #endif /* IPV6 */
4916 default:
4917 addrp = NULL;
4918 goto okay;
4919 }
4920
4921 parse_error:
4922 pr_warn(
4923 "SELinux: failure in selinux_parse_skb(),"
4924 " unable to parse packet\n");
4925 return ret;
4926
4927 okay:
4928 if (_addrp)
4929 *_addrp = addrp;
4930 return 0;
4931 }
4932
4933 /**
4934 * selinux_skb_peerlbl_sid - Determine the peer label of a packet
4935 * @skb: the packet
4936 * @family: protocol family
4937 * @sid: the packet's peer label SID
4938 *
4939 * Description:
4940 * Check the various different forms of network peer labeling and determine
4941 * the peer label/SID for the packet; most of the magic actually occurs in
4942 * the security server function security_net_peersid_cmp(). The function
4943 * returns zero if the value in @sid is valid (although it may be SECSID_NULL)
4944 * or -EACCES if @sid is invalid due to inconsistencies with the different
4945 * peer labels.
4946 *
4947 */
selinux_skb_peerlbl_sid(struct sk_buff * skb,u16 family,u32 * sid)4948 static int selinux_skb_peerlbl_sid(struct sk_buff *skb, u16 family, u32 *sid)
4949 {
4950 int err;
4951 u32 xfrm_sid;
4952 u32 nlbl_sid;
4953 u32 nlbl_type;
4954
4955 err = selinux_xfrm_skb_sid(skb, &xfrm_sid);
4956 if (unlikely(err))
4957 return -EACCES;
4958 err = selinux_netlbl_skbuff_getsid(skb, family, &nlbl_type, &nlbl_sid);
4959 if (unlikely(err))
4960 return -EACCES;
4961
4962 err = security_net_peersid_resolve(nlbl_sid,
4963 nlbl_type, xfrm_sid, sid);
4964 if (unlikely(err)) {
4965 pr_warn(
4966 "SELinux: failure in selinux_skb_peerlbl_sid(),"
4967 " unable to determine packet's peer label\n");
4968 return -EACCES;
4969 }
4970
4971 return 0;
4972 }
4973
4974 /**
4975 * selinux_conn_sid - Determine the child socket label for a connection
4976 * @sk_sid: the parent socket's SID
4977 * @skb_sid: the packet's SID
4978 * @conn_sid: the resulting connection SID
4979 *
4980 * If @skb_sid is valid then the user:role:type information from @sk_sid is
4981 * combined with the MLS information from @skb_sid in order to create
4982 * @conn_sid. If @skb_sid is not valid then @conn_sid is simply a copy
4983 * of @sk_sid. Returns zero on success, negative values on failure.
4984 *
4985 */
selinux_conn_sid(u32 sk_sid,u32 skb_sid,u32 * conn_sid)4986 static int selinux_conn_sid(u32 sk_sid, u32 skb_sid, u32 *conn_sid)
4987 {
4988 int err = 0;
4989
4990 if (skb_sid != SECSID_NULL)
4991 err = security_sid_mls_copy(sk_sid, skb_sid,
4992 conn_sid);
4993 else
4994 *conn_sid = sk_sid;
4995
4996 return err;
4997 }
4998
4999 /* socket security operations */
5000
socket_sockcreate_sid(const struct cred_security_struct * crsec,u16 secclass,u32 * socksid)5001 static int socket_sockcreate_sid(const struct cred_security_struct *crsec,
5002 u16 secclass, u32 *socksid)
5003 {
5004 if (crsec->sockcreate_sid > SECSID_NULL) {
5005 *socksid = crsec->sockcreate_sid;
5006 return 0;
5007 }
5008
5009 return security_transition_sid(crsec->sid, crsec->sid,
5010 secclass, NULL, socksid);
5011 }
5012
sock_skip_has_perm(u32 sid)5013 static bool sock_skip_has_perm(u32 sid)
5014 {
5015 if (sid == SECINITSID_KERNEL)
5016 return true;
5017
5018 /*
5019 * Before POLICYDB_CAP_USERSPACE_INITIAL_CONTEXT, sockets that
5020 * inherited the kernel context from early boot used to be skipped
5021 * here, so preserve that behavior unless the capability is set.
5022 *
5023 * By setting the capability the policy signals that it is ready
5024 * for this quirk to be fixed. Note that sockets created by a kernel
5025 * thread or a usermode helper executed without a transition will
5026 * still be skipped in this check regardless of the policycap
5027 * setting.
5028 */
5029 if (!selinux_policycap_userspace_initial_context() &&
5030 sid == SECINITSID_INIT)
5031 return true;
5032 return false;
5033 }
5034
5035
sock_has_perm(struct sock * sk,u32 perms)5036 static int sock_has_perm(struct sock *sk, u32 perms)
5037 {
5038 struct sk_security_struct *sksec = selinux_sock(sk);
5039 struct common_audit_data ad;
5040 struct lsm_network_audit net;
5041
5042 if (sock_skip_has_perm(sksec->sid))
5043 return 0;
5044
5045 ad_net_init_from_sk(&ad, &net, sk);
5046
5047 return avc_has_perm(current_sid(), sksec->sid, sksec->sclass, perms,
5048 &ad);
5049 }
5050
selinux_socket_create(int family,int type,int protocol,int kern)5051 static int selinux_socket_create(int family, int type,
5052 int protocol, int kern)
5053 {
5054 const struct cred_security_struct *crsec = selinux_cred(current_cred());
5055 u32 newsid;
5056 u16 secclass;
5057 int rc;
5058
5059 if (kern)
5060 return 0;
5061
5062 secclass = socket_type_to_security_class(family, type, protocol);
5063 rc = socket_sockcreate_sid(crsec, secclass, &newsid);
5064 if (rc)
5065 return rc;
5066
5067 return avc_has_perm(crsec->sid, newsid, secclass, SOCKET__CREATE, NULL);
5068 }
5069
selinux_socket_post_create(struct socket * sock,int family,int type,int protocol,int kern)5070 static int selinux_socket_post_create(struct socket *sock, int family,
5071 int type, int protocol, int kern)
5072 {
5073 const struct cred_security_struct *crsec = selinux_cred(current_cred());
5074 struct inode_security_struct *isec = inode_security_novalidate(SOCK_INODE(sock));
5075 struct sk_security_struct *sksec;
5076 u16 sclass = socket_type_to_security_class(family, type, protocol);
5077 u32 sid = SECINITSID_KERNEL;
5078 int err = 0;
5079
5080 if (!kern) {
5081 err = socket_sockcreate_sid(crsec, sclass, &sid);
5082 if (err)
5083 return err;
5084 }
5085
5086 isec->sclass = sclass;
5087 isec->sid = sid;
5088 isec->initialized = LABEL_INITIALIZED;
5089
5090 if (sock->sk) {
5091 sksec = selinux_sock(sock->sk);
5092 sksec->sclass = sclass;
5093 sksec->sid = sid;
5094 /* Allows detection of the first association on this socket */
5095 if (sksec->sclass == SECCLASS_SCTP_SOCKET)
5096 sksec->sctp_assoc_state = SCTP_ASSOC_UNSET;
5097
5098 err = selinux_netlbl_socket_post_create(sock->sk, family);
5099 }
5100
5101 return err;
5102 }
5103
selinux_socket_socketpair(struct socket * socka,struct socket * sockb)5104 static int selinux_socket_socketpair(struct socket *socka,
5105 struct socket *sockb)
5106 {
5107 struct sk_security_struct *sksec_a = selinux_sock(socka->sk);
5108 struct sk_security_struct *sksec_b = selinux_sock(sockb->sk);
5109
5110 sksec_a->peer_sid = sksec_b->sid;
5111 sksec_b->peer_sid = sksec_a->sid;
5112
5113 return 0;
5114 }
5115
5116 /* Range of port numbers used to automatically bind.
5117 Need to determine whether we should perform a name_bind
5118 permission check between the socket and the port number. */
5119
__selinux_socket_bind(struct sock * sk,struct sockaddr * address,int addrlen)5120 static int __selinux_socket_bind(struct sock *sk, struct sockaddr *address, int addrlen)
5121 {
5122 struct sk_security_struct *sksec = selinux_sock(sk);
5123 u16 family;
5124 int err;
5125
5126 err = sock_has_perm(sk, SOCKET__BIND);
5127 if (err)
5128 goto out;
5129
5130 /* If PF_INET or PF_INET6, check name_bind permission for the port. */
5131 family = sk->sk_family;
5132 if (family == PF_INET || family == PF_INET6) {
5133 char *addrp;
5134 struct common_audit_data ad;
5135 struct lsm_network_audit net = {0,};
5136 struct sockaddr_in *addr4 = NULL;
5137 struct sockaddr_in6 *addr6 = NULL;
5138 u16 family_sa;
5139 unsigned short snum;
5140 u32 sid, node_perm;
5141
5142 /*
5143 * sctp_bindx(3) calls via selinux_sctp_bind_connect()
5144 * that validates multiple binding addresses. Because of this
5145 * need to check address->sa_family as it is possible to have
5146 * sk->sk_family = PF_INET6 with addr->sa_family = AF_INET.
5147 */
5148 if (addrlen < offsetofend(struct sockaddr, sa_family))
5149 return -EINVAL;
5150 family_sa = address->sa_family;
5151 switch (family_sa) {
5152 case AF_UNSPEC:
5153 case AF_INET:
5154 if (addrlen < sizeof(struct sockaddr_in))
5155 return -EINVAL;
5156 addr4 = (struct sockaddr_in *)address;
5157 if (family_sa == AF_UNSPEC) {
5158 if (family == PF_INET6) {
5159 /* Length check from inet6_bind_sk() */
5160 if (addrlen < SIN6_LEN_RFC2133)
5161 return -EINVAL;
5162 /* Family check from __inet6_bind() */
5163 goto err_af;
5164 }
5165 /* see __inet_bind(), we only want to allow
5166 * AF_UNSPEC if the address is INADDR_ANY
5167 */
5168 if (addr4->sin_addr.s_addr != htonl(INADDR_ANY))
5169 goto err_af;
5170 family_sa = AF_INET;
5171 }
5172 snum = ntohs(addr4->sin_port);
5173 addrp = (char *)&addr4->sin_addr.s_addr;
5174 break;
5175 case AF_INET6:
5176 if (addrlen < SIN6_LEN_RFC2133)
5177 return -EINVAL;
5178 addr6 = (struct sockaddr_in6 *)address;
5179 snum = ntohs(addr6->sin6_port);
5180 addrp = (char *)&addr6->sin6_addr.s6_addr;
5181 break;
5182 default:
5183 goto err_af;
5184 }
5185
5186 ad.type = LSM_AUDIT_DATA_NET;
5187 ad.u.net = &net;
5188 ad.u.net->sport = htons(snum);
5189 ad.u.net->family = family_sa;
5190
5191 if (snum) {
5192 int low, high;
5193
5194 inet_get_local_port_range(sock_net(sk), &low, &high);
5195
5196 if (inet_port_requires_bind_service(sock_net(sk), snum) ||
5197 snum < low || snum > high) {
5198 err = sel_netport_sid(sk->sk_protocol,
5199 snum, &sid);
5200 if (err)
5201 goto out;
5202 err = avc_has_perm(sksec->sid, sid,
5203 sksec->sclass,
5204 SOCKET__NAME_BIND, &ad);
5205 if (err)
5206 goto out;
5207 }
5208 }
5209
5210 switch (sksec->sclass) {
5211 case SECCLASS_TCP_SOCKET:
5212 node_perm = TCP_SOCKET__NODE_BIND;
5213 break;
5214
5215 case SECCLASS_UDP_SOCKET:
5216 node_perm = UDP_SOCKET__NODE_BIND;
5217 break;
5218
5219 case SECCLASS_SCTP_SOCKET:
5220 node_perm = SCTP_SOCKET__NODE_BIND;
5221 break;
5222
5223 default:
5224 node_perm = RAWIP_SOCKET__NODE_BIND;
5225 break;
5226 }
5227
5228 err = sel_netnode_sid(addrp, family_sa, &sid);
5229 if (err)
5230 goto out;
5231
5232 if (family_sa == AF_INET)
5233 ad.u.net->v4info.saddr = addr4->sin_addr.s_addr;
5234 else
5235 ad.u.net->v6info.saddr = addr6->sin6_addr;
5236
5237 err = avc_has_perm(sksec->sid, sid,
5238 sksec->sclass, node_perm, &ad);
5239 if (err)
5240 goto out;
5241 }
5242 out:
5243 return err;
5244 err_af:
5245 /* Note that SCTP services expect -EINVAL, others -EAFNOSUPPORT. */
5246 if (sk->sk_protocol == IPPROTO_SCTP)
5247 return -EINVAL;
5248 return -EAFNOSUPPORT;
5249 }
5250
selinux_socket_bind(struct socket * sock,struct sockaddr * address,int addrlen)5251 static int selinux_socket_bind(struct socket *sock, struct sockaddr *address, int addrlen)
5252 {
5253 return __selinux_socket_bind(sock->sk, address, addrlen);
5254 }
5255
5256 /* This supports connect(2) and SCTP connect services such as sctp_connectx(3)
5257 * and sctp_sendmsg(3) as described in Documentation/security/SCTP.rst
5258 */
selinux_socket_connect_helper(struct sock * sk,struct sockaddr * address,int addrlen)5259 static int selinux_socket_connect_helper(struct sock *sk,
5260 struct sockaddr *address, int addrlen)
5261 {
5262 struct sk_security_struct *sksec = selinux_sock(sk);
5263 int err;
5264
5265 err = sock_has_perm(sk, SOCKET__CONNECT);
5266 if (err)
5267 return err;
5268 if (addrlen < offsetofend(struct sockaddr, sa_family))
5269 return -EINVAL;
5270
5271 /* connect(AF_UNSPEC) has special handling, as it is a documented
5272 * way to disconnect the socket
5273 */
5274 if (address->sa_family == AF_UNSPEC)
5275 return 0;
5276
5277 /*
5278 * If a TCP or SCTP socket, check name_connect permission
5279 * for the port.
5280 */
5281 if (sksec->sclass == SECCLASS_TCP_SOCKET ||
5282 sksec->sclass == SECCLASS_SCTP_SOCKET) {
5283 struct common_audit_data ad;
5284 struct lsm_network_audit net = {0,};
5285 struct sockaddr_in *addr4 = NULL;
5286 struct sockaddr_in6 *addr6 = NULL;
5287 unsigned short snum;
5288 u32 sid, perm;
5289
5290 /* sctp_connectx(3) calls via selinux_sctp_bind_connect()
5291 * that validates multiple connect addresses. Because of this
5292 * need to check address->sa_family as it is possible to have
5293 * sk->sk_family = PF_INET6 with addr->sa_family = AF_INET.
5294 */
5295 switch (address->sa_family) {
5296 case AF_INET:
5297 addr4 = (struct sockaddr_in *)address;
5298 if (addrlen < sizeof(struct sockaddr_in))
5299 return -EINVAL;
5300 snum = ntohs(addr4->sin_port);
5301 break;
5302 case AF_INET6:
5303 addr6 = (struct sockaddr_in6 *)address;
5304 if (addrlen < SIN6_LEN_RFC2133)
5305 return -EINVAL;
5306 snum = ntohs(addr6->sin6_port);
5307 break;
5308 default:
5309 /* Note that SCTP services expect -EINVAL, whereas
5310 * others expect -EAFNOSUPPORT.
5311 */
5312 if (sksec->sclass == SECCLASS_SCTP_SOCKET)
5313 return -EINVAL;
5314 else
5315 return -EAFNOSUPPORT;
5316 }
5317
5318 err = sel_netport_sid(sk->sk_protocol, snum, &sid);
5319 if (err)
5320 return err;
5321
5322 switch (sksec->sclass) {
5323 case SECCLASS_TCP_SOCKET:
5324 perm = TCP_SOCKET__NAME_CONNECT;
5325 break;
5326 case SECCLASS_SCTP_SOCKET:
5327 perm = SCTP_SOCKET__NAME_CONNECT;
5328 break;
5329 }
5330
5331 ad.type = LSM_AUDIT_DATA_NET;
5332 ad.u.net = &net;
5333 ad.u.net->dport = htons(snum);
5334 ad.u.net->family = address->sa_family;
5335 err = avc_has_perm(sksec->sid, sid, sksec->sclass, perm, &ad);
5336 if (err)
5337 return err;
5338 }
5339
5340 return 0;
5341 }
5342
5343 /* Supports connect(2), see comments in selinux_socket_connect_helper() */
selinux_socket_connect(struct socket * sock,struct sockaddr * address,int addrlen)5344 static int selinux_socket_connect(struct socket *sock,
5345 struct sockaddr *address, int addrlen)
5346 {
5347 int err;
5348 struct sock *sk = sock->sk;
5349
5350 err = selinux_socket_connect_helper(sk, address, addrlen);
5351 if (err)
5352 return err;
5353
5354 return selinux_netlbl_socket_connect(sk, address);
5355 }
5356
selinux_socket_listen(struct socket * sock,int backlog)5357 static int selinux_socket_listen(struct socket *sock, int backlog)
5358 {
5359 return sock_has_perm(sock->sk, SOCKET__LISTEN);
5360 }
5361
selinux_socket_accept(struct socket * sock,struct socket * newsock)5362 static int selinux_socket_accept(struct socket *sock, struct socket *newsock)
5363 {
5364 int err;
5365 struct inode_security_struct *isec;
5366 struct inode_security_struct *newisec;
5367 u16 sclass;
5368 u32 sid;
5369
5370 err = sock_has_perm(sock->sk, SOCKET__ACCEPT);
5371 if (err)
5372 return err;
5373
5374 isec = inode_security_novalidate(SOCK_INODE(sock));
5375 spin_lock(&isec->lock);
5376 sclass = isec->sclass;
5377 sid = isec->sid;
5378 spin_unlock(&isec->lock);
5379
5380 newisec = inode_security_novalidate(SOCK_INODE(newsock));
5381 newisec->sclass = sclass;
5382 newisec->sid = sid;
5383 newisec->initialized = LABEL_INITIALIZED;
5384
5385 return 0;
5386 }
5387
selinux_socket_sendmsg(struct socket * sock,struct msghdr * msg,int size)5388 static int selinux_socket_sendmsg(struct socket *sock, struct msghdr *msg,
5389 int size)
5390 {
5391 int rc;
5392 struct sockaddr *const addr = msg->msg_name;
5393 const int addrlen = msg->msg_namelen;
5394
5395 rc = sock_has_perm(sock->sk, SOCKET__WRITE);
5396 if (rc)
5397 return rc;
5398
5399 if (addr && (msg->msg_flags & MSG_FASTOPEN) &&
5400 (sk_is_tcp(sock->sk) ||
5401 (sk_is_inet(sock->sk) && sock->sk->sk_type == SOCK_STREAM &&
5402 sock->sk->sk_protocol == IPPROTO_MPTCP))) {
5403 rc = selinux_socket_connect(sock, addr, addrlen);
5404 if (rc)
5405 return rc;
5406 }
5407
5408 return 0;
5409 }
5410
selinux_socket_recvmsg(struct socket * sock,struct msghdr * msg,int size,int flags)5411 static int selinux_socket_recvmsg(struct socket *sock, struct msghdr *msg,
5412 int size, int flags)
5413 {
5414 return sock_has_perm(sock->sk, SOCKET__READ);
5415 }
5416
selinux_socket_getsockname(struct socket * sock)5417 static int selinux_socket_getsockname(struct socket *sock)
5418 {
5419 return sock_has_perm(sock->sk, SOCKET__GETATTR);
5420 }
5421
selinux_socket_getpeername(struct socket * sock)5422 static int selinux_socket_getpeername(struct socket *sock)
5423 {
5424 return sock_has_perm(sock->sk, SOCKET__GETATTR);
5425 }
5426
selinux_socket_setsockopt(struct socket * sock,int level,int optname)5427 static int selinux_socket_setsockopt(struct socket *sock, int level, int optname)
5428 {
5429 int err;
5430
5431 err = sock_has_perm(sock->sk, SOCKET__SETOPT);
5432 if (err)
5433 return err;
5434
5435 return selinux_netlbl_socket_setsockopt(sock, level, optname);
5436 }
5437
selinux_socket_getsockopt(struct socket * sock,int level,int optname)5438 static int selinux_socket_getsockopt(struct socket *sock, int level,
5439 int optname)
5440 {
5441 return sock_has_perm(sock->sk, SOCKET__GETOPT);
5442 }
5443
selinux_socket_shutdown(struct socket * sock,int how)5444 static int selinux_socket_shutdown(struct socket *sock, int how)
5445 {
5446 return sock_has_perm(sock->sk, SOCKET__SHUTDOWN);
5447 }
5448
selinux_socket_unix_stream_connect(struct sock * sock,struct sock * other,struct sock * newsk)5449 static int selinux_socket_unix_stream_connect(struct sock *sock,
5450 struct sock *other,
5451 struct sock *newsk)
5452 {
5453 struct sk_security_struct *sksec_sock = selinux_sock(sock);
5454 struct sk_security_struct *sksec_other = selinux_sock(other);
5455 struct sk_security_struct *sksec_new = selinux_sock(newsk);
5456 struct common_audit_data ad;
5457 struct lsm_network_audit net;
5458 int err;
5459
5460 ad_net_init_from_sk(&ad, &net, other);
5461
5462 err = avc_has_perm(sksec_sock->sid, sksec_other->sid,
5463 sksec_other->sclass,
5464 UNIX_STREAM_SOCKET__CONNECTTO, &ad);
5465 if (err)
5466 return err;
5467
5468 /* server child socket */
5469 sksec_new->peer_sid = sksec_sock->sid;
5470 err = security_sid_mls_copy(sksec_other->sid,
5471 sksec_sock->sid, &sksec_new->sid);
5472 if (err)
5473 return err;
5474
5475 /* connecting socket */
5476 sksec_sock->peer_sid = sksec_new->sid;
5477
5478 return 0;
5479 }
5480
selinux_socket_unix_may_send(struct socket * sock,struct socket * other)5481 static int selinux_socket_unix_may_send(struct socket *sock,
5482 struct socket *other)
5483 {
5484 struct sk_security_struct *ssec = selinux_sock(sock->sk);
5485 struct sk_security_struct *osec = selinux_sock(other->sk);
5486 struct common_audit_data ad;
5487 struct lsm_network_audit net;
5488
5489 ad_net_init_from_sk(&ad, &net, other->sk);
5490
5491 return avc_has_perm(ssec->sid, osec->sid, osec->sclass, SOCKET__SENDTO,
5492 &ad);
5493 }
5494
selinux_inet_sys_rcv_skb(struct net * ns,int ifindex,char * addrp,u16 family,u32 peer_sid,struct common_audit_data * ad)5495 static int selinux_inet_sys_rcv_skb(struct net *ns, int ifindex,
5496 char *addrp, u16 family, u32 peer_sid,
5497 struct common_audit_data *ad)
5498 {
5499 int err;
5500 u32 if_sid;
5501 u32 node_sid;
5502
5503 err = sel_netif_sid(ns, ifindex, &if_sid);
5504 if (err)
5505 return err;
5506 err = avc_has_perm(peer_sid, if_sid,
5507 SECCLASS_NETIF, NETIF__INGRESS, ad);
5508 if (err)
5509 return err;
5510
5511 err = sel_netnode_sid(addrp, family, &node_sid);
5512 if (err)
5513 return err;
5514 return avc_has_perm(peer_sid, node_sid,
5515 SECCLASS_NODE, NODE__RECVFROM, ad);
5516 }
5517
selinux_sock_rcv_skb_compat(struct sock * sk,struct sk_buff * skb,u16 family)5518 static int selinux_sock_rcv_skb_compat(struct sock *sk, struct sk_buff *skb,
5519 u16 family)
5520 {
5521 int err = 0;
5522 struct sk_security_struct *sksec = selinux_sock(sk);
5523 u32 sk_sid = sksec->sid;
5524 struct common_audit_data ad;
5525 struct lsm_network_audit net;
5526 char *addrp;
5527
5528 ad_net_init_from_iif(&ad, &net, skb->skb_iif, family);
5529 err = selinux_parse_skb(skb, &ad, &addrp, 1, NULL);
5530 if (err)
5531 return err;
5532
5533 if (selinux_secmark_enabled()) {
5534 err = avc_has_perm(sk_sid, skb->secmark, SECCLASS_PACKET,
5535 PACKET__RECV, &ad);
5536 if (err)
5537 return err;
5538 }
5539
5540 err = selinux_netlbl_sock_rcv_skb(sksec, skb, family, &ad);
5541 if (err)
5542 return err;
5543 err = selinux_xfrm_sock_rcv_skb(sksec->sid, skb, &ad);
5544
5545 return err;
5546 }
5547
selinux_socket_sock_rcv_skb(struct sock * sk,struct sk_buff * skb)5548 static int selinux_socket_sock_rcv_skb(struct sock *sk, struct sk_buff *skb)
5549 {
5550 int err, peerlbl_active, secmark_active;
5551 struct sk_security_struct *sksec = selinux_sock(sk);
5552 u16 family = sk->sk_family;
5553 u32 sk_sid = sksec->sid;
5554 struct common_audit_data ad;
5555 struct lsm_network_audit net;
5556 char *addrp;
5557
5558 if (family != PF_INET && family != PF_INET6)
5559 return 0;
5560
5561 /* Handle mapped IPv4 packets arriving via IPv6 sockets */
5562 if (family == PF_INET6 && skb->protocol == htons(ETH_P_IP))
5563 family = PF_INET;
5564
5565 /* If any sort of compatibility mode is enabled then handoff processing
5566 * to the selinux_sock_rcv_skb_compat() function to deal with the
5567 * special handling. We do this in an attempt to keep this function
5568 * as fast and as clean as possible. */
5569 if (!selinux_policycap_netpeer())
5570 return selinux_sock_rcv_skb_compat(sk, skb, family);
5571
5572 secmark_active = selinux_secmark_enabled();
5573 peerlbl_active = selinux_peerlbl_enabled();
5574 if (!secmark_active && !peerlbl_active)
5575 return 0;
5576
5577 ad_net_init_from_iif(&ad, &net, skb->skb_iif, family);
5578 err = selinux_parse_skb(skb, &ad, &addrp, 1, NULL);
5579 if (err)
5580 return err;
5581
5582 if (peerlbl_active) {
5583 u32 peer_sid;
5584
5585 err = selinux_skb_peerlbl_sid(skb, family, &peer_sid);
5586 if (err)
5587 return err;
5588 err = selinux_inet_sys_rcv_skb(sock_net(sk), skb->skb_iif,
5589 addrp, family, peer_sid, &ad);
5590 if (err) {
5591 selinux_netlbl_err(skb, family, err, 0);
5592 return err;
5593 }
5594 err = avc_has_perm(sk_sid, peer_sid, SECCLASS_PEER,
5595 PEER__RECV, &ad);
5596 if (err) {
5597 selinux_netlbl_err(skb, family, err, 0);
5598 return err;
5599 }
5600 }
5601
5602 if (secmark_active) {
5603 err = avc_has_perm(sk_sid, skb->secmark, SECCLASS_PACKET,
5604 PACKET__RECV, &ad);
5605 if (err)
5606 return err;
5607 }
5608
5609 return err;
5610 }
5611
selinux_socket_getpeersec_stream(struct socket * sock,sockptr_t optval,sockptr_t optlen,unsigned int len)5612 static int selinux_socket_getpeersec_stream(struct socket *sock,
5613 sockptr_t optval, sockptr_t optlen,
5614 unsigned int len)
5615 {
5616 int err = 0;
5617 char *scontext = NULL;
5618 u32 scontext_len;
5619 struct sk_security_struct *sksec = selinux_sock(sock->sk);
5620 u32 peer_sid = SECSID_NULL;
5621
5622 if (sksec->sclass == SECCLASS_UNIX_STREAM_SOCKET ||
5623 sksec->sclass == SECCLASS_TCP_SOCKET ||
5624 sksec->sclass == SECCLASS_SCTP_SOCKET)
5625 peer_sid = sksec->peer_sid;
5626 if (peer_sid == SECSID_NULL)
5627 return -ENOPROTOOPT;
5628
5629 err = security_sid_to_context(peer_sid, &scontext,
5630 &scontext_len);
5631 if (err)
5632 return err;
5633 if (scontext_len > len) {
5634 err = -ERANGE;
5635 goto out_len;
5636 }
5637
5638 if (copy_to_sockptr(optval, scontext, scontext_len))
5639 err = -EFAULT;
5640 out_len:
5641 if (copy_to_sockptr(optlen, &scontext_len, sizeof(scontext_len)))
5642 err = -EFAULT;
5643 kfree(scontext);
5644 return err;
5645 }
5646
selinux_socket_getpeersec_dgram(struct socket * sock,struct sk_buff * skb,u32 * secid)5647 static int selinux_socket_getpeersec_dgram(struct socket *sock,
5648 struct sk_buff *skb, u32 *secid)
5649 {
5650 u32 peer_secid = SECSID_NULL;
5651 u16 family;
5652
5653 if (skb && skb->protocol == htons(ETH_P_IP))
5654 family = PF_INET;
5655 else if (skb && skb->protocol == htons(ETH_P_IPV6))
5656 family = PF_INET6;
5657 else if (sock)
5658 family = sock->sk->sk_family;
5659 else {
5660 *secid = SECSID_NULL;
5661 return -EINVAL;
5662 }
5663
5664 if (sock && family == PF_UNIX) {
5665 struct inode_security_struct *isec;
5666 isec = inode_security_novalidate(SOCK_INODE(sock));
5667 peer_secid = isec->sid;
5668 } else if (skb)
5669 selinux_skb_peerlbl_sid(skb, family, &peer_secid);
5670
5671 *secid = peer_secid;
5672 if (peer_secid == SECSID_NULL)
5673 return -ENOPROTOOPT;
5674 return 0;
5675 }
5676
selinux_sk_alloc_security(struct sock * sk,int family,gfp_t priority)5677 static int selinux_sk_alloc_security(struct sock *sk, int family, gfp_t priority)
5678 {
5679 struct sk_security_struct *sksec = selinux_sock(sk);
5680
5681 sksec->peer_sid = SECINITSID_UNLABELED;
5682 sksec->sid = SECINITSID_UNLABELED;
5683 sksec->sclass = SECCLASS_SOCKET;
5684 selinux_netlbl_sk_security_reset(sksec);
5685
5686 return 0;
5687 }
5688
selinux_sk_free_security(struct sock * sk)5689 static void selinux_sk_free_security(struct sock *sk)
5690 {
5691 struct sk_security_struct *sksec = selinux_sock(sk);
5692
5693 selinux_netlbl_sk_security_free(sksec);
5694 }
5695
selinux_sk_clone_security(const struct sock * sk,struct sock * newsk)5696 static void selinux_sk_clone_security(const struct sock *sk, struct sock *newsk)
5697 {
5698 struct sk_security_struct *sksec = selinux_sock(sk);
5699 struct sk_security_struct *newsksec = selinux_sock(newsk);
5700
5701 newsksec->sid = sksec->sid;
5702 newsksec->peer_sid = sksec->peer_sid;
5703 newsksec->sclass = sksec->sclass;
5704
5705 selinux_netlbl_sk_security_reset(newsksec);
5706 }
5707
selinux_sk_getsecid(const struct sock * sk,u32 * secid)5708 static void selinux_sk_getsecid(const struct sock *sk, u32 *secid)
5709 {
5710 if (!sk)
5711 *secid = SECINITSID_ANY_SOCKET;
5712 else {
5713 const struct sk_security_struct *sksec = selinux_sock(sk);
5714
5715 *secid = sksec->sid;
5716 }
5717 }
5718
selinux_sock_graft(struct sock * sk,struct socket * parent)5719 static void selinux_sock_graft(struct sock *sk, struct socket *parent)
5720 {
5721 struct inode_security_struct *isec =
5722 inode_security_novalidate(SOCK_INODE(parent));
5723 struct sk_security_struct *sksec = selinux_sock(sk);
5724
5725 if (sk->sk_family == PF_INET || sk->sk_family == PF_INET6 ||
5726 sk->sk_family == PF_UNIX)
5727 isec->sid = sksec->sid;
5728 sksec->sclass = isec->sclass;
5729 }
5730
5731 /*
5732 * Determines peer_secid for the asoc and updates socket's peer label
5733 * if it's the first association on the socket.
5734 */
selinux_sctp_process_new_assoc(struct sctp_association * asoc,struct sk_buff * skb)5735 static int selinux_sctp_process_new_assoc(struct sctp_association *asoc,
5736 struct sk_buff *skb)
5737 {
5738 struct sock *sk = asoc->base.sk;
5739 u16 family = sk->sk_family;
5740 struct sk_security_struct *sksec = selinux_sock(sk);
5741 struct common_audit_data ad;
5742 struct lsm_network_audit net;
5743 int err;
5744
5745 /* handle mapped IPv4 packets arriving via IPv6 sockets */
5746 if (family == PF_INET6 && skb->protocol == htons(ETH_P_IP))
5747 family = PF_INET;
5748
5749 if (selinux_peerlbl_enabled()) {
5750 asoc->peer_secid = SECSID_NULL;
5751
5752 /* This will return peer_sid = SECSID_NULL if there are
5753 * no peer labels, see security_net_peersid_resolve().
5754 */
5755 err = selinux_skb_peerlbl_sid(skb, family, &asoc->peer_secid);
5756 if (err)
5757 return err;
5758
5759 if (asoc->peer_secid == SECSID_NULL)
5760 asoc->peer_secid = SECINITSID_UNLABELED;
5761 } else {
5762 asoc->peer_secid = SECINITSID_UNLABELED;
5763 }
5764
5765 if (sksec->sctp_assoc_state == SCTP_ASSOC_UNSET) {
5766 sksec->sctp_assoc_state = SCTP_ASSOC_SET;
5767
5768 /* Here as first association on socket. As the peer SID
5769 * was allowed by peer recv (and the netif/node checks),
5770 * then it is approved by policy and used as the primary
5771 * peer SID for getpeercon(3).
5772 */
5773 sksec->peer_sid = asoc->peer_secid;
5774 } else if (sksec->peer_sid != asoc->peer_secid) {
5775 /* Other association peer SIDs are checked to enforce
5776 * consistency among the peer SIDs.
5777 */
5778 ad_net_init_from_sk(&ad, &net, asoc->base.sk);
5779 err = avc_has_perm(sksec->peer_sid, asoc->peer_secid,
5780 sksec->sclass, SCTP_SOCKET__ASSOCIATION,
5781 &ad);
5782 if (err)
5783 return err;
5784 }
5785 return 0;
5786 }
5787
5788 /* Called whenever SCTP receives an INIT or COOKIE ECHO chunk. This
5789 * happens on an incoming connect(2), sctp_connectx(3) or
5790 * sctp_sendmsg(3) (with no association already present).
5791 */
selinux_sctp_assoc_request(struct sctp_association * asoc,struct sk_buff * skb)5792 static int selinux_sctp_assoc_request(struct sctp_association *asoc,
5793 struct sk_buff *skb)
5794 {
5795 struct sk_security_struct *sksec = selinux_sock(asoc->base.sk);
5796 u32 conn_sid;
5797 int err;
5798
5799 if (!selinux_policycap_extsockclass())
5800 return 0;
5801
5802 err = selinux_sctp_process_new_assoc(asoc, skb);
5803 if (err)
5804 return err;
5805
5806 /* Compute the MLS component for the connection and store
5807 * the information in asoc. This will be used by SCTP TCP type
5808 * sockets and peeled off connections as they cause a new
5809 * socket to be generated. selinux_sctp_sk_clone() will then
5810 * plug this into the new socket.
5811 */
5812 err = selinux_conn_sid(sksec->sid, asoc->peer_secid, &conn_sid);
5813 if (err)
5814 return err;
5815
5816 asoc->secid = conn_sid;
5817
5818 /* Set any NetLabel labels including CIPSO/CALIPSO options. */
5819 return selinux_netlbl_sctp_assoc_request(asoc, skb);
5820 }
5821
5822 /* Called when SCTP receives a COOKIE ACK chunk as the final
5823 * response to an association request (initited by us).
5824 */
selinux_sctp_assoc_established(struct sctp_association * asoc,struct sk_buff * skb)5825 static int selinux_sctp_assoc_established(struct sctp_association *asoc,
5826 struct sk_buff *skb)
5827 {
5828 struct sk_security_struct *sksec = selinux_sock(asoc->base.sk);
5829
5830 if (!selinux_policycap_extsockclass())
5831 return 0;
5832
5833 /* Inherit secid from the parent socket - this will be picked up
5834 * by selinux_sctp_sk_clone() if the association gets peeled off
5835 * into a new socket.
5836 */
5837 asoc->secid = sksec->sid;
5838
5839 return selinux_sctp_process_new_assoc(asoc, skb);
5840 }
5841
5842 /* Check if sctp IPv4/IPv6 addresses are valid for binding or connecting
5843 * based on their @optname.
5844 */
selinux_sctp_bind_connect(struct sock * sk,int optname,struct sockaddr * address,int addrlen)5845 static int selinux_sctp_bind_connect(struct sock *sk, int optname,
5846 struct sockaddr *address,
5847 int addrlen)
5848 {
5849 int len, err = 0, walk_size = 0;
5850 void *addr_buf;
5851 struct sockaddr *addr;
5852
5853 if (!selinux_policycap_extsockclass())
5854 return 0;
5855
5856 /* Process one or more addresses that may be IPv4 or IPv6 */
5857 addr_buf = address;
5858
5859 while (walk_size < addrlen) {
5860 if (walk_size + sizeof(sa_family_t) > addrlen)
5861 return -EINVAL;
5862
5863 addr = addr_buf;
5864 switch (addr->sa_family) {
5865 case AF_UNSPEC:
5866 case AF_INET:
5867 len = sizeof(struct sockaddr_in);
5868 break;
5869 case AF_INET6:
5870 len = sizeof(struct sockaddr_in6);
5871 break;
5872 default:
5873 return -EINVAL;
5874 }
5875
5876 if (walk_size + len > addrlen)
5877 return -EINVAL;
5878
5879 err = -EINVAL;
5880 switch (optname) {
5881 /* Bind checks */
5882 case SCTP_PRIMARY_ADDR:
5883 case SCTP_SET_PEER_PRIMARY_ADDR:
5884 case SCTP_SOCKOPT_BINDX_ADD:
5885 err = __selinux_socket_bind(sk, addr, len);
5886 break;
5887 /* Connect checks */
5888 case SCTP_SOCKOPT_CONNECTX:
5889 case SCTP_PARAM_SET_PRIMARY:
5890 case SCTP_PARAM_ADD_IP:
5891 case SCTP_SENDMSG_CONNECT:
5892 err = selinux_socket_connect_helper(sk, addr, len);
5893 if (err)
5894 return err;
5895
5896 /* As selinux_sctp_bind_connect() is called by the
5897 * SCTP protocol layer, the socket is already locked,
5898 * therefore selinux_netlbl_socket_connect_locked()
5899 * is called here. The situations handled are:
5900 * sctp_connectx(3), sctp_sendmsg(3), sendmsg(2),
5901 * whenever a new IP address is added or when a new
5902 * primary address is selected.
5903 * Note that an SCTP connect(2) call happens before
5904 * the SCTP protocol layer and is handled via
5905 * selinux_socket_connect().
5906 */
5907 err = selinux_netlbl_socket_connect_locked(sk, addr);
5908 break;
5909 }
5910
5911 if (err)
5912 return err;
5913
5914 addr_buf += len;
5915 walk_size += len;
5916 }
5917
5918 return 0;
5919 }
5920
5921 /* Called whenever a new socket is created by accept(2) or sctp_peeloff(3). */
selinux_sctp_sk_clone(struct sctp_association * asoc,struct sock * sk,struct sock * newsk)5922 static void selinux_sctp_sk_clone(struct sctp_association *asoc, struct sock *sk,
5923 struct sock *newsk)
5924 {
5925 struct sk_security_struct *sksec = selinux_sock(sk);
5926 struct sk_security_struct *newsksec = selinux_sock(newsk);
5927
5928 /* If policy does not support SECCLASS_SCTP_SOCKET then call
5929 * the non-sctp clone version.
5930 */
5931 if (!selinux_policycap_extsockclass())
5932 return selinux_sk_clone_security(sk, newsk);
5933
5934 newsksec->sid = asoc->secid;
5935 newsksec->peer_sid = asoc->peer_secid;
5936 newsksec->sclass = sksec->sclass;
5937 selinux_netlbl_sctp_sk_clone(sk, newsk);
5938 }
5939
selinux_mptcp_add_subflow(struct sock * sk,struct sock * ssk)5940 static int selinux_mptcp_add_subflow(struct sock *sk, struct sock *ssk)
5941 {
5942 struct sk_security_struct *ssksec = selinux_sock(ssk);
5943 struct sk_security_struct *sksec = selinux_sock(sk);
5944
5945 ssksec->sclass = sksec->sclass;
5946 ssksec->sid = sksec->sid;
5947
5948 /* replace the existing subflow label deleting the existing one
5949 * and re-recreating a new label using the updated context
5950 */
5951 selinux_netlbl_sk_security_free(ssksec);
5952 return selinux_netlbl_socket_post_create(ssk, ssk->sk_family);
5953 }
5954
selinux_inet_conn_request(const struct sock * sk,struct sk_buff * skb,struct request_sock * req)5955 static int selinux_inet_conn_request(const struct sock *sk, struct sk_buff *skb,
5956 struct request_sock *req)
5957 {
5958 struct sk_security_struct *sksec = selinux_sock(sk);
5959 int err;
5960 u16 family = req->rsk_ops->family;
5961 u32 connsid;
5962 u32 peersid;
5963
5964 err = selinux_skb_peerlbl_sid(skb, family, &peersid);
5965 if (err)
5966 return err;
5967 err = selinux_conn_sid(sksec->sid, peersid, &connsid);
5968 if (err)
5969 return err;
5970 req->secid = connsid;
5971 req->peer_secid = peersid;
5972
5973 return selinux_netlbl_inet_conn_request(req, family);
5974 }
5975
selinux_inet_csk_clone(struct sock * newsk,const struct request_sock * req)5976 static void selinux_inet_csk_clone(struct sock *newsk,
5977 const struct request_sock *req)
5978 {
5979 struct sk_security_struct *newsksec = selinux_sock(newsk);
5980
5981 newsksec->sid = req->secid;
5982 newsksec->peer_sid = req->peer_secid;
5983 /* NOTE: Ideally, we should also get the isec->sid for the
5984 new socket in sync, but we don't have the isec available yet.
5985 So we will wait until sock_graft to do it, by which
5986 time it will have been created and available. */
5987
5988 /* We don't need to take any sort of lock here as we are the only
5989 * thread with access to newsksec */
5990 selinux_netlbl_inet_csk_clone(newsk, req->rsk_ops->family);
5991 }
5992
selinux_inet_conn_established(struct sock * sk,struct sk_buff * skb)5993 static void selinux_inet_conn_established(struct sock *sk, struct sk_buff *skb)
5994 {
5995 u16 family = sk->sk_family;
5996 struct sk_security_struct *sksec = selinux_sock(sk);
5997
5998 /* handle mapped IPv4 packets arriving via IPv6 sockets */
5999 if (family == PF_INET6 && skb->protocol == htons(ETH_P_IP))
6000 family = PF_INET;
6001
6002 selinux_skb_peerlbl_sid(skb, family, &sksec->peer_sid);
6003 }
6004
selinux_secmark_relabel_packet(u32 sid)6005 static int selinux_secmark_relabel_packet(u32 sid)
6006 {
6007 return avc_has_perm(current_sid(), sid, SECCLASS_PACKET, PACKET__RELABELTO,
6008 NULL);
6009 }
6010
selinux_secmark_refcount_inc(void)6011 static void selinux_secmark_refcount_inc(void)
6012 {
6013 atomic_inc(&selinux_secmark_refcount);
6014 }
6015
selinux_secmark_refcount_dec(void)6016 static void selinux_secmark_refcount_dec(void)
6017 {
6018 atomic_dec(&selinux_secmark_refcount);
6019 }
6020
selinux_req_classify_flow(const struct request_sock * req,struct flowi_common * flic)6021 static void selinux_req_classify_flow(const struct request_sock *req,
6022 struct flowi_common *flic)
6023 {
6024 flic->flowic_secid = req->secid;
6025 }
6026
selinux_tun_dev_alloc_security(void * security)6027 static int selinux_tun_dev_alloc_security(void *security)
6028 {
6029 struct tun_security_struct *tunsec = selinux_tun_dev(security);
6030
6031 tunsec->sid = current_sid();
6032 return 0;
6033 }
6034
selinux_tun_dev_create(void)6035 static int selinux_tun_dev_create(void)
6036 {
6037 u32 sid = current_sid();
6038
6039 /* we aren't taking into account the "sockcreate" SID since the socket
6040 * that is being created here is not a socket in the traditional sense,
6041 * instead it is a private sock, accessible only to the kernel, and
6042 * representing a wide range of network traffic spanning multiple
6043 * connections unlike traditional sockets - check the TUN driver to
6044 * get a better understanding of why this socket is special */
6045
6046 return avc_has_perm(sid, sid, SECCLASS_TUN_SOCKET, TUN_SOCKET__CREATE,
6047 NULL);
6048 }
6049
selinux_tun_dev_attach_queue(void * security)6050 static int selinux_tun_dev_attach_queue(void *security)
6051 {
6052 struct tun_security_struct *tunsec = selinux_tun_dev(security);
6053
6054 return avc_has_perm(current_sid(), tunsec->sid, SECCLASS_TUN_SOCKET,
6055 TUN_SOCKET__ATTACH_QUEUE, NULL);
6056 }
6057
selinux_tun_dev_attach(struct sock * sk,void * security)6058 static int selinux_tun_dev_attach(struct sock *sk, void *security)
6059 {
6060 struct tun_security_struct *tunsec = selinux_tun_dev(security);
6061 struct sk_security_struct *sksec = selinux_sock(sk);
6062
6063 /* we don't currently perform any NetLabel based labeling here and it
6064 * isn't clear that we would want to do so anyway; while we could apply
6065 * labeling without the support of the TUN user the resulting labeled
6066 * traffic from the other end of the connection would almost certainly
6067 * cause confusion to the TUN user that had no idea network labeling
6068 * protocols were being used */
6069
6070 sksec->sid = tunsec->sid;
6071 sksec->sclass = SECCLASS_TUN_SOCKET;
6072
6073 return 0;
6074 }
6075
selinux_tun_dev_open(void * security)6076 static int selinux_tun_dev_open(void *security)
6077 {
6078 struct tun_security_struct *tunsec = selinux_tun_dev(security);
6079 u32 sid = current_sid();
6080 int err;
6081
6082 err = avc_has_perm(sid, tunsec->sid, SECCLASS_TUN_SOCKET,
6083 TUN_SOCKET__RELABELFROM, NULL);
6084 if (err)
6085 return err;
6086 err = avc_has_perm(sid, sid, SECCLASS_TUN_SOCKET,
6087 TUN_SOCKET__RELABELTO, NULL);
6088 if (err)
6089 return err;
6090 tunsec->sid = sid;
6091
6092 return 0;
6093 }
6094
6095 #ifdef CONFIG_NETFILTER
6096
selinux_ip_forward(void * priv,struct sk_buff * skb,const struct nf_hook_state * state)6097 static unsigned int selinux_ip_forward(void *priv, struct sk_buff *skb,
6098 const struct nf_hook_state *state)
6099 {
6100 int ifindex;
6101 u16 family;
6102 char *addrp;
6103 u32 peer_sid;
6104 struct common_audit_data ad;
6105 struct lsm_network_audit net;
6106 int secmark_active, peerlbl_active;
6107
6108 if (!selinux_policycap_netpeer())
6109 return NF_ACCEPT;
6110
6111 secmark_active = selinux_secmark_enabled();
6112 peerlbl_active = selinux_peerlbl_enabled();
6113 if (!secmark_active && !peerlbl_active)
6114 return NF_ACCEPT;
6115
6116 family = state->pf;
6117 if (selinux_skb_peerlbl_sid(skb, family, &peer_sid) != 0)
6118 return NF_DROP;
6119
6120 ifindex = state->in->ifindex;
6121 ad_net_init_from_iif(&ad, &net, ifindex, family);
6122 if (selinux_parse_skb(skb, &ad, &addrp, 1, NULL) != 0)
6123 return NF_DROP;
6124
6125 if (peerlbl_active) {
6126 int err;
6127
6128 err = selinux_inet_sys_rcv_skb(state->net, ifindex,
6129 addrp, family, peer_sid, &ad);
6130 if (err) {
6131 selinux_netlbl_err(skb, family, err, 1);
6132 return NF_DROP;
6133 }
6134 }
6135
6136 if (secmark_active)
6137 if (avc_has_perm(peer_sid, skb->secmark,
6138 SECCLASS_PACKET, PACKET__FORWARD_IN, &ad))
6139 return NF_DROP;
6140
6141 if (netlbl_enabled())
6142 /* we do this in the FORWARD path and not the POST_ROUTING
6143 * path because we want to make sure we apply the necessary
6144 * labeling before IPsec is applied so we can leverage AH
6145 * protection */
6146 if (selinux_netlbl_skbuff_setsid(skb, family, peer_sid) != 0)
6147 return NF_DROP;
6148
6149 return NF_ACCEPT;
6150 }
6151
selinux_ip_output(void * priv,struct sk_buff * skb,const struct nf_hook_state * state)6152 static unsigned int selinux_ip_output(void *priv, struct sk_buff *skb,
6153 const struct nf_hook_state *state)
6154 {
6155 struct sock *sk;
6156 u32 sid;
6157
6158 if (!netlbl_enabled())
6159 return NF_ACCEPT;
6160
6161 /* we do this in the LOCAL_OUT path and not the POST_ROUTING path
6162 * because we want to make sure we apply the necessary labeling
6163 * before IPsec is applied so we can leverage AH protection */
6164 sk = skb_to_full_sk(skb);
6165 if (sk) {
6166 struct sk_security_struct *sksec;
6167
6168 if (sk_listener(sk))
6169 /* if the socket is the listening state then this
6170 * packet is a SYN-ACK packet which means it needs to
6171 * be labeled based on the connection/request_sock and
6172 * not the parent socket. unfortunately, we can't
6173 * lookup the request_sock yet as it isn't queued on
6174 * the parent socket until after the SYN-ACK is sent.
6175 * the "solution" is to simply pass the packet as-is
6176 * as any IP option based labeling should be copied
6177 * from the initial connection request (in the IP
6178 * layer). it is far from ideal, but until we get a
6179 * security label in the packet itself this is the
6180 * best we can do. */
6181 return NF_ACCEPT;
6182
6183 /* standard practice, label using the parent socket */
6184 sksec = selinux_sock(sk);
6185 sid = sksec->sid;
6186 } else
6187 sid = SECINITSID_KERNEL;
6188 if (selinux_netlbl_skbuff_setsid(skb, state->pf, sid) != 0)
6189 return NF_DROP;
6190
6191 return NF_ACCEPT;
6192 }
6193
6194
selinux_ip_postroute_compat(struct sk_buff * skb,const struct nf_hook_state * state)6195 static unsigned int selinux_ip_postroute_compat(struct sk_buff *skb,
6196 const struct nf_hook_state *state)
6197 {
6198 struct sock *sk;
6199 struct sk_security_struct *sksec;
6200 struct common_audit_data ad;
6201 struct lsm_network_audit net;
6202 u8 proto = 0;
6203
6204 sk = skb_to_full_sk(skb);
6205 if (sk == NULL)
6206 return NF_ACCEPT;
6207 sksec = selinux_sock(sk);
6208
6209 ad_net_init_from_iif(&ad, &net, state->out->ifindex, state->pf);
6210 if (selinux_parse_skb(skb, &ad, NULL, 0, &proto))
6211 return NF_DROP;
6212
6213 if (selinux_secmark_enabled())
6214 if (avc_has_perm(sksec->sid, skb->secmark,
6215 SECCLASS_PACKET, PACKET__SEND, &ad))
6216 return NF_DROP_ERR(-ECONNREFUSED);
6217
6218 if (selinux_xfrm_postroute_last(sksec->sid, skb, &ad, proto))
6219 return NF_DROP_ERR(-ECONNREFUSED);
6220
6221 return NF_ACCEPT;
6222 }
6223
selinux_ip_postroute(void * priv,struct sk_buff * skb,const struct nf_hook_state * state)6224 static unsigned int selinux_ip_postroute(void *priv,
6225 struct sk_buff *skb,
6226 const struct nf_hook_state *state)
6227 {
6228 u16 family;
6229 u32 secmark_perm;
6230 u32 peer_sid;
6231 int ifindex;
6232 struct sock *sk;
6233 struct common_audit_data ad;
6234 struct lsm_network_audit net;
6235 char *addrp;
6236 int secmark_active, peerlbl_active;
6237
6238 /* If any sort of compatibility mode is enabled then handoff processing
6239 * to the selinux_ip_postroute_compat() function to deal with the
6240 * special handling. We do this in an attempt to keep this function
6241 * as fast and as clean as possible. */
6242 if (!selinux_policycap_netpeer())
6243 return selinux_ip_postroute_compat(skb, state);
6244
6245 secmark_active = selinux_secmark_enabled();
6246 peerlbl_active = selinux_peerlbl_enabled();
6247 if (!secmark_active && !peerlbl_active)
6248 return NF_ACCEPT;
6249
6250 sk = skb_to_full_sk(skb);
6251
6252 #ifdef CONFIG_XFRM
6253 /* If skb->dst->xfrm is non-NULL then the packet is undergoing an IPsec
6254 * packet transformation so allow the packet to pass without any checks
6255 * since we'll have another chance to perform access control checks
6256 * when the packet is on it's final way out.
6257 * NOTE: there appear to be some IPv6 multicast cases where skb->dst
6258 * is NULL, in this case go ahead and apply access control.
6259 * NOTE: if this is a local socket (skb->sk != NULL) that is in the
6260 * TCP listening state we cannot wait until the XFRM processing
6261 * is done as we will miss out on the SA label if we do;
6262 * unfortunately, this means more work, but it is only once per
6263 * connection. */
6264 if (skb_dst(skb) != NULL && skb_dst(skb)->xfrm != NULL &&
6265 !(sk && sk_listener(sk)))
6266 return NF_ACCEPT;
6267 #endif
6268
6269 family = state->pf;
6270 if (sk == NULL) {
6271 /* Without an associated socket the packet is either coming
6272 * from the kernel or it is being forwarded; check the packet
6273 * to determine which and if the packet is being forwarded
6274 * query the packet directly to determine the security label. */
6275 if (skb->skb_iif) {
6276 secmark_perm = PACKET__FORWARD_OUT;
6277 if (selinux_skb_peerlbl_sid(skb, family, &peer_sid))
6278 return NF_DROP;
6279 } else {
6280 secmark_perm = PACKET__SEND;
6281 peer_sid = SECINITSID_KERNEL;
6282 }
6283 } else if (sk_listener(sk)) {
6284 /* Locally generated packet but the associated socket is in the
6285 * listening state which means this is a SYN-ACK packet. In
6286 * this particular case the correct security label is assigned
6287 * to the connection/request_sock but unfortunately we can't
6288 * query the request_sock as it isn't queued on the parent
6289 * socket until after the SYN-ACK packet is sent; the only
6290 * viable choice is to regenerate the label like we do in
6291 * selinux_inet_conn_request(). See also selinux_ip_output()
6292 * for similar problems. */
6293 u32 skb_sid;
6294 struct sk_security_struct *sksec;
6295
6296 sksec = selinux_sock(sk);
6297 if (selinux_skb_peerlbl_sid(skb, family, &skb_sid))
6298 return NF_DROP;
6299 /* At this point, if the returned skb peerlbl is SECSID_NULL
6300 * and the packet has been through at least one XFRM
6301 * transformation then we must be dealing with the "final"
6302 * form of labeled IPsec packet; since we've already applied
6303 * all of our access controls on this packet we can safely
6304 * pass the packet. */
6305 if (skb_sid == SECSID_NULL) {
6306 switch (family) {
6307 case PF_INET:
6308 if (IPCB(skb)->flags & IPSKB_XFRM_TRANSFORMED)
6309 return NF_ACCEPT;
6310 break;
6311 case PF_INET6:
6312 if (IP6CB(skb)->flags & IP6SKB_XFRM_TRANSFORMED)
6313 return NF_ACCEPT;
6314 break;
6315 default:
6316 return NF_DROP_ERR(-ECONNREFUSED);
6317 }
6318 }
6319 if (selinux_conn_sid(sksec->sid, skb_sid, &peer_sid))
6320 return NF_DROP;
6321 secmark_perm = PACKET__SEND;
6322 } else {
6323 /* Locally generated packet, fetch the security label from the
6324 * associated socket. */
6325 struct sk_security_struct *sksec = selinux_sock(sk);
6326 peer_sid = sksec->sid;
6327 secmark_perm = PACKET__SEND;
6328 }
6329
6330 ifindex = state->out->ifindex;
6331 ad_net_init_from_iif(&ad, &net, ifindex, family);
6332 if (selinux_parse_skb(skb, &ad, &addrp, 0, NULL))
6333 return NF_DROP;
6334
6335 if (secmark_active)
6336 if (avc_has_perm(peer_sid, skb->secmark,
6337 SECCLASS_PACKET, secmark_perm, &ad))
6338 return NF_DROP_ERR(-ECONNREFUSED);
6339
6340 if (peerlbl_active) {
6341 u32 if_sid;
6342 u32 node_sid;
6343
6344 if (sel_netif_sid(state->net, ifindex, &if_sid))
6345 return NF_DROP;
6346 if (avc_has_perm(peer_sid, if_sid,
6347 SECCLASS_NETIF, NETIF__EGRESS, &ad))
6348 return NF_DROP_ERR(-ECONNREFUSED);
6349
6350 if (sel_netnode_sid(addrp, family, &node_sid))
6351 return NF_DROP;
6352 if (avc_has_perm(peer_sid, node_sid,
6353 SECCLASS_NODE, NODE__SENDTO, &ad))
6354 return NF_DROP_ERR(-ECONNREFUSED);
6355 }
6356
6357 return NF_ACCEPT;
6358 }
6359 #endif /* CONFIG_NETFILTER */
6360
nlmsg_sock_has_extended_perms(struct sock * sk,u32 perms,u16 nlmsg_type)6361 static int nlmsg_sock_has_extended_perms(struct sock *sk, u32 perms, u16 nlmsg_type)
6362 {
6363 struct sk_security_struct *sksec = selinux_sock(sk);
6364 struct common_audit_data ad;
6365 u8 driver;
6366 u8 xperm;
6367
6368 if (sock_skip_has_perm(sksec->sid))
6369 return 0;
6370
6371 ad.type = LSM_AUDIT_DATA_NLMSGTYPE;
6372 ad.u.nlmsg_type = nlmsg_type;
6373
6374 driver = nlmsg_type >> 8;
6375 xperm = nlmsg_type & 0xff;
6376
6377 return avc_has_extended_perms(current_sid(), sksec->sid, sksec->sclass,
6378 perms, driver, AVC_EXT_NLMSG, xperm, &ad);
6379 }
6380
selinux_netlink_send(struct sock * sk,struct sk_buff * skb)6381 static int selinux_netlink_send(struct sock *sk, struct sk_buff *skb)
6382 {
6383 int rc = 0;
6384 unsigned int msg_len;
6385 unsigned int data_len = skb->len;
6386 unsigned char *data = skb->data;
6387 struct nlmsghdr *nlh;
6388 struct sk_security_struct *sksec = selinux_sock(sk);
6389 u16 sclass = sksec->sclass;
6390 u32 perm;
6391
6392 while (data_len >= nlmsg_total_size(0)) {
6393 nlh = (struct nlmsghdr *)data;
6394
6395 /* NOTE: the nlmsg_len field isn't reliably set by some netlink
6396 * users which means we can't reject skb's with bogus
6397 * length fields; our solution is to follow what
6398 * netlink_rcv_skb() does and simply skip processing at
6399 * messages with length fields that are clearly junk
6400 */
6401 if (nlh->nlmsg_len < NLMSG_HDRLEN || nlh->nlmsg_len > data_len)
6402 return 0;
6403
6404 rc = selinux_nlmsg_lookup(sclass, nlh->nlmsg_type, &perm);
6405 if (rc == 0) {
6406 if (selinux_policycap_netlink_xperm()) {
6407 rc = nlmsg_sock_has_extended_perms(
6408 sk, perm, nlh->nlmsg_type);
6409 } else {
6410 rc = sock_has_perm(sk, perm);
6411 }
6412 if (rc)
6413 return rc;
6414 } else if (rc == -EINVAL) {
6415 /* -EINVAL is a missing msg/perm mapping */
6416 if (sclass == SECCLASS_NETLINK_TCPDIAG_SOCKET &&
6417 nlh->nlmsg_type == DCCPDIAG_GETSOCK)
6418 pr_warn_once("SELinux: DCCP has been removed, pid=%d comm=%s\n",
6419 task_pid_nr(current), current->comm);
6420 else
6421 pr_warn_ratelimited("SELinux: unrecognized netlink"
6422 " message: protocol=%hu nlmsg_type=%hu sclass=%s"
6423 " pid=%d comm=%s\n",
6424 sk->sk_protocol, nlh->nlmsg_type,
6425 secclass_map[sclass - 1].name,
6426 task_pid_nr(current), current->comm);
6427 if (enforcing_enabled() &&
6428 !security_get_allow_unknown())
6429 return rc;
6430 rc = 0;
6431 } else if (rc == -ENOENT) {
6432 /* -ENOENT is a missing socket/class mapping, ignore */
6433 rc = 0;
6434 } else {
6435 return rc;
6436 }
6437
6438 /* move to the next message after applying netlink padding */
6439 msg_len = NLMSG_ALIGN(nlh->nlmsg_len);
6440 if (msg_len >= data_len)
6441 return 0;
6442 data_len -= msg_len;
6443 data += msg_len;
6444 }
6445
6446 return rc;
6447 }
6448
ipc_init_security(struct ipc_security_struct * isec,u16 sclass)6449 static void ipc_init_security(struct ipc_security_struct *isec, u16 sclass)
6450 {
6451 isec->sclass = sclass;
6452 isec->sid = current_sid();
6453 }
6454
ipc_has_perm(struct kern_ipc_perm * ipc_perms,u32 perms)6455 static int ipc_has_perm(struct kern_ipc_perm *ipc_perms,
6456 u32 perms)
6457 {
6458 struct ipc_security_struct *isec;
6459 struct common_audit_data ad;
6460 u32 sid = current_sid();
6461
6462 isec = selinux_ipc(ipc_perms);
6463
6464 ad.type = LSM_AUDIT_DATA_IPC;
6465 ad.u.ipc_id = ipc_perms->key;
6466
6467 return avc_has_perm(sid, isec->sid, isec->sclass, perms, &ad);
6468 }
6469
selinux_msg_msg_alloc_security(struct msg_msg * msg)6470 static int selinux_msg_msg_alloc_security(struct msg_msg *msg)
6471 {
6472 struct msg_security_struct *msec;
6473
6474 msec = selinux_msg_msg(msg);
6475 msec->sid = SECINITSID_UNLABELED;
6476
6477 return 0;
6478 }
6479
6480 /* message queue security operations */
selinux_msg_queue_alloc_security(struct kern_ipc_perm * msq)6481 static int selinux_msg_queue_alloc_security(struct kern_ipc_perm *msq)
6482 {
6483 struct ipc_security_struct *isec;
6484 struct common_audit_data ad;
6485 u32 sid = current_sid();
6486
6487 isec = selinux_ipc(msq);
6488 ipc_init_security(isec, SECCLASS_MSGQ);
6489
6490 ad.type = LSM_AUDIT_DATA_IPC;
6491 ad.u.ipc_id = msq->key;
6492
6493 return avc_has_perm(sid, isec->sid, SECCLASS_MSGQ,
6494 MSGQ__CREATE, &ad);
6495 }
6496
selinux_msg_queue_associate(struct kern_ipc_perm * msq,int msqflg)6497 static int selinux_msg_queue_associate(struct kern_ipc_perm *msq, int msqflg)
6498 {
6499 struct ipc_security_struct *isec;
6500 struct common_audit_data ad;
6501 u32 sid = current_sid();
6502
6503 isec = selinux_ipc(msq);
6504
6505 ad.type = LSM_AUDIT_DATA_IPC;
6506 ad.u.ipc_id = msq->key;
6507
6508 return avc_has_perm(sid, isec->sid, SECCLASS_MSGQ,
6509 MSGQ__ASSOCIATE, &ad);
6510 }
6511
selinux_msg_queue_msgctl(struct kern_ipc_perm * msq,int cmd)6512 static int selinux_msg_queue_msgctl(struct kern_ipc_perm *msq, int cmd)
6513 {
6514 u32 perms;
6515
6516 switch (cmd) {
6517 case IPC_INFO:
6518 case MSG_INFO:
6519 /* No specific object, just general system-wide information. */
6520 return avc_has_perm(current_sid(), SECINITSID_KERNEL,
6521 SECCLASS_SYSTEM, SYSTEM__IPC_INFO, NULL);
6522 case IPC_STAT:
6523 case MSG_STAT:
6524 case MSG_STAT_ANY:
6525 perms = MSGQ__GETATTR | MSGQ__ASSOCIATE;
6526 break;
6527 case IPC_SET:
6528 perms = MSGQ__SETATTR;
6529 break;
6530 case IPC_RMID:
6531 perms = MSGQ__DESTROY;
6532 break;
6533 default:
6534 return 0;
6535 }
6536
6537 return ipc_has_perm(msq, perms);
6538 }
6539
selinux_msg_queue_msgsnd(struct kern_ipc_perm * msq,struct msg_msg * msg,int msqflg)6540 static int selinux_msg_queue_msgsnd(struct kern_ipc_perm *msq, struct msg_msg *msg, int msqflg)
6541 {
6542 struct ipc_security_struct *isec;
6543 struct msg_security_struct *msec;
6544 struct common_audit_data ad;
6545 u32 sid = current_sid();
6546 int rc;
6547
6548 isec = selinux_ipc(msq);
6549 msec = selinux_msg_msg(msg);
6550
6551 /*
6552 * First time through, need to assign label to the message
6553 */
6554 if (msec->sid == SECINITSID_UNLABELED) {
6555 /*
6556 * Compute new sid based on current process and
6557 * message queue this message will be stored in
6558 */
6559 rc = security_transition_sid(sid, isec->sid,
6560 SECCLASS_MSG, NULL, &msec->sid);
6561 if (rc)
6562 return rc;
6563 }
6564
6565 ad.type = LSM_AUDIT_DATA_IPC;
6566 ad.u.ipc_id = msq->key;
6567
6568 /* Can this process write to the queue? */
6569 rc = avc_has_perm(sid, isec->sid, SECCLASS_MSGQ,
6570 MSGQ__WRITE, &ad);
6571 if (!rc)
6572 /* Can this process send the message */
6573 rc = avc_has_perm(sid, msec->sid, SECCLASS_MSG,
6574 MSG__SEND, &ad);
6575 if (!rc)
6576 /* Can the message be put in the queue? */
6577 rc = avc_has_perm(msec->sid, isec->sid, SECCLASS_MSGQ,
6578 MSGQ__ENQUEUE, &ad);
6579
6580 return rc;
6581 }
6582
selinux_msg_queue_msgrcv(struct kern_ipc_perm * msq,struct msg_msg * msg,struct task_struct * target,long type,int mode)6583 static int selinux_msg_queue_msgrcv(struct kern_ipc_perm *msq, struct msg_msg *msg,
6584 struct task_struct *target,
6585 long type, int mode)
6586 {
6587 struct ipc_security_struct *isec;
6588 struct msg_security_struct *msec;
6589 struct common_audit_data ad;
6590 u32 sid = task_sid_obj(target);
6591 int rc;
6592
6593 isec = selinux_ipc(msq);
6594 msec = selinux_msg_msg(msg);
6595
6596 ad.type = LSM_AUDIT_DATA_IPC;
6597 ad.u.ipc_id = msq->key;
6598
6599 rc = avc_has_perm(sid, isec->sid,
6600 SECCLASS_MSGQ, MSGQ__READ, &ad);
6601 if (!rc)
6602 rc = avc_has_perm(sid, msec->sid,
6603 SECCLASS_MSG, MSG__RECEIVE, &ad);
6604 return rc;
6605 }
6606
6607 /* Shared Memory security operations */
selinux_shm_alloc_security(struct kern_ipc_perm * shp)6608 static int selinux_shm_alloc_security(struct kern_ipc_perm *shp)
6609 {
6610 struct ipc_security_struct *isec;
6611 struct common_audit_data ad;
6612 u32 sid = current_sid();
6613
6614 isec = selinux_ipc(shp);
6615 ipc_init_security(isec, SECCLASS_SHM);
6616
6617 ad.type = LSM_AUDIT_DATA_IPC;
6618 ad.u.ipc_id = shp->key;
6619
6620 return avc_has_perm(sid, isec->sid, SECCLASS_SHM,
6621 SHM__CREATE, &ad);
6622 }
6623
selinux_shm_associate(struct kern_ipc_perm * shp,int shmflg)6624 static int selinux_shm_associate(struct kern_ipc_perm *shp, int shmflg)
6625 {
6626 struct ipc_security_struct *isec;
6627 struct common_audit_data ad;
6628 u32 sid = current_sid();
6629
6630 isec = selinux_ipc(shp);
6631
6632 ad.type = LSM_AUDIT_DATA_IPC;
6633 ad.u.ipc_id = shp->key;
6634
6635 return avc_has_perm(sid, isec->sid, SECCLASS_SHM,
6636 SHM__ASSOCIATE, &ad);
6637 }
6638
6639 /* Note, at this point, shp is locked down */
selinux_shm_shmctl(struct kern_ipc_perm * shp,int cmd)6640 static int selinux_shm_shmctl(struct kern_ipc_perm *shp, int cmd)
6641 {
6642 u32 perms;
6643
6644 switch (cmd) {
6645 case IPC_INFO:
6646 case SHM_INFO:
6647 /* No specific object, just general system-wide information. */
6648 return avc_has_perm(current_sid(), SECINITSID_KERNEL,
6649 SECCLASS_SYSTEM, SYSTEM__IPC_INFO, NULL);
6650 case IPC_STAT:
6651 case SHM_STAT:
6652 case SHM_STAT_ANY:
6653 perms = SHM__GETATTR | SHM__ASSOCIATE;
6654 break;
6655 case IPC_SET:
6656 perms = SHM__SETATTR;
6657 break;
6658 case SHM_LOCK:
6659 case SHM_UNLOCK:
6660 perms = SHM__LOCK;
6661 break;
6662 case IPC_RMID:
6663 perms = SHM__DESTROY;
6664 break;
6665 default:
6666 return 0;
6667 }
6668
6669 return ipc_has_perm(shp, perms);
6670 }
6671
selinux_shm_shmat(struct kern_ipc_perm * shp,char __user * shmaddr,int shmflg)6672 static int selinux_shm_shmat(struct kern_ipc_perm *shp,
6673 char __user *shmaddr, int shmflg)
6674 {
6675 u32 perms;
6676
6677 if (shmflg & SHM_RDONLY)
6678 perms = SHM__READ;
6679 else
6680 perms = SHM__READ | SHM__WRITE;
6681
6682 return ipc_has_perm(shp, perms);
6683 }
6684
6685 /* Semaphore security operations */
selinux_sem_alloc_security(struct kern_ipc_perm * sma)6686 static int selinux_sem_alloc_security(struct kern_ipc_perm *sma)
6687 {
6688 struct ipc_security_struct *isec;
6689 struct common_audit_data ad;
6690 u32 sid = current_sid();
6691
6692 isec = selinux_ipc(sma);
6693 ipc_init_security(isec, SECCLASS_SEM);
6694
6695 ad.type = LSM_AUDIT_DATA_IPC;
6696 ad.u.ipc_id = sma->key;
6697
6698 return avc_has_perm(sid, isec->sid, SECCLASS_SEM,
6699 SEM__CREATE, &ad);
6700 }
6701
selinux_sem_associate(struct kern_ipc_perm * sma,int semflg)6702 static int selinux_sem_associate(struct kern_ipc_perm *sma, int semflg)
6703 {
6704 struct ipc_security_struct *isec;
6705 struct common_audit_data ad;
6706 u32 sid = current_sid();
6707
6708 isec = selinux_ipc(sma);
6709
6710 ad.type = LSM_AUDIT_DATA_IPC;
6711 ad.u.ipc_id = sma->key;
6712
6713 return avc_has_perm(sid, isec->sid, SECCLASS_SEM,
6714 SEM__ASSOCIATE, &ad);
6715 }
6716
6717 /* Note, at this point, sma is locked down */
selinux_sem_semctl(struct kern_ipc_perm * sma,int cmd)6718 static int selinux_sem_semctl(struct kern_ipc_perm *sma, int cmd)
6719 {
6720 int err;
6721 u32 perms;
6722
6723 switch (cmd) {
6724 case IPC_INFO:
6725 case SEM_INFO:
6726 /* No specific object, just general system-wide information. */
6727 return avc_has_perm(current_sid(), SECINITSID_KERNEL,
6728 SECCLASS_SYSTEM, SYSTEM__IPC_INFO, NULL);
6729 case GETPID:
6730 case GETNCNT:
6731 case GETZCNT:
6732 perms = SEM__GETATTR;
6733 break;
6734 case GETVAL:
6735 case GETALL:
6736 perms = SEM__READ;
6737 break;
6738 case SETVAL:
6739 case SETALL:
6740 perms = SEM__WRITE;
6741 break;
6742 case IPC_RMID:
6743 perms = SEM__DESTROY;
6744 break;
6745 case IPC_SET:
6746 perms = SEM__SETATTR;
6747 break;
6748 case IPC_STAT:
6749 case SEM_STAT:
6750 case SEM_STAT_ANY:
6751 perms = SEM__GETATTR | SEM__ASSOCIATE;
6752 break;
6753 default:
6754 return 0;
6755 }
6756
6757 err = ipc_has_perm(sma, perms);
6758 return err;
6759 }
6760
selinux_sem_semop(struct kern_ipc_perm * sma,struct sembuf * sops,unsigned nsops,int alter)6761 static int selinux_sem_semop(struct kern_ipc_perm *sma,
6762 struct sembuf *sops, unsigned nsops, int alter)
6763 {
6764 u32 perms;
6765
6766 if (alter)
6767 perms = SEM__READ | SEM__WRITE;
6768 else
6769 perms = SEM__READ;
6770
6771 return ipc_has_perm(sma, perms);
6772 }
6773
selinux_ipc_permission(struct kern_ipc_perm * ipcp,short flag)6774 static int selinux_ipc_permission(struct kern_ipc_perm *ipcp, short flag)
6775 {
6776 u32 av = 0;
6777
6778 av = 0;
6779 if (flag & S_IRUGO)
6780 av |= IPC__UNIX_READ;
6781 if (flag & S_IWUGO)
6782 av |= IPC__UNIX_WRITE;
6783
6784 if (av == 0)
6785 return 0;
6786
6787 return ipc_has_perm(ipcp, av);
6788 }
6789
selinux_ipc_getlsmprop(struct kern_ipc_perm * ipcp,struct lsm_prop * prop)6790 static void selinux_ipc_getlsmprop(struct kern_ipc_perm *ipcp,
6791 struct lsm_prop *prop)
6792 {
6793 struct ipc_security_struct *isec = selinux_ipc(ipcp);
6794 prop->selinux.secid = isec->sid;
6795 }
6796
selinux_d_instantiate(struct dentry * dentry,struct inode * inode)6797 static void selinux_d_instantiate(struct dentry *dentry, struct inode *inode)
6798 {
6799 if (inode)
6800 inode_doinit_with_dentry(inode, dentry);
6801 }
6802
selinux_lsm_getattr(unsigned int attr,struct task_struct * p,char ** value)6803 static int selinux_lsm_getattr(unsigned int attr, struct task_struct *p,
6804 char **value)
6805 {
6806 const struct cred_security_struct *crsec;
6807 int error;
6808 u32 sid;
6809 u32 len;
6810
6811 rcu_read_lock();
6812 crsec = selinux_cred(__task_cred(p));
6813 if (p != current) {
6814 error = avc_has_perm(current_sid(), crsec->sid,
6815 SECCLASS_PROCESS, PROCESS__GETATTR, NULL);
6816 if (error)
6817 goto err_unlock;
6818 }
6819 switch (attr) {
6820 case LSM_ATTR_CURRENT:
6821 sid = crsec->sid;
6822 break;
6823 case LSM_ATTR_PREV:
6824 sid = crsec->osid;
6825 break;
6826 case LSM_ATTR_EXEC:
6827 sid = crsec->exec_sid;
6828 break;
6829 case LSM_ATTR_FSCREATE:
6830 sid = crsec->create_sid;
6831 break;
6832 case LSM_ATTR_KEYCREATE:
6833 sid = crsec->keycreate_sid;
6834 break;
6835 case LSM_ATTR_SOCKCREATE:
6836 sid = crsec->sockcreate_sid;
6837 break;
6838 default:
6839 error = -EOPNOTSUPP;
6840 goto err_unlock;
6841 }
6842 rcu_read_unlock();
6843
6844 if (sid == SECSID_NULL) {
6845 *value = NULL;
6846 return 0;
6847 }
6848
6849 error = security_sid_to_context(sid, value, &len);
6850 if (error)
6851 return error;
6852 return len;
6853
6854 err_unlock:
6855 rcu_read_unlock();
6856 return error;
6857 }
6858
selinux_lsm_setattr(u64 attr,void * value,size_t size)6859 static int selinux_lsm_setattr(u64 attr, void *value, size_t size)
6860 {
6861 struct cred_security_struct *crsec;
6862 struct cred *new;
6863 u32 mysid = current_sid(), sid = 0, ptsid;
6864 int error;
6865 char *str = value;
6866
6867 /*
6868 * Basic control over ability to set these attributes at all.
6869 */
6870 switch (attr) {
6871 case LSM_ATTR_EXEC:
6872 error = avc_has_perm(mysid, mysid, SECCLASS_PROCESS,
6873 PROCESS__SETEXEC, NULL);
6874 break;
6875 case LSM_ATTR_FSCREATE:
6876 error = avc_has_perm(mysid, mysid, SECCLASS_PROCESS,
6877 PROCESS__SETFSCREATE, NULL);
6878 break;
6879 case LSM_ATTR_KEYCREATE:
6880 error = avc_has_perm(mysid, mysid, SECCLASS_PROCESS,
6881 PROCESS__SETKEYCREATE, NULL);
6882 break;
6883 case LSM_ATTR_SOCKCREATE:
6884 error = avc_has_perm(mysid, mysid, SECCLASS_PROCESS,
6885 PROCESS__SETSOCKCREATE, NULL);
6886 break;
6887 case LSM_ATTR_CURRENT:
6888 error = avc_has_perm(mysid, mysid, SECCLASS_PROCESS,
6889 PROCESS__SETCURRENT, NULL);
6890 break;
6891 default:
6892 error = -EOPNOTSUPP;
6893 break;
6894 }
6895 if (error)
6896 return error;
6897
6898 /* Obtain a SID for the context, if one was specified. */
6899 if (size && str[0] && str[0] != '\n') {
6900 if (str[size-1] == '\n') {
6901 str[size-1] = 0;
6902 size--;
6903 }
6904 error = security_context_to_sid(value, size,
6905 &sid, GFP_KERNEL);
6906 if (error == -EINVAL && attr == LSM_ATTR_FSCREATE) {
6907 if (!has_cap_mac_admin(true)) {
6908 struct audit_buffer *ab;
6909 size_t audit_size;
6910
6911 /* We strip a nul only if it is at the end,
6912 * otherwise the context contains a nul and
6913 * we should audit that */
6914 if (str[size - 1] == '\0')
6915 audit_size = size - 1;
6916 else
6917 audit_size = size;
6918 ab = audit_log_start(audit_context(),
6919 GFP_ATOMIC,
6920 AUDIT_SELINUX_ERR);
6921 if (!ab)
6922 return error;
6923 audit_log_format(ab, "op=fscreate invalid_context=");
6924 audit_log_n_untrustedstring(ab, value,
6925 audit_size);
6926 audit_log_end(ab);
6927
6928 return error;
6929 }
6930 error = security_context_to_sid_force(value, size,
6931 &sid);
6932 }
6933 if (error)
6934 return error;
6935 }
6936
6937 new = prepare_creds();
6938 if (!new)
6939 return -ENOMEM;
6940
6941 /* Permission checking based on the specified context is
6942 performed during the actual operation (execve,
6943 open/mkdir/...), when we know the full context of the
6944 operation. See selinux_bprm_creds_for_exec for the execve
6945 checks and may_create for the file creation checks. The
6946 operation will then fail if the context is not permitted. */
6947 crsec = selinux_cred(new);
6948 if (attr == LSM_ATTR_EXEC) {
6949 crsec->exec_sid = sid;
6950 } else if (attr == LSM_ATTR_FSCREATE) {
6951 crsec->create_sid = sid;
6952 } else if (attr == LSM_ATTR_KEYCREATE) {
6953 if (sid) {
6954 error = avc_has_perm(mysid, sid,
6955 SECCLASS_KEY, KEY__CREATE, NULL);
6956 if (error)
6957 goto abort_change;
6958 }
6959 crsec->keycreate_sid = sid;
6960 } else if (attr == LSM_ATTR_SOCKCREATE) {
6961 crsec->sockcreate_sid = sid;
6962 } else if (attr == LSM_ATTR_CURRENT) {
6963 error = -EINVAL;
6964 if (sid == 0)
6965 goto abort_change;
6966
6967 if (!current_is_single_threaded()) {
6968 error = security_bounded_transition(crsec->sid, sid);
6969 if (error)
6970 goto abort_change;
6971 }
6972
6973 /* Check permissions for the transition. */
6974 error = avc_has_perm(crsec->sid, sid, SECCLASS_PROCESS,
6975 PROCESS__DYNTRANSITION, NULL);
6976 if (error)
6977 goto abort_change;
6978
6979 /* Check for ptracing, and update the task SID if ok.
6980 Otherwise, leave SID unchanged and fail. */
6981 ptsid = ptrace_parent_sid();
6982 if (ptsid != 0) {
6983 error = avc_has_perm(ptsid, sid, SECCLASS_PROCESS,
6984 PROCESS__PTRACE, NULL);
6985 if (error)
6986 goto abort_change;
6987 }
6988
6989 crsec->sid = sid;
6990 } else {
6991 error = -EINVAL;
6992 goto abort_change;
6993 }
6994
6995 commit_creds(new);
6996 return size;
6997
6998 abort_change:
6999 abort_creds(new);
7000 return error;
7001 }
7002
7003 /**
7004 * selinux_getselfattr - Get SELinux current task attributes
7005 * @attr: the requested attribute
7006 * @ctx: buffer to receive the result
7007 * @size: buffer size (input), buffer size used (output)
7008 * @flags: unused
7009 *
7010 * Fill the passed user space @ctx with the details of the requested
7011 * attribute.
7012 *
7013 * Returns the number of attributes on success, an error code otherwise.
7014 * There will only ever be one attribute.
7015 */
selinux_getselfattr(unsigned int attr,struct lsm_ctx __user * ctx,u32 * size,u32 flags)7016 static int selinux_getselfattr(unsigned int attr, struct lsm_ctx __user *ctx,
7017 u32 *size, u32 flags)
7018 {
7019 int rc;
7020 char *val = NULL;
7021 int val_len;
7022
7023 val_len = selinux_lsm_getattr(attr, current, &val);
7024 if (val_len < 0)
7025 return val_len;
7026 rc = lsm_fill_user_ctx(ctx, size, val, val_len, LSM_ID_SELINUX, 0);
7027 kfree(val);
7028 return (!rc ? 1 : rc);
7029 }
7030
selinux_setselfattr(unsigned int attr,struct lsm_ctx * ctx,u32 size,u32 flags)7031 static int selinux_setselfattr(unsigned int attr, struct lsm_ctx *ctx,
7032 u32 size, u32 flags)
7033 {
7034 int rc;
7035
7036 rc = selinux_lsm_setattr(attr, ctx->ctx, ctx->ctx_len);
7037 if (rc > 0)
7038 return 0;
7039 return rc;
7040 }
7041
selinux_getprocattr(struct task_struct * p,const char * name,char ** value)7042 static int selinux_getprocattr(struct task_struct *p,
7043 const char *name, char **value)
7044 {
7045 unsigned int attr = lsm_name_to_attr(name);
7046 int rc;
7047
7048 if (attr) {
7049 rc = selinux_lsm_getattr(attr, p, value);
7050 if (rc != -EOPNOTSUPP)
7051 return rc;
7052 }
7053
7054 return -EINVAL;
7055 }
7056
selinux_setprocattr(const char * name,void * value,size_t size)7057 static int selinux_setprocattr(const char *name, void *value, size_t size)
7058 {
7059 int attr = lsm_name_to_attr(name);
7060
7061 if (attr)
7062 return selinux_lsm_setattr(attr, value, size);
7063 return -EINVAL;
7064 }
7065
selinux_ismaclabel(const char * name)7066 static int selinux_ismaclabel(const char *name)
7067 {
7068 return (strcmp(name, XATTR_SELINUX_SUFFIX) == 0);
7069 }
7070
selinux_secid_to_secctx(u32 secid,struct lsm_context * cp)7071 static int selinux_secid_to_secctx(u32 secid, struct lsm_context *cp)
7072 {
7073 u32 seclen;
7074 int ret;
7075
7076 if (cp) {
7077 cp->id = LSM_ID_SELINUX;
7078 ret = security_sid_to_context(secid, &cp->context, &cp->len);
7079 if (ret < 0)
7080 return ret;
7081 return cp->len;
7082 }
7083 ret = security_sid_to_context(secid, NULL, &seclen);
7084 if (ret < 0)
7085 return ret;
7086 return seclen;
7087 }
7088
selinux_lsmprop_to_secctx(struct lsm_prop * prop,struct lsm_context * cp)7089 static int selinux_lsmprop_to_secctx(struct lsm_prop *prop,
7090 struct lsm_context *cp)
7091 {
7092 return selinux_secid_to_secctx(prop->selinux.secid, cp);
7093 }
7094
selinux_secctx_to_secid(const char * secdata,u32 seclen,u32 * secid)7095 static int selinux_secctx_to_secid(const char *secdata, u32 seclen, u32 *secid)
7096 {
7097 return security_context_to_sid(secdata, seclen,
7098 secid, GFP_KERNEL);
7099 }
7100
selinux_release_secctx(struct lsm_context * cp)7101 static void selinux_release_secctx(struct lsm_context *cp)
7102 {
7103 if (cp->id == LSM_ID_SELINUX) {
7104 kfree(cp->context);
7105 cp->context = NULL;
7106 cp->id = LSM_ID_UNDEF;
7107 }
7108 }
7109
selinux_inode_invalidate_secctx(struct inode * inode)7110 static void selinux_inode_invalidate_secctx(struct inode *inode)
7111 {
7112 struct inode_security_struct *isec = selinux_inode(inode);
7113
7114 spin_lock(&isec->lock);
7115 isec->initialized = LABEL_INVALID;
7116 spin_unlock(&isec->lock);
7117 }
7118
7119 /*
7120 * called with inode->i_mutex locked
7121 */
selinux_inode_notifysecctx(struct inode * inode,void * ctx,u32 ctxlen)7122 static int selinux_inode_notifysecctx(struct inode *inode, void *ctx, u32 ctxlen)
7123 {
7124 int rc = selinux_inode_setsecurity(inode, XATTR_SELINUX_SUFFIX,
7125 ctx, ctxlen, 0);
7126 /* Do not return error when suppressing label (SBLABEL_MNT not set). */
7127 return rc == -EOPNOTSUPP ? 0 : rc;
7128 }
7129
7130 /*
7131 * called with inode->i_mutex locked
7132 */
selinux_inode_setsecctx(struct dentry * dentry,void * ctx,u32 ctxlen)7133 static int selinux_inode_setsecctx(struct dentry *dentry, void *ctx, u32 ctxlen)
7134 {
7135 return __vfs_setxattr_locked(&nop_mnt_idmap, dentry, XATTR_NAME_SELINUX,
7136 ctx, ctxlen, 0, NULL);
7137 }
7138
selinux_inode_getsecctx(struct inode * inode,struct lsm_context * cp)7139 static int selinux_inode_getsecctx(struct inode *inode, struct lsm_context *cp)
7140 {
7141 int len;
7142 len = selinux_inode_getsecurity(&nop_mnt_idmap, inode,
7143 XATTR_SELINUX_SUFFIX,
7144 (void **)&cp->context, true);
7145 if (len < 0)
7146 return len;
7147 cp->len = len;
7148 cp->id = LSM_ID_SELINUX;
7149 return 0;
7150 }
7151 #ifdef CONFIG_KEYS
7152
selinux_key_alloc(struct key * k,const struct cred * cred,unsigned long flags)7153 static int selinux_key_alloc(struct key *k, const struct cred *cred,
7154 unsigned long flags)
7155 {
7156 const struct cred_security_struct *crsec;
7157 struct key_security_struct *ksec = selinux_key(k);
7158
7159 crsec = selinux_cred(cred);
7160 if (crsec->keycreate_sid)
7161 ksec->sid = crsec->keycreate_sid;
7162 else
7163 ksec->sid = crsec->sid;
7164
7165 return 0;
7166 }
7167
selinux_key_permission(key_ref_t key_ref,const struct cred * cred,enum key_need_perm need_perm)7168 static int selinux_key_permission(key_ref_t key_ref,
7169 const struct cred *cred,
7170 enum key_need_perm need_perm)
7171 {
7172 struct key *key;
7173 struct key_security_struct *ksec;
7174 u32 perm, sid;
7175
7176 switch (need_perm) {
7177 case KEY_NEED_VIEW:
7178 perm = KEY__VIEW;
7179 break;
7180 case KEY_NEED_READ:
7181 perm = KEY__READ;
7182 break;
7183 case KEY_NEED_WRITE:
7184 perm = KEY__WRITE;
7185 break;
7186 case KEY_NEED_SEARCH:
7187 perm = KEY__SEARCH;
7188 break;
7189 case KEY_NEED_LINK:
7190 perm = KEY__LINK;
7191 break;
7192 case KEY_NEED_SETATTR:
7193 perm = KEY__SETATTR;
7194 break;
7195 case KEY_NEED_UNLINK:
7196 case KEY_SYSADMIN_OVERRIDE:
7197 case KEY_AUTHTOKEN_OVERRIDE:
7198 case KEY_DEFER_PERM_CHECK:
7199 return 0;
7200 default:
7201 WARN_ON(1);
7202 return -EPERM;
7203
7204 }
7205
7206 sid = cred_sid(cred);
7207 key = key_ref_to_ptr(key_ref);
7208 ksec = selinux_key(key);
7209
7210 return avc_has_perm(sid, ksec->sid, SECCLASS_KEY, perm, NULL);
7211 }
7212
selinux_key_getsecurity(struct key * key,char ** _buffer)7213 static int selinux_key_getsecurity(struct key *key, char **_buffer)
7214 {
7215 struct key_security_struct *ksec = selinux_key(key);
7216 char *context = NULL;
7217 unsigned len;
7218 int rc;
7219
7220 rc = security_sid_to_context(ksec->sid,
7221 &context, &len);
7222 if (!rc)
7223 rc = len;
7224 *_buffer = context;
7225 return rc;
7226 }
7227
7228 #ifdef CONFIG_KEY_NOTIFICATIONS
selinux_watch_key(struct key * key)7229 static int selinux_watch_key(struct key *key)
7230 {
7231 struct key_security_struct *ksec = selinux_key(key);
7232 u32 sid = current_sid();
7233
7234 return avc_has_perm(sid, ksec->sid, SECCLASS_KEY, KEY__VIEW, NULL);
7235 }
7236 #endif
7237 #endif
7238
7239 #ifdef CONFIG_SECURITY_INFINIBAND
selinux_ib_pkey_access(void * ib_sec,u64 subnet_prefix,u16 pkey_val)7240 static int selinux_ib_pkey_access(void *ib_sec, u64 subnet_prefix, u16 pkey_val)
7241 {
7242 struct common_audit_data ad;
7243 int err;
7244 u32 sid = 0;
7245 struct ib_security_struct *sec = ib_sec;
7246 struct lsm_ibpkey_audit ibpkey;
7247
7248 err = sel_ib_pkey_sid(subnet_prefix, pkey_val, &sid);
7249 if (err)
7250 return err;
7251
7252 ad.type = LSM_AUDIT_DATA_IBPKEY;
7253 ibpkey.subnet_prefix = subnet_prefix;
7254 ibpkey.pkey = pkey_val;
7255 ad.u.ibpkey = &ibpkey;
7256 return avc_has_perm(sec->sid, sid,
7257 SECCLASS_INFINIBAND_PKEY,
7258 INFINIBAND_PKEY__ACCESS, &ad);
7259 }
7260
selinux_ib_endport_manage_subnet(void * ib_sec,const char * dev_name,u8 port_num)7261 static int selinux_ib_endport_manage_subnet(void *ib_sec, const char *dev_name,
7262 u8 port_num)
7263 {
7264 struct common_audit_data ad;
7265 int err;
7266 u32 sid = 0;
7267 struct ib_security_struct *sec = ib_sec;
7268 struct lsm_ibendport_audit ibendport;
7269
7270 err = security_ib_endport_sid(dev_name, port_num,
7271 &sid);
7272
7273 if (err)
7274 return err;
7275
7276 ad.type = LSM_AUDIT_DATA_IBENDPORT;
7277 ibendport.dev_name = dev_name;
7278 ibendport.port = port_num;
7279 ad.u.ibendport = &ibendport;
7280 return avc_has_perm(sec->sid, sid,
7281 SECCLASS_INFINIBAND_ENDPORT,
7282 INFINIBAND_ENDPORT__MANAGE_SUBNET, &ad);
7283 }
7284
selinux_ib_alloc_security(void * ib_sec)7285 static int selinux_ib_alloc_security(void *ib_sec)
7286 {
7287 struct ib_security_struct *sec = selinux_ib(ib_sec);
7288
7289 sec->sid = current_sid();
7290 return 0;
7291 }
7292 #endif
7293
7294 #ifdef CONFIG_BPF_SYSCALL
selinux_bpf(int cmd,union bpf_attr * attr,unsigned int size,bool kernel)7295 static int selinux_bpf(int cmd, union bpf_attr *attr,
7296 unsigned int size, bool kernel)
7297 {
7298 u32 sid = current_sid();
7299 int ret;
7300
7301 if (selinux_policycap_bpf_token_perms())
7302 return 0;
7303
7304 switch (cmd) {
7305 case BPF_MAP_CREATE:
7306 ret = avc_has_perm(sid, sid, SECCLASS_BPF, BPF__MAP_CREATE,
7307 NULL);
7308 break;
7309 case BPF_PROG_LOAD:
7310 ret = avc_has_perm(sid, sid, SECCLASS_BPF, BPF__PROG_LOAD,
7311 NULL);
7312 break;
7313 default:
7314 ret = 0;
7315 break;
7316 }
7317
7318 return ret;
7319 }
7320
bpf_map_fmode_to_av(fmode_t fmode)7321 static u32 bpf_map_fmode_to_av(fmode_t fmode)
7322 {
7323 u32 av = 0;
7324
7325 if (fmode & FMODE_READ)
7326 av |= BPF__MAP_READ;
7327 if (fmode & FMODE_WRITE)
7328 av |= BPF__MAP_WRITE;
7329 return av;
7330 }
7331
7332 /* This function will check the file pass through unix socket or binder to see
7333 * if it is a bpf related object. And apply corresponding checks on the bpf
7334 * object based on the type. The bpf maps and programs, not like other files and
7335 * socket, are using a shared anonymous inode inside the kernel as their inode.
7336 * So checking that inode cannot identify if the process have privilege to
7337 * access the bpf object and that's why we have to add this additional check in
7338 * selinux_file_receive and selinux_binder_transfer_files.
7339 */
bpf_fd_pass(const struct file * file,u32 sid)7340 static int bpf_fd_pass(const struct file *file, u32 sid)
7341 {
7342 struct bpf_security_struct *bpfsec;
7343 struct bpf_prog *prog;
7344 struct bpf_map *map;
7345 int ret;
7346
7347 if (file->f_op == &bpf_map_fops) {
7348 map = file->private_data;
7349 bpfsec = selinux_bpf_map_security(map);
7350 ret = avc_has_perm(sid, bpfsec->sid, SECCLASS_BPF,
7351 bpf_map_fmode_to_av(file->f_mode), NULL);
7352 if (ret)
7353 return ret;
7354 } else if (file->f_op == &bpf_prog_fops) {
7355 prog = file->private_data;
7356 bpfsec = selinux_bpf_prog_security(prog);
7357 ret = avc_has_perm(sid, bpfsec->sid, SECCLASS_BPF,
7358 BPF__PROG_RUN, NULL);
7359 if (ret)
7360 return ret;
7361 }
7362 return 0;
7363 }
7364
selinux_bpf_map(struct bpf_map * map,fmode_t fmode)7365 static int selinux_bpf_map(struct bpf_map *map, fmode_t fmode)
7366 {
7367 u32 sid = current_sid();
7368 struct bpf_security_struct *bpfsec;
7369
7370 bpfsec = selinux_bpf_map_security(map);
7371 return avc_has_perm(sid, bpfsec->sid, SECCLASS_BPF,
7372 bpf_map_fmode_to_av(fmode), NULL);
7373 }
7374
selinux_bpf_prog(struct bpf_prog * prog)7375 static int selinux_bpf_prog(struct bpf_prog *prog)
7376 {
7377 u32 sid = current_sid();
7378 struct bpf_security_struct *bpfsec;
7379
7380 bpfsec = selinux_bpf_prog_security(prog);
7381 return avc_has_perm(sid, bpfsec->sid, SECCLASS_BPF,
7382 BPF__PROG_RUN, NULL);
7383 }
7384
selinux_bpf_map_create(struct bpf_map * map,union bpf_attr * attr,struct bpf_token * token,bool kernel)7385 static int selinux_bpf_map_create(struct bpf_map *map, union bpf_attr *attr,
7386 struct bpf_token *token, bool kernel)
7387 {
7388 struct bpf_security_struct *bpfsec;
7389 u32 ssid;
7390
7391 bpfsec = selinux_bpf_map_security(map);
7392 bpfsec->sid = current_sid();
7393
7394 if (!token)
7395 ssid = bpfsec->sid;
7396 else
7397 ssid = selinux_bpf_token_security(token)->grantor_sid;
7398
7399 return avc_has_perm(ssid, bpfsec->sid, SECCLASS_BPF, BPF__MAP_CREATE,
7400 NULL);
7401 }
7402
selinux_bpf_prog_load(struct bpf_prog * prog,union bpf_attr * attr,struct bpf_token * token,bool kernel)7403 static int selinux_bpf_prog_load(struct bpf_prog *prog, union bpf_attr *attr,
7404 struct bpf_token *token, bool kernel)
7405 {
7406 struct bpf_security_struct *bpfsec;
7407 u32 ssid;
7408
7409 bpfsec = selinux_bpf_prog_security(prog);
7410 bpfsec->sid = current_sid();
7411
7412 if (!token)
7413 ssid = bpfsec->sid;
7414 else
7415 ssid = selinux_bpf_token_security(token)->grantor_sid;
7416
7417 return avc_has_perm(ssid, bpfsec->sid, SECCLASS_BPF, BPF__PROG_LOAD,
7418 NULL);
7419 }
7420
7421 #define bpf_token_cmd(T, C) \
7422 ((T)->allowed_cmds & (1ULL << (C)))
7423
selinux_bpf_token_create(struct bpf_token * token,union bpf_attr * attr,const struct path * path)7424 static int selinux_bpf_token_create(struct bpf_token *token,
7425 union bpf_attr *attr,
7426 const struct path *path)
7427 {
7428 struct bpf_security_struct *bpfsec;
7429 struct superblock_security_struct *sbsec;
7430 int err;
7431
7432 sbsec = selinux_superblock(path->dentry->d_sb);
7433
7434 bpfsec = selinux_bpf_token_security(token);
7435 bpfsec->sid = current_sid();
7436 bpfsec->grantor_sid = sbsec->creator_sid;
7437
7438 bpfsec->perms = 0;
7439 /**
7440 * 'token->allowed_cmds' is a bit mask of allowed commands
7441 * Convert the BPF command enum to a bitmask representing its position
7442 * in the allowed_cmds bitmap.
7443 */
7444 if (bpf_token_cmd(token, BPF_MAP_CREATE)) {
7445 err = avc_has_perm(bpfsec->sid, bpfsec->grantor_sid,
7446 SECCLASS_BPF, BPF__MAP_CREATE_AS, NULL);
7447 if (err)
7448 return err;
7449 bpfsec->perms |= BPF__MAP_CREATE;
7450 }
7451 if (bpf_token_cmd(token, BPF_PROG_LOAD)) {
7452 err = avc_has_perm(bpfsec->sid, bpfsec->grantor_sid,
7453 SECCLASS_BPF, BPF__PROG_LOAD_AS, NULL);
7454 if (err)
7455 return err;
7456 bpfsec->perms |= BPF__PROG_LOAD;
7457 }
7458
7459 return 0;
7460 }
7461
selinux_bpf_token_cmd(const struct bpf_token * token,enum bpf_cmd cmd)7462 static int selinux_bpf_token_cmd(const struct bpf_token *token,
7463 enum bpf_cmd cmd)
7464 {
7465 struct bpf_security_struct *bpfsec;
7466
7467 bpfsec = token->security;
7468 switch (cmd) {
7469 case BPF_MAP_CREATE:
7470 if (!(bpfsec->perms & BPF__MAP_CREATE))
7471 return -EACCES;
7472 break;
7473 case BPF_PROG_LOAD:
7474 if (!(bpfsec->perms & BPF__PROG_LOAD))
7475 return -EACCES;
7476 break;
7477 default:
7478 break;
7479 }
7480
7481 return 0;
7482 }
7483
selinux_bpf_token_capable(const struct bpf_token * token,int cap)7484 static int selinux_bpf_token_capable(const struct bpf_token *token, int cap)
7485 {
7486 u16 sclass;
7487 struct bpf_security_struct *bpfsec = token->security;
7488 bool initns = (token->userns == &init_user_ns);
7489 u32 av = CAP_TO_MASK(cap);
7490
7491 switch (CAP_TO_INDEX(cap)) {
7492 case 0:
7493 sclass = initns ? SECCLASS_CAPABILITY : SECCLASS_CAP_USERNS;
7494 break;
7495 case 1:
7496 sclass = initns ? SECCLASS_CAPABILITY2 : SECCLASS_CAP2_USERNS;
7497 break;
7498 default:
7499 pr_err("SELinux: out of range capability %d\n", cap);
7500 return -EINVAL;
7501 }
7502
7503 return avc_has_perm(current_sid(), bpfsec->grantor_sid, sclass, av,
7504 NULL);
7505 }
7506 #endif
7507
7508 #ifdef CONFIG_PERF_EVENTS
selinux_perf_event_open(int type)7509 static int selinux_perf_event_open(int type)
7510 {
7511 u32 requested, sid = current_sid();
7512
7513 if (type == PERF_SECURITY_OPEN)
7514 requested = PERF_EVENT__OPEN;
7515 else if (type == PERF_SECURITY_CPU)
7516 requested = PERF_EVENT__CPU;
7517 else if (type == PERF_SECURITY_KERNEL)
7518 requested = PERF_EVENT__KERNEL;
7519 else if (type == PERF_SECURITY_TRACEPOINT)
7520 requested = PERF_EVENT__TRACEPOINT;
7521 else
7522 return -EINVAL;
7523
7524 return avc_has_perm(sid, sid, SECCLASS_PERF_EVENT,
7525 requested, NULL);
7526 }
7527
selinux_perf_event_alloc(struct perf_event * event)7528 static int selinux_perf_event_alloc(struct perf_event *event)
7529 {
7530 struct perf_event_security_struct *perfsec;
7531
7532 perfsec = selinux_perf_event(event->security);
7533 perfsec->sid = current_sid();
7534
7535 return 0;
7536 }
7537
selinux_perf_event_read(struct perf_event * event)7538 static int selinux_perf_event_read(struct perf_event *event)
7539 {
7540 struct perf_event_security_struct *perfsec = event->security;
7541 u32 sid = current_sid();
7542
7543 return avc_has_perm(sid, perfsec->sid,
7544 SECCLASS_PERF_EVENT, PERF_EVENT__READ, NULL);
7545 }
7546
selinux_perf_event_write(struct perf_event * event)7547 static int selinux_perf_event_write(struct perf_event *event)
7548 {
7549 struct perf_event_security_struct *perfsec = event->security;
7550 u32 sid = current_sid();
7551
7552 return avc_has_perm(sid, perfsec->sid,
7553 SECCLASS_PERF_EVENT, PERF_EVENT__WRITE, NULL);
7554 }
7555 #endif
7556
7557 #ifdef CONFIG_IO_URING
7558 /**
7559 * selinux_uring_override_creds - check the requested cred override
7560 * @new: the target creds
7561 *
7562 * Check to see if the current task is allowed to override it's credentials
7563 * to service an io_uring operation.
7564 */
selinux_uring_override_creds(const struct cred * new)7565 static int selinux_uring_override_creds(const struct cred *new)
7566 {
7567 return avc_has_perm(current_sid(), cred_sid(new),
7568 SECCLASS_IO_URING, IO_URING__OVERRIDE_CREDS, NULL);
7569 }
7570
7571 /**
7572 * selinux_uring_sqpoll - check if a io_uring polling thread can be created
7573 *
7574 * Check to see if the current task is allowed to create a new io_uring
7575 * kernel polling thread.
7576 */
selinux_uring_sqpoll(void)7577 static int selinux_uring_sqpoll(void)
7578 {
7579 u32 sid = current_sid();
7580
7581 return avc_has_perm(sid, sid,
7582 SECCLASS_IO_URING, IO_URING__SQPOLL, NULL);
7583 }
7584
7585 /**
7586 * selinux_uring_cmd - check if IORING_OP_URING_CMD is allowed
7587 * @ioucmd: the io_uring command structure
7588 *
7589 * Check to see if the current domain is allowed to execute an
7590 * IORING_OP_URING_CMD against the device/file specified in @ioucmd.
7591 *
7592 */
selinux_uring_cmd(struct io_uring_cmd * ioucmd)7593 static int selinux_uring_cmd(struct io_uring_cmd *ioucmd)
7594 {
7595 struct file *file = ioucmd->file;
7596 struct inode *inode = file_inode(file);
7597 struct inode_security_struct *isec = selinux_inode(inode);
7598 struct common_audit_data ad;
7599
7600 ad.type = LSM_AUDIT_DATA_FILE;
7601 ad.u.file = file;
7602
7603 return avc_has_perm(current_sid(), isec->sid,
7604 SECCLASS_IO_URING, IO_URING__CMD, &ad);
7605 }
7606
7607 /**
7608 * selinux_uring_allowed - check if io_uring_setup() can be called
7609 *
7610 * Check to see if the current task is allowed to call io_uring_setup().
7611 */
selinux_uring_allowed(void)7612 static int selinux_uring_allowed(void)
7613 {
7614 u32 sid = current_sid();
7615
7616 return avc_has_perm(sid, sid, SECCLASS_IO_URING, IO_URING__ALLOWED,
7617 NULL);
7618 }
7619 #endif /* CONFIG_IO_URING */
7620
7621 static const struct lsm_id selinux_lsmid = {
7622 .name = "selinux",
7623 .id = LSM_ID_SELINUX,
7624 };
7625
7626 struct lsm_blob_sizes selinux_blob_sizes __ro_after_init = {
7627 .lbs_cred = sizeof(struct cred_security_struct),
7628 .lbs_task = sizeof(struct task_security_struct),
7629 .lbs_file = sizeof(struct file_security_struct),
7630 .lbs_backing_file = sizeof(struct backing_file_security_struct),
7631 .lbs_inode = sizeof(struct inode_security_struct),
7632 .lbs_ipc = sizeof(struct ipc_security_struct),
7633 .lbs_key = sizeof(struct key_security_struct),
7634 .lbs_msg_msg = sizeof(struct msg_security_struct),
7635 #ifdef CONFIG_PERF_EVENTS
7636 .lbs_perf_event = sizeof(struct perf_event_security_struct),
7637 #endif
7638 .lbs_sock = sizeof(struct sk_security_struct),
7639 .lbs_superblock = sizeof(struct superblock_security_struct),
7640 .lbs_xattr_count = SELINUX_INODE_INIT_XATTRS,
7641 .lbs_tun_dev = sizeof(struct tun_security_struct),
7642 .lbs_ib = sizeof(struct ib_security_struct),
7643 .lbs_bpf_map = sizeof(struct bpf_security_struct),
7644 .lbs_bpf_prog = sizeof(struct bpf_security_struct),
7645 .lbs_bpf_token = sizeof(struct bpf_security_struct),
7646 };
7647
7648 /*
7649 * IMPORTANT NOTE: When adding new hooks, please be careful to keep this order:
7650 * 1. any hooks that don't belong to (2.) or (3.) below,
7651 * 2. hooks that both access structures allocated by other hooks, and allocate
7652 * structures that can be later accessed by other hooks (mostly "cloning"
7653 * hooks),
7654 * 3. hooks that only allocate structures that can be later accessed by other
7655 * hooks ("allocating" hooks).
7656 *
7657 * Please follow block comment delimiters in the list to keep this order.
7658 */
7659 static struct security_hook_list selinux_hooks[] __ro_after_init = {
7660 LSM_HOOK_INIT(binder_set_context_mgr, selinux_binder_set_context_mgr),
7661 LSM_HOOK_INIT(binder_transaction, selinux_binder_transaction),
7662 LSM_HOOK_INIT(binder_transfer_binder, selinux_binder_transfer_binder),
7663 LSM_HOOK_INIT(binder_transfer_file, selinux_binder_transfer_file),
7664
7665 LSM_HOOK_INIT(ptrace_access_check, selinux_ptrace_access_check),
7666 LSM_HOOK_INIT(ptrace_traceme, selinux_ptrace_traceme),
7667 LSM_HOOK_INIT(capget, selinux_capget),
7668 LSM_HOOK_INIT(capset, selinux_capset),
7669 LSM_HOOK_INIT(capable, selinux_capable),
7670 LSM_HOOK_INIT(quotactl, selinux_quotactl),
7671 LSM_HOOK_INIT(quota_on, selinux_quota_on),
7672 LSM_HOOK_INIT(syslog, selinux_syslog),
7673 LSM_HOOK_INIT(vm_enough_memory, selinux_vm_enough_memory),
7674
7675 LSM_HOOK_INIT(netlink_send, selinux_netlink_send),
7676
7677 LSM_HOOK_INIT(bprm_creds_for_exec, selinux_bprm_creds_for_exec),
7678 LSM_HOOK_INIT(bprm_committing_creds, selinux_bprm_committing_creds),
7679 LSM_HOOK_INIT(bprm_committed_creds, selinux_bprm_committed_creds),
7680
7681 LSM_HOOK_INIT(sb_free_mnt_opts, selinux_free_mnt_opts),
7682 LSM_HOOK_INIT(sb_mnt_opts_compat, selinux_sb_mnt_opts_compat),
7683 LSM_HOOK_INIT(sb_remount, selinux_sb_remount),
7684 LSM_HOOK_INIT(sb_kern_mount, selinux_sb_kern_mount),
7685 LSM_HOOK_INIT(sb_show_options, selinux_sb_show_options),
7686 LSM_HOOK_INIT(sb_statfs, selinux_sb_statfs),
7687 LSM_HOOK_INIT(sb_mount, selinux_mount),
7688 LSM_HOOK_INIT(sb_umount, selinux_umount),
7689 LSM_HOOK_INIT(sb_set_mnt_opts, selinux_set_mnt_opts),
7690 LSM_HOOK_INIT(sb_clone_mnt_opts, selinux_sb_clone_mnt_opts),
7691
7692 LSM_HOOK_INIT(move_mount, selinux_move_mount),
7693
7694 LSM_HOOK_INIT(dentry_init_security, selinux_dentry_init_security),
7695 LSM_HOOK_INIT(dentry_create_files_as, selinux_dentry_create_files_as),
7696
7697 LSM_HOOK_INIT(inode_free_security, selinux_inode_free_security),
7698 LSM_HOOK_INIT(inode_init_security, selinux_inode_init_security),
7699 LSM_HOOK_INIT(inode_init_security_anon, selinux_inode_init_security_anon),
7700 LSM_HOOK_INIT(inode_create, selinux_inode_create),
7701 LSM_HOOK_INIT(inode_link, selinux_inode_link),
7702 LSM_HOOK_INIT(inode_unlink, selinux_inode_unlink),
7703 LSM_HOOK_INIT(inode_symlink, selinux_inode_symlink),
7704 LSM_HOOK_INIT(inode_mkdir, selinux_inode_mkdir),
7705 LSM_HOOK_INIT(inode_rmdir, selinux_inode_rmdir),
7706 LSM_HOOK_INIT(inode_mknod, selinux_inode_mknod),
7707 LSM_HOOK_INIT(inode_rename, selinux_inode_rename),
7708 LSM_HOOK_INIT(inode_readlink, selinux_inode_readlink),
7709 LSM_HOOK_INIT(inode_follow_link, selinux_inode_follow_link),
7710 LSM_HOOK_INIT(inode_permission, selinux_inode_permission),
7711 LSM_HOOK_INIT(inode_setattr, selinux_inode_setattr),
7712 LSM_HOOK_INIT(inode_getattr, selinux_inode_getattr),
7713 LSM_HOOK_INIT(inode_xattr_skipcap, selinux_inode_xattr_skipcap),
7714 LSM_HOOK_INIT(inode_setxattr, selinux_inode_setxattr),
7715 LSM_HOOK_INIT(inode_post_setxattr, selinux_inode_post_setxattr),
7716 LSM_HOOK_INIT(inode_getxattr, selinux_inode_getxattr),
7717 LSM_HOOK_INIT(inode_listxattr, selinux_inode_listxattr),
7718 LSM_HOOK_INIT(inode_removexattr, selinux_inode_removexattr),
7719 LSM_HOOK_INIT(inode_file_getattr, selinux_inode_file_getattr),
7720 LSM_HOOK_INIT(inode_file_setattr, selinux_inode_file_setattr),
7721 LSM_HOOK_INIT(inode_set_acl, selinux_inode_set_acl),
7722 LSM_HOOK_INIT(inode_get_acl, selinux_inode_get_acl),
7723 LSM_HOOK_INIT(inode_remove_acl, selinux_inode_remove_acl),
7724 LSM_HOOK_INIT(inode_getsecurity, selinux_inode_getsecurity),
7725 LSM_HOOK_INIT(inode_setsecurity, selinux_inode_setsecurity),
7726 LSM_HOOK_INIT(inode_listsecurity, selinux_inode_listsecurity),
7727 LSM_HOOK_INIT(inode_getlsmprop, selinux_inode_getlsmprop),
7728 LSM_HOOK_INIT(inode_copy_up, selinux_inode_copy_up),
7729 LSM_HOOK_INIT(inode_copy_up_xattr, selinux_inode_copy_up_xattr),
7730 LSM_HOOK_INIT(path_notify, selinux_path_notify),
7731
7732 LSM_HOOK_INIT(kernfs_init_security, selinux_kernfs_init_security),
7733
7734 LSM_HOOK_INIT(file_permission, selinux_file_permission),
7735 LSM_HOOK_INIT(file_alloc_security, selinux_file_alloc_security),
7736 LSM_HOOK_INIT(backing_file_alloc, selinux_backing_file_alloc),
7737 LSM_HOOK_INIT(backing_file_free, selinux_backing_file_free),
7738 LSM_HOOK_INIT(file_ioctl, selinux_file_ioctl),
7739 LSM_HOOK_INIT(file_ioctl_compat, selinux_file_ioctl_compat),
7740 LSM_HOOK_INIT(mmap_file, selinux_mmap_file),
7741 LSM_HOOK_INIT(mmap_backing_file, selinux_mmap_backing_file),
7742 LSM_HOOK_INIT(mmap_addr, selinux_mmap_addr),
7743 LSM_HOOK_INIT(file_mprotect, selinux_file_mprotect),
7744 LSM_HOOK_INIT(file_lock, selinux_file_lock),
7745 LSM_HOOK_INIT(file_fcntl, selinux_file_fcntl),
7746 LSM_HOOK_INIT(file_set_fowner, selinux_file_set_fowner),
7747 LSM_HOOK_INIT(file_send_sigiotask, selinux_file_send_sigiotask),
7748 LSM_HOOK_INIT(file_receive, selinux_file_receive),
7749
7750 LSM_HOOK_INIT(file_open, selinux_file_open),
7751
7752 LSM_HOOK_INIT(task_alloc, selinux_task_alloc),
7753 LSM_HOOK_INIT(cred_prepare, selinux_cred_prepare),
7754 LSM_HOOK_INIT(cred_transfer, selinux_cred_transfer),
7755 LSM_HOOK_INIT(cred_getsecid, selinux_cred_getsecid),
7756 LSM_HOOK_INIT(cred_getlsmprop, selinux_cred_getlsmprop),
7757 LSM_HOOK_INIT(kernel_act_as, selinux_kernel_act_as),
7758 LSM_HOOK_INIT(kernel_create_files_as, selinux_kernel_create_files_as),
7759 LSM_HOOK_INIT(kernel_module_request, selinux_kernel_module_request),
7760 LSM_HOOK_INIT(kernel_load_data, selinux_kernel_load_data),
7761 LSM_HOOK_INIT(kernel_read_file, selinux_kernel_read_file),
7762 LSM_HOOK_INIT(task_setpgid, selinux_task_setpgid),
7763 LSM_HOOK_INIT(task_getpgid, selinux_task_getpgid),
7764 LSM_HOOK_INIT(task_getsid, selinux_task_getsid),
7765 LSM_HOOK_INIT(current_getlsmprop_subj, selinux_current_getlsmprop_subj),
7766 LSM_HOOK_INIT(task_getlsmprop_obj, selinux_task_getlsmprop_obj),
7767 LSM_HOOK_INIT(task_setnice, selinux_task_setnice),
7768 LSM_HOOK_INIT(task_setioprio, selinux_task_setioprio),
7769 LSM_HOOK_INIT(task_getioprio, selinux_task_getioprio),
7770 LSM_HOOK_INIT(task_prlimit, selinux_task_prlimit),
7771 LSM_HOOK_INIT(task_setrlimit, selinux_task_setrlimit),
7772 LSM_HOOK_INIT(task_setscheduler, selinux_task_setscheduler),
7773 LSM_HOOK_INIT(task_getscheduler, selinux_task_getscheduler),
7774 LSM_HOOK_INIT(task_movememory, selinux_task_movememory),
7775 LSM_HOOK_INIT(task_kill, selinux_task_kill),
7776 LSM_HOOK_INIT(task_to_inode, selinux_task_to_inode),
7777 LSM_HOOK_INIT(userns_create, selinux_userns_create),
7778
7779 LSM_HOOK_INIT(ipc_permission, selinux_ipc_permission),
7780 LSM_HOOK_INIT(ipc_getlsmprop, selinux_ipc_getlsmprop),
7781
7782 LSM_HOOK_INIT(msg_queue_associate, selinux_msg_queue_associate),
7783 LSM_HOOK_INIT(msg_queue_msgctl, selinux_msg_queue_msgctl),
7784 LSM_HOOK_INIT(msg_queue_msgsnd, selinux_msg_queue_msgsnd),
7785 LSM_HOOK_INIT(msg_queue_msgrcv, selinux_msg_queue_msgrcv),
7786
7787 LSM_HOOK_INIT(shm_associate, selinux_shm_associate),
7788 LSM_HOOK_INIT(shm_shmctl, selinux_shm_shmctl),
7789 LSM_HOOK_INIT(shm_shmat, selinux_shm_shmat),
7790
7791 LSM_HOOK_INIT(sem_associate, selinux_sem_associate),
7792 LSM_HOOK_INIT(sem_semctl, selinux_sem_semctl),
7793 LSM_HOOK_INIT(sem_semop, selinux_sem_semop),
7794
7795 LSM_HOOK_INIT(d_instantiate, selinux_d_instantiate),
7796
7797 LSM_HOOK_INIT(getselfattr, selinux_getselfattr),
7798 LSM_HOOK_INIT(setselfattr, selinux_setselfattr),
7799 LSM_HOOK_INIT(getprocattr, selinux_getprocattr),
7800 LSM_HOOK_INIT(setprocattr, selinux_setprocattr),
7801
7802 LSM_HOOK_INIT(ismaclabel, selinux_ismaclabel),
7803 LSM_HOOK_INIT(secctx_to_secid, selinux_secctx_to_secid),
7804 LSM_HOOK_INIT(release_secctx, selinux_release_secctx),
7805 LSM_HOOK_INIT(inode_invalidate_secctx, selinux_inode_invalidate_secctx),
7806 LSM_HOOK_INIT(inode_notifysecctx, selinux_inode_notifysecctx),
7807 LSM_HOOK_INIT(inode_setsecctx, selinux_inode_setsecctx),
7808
7809 LSM_HOOK_INIT(unix_stream_connect, selinux_socket_unix_stream_connect),
7810 LSM_HOOK_INIT(unix_may_send, selinux_socket_unix_may_send),
7811
7812 LSM_HOOK_INIT(socket_create, selinux_socket_create),
7813 LSM_HOOK_INIT(socket_post_create, selinux_socket_post_create),
7814 LSM_HOOK_INIT(socket_socketpair, selinux_socket_socketpair),
7815 LSM_HOOK_INIT(socket_bind, selinux_socket_bind),
7816 LSM_HOOK_INIT(socket_connect, selinux_socket_connect),
7817 LSM_HOOK_INIT(socket_listen, selinux_socket_listen),
7818 LSM_HOOK_INIT(socket_accept, selinux_socket_accept),
7819 LSM_HOOK_INIT(socket_sendmsg, selinux_socket_sendmsg),
7820 LSM_HOOK_INIT(socket_recvmsg, selinux_socket_recvmsg),
7821 LSM_HOOK_INIT(socket_getsockname, selinux_socket_getsockname),
7822 LSM_HOOK_INIT(socket_getpeername, selinux_socket_getpeername),
7823 LSM_HOOK_INIT(socket_getsockopt, selinux_socket_getsockopt),
7824 LSM_HOOK_INIT(socket_setsockopt, selinux_socket_setsockopt),
7825 LSM_HOOK_INIT(socket_shutdown, selinux_socket_shutdown),
7826 LSM_HOOK_INIT(socket_sock_rcv_skb, selinux_socket_sock_rcv_skb),
7827 LSM_HOOK_INIT(socket_getpeersec_stream,
7828 selinux_socket_getpeersec_stream),
7829 LSM_HOOK_INIT(socket_getpeersec_dgram, selinux_socket_getpeersec_dgram),
7830 LSM_HOOK_INIT(sk_free_security, selinux_sk_free_security),
7831 LSM_HOOK_INIT(sk_clone_security, selinux_sk_clone_security),
7832 LSM_HOOK_INIT(sk_getsecid, selinux_sk_getsecid),
7833 LSM_HOOK_INIT(sock_graft, selinux_sock_graft),
7834 LSM_HOOK_INIT(sctp_assoc_request, selinux_sctp_assoc_request),
7835 LSM_HOOK_INIT(sctp_sk_clone, selinux_sctp_sk_clone),
7836 LSM_HOOK_INIT(sctp_bind_connect, selinux_sctp_bind_connect),
7837 LSM_HOOK_INIT(sctp_assoc_established, selinux_sctp_assoc_established),
7838 LSM_HOOK_INIT(mptcp_add_subflow, selinux_mptcp_add_subflow),
7839 LSM_HOOK_INIT(inet_conn_request, selinux_inet_conn_request),
7840 LSM_HOOK_INIT(inet_csk_clone, selinux_inet_csk_clone),
7841 LSM_HOOK_INIT(inet_conn_established, selinux_inet_conn_established),
7842 LSM_HOOK_INIT(secmark_relabel_packet, selinux_secmark_relabel_packet),
7843 LSM_HOOK_INIT(secmark_refcount_inc, selinux_secmark_refcount_inc),
7844 LSM_HOOK_INIT(secmark_refcount_dec, selinux_secmark_refcount_dec),
7845 LSM_HOOK_INIT(req_classify_flow, selinux_req_classify_flow),
7846 LSM_HOOK_INIT(tun_dev_create, selinux_tun_dev_create),
7847 LSM_HOOK_INIT(tun_dev_attach_queue, selinux_tun_dev_attach_queue),
7848 LSM_HOOK_INIT(tun_dev_attach, selinux_tun_dev_attach),
7849 LSM_HOOK_INIT(tun_dev_open, selinux_tun_dev_open),
7850 #ifdef CONFIG_SECURITY_INFINIBAND
7851 LSM_HOOK_INIT(ib_pkey_access, selinux_ib_pkey_access),
7852 LSM_HOOK_INIT(ib_endport_manage_subnet,
7853 selinux_ib_endport_manage_subnet),
7854 #endif
7855 #ifdef CONFIG_SECURITY_NETWORK_XFRM
7856 LSM_HOOK_INIT(xfrm_policy_free_security, selinux_xfrm_policy_free),
7857 LSM_HOOK_INIT(xfrm_policy_delete_security, selinux_xfrm_policy_delete),
7858 LSM_HOOK_INIT(xfrm_state_free_security, selinux_xfrm_state_free),
7859 LSM_HOOK_INIT(xfrm_state_delete_security, selinux_xfrm_state_delete),
7860 LSM_HOOK_INIT(xfrm_policy_lookup, selinux_xfrm_policy_lookup),
7861 LSM_HOOK_INIT(xfrm_state_pol_flow_match,
7862 selinux_xfrm_state_pol_flow_match),
7863 LSM_HOOK_INIT(xfrm_decode_session, selinux_xfrm_decode_session),
7864 #endif
7865
7866 #ifdef CONFIG_KEYS
7867 LSM_HOOK_INIT(key_permission, selinux_key_permission),
7868 LSM_HOOK_INIT(key_getsecurity, selinux_key_getsecurity),
7869 #ifdef CONFIG_KEY_NOTIFICATIONS
7870 LSM_HOOK_INIT(watch_key, selinux_watch_key),
7871 #endif
7872 #endif
7873
7874 #ifdef CONFIG_AUDIT
7875 LSM_HOOK_INIT(audit_rule_known, selinux_audit_rule_known),
7876 LSM_HOOK_INIT(audit_rule_match, selinux_audit_rule_match),
7877 LSM_HOOK_INIT(audit_rule_free, selinux_audit_rule_free),
7878 #endif
7879
7880 #ifdef CONFIG_BPF_SYSCALL
7881 LSM_HOOK_INIT(bpf, selinux_bpf),
7882 LSM_HOOK_INIT(bpf_map, selinux_bpf_map),
7883 LSM_HOOK_INIT(bpf_prog, selinux_bpf_prog),
7884 #endif
7885
7886 #ifdef CONFIG_PERF_EVENTS
7887 LSM_HOOK_INIT(perf_event_open, selinux_perf_event_open),
7888 LSM_HOOK_INIT(perf_event_read, selinux_perf_event_read),
7889 LSM_HOOK_INIT(perf_event_write, selinux_perf_event_write),
7890 #endif
7891
7892 #ifdef CONFIG_IO_URING
7893 LSM_HOOK_INIT(uring_override_creds, selinux_uring_override_creds),
7894 LSM_HOOK_INIT(uring_sqpoll, selinux_uring_sqpoll),
7895 LSM_HOOK_INIT(uring_cmd, selinux_uring_cmd),
7896 LSM_HOOK_INIT(uring_allowed, selinux_uring_allowed),
7897 #endif
7898
7899 /*
7900 * PUT "CLONING" (ACCESSING + ALLOCATING) HOOKS HERE
7901 */
7902 LSM_HOOK_INIT(fs_context_submount, selinux_fs_context_submount),
7903 LSM_HOOK_INIT(fs_context_dup, selinux_fs_context_dup),
7904 LSM_HOOK_INIT(fs_context_parse_param, selinux_fs_context_parse_param),
7905 LSM_HOOK_INIT(sb_eat_lsm_opts, selinux_sb_eat_lsm_opts),
7906 #ifdef CONFIG_SECURITY_NETWORK_XFRM
7907 LSM_HOOK_INIT(xfrm_policy_clone_security, selinux_xfrm_policy_clone),
7908 #endif
7909
7910 /*
7911 * PUT "ALLOCATING" HOOKS HERE
7912 */
7913 LSM_HOOK_INIT(msg_msg_alloc_security, selinux_msg_msg_alloc_security),
7914 LSM_HOOK_INIT(msg_queue_alloc_security,
7915 selinux_msg_queue_alloc_security),
7916 LSM_HOOK_INIT(shm_alloc_security, selinux_shm_alloc_security),
7917 LSM_HOOK_INIT(sb_alloc_security, selinux_sb_alloc_security),
7918 LSM_HOOK_INIT(inode_alloc_security, selinux_inode_alloc_security),
7919 LSM_HOOK_INIT(sem_alloc_security, selinux_sem_alloc_security),
7920 LSM_HOOK_INIT(secid_to_secctx, selinux_secid_to_secctx),
7921 LSM_HOOK_INIT(lsmprop_to_secctx, selinux_lsmprop_to_secctx),
7922 LSM_HOOK_INIT(inode_getsecctx, selinux_inode_getsecctx),
7923 LSM_HOOK_INIT(sk_alloc_security, selinux_sk_alloc_security),
7924 LSM_HOOK_INIT(tun_dev_alloc_security, selinux_tun_dev_alloc_security),
7925 #ifdef CONFIG_SECURITY_INFINIBAND
7926 LSM_HOOK_INIT(ib_alloc_security, selinux_ib_alloc_security),
7927 #endif
7928 #ifdef CONFIG_SECURITY_NETWORK_XFRM
7929 LSM_HOOK_INIT(xfrm_policy_alloc_security, selinux_xfrm_policy_alloc),
7930 LSM_HOOK_INIT(xfrm_state_alloc, selinux_xfrm_state_alloc),
7931 LSM_HOOK_INIT(xfrm_state_alloc_acquire,
7932 selinux_xfrm_state_alloc_acquire),
7933 #endif
7934 #ifdef CONFIG_KEYS
7935 LSM_HOOK_INIT(key_alloc, selinux_key_alloc),
7936 #endif
7937 #ifdef CONFIG_AUDIT
7938 LSM_HOOK_INIT(audit_rule_init, selinux_audit_rule_init),
7939 #endif
7940 #ifdef CONFIG_BPF_SYSCALL
7941 LSM_HOOK_INIT(bpf_map_create, selinux_bpf_map_create),
7942 LSM_HOOK_INIT(bpf_prog_load, selinux_bpf_prog_load),
7943 LSM_HOOK_INIT(bpf_token_create, selinux_bpf_token_create),
7944 LSM_HOOK_INIT(bpf_token_cmd, selinux_bpf_token_cmd),
7945 LSM_HOOK_INIT(bpf_token_capable, selinux_bpf_token_capable),
7946 #endif
7947 #ifdef CONFIG_PERF_EVENTS
7948 LSM_HOOK_INIT(perf_event_alloc, selinux_perf_event_alloc),
7949 #endif
7950 };
7951
selinux_init(void)7952 static __init int selinux_init(void)
7953 {
7954 vma_flags_t data_default_flags = VMA_DATA_DEFAULT_FLAGS;
7955
7956 pr_info("SELinux: Initializing.\n");
7957
7958 memset(&selinux_state, 0, sizeof(selinux_state));
7959 enforcing_set(selinux_enforcing_boot);
7960 selinux_avc_init();
7961 mutex_init(&selinux_state.status_lock);
7962 mutex_init(&selinux_state.policy_mutex);
7963
7964 /* Set the security state for the initial task. */
7965 cred_init_security();
7966
7967 /* Inform the audit system that secctx is used */
7968 audit_cfg_lsm(&selinux_lsmid,
7969 AUDIT_CFG_LSM_SECCTX_SUBJECT |
7970 AUDIT_CFG_LSM_SECCTX_OBJECT);
7971
7972 default_noexec = !vma_flags_test(&data_default_flags, VMA_EXEC_BIT);
7973 if (!default_noexec)
7974 pr_notice("SELinux: virtual memory is executable by default\n");
7975
7976 avc_init();
7977
7978 avtab_cache_init();
7979
7980 ebitmap_cache_init();
7981
7982 hashtab_cache_init();
7983
7984 selinux_ima_config_len_init();
7985
7986 security_add_hooks(selinux_hooks, ARRAY_SIZE(selinux_hooks),
7987 &selinux_lsmid);
7988
7989 if (avc_add_callback(selinux_netcache_avc_callback, AVC_CALLBACK_RESET))
7990 panic("SELinux: Unable to register AVC netcache callback\n");
7991
7992 if (avc_add_callback(selinux_lsm_notifier_avc_callback, AVC_CALLBACK_RESET))
7993 panic("SELinux: Unable to register AVC LSM notifier callback\n");
7994
7995 if (avc_add_callback(selinux_audit_rule_avc_callback,
7996 AVC_CALLBACK_RESET))
7997 panic("SELinux: Unable to register AVC audit callback\n");
7998
7999 if (selinux_enforcing_boot)
8000 pr_debug("SELinux: Starting in enforcing mode\n");
8001 else
8002 pr_debug("SELinux: Starting in permissive mode\n");
8003
8004 fs_validate_description("selinux", selinux_fs_parameters);
8005
8006 return 0;
8007 }
8008
delayed_superblock_init(struct super_block * sb,void * unused)8009 static void delayed_superblock_init(struct super_block *sb, void *unused)
8010 {
8011 selinux_set_mnt_opts(sb, NULL, 0, NULL);
8012 }
8013
selinux_complete_init(void)8014 void selinux_complete_init(void)
8015 {
8016 pr_debug("SELinux: Completing initialization.\n");
8017
8018 /* Set up any superblocks initialized prior to the policy load. */
8019 pr_debug("SELinux: Setting up existing superblocks.\n");
8020 iterate_supers(delayed_superblock_init, NULL);
8021 }
8022
8023 /* SELinux requires early initialization in order to label
8024 all processes and objects when they are created. */
8025 DEFINE_LSM(selinux) = {
8026 .id = &selinux_lsmid,
8027 .flags = LSM_FLAG_LEGACY_MAJOR | LSM_FLAG_EXCLUSIVE,
8028 .enabled = &selinux_enabled_boot,
8029 .blobs = &selinux_blob_sizes,
8030 .init = selinux_init,
8031 .initcall_device = selinux_initcall,
8032 };
8033
8034 #if defined(CONFIG_NETFILTER)
8035 static const struct nf_hook_ops selinux_nf_ops[] = {
8036 {
8037 .hook = selinux_ip_postroute,
8038 .pf = NFPROTO_IPV4,
8039 .hooknum = NF_INET_POST_ROUTING,
8040 .priority = NF_IP_PRI_SELINUX_LAST,
8041 },
8042 {
8043 .hook = selinux_ip_forward,
8044 .pf = NFPROTO_IPV4,
8045 .hooknum = NF_INET_FORWARD,
8046 .priority = NF_IP_PRI_SELINUX_FIRST,
8047 },
8048 {
8049 .hook = selinux_ip_output,
8050 .pf = NFPROTO_IPV4,
8051 .hooknum = NF_INET_LOCAL_OUT,
8052 .priority = NF_IP_PRI_SELINUX_FIRST,
8053 },
8054 #if IS_ENABLED(CONFIG_IPV6)
8055 {
8056 .hook = selinux_ip_postroute,
8057 .pf = NFPROTO_IPV6,
8058 .hooknum = NF_INET_POST_ROUTING,
8059 .priority = NF_IP6_PRI_SELINUX_LAST,
8060 },
8061 {
8062 .hook = selinux_ip_forward,
8063 .pf = NFPROTO_IPV6,
8064 .hooknum = NF_INET_FORWARD,
8065 .priority = NF_IP6_PRI_SELINUX_FIRST,
8066 },
8067 {
8068 .hook = selinux_ip_output,
8069 .pf = NFPROTO_IPV6,
8070 .hooknum = NF_INET_LOCAL_OUT,
8071 .priority = NF_IP6_PRI_SELINUX_FIRST,
8072 },
8073 #endif /* IPV6 */
8074 };
8075
selinux_nf_register(struct net * net)8076 static int __net_init selinux_nf_register(struct net *net)
8077 {
8078 return nf_register_net_hooks(net, selinux_nf_ops,
8079 ARRAY_SIZE(selinux_nf_ops));
8080 }
8081
selinux_nf_unregister(struct net * net)8082 static void __net_exit selinux_nf_unregister(struct net *net)
8083 {
8084 nf_unregister_net_hooks(net, selinux_nf_ops,
8085 ARRAY_SIZE(selinux_nf_ops));
8086 }
8087
8088 static struct pernet_operations selinux_net_ops = {
8089 .init = selinux_nf_register,
8090 .exit = selinux_nf_unregister,
8091 };
8092
selinux_nf_ip_init(void)8093 int __init selinux_nf_ip_init(void)
8094 {
8095 int err;
8096
8097 if (!selinux_enabled_boot)
8098 return 0;
8099
8100 pr_debug("SELinux: Registering netfilter hooks\n");
8101
8102 err = register_pernet_subsys(&selinux_net_ops);
8103 if (err)
8104 panic("SELinux: register_pernet_subsys: error %d\n", err);
8105
8106 return 0;
8107 }
8108 #endif /* CONFIG_NETFILTER */
8109