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