erofs: reduntant assignment in __erofs_get_meta_page()
[linux/fpc-iii.git] / security / selinux / hooks.c
blob74dd46de01b6a4a7dbde1b8d697b9888cbe85f21
1 // SPDX-License-Identifier: GPL-2.0-only
2 /*
3 * NSA Security-Enhanced Linux (SELinux) security module
5 * This file contains the SELinux hook function implementations.
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>
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
24 #include <linux/init.h>
25 #include <linux/kd.h>
26 #include <linux/kernel.h>
27 #include <linux/tracehook.h>
28 #include <linux/errno.h>
29 #include <linux/sched/signal.h>
30 #include <linux/sched/task.h>
31 #include <linux/lsm_hooks.h>
32 #include <linux/xattr.h>
33 #include <linux/capability.h>
34 #include <linux/unistd.h>
35 #include <linux/mm.h>
36 #include <linux/mman.h>
37 #include <linux/slab.h>
38 #include <linux/pagemap.h>
39 #include <linux/proc_fs.h>
40 #include <linux/swap.h>
41 #include <linux/spinlock.h>
42 #include <linux/syscalls.h>
43 #include <linux/dcache.h>
44 #include <linux/file.h>
45 #include <linux/fdtable.h>
46 #include <linux/namei.h>
47 #include <linux/mount.h>
48 #include <linux/fs_context.h>
49 #include <linux/fs_parser.h>
50 #include <linux/netfilter_ipv4.h>
51 #include <linux/netfilter_ipv6.h>
52 #include <linux/tty.h>
53 #include <net/icmp.h>
54 #include <net/ip.h> /* for local_port_range[] */
55 #include <net/tcp.h> /* struct or_callable used in sock_rcv_skb */
56 #include <net/inet_connection_sock.h>
57 #include <net/net_namespace.h>
58 #include <net/netlabel.h>
59 #include <linux/uaccess.h>
60 #include <asm/ioctls.h>
61 #include <linux/atomic.h>
62 #include <linux/bitops.h>
63 #include <linux/interrupt.h>
64 #include <linux/netdevice.h> /* for network interface checks */
65 #include <net/netlink.h>
66 #include <linux/tcp.h>
67 #include <linux/udp.h>
68 #include <linux/dccp.h>
69 #include <linux/sctp.h>
70 #include <net/sctp/structs.h>
71 #include <linux/quota.h>
72 #include <linux/un.h> /* for Unix socket types */
73 #include <net/af_unix.h> /* for Unix socket types */
74 #include <linux/parser.h>
75 #include <linux/nfs_mount.h>
76 #include <net/ipv6.h>
77 #include <linux/hugetlb.h>
78 #include <linux/personality.h>
79 #include <linux/audit.h>
80 #include <linux/string.h>
81 #include <linux/mutex.h>
82 #include <linux/posix-timers.h>
83 #include <linux/syslog.h>
84 #include <linux/user_namespace.h>
85 #include <linux/export.h>
86 #include <linux/msg.h>
87 #include <linux/shm.h>
88 #include <linux/bpf.h>
89 #include <linux/kernfs.h>
90 #include <linux/stringhash.h> /* for hashlen_string() */
91 #include <uapi/linux/mount.h>
93 #include "avc.h"
94 #include "objsec.h"
95 #include "netif.h"
96 #include "netnode.h"
97 #include "netport.h"
98 #include "ibpkey.h"
99 #include "xfrm.h"
100 #include "netlabel.h"
101 #include "audit.h"
102 #include "avc_ss.h"
104 struct selinux_state selinux_state;
106 /* SECMARK reference count */
107 static atomic_t selinux_secmark_refcount = ATOMIC_INIT(0);
109 #ifdef CONFIG_SECURITY_SELINUX_DEVELOP
110 static int selinux_enforcing_boot;
112 static int __init enforcing_setup(char *str)
114 unsigned long enforcing;
115 if (!kstrtoul(str, 0, &enforcing))
116 selinux_enforcing_boot = enforcing ? 1 : 0;
117 return 1;
119 __setup("enforcing=", enforcing_setup);
120 #else
121 #define selinux_enforcing_boot 1
122 #endif
124 int selinux_enabled __lsm_ro_after_init = 1;
125 #ifdef CONFIG_SECURITY_SELINUX_BOOTPARAM
126 static int __init selinux_enabled_setup(char *str)
128 unsigned long enabled;
129 if (!kstrtoul(str, 0, &enabled))
130 selinux_enabled = enabled ? 1 : 0;
131 return 1;
133 __setup("selinux=", selinux_enabled_setup);
134 #endif
136 static unsigned int selinux_checkreqprot_boot =
137 CONFIG_SECURITY_SELINUX_CHECKREQPROT_VALUE;
139 static int __init checkreqprot_setup(char *str)
141 unsigned long checkreqprot;
143 if (!kstrtoul(str, 0, &checkreqprot))
144 selinux_checkreqprot_boot = checkreqprot ? 1 : 0;
145 return 1;
147 __setup("checkreqprot=", checkreqprot_setup);
150 * selinux_secmark_enabled - Check to see if SECMARK is currently enabled
152 * Description:
153 * This function checks the SECMARK reference counter to see if any SECMARK
154 * targets are currently configured, if the reference counter is greater than
155 * zero SECMARK is considered to be enabled. Returns true (1) if SECMARK is
156 * enabled, false (0) if SECMARK is disabled. If the always_check_network
157 * policy capability is enabled, SECMARK is always considered enabled.
160 static int selinux_secmark_enabled(void)
162 return (selinux_policycap_alwaysnetwork() ||
163 atomic_read(&selinux_secmark_refcount));
167 * selinux_peerlbl_enabled - Check to see if peer labeling is currently enabled
169 * Description:
170 * This function checks if NetLabel or labeled IPSEC is enabled. Returns true
171 * (1) if any are enabled or false (0) if neither are enabled. If the
172 * always_check_network policy capability is enabled, peer labeling
173 * is always considered enabled.
176 static int selinux_peerlbl_enabled(void)
178 return (selinux_policycap_alwaysnetwork() ||
179 netlbl_enabled() || selinux_xfrm_enabled());
182 static int selinux_netcache_avc_callback(u32 event)
184 if (event == AVC_CALLBACK_RESET) {
185 sel_netif_flush();
186 sel_netnode_flush();
187 sel_netport_flush();
188 synchronize_net();
190 return 0;
193 static int selinux_lsm_notifier_avc_callback(u32 event)
195 if (event == AVC_CALLBACK_RESET) {
196 sel_ib_pkey_flush();
197 call_blocking_lsm_notifier(LSM_POLICY_CHANGE, NULL);
200 return 0;
204 * initialise the security for the init task
206 static void cred_init_security(void)
208 struct cred *cred = (struct cred *) current->real_cred;
209 struct task_security_struct *tsec;
211 tsec = selinux_cred(cred);
212 tsec->osid = tsec->sid = SECINITSID_KERNEL;
216 * get the security ID of a set of credentials
218 static inline u32 cred_sid(const struct cred *cred)
220 const struct task_security_struct *tsec;
222 tsec = selinux_cred(cred);
223 return tsec->sid;
227 * get the objective security ID of a task
229 static inline u32 task_sid(const struct task_struct *task)
231 u32 sid;
233 rcu_read_lock();
234 sid = cred_sid(__task_cred(task));
235 rcu_read_unlock();
236 return sid;
239 /* Allocate and free functions for each kind of security blob. */
241 static int inode_alloc_security(struct inode *inode)
243 struct inode_security_struct *isec = selinux_inode(inode);
244 u32 sid = current_sid();
246 spin_lock_init(&isec->lock);
247 INIT_LIST_HEAD(&isec->list);
248 isec->inode = inode;
249 isec->sid = SECINITSID_UNLABELED;
250 isec->sclass = SECCLASS_FILE;
251 isec->task_sid = sid;
252 isec->initialized = LABEL_INVALID;
254 return 0;
257 static int inode_doinit_with_dentry(struct inode *inode, struct dentry *opt_dentry);
260 * Try reloading inode security labels that have been marked as invalid. The
261 * @may_sleep parameter indicates when sleeping and thus reloading labels is
262 * allowed; when set to false, returns -ECHILD when the label is
263 * invalid. The @dentry parameter should be set to a dentry of the inode.
265 static int __inode_security_revalidate(struct inode *inode,
266 struct dentry *dentry,
267 bool may_sleep)
269 struct inode_security_struct *isec = selinux_inode(inode);
271 might_sleep_if(may_sleep);
273 if (selinux_state.initialized &&
274 isec->initialized != LABEL_INITIALIZED) {
275 if (!may_sleep)
276 return -ECHILD;
279 * Try reloading the inode security label. This will fail if
280 * @opt_dentry is NULL and no dentry for this inode can be
281 * found; in that case, continue using the old label.
283 inode_doinit_with_dentry(inode, dentry);
285 return 0;
288 static struct inode_security_struct *inode_security_novalidate(struct inode *inode)
290 return selinux_inode(inode);
293 static struct inode_security_struct *inode_security_rcu(struct inode *inode, bool rcu)
295 int error;
297 error = __inode_security_revalidate(inode, NULL, !rcu);
298 if (error)
299 return ERR_PTR(error);
300 return selinux_inode(inode);
304 * Get the security label of an inode.
306 static struct inode_security_struct *inode_security(struct inode *inode)
308 __inode_security_revalidate(inode, NULL, true);
309 return selinux_inode(inode);
312 static struct inode_security_struct *backing_inode_security_novalidate(struct dentry *dentry)
314 struct inode *inode = d_backing_inode(dentry);
316 return selinux_inode(inode);
320 * Get the security label of a dentry's backing inode.
322 static struct inode_security_struct *backing_inode_security(struct dentry *dentry)
324 struct inode *inode = d_backing_inode(dentry);
326 __inode_security_revalidate(inode, dentry, true);
327 return selinux_inode(inode);
330 static void inode_free_security(struct inode *inode)
332 struct inode_security_struct *isec = selinux_inode(inode);
333 struct superblock_security_struct *sbsec;
335 if (!isec)
336 return;
337 sbsec = inode->i_sb->s_security;
339 * As not all inode security structures are in a list, we check for
340 * empty list outside of the lock to make sure that we won't waste
341 * time taking a lock doing nothing.
343 * The list_del_init() function can be safely called more than once.
344 * It should not be possible for this function to be called with
345 * concurrent list_add(), but for better safety against future changes
346 * in the code, we use list_empty_careful() here.
348 if (!list_empty_careful(&isec->list)) {
349 spin_lock(&sbsec->isec_lock);
350 list_del_init(&isec->list);
351 spin_unlock(&sbsec->isec_lock);
355 static int file_alloc_security(struct file *file)
357 struct file_security_struct *fsec = selinux_file(file);
358 u32 sid = current_sid();
360 fsec->sid = sid;
361 fsec->fown_sid = sid;
363 return 0;
366 static int superblock_alloc_security(struct super_block *sb)
368 struct superblock_security_struct *sbsec;
370 sbsec = kzalloc(sizeof(struct superblock_security_struct), GFP_KERNEL);
371 if (!sbsec)
372 return -ENOMEM;
374 mutex_init(&sbsec->lock);
375 INIT_LIST_HEAD(&sbsec->isec_head);
376 spin_lock_init(&sbsec->isec_lock);
377 sbsec->sb = sb;
378 sbsec->sid = SECINITSID_UNLABELED;
379 sbsec->def_sid = SECINITSID_FILE;
380 sbsec->mntpoint_sid = SECINITSID_UNLABELED;
381 sb->s_security = sbsec;
383 return 0;
386 static void superblock_free_security(struct super_block *sb)
388 struct superblock_security_struct *sbsec = sb->s_security;
389 sb->s_security = NULL;
390 kfree(sbsec);
393 struct selinux_mnt_opts {
394 const char *fscontext, *context, *rootcontext, *defcontext;
397 static void selinux_free_mnt_opts(void *mnt_opts)
399 struct selinux_mnt_opts *opts = mnt_opts;
400 kfree(opts->fscontext);
401 kfree(opts->context);
402 kfree(opts->rootcontext);
403 kfree(opts->defcontext);
404 kfree(opts);
407 static inline int inode_doinit(struct inode *inode)
409 return inode_doinit_with_dentry(inode, NULL);
412 enum {
413 Opt_error = -1,
414 Opt_context = 0,
415 Opt_defcontext = 1,
416 Opt_fscontext = 2,
417 Opt_rootcontext = 3,
418 Opt_seclabel = 4,
421 #define A(s, has_arg) {#s, sizeof(#s) - 1, Opt_##s, has_arg}
422 static struct {
423 const char *name;
424 int len;
425 int opt;
426 bool has_arg;
427 } tokens[] = {
428 A(context, true),
429 A(fscontext, true),
430 A(defcontext, true),
431 A(rootcontext, true),
432 A(seclabel, false),
434 #undef A
436 static int match_opt_prefix(char *s, int l, char **arg)
438 int i;
440 for (i = 0; i < ARRAY_SIZE(tokens); i++) {
441 size_t len = tokens[i].len;
442 if (len > l || memcmp(s, tokens[i].name, len))
443 continue;
444 if (tokens[i].has_arg) {
445 if (len == l || s[len] != '=')
446 continue;
447 *arg = s + len + 1;
448 } else if (len != l)
449 continue;
450 return tokens[i].opt;
452 return Opt_error;
455 #define SEL_MOUNT_FAIL_MSG "SELinux: duplicate or incompatible mount options\n"
457 static int may_context_mount_sb_relabel(u32 sid,
458 struct superblock_security_struct *sbsec,
459 const struct cred *cred)
461 const struct task_security_struct *tsec = selinux_cred(cred);
462 int rc;
464 rc = avc_has_perm(&selinux_state,
465 tsec->sid, sbsec->sid, SECCLASS_FILESYSTEM,
466 FILESYSTEM__RELABELFROM, NULL);
467 if (rc)
468 return rc;
470 rc = avc_has_perm(&selinux_state,
471 tsec->sid, sid, SECCLASS_FILESYSTEM,
472 FILESYSTEM__RELABELTO, NULL);
473 return rc;
476 static int may_context_mount_inode_relabel(u32 sid,
477 struct superblock_security_struct *sbsec,
478 const struct cred *cred)
480 const struct task_security_struct *tsec = selinux_cred(cred);
481 int rc;
482 rc = avc_has_perm(&selinux_state,
483 tsec->sid, sbsec->sid, SECCLASS_FILESYSTEM,
484 FILESYSTEM__RELABELFROM, NULL);
485 if (rc)
486 return rc;
488 rc = avc_has_perm(&selinux_state,
489 sid, sbsec->sid, SECCLASS_FILESYSTEM,
490 FILESYSTEM__ASSOCIATE, NULL);
491 return rc;
494 static int selinux_is_genfs_special_handling(struct super_block *sb)
496 /* Special handling. Genfs but also in-core setxattr handler */
497 return !strcmp(sb->s_type->name, "sysfs") ||
498 !strcmp(sb->s_type->name, "pstore") ||
499 !strcmp(sb->s_type->name, "debugfs") ||
500 !strcmp(sb->s_type->name, "tracefs") ||
501 !strcmp(sb->s_type->name, "rootfs") ||
502 (selinux_policycap_cgroupseclabel() &&
503 (!strcmp(sb->s_type->name, "cgroup") ||
504 !strcmp(sb->s_type->name, "cgroup2")));
507 static int selinux_is_sblabel_mnt(struct super_block *sb)
509 struct superblock_security_struct *sbsec = sb->s_security;
512 * IMPORTANT: Double-check logic in this function when adding a new
513 * SECURITY_FS_USE_* definition!
515 BUILD_BUG_ON(SECURITY_FS_USE_MAX != 7);
517 switch (sbsec->behavior) {
518 case SECURITY_FS_USE_XATTR:
519 case SECURITY_FS_USE_TRANS:
520 case SECURITY_FS_USE_TASK:
521 case SECURITY_FS_USE_NATIVE:
522 return 1;
524 case SECURITY_FS_USE_GENFS:
525 return selinux_is_genfs_special_handling(sb);
527 /* Never allow relabeling on context mounts */
528 case SECURITY_FS_USE_MNTPOINT:
529 case SECURITY_FS_USE_NONE:
530 default:
531 return 0;
535 static int sb_finish_set_opts(struct super_block *sb)
537 struct superblock_security_struct *sbsec = sb->s_security;
538 struct dentry *root = sb->s_root;
539 struct inode *root_inode = d_backing_inode(root);
540 int rc = 0;
542 if (sbsec->behavior == SECURITY_FS_USE_XATTR) {
543 /* Make sure that the xattr handler exists and that no
544 error other than -ENODATA is returned by getxattr on
545 the root directory. -ENODATA is ok, as this may be
546 the first boot of the SELinux kernel before we have
547 assigned xattr values to the filesystem. */
548 if (!(root_inode->i_opflags & IOP_XATTR)) {
549 pr_warn("SELinux: (dev %s, type %s) has no "
550 "xattr support\n", sb->s_id, sb->s_type->name);
551 rc = -EOPNOTSUPP;
552 goto out;
555 rc = __vfs_getxattr(root, root_inode, XATTR_NAME_SELINUX, NULL, 0);
556 if (rc < 0 && rc != -ENODATA) {
557 if (rc == -EOPNOTSUPP)
558 pr_warn("SELinux: (dev %s, type "
559 "%s) has no security xattr handler\n",
560 sb->s_id, sb->s_type->name);
561 else
562 pr_warn("SELinux: (dev %s, type "
563 "%s) getxattr errno %d\n", sb->s_id,
564 sb->s_type->name, -rc);
565 goto out;
569 sbsec->flags |= SE_SBINITIALIZED;
572 * Explicitly set or clear SBLABEL_MNT. It's not sufficient to simply
573 * leave the flag untouched because sb_clone_mnt_opts might be handing
574 * us a superblock that needs the flag to be cleared.
576 if (selinux_is_sblabel_mnt(sb))
577 sbsec->flags |= SBLABEL_MNT;
578 else
579 sbsec->flags &= ~SBLABEL_MNT;
581 /* Initialize the root inode. */
582 rc = inode_doinit_with_dentry(root_inode, root);
584 /* Initialize any other inodes associated with the superblock, e.g.
585 inodes created prior to initial policy load or inodes created
586 during get_sb by a pseudo filesystem that directly
587 populates itself. */
588 spin_lock(&sbsec->isec_lock);
589 while (!list_empty(&sbsec->isec_head)) {
590 struct inode_security_struct *isec =
591 list_first_entry(&sbsec->isec_head,
592 struct inode_security_struct, list);
593 struct inode *inode = isec->inode;
594 list_del_init(&isec->list);
595 spin_unlock(&sbsec->isec_lock);
596 inode = igrab(inode);
597 if (inode) {
598 if (!IS_PRIVATE(inode))
599 inode_doinit(inode);
600 iput(inode);
602 spin_lock(&sbsec->isec_lock);
604 spin_unlock(&sbsec->isec_lock);
605 out:
606 return rc;
609 static int bad_option(struct superblock_security_struct *sbsec, char flag,
610 u32 old_sid, u32 new_sid)
612 char mnt_flags = sbsec->flags & SE_MNTMASK;
614 /* check if the old mount command had the same options */
615 if (sbsec->flags & SE_SBINITIALIZED)
616 if (!(sbsec->flags & flag) ||
617 (old_sid != new_sid))
618 return 1;
620 /* check if we were passed the same options twice,
621 * aka someone passed context=a,context=b
623 if (!(sbsec->flags & SE_SBINITIALIZED))
624 if (mnt_flags & flag)
625 return 1;
626 return 0;
629 static int parse_sid(struct super_block *sb, const char *s, u32 *sid)
631 int rc = security_context_str_to_sid(&selinux_state, s,
632 sid, GFP_KERNEL);
633 if (rc)
634 pr_warn("SELinux: security_context_str_to_sid"
635 "(%s) failed for (dev %s, type %s) errno=%d\n",
636 s, sb->s_id, sb->s_type->name, rc);
637 return rc;
641 * Allow filesystems with binary mount data to explicitly set mount point
642 * labeling information.
644 static int selinux_set_mnt_opts(struct super_block *sb,
645 void *mnt_opts,
646 unsigned long kern_flags,
647 unsigned long *set_kern_flags)
649 const struct cred *cred = current_cred();
650 struct superblock_security_struct *sbsec = sb->s_security;
651 struct dentry *root = sbsec->sb->s_root;
652 struct selinux_mnt_opts *opts = mnt_opts;
653 struct inode_security_struct *root_isec;
654 u32 fscontext_sid = 0, context_sid = 0, rootcontext_sid = 0;
655 u32 defcontext_sid = 0;
656 int rc = 0;
658 mutex_lock(&sbsec->lock);
660 if (!selinux_state.initialized) {
661 if (!opts) {
662 /* Defer initialization until selinux_complete_init,
663 after the initial policy is loaded and the security
664 server is ready to handle calls. */
665 goto out;
667 rc = -EINVAL;
668 pr_warn("SELinux: Unable to set superblock options "
669 "before the security server is initialized\n");
670 goto out;
672 if (kern_flags && !set_kern_flags) {
673 /* Specifying internal flags without providing a place to
674 * place the results is not allowed */
675 rc = -EINVAL;
676 goto out;
680 * Binary mount data FS will come through this function twice. Once
681 * from an explicit call and once from the generic calls from the vfs.
682 * Since the generic VFS calls will not contain any security mount data
683 * we need to skip the double mount verification.
685 * This does open a hole in which we will not notice if the first
686 * mount using this sb set explict options and a second mount using
687 * this sb does not set any security options. (The first options
688 * will be used for both mounts)
690 if ((sbsec->flags & SE_SBINITIALIZED) && (sb->s_type->fs_flags & FS_BINARY_MOUNTDATA)
691 && !opts)
692 goto out;
694 root_isec = backing_inode_security_novalidate(root);
697 * parse the mount options, check if they are valid sids.
698 * also check if someone is trying to mount the same sb more
699 * than once with different security options.
701 if (opts) {
702 if (opts->fscontext) {
703 rc = parse_sid(sb, opts->fscontext, &fscontext_sid);
704 if (rc)
705 goto out;
706 if (bad_option(sbsec, FSCONTEXT_MNT, sbsec->sid,
707 fscontext_sid))
708 goto out_double_mount;
709 sbsec->flags |= FSCONTEXT_MNT;
711 if (opts->context) {
712 rc = parse_sid(sb, opts->context, &context_sid);
713 if (rc)
714 goto out;
715 if (bad_option(sbsec, CONTEXT_MNT, sbsec->mntpoint_sid,
716 context_sid))
717 goto out_double_mount;
718 sbsec->flags |= CONTEXT_MNT;
720 if (opts->rootcontext) {
721 rc = parse_sid(sb, opts->rootcontext, &rootcontext_sid);
722 if (rc)
723 goto out;
724 if (bad_option(sbsec, ROOTCONTEXT_MNT, root_isec->sid,
725 rootcontext_sid))
726 goto out_double_mount;
727 sbsec->flags |= ROOTCONTEXT_MNT;
729 if (opts->defcontext) {
730 rc = parse_sid(sb, opts->defcontext, &defcontext_sid);
731 if (rc)
732 goto out;
733 if (bad_option(sbsec, DEFCONTEXT_MNT, sbsec->def_sid,
734 defcontext_sid))
735 goto out_double_mount;
736 sbsec->flags |= DEFCONTEXT_MNT;
740 if (sbsec->flags & SE_SBINITIALIZED) {
741 /* previously mounted with options, but not on this attempt? */
742 if ((sbsec->flags & SE_MNTMASK) && !opts)
743 goto out_double_mount;
744 rc = 0;
745 goto out;
748 if (strcmp(sb->s_type->name, "proc") == 0)
749 sbsec->flags |= SE_SBPROC | SE_SBGENFS;
751 if (!strcmp(sb->s_type->name, "debugfs") ||
752 !strcmp(sb->s_type->name, "tracefs") ||
753 !strcmp(sb->s_type->name, "pstore"))
754 sbsec->flags |= SE_SBGENFS;
756 if (!strcmp(sb->s_type->name, "sysfs") ||
757 !strcmp(sb->s_type->name, "cgroup") ||
758 !strcmp(sb->s_type->name, "cgroup2"))
759 sbsec->flags |= SE_SBGENFS | SE_SBGENFS_XATTR;
761 if (!sbsec->behavior) {
763 * Determine the labeling behavior to use for this
764 * filesystem type.
766 rc = security_fs_use(&selinux_state, sb);
767 if (rc) {
768 pr_warn("%s: security_fs_use(%s) returned %d\n",
769 __func__, sb->s_type->name, rc);
770 goto out;
775 * If this is a user namespace mount and the filesystem type is not
776 * explicitly whitelisted, then no contexts are allowed on the command
777 * line and security labels must be ignored.
779 if (sb->s_user_ns != &init_user_ns &&
780 strcmp(sb->s_type->name, "tmpfs") &&
781 strcmp(sb->s_type->name, "ramfs") &&
782 strcmp(sb->s_type->name, "devpts")) {
783 if (context_sid || fscontext_sid || rootcontext_sid ||
784 defcontext_sid) {
785 rc = -EACCES;
786 goto out;
788 if (sbsec->behavior == SECURITY_FS_USE_XATTR) {
789 sbsec->behavior = SECURITY_FS_USE_MNTPOINT;
790 rc = security_transition_sid(&selinux_state,
791 current_sid(),
792 current_sid(),
793 SECCLASS_FILE, NULL,
794 &sbsec->mntpoint_sid);
795 if (rc)
796 goto out;
798 goto out_set_opts;
801 /* sets the context of the superblock for the fs being mounted. */
802 if (fscontext_sid) {
803 rc = may_context_mount_sb_relabel(fscontext_sid, sbsec, cred);
804 if (rc)
805 goto out;
807 sbsec->sid = fscontext_sid;
811 * Switch to using mount point labeling behavior.
812 * sets the label used on all file below the mountpoint, and will set
813 * the superblock context if not already set.
815 if (kern_flags & SECURITY_LSM_NATIVE_LABELS && !context_sid) {
816 sbsec->behavior = SECURITY_FS_USE_NATIVE;
817 *set_kern_flags |= SECURITY_LSM_NATIVE_LABELS;
820 if (context_sid) {
821 if (!fscontext_sid) {
822 rc = may_context_mount_sb_relabel(context_sid, sbsec,
823 cred);
824 if (rc)
825 goto out;
826 sbsec->sid = context_sid;
827 } else {
828 rc = may_context_mount_inode_relabel(context_sid, sbsec,
829 cred);
830 if (rc)
831 goto out;
833 if (!rootcontext_sid)
834 rootcontext_sid = context_sid;
836 sbsec->mntpoint_sid = context_sid;
837 sbsec->behavior = SECURITY_FS_USE_MNTPOINT;
840 if (rootcontext_sid) {
841 rc = may_context_mount_inode_relabel(rootcontext_sid, sbsec,
842 cred);
843 if (rc)
844 goto out;
846 root_isec->sid = rootcontext_sid;
847 root_isec->initialized = LABEL_INITIALIZED;
850 if (defcontext_sid) {
851 if (sbsec->behavior != SECURITY_FS_USE_XATTR &&
852 sbsec->behavior != SECURITY_FS_USE_NATIVE) {
853 rc = -EINVAL;
854 pr_warn("SELinux: defcontext option is "
855 "invalid for this filesystem type\n");
856 goto out;
859 if (defcontext_sid != sbsec->def_sid) {
860 rc = may_context_mount_inode_relabel(defcontext_sid,
861 sbsec, cred);
862 if (rc)
863 goto out;
866 sbsec->def_sid = defcontext_sid;
869 out_set_opts:
870 rc = sb_finish_set_opts(sb);
871 out:
872 mutex_unlock(&sbsec->lock);
873 return rc;
874 out_double_mount:
875 rc = -EINVAL;
876 pr_warn("SELinux: mount invalid. Same superblock, different "
877 "security settings for (dev %s, type %s)\n", sb->s_id,
878 sb->s_type->name);
879 goto out;
882 static int selinux_cmp_sb_context(const struct super_block *oldsb,
883 const struct super_block *newsb)
885 struct superblock_security_struct *old = oldsb->s_security;
886 struct superblock_security_struct *new = newsb->s_security;
887 char oldflags = old->flags & SE_MNTMASK;
888 char newflags = new->flags & SE_MNTMASK;
890 if (oldflags != newflags)
891 goto mismatch;
892 if ((oldflags & FSCONTEXT_MNT) && old->sid != new->sid)
893 goto mismatch;
894 if ((oldflags & CONTEXT_MNT) && old->mntpoint_sid != new->mntpoint_sid)
895 goto mismatch;
896 if ((oldflags & DEFCONTEXT_MNT) && old->def_sid != new->def_sid)
897 goto mismatch;
898 if (oldflags & ROOTCONTEXT_MNT) {
899 struct inode_security_struct *oldroot = backing_inode_security(oldsb->s_root);
900 struct inode_security_struct *newroot = backing_inode_security(newsb->s_root);
901 if (oldroot->sid != newroot->sid)
902 goto mismatch;
904 return 0;
905 mismatch:
906 pr_warn("SELinux: mount invalid. Same superblock, "
907 "different security settings for (dev %s, "
908 "type %s)\n", newsb->s_id, newsb->s_type->name);
909 return -EBUSY;
912 static int selinux_sb_clone_mnt_opts(const struct super_block *oldsb,
913 struct super_block *newsb,
914 unsigned long kern_flags,
915 unsigned long *set_kern_flags)
917 int rc = 0;
918 const struct superblock_security_struct *oldsbsec = oldsb->s_security;
919 struct superblock_security_struct *newsbsec = newsb->s_security;
921 int set_fscontext = (oldsbsec->flags & FSCONTEXT_MNT);
922 int set_context = (oldsbsec->flags & CONTEXT_MNT);
923 int set_rootcontext = (oldsbsec->flags & ROOTCONTEXT_MNT);
926 * if the parent was able to be mounted it clearly had no special lsm
927 * mount options. thus we can safely deal with this superblock later
929 if (!selinux_state.initialized)
930 return 0;
933 * Specifying internal flags without providing a place to
934 * place the results is not allowed.
936 if (kern_flags && !set_kern_flags)
937 return -EINVAL;
939 /* how can we clone if the old one wasn't set up?? */
940 BUG_ON(!(oldsbsec->flags & SE_SBINITIALIZED));
942 /* if fs is reusing a sb, make sure that the contexts match */
943 if (newsbsec->flags & SE_SBINITIALIZED) {
944 if ((kern_flags & SECURITY_LSM_NATIVE_LABELS) && !set_context)
945 *set_kern_flags |= SECURITY_LSM_NATIVE_LABELS;
946 return selinux_cmp_sb_context(oldsb, newsb);
949 mutex_lock(&newsbsec->lock);
951 newsbsec->flags = oldsbsec->flags;
953 newsbsec->sid = oldsbsec->sid;
954 newsbsec->def_sid = oldsbsec->def_sid;
955 newsbsec->behavior = oldsbsec->behavior;
957 if (newsbsec->behavior == SECURITY_FS_USE_NATIVE &&
958 !(kern_flags & SECURITY_LSM_NATIVE_LABELS) && !set_context) {
959 rc = security_fs_use(&selinux_state, newsb);
960 if (rc)
961 goto out;
964 if (kern_flags & SECURITY_LSM_NATIVE_LABELS && !set_context) {
965 newsbsec->behavior = SECURITY_FS_USE_NATIVE;
966 *set_kern_flags |= SECURITY_LSM_NATIVE_LABELS;
969 if (set_context) {
970 u32 sid = oldsbsec->mntpoint_sid;
972 if (!set_fscontext)
973 newsbsec->sid = sid;
974 if (!set_rootcontext) {
975 struct inode_security_struct *newisec = backing_inode_security(newsb->s_root);
976 newisec->sid = sid;
978 newsbsec->mntpoint_sid = sid;
980 if (set_rootcontext) {
981 const struct inode_security_struct *oldisec = backing_inode_security(oldsb->s_root);
982 struct inode_security_struct *newisec = backing_inode_security(newsb->s_root);
984 newisec->sid = oldisec->sid;
987 sb_finish_set_opts(newsb);
988 out:
989 mutex_unlock(&newsbsec->lock);
990 return rc;
993 static int selinux_add_opt(int token, const char *s, void **mnt_opts)
995 struct selinux_mnt_opts *opts = *mnt_opts;
997 if (token == Opt_seclabel) /* eaten and completely ignored */
998 return 0;
1000 if (!opts) {
1001 opts = kzalloc(sizeof(struct selinux_mnt_opts), GFP_KERNEL);
1002 if (!opts)
1003 return -ENOMEM;
1004 *mnt_opts = opts;
1006 if (!s)
1007 return -ENOMEM;
1008 switch (token) {
1009 case Opt_context:
1010 if (opts->context || opts->defcontext)
1011 goto Einval;
1012 opts->context = s;
1013 break;
1014 case Opt_fscontext:
1015 if (opts->fscontext)
1016 goto Einval;
1017 opts->fscontext = s;
1018 break;
1019 case Opt_rootcontext:
1020 if (opts->rootcontext)
1021 goto Einval;
1022 opts->rootcontext = s;
1023 break;
1024 case Opt_defcontext:
1025 if (opts->context || opts->defcontext)
1026 goto Einval;
1027 opts->defcontext = s;
1028 break;
1030 return 0;
1031 Einval:
1032 pr_warn(SEL_MOUNT_FAIL_MSG);
1033 return -EINVAL;
1036 static int selinux_add_mnt_opt(const char *option, const char *val, int len,
1037 void **mnt_opts)
1039 int token = Opt_error;
1040 int rc, i;
1042 for (i = 0; i < ARRAY_SIZE(tokens); i++) {
1043 if (strcmp(option, tokens[i].name) == 0) {
1044 token = tokens[i].opt;
1045 break;
1049 if (token == Opt_error)
1050 return -EINVAL;
1052 if (token != Opt_seclabel) {
1053 val = kmemdup_nul(val, len, GFP_KERNEL);
1054 if (!val) {
1055 rc = -ENOMEM;
1056 goto free_opt;
1059 rc = selinux_add_opt(token, val, mnt_opts);
1060 if (unlikely(rc)) {
1061 kfree(val);
1062 goto free_opt;
1064 return rc;
1066 free_opt:
1067 if (*mnt_opts) {
1068 selinux_free_mnt_opts(*mnt_opts);
1069 *mnt_opts = NULL;
1071 return rc;
1074 static int show_sid(struct seq_file *m, u32 sid)
1076 char *context = NULL;
1077 u32 len;
1078 int rc;
1080 rc = security_sid_to_context(&selinux_state, sid,
1081 &context, &len);
1082 if (!rc) {
1083 bool has_comma = context && strchr(context, ',');
1085 seq_putc(m, '=');
1086 if (has_comma)
1087 seq_putc(m, '\"');
1088 seq_escape(m, context, "\"\n\\");
1089 if (has_comma)
1090 seq_putc(m, '\"');
1092 kfree(context);
1093 return rc;
1096 static int selinux_sb_show_options(struct seq_file *m, struct super_block *sb)
1098 struct superblock_security_struct *sbsec = sb->s_security;
1099 int rc;
1101 if (!(sbsec->flags & SE_SBINITIALIZED))
1102 return 0;
1104 if (!selinux_state.initialized)
1105 return 0;
1107 if (sbsec->flags & FSCONTEXT_MNT) {
1108 seq_putc(m, ',');
1109 seq_puts(m, FSCONTEXT_STR);
1110 rc = show_sid(m, sbsec->sid);
1111 if (rc)
1112 return rc;
1114 if (sbsec->flags & CONTEXT_MNT) {
1115 seq_putc(m, ',');
1116 seq_puts(m, CONTEXT_STR);
1117 rc = show_sid(m, sbsec->mntpoint_sid);
1118 if (rc)
1119 return rc;
1121 if (sbsec->flags & DEFCONTEXT_MNT) {
1122 seq_putc(m, ',');
1123 seq_puts(m, DEFCONTEXT_STR);
1124 rc = show_sid(m, sbsec->def_sid);
1125 if (rc)
1126 return rc;
1128 if (sbsec->flags & ROOTCONTEXT_MNT) {
1129 struct dentry *root = sbsec->sb->s_root;
1130 struct inode_security_struct *isec = backing_inode_security(root);
1131 seq_putc(m, ',');
1132 seq_puts(m, ROOTCONTEXT_STR);
1133 rc = show_sid(m, isec->sid);
1134 if (rc)
1135 return rc;
1137 if (sbsec->flags & SBLABEL_MNT) {
1138 seq_putc(m, ',');
1139 seq_puts(m, SECLABEL_STR);
1141 return 0;
1144 static inline u16 inode_mode_to_security_class(umode_t mode)
1146 switch (mode & S_IFMT) {
1147 case S_IFSOCK:
1148 return SECCLASS_SOCK_FILE;
1149 case S_IFLNK:
1150 return SECCLASS_LNK_FILE;
1151 case S_IFREG:
1152 return SECCLASS_FILE;
1153 case S_IFBLK:
1154 return SECCLASS_BLK_FILE;
1155 case S_IFDIR:
1156 return SECCLASS_DIR;
1157 case S_IFCHR:
1158 return SECCLASS_CHR_FILE;
1159 case S_IFIFO:
1160 return SECCLASS_FIFO_FILE;
1164 return SECCLASS_FILE;
1167 static inline int default_protocol_stream(int protocol)
1169 return (protocol == IPPROTO_IP || protocol == IPPROTO_TCP);
1172 static inline int default_protocol_dgram(int protocol)
1174 return (protocol == IPPROTO_IP || protocol == IPPROTO_UDP);
1177 static inline u16 socket_type_to_security_class(int family, int type, int protocol)
1179 int extsockclass = selinux_policycap_extsockclass();
1181 switch (family) {
1182 case PF_UNIX:
1183 switch (type) {
1184 case SOCK_STREAM:
1185 case SOCK_SEQPACKET:
1186 return SECCLASS_UNIX_STREAM_SOCKET;
1187 case SOCK_DGRAM:
1188 case SOCK_RAW:
1189 return SECCLASS_UNIX_DGRAM_SOCKET;
1191 break;
1192 case PF_INET:
1193 case PF_INET6:
1194 switch (type) {
1195 case SOCK_STREAM:
1196 case SOCK_SEQPACKET:
1197 if (default_protocol_stream(protocol))
1198 return SECCLASS_TCP_SOCKET;
1199 else if (extsockclass && protocol == IPPROTO_SCTP)
1200 return SECCLASS_SCTP_SOCKET;
1201 else
1202 return SECCLASS_RAWIP_SOCKET;
1203 case SOCK_DGRAM:
1204 if (default_protocol_dgram(protocol))
1205 return SECCLASS_UDP_SOCKET;
1206 else if (extsockclass && (protocol == IPPROTO_ICMP ||
1207 protocol == IPPROTO_ICMPV6))
1208 return SECCLASS_ICMP_SOCKET;
1209 else
1210 return SECCLASS_RAWIP_SOCKET;
1211 case SOCK_DCCP:
1212 return SECCLASS_DCCP_SOCKET;
1213 default:
1214 return SECCLASS_RAWIP_SOCKET;
1216 break;
1217 case PF_NETLINK:
1218 switch (protocol) {
1219 case NETLINK_ROUTE:
1220 return SECCLASS_NETLINK_ROUTE_SOCKET;
1221 case NETLINK_SOCK_DIAG:
1222 return SECCLASS_NETLINK_TCPDIAG_SOCKET;
1223 case NETLINK_NFLOG:
1224 return SECCLASS_NETLINK_NFLOG_SOCKET;
1225 case NETLINK_XFRM:
1226 return SECCLASS_NETLINK_XFRM_SOCKET;
1227 case NETLINK_SELINUX:
1228 return SECCLASS_NETLINK_SELINUX_SOCKET;
1229 case NETLINK_ISCSI:
1230 return SECCLASS_NETLINK_ISCSI_SOCKET;
1231 case NETLINK_AUDIT:
1232 return SECCLASS_NETLINK_AUDIT_SOCKET;
1233 case NETLINK_FIB_LOOKUP:
1234 return SECCLASS_NETLINK_FIB_LOOKUP_SOCKET;
1235 case NETLINK_CONNECTOR:
1236 return SECCLASS_NETLINK_CONNECTOR_SOCKET;
1237 case NETLINK_NETFILTER:
1238 return SECCLASS_NETLINK_NETFILTER_SOCKET;
1239 case NETLINK_DNRTMSG:
1240 return SECCLASS_NETLINK_DNRT_SOCKET;
1241 case NETLINK_KOBJECT_UEVENT:
1242 return SECCLASS_NETLINK_KOBJECT_UEVENT_SOCKET;
1243 case NETLINK_GENERIC:
1244 return SECCLASS_NETLINK_GENERIC_SOCKET;
1245 case NETLINK_SCSITRANSPORT:
1246 return SECCLASS_NETLINK_SCSITRANSPORT_SOCKET;
1247 case NETLINK_RDMA:
1248 return SECCLASS_NETLINK_RDMA_SOCKET;
1249 case NETLINK_CRYPTO:
1250 return SECCLASS_NETLINK_CRYPTO_SOCKET;
1251 default:
1252 return SECCLASS_NETLINK_SOCKET;
1254 case PF_PACKET:
1255 return SECCLASS_PACKET_SOCKET;
1256 case PF_KEY:
1257 return SECCLASS_KEY_SOCKET;
1258 case PF_APPLETALK:
1259 return SECCLASS_APPLETALK_SOCKET;
1262 if (extsockclass) {
1263 switch (family) {
1264 case PF_AX25:
1265 return SECCLASS_AX25_SOCKET;
1266 case PF_IPX:
1267 return SECCLASS_IPX_SOCKET;
1268 case PF_NETROM:
1269 return SECCLASS_NETROM_SOCKET;
1270 case PF_ATMPVC:
1271 return SECCLASS_ATMPVC_SOCKET;
1272 case PF_X25:
1273 return SECCLASS_X25_SOCKET;
1274 case PF_ROSE:
1275 return SECCLASS_ROSE_SOCKET;
1276 case PF_DECnet:
1277 return SECCLASS_DECNET_SOCKET;
1278 case PF_ATMSVC:
1279 return SECCLASS_ATMSVC_SOCKET;
1280 case PF_RDS:
1281 return SECCLASS_RDS_SOCKET;
1282 case PF_IRDA:
1283 return SECCLASS_IRDA_SOCKET;
1284 case PF_PPPOX:
1285 return SECCLASS_PPPOX_SOCKET;
1286 case PF_LLC:
1287 return SECCLASS_LLC_SOCKET;
1288 case PF_CAN:
1289 return SECCLASS_CAN_SOCKET;
1290 case PF_TIPC:
1291 return SECCLASS_TIPC_SOCKET;
1292 case PF_BLUETOOTH:
1293 return SECCLASS_BLUETOOTH_SOCKET;
1294 case PF_IUCV:
1295 return SECCLASS_IUCV_SOCKET;
1296 case PF_RXRPC:
1297 return SECCLASS_RXRPC_SOCKET;
1298 case PF_ISDN:
1299 return SECCLASS_ISDN_SOCKET;
1300 case PF_PHONET:
1301 return SECCLASS_PHONET_SOCKET;
1302 case PF_IEEE802154:
1303 return SECCLASS_IEEE802154_SOCKET;
1304 case PF_CAIF:
1305 return SECCLASS_CAIF_SOCKET;
1306 case PF_ALG:
1307 return SECCLASS_ALG_SOCKET;
1308 case PF_NFC:
1309 return SECCLASS_NFC_SOCKET;
1310 case PF_VSOCK:
1311 return SECCLASS_VSOCK_SOCKET;
1312 case PF_KCM:
1313 return SECCLASS_KCM_SOCKET;
1314 case PF_QIPCRTR:
1315 return SECCLASS_QIPCRTR_SOCKET;
1316 case PF_SMC:
1317 return SECCLASS_SMC_SOCKET;
1318 case PF_XDP:
1319 return SECCLASS_XDP_SOCKET;
1320 #if PF_MAX > 45
1321 #error New address family defined, please update this function.
1322 #endif
1326 return SECCLASS_SOCKET;
1329 static int selinux_genfs_get_sid(struct dentry *dentry,
1330 u16 tclass,
1331 u16 flags,
1332 u32 *sid)
1334 int rc;
1335 struct super_block *sb = dentry->d_sb;
1336 char *buffer, *path;
1338 buffer = (char *)__get_free_page(GFP_KERNEL);
1339 if (!buffer)
1340 return -ENOMEM;
1342 path = dentry_path_raw(dentry, buffer, PAGE_SIZE);
1343 if (IS_ERR(path))
1344 rc = PTR_ERR(path);
1345 else {
1346 if (flags & SE_SBPROC) {
1347 /* each process gets a /proc/PID/ entry. Strip off the
1348 * PID part to get a valid selinux labeling.
1349 * e.g. /proc/1/net/rpc/nfs -> /net/rpc/nfs */
1350 while (path[1] >= '0' && path[1] <= '9') {
1351 path[1] = '/';
1352 path++;
1355 rc = security_genfs_sid(&selinux_state, sb->s_type->name,
1356 path, tclass, sid);
1357 if (rc == -ENOENT) {
1358 /* No match in policy, mark as unlabeled. */
1359 *sid = SECINITSID_UNLABELED;
1360 rc = 0;
1363 free_page((unsigned long)buffer);
1364 return rc;
1367 static int inode_doinit_use_xattr(struct inode *inode, struct dentry *dentry,
1368 u32 def_sid, u32 *sid)
1370 #define INITCONTEXTLEN 255
1371 char *context;
1372 unsigned int len;
1373 int rc;
1375 len = INITCONTEXTLEN;
1376 context = kmalloc(len + 1, GFP_NOFS);
1377 if (!context)
1378 return -ENOMEM;
1380 context[len] = '\0';
1381 rc = __vfs_getxattr(dentry, inode, XATTR_NAME_SELINUX, context, len);
1382 if (rc == -ERANGE) {
1383 kfree(context);
1385 /* Need a larger buffer. Query for the right size. */
1386 rc = __vfs_getxattr(dentry, inode, XATTR_NAME_SELINUX, NULL, 0);
1387 if (rc < 0)
1388 return rc;
1390 len = rc;
1391 context = kmalloc(len + 1, GFP_NOFS);
1392 if (!context)
1393 return -ENOMEM;
1395 context[len] = '\0';
1396 rc = __vfs_getxattr(dentry, inode, XATTR_NAME_SELINUX,
1397 context, len);
1399 if (rc < 0) {
1400 kfree(context);
1401 if (rc != -ENODATA) {
1402 pr_warn("SELinux: %s: getxattr returned %d for dev=%s ino=%ld\n",
1403 __func__, -rc, inode->i_sb->s_id, inode->i_ino);
1404 return rc;
1406 *sid = def_sid;
1407 return 0;
1410 rc = security_context_to_sid_default(&selinux_state, context, rc, sid,
1411 def_sid, GFP_NOFS);
1412 if (rc) {
1413 char *dev = inode->i_sb->s_id;
1414 unsigned long ino = inode->i_ino;
1416 if (rc == -EINVAL) {
1417 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",
1418 ino, dev, context);
1419 } else {
1420 pr_warn("SELinux: %s: context_to_sid(%s) returned %d for dev=%s ino=%ld\n",
1421 __func__, context, -rc, dev, ino);
1424 kfree(context);
1425 return 0;
1428 /* The inode's security attributes must be initialized before first use. */
1429 static int inode_doinit_with_dentry(struct inode *inode, struct dentry *opt_dentry)
1431 struct superblock_security_struct *sbsec = NULL;
1432 struct inode_security_struct *isec = selinux_inode(inode);
1433 u32 task_sid, sid = 0;
1434 u16 sclass;
1435 struct dentry *dentry;
1436 int rc = 0;
1438 if (isec->initialized == LABEL_INITIALIZED)
1439 return 0;
1441 spin_lock(&isec->lock);
1442 if (isec->initialized == LABEL_INITIALIZED)
1443 goto out_unlock;
1445 if (isec->sclass == SECCLASS_FILE)
1446 isec->sclass = inode_mode_to_security_class(inode->i_mode);
1448 sbsec = inode->i_sb->s_security;
1449 if (!(sbsec->flags & SE_SBINITIALIZED)) {
1450 /* Defer initialization until selinux_complete_init,
1451 after the initial policy is loaded and the security
1452 server is ready to handle calls. */
1453 spin_lock(&sbsec->isec_lock);
1454 if (list_empty(&isec->list))
1455 list_add(&isec->list, &sbsec->isec_head);
1456 spin_unlock(&sbsec->isec_lock);
1457 goto out_unlock;
1460 sclass = isec->sclass;
1461 task_sid = isec->task_sid;
1462 sid = isec->sid;
1463 isec->initialized = LABEL_PENDING;
1464 spin_unlock(&isec->lock);
1466 switch (sbsec->behavior) {
1467 case SECURITY_FS_USE_NATIVE:
1468 break;
1469 case SECURITY_FS_USE_XATTR:
1470 if (!(inode->i_opflags & IOP_XATTR)) {
1471 sid = sbsec->def_sid;
1472 break;
1474 /* Need a dentry, since the xattr API requires one.
1475 Life would be simpler if we could just pass the inode. */
1476 if (opt_dentry) {
1477 /* Called from d_instantiate or d_splice_alias. */
1478 dentry = dget(opt_dentry);
1479 } else {
1481 * Called from selinux_complete_init, try to find a dentry.
1482 * Some filesystems really want a connected one, so try
1483 * that first. We could split SECURITY_FS_USE_XATTR in
1484 * two, depending upon that...
1486 dentry = d_find_alias(inode);
1487 if (!dentry)
1488 dentry = d_find_any_alias(inode);
1490 if (!dentry) {
1492 * this is can be hit on boot when a file is accessed
1493 * before the policy is loaded. When we load policy we
1494 * may find inodes that have no dentry on the
1495 * sbsec->isec_head list. No reason to complain as these
1496 * will get fixed up the next time we go through
1497 * inode_doinit with a dentry, before these inodes could
1498 * be used again by userspace.
1500 goto out;
1503 rc = inode_doinit_use_xattr(inode, dentry, sbsec->def_sid,
1504 &sid);
1505 dput(dentry);
1506 if (rc)
1507 goto out;
1508 break;
1509 case SECURITY_FS_USE_TASK:
1510 sid = task_sid;
1511 break;
1512 case SECURITY_FS_USE_TRANS:
1513 /* Default to the fs SID. */
1514 sid = sbsec->sid;
1516 /* Try to obtain a transition SID. */
1517 rc = security_transition_sid(&selinux_state, task_sid, sid,
1518 sclass, NULL, &sid);
1519 if (rc)
1520 goto out;
1521 break;
1522 case SECURITY_FS_USE_MNTPOINT:
1523 sid = sbsec->mntpoint_sid;
1524 break;
1525 default:
1526 /* Default to the fs superblock SID. */
1527 sid = sbsec->sid;
1529 if ((sbsec->flags & SE_SBGENFS) && !S_ISLNK(inode->i_mode)) {
1530 /* We must have a dentry to determine the label on
1531 * procfs inodes */
1532 if (opt_dentry) {
1533 /* Called from d_instantiate or
1534 * d_splice_alias. */
1535 dentry = dget(opt_dentry);
1536 } else {
1537 /* Called from selinux_complete_init, try to
1538 * find a dentry. Some filesystems really want
1539 * a connected one, so try that first.
1541 dentry = d_find_alias(inode);
1542 if (!dentry)
1543 dentry = d_find_any_alias(inode);
1546 * This can be hit on boot when a file is accessed
1547 * before the policy is loaded. When we load policy we
1548 * may find inodes that have no dentry on the
1549 * sbsec->isec_head list. No reason to complain as
1550 * these will get fixed up the next time we go through
1551 * inode_doinit() with a dentry, before these inodes
1552 * could be used again by userspace.
1554 if (!dentry)
1555 goto out;
1556 rc = selinux_genfs_get_sid(dentry, sclass,
1557 sbsec->flags, &sid);
1558 if (rc) {
1559 dput(dentry);
1560 goto out;
1563 if ((sbsec->flags & SE_SBGENFS_XATTR) &&
1564 (inode->i_opflags & IOP_XATTR)) {
1565 rc = inode_doinit_use_xattr(inode, dentry,
1566 sid, &sid);
1567 if (rc) {
1568 dput(dentry);
1569 goto out;
1572 dput(dentry);
1574 break;
1577 out:
1578 spin_lock(&isec->lock);
1579 if (isec->initialized == LABEL_PENDING) {
1580 if (!sid || rc) {
1581 isec->initialized = LABEL_INVALID;
1582 goto out_unlock;
1585 isec->initialized = LABEL_INITIALIZED;
1586 isec->sid = sid;
1589 out_unlock:
1590 spin_unlock(&isec->lock);
1591 return rc;
1594 /* Convert a Linux signal to an access vector. */
1595 static inline u32 signal_to_av(int sig)
1597 u32 perm = 0;
1599 switch (sig) {
1600 case SIGCHLD:
1601 /* Commonly granted from child to parent. */
1602 perm = PROCESS__SIGCHLD;
1603 break;
1604 case SIGKILL:
1605 /* Cannot be caught or ignored */
1606 perm = PROCESS__SIGKILL;
1607 break;
1608 case SIGSTOP:
1609 /* Cannot be caught or ignored */
1610 perm = PROCESS__SIGSTOP;
1611 break;
1612 default:
1613 /* All other signals. */
1614 perm = PROCESS__SIGNAL;
1615 break;
1618 return perm;
1621 #if CAP_LAST_CAP > 63
1622 #error Fix SELinux to handle capabilities > 63.
1623 #endif
1625 /* Check whether a task is allowed to use a capability. */
1626 static int cred_has_capability(const struct cred *cred,
1627 int cap, unsigned int opts, bool initns)
1629 struct common_audit_data ad;
1630 struct av_decision avd;
1631 u16 sclass;
1632 u32 sid = cred_sid(cred);
1633 u32 av = CAP_TO_MASK(cap);
1634 int rc;
1636 ad.type = LSM_AUDIT_DATA_CAP;
1637 ad.u.cap = cap;
1639 switch (CAP_TO_INDEX(cap)) {
1640 case 0:
1641 sclass = initns ? SECCLASS_CAPABILITY : SECCLASS_CAP_USERNS;
1642 break;
1643 case 1:
1644 sclass = initns ? SECCLASS_CAPABILITY2 : SECCLASS_CAP2_USERNS;
1645 break;
1646 default:
1647 pr_err("SELinux: out of range capability %d\n", cap);
1648 BUG();
1649 return -EINVAL;
1652 rc = avc_has_perm_noaudit(&selinux_state,
1653 sid, sid, sclass, av, 0, &avd);
1654 if (!(opts & CAP_OPT_NOAUDIT)) {
1655 int rc2 = avc_audit(&selinux_state,
1656 sid, sid, sclass, av, &avd, rc, &ad, 0);
1657 if (rc2)
1658 return rc2;
1660 return rc;
1663 /* Check whether a task has a particular permission to an inode.
1664 The 'adp' parameter is optional and allows other audit
1665 data to be passed (e.g. the dentry). */
1666 static int inode_has_perm(const struct cred *cred,
1667 struct inode *inode,
1668 u32 perms,
1669 struct common_audit_data *adp)
1671 struct inode_security_struct *isec;
1672 u32 sid;
1674 validate_creds(cred);
1676 if (unlikely(IS_PRIVATE(inode)))
1677 return 0;
1679 sid = cred_sid(cred);
1680 isec = selinux_inode(inode);
1682 return avc_has_perm(&selinux_state,
1683 sid, isec->sid, isec->sclass, perms, adp);
1686 /* Same as inode_has_perm, but pass explicit audit data containing
1687 the dentry to help the auditing code to more easily generate the
1688 pathname if needed. */
1689 static inline int dentry_has_perm(const struct cred *cred,
1690 struct dentry *dentry,
1691 u32 av)
1693 struct inode *inode = d_backing_inode(dentry);
1694 struct common_audit_data ad;
1696 ad.type = LSM_AUDIT_DATA_DENTRY;
1697 ad.u.dentry = dentry;
1698 __inode_security_revalidate(inode, dentry, true);
1699 return inode_has_perm(cred, inode, av, &ad);
1702 /* Same as inode_has_perm, but pass explicit audit data containing
1703 the path to help the auditing code to more easily generate the
1704 pathname if needed. */
1705 static inline int path_has_perm(const struct cred *cred,
1706 const struct path *path,
1707 u32 av)
1709 struct inode *inode = d_backing_inode(path->dentry);
1710 struct common_audit_data ad;
1712 ad.type = LSM_AUDIT_DATA_PATH;
1713 ad.u.path = *path;
1714 __inode_security_revalidate(inode, path->dentry, true);
1715 return inode_has_perm(cred, inode, av, &ad);
1718 /* Same as path_has_perm, but uses the inode from the file struct. */
1719 static inline int file_path_has_perm(const struct cred *cred,
1720 struct file *file,
1721 u32 av)
1723 struct common_audit_data ad;
1725 ad.type = LSM_AUDIT_DATA_FILE;
1726 ad.u.file = file;
1727 return inode_has_perm(cred, file_inode(file), av, &ad);
1730 #ifdef CONFIG_BPF_SYSCALL
1731 static int bpf_fd_pass(struct file *file, u32 sid);
1732 #endif
1734 /* Check whether a task can use an open file descriptor to
1735 access an inode in a given way. Check access to the
1736 descriptor itself, and then use dentry_has_perm to
1737 check a particular permission to the file.
1738 Access to the descriptor is implicitly granted if it
1739 has the same SID as the process. If av is zero, then
1740 access to the file is not checked, e.g. for cases
1741 where only the descriptor is affected like seek. */
1742 static int file_has_perm(const struct cred *cred,
1743 struct file *file,
1744 u32 av)
1746 struct file_security_struct *fsec = selinux_file(file);
1747 struct inode *inode = file_inode(file);
1748 struct common_audit_data ad;
1749 u32 sid = cred_sid(cred);
1750 int rc;
1752 ad.type = LSM_AUDIT_DATA_FILE;
1753 ad.u.file = file;
1755 if (sid != fsec->sid) {
1756 rc = avc_has_perm(&selinux_state,
1757 sid, fsec->sid,
1758 SECCLASS_FD,
1759 FD__USE,
1760 &ad);
1761 if (rc)
1762 goto out;
1765 #ifdef CONFIG_BPF_SYSCALL
1766 rc = bpf_fd_pass(file, cred_sid(cred));
1767 if (rc)
1768 return rc;
1769 #endif
1771 /* av is zero if only checking access to the descriptor. */
1772 rc = 0;
1773 if (av)
1774 rc = inode_has_perm(cred, inode, av, &ad);
1776 out:
1777 return rc;
1781 * Determine the label for an inode that might be unioned.
1783 static int
1784 selinux_determine_inode_label(const struct task_security_struct *tsec,
1785 struct inode *dir,
1786 const struct qstr *name, u16 tclass,
1787 u32 *_new_isid)
1789 const struct superblock_security_struct *sbsec = dir->i_sb->s_security;
1791 if ((sbsec->flags & SE_SBINITIALIZED) &&
1792 (sbsec->behavior == SECURITY_FS_USE_MNTPOINT)) {
1793 *_new_isid = sbsec->mntpoint_sid;
1794 } else if ((sbsec->flags & SBLABEL_MNT) &&
1795 tsec->create_sid) {
1796 *_new_isid = tsec->create_sid;
1797 } else {
1798 const struct inode_security_struct *dsec = inode_security(dir);
1799 return security_transition_sid(&selinux_state, tsec->sid,
1800 dsec->sid, tclass,
1801 name, _new_isid);
1804 return 0;
1807 /* Check whether a task can create a file. */
1808 static int may_create(struct inode *dir,
1809 struct dentry *dentry,
1810 u16 tclass)
1812 const struct task_security_struct *tsec = selinux_cred(current_cred());
1813 struct inode_security_struct *dsec;
1814 struct superblock_security_struct *sbsec;
1815 u32 sid, newsid;
1816 struct common_audit_data ad;
1817 int rc;
1819 dsec = inode_security(dir);
1820 sbsec = dir->i_sb->s_security;
1822 sid = tsec->sid;
1824 ad.type = LSM_AUDIT_DATA_DENTRY;
1825 ad.u.dentry = dentry;
1827 rc = avc_has_perm(&selinux_state,
1828 sid, dsec->sid, SECCLASS_DIR,
1829 DIR__ADD_NAME | DIR__SEARCH,
1830 &ad);
1831 if (rc)
1832 return rc;
1834 rc = selinux_determine_inode_label(selinux_cred(current_cred()), dir,
1835 &dentry->d_name, tclass, &newsid);
1836 if (rc)
1837 return rc;
1839 rc = avc_has_perm(&selinux_state,
1840 sid, newsid, tclass, FILE__CREATE, &ad);
1841 if (rc)
1842 return rc;
1844 return avc_has_perm(&selinux_state,
1845 newsid, sbsec->sid,
1846 SECCLASS_FILESYSTEM,
1847 FILESYSTEM__ASSOCIATE, &ad);
1850 #define MAY_LINK 0
1851 #define MAY_UNLINK 1
1852 #define MAY_RMDIR 2
1854 /* Check whether a task can link, unlink, or rmdir a file/directory. */
1855 static int may_link(struct inode *dir,
1856 struct dentry *dentry,
1857 int kind)
1860 struct inode_security_struct *dsec, *isec;
1861 struct common_audit_data ad;
1862 u32 sid = current_sid();
1863 u32 av;
1864 int rc;
1866 dsec = inode_security(dir);
1867 isec = backing_inode_security(dentry);
1869 ad.type = LSM_AUDIT_DATA_DENTRY;
1870 ad.u.dentry = dentry;
1872 av = DIR__SEARCH;
1873 av |= (kind ? DIR__REMOVE_NAME : DIR__ADD_NAME);
1874 rc = avc_has_perm(&selinux_state,
1875 sid, dsec->sid, SECCLASS_DIR, av, &ad);
1876 if (rc)
1877 return rc;
1879 switch (kind) {
1880 case MAY_LINK:
1881 av = FILE__LINK;
1882 break;
1883 case MAY_UNLINK:
1884 av = FILE__UNLINK;
1885 break;
1886 case MAY_RMDIR:
1887 av = DIR__RMDIR;
1888 break;
1889 default:
1890 pr_warn("SELinux: %s: unrecognized kind %d\n",
1891 __func__, kind);
1892 return 0;
1895 rc = avc_has_perm(&selinux_state,
1896 sid, isec->sid, isec->sclass, av, &ad);
1897 return rc;
1900 static inline int may_rename(struct inode *old_dir,
1901 struct dentry *old_dentry,
1902 struct inode *new_dir,
1903 struct dentry *new_dentry)
1905 struct inode_security_struct *old_dsec, *new_dsec, *old_isec, *new_isec;
1906 struct common_audit_data ad;
1907 u32 sid = current_sid();
1908 u32 av;
1909 int old_is_dir, new_is_dir;
1910 int rc;
1912 old_dsec = inode_security(old_dir);
1913 old_isec = backing_inode_security(old_dentry);
1914 old_is_dir = d_is_dir(old_dentry);
1915 new_dsec = inode_security(new_dir);
1917 ad.type = LSM_AUDIT_DATA_DENTRY;
1919 ad.u.dentry = old_dentry;
1920 rc = avc_has_perm(&selinux_state,
1921 sid, old_dsec->sid, SECCLASS_DIR,
1922 DIR__REMOVE_NAME | DIR__SEARCH, &ad);
1923 if (rc)
1924 return rc;
1925 rc = avc_has_perm(&selinux_state,
1926 sid, old_isec->sid,
1927 old_isec->sclass, FILE__RENAME, &ad);
1928 if (rc)
1929 return rc;
1930 if (old_is_dir && new_dir != old_dir) {
1931 rc = avc_has_perm(&selinux_state,
1932 sid, old_isec->sid,
1933 old_isec->sclass, DIR__REPARENT, &ad);
1934 if (rc)
1935 return rc;
1938 ad.u.dentry = new_dentry;
1939 av = DIR__ADD_NAME | DIR__SEARCH;
1940 if (d_is_positive(new_dentry))
1941 av |= DIR__REMOVE_NAME;
1942 rc = avc_has_perm(&selinux_state,
1943 sid, new_dsec->sid, SECCLASS_DIR, av, &ad);
1944 if (rc)
1945 return rc;
1946 if (d_is_positive(new_dentry)) {
1947 new_isec = backing_inode_security(new_dentry);
1948 new_is_dir = d_is_dir(new_dentry);
1949 rc = avc_has_perm(&selinux_state,
1950 sid, new_isec->sid,
1951 new_isec->sclass,
1952 (new_is_dir ? DIR__RMDIR : FILE__UNLINK), &ad);
1953 if (rc)
1954 return rc;
1957 return 0;
1960 /* Check whether a task can perform a filesystem operation. */
1961 static int superblock_has_perm(const struct cred *cred,
1962 struct super_block *sb,
1963 u32 perms,
1964 struct common_audit_data *ad)
1966 struct superblock_security_struct *sbsec;
1967 u32 sid = cred_sid(cred);
1969 sbsec = sb->s_security;
1970 return avc_has_perm(&selinux_state,
1971 sid, sbsec->sid, SECCLASS_FILESYSTEM, perms, ad);
1974 /* Convert a Linux mode and permission mask to an access vector. */
1975 static inline u32 file_mask_to_av(int mode, int mask)
1977 u32 av = 0;
1979 if (!S_ISDIR(mode)) {
1980 if (mask & MAY_EXEC)
1981 av |= FILE__EXECUTE;
1982 if (mask & MAY_READ)
1983 av |= FILE__READ;
1985 if (mask & MAY_APPEND)
1986 av |= FILE__APPEND;
1987 else if (mask & MAY_WRITE)
1988 av |= FILE__WRITE;
1990 } else {
1991 if (mask & MAY_EXEC)
1992 av |= DIR__SEARCH;
1993 if (mask & MAY_WRITE)
1994 av |= DIR__WRITE;
1995 if (mask & MAY_READ)
1996 av |= DIR__READ;
1999 return av;
2002 /* Convert a Linux file to an access vector. */
2003 static inline u32 file_to_av(struct file *file)
2005 u32 av = 0;
2007 if (file->f_mode & FMODE_READ)
2008 av |= FILE__READ;
2009 if (file->f_mode & FMODE_WRITE) {
2010 if (file->f_flags & O_APPEND)
2011 av |= FILE__APPEND;
2012 else
2013 av |= FILE__WRITE;
2015 if (!av) {
2017 * Special file opened with flags 3 for ioctl-only use.
2019 av = FILE__IOCTL;
2022 return av;
2026 * Convert a file to an access vector and include the correct open
2027 * open permission.
2029 static inline u32 open_file_to_av(struct file *file)
2031 u32 av = file_to_av(file);
2032 struct inode *inode = file_inode(file);
2034 if (selinux_policycap_openperm() &&
2035 inode->i_sb->s_magic != SOCKFS_MAGIC)
2036 av |= FILE__OPEN;
2038 return av;
2041 /* Hook functions begin here. */
2043 static int selinux_binder_set_context_mgr(struct task_struct *mgr)
2045 u32 mysid = current_sid();
2046 u32 mgrsid = task_sid(mgr);
2048 return avc_has_perm(&selinux_state,
2049 mysid, mgrsid, SECCLASS_BINDER,
2050 BINDER__SET_CONTEXT_MGR, NULL);
2053 static int selinux_binder_transaction(struct task_struct *from,
2054 struct task_struct *to)
2056 u32 mysid = current_sid();
2057 u32 fromsid = task_sid(from);
2058 u32 tosid = task_sid(to);
2059 int rc;
2061 if (mysid != fromsid) {
2062 rc = avc_has_perm(&selinux_state,
2063 mysid, fromsid, SECCLASS_BINDER,
2064 BINDER__IMPERSONATE, NULL);
2065 if (rc)
2066 return rc;
2069 return avc_has_perm(&selinux_state,
2070 fromsid, tosid, SECCLASS_BINDER, BINDER__CALL,
2071 NULL);
2074 static int selinux_binder_transfer_binder(struct task_struct *from,
2075 struct task_struct *to)
2077 u32 fromsid = task_sid(from);
2078 u32 tosid = task_sid(to);
2080 return avc_has_perm(&selinux_state,
2081 fromsid, tosid, SECCLASS_BINDER, BINDER__TRANSFER,
2082 NULL);
2085 static int selinux_binder_transfer_file(struct task_struct *from,
2086 struct task_struct *to,
2087 struct file *file)
2089 u32 sid = task_sid(to);
2090 struct file_security_struct *fsec = selinux_file(file);
2091 struct dentry *dentry = file->f_path.dentry;
2092 struct inode_security_struct *isec;
2093 struct common_audit_data ad;
2094 int rc;
2096 ad.type = LSM_AUDIT_DATA_PATH;
2097 ad.u.path = file->f_path;
2099 if (sid != fsec->sid) {
2100 rc = avc_has_perm(&selinux_state,
2101 sid, fsec->sid,
2102 SECCLASS_FD,
2103 FD__USE,
2104 &ad);
2105 if (rc)
2106 return rc;
2109 #ifdef CONFIG_BPF_SYSCALL
2110 rc = bpf_fd_pass(file, sid);
2111 if (rc)
2112 return rc;
2113 #endif
2115 if (unlikely(IS_PRIVATE(d_backing_inode(dentry))))
2116 return 0;
2118 isec = backing_inode_security(dentry);
2119 return avc_has_perm(&selinux_state,
2120 sid, isec->sid, isec->sclass, file_to_av(file),
2121 &ad);
2124 static int selinux_ptrace_access_check(struct task_struct *child,
2125 unsigned int mode)
2127 u32 sid = current_sid();
2128 u32 csid = task_sid(child);
2130 if (mode & PTRACE_MODE_READ)
2131 return avc_has_perm(&selinux_state,
2132 sid, csid, SECCLASS_FILE, FILE__READ, NULL);
2134 return avc_has_perm(&selinux_state,
2135 sid, csid, SECCLASS_PROCESS, PROCESS__PTRACE, NULL);
2138 static int selinux_ptrace_traceme(struct task_struct *parent)
2140 return avc_has_perm(&selinux_state,
2141 task_sid(parent), current_sid(), SECCLASS_PROCESS,
2142 PROCESS__PTRACE, NULL);
2145 static int selinux_capget(struct task_struct *target, kernel_cap_t *effective,
2146 kernel_cap_t *inheritable, kernel_cap_t *permitted)
2148 return avc_has_perm(&selinux_state,
2149 current_sid(), task_sid(target), SECCLASS_PROCESS,
2150 PROCESS__GETCAP, NULL);
2153 static int selinux_capset(struct cred *new, const struct cred *old,
2154 const kernel_cap_t *effective,
2155 const kernel_cap_t *inheritable,
2156 const kernel_cap_t *permitted)
2158 return avc_has_perm(&selinux_state,
2159 cred_sid(old), cred_sid(new), SECCLASS_PROCESS,
2160 PROCESS__SETCAP, NULL);
2164 * (This comment used to live with the selinux_task_setuid hook,
2165 * which was removed).
2167 * Since setuid only affects the current process, and since the SELinux
2168 * controls are not based on the Linux identity attributes, SELinux does not
2169 * need to control this operation. However, SELinux does control the use of
2170 * the CAP_SETUID and CAP_SETGID capabilities using the capable hook.
2173 static int selinux_capable(const struct cred *cred, struct user_namespace *ns,
2174 int cap, unsigned int opts)
2176 return cred_has_capability(cred, cap, opts, ns == &init_user_ns);
2179 static int selinux_quotactl(int cmds, int type, int id, struct super_block *sb)
2181 const struct cred *cred = current_cred();
2182 int rc = 0;
2184 if (!sb)
2185 return 0;
2187 switch (cmds) {
2188 case Q_SYNC:
2189 case Q_QUOTAON:
2190 case Q_QUOTAOFF:
2191 case Q_SETINFO:
2192 case Q_SETQUOTA:
2193 rc = superblock_has_perm(cred, sb, FILESYSTEM__QUOTAMOD, NULL);
2194 break;
2195 case Q_GETFMT:
2196 case Q_GETINFO:
2197 case Q_GETQUOTA:
2198 rc = superblock_has_perm(cred, sb, FILESYSTEM__QUOTAGET, NULL);
2199 break;
2200 default:
2201 rc = 0; /* let the kernel handle invalid cmds */
2202 break;
2204 return rc;
2207 static int selinux_quota_on(struct dentry *dentry)
2209 const struct cred *cred = current_cred();
2211 return dentry_has_perm(cred, dentry, FILE__QUOTAON);
2214 static int selinux_syslog(int type)
2216 switch (type) {
2217 case SYSLOG_ACTION_READ_ALL: /* Read last kernel messages */
2218 case SYSLOG_ACTION_SIZE_BUFFER: /* Return size of the log buffer */
2219 return avc_has_perm(&selinux_state,
2220 current_sid(), SECINITSID_KERNEL,
2221 SECCLASS_SYSTEM, SYSTEM__SYSLOG_READ, NULL);
2222 case SYSLOG_ACTION_CONSOLE_OFF: /* Disable logging to console */
2223 case SYSLOG_ACTION_CONSOLE_ON: /* Enable logging to console */
2224 /* Set level of messages printed to console */
2225 case SYSLOG_ACTION_CONSOLE_LEVEL:
2226 return avc_has_perm(&selinux_state,
2227 current_sid(), SECINITSID_KERNEL,
2228 SECCLASS_SYSTEM, SYSTEM__SYSLOG_CONSOLE,
2229 NULL);
2231 /* All other syslog types */
2232 return avc_has_perm(&selinux_state,
2233 current_sid(), SECINITSID_KERNEL,
2234 SECCLASS_SYSTEM, SYSTEM__SYSLOG_MOD, NULL);
2238 * Check that a process has enough memory to allocate a new virtual
2239 * mapping. 0 means there is enough memory for the allocation to
2240 * succeed and -ENOMEM implies there is not.
2242 * Do not audit the selinux permission check, as this is applied to all
2243 * processes that allocate mappings.
2245 static int selinux_vm_enough_memory(struct mm_struct *mm, long pages)
2247 int rc, cap_sys_admin = 0;
2249 rc = cred_has_capability(current_cred(), CAP_SYS_ADMIN,
2250 CAP_OPT_NOAUDIT, true);
2251 if (rc == 0)
2252 cap_sys_admin = 1;
2254 return cap_sys_admin;
2257 /* binprm security operations */
2259 static u32 ptrace_parent_sid(void)
2261 u32 sid = 0;
2262 struct task_struct *tracer;
2264 rcu_read_lock();
2265 tracer = ptrace_parent(current);
2266 if (tracer)
2267 sid = task_sid(tracer);
2268 rcu_read_unlock();
2270 return sid;
2273 static int check_nnp_nosuid(const struct linux_binprm *bprm,
2274 const struct task_security_struct *old_tsec,
2275 const struct task_security_struct *new_tsec)
2277 int nnp = (bprm->unsafe & LSM_UNSAFE_NO_NEW_PRIVS);
2278 int nosuid = !mnt_may_suid(bprm->file->f_path.mnt);
2279 int rc;
2280 u32 av;
2282 if (!nnp && !nosuid)
2283 return 0; /* neither NNP nor nosuid */
2285 if (new_tsec->sid == old_tsec->sid)
2286 return 0; /* No change in credentials */
2289 * If the policy enables the nnp_nosuid_transition policy capability,
2290 * then we permit transitions under NNP or nosuid if the
2291 * policy allows the corresponding permission between
2292 * the old and new contexts.
2294 if (selinux_policycap_nnp_nosuid_transition()) {
2295 av = 0;
2296 if (nnp)
2297 av |= PROCESS2__NNP_TRANSITION;
2298 if (nosuid)
2299 av |= PROCESS2__NOSUID_TRANSITION;
2300 rc = avc_has_perm(&selinux_state,
2301 old_tsec->sid, new_tsec->sid,
2302 SECCLASS_PROCESS2, av, NULL);
2303 if (!rc)
2304 return 0;
2308 * We also permit NNP or nosuid transitions to bounded SIDs,
2309 * i.e. SIDs that are guaranteed to only be allowed a subset
2310 * of the permissions of the current SID.
2312 rc = security_bounded_transition(&selinux_state, old_tsec->sid,
2313 new_tsec->sid);
2314 if (!rc)
2315 return 0;
2318 * On failure, preserve the errno values for NNP vs nosuid.
2319 * NNP: Operation not permitted for caller.
2320 * nosuid: Permission denied to file.
2322 if (nnp)
2323 return -EPERM;
2324 return -EACCES;
2327 static int selinux_bprm_set_creds(struct linux_binprm *bprm)
2329 const struct task_security_struct *old_tsec;
2330 struct task_security_struct *new_tsec;
2331 struct inode_security_struct *isec;
2332 struct common_audit_data ad;
2333 struct inode *inode = file_inode(bprm->file);
2334 int rc;
2336 /* SELinux context only depends on initial program or script and not
2337 * the script interpreter */
2338 if (bprm->called_set_creds)
2339 return 0;
2341 old_tsec = selinux_cred(current_cred());
2342 new_tsec = selinux_cred(bprm->cred);
2343 isec = inode_security(inode);
2345 /* Default to the current task SID. */
2346 new_tsec->sid = old_tsec->sid;
2347 new_tsec->osid = old_tsec->sid;
2349 /* Reset fs, key, and sock SIDs on execve. */
2350 new_tsec->create_sid = 0;
2351 new_tsec->keycreate_sid = 0;
2352 new_tsec->sockcreate_sid = 0;
2354 if (old_tsec->exec_sid) {
2355 new_tsec->sid = old_tsec->exec_sid;
2356 /* Reset exec SID on execve. */
2357 new_tsec->exec_sid = 0;
2359 /* Fail on NNP or nosuid if not an allowed transition. */
2360 rc = check_nnp_nosuid(bprm, old_tsec, new_tsec);
2361 if (rc)
2362 return rc;
2363 } else {
2364 /* Check for a default transition on this program. */
2365 rc = security_transition_sid(&selinux_state, old_tsec->sid,
2366 isec->sid, SECCLASS_PROCESS, NULL,
2367 &new_tsec->sid);
2368 if (rc)
2369 return rc;
2372 * Fallback to old SID on NNP or nosuid if not an allowed
2373 * transition.
2375 rc = check_nnp_nosuid(bprm, old_tsec, new_tsec);
2376 if (rc)
2377 new_tsec->sid = old_tsec->sid;
2380 ad.type = LSM_AUDIT_DATA_FILE;
2381 ad.u.file = bprm->file;
2383 if (new_tsec->sid == old_tsec->sid) {
2384 rc = avc_has_perm(&selinux_state,
2385 old_tsec->sid, isec->sid,
2386 SECCLASS_FILE, FILE__EXECUTE_NO_TRANS, &ad);
2387 if (rc)
2388 return rc;
2389 } else {
2390 /* Check permissions for the transition. */
2391 rc = avc_has_perm(&selinux_state,
2392 old_tsec->sid, new_tsec->sid,
2393 SECCLASS_PROCESS, PROCESS__TRANSITION, &ad);
2394 if (rc)
2395 return rc;
2397 rc = avc_has_perm(&selinux_state,
2398 new_tsec->sid, isec->sid,
2399 SECCLASS_FILE, FILE__ENTRYPOINT, &ad);
2400 if (rc)
2401 return rc;
2403 /* Check for shared state */
2404 if (bprm->unsafe & LSM_UNSAFE_SHARE) {
2405 rc = avc_has_perm(&selinux_state,
2406 old_tsec->sid, new_tsec->sid,
2407 SECCLASS_PROCESS, PROCESS__SHARE,
2408 NULL);
2409 if (rc)
2410 return -EPERM;
2413 /* Make sure that anyone attempting to ptrace over a task that
2414 * changes its SID has the appropriate permit */
2415 if (bprm->unsafe & LSM_UNSAFE_PTRACE) {
2416 u32 ptsid = ptrace_parent_sid();
2417 if (ptsid != 0) {
2418 rc = avc_has_perm(&selinux_state,
2419 ptsid, new_tsec->sid,
2420 SECCLASS_PROCESS,
2421 PROCESS__PTRACE, NULL);
2422 if (rc)
2423 return -EPERM;
2427 /* Clear any possibly unsafe personality bits on exec: */
2428 bprm->per_clear |= PER_CLEAR_ON_SETID;
2430 /* Enable secure mode for SIDs transitions unless
2431 the noatsecure permission is granted between
2432 the two SIDs, i.e. ahp returns 0. */
2433 rc = avc_has_perm(&selinux_state,
2434 old_tsec->sid, new_tsec->sid,
2435 SECCLASS_PROCESS, PROCESS__NOATSECURE,
2436 NULL);
2437 bprm->secureexec |= !!rc;
2440 return 0;
2443 static int match_file(const void *p, struct file *file, unsigned fd)
2445 return file_has_perm(p, file, file_to_av(file)) ? fd + 1 : 0;
2448 /* Derived from fs/exec.c:flush_old_files. */
2449 static inline void flush_unauthorized_files(const struct cred *cred,
2450 struct files_struct *files)
2452 struct file *file, *devnull = NULL;
2453 struct tty_struct *tty;
2454 int drop_tty = 0;
2455 unsigned n;
2457 tty = get_current_tty();
2458 if (tty) {
2459 spin_lock(&tty->files_lock);
2460 if (!list_empty(&tty->tty_files)) {
2461 struct tty_file_private *file_priv;
2463 /* Revalidate access to controlling tty.
2464 Use file_path_has_perm on the tty path directly
2465 rather than using file_has_perm, as this particular
2466 open file may belong to another process and we are
2467 only interested in the inode-based check here. */
2468 file_priv = list_first_entry(&tty->tty_files,
2469 struct tty_file_private, list);
2470 file = file_priv->file;
2471 if (file_path_has_perm(cred, file, FILE__READ | FILE__WRITE))
2472 drop_tty = 1;
2474 spin_unlock(&tty->files_lock);
2475 tty_kref_put(tty);
2477 /* Reset controlling tty. */
2478 if (drop_tty)
2479 no_tty();
2481 /* Revalidate access to inherited open files. */
2482 n = iterate_fd(files, 0, match_file, cred);
2483 if (!n) /* none found? */
2484 return;
2486 devnull = dentry_open(&selinux_null, O_RDWR, cred);
2487 if (IS_ERR(devnull))
2488 devnull = NULL;
2489 /* replace all the matching ones with this */
2490 do {
2491 replace_fd(n - 1, devnull, 0);
2492 } while ((n = iterate_fd(files, n, match_file, cred)) != 0);
2493 if (devnull)
2494 fput(devnull);
2498 * Prepare a process for imminent new credential changes due to exec
2500 static void selinux_bprm_committing_creds(struct linux_binprm *bprm)
2502 struct task_security_struct *new_tsec;
2503 struct rlimit *rlim, *initrlim;
2504 int rc, i;
2506 new_tsec = selinux_cred(bprm->cred);
2507 if (new_tsec->sid == new_tsec->osid)
2508 return;
2510 /* Close files for which the new task SID is not authorized. */
2511 flush_unauthorized_files(bprm->cred, current->files);
2513 /* Always clear parent death signal on SID transitions. */
2514 current->pdeath_signal = 0;
2516 /* Check whether the new SID can inherit resource limits from the old
2517 * SID. If not, reset all soft limits to the lower of the current
2518 * task's hard limit and the init task's soft limit.
2520 * Note that the setting of hard limits (even to lower them) can be
2521 * controlled by the setrlimit check. The inclusion of the init task's
2522 * soft limit into the computation is to avoid resetting soft limits
2523 * higher than the default soft limit for cases where the default is
2524 * lower than the hard limit, e.g. RLIMIT_CORE or RLIMIT_STACK.
2526 rc = avc_has_perm(&selinux_state,
2527 new_tsec->osid, new_tsec->sid, SECCLASS_PROCESS,
2528 PROCESS__RLIMITINH, NULL);
2529 if (rc) {
2530 /* protect against do_prlimit() */
2531 task_lock(current);
2532 for (i = 0; i < RLIM_NLIMITS; i++) {
2533 rlim = current->signal->rlim + i;
2534 initrlim = init_task.signal->rlim + i;
2535 rlim->rlim_cur = min(rlim->rlim_max, initrlim->rlim_cur);
2537 task_unlock(current);
2538 if (IS_ENABLED(CONFIG_POSIX_TIMERS))
2539 update_rlimit_cpu(current, rlimit(RLIMIT_CPU));
2544 * Clean up the process immediately after the installation of new credentials
2545 * due to exec
2547 static void selinux_bprm_committed_creds(struct linux_binprm *bprm)
2549 const struct task_security_struct *tsec = selinux_cred(current_cred());
2550 struct itimerval itimer;
2551 u32 osid, sid;
2552 int rc, i;
2554 osid = tsec->osid;
2555 sid = tsec->sid;
2557 if (sid == osid)
2558 return;
2560 /* Check whether the new SID can inherit signal state from the old SID.
2561 * If not, clear itimers to avoid subsequent signal generation and
2562 * flush and unblock signals.
2564 * This must occur _after_ the task SID has been updated so that any
2565 * kill done after the flush will be checked against the new SID.
2567 rc = avc_has_perm(&selinux_state,
2568 osid, sid, SECCLASS_PROCESS, PROCESS__SIGINH, NULL);
2569 if (rc) {
2570 if (IS_ENABLED(CONFIG_POSIX_TIMERS)) {
2571 memset(&itimer, 0, sizeof itimer);
2572 for (i = 0; i < 3; i++)
2573 do_setitimer(i, &itimer, NULL);
2575 spin_lock_irq(&current->sighand->siglock);
2576 if (!fatal_signal_pending(current)) {
2577 flush_sigqueue(&current->pending);
2578 flush_sigqueue(&current->signal->shared_pending);
2579 flush_signal_handlers(current, 1);
2580 sigemptyset(&current->blocked);
2581 recalc_sigpending();
2583 spin_unlock_irq(&current->sighand->siglock);
2586 /* Wake up the parent if it is waiting so that it can recheck
2587 * wait permission to the new task SID. */
2588 read_lock(&tasklist_lock);
2589 __wake_up_parent(current, current->real_parent);
2590 read_unlock(&tasklist_lock);
2593 /* superblock security operations */
2595 static int selinux_sb_alloc_security(struct super_block *sb)
2597 return superblock_alloc_security(sb);
2600 static void selinux_sb_free_security(struct super_block *sb)
2602 superblock_free_security(sb);
2605 static inline int opt_len(const char *s)
2607 bool open_quote = false;
2608 int len;
2609 char c;
2611 for (len = 0; (c = s[len]) != '\0'; len++) {
2612 if (c == '"')
2613 open_quote = !open_quote;
2614 if (c == ',' && !open_quote)
2615 break;
2617 return len;
2620 static int selinux_sb_eat_lsm_opts(char *options, void **mnt_opts)
2622 char *from = options;
2623 char *to = options;
2624 bool first = true;
2625 int rc;
2627 while (1) {
2628 int len = opt_len(from);
2629 int token;
2630 char *arg = NULL;
2632 token = match_opt_prefix(from, len, &arg);
2634 if (token != Opt_error) {
2635 char *p, *q;
2637 /* strip quotes */
2638 if (arg) {
2639 for (p = q = arg; p < from + len; p++) {
2640 char c = *p;
2641 if (c != '"')
2642 *q++ = c;
2644 arg = kmemdup_nul(arg, q - arg, GFP_KERNEL);
2645 if (!arg) {
2646 rc = -ENOMEM;
2647 goto free_opt;
2650 rc = selinux_add_opt(token, arg, mnt_opts);
2651 if (unlikely(rc)) {
2652 kfree(arg);
2653 goto free_opt;
2655 } else {
2656 if (!first) { // copy with preceding comma
2657 from--;
2658 len++;
2660 if (to != from)
2661 memmove(to, from, len);
2662 to += len;
2663 first = false;
2665 if (!from[len])
2666 break;
2667 from += len + 1;
2669 *to = '\0';
2670 return 0;
2672 free_opt:
2673 if (*mnt_opts) {
2674 selinux_free_mnt_opts(*mnt_opts);
2675 *mnt_opts = NULL;
2677 return rc;
2680 static int selinux_sb_remount(struct super_block *sb, void *mnt_opts)
2682 struct selinux_mnt_opts *opts = mnt_opts;
2683 struct superblock_security_struct *sbsec = sb->s_security;
2684 u32 sid;
2685 int rc;
2687 if (!(sbsec->flags & SE_SBINITIALIZED))
2688 return 0;
2690 if (!opts)
2691 return 0;
2693 if (opts->fscontext) {
2694 rc = parse_sid(sb, opts->fscontext, &sid);
2695 if (rc)
2696 return rc;
2697 if (bad_option(sbsec, FSCONTEXT_MNT, sbsec->sid, sid))
2698 goto out_bad_option;
2700 if (opts->context) {
2701 rc = parse_sid(sb, opts->context, &sid);
2702 if (rc)
2703 return rc;
2704 if (bad_option(sbsec, CONTEXT_MNT, sbsec->mntpoint_sid, sid))
2705 goto out_bad_option;
2707 if (opts->rootcontext) {
2708 struct inode_security_struct *root_isec;
2709 root_isec = backing_inode_security(sb->s_root);
2710 rc = parse_sid(sb, opts->rootcontext, &sid);
2711 if (rc)
2712 return rc;
2713 if (bad_option(sbsec, ROOTCONTEXT_MNT, root_isec->sid, sid))
2714 goto out_bad_option;
2716 if (opts->defcontext) {
2717 rc = parse_sid(sb, opts->defcontext, &sid);
2718 if (rc)
2719 return rc;
2720 if (bad_option(sbsec, DEFCONTEXT_MNT, sbsec->def_sid, sid))
2721 goto out_bad_option;
2723 return 0;
2725 out_bad_option:
2726 pr_warn("SELinux: unable to change security options "
2727 "during remount (dev %s, type=%s)\n", sb->s_id,
2728 sb->s_type->name);
2729 return -EINVAL;
2732 static int selinux_sb_kern_mount(struct super_block *sb)
2734 const struct cred *cred = current_cred();
2735 struct common_audit_data ad;
2737 ad.type = LSM_AUDIT_DATA_DENTRY;
2738 ad.u.dentry = sb->s_root;
2739 return superblock_has_perm(cred, sb, FILESYSTEM__MOUNT, &ad);
2742 static int selinux_sb_statfs(struct dentry *dentry)
2744 const struct cred *cred = current_cred();
2745 struct common_audit_data ad;
2747 ad.type = LSM_AUDIT_DATA_DENTRY;
2748 ad.u.dentry = dentry->d_sb->s_root;
2749 return superblock_has_perm(cred, dentry->d_sb, FILESYSTEM__GETATTR, &ad);
2752 static int selinux_mount(const char *dev_name,
2753 const struct path *path,
2754 const char *type,
2755 unsigned long flags,
2756 void *data)
2758 const struct cred *cred = current_cred();
2760 if (flags & MS_REMOUNT)
2761 return superblock_has_perm(cred, path->dentry->d_sb,
2762 FILESYSTEM__REMOUNT, NULL);
2763 else
2764 return path_has_perm(cred, path, FILE__MOUNTON);
2767 static int selinux_umount(struct vfsmount *mnt, int flags)
2769 const struct cred *cred = current_cred();
2771 return superblock_has_perm(cred, mnt->mnt_sb,
2772 FILESYSTEM__UNMOUNT, NULL);
2775 static int selinux_fs_context_dup(struct fs_context *fc,
2776 struct fs_context *src_fc)
2778 const struct selinux_mnt_opts *src = src_fc->security;
2779 struct selinux_mnt_opts *opts;
2781 if (!src)
2782 return 0;
2784 fc->security = kzalloc(sizeof(struct selinux_mnt_opts), GFP_KERNEL);
2785 if (!fc->security)
2786 return -ENOMEM;
2788 opts = fc->security;
2790 if (src->fscontext) {
2791 opts->fscontext = kstrdup(src->fscontext, GFP_KERNEL);
2792 if (!opts->fscontext)
2793 return -ENOMEM;
2795 if (src->context) {
2796 opts->context = kstrdup(src->context, GFP_KERNEL);
2797 if (!opts->context)
2798 return -ENOMEM;
2800 if (src->rootcontext) {
2801 opts->rootcontext = kstrdup(src->rootcontext, GFP_KERNEL);
2802 if (!opts->rootcontext)
2803 return -ENOMEM;
2805 if (src->defcontext) {
2806 opts->defcontext = kstrdup(src->defcontext, GFP_KERNEL);
2807 if (!opts->defcontext)
2808 return -ENOMEM;
2810 return 0;
2813 static const struct fs_parameter_spec selinux_param_specs[] = {
2814 fsparam_string(CONTEXT_STR, Opt_context),
2815 fsparam_string(DEFCONTEXT_STR, Opt_defcontext),
2816 fsparam_string(FSCONTEXT_STR, Opt_fscontext),
2817 fsparam_string(ROOTCONTEXT_STR, Opt_rootcontext),
2818 fsparam_flag (SECLABEL_STR, Opt_seclabel),
2822 static const struct fs_parameter_description selinux_fs_parameters = {
2823 .name = "SELinux",
2824 .specs = selinux_param_specs,
2827 static int selinux_fs_context_parse_param(struct fs_context *fc,
2828 struct fs_parameter *param)
2830 struct fs_parse_result result;
2831 int opt, rc;
2833 opt = fs_parse(fc, &selinux_fs_parameters, param, &result);
2834 if (opt < 0)
2835 return opt;
2837 rc = selinux_add_opt(opt, param->string, &fc->security);
2838 if (!rc) {
2839 param->string = NULL;
2840 rc = 1;
2842 return rc;
2845 /* inode security operations */
2847 static int selinux_inode_alloc_security(struct inode *inode)
2849 return inode_alloc_security(inode);
2852 static void selinux_inode_free_security(struct inode *inode)
2854 inode_free_security(inode);
2857 static int selinux_dentry_init_security(struct dentry *dentry, int mode,
2858 const struct qstr *name, void **ctx,
2859 u32 *ctxlen)
2861 u32 newsid;
2862 int rc;
2864 rc = selinux_determine_inode_label(selinux_cred(current_cred()),
2865 d_inode(dentry->d_parent), name,
2866 inode_mode_to_security_class(mode),
2867 &newsid);
2868 if (rc)
2869 return rc;
2871 return security_sid_to_context(&selinux_state, newsid, (char **)ctx,
2872 ctxlen);
2875 static int selinux_dentry_create_files_as(struct dentry *dentry, int mode,
2876 struct qstr *name,
2877 const struct cred *old,
2878 struct cred *new)
2880 u32 newsid;
2881 int rc;
2882 struct task_security_struct *tsec;
2884 rc = selinux_determine_inode_label(selinux_cred(old),
2885 d_inode(dentry->d_parent), name,
2886 inode_mode_to_security_class(mode),
2887 &newsid);
2888 if (rc)
2889 return rc;
2891 tsec = selinux_cred(new);
2892 tsec->create_sid = newsid;
2893 return 0;
2896 static int selinux_inode_init_security(struct inode *inode, struct inode *dir,
2897 const struct qstr *qstr,
2898 const char **name,
2899 void **value, size_t *len)
2901 const struct task_security_struct *tsec = selinux_cred(current_cred());
2902 struct superblock_security_struct *sbsec;
2903 u32 newsid, clen;
2904 int rc;
2905 char *context;
2907 sbsec = dir->i_sb->s_security;
2909 newsid = tsec->create_sid;
2911 rc = selinux_determine_inode_label(selinux_cred(current_cred()),
2912 dir, qstr,
2913 inode_mode_to_security_class(inode->i_mode),
2914 &newsid);
2915 if (rc)
2916 return rc;
2918 /* Possibly defer initialization to selinux_complete_init. */
2919 if (sbsec->flags & SE_SBINITIALIZED) {
2920 struct inode_security_struct *isec = selinux_inode(inode);
2921 isec->sclass = inode_mode_to_security_class(inode->i_mode);
2922 isec->sid = newsid;
2923 isec->initialized = LABEL_INITIALIZED;
2926 if (!selinux_state.initialized || !(sbsec->flags & SBLABEL_MNT))
2927 return -EOPNOTSUPP;
2929 if (name)
2930 *name = XATTR_SELINUX_SUFFIX;
2932 if (value && len) {
2933 rc = security_sid_to_context_force(&selinux_state, newsid,
2934 &context, &clen);
2935 if (rc)
2936 return rc;
2937 *value = context;
2938 *len = clen;
2941 return 0;
2944 static int selinux_inode_create(struct inode *dir, struct dentry *dentry, umode_t mode)
2946 return may_create(dir, dentry, SECCLASS_FILE);
2949 static int selinux_inode_link(struct dentry *old_dentry, struct inode *dir, struct dentry *new_dentry)
2951 return may_link(dir, old_dentry, MAY_LINK);
2954 static int selinux_inode_unlink(struct inode *dir, struct dentry *dentry)
2956 return may_link(dir, dentry, MAY_UNLINK);
2959 static int selinux_inode_symlink(struct inode *dir, struct dentry *dentry, const char *name)
2961 return may_create(dir, dentry, SECCLASS_LNK_FILE);
2964 static int selinux_inode_mkdir(struct inode *dir, struct dentry *dentry, umode_t mask)
2966 return may_create(dir, dentry, SECCLASS_DIR);
2969 static int selinux_inode_rmdir(struct inode *dir, struct dentry *dentry)
2971 return may_link(dir, dentry, MAY_RMDIR);
2974 static int selinux_inode_mknod(struct inode *dir, struct dentry *dentry, umode_t mode, dev_t dev)
2976 return may_create(dir, dentry, inode_mode_to_security_class(mode));
2979 static int selinux_inode_rename(struct inode *old_inode, struct dentry *old_dentry,
2980 struct inode *new_inode, struct dentry *new_dentry)
2982 return may_rename(old_inode, old_dentry, new_inode, new_dentry);
2985 static int selinux_inode_readlink(struct dentry *dentry)
2987 const struct cred *cred = current_cred();
2989 return dentry_has_perm(cred, dentry, FILE__READ);
2992 static int selinux_inode_follow_link(struct dentry *dentry, struct inode *inode,
2993 bool rcu)
2995 const struct cred *cred = current_cred();
2996 struct common_audit_data ad;
2997 struct inode_security_struct *isec;
2998 u32 sid;
3000 validate_creds(cred);
3002 ad.type = LSM_AUDIT_DATA_DENTRY;
3003 ad.u.dentry = dentry;
3004 sid = cred_sid(cred);
3005 isec = inode_security_rcu(inode, rcu);
3006 if (IS_ERR(isec))
3007 return PTR_ERR(isec);
3009 return avc_has_perm(&selinux_state,
3010 sid, isec->sid, isec->sclass, FILE__READ, &ad);
3013 static noinline int audit_inode_permission(struct inode *inode,
3014 u32 perms, u32 audited, u32 denied,
3015 int result,
3016 unsigned flags)
3018 struct common_audit_data ad;
3019 struct inode_security_struct *isec = selinux_inode(inode);
3020 int rc;
3022 ad.type = LSM_AUDIT_DATA_INODE;
3023 ad.u.inode = inode;
3025 rc = slow_avc_audit(&selinux_state,
3026 current_sid(), isec->sid, isec->sclass, perms,
3027 audited, denied, result, &ad, flags);
3028 if (rc)
3029 return rc;
3030 return 0;
3033 static int selinux_inode_permission(struct inode *inode, int mask)
3035 const struct cred *cred = current_cred();
3036 u32 perms;
3037 bool from_access;
3038 unsigned flags = mask & MAY_NOT_BLOCK;
3039 struct inode_security_struct *isec;
3040 u32 sid;
3041 struct av_decision avd;
3042 int rc, rc2;
3043 u32 audited, denied;
3045 from_access = mask & MAY_ACCESS;
3046 mask &= (MAY_READ|MAY_WRITE|MAY_EXEC|MAY_APPEND);
3048 /* No permission to check. Existence test. */
3049 if (!mask)
3050 return 0;
3052 validate_creds(cred);
3054 if (unlikely(IS_PRIVATE(inode)))
3055 return 0;
3057 perms = file_mask_to_av(inode->i_mode, mask);
3059 sid = cred_sid(cred);
3060 isec = inode_security_rcu(inode, flags & MAY_NOT_BLOCK);
3061 if (IS_ERR(isec))
3062 return PTR_ERR(isec);
3064 rc = avc_has_perm_noaudit(&selinux_state,
3065 sid, isec->sid, isec->sclass, perms,
3066 (flags & MAY_NOT_BLOCK) ? AVC_NONBLOCKING : 0,
3067 &avd);
3068 audited = avc_audit_required(perms, &avd, rc,
3069 from_access ? FILE__AUDIT_ACCESS : 0,
3070 &denied);
3071 if (likely(!audited))
3072 return rc;
3074 rc2 = audit_inode_permission(inode, perms, audited, denied, rc, flags);
3075 if (rc2)
3076 return rc2;
3077 return rc;
3080 static int selinux_inode_setattr(struct dentry *dentry, struct iattr *iattr)
3082 const struct cred *cred = current_cred();
3083 struct inode *inode = d_backing_inode(dentry);
3084 unsigned int ia_valid = iattr->ia_valid;
3085 __u32 av = FILE__WRITE;
3087 /* ATTR_FORCE is just used for ATTR_KILL_S[UG]ID. */
3088 if (ia_valid & ATTR_FORCE) {
3089 ia_valid &= ~(ATTR_KILL_SUID | ATTR_KILL_SGID | ATTR_MODE |
3090 ATTR_FORCE);
3091 if (!ia_valid)
3092 return 0;
3095 if (ia_valid & (ATTR_MODE | ATTR_UID | ATTR_GID |
3096 ATTR_ATIME_SET | ATTR_MTIME_SET | ATTR_TIMES_SET))
3097 return dentry_has_perm(cred, dentry, FILE__SETATTR);
3099 if (selinux_policycap_openperm() &&
3100 inode->i_sb->s_magic != SOCKFS_MAGIC &&
3101 (ia_valid & ATTR_SIZE) &&
3102 !(ia_valid & ATTR_FILE))
3103 av |= FILE__OPEN;
3105 return dentry_has_perm(cred, dentry, av);
3108 static int selinux_inode_getattr(const struct path *path)
3110 return path_has_perm(current_cred(), path, FILE__GETATTR);
3113 static bool has_cap_mac_admin(bool audit)
3115 const struct cred *cred = current_cred();
3116 unsigned int opts = audit ? CAP_OPT_NONE : CAP_OPT_NOAUDIT;
3118 if (cap_capable(cred, &init_user_ns, CAP_MAC_ADMIN, opts))
3119 return false;
3120 if (cred_has_capability(cred, CAP_MAC_ADMIN, opts, true))
3121 return false;
3122 return true;
3125 static int selinux_inode_setxattr(struct dentry *dentry, const char *name,
3126 const void *value, size_t size, int flags)
3128 struct inode *inode = d_backing_inode(dentry);
3129 struct inode_security_struct *isec;
3130 struct superblock_security_struct *sbsec;
3131 struct common_audit_data ad;
3132 u32 newsid, sid = current_sid();
3133 int rc = 0;
3135 if (strcmp(name, XATTR_NAME_SELINUX)) {
3136 rc = cap_inode_setxattr(dentry, name, value, size, flags);
3137 if (rc)
3138 return rc;
3140 /* Not an attribute we recognize, so just check the
3141 ordinary setattr permission. */
3142 return dentry_has_perm(current_cred(), dentry, FILE__SETATTR);
3145 sbsec = inode->i_sb->s_security;
3146 if (!(sbsec->flags & SBLABEL_MNT))
3147 return -EOPNOTSUPP;
3149 if (!inode_owner_or_capable(inode))
3150 return -EPERM;
3152 ad.type = LSM_AUDIT_DATA_DENTRY;
3153 ad.u.dentry = dentry;
3155 isec = backing_inode_security(dentry);
3156 rc = avc_has_perm(&selinux_state,
3157 sid, isec->sid, isec->sclass,
3158 FILE__RELABELFROM, &ad);
3159 if (rc)
3160 return rc;
3162 rc = security_context_to_sid(&selinux_state, value, size, &newsid,
3163 GFP_KERNEL);
3164 if (rc == -EINVAL) {
3165 if (!has_cap_mac_admin(true)) {
3166 struct audit_buffer *ab;
3167 size_t audit_size;
3169 /* We strip a nul only if it is at the end, otherwise the
3170 * context contains a nul and we should audit that */
3171 if (value) {
3172 const char *str = value;
3174 if (str[size - 1] == '\0')
3175 audit_size = size - 1;
3176 else
3177 audit_size = size;
3178 } else {
3179 audit_size = 0;
3181 ab = audit_log_start(audit_context(),
3182 GFP_ATOMIC, AUDIT_SELINUX_ERR);
3183 audit_log_format(ab, "op=setxattr invalid_context=");
3184 audit_log_n_untrustedstring(ab, value, audit_size);
3185 audit_log_end(ab);
3187 return rc;
3189 rc = security_context_to_sid_force(&selinux_state, value,
3190 size, &newsid);
3192 if (rc)
3193 return rc;
3195 rc = avc_has_perm(&selinux_state,
3196 sid, newsid, isec->sclass,
3197 FILE__RELABELTO, &ad);
3198 if (rc)
3199 return rc;
3201 rc = security_validate_transition(&selinux_state, isec->sid, newsid,
3202 sid, isec->sclass);
3203 if (rc)
3204 return rc;
3206 return avc_has_perm(&selinux_state,
3207 newsid,
3208 sbsec->sid,
3209 SECCLASS_FILESYSTEM,
3210 FILESYSTEM__ASSOCIATE,
3211 &ad);
3214 static void selinux_inode_post_setxattr(struct dentry *dentry, const char *name,
3215 const void *value, size_t size,
3216 int flags)
3218 struct inode *inode = d_backing_inode(dentry);
3219 struct inode_security_struct *isec;
3220 u32 newsid;
3221 int rc;
3223 if (strcmp(name, XATTR_NAME_SELINUX)) {
3224 /* Not an attribute we recognize, so nothing to do. */
3225 return;
3228 rc = security_context_to_sid_force(&selinux_state, value, size,
3229 &newsid);
3230 if (rc) {
3231 pr_err("SELinux: unable to map context to SID"
3232 "for (%s, %lu), rc=%d\n",
3233 inode->i_sb->s_id, inode->i_ino, -rc);
3234 return;
3237 isec = backing_inode_security(dentry);
3238 spin_lock(&isec->lock);
3239 isec->sclass = inode_mode_to_security_class(inode->i_mode);
3240 isec->sid = newsid;
3241 isec->initialized = LABEL_INITIALIZED;
3242 spin_unlock(&isec->lock);
3244 return;
3247 static int selinux_inode_getxattr(struct dentry *dentry, const char *name)
3249 const struct cred *cred = current_cred();
3251 return dentry_has_perm(cred, dentry, FILE__GETATTR);
3254 static int selinux_inode_listxattr(struct dentry *dentry)
3256 const struct cred *cred = current_cred();
3258 return dentry_has_perm(cred, dentry, FILE__GETATTR);
3261 static int selinux_inode_removexattr(struct dentry *dentry, const char *name)
3263 if (strcmp(name, XATTR_NAME_SELINUX)) {
3264 int rc = cap_inode_removexattr(dentry, name);
3265 if (rc)
3266 return rc;
3268 /* Not an attribute we recognize, so just check the
3269 ordinary setattr permission. */
3270 return dentry_has_perm(current_cred(), dentry, FILE__SETATTR);
3273 /* No one is allowed to remove a SELinux security label.
3274 You can change the label, but all data must be labeled. */
3275 return -EACCES;
3279 * Copy the inode security context value to the user.
3281 * Permission check is handled by selinux_inode_getxattr hook.
3283 static int selinux_inode_getsecurity(struct inode *inode, const char *name, void **buffer, bool alloc)
3285 u32 size;
3286 int error;
3287 char *context = NULL;
3288 struct inode_security_struct *isec;
3290 if (strcmp(name, XATTR_SELINUX_SUFFIX))
3291 return -EOPNOTSUPP;
3294 * If the caller has CAP_MAC_ADMIN, then get the raw context
3295 * value even if it is not defined by current policy; otherwise,
3296 * use the in-core value under current policy.
3297 * Use the non-auditing forms of the permission checks since
3298 * getxattr may be called by unprivileged processes commonly
3299 * and lack of permission just means that we fall back to the
3300 * in-core context value, not a denial.
3302 isec = inode_security(inode);
3303 if (has_cap_mac_admin(false))
3304 error = security_sid_to_context_force(&selinux_state,
3305 isec->sid, &context,
3306 &size);
3307 else
3308 error = security_sid_to_context(&selinux_state, isec->sid,
3309 &context, &size);
3310 if (error)
3311 return error;
3312 error = size;
3313 if (alloc) {
3314 *buffer = context;
3315 goto out_nofree;
3317 kfree(context);
3318 out_nofree:
3319 return error;
3322 static int selinux_inode_setsecurity(struct inode *inode, const char *name,
3323 const void *value, size_t size, int flags)
3325 struct inode_security_struct *isec = inode_security_novalidate(inode);
3326 struct superblock_security_struct *sbsec = inode->i_sb->s_security;
3327 u32 newsid;
3328 int rc;
3330 if (strcmp(name, XATTR_SELINUX_SUFFIX))
3331 return -EOPNOTSUPP;
3333 if (!(sbsec->flags & SBLABEL_MNT))
3334 return -EOPNOTSUPP;
3336 if (!value || !size)
3337 return -EACCES;
3339 rc = security_context_to_sid(&selinux_state, value, size, &newsid,
3340 GFP_KERNEL);
3341 if (rc)
3342 return rc;
3344 spin_lock(&isec->lock);
3345 isec->sclass = inode_mode_to_security_class(inode->i_mode);
3346 isec->sid = newsid;
3347 isec->initialized = LABEL_INITIALIZED;
3348 spin_unlock(&isec->lock);
3349 return 0;
3352 static int selinux_inode_listsecurity(struct inode *inode, char *buffer, size_t buffer_size)
3354 const int len = sizeof(XATTR_NAME_SELINUX);
3355 if (buffer && len <= buffer_size)
3356 memcpy(buffer, XATTR_NAME_SELINUX, len);
3357 return len;
3360 static void selinux_inode_getsecid(struct inode *inode, u32 *secid)
3362 struct inode_security_struct *isec = inode_security_novalidate(inode);
3363 *secid = isec->sid;
3366 static int selinux_inode_copy_up(struct dentry *src, struct cred **new)
3368 u32 sid;
3369 struct task_security_struct *tsec;
3370 struct cred *new_creds = *new;
3372 if (new_creds == NULL) {
3373 new_creds = prepare_creds();
3374 if (!new_creds)
3375 return -ENOMEM;
3378 tsec = selinux_cred(new_creds);
3379 /* Get label from overlay inode and set it in create_sid */
3380 selinux_inode_getsecid(d_inode(src), &sid);
3381 tsec->create_sid = sid;
3382 *new = new_creds;
3383 return 0;
3386 static int selinux_inode_copy_up_xattr(const char *name)
3388 /* The copy_up hook above sets the initial context on an inode, but we
3389 * don't then want to overwrite it by blindly copying all the lower
3390 * xattrs up. Instead, we have to filter out SELinux-related xattrs.
3392 if (strcmp(name, XATTR_NAME_SELINUX) == 0)
3393 return 1; /* Discard */
3395 * Any other attribute apart from SELINUX is not claimed, supported
3396 * by selinux.
3398 return -EOPNOTSUPP;
3401 /* kernfs node operations */
3403 static int selinux_kernfs_init_security(struct kernfs_node *kn_dir,
3404 struct kernfs_node *kn)
3406 const struct task_security_struct *tsec = current_security();
3407 u32 parent_sid, newsid, clen;
3408 int rc;
3409 char *context;
3411 rc = kernfs_xattr_get(kn_dir, XATTR_NAME_SELINUX, NULL, 0);
3412 if (rc == -ENODATA)
3413 return 0;
3414 else if (rc < 0)
3415 return rc;
3417 clen = (u32)rc;
3418 context = kmalloc(clen, GFP_KERNEL);
3419 if (!context)
3420 return -ENOMEM;
3422 rc = kernfs_xattr_get(kn_dir, XATTR_NAME_SELINUX, context, clen);
3423 if (rc < 0) {
3424 kfree(context);
3425 return rc;
3428 rc = security_context_to_sid(&selinux_state, context, clen, &parent_sid,
3429 GFP_KERNEL);
3430 kfree(context);
3431 if (rc)
3432 return rc;
3434 if (tsec->create_sid) {
3435 newsid = tsec->create_sid;
3436 } else {
3437 u16 secclass = inode_mode_to_security_class(kn->mode);
3438 struct qstr q;
3440 q.name = kn->name;
3441 q.hash_len = hashlen_string(kn_dir, kn->name);
3443 rc = security_transition_sid(&selinux_state, tsec->sid,
3444 parent_sid, secclass, &q,
3445 &newsid);
3446 if (rc)
3447 return rc;
3450 rc = security_sid_to_context_force(&selinux_state, newsid,
3451 &context, &clen);
3452 if (rc)
3453 return rc;
3455 rc = kernfs_xattr_set(kn, XATTR_NAME_SELINUX, context, clen,
3456 XATTR_CREATE);
3457 kfree(context);
3458 return rc;
3462 /* file security operations */
3464 static int selinux_revalidate_file_permission(struct file *file, int mask)
3466 const struct cred *cred = current_cred();
3467 struct inode *inode = file_inode(file);
3469 /* file_mask_to_av won't add FILE__WRITE if MAY_APPEND is set */
3470 if ((file->f_flags & O_APPEND) && (mask & MAY_WRITE))
3471 mask |= MAY_APPEND;
3473 return file_has_perm(cred, file,
3474 file_mask_to_av(inode->i_mode, mask));
3477 static int selinux_file_permission(struct file *file, int mask)
3479 struct inode *inode = file_inode(file);
3480 struct file_security_struct *fsec = selinux_file(file);
3481 struct inode_security_struct *isec;
3482 u32 sid = current_sid();
3484 if (!mask)
3485 /* No permission to check. Existence test. */
3486 return 0;
3488 isec = inode_security(inode);
3489 if (sid == fsec->sid && fsec->isid == isec->sid &&
3490 fsec->pseqno == avc_policy_seqno(&selinux_state))
3491 /* No change since file_open check. */
3492 return 0;
3494 return selinux_revalidate_file_permission(file, mask);
3497 static int selinux_file_alloc_security(struct file *file)
3499 return file_alloc_security(file);
3503 * Check whether a task has the ioctl permission and cmd
3504 * operation to an inode.
3506 static int ioctl_has_perm(const struct cred *cred, struct file *file,
3507 u32 requested, u16 cmd)
3509 struct common_audit_data ad;
3510 struct file_security_struct *fsec = selinux_file(file);
3511 struct inode *inode = file_inode(file);
3512 struct inode_security_struct *isec;
3513 struct lsm_ioctlop_audit ioctl;
3514 u32 ssid = cred_sid(cred);
3515 int rc;
3516 u8 driver = cmd >> 8;
3517 u8 xperm = cmd & 0xff;
3519 ad.type = LSM_AUDIT_DATA_IOCTL_OP;
3520 ad.u.op = &ioctl;
3521 ad.u.op->cmd = cmd;
3522 ad.u.op->path = file->f_path;
3524 if (ssid != fsec->sid) {
3525 rc = avc_has_perm(&selinux_state,
3526 ssid, fsec->sid,
3527 SECCLASS_FD,
3528 FD__USE,
3529 &ad);
3530 if (rc)
3531 goto out;
3534 if (unlikely(IS_PRIVATE(inode)))
3535 return 0;
3537 isec = inode_security(inode);
3538 rc = avc_has_extended_perms(&selinux_state,
3539 ssid, isec->sid, isec->sclass,
3540 requested, driver, xperm, &ad);
3541 out:
3542 return rc;
3545 static int selinux_file_ioctl(struct file *file, unsigned int cmd,
3546 unsigned long arg)
3548 const struct cred *cred = current_cred();
3549 int error = 0;
3551 switch (cmd) {
3552 case FIONREAD:
3553 /* fall through */
3554 case FIBMAP:
3555 /* fall through */
3556 case FIGETBSZ:
3557 /* fall through */
3558 case FS_IOC_GETFLAGS:
3559 /* fall through */
3560 case FS_IOC_GETVERSION:
3561 error = file_has_perm(cred, file, FILE__GETATTR);
3562 break;
3564 case FS_IOC_SETFLAGS:
3565 /* fall through */
3566 case FS_IOC_SETVERSION:
3567 error = file_has_perm(cred, file, FILE__SETATTR);
3568 break;
3570 /* sys_ioctl() checks */
3571 case FIONBIO:
3572 /* fall through */
3573 case FIOASYNC:
3574 error = file_has_perm(cred, file, 0);
3575 break;
3577 case KDSKBENT:
3578 case KDSKBSENT:
3579 error = cred_has_capability(cred, CAP_SYS_TTY_CONFIG,
3580 CAP_OPT_NONE, true);
3581 break;
3583 /* default case assumes that the command will go
3584 * to the file's ioctl() function.
3586 default:
3587 error = ioctl_has_perm(cred, file, FILE__IOCTL, (u16) cmd);
3589 return error;
3592 static int default_noexec;
3594 static int file_map_prot_check(struct file *file, unsigned long prot, int shared)
3596 const struct cred *cred = current_cred();
3597 u32 sid = cred_sid(cred);
3598 int rc = 0;
3600 if (default_noexec &&
3601 (prot & PROT_EXEC) && (!file || IS_PRIVATE(file_inode(file)) ||
3602 (!shared && (prot & PROT_WRITE)))) {
3604 * We are making executable an anonymous mapping or a
3605 * private file mapping that will also be writable.
3606 * This has an additional check.
3608 rc = avc_has_perm(&selinux_state,
3609 sid, sid, SECCLASS_PROCESS,
3610 PROCESS__EXECMEM, NULL);
3611 if (rc)
3612 goto error;
3615 if (file) {
3616 /* read access is always possible with a mapping */
3617 u32 av = FILE__READ;
3619 /* write access only matters if the mapping is shared */
3620 if (shared && (prot & PROT_WRITE))
3621 av |= FILE__WRITE;
3623 if (prot & PROT_EXEC)
3624 av |= FILE__EXECUTE;
3626 return file_has_perm(cred, file, av);
3629 error:
3630 return rc;
3633 static int selinux_mmap_addr(unsigned long addr)
3635 int rc = 0;
3637 if (addr < CONFIG_LSM_MMAP_MIN_ADDR) {
3638 u32 sid = current_sid();
3639 rc = avc_has_perm(&selinux_state,
3640 sid, sid, SECCLASS_MEMPROTECT,
3641 MEMPROTECT__MMAP_ZERO, NULL);
3644 return rc;
3647 static int selinux_mmap_file(struct file *file, unsigned long reqprot,
3648 unsigned long prot, unsigned long flags)
3650 struct common_audit_data ad;
3651 int rc;
3653 if (file) {
3654 ad.type = LSM_AUDIT_DATA_FILE;
3655 ad.u.file = file;
3656 rc = inode_has_perm(current_cred(), file_inode(file),
3657 FILE__MAP, &ad);
3658 if (rc)
3659 return rc;
3662 if (selinux_state.checkreqprot)
3663 prot = reqprot;
3665 return file_map_prot_check(file, prot,
3666 (flags & MAP_TYPE) == MAP_SHARED);
3669 static int selinux_file_mprotect(struct vm_area_struct *vma,
3670 unsigned long reqprot,
3671 unsigned long prot)
3673 const struct cred *cred = current_cred();
3674 u32 sid = cred_sid(cred);
3676 if (selinux_state.checkreqprot)
3677 prot = reqprot;
3679 if (default_noexec &&
3680 (prot & PROT_EXEC) && !(vma->vm_flags & VM_EXEC)) {
3681 int rc = 0;
3682 if (vma->vm_start >= vma->vm_mm->start_brk &&
3683 vma->vm_end <= vma->vm_mm->brk) {
3684 rc = avc_has_perm(&selinux_state,
3685 sid, sid, SECCLASS_PROCESS,
3686 PROCESS__EXECHEAP, NULL);
3687 } else if (!vma->vm_file &&
3688 ((vma->vm_start <= vma->vm_mm->start_stack &&
3689 vma->vm_end >= vma->vm_mm->start_stack) ||
3690 vma_is_stack_for_current(vma))) {
3691 rc = avc_has_perm(&selinux_state,
3692 sid, sid, SECCLASS_PROCESS,
3693 PROCESS__EXECSTACK, NULL);
3694 } else if (vma->vm_file && vma->anon_vma) {
3696 * We are making executable a file mapping that has
3697 * had some COW done. Since pages might have been
3698 * written, check ability to execute the possibly
3699 * modified content. This typically should only
3700 * occur for text relocations.
3702 rc = file_has_perm(cred, vma->vm_file, FILE__EXECMOD);
3704 if (rc)
3705 return rc;
3708 return file_map_prot_check(vma->vm_file, prot, vma->vm_flags&VM_SHARED);
3711 static int selinux_file_lock(struct file *file, unsigned int cmd)
3713 const struct cred *cred = current_cred();
3715 return file_has_perm(cred, file, FILE__LOCK);
3718 static int selinux_file_fcntl(struct file *file, unsigned int cmd,
3719 unsigned long arg)
3721 const struct cred *cred = current_cred();
3722 int err = 0;
3724 switch (cmd) {
3725 case F_SETFL:
3726 if ((file->f_flags & O_APPEND) && !(arg & O_APPEND)) {
3727 err = file_has_perm(cred, file, FILE__WRITE);
3728 break;
3730 /* fall through */
3731 case F_SETOWN:
3732 case F_SETSIG:
3733 case F_GETFL:
3734 case F_GETOWN:
3735 case F_GETSIG:
3736 case F_GETOWNER_UIDS:
3737 /* Just check FD__USE permission */
3738 err = file_has_perm(cred, file, 0);
3739 break;
3740 case F_GETLK:
3741 case F_SETLK:
3742 case F_SETLKW:
3743 case F_OFD_GETLK:
3744 case F_OFD_SETLK:
3745 case F_OFD_SETLKW:
3746 #if BITS_PER_LONG == 32
3747 case F_GETLK64:
3748 case F_SETLK64:
3749 case F_SETLKW64:
3750 #endif
3751 err = file_has_perm(cred, file, FILE__LOCK);
3752 break;
3755 return err;
3758 static void selinux_file_set_fowner(struct file *file)
3760 struct file_security_struct *fsec;
3762 fsec = selinux_file(file);
3763 fsec->fown_sid = current_sid();
3766 static int selinux_file_send_sigiotask(struct task_struct *tsk,
3767 struct fown_struct *fown, int signum)
3769 struct file *file;
3770 u32 sid = task_sid(tsk);
3771 u32 perm;
3772 struct file_security_struct *fsec;
3774 /* struct fown_struct is never outside the context of a struct file */
3775 file = container_of(fown, struct file, f_owner);
3777 fsec = selinux_file(file);
3779 if (!signum)
3780 perm = signal_to_av(SIGIO); /* as per send_sigio_to_task */
3781 else
3782 perm = signal_to_av(signum);
3784 return avc_has_perm(&selinux_state,
3785 fsec->fown_sid, sid,
3786 SECCLASS_PROCESS, perm, NULL);
3789 static int selinux_file_receive(struct file *file)
3791 const struct cred *cred = current_cred();
3793 return file_has_perm(cred, file, file_to_av(file));
3796 static int selinux_file_open(struct file *file)
3798 struct file_security_struct *fsec;
3799 struct inode_security_struct *isec;
3801 fsec = selinux_file(file);
3802 isec = inode_security(file_inode(file));
3804 * Save inode label and policy sequence number
3805 * at open-time so that selinux_file_permission
3806 * can determine whether revalidation is necessary.
3807 * Task label is already saved in the file security
3808 * struct as its SID.
3810 fsec->isid = isec->sid;
3811 fsec->pseqno = avc_policy_seqno(&selinux_state);
3813 * Since the inode label or policy seqno may have changed
3814 * between the selinux_inode_permission check and the saving
3815 * of state above, recheck that access is still permitted.
3816 * Otherwise, access might never be revalidated against the
3817 * new inode label or new policy.
3818 * This check is not redundant - do not remove.
3820 return file_path_has_perm(file->f_cred, file, open_file_to_av(file));
3823 /* task security operations */
3825 static int selinux_task_alloc(struct task_struct *task,
3826 unsigned long clone_flags)
3828 u32 sid = current_sid();
3830 return avc_has_perm(&selinux_state,
3831 sid, sid, SECCLASS_PROCESS, PROCESS__FORK, NULL);
3835 * prepare a new set of credentials for modification
3837 static int selinux_cred_prepare(struct cred *new, const struct cred *old,
3838 gfp_t gfp)
3840 const struct task_security_struct *old_tsec = selinux_cred(old);
3841 struct task_security_struct *tsec = selinux_cred(new);
3843 *tsec = *old_tsec;
3844 return 0;
3848 * transfer the SELinux data to a blank set of creds
3850 static void selinux_cred_transfer(struct cred *new, const struct cred *old)
3852 const struct task_security_struct *old_tsec = selinux_cred(old);
3853 struct task_security_struct *tsec = selinux_cred(new);
3855 *tsec = *old_tsec;
3858 static void selinux_cred_getsecid(const struct cred *c, u32 *secid)
3860 *secid = cred_sid(c);
3864 * set the security data for a kernel service
3865 * - all the creation contexts are set to unlabelled
3867 static int selinux_kernel_act_as(struct cred *new, u32 secid)
3869 struct task_security_struct *tsec = selinux_cred(new);
3870 u32 sid = current_sid();
3871 int ret;
3873 ret = avc_has_perm(&selinux_state,
3874 sid, secid,
3875 SECCLASS_KERNEL_SERVICE,
3876 KERNEL_SERVICE__USE_AS_OVERRIDE,
3877 NULL);
3878 if (ret == 0) {
3879 tsec->sid = secid;
3880 tsec->create_sid = 0;
3881 tsec->keycreate_sid = 0;
3882 tsec->sockcreate_sid = 0;
3884 return ret;
3888 * set the file creation context in a security record to the same as the
3889 * objective context of the specified inode
3891 static int selinux_kernel_create_files_as(struct cred *new, struct inode *inode)
3893 struct inode_security_struct *isec = inode_security(inode);
3894 struct task_security_struct *tsec = selinux_cred(new);
3895 u32 sid = current_sid();
3896 int ret;
3898 ret = avc_has_perm(&selinux_state,
3899 sid, isec->sid,
3900 SECCLASS_KERNEL_SERVICE,
3901 KERNEL_SERVICE__CREATE_FILES_AS,
3902 NULL);
3904 if (ret == 0)
3905 tsec->create_sid = isec->sid;
3906 return ret;
3909 static int selinux_kernel_module_request(char *kmod_name)
3911 struct common_audit_data ad;
3913 ad.type = LSM_AUDIT_DATA_KMOD;
3914 ad.u.kmod_name = kmod_name;
3916 return avc_has_perm(&selinux_state,
3917 current_sid(), SECINITSID_KERNEL, SECCLASS_SYSTEM,
3918 SYSTEM__MODULE_REQUEST, &ad);
3921 static int selinux_kernel_module_from_file(struct file *file)
3923 struct common_audit_data ad;
3924 struct inode_security_struct *isec;
3925 struct file_security_struct *fsec;
3926 u32 sid = current_sid();
3927 int rc;
3929 /* init_module */
3930 if (file == NULL)
3931 return avc_has_perm(&selinux_state,
3932 sid, sid, SECCLASS_SYSTEM,
3933 SYSTEM__MODULE_LOAD, NULL);
3935 /* finit_module */
3937 ad.type = LSM_AUDIT_DATA_FILE;
3938 ad.u.file = file;
3940 fsec = selinux_file(file);
3941 if (sid != fsec->sid) {
3942 rc = avc_has_perm(&selinux_state,
3943 sid, fsec->sid, SECCLASS_FD, FD__USE, &ad);
3944 if (rc)
3945 return rc;
3948 isec = inode_security(file_inode(file));
3949 return avc_has_perm(&selinux_state,
3950 sid, isec->sid, SECCLASS_SYSTEM,
3951 SYSTEM__MODULE_LOAD, &ad);
3954 static int selinux_kernel_read_file(struct file *file,
3955 enum kernel_read_file_id id)
3957 int rc = 0;
3959 switch (id) {
3960 case READING_MODULE:
3961 rc = selinux_kernel_module_from_file(file);
3962 break;
3963 default:
3964 break;
3967 return rc;
3970 static int selinux_kernel_load_data(enum kernel_load_data_id id)
3972 int rc = 0;
3974 switch (id) {
3975 case LOADING_MODULE:
3976 rc = selinux_kernel_module_from_file(NULL);
3977 default:
3978 break;
3981 return rc;
3984 static int selinux_task_setpgid(struct task_struct *p, pid_t pgid)
3986 return avc_has_perm(&selinux_state,
3987 current_sid(), task_sid(p), SECCLASS_PROCESS,
3988 PROCESS__SETPGID, NULL);
3991 static int selinux_task_getpgid(struct task_struct *p)
3993 return avc_has_perm(&selinux_state,
3994 current_sid(), task_sid(p), SECCLASS_PROCESS,
3995 PROCESS__GETPGID, NULL);
3998 static int selinux_task_getsid(struct task_struct *p)
4000 return avc_has_perm(&selinux_state,
4001 current_sid(), task_sid(p), SECCLASS_PROCESS,
4002 PROCESS__GETSESSION, NULL);
4005 static void selinux_task_getsecid(struct task_struct *p, u32 *secid)
4007 *secid = task_sid(p);
4010 static int selinux_task_setnice(struct task_struct *p, int nice)
4012 return avc_has_perm(&selinux_state,
4013 current_sid(), task_sid(p), SECCLASS_PROCESS,
4014 PROCESS__SETSCHED, NULL);
4017 static int selinux_task_setioprio(struct task_struct *p, int ioprio)
4019 return avc_has_perm(&selinux_state,
4020 current_sid(), task_sid(p), SECCLASS_PROCESS,
4021 PROCESS__SETSCHED, NULL);
4024 static int selinux_task_getioprio(struct task_struct *p)
4026 return avc_has_perm(&selinux_state,
4027 current_sid(), task_sid(p), SECCLASS_PROCESS,
4028 PROCESS__GETSCHED, NULL);
4031 static int selinux_task_prlimit(const struct cred *cred, const struct cred *tcred,
4032 unsigned int flags)
4034 u32 av = 0;
4036 if (!flags)
4037 return 0;
4038 if (flags & LSM_PRLIMIT_WRITE)
4039 av |= PROCESS__SETRLIMIT;
4040 if (flags & LSM_PRLIMIT_READ)
4041 av |= PROCESS__GETRLIMIT;
4042 return avc_has_perm(&selinux_state,
4043 cred_sid(cred), cred_sid(tcred),
4044 SECCLASS_PROCESS, av, NULL);
4047 static int selinux_task_setrlimit(struct task_struct *p, unsigned int resource,
4048 struct rlimit *new_rlim)
4050 struct rlimit *old_rlim = p->signal->rlim + resource;
4052 /* Control the ability to change the hard limit (whether
4053 lowering or raising it), so that the hard limit can
4054 later be used as a safe reset point for the soft limit
4055 upon context transitions. See selinux_bprm_committing_creds. */
4056 if (old_rlim->rlim_max != new_rlim->rlim_max)
4057 return avc_has_perm(&selinux_state,
4058 current_sid(), task_sid(p),
4059 SECCLASS_PROCESS, PROCESS__SETRLIMIT, NULL);
4061 return 0;
4064 static int selinux_task_setscheduler(struct task_struct *p)
4066 return avc_has_perm(&selinux_state,
4067 current_sid(), task_sid(p), SECCLASS_PROCESS,
4068 PROCESS__SETSCHED, NULL);
4071 static int selinux_task_getscheduler(struct task_struct *p)
4073 return avc_has_perm(&selinux_state,
4074 current_sid(), task_sid(p), SECCLASS_PROCESS,
4075 PROCESS__GETSCHED, NULL);
4078 static int selinux_task_movememory(struct task_struct *p)
4080 return avc_has_perm(&selinux_state,
4081 current_sid(), task_sid(p), SECCLASS_PROCESS,
4082 PROCESS__SETSCHED, NULL);
4085 static int selinux_task_kill(struct task_struct *p, struct kernel_siginfo *info,
4086 int sig, const struct cred *cred)
4088 u32 secid;
4089 u32 perm;
4091 if (!sig)
4092 perm = PROCESS__SIGNULL; /* null signal; existence test */
4093 else
4094 perm = signal_to_av(sig);
4095 if (!cred)
4096 secid = current_sid();
4097 else
4098 secid = cred_sid(cred);
4099 return avc_has_perm(&selinux_state,
4100 secid, task_sid(p), SECCLASS_PROCESS, perm, NULL);
4103 static void selinux_task_to_inode(struct task_struct *p,
4104 struct inode *inode)
4106 struct inode_security_struct *isec = selinux_inode(inode);
4107 u32 sid = task_sid(p);
4109 spin_lock(&isec->lock);
4110 isec->sclass = inode_mode_to_security_class(inode->i_mode);
4111 isec->sid = sid;
4112 isec->initialized = LABEL_INITIALIZED;
4113 spin_unlock(&isec->lock);
4116 /* Returns error only if unable to parse addresses */
4117 static int selinux_parse_skb_ipv4(struct sk_buff *skb,
4118 struct common_audit_data *ad, u8 *proto)
4120 int offset, ihlen, ret = -EINVAL;
4121 struct iphdr _iph, *ih;
4123 offset = skb_network_offset(skb);
4124 ih = skb_header_pointer(skb, offset, sizeof(_iph), &_iph);
4125 if (ih == NULL)
4126 goto out;
4128 ihlen = ih->ihl * 4;
4129 if (ihlen < sizeof(_iph))
4130 goto out;
4132 ad->u.net->v4info.saddr = ih->saddr;
4133 ad->u.net->v4info.daddr = ih->daddr;
4134 ret = 0;
4136 if (proto)
4137 *proto = ih->protocol;
4139 switch (ih->protocol) {
4140 case IPPROTO_TCP: {
4141 struct tcphdr _tcph, *th;
4143 if (ntohs(ih->frag_off) & IP_OFFSET)
4144 break;
4146 offset += ihlen;
4147 th = skb_header_pointer(skb, offset, sizeof(_tcph), &_tcph);
4148 if (th == NULL)
4149 break;
4151 ad->u.net->sport = th->source;
4152 ad->u.net->dport = th->dest;
4153 break;
4156 case IPPROTO_UDP: {
4157 struct udphdr _udph, *uh;
4159 if (ntohs(ih->frag_off) & IP_OFFSET)
4160 break;
4162 offset += ihlen;
4163 uh = skb_header_pointer(skb, offset, sizeof(_udph), &_udph);
4164 if (uh == NULL)
4165 break;
4167 ad->u.net->sport = uh->source;
4168 ad->u.net->dport = uh->dest;
4169 break;
4172 case IPPROTO_DCCP: {
4173 struct dccp_hdr _dccph, *dh;
4175 if (ntohs(ih->frag_off) & IP_OFFSET)
4176 break;
4178 offset += ihlen;
4179 dh = skb_header_pointer(skb, offset, sizeof(_dccph), &_dccph);
4180 if (dh == NULL)
4181 break;
4183 ad->u.net->sport = dh->dccph_sport;
4184 ad->u.net->dport = dh->dccph_dport;
4185 break;
4188 #if IS_ENABLED(CONFIG_IP_SCTP)
4189 case IPPROTO_SCTP: {
4190 struct sctphdr _sctph, *sh;
4192 if (ntohs(ih->frag_off) & IP_OFFSET)
4193 break;
4195 offset += ihlen;
4196 sh = skb_header_pointer(skb, offset, sizeof(_sctph), &_sctph);
4197 if (sh == NULL)
4198 break;
4200 ad->u.net->sport = sh->source;
4201 ad->u.net->dport = sh->dest;
4202 break;
4204 #endif
4205 default:
4206 break;
4208 out:
4209 return ret;
4212 #if IS_ENABLED(CONFIG_IPV6)
4214 /* Returns error only if unable to parse addresses */
4215 static int selinux_parse_skb_ipv6(struct sk_buff *skb,
4216 struct common_audit_data *ad, u8 *proto)
4218 u8 nexthdr;
4219 int ret = -EINVAL, offset;
4220 struct ipv6hdr _ipv6h, *ip6;
4221 __be16 frag_off;
4223 offset = skb_network_offset(skb);
4224 ip6 = skb_header_pointer(skb, offset, sizeof(_ipv6h), &_ipv6h);
4225 if (ip6 == NULL)
4226 goto out;
4228 ad->u.net->v6info.saddr = ip6->saddr;
4229 ad->u.net->v6info.daddr = ip6->daddr;
4230 ret = 0;
4232 nexthdr = ip6->nexthdr;
4233 offset += sizeof(_ipv6h);
4234 offset = ipv6_skip_exthdr(skb, offset, &nexthdr, &frag_off);
4235 if (offset < 0)
4236 goto out;
4238 if (proto)
4239 *proto = nexthdr;
4241 switch (nexthdr) {
4242 case IPPROTO_TCP: {
4243 struct tcphdr _tcph, *th;
4245 th = skb_header_pointer(skb, offset, sizeof(_tcph), &_tcph);
4246 if (th == NULL)
4247 break;
4249 ad->u.net->sport = th->source;
4250 ad->u.net->dport = th->dest;
4251 break;
4254 case IPPROTO_UDP: {
4255 struct udphdr _udph, *uh;
4257 uh = skb_header_pointer(skb, offset, sizeof(_udph), &_udph);
4258 if (uh == NULL)
4259 break;
4261 ad->u.net->sport = uh->source;
4262 ad->u.net->dport = uh->dest;
4263 break;
4266 case IPPROTO_DCCP: {
4267 struct dccp_hdr _dccph, *dh;
4269 dh = skb_header_pointer(skb, offset, sizeof(_dccph), &_dccph);
4270 if (dh == NULL)
4271 break;
4273 ad->u.net->sport = dh->dccph_sport;
4274 ad->u.net->dport = dh->dccph_dport;
4275 break;
4278 #if IS_ENABLED(CONFIG_IP_SCTP)
4279 case IPPROTO_SCTP: {
4280 struct sctphdr _sctph, *sh;
4282 sh = skb_header_pointer(skb, offset, sizeof(_sctph), &_sctph);
4283 if (sh == NULL)
4284 break;
4286 ad->u.net->sport = sh->source;
4287 ad->u.net->dport = sh->dest;
4288 break;
4290 #endif
4291 /* includes fragments */
4292 default:
4293 break;
4295 out:
4296 return ret;
4299 #endif /* IPV6 */
4301 static int selinux_parse_skb(struct sk_buff *skb, struct common_audit_data *ad,
4302 char **_addrp, int src, u8 *proto)
4304 char *addrp;
4305 int ret;
4307 switch (ad->u.net->family) {
4308 case PF_INET:
4309 ret = selinux_parse_skb_ipv4(skb, ad, proto);
4310 if (ret)
4311 goto parse_error;
4312 addrp = (char *)(src ? &ad->u.net->v4info.saddr :
4313 &ad->u.net->v4info.daddr);
4314 goto okay;
4316 #if IS_ENABLED(CONFIG_IPV6)
4317 case PF_INET6:
4318 ret = selinux_parse_skb_ipv6(skb, ad, proto);
4319 if (ret)
4320 goto parse_error;
4321 addrp = (char *)(src ? &ad->u.net->v6info.saddr :
4322 &ad->u.net->v6info.daddr);
4323 goto okay;
4324 #endif /* IPV6 */
4325 default:
4326 addrp = NULL;
4327 goto okay;
4330 parse_error:
4331 pr_warn(
4332 "SELinux: failure in selinux_parse_skb(),"
4333 " unable to parse packet\n");
4334 return ret;
4336 okay:
4337 if (_addrp)
4338 *_addrp = addrp;
4339 return 0;
4343 * selinux_skb_peerlbl_sid - Determine the peer label of a packet
4344 * @skb: the packet
4345 * @family: protocol family
4346 * @sid: the packet's peer label SID
4348 * Description:
4349 * Check the various different forms of network peer labeling and determine
4350 * the peer label/SID for the packet; most of the magic actually occurs in
4351 * the security server function security_net_peersid_cmp(). The function
4352 * returns zero if the value in @sid is valid (although it may be SECSID_NULL)
4353 * or -EACCES if @sid is invalid due to inconsistencies with the different
4354 * peer labels.
4357 static int selinux_skb_peerlbl_sid(struct sk_buff *skb, u16 family, u32 *sid)
4359 int err;
4360 u32 xfrm_sid;
4361 u32 nlbl_sid;
4362 u32 nlbl_type;
4364 err = selinux_xfrm_skb_sid(skb, &xfrm_sid);
4365 if (unlikely(err))
4366 return -EACCES;
4367 err = selinux_netlbl_skbuff_getsid(skb, family, &nlbl_type, &nlbl_sid);
4368 if (unlikely(err))
4369 return -EACCES;
4371 err = security_net_peersid_resolve(&selinux_state, nlbl_sid,
4372 nlbl_type, xfrm_sid, sid);
4373 if (unlikely(err)) {
4374 pr_warn(
4375 "SELinux: failure in selinux_skb_peerlbl_sid(),"
4376 " unable to determine packet's peer label\n");
4377 return -EACCES;
4380 return 0;
4384 * selinux_conn_sid - Determine the child socket label for a connection
4385 * @sk_sid: the parent socket's SID
4386 * @skb_sid: the packet's SID
4387 * @conn_sid: the resulting connection SID
4389 * If @skb_sid is valid then the user:role:type information from @sk_sid is
4390 * combined with the MLS information from @skb_sid in order to create
4391 * @conn_sid. If @skb_sid is not valid then then @conn_sid is simply a copy
4392 * of @sk_sid. Returns zero on success, negative values on failure.
4395 static int selinux_conn_sid(u32 sk_sid, u32 skb_sid, u32 *conn_sid)
4397 int err = 0;
4399 if (skb_sid != SECSID_NULL)
4400 err = security_sid_mls_copy(&selinux_state, sk_sid, skb_sid,
4401 conn_sid);
4402 else
4403 *conn_sid = sk_sid;
4405 return err;
4408 /* socket security operations */
4410 static int socket_sockcreate_sid(const struct task_security_struct *tsec,
4411 u16 secclass, u32 *socksid)
4413 if (tsec->sockcreate_sid > SECSID_NULL) {
4414 *socksid = tsec->sockcreate_sid;
4415 return 0;
4418 return security_transition_sid(&selinux_state, tsec->sid, tsec->sid,
4419 secclass, NULL, socksid);
4422 static int sock_has_perm(struct sock *sk, u32 perms)
4424 struct sk_security_struct *sksec = sk->sk_security;
4425 struct common_audit_data ad;
4426 struct lsm_network_audit net = {0,};
4428 if (sksec->sid == SECINITSID_KERNEL)
4429 return 0;
4431 ad.type = LSM_AUDIT_DATA_NET;
4432 ad.u.net = &net;
4433 ad.u.net->sk = sk;
4435 return avc_has_perm(&selinux_state,
4436 current_sid(), sksec->sid, sksec->sclass, perms,
4437 &ad);
4440 static int selinux_socket_create(int family, int type,
4441 int protocol, int kern)
4443 const struct task_security_struct *tsec = selinux_cred(current_cred());
4444 u32 newsid;
4445 u16 secclass;
4446 int rc;
4448 if (kern)
4449 return 0;
4451 secclass = socket_type_to_security_class(family, type, protocol);
4452 rc = socket_sockcreate_sid(tsec, secclass, &newsid);
4453 if (rc)
4454 return rc;
4456 return avc_has_perm(&selinux_state,
4457 tsec->sid, newsid, secclass, SOCKET__CREATE, NULL);
4460 static int selinux_socket_post_create(struct socket *sock, int family,
4461 int type, int protocol, int kern)
4463 const struct task_security_struct *tsec = selinux_cred(current_cred());
4464 struct inode_security_struct *isec = inode_security_novalidate(SOCK_INODE(sock));
4465 struct sk_security_struct *sksec;
4466 u16 sclass = socket_type_to_security_class(family, type, protocol);
4467 u32 sid = SECINITSID_KERNEL;
4468 int err = 0;
4470 if (!kern) {
4471 err = socket_sockcreate_sid(tsec, sclass, &sid);
4472 if (err)
4473 return err;
4476 isec->sclass = sclass;
4477 isec->sid = sid;
4478 isec->initialized = LABEL_INITIALIZED;
4480 if (sock->sk) {
4481 sksec = sock->sk->sk_security;
4482 sksec->sclass = sclass;
4483 sksec->sid = sid;
4484 /* Allows detection of the first association on this socket */
4485 if (sksec->sclass == SECCLASS_SCTP_SOCKET)
4486 sksec->sctp_assoc_state = SCTP_ASSOC_UNSET;
4488 err = selinux_netlbl_socket_post_create(sock->sk, family);
4491 return err;
4494 static int selinux_socket_socketpair(struct socket *socka,
4495 struct socket *sockb)
4497 struct sk_security_struct *sksec_a = socka->sk->sk_security;
4498 struct sk_security_struct *sksec_b = sockb->sk->sk_security;
4500 sksec_a->peer_sid = sksec_b->sid;
4501 sksec_b->peer_sid = sksec_a->sid;
4503 return 0;
4506 /* Range of port numbers used to automatically bind.
4507 Need to determine whether we should perform a name_bind
4508 permission check between the socket and the port number. */
4510 static int selinux_socket_bind(struct socket *sock, struct sockaddr *address, int addrlen)
4512 struct sock *sk = sock->sk;
4513 struct sk_security_struct *sksec = sk->sk_security;
4514 u16 family;
4515 int err;
4517 err = sock_has_perm(sk, SOCKET__BIND);
4518 if (err)
4519 goto out;
4521 /* If PF_INET or PF_INET6, check name_bind permission for the port. */
4522 family = sk->sk_family;
4523 if (family == PF_INET || family == PF_INET6) {
4524 char *addrp;
4525 struct common_audit_data ad;
4526 struct lsm_network_audit net = {0,};
4527 struct sockaddr_in *addr4 = NULL;
4528 struct sockaddr_in6 *addr6 = NULL;
4529 u16 family_sa;
4530 unsigned short snum;
4531 u32 sid, node_perm;
4534 * sctp_bindx(3) calls via selinux_sctp_bind_connect()
4535 * that validates multiple binding addresses. Because of this
4536 * need to check address->sa_family as it is possible to have
4537 * sk->sk_family = PF_INET6 with addr->sa_family = AF_INET.
4539 if (addrlen < offsetofend(struct sockaddr, sa_family))
4540 return -EINVAL;
4541 family_sa = address->sa_family;
4542 switch (family_sa) {
4543 case AF_UNSPEC:
4544 case AF_INET:
4545 if (addrlen < sizeof(struct sockaddr_in))
4546 return -EINVAL;
4547 addr4 = (struct sockaddr_in *)address;
4548 if (family_sa == AF_UNSPEC) {
4549 /* see __inet_bind(), we only want to allow
4550 * AF_UNSPEC if the address is INADDR_ANY
4552 if (addr4->sin_addr.s_addr != htonl(INADDR_ANY))
4553 goto err_af;
4554 family_sa = AF_INET;
4556 snum = ntohs(addr4->sin_port);
4557 addrp = (char *)&addr4->sin_addr.s_addr;
4558 break;
4559 case AF_INET6:
4560 if (addrlen < SIN6_LEN_RFC2133)
4561 return -EINVAL;
4562 addr6 = (struct sockaddr_in6 *)address;
4563 snum = ntohs(addr6->sin6_port);
4564 addrp = (char *)&addr6->sin6_addr.s6_addr;
4565 break;
4566 default:
4567 goto err_af;
4570 ad.type = LSM_AUDIT_DATA_NET;
4571 ad.u.net = &net;
4572 ad.u.net->sport = htons(snum);
4573 ad.u.net->family = family_sa;
4575 if (snum) {
4576 int low, high;
4578 inet_get_local_port_range(sock_net(sk), &low, &high);
4580 if (snum < max(inet_prot_sock(sock_net(sk)), low) ||
4581 snum > high) {
4582 err = sel_netport_sid(sk->sk_protocol,
4583 snum, &sid);
4584 if (err)
4585 goto out;
4586 err = avc_has_perm(&selinux_state,
4587 sksec->sid, sid,
4588 sksec->sclass,
4589 SOCKET__NAME_BIND, &ad);
4590 if (err)
4591 goto out;
4595 switch (sksec->sclass) {
4596 case SECCLASS_TCP_SOCKET:
4597 node_perm = TCP_SOCKET__NODE_BIND;
4598 break;
4600 case SECCLASS_UDP_SOCKET:
4601 node_perm = UDP_SOCKET__NODE_BIND;
4602 break;
4604 case SECCLASS_DCCP_SOCKET:
4605 node_perm = DCCP_SOCKET__NODE_BIND;
4606 break;
4608 case SECCLASS_SCTP_SOCKET:
4609 node_perm = SCTP_SOCKET__NODE_BIND;
4610 break;
4612 default:
4613 node_perm = RAWIP_SOCKET__NODE_BIND;
4614 break;
4617 err = sel_netnode_sid(addrp, family_sa, &sid);
4618 if (err)
4619 goto out;
4621 if (family_sa == AF_INET)
4622 ad.u.net->v4info.saddr = addr4->sin_addr.s_addr;
4623 else
4624 ad.u.net->v6info.saddr = addr6->sin6_addr;
4626 err = avc_has_perm(&selinux_state,
4627 sksec->sid, sid,
4628 sksec->sclass, node_perm, &ad);
4629 if (err)
4630 goto out;
4632 out:
4633 return err;
4634 err_af:
4635 /* Note that SCTP services expect -EINVAL, others -EAFNOSUPPORT. */
4636 if (sksec->sclass == SECCLASS_SCTP_SOCKET)
4637 return -EINVAL;
4638 return -EAFNOSUPPORT;
4641 /* This supports connect(2) and SCTP connect services such as sctp_connectx(3)
4642 * and sctp_sendmsg(3) as described in Documentation/security/SCTP.rst
4644 static int selinux_socket_connect_helper(struct socket *sock,
4645 struct sockaddr *address, int addrlen)
4647 struct sock *sk = sock->sk;
4648 struct sk_security_struct *sksec = sk->sk_security;
4649 int err;
4651 err = sock_has_perm(sk, SOCKET__CONNECT);
4652 if (err)
4653 return err;
4654 if (addrlen < offsetofend(struct sockaddr, sa_family))
4655 return -EINVAL;
4657 /* connect(AF_UNSPEC) has special handling, as it is a documented
4658 * way to disconnect the socket
4660 if (address->sa_family == AF_UNSPEC)
4661 return 0;
4664 * If a TCP, DCCP or SCTP socket, check name_connect permission
4665 * for the port.
4667 if (sksec->sclass == SECCLASS_TCP_SOCKET ||
4668 sksec->sclass == SECCLASS_DCCP_SOCKET ||
4669 sksec->sclass == SECCLASS_SCTP_SOCKET) {
4670 struct common_audit_data ad;
4671 struct lsm_network_audit net = {0,};
4672 struct sockaddr_in *addr4 = NULL;
4673 struct sockaddr_in6 *addr6 = NULL;
4674 unsigned short snum;
4675 u32 sid, perm;
4677 /* sctp_connectx(3) calls via selinux_sctp_bind_connect()
4678 * that validates multiple connect addresses. Because of this
4679 * need to check address->sa_family as it is possible to have
4680 * sk->sk_family = PF_INET6 with addr->sa_family = AF_INET.
4682 switch (address->sa_family) {
4683 case AF_INET:
4684 addr4 = (struct sockaddr_in *)address;
4685 if (addrlen < sizeof(struct sockaddr_in))
4686 return -EINVAL;
4687 snum = ntohs(addr4->sin_port);
4688 break;
4689 case AF_INET6:
4690 addr6 = (struct sockaddr_in6 *)address;
4691 if (addrlen < SIN6_LEN_RFC2133)
4692 return -EINVAL;
4693 snum = ntohs(addr6->sin6_port);
4694 break;
4695 default:
4696 /* Note that SCTP services expect -EINVAL, whereas
4697 * others expect -EAFNOSUPPORT.
4699 if (sksec->sclass == SECCLASS_SCTP_SOCKET)
4700 return -EINVAL;
4701 else
4702 return -EAFNOSUPPORT;
4705 err = sel_netport_sid(sk->sk_protocol, snum, &sid);
4706 if (err)
4707 return err;
4709 switch (sksec->sclass) {
4710 case SECCLASS_TCP_SOCKET:
4711 perm = TCP_SOCKET__NAME_CONNECT;
4712 break;
4713 case SECCLASS_DCCP_SOCKET:
4714 perm = DCCP_SOCKET__NAME_CONNECT;
4715 break;
4716 case SECCLASS_SCTP_SOCKET:
4717 perm = SCTP_SOCKET__NAME_CONNECT;
4718 break;
4721 ad.type = LSM_AUDIT_DATA_NET;
4722 ad.u.net = &net;
4723 ad.u.net->dport = htons(snum);
4724 ad.u.net->family = address->sa_family;
4725 err = avc_has_perm(&selinux_state,
4726 sksec->sid, sid, sksec->sclass, perm, &ad);
4727 if (err)
4728 return err;
4731 return 0;
4734 /* Supports connect(2), see comments in selinux_socket_connect_helper() */
4735 static int selinux_socket_connect(struct socket *sock,
4736 struct sockaddr *address, int addrlen)
4738 int err;
4739 struct sock *sk = sock->sk;
4741 err = selinux_socket_connect_helper(sock, address, addrlen);
4742 if (err)
4743 return err;
4745 return selinux_netlbl_socket_connect(sk, address);
4748 static int selinux_socket_listen(struct socket *sock, int backlog)
4750 return sock_has_perm(sock->sk, SOCKET__LISTEN);
4753 static int selinux_socket_accept(struct socket *sock, struct socket *newsock)
4755 int err;
4756 struct inode_security_struct *isec;
4757 struct inode_security_struct *newisec;
4758 u16 sclass;
4759 u32 sid;
4761 err = sock_has_perm(sock->sk, SOCKET__ACCEPT);
4762 if (err)
4763 return err;
4765 isec = inode_security_novalidate(SOCK_INODE(sock));
4766 spin_lock(&isec->lock);
4767 sclass = isec->sclass;
4768 sid = isec->sid;
4769 spin_unlock(&isec->lock);
4771 newisec = inode_security_novalidate(SOCK_INODE(newsock));
4772 newisec->sclass = sclass;
4773 newisec->sid = sid;
4774 newisec->initialized = LABEL_INITIALIZED;
4776 return 0;
4779 static int selinux_socket_sendmsg(struct socket *sock, struct msghdr *msg,
4780 int size)
4782 return sock_has_perm(sock->sk, SOCKET__WRITE);
4785 static int selinux_socket_recvmsg(struct socket *sock, struct msghdr *msg,
4786 int size, int flags)
4788 return sock_has_perm(sock->sk, SOCKET__READ);
4791 static int selinux_socket_getsockname(struct socket *sock)
4793 return sock_has_perm(sock->sk, SOCKET__GETATTR);
4796 static int selinux_socket_getpeername(struct socket *sock)
4798 return sock_has_perm(sock->sk, SOCKET__GETATTR);
4801 static int selinux_socket_setsockopt(struct socket *sock, int level, int optname)
4803 int err;
4805 err = sock_has_perm(sock->sk, SOCKET__SETOPT);
4806 if (err)
4807 return err;
4809 return selinux_netlbl_socket_setsockopt(sock, level, optname);
4812 static int selinux_socket_getsockopt(struct socket *sock, int level,
4813 int optname)
4815 return sock_has_perm(sock->sk, SOCKET__GETOPT);
4818 static int selinux_socket_shutdown(struct socket *sock, int how)
4820 return sock_has_perm(sock->sk, SOCKET__SHUTDOWN);
4823 static int selinux_socket_unix_stream_connect(struct sock *sock,
4824 struct sock *other,
4825 struct sock *newsk)
4827 struct sk_security_struct *sksec_sock = sock->sk_security;
4828 struct sk_security_struct *sksec_other = other->sk_security;
4829 struct sk_security_struct *sksec_new = newsk->sk_security;
4830 struct common_audit_data ad;
4831 struct lsm_network_audit net = {0,};
4832 int err;
4834 ad.type = LSM_AUDIT_DATA_NET;
4835 ad.u.net = &net;
4836 ad.u.net->sk = other;
4838 err = avc_has_perm(&selinux_state,
4839 sksec_sock->sid, sksec_other->sid,
4840 sksec_other->sclass,
4841 UNIX_STREAM_SOCKET__CONNECTTO, &ad);
4842 if (err)
4843 return err;
4845 /* server child socket */
4846 sksec_new->peer_sid = sksec_sock->sid;
4847 err = security_sid_mls_copy(&selinux_state, sksec_other->sid,
4848 sksec_sock->sid, &sksec_new->sid);
4849 if (err)
4850 return err;
4852 /* connecting socket */
4853 sksec_sock->peer_sid = sksec_new->sid;
4855 return 0;
4858 static int selinux_socket_unix_may_send(struct socket *sock,
4859 struct socket *other)
4861 struct sk_security_struct *ssec = sock->sk->sk_security;
4862 struct sk_security_struct *osec = other->sk->sk_security;
4863 struct common_audit_data ad;
4864 struct lsm_network_audit net = {0,};
4866 ad.type = LSM_AUDIT_DATA_NET;
4867 ad.u.net = &net;
4868 ad.u.net->sk = other->sk;
4870 return avc_has_perm(&selinux_state,
4871 ssec->sid, osec->sid, osec->sclass, SOCKET__SENDTO,
4872 &ad);
4875 static int selinux_inet_sys_rcv_skb(struct net *ns, int ifindex,
4876 char *addrp, u16 family, u32 peer_sid,
4877 struct common_audit_data *ad)
4879 int err;
4880 u32 if_sid;
4881 u32 node_sid;
4883 err = sel_netif_sid(ns, ifindex, &if_sid);
4884 if (err)
4885 return err;
4886 err = avc_has_perm(&selinux_state,
4887 peer_sid, if_sid,
4888 SECCLASS_NETIF, NETIF__INGRESS, ad);
4889 if (err)
4890 return err;
4892 err = sel_netnode_sid(addrp, family, &node_sid);
4893 if (err)
4894 return err;
4895 return avc_has_perm(&selinux_state,
4896 peer_sid, node_sid,
4897 SECCLASS_NODE, NODE__RECVFROM, ad);
4900 static int selinux_sock_rcv_skb_compat(struct sock *sk, struct sk_buff *skb,
4901 u16 family)
4903 int err = 0;
4904 struct sk_security_struct *sksec = sk->sk_security;
4905 u32 sk_sid = sksec->sid;
4906 struct common_audit_data ad;
4907 struct lsm_network_audit net = {0,};
4908 char *addrp;
4910 ad.type = LSM_AUDIT_DATA_NET;
4911 ad.u.net = &net;
4912 ad.u.net->netif = skb->skb_iif;
4913 ad.u.net->family = family;
4914 err = selinux_parse_skb(skb, &ad, &addrp, 1, NULL);
4915 if (err)
4916 return err;
4918 if (selinux_secmark_enabled()) {
4919 err = avc_has_perm(&selinux_state,
4920 sk_sid, skb->secmark, SECCLASS_PACKET,
4921 PACKET__RECV, &ad);
4922 if (err)
4923 return err;
4926 err = selinux_netlbl_sock_rcv_skb(sksec, skb, family, &ad);
4927 if (err)
4928 return err;
4929 err = selinux_xfrm_sock_rcv_skb(sksec->sid, skb, &ad);
4931 return err;
4934 static int selinux_socket_sock_rcv_skb(struct sock *sk, struct sk_buff *skb)
4936 int err;
4937 struct sk_security_struct *sksec = sk->sk_security;
4938 u16 family = sk->sk_family;
4939 u32 sk_sid = sksec->sid;
4940 struct common_audit_data ad;
4941 struct lsm_network_audit net = {0,};
4942 char *addrp;
4943 u8 secmark_active;
4944 u8 peerlbl_active;
4946 if (family != PF_INET && family != PF_INET6)
4947 return 0;
4949 /* Handle mapped IPv4 packets arriving via IPv6 sockets */
4950 if (family == PF_INET6 && skb->protocol == htons(ETH_P_IP))
4951 family = PF_INET;
4953 /* If any sort of compatibility mode is enabled then handoff processing
4954 * to the selinux_sock_rcv_skb_compat() function to deal with the
4955 * special handling. We do this in an attempt to keep this function
4956 * as fast and as clean as possible. */
4957 if (!selinux_policycap_netpeer())
4958 return selinux_sock_rcv_skb_compat(sk, skb, family);
4960 secmark_active = selinux_secmark_enabled();
4961 peerlbl_active = selinux_peerlbl_enabled();
4962 if (!secmark_active && !peerlbl_active)
4963 return 0;
4965 ad.type = LSM_AUDIT_DATA_NET;
4966 ad.u.net = &net;
4967 ad.u.net->netif = skb->skb_iif;
4968 ad.u.net->family = family;
4969 err = selinux_parse_skb(skb, &ad, &addrp, 1, NULL);
4970 if (err)
4971 return err;
4973 if (peerlbl_active) {
4974 u32 peer_sid;
4976 err = selinux_skb_peerlbl_sid(skb, family, &peer_sid);
4977 if (err)
4978 return err;
4979 err = selinux_inet_sys_rcv_skb(sock_net(sk), skb->skb_iif,
4980 addrp, family, peer_sid, &ad);
4981 if (err) {
4982 selinux_netlbl_err(skb, family, err, 0);
4983 return err;
4985 err = avc_has_perm(&selinux_state,
4986 sk_sid, peer_sid, SECCLASS_PEER,
4987 PEER__RECV, &ad);
4988 if (err) {
4989 selinux_netlbl_err(skb, family, err, 0);
4990 return err;
4994 if (secmark_active) {
4995 err = avc_has_perm(&selinux_state,
4996 sk_sid, skb->secmark, SECCLASS_PACKET,
4997 PACKET__RECV, &ad);
4998 if (err)
4999 return err;
5002 return err;
5005 static int selinux_socket_getpeersec_stream(struct socket *sock, char __user *optval,
5006 int __user *optlen, unsigned len)
5008 int err = 0;
5009 char *scontext;
5010 u32 scontext_len;
5011 struct sk_security_struct *sksec = sock->sk->sk_security;
5012 u32 peer_sid = SECSID_NULL;
5014 if (sksec->sclass == SECCLASS_UNIX_STREAM_SOCKET ||
5015 sksec->sclass == SECCLASS_TCP_SOCKET ||
5016 sksec->sclass == SECCLASS_SCTP_SOCKET)
5017 peer_sid = sksec->peer_sid;
5018 if (peer_sid == SECSID_NULL)
5019 return -ENOPROTOOPT;
5021 err = security_sid_to_context(&selinux_state, peer_sid, &scontext,
5022 &scontext_len);
5023 if (err)
5024 return err;
5026 if (scontext_len > len) {
5027 err = -ERANGE;
5028 goto out_len;
5031 if (copy_to_user(optval, scontext, scontext_len))
5032 err = -EFAULT;
5034 out_len:
5035 if (put_user(scontext_len, optlen))
5036 err = -EFAULT;
5037 kfree(scontext);
5038 return err;
5041 static int selinux_socket_getpeersec_dgram(struct socket *sock, struct sk_buff *skb, u32 *secid)
5043 u32 peer_secid = SECSID_NULL;
5044 u16 family;
5045 struct inode_security_struct *isec;
5047 if (skb && skb->protocol == htons(ETH_P_IP))
5048 family = PF_INET;
5049 else if (skb && skb->protocol == htons(ETH_P_IPV6))
5050 family = PF_INET6;
5051 else if (sock)
5052 family = sock->sk->sk_family;
5053 else
5054 goto out;
5056 if (sock && family == PF_UNIX) {
5057 isec = inode_security_novalidate(SOCK_INODE(sock));
5058 peer_secid = isec->sid;
5059 } else if (skb)
5060 selinux_skb_peerlbl_sid(skb, family, &peer_secid);
5062 out:
5063 *secid = peer_secid;
5064 if (peer_secid == SECSID_NULL)
5065 return -EINVAL;
5066 return 0;
5069 static int selinux_sk_alloc_security(struct sock *sk, int family, gfp_t priority)
5071 struct sk_security_struct *sksec;
5073 sksec = kzalloc(sizeof(*sksec), priority);
5074 if (!sksec)
5075 return -ENOMEM;
5077 sksec->peer_sid = SECINITSID_UNLABELED;
5078 sksec->sid = SECINITSID_UNLABELED;
5079 sksec->sclass = SECCLASS_SOCKET;
5080 selinux_netlbl_sk_security_reset(sksec);
5081 sk->sk_security = sksec;
5083 return 0;
5086 static void selinux_sk_free_security(struct sock *sk)
5088 struct sk_security_struct *sksec = sk->sk_security;
5090 sk->sk_security = NULL;
5091 selinux_netlbl_sk_security_free(sksec);
5092 kfree(sksec);
5095 static void selinux_sk_clone_security(const struct sock *sk, struct sock *newsk)
5097 struct sk_security_struct *sksec = sk->sk_security;
5098 struct sk_security_struct *newsksec = newsk->sk_security;
5100 newsksec->sid = sksec->sid;
5101 newsksec->peer_sid = sksec->peer_sid;
5102 newsksec->sclass = sksec->sclass;
5104 selinux_netlbl_sk_security_reset(newsksec);
5107 static void selinux_sk_getsecid(struct sock *sk, u32 *secid)
5109 if (!sk)
5110 *secid = SECINITSID_ANY_SOCKET;
5111 else {
5112 struct sk_security_struct *sksec = sk->sk_security;
5114 *secid = sksec->sid;
5118 static void selinux_sock_graft(struct sock *sk, struct socket *parent)
5120 struct inode_security_struct *isec =
5121 inode_security_novalidate(SOCK_INODE(parent));
5122 struct sk_security_struct *sksec = sk->sk_security;
5124 if (sk->sk_family == PF_INET || sk->sk_family == PF_INET6 ||
5125 sk->sk_family == PF_UNIX)
5126 isec->sid = sksec->sid;
5127 sksec->sclass = isec->sclass;
5130 /* Called whenever SCTP receives an INIT chunk. This happens when an incoming
5131 * connect(2), sctp_connectx(3) or sctp_sendmsg(3) (with no association
5132 * already present).
5134 static int selinux_sctp_assoc_request(struct sctp_endpoint *ep,
5135 struct sk_buff *skb)
5137 struct sk_security_struct *sksec = ep->base.sk->sk_security;
5138 struct common_audit_data ad;
5139 struct lsm_network_audit net = {0,};
5140 u8 peerlbl_active;
5141 u32 peer_sid = SECINITSID_UNLABELED;
5142 u32 conn_sid;
5143 int err = 0;
5145 if (!selinux_policycap_extsockclass())
5146 return 0;
5148 peerlbl_active = selinux_peerlbl_enabled();
5150 if (peerlbl_active) {
5151 /* This will return peer_sid = SECSID_NULL if there are
5152 * no peer labels, see security_net_peersid_resolve().
5154 err = selinux_skb_peerlbl_sid(skb, ep->base.sk->sk_family,
5155 &peer_sid);
5156 if (err)
5157 return err;
5159 if (peer_sid == SECSID_NULL)
5160 peer_sid = SECINITSID_UNLABELED;
5163 if (sksec->sctp_assoc_state == SCTP_ASSOC_UNSET) {
5164 sksec->sctp_assoc_state = SCTP_ASSOC_SET;
5166 /* Here as first association on socket. As the peer SID
5167 * was allowed by peer recv (and the netif/node checks),
5168 * then it is approved by policy and used as the primary
5169 * peer SID for getpeercon(3).
5171 sksec->peer_sid = peer_sid;
5172 } else if (sksec->peer_sid != peer_sid) {
5173 /* Other association peer SIDs are checked to enforce
5174 * consistency among the peer SIDs.
5176 ad.type = LSM_AUDIT_DATA_NET;
5177 ad.u.net = &net;
5178 ad.u.net->sk = ep->base.sk;
5179 err = avc_has_perm(&selinux_state,
5180 sksec->peer_sid, peer_sid, sksec->sclass,
5181 SCTP_SOCKET__ASSOCIATION, &ad);
5182 if (err)
5183 return err;
5186 /* Compute the MLS component for the connection and store
5187 * the information in ep. This will be used by SCTP TCP type
5188 * sockets and peeled off connections as they cause a new
5189 * socket to be generated. selinux_sctp_sk_clone() will then
5190 * plug this into the new socket.
5192 err = selinux_conn_sid(sksec->sid, peer_sid, &conn_sid);
5193 if (err)
5194 return err;
5196 ep->secid = conn_sid;
5197 ep->peer_secid = peer_sid;
5199 /* Set any NetLabel labels including CIPSO/CALIPSO options. */
5200 return selinux_netlbl_sctp_assoc_request(ep, skb);
5203 /* Check if sctp IPv4/IPv6 addresses are valid for binding or connecting
5204 * based on their @optname.
5206 static int selinux_sctp_bind_connect(struct sock *sk, int optname,
5207 struct sockaddr *address,
5208 int addrlen)
5210 int len, err = 0, walk_size = 0;
5211 void *addr_buf;
5212 struct sockaddr *addr;
5213 struct socket *sock;
5215 if (!selinux_policycap_extsockclass())
5216 return 0;
5218 /* Process one or more addresses that may be IPv4 or IPv6 */
5219 sock = sk->sk_socket;
5220 addr_buf = address;
5222 while (walk_size < addrlen) {
5223 if (walk_size + sizeof(sa_family_t) > addrlen)
5224 return -EINVAL;
5226 addr = addr_buf;
5227 switch (addr->sa_family) {
5228 case AF_UNSPEC:
5229 case AF_INET:
5230 len = sizeof(struct sockaddr_in);
5231 break;
5232 case AF_INET6:
5233 len = sizeof(struct sockaddr_in6);
5234 break;
5235 default:
5236 return -EINVAL;
5239 if (walk_size + len > addrlen)
5240 return -EINVAL;
5242 err = -EINVAL;
5243 switch (optname) {
5244 /* Bind checks */
5245 case SCTP_PRIMARY_ADDR:
5246 case SCTP_SET_PEER_PRIMARY_ADDR:
5247 case SCTP_SOCKOPT_BINDX_ADD:
5248 err = selinux_socket_bind(sock, addr, len);
5249 break;
5250 /* Connect checks */
5251 case SCTP_SOCKOPT_CONNECTX:
5252 case SCTP_PARAM_SET_PRIMARY:
5253 case SCTP_PARAM_ADD_IP:
5254 case SCTP_SENDMSG_CONNECT:
5255 err = selinux_socket_connect_helper(sock, addr, len);
5256 if (err)
5257 return err;
5259 /* As selinux_sctp_bind_connect() is called by the
5260 * SCTP protocol layer, the socket is already locked,
5261 * therefore selinux_netlbl_socket_connect_locked() is
5262 * is called here. The situations handled are:
5263 * sctp_connectx(3), sctp_sendmsg(3), sendmsg(2),
5264 * whenever a new IP address is added or when a new
5265 * primary address is selected.
5266 * Note that an SCTP connect(2) call happens before
5267 * the SCTP protocol layer and is handled via
5268 * selinux_socket_connect().
5270 err = selinux_netlbl_socket_connect_locked(sk, addr);
5271 break;
5274 if (err)
5275 return err;
5277 addr_buf += len;
5278 walk_size += len;
5281 return 0;
5284 /* Called whenever a new socket is created by accept(2) or sctp_peeloff(3). */
5285 static void selinux_sctp_sk_clone(struct sctp_endpoint *ep, struct sock *sk,
5286 struct sock *newsk)
5288 struct sk_security_struct *sksec = sk->sk_security;
5289 struct sk_security_struct *newsksec = newsk->sk_security;
5291 /* If policy does not support SECCLASS_SCTP_SOCKET then call
5292 * the non-sctp clone version.
5294 if (!selinux_policycap_extsockclass())
5295 return selinux_sk_clone_security(sk, newsk);
5297 newsksec->sid = ep->secid;
5298 newsksec->peer_sid = ep->peer_secid;
5299 newsksec->sclass = sksec->sclass;
5300 selinux_netlbl_sctp_sk_clone(sk, newsk);
5303 static int selinux_inet_conn_request(struct sock *sk, struct sk_buff *skb,
5304 struct request_sock *req)
5306 struct sk_security_struct *sksec = sk->sk_security;
5307 int err;
5308 u16 family = req->rsk_ops->family;
5309 u32 connsid;
5310 u32 peersid;
5312 err = selinux_skb_peerlbl_sid(skb, family, &peersid);
5313 if (err)
5314 return err;
5315 err = selinux_conn_sid(sksec->sid, peersid, &connsid);
5316 if (err)
5317 return err;
5318 req->secid = connsid;
5319 req->peer_secid = peersid;
5321 return selinux_netlbl_inet_conn_request(req, family);
5324 static void selinux_inet_csk_clone(struct sock *newsk,
5325 const struct request_sock *req)
5327 struct sk_security_struct *newsksec = newsk->sk_security;
5329 newsksec->sid = req->secid;
5330 newsksec->peer_sid = req->peer_secid;
5331 /* NOTE: Ideally, we should also get the isec->sid for the
5332 new socket in sync, but we don't have the isec available yet.
5333 So we will wait until sock_graft to do it, by which
5334 time it will have been created and available. */
5336 /* We don't need to take any sort of lock here as we are the only
5337 * thread with access to newsksec */
5338 selinux_netlbl_inet_csk_clone(newsk, req->rsk_ops->family);
5341 static void selinux_inet_conn_established(struct sock *sk, struct sk_buff *skb)
5343 u16 family = sk->sk_family;
5344 struct sk_security_struct *sksec = sk->sk_security;
5346 /* handle mapped IPv4 packets arriving via IPv6 sockets */
5347 if (family == PF_INET6 && skb->protocol == htons(ETH_P_IP))
5348 family = PF_INET;
5350 selinux_skb_peerlbl_sid(skb, family, &sksec->peer_sid);
5353 static int selinux_secmark_relabel_packet(u32 sid)
5355 const struct task_security_struct *__tsec;
5356 u32 tsid;
5358 __tsec = selinux_cred(current_cred());
5359 tsid = __tsec->sid;
5361 return avc_has_perm(&selinux_state,
5362 tsid, sid, SECCLASS_PACKET, PACKET__RELABELTO,
5363 NULL);
5366 static void selinux_secmark_refcount_inc(void)
5368 atomic_inc(&selinux_secmark_refcount);
5371 static void selinux_secmark_refcount_dec(void)
5373 atomic_dec(&selinux_secmark_refcount);
5376 static void selinux_req_classify_flow(const struct request_sock *req,
5377 struct flowi *fl)
5379 fl->flowi_secid = req->secid;
5382 static int selinux_tun_dev_alloc_security(void **security)
5384 struct tun_security_struct *tunsec;
5386 tunsec = kzalloc(sizeof(*tunsec), GFP_KERNEL);
5387 if (!tunsec)
5388 return -ENOMEM;
5389 tunsec->sid = current_sid();
5391 *security = tunsec;
5392 return 0;
5395 static void selinux_tun_dev_free_security(void *security)
5397 kfree(security);
5400 static int selinux_tun_dev_create(void)
5402 u32 sid = current_sid();
5404 /* we aren't taking into account the "sockcreate" SID since the socket
5405 * that is being created here is not a socket in the traditional sense,
5406 * instead it is a private sock, accessible only to the kernel, and
5407 * representing a wide range of network traffic spanning multiple
5408 * connections unlike traditional sockets - check the TUN driver to
5409 * get a better understanding of why this socket is special */
5411 return avc_has_perm(&selinux_state,
5412 sid, sid, SECCLASS_TUN_SOCKET, TUN_SOCKET__CREATE,
5413 NULL);
5416 static int selinux_tun_dev_attach_queue(void *security)
5418 struct tun_security_struct *tunsec = security;
5420 return avc_has_perm(&selinux_state,
5421 current_sid(), tunsec->sid, SECCLASS_TUN_SOCKET,
5422 TUN_SOCKET__ATTACH_QUEUE, NULL);
5425 static int selinux_tun_dev_attach(struct sock *sk, void *security)
5427 struct tun_security_struct *tunsec = security;
5428 struct sk_security_struct *sksec = sk->sk_security;
5430 /* we don't currently perform any NetLabel based labeling here and it
5431 * isn't clear that we would want to do so anyway; while we could apply
5432 * labeling without the support of the TUN user the resulting labeled
5433 * traffic from the other end of the connection would almost certainly
5434 * cause confusion to the TUN user that had no idea network labeling
5435 * protocols were being used */
5437 sksec->sid = tunsec->sid;
5438 sksec->sclass = SECCLASS_TUN_SOCKET;
5440 return 0;
5443 static int selinux_tun_dev_open(void *security)
5445 struct tun_security_struct *tunsec = security;
5446 u32 sid = current_sid();
5447 int err;
5449 err = avc_has_perm(&selinux_state,
5450 sid, tunsec->sid, SECCLASS_TUN_SOCKET,
5451 TUN_SOCKET__RELABELFROM, NULL);
5452 if (err)
5453 return err;
5454 err = avc_has_perm(&selinux_state,
5455 sid, sid, SECCLASS_TUN_SOCKET,
5456 TUN_SOCKET__RELABELTO, NULL);
5457 if (err)
5458 return err;
5459 tunsec->sid = sid;
5461 return 0;
5464 static int selinux_nlmsg_perm(struct sock *sk, struct sk_buff *skb)
5466 int err = 0;
5467 u32 perm;
5468 struct nlmsghdr *nlh;
5469 struct sk_security_struct *sksec = sk->sk_security;
5471 if (skb->len < NLMSG_HDRLEN) {
5472 err = -EINVAL;
5473 goto out;
5475 nlh = nlmsg_hdr(skb);
5477 err = selinux_nlmsg_lookup(sksec->sclass, nlh->nlmsg_type, &perm);
5478 if (err) {
5479 if (err == -EINVAL) {
5480 pr_warn_ratelimited("SELinux: unrecognized netlink"
5481 " message: protocol=%hu nlmsg_type=%hu sclass=%s"
5482 " pig=%d comm=%s\n",
5483 sk->sk_protocol, nlh->nlmsg_type,
5484 secclass_map[sksec->sclass - 1].name,
5485 task_pid_nr(current), current->comm);
5486 if (!enforcing_enabled(&selinux_state) ||
5487 security_get_allow_unknown(&selinux_state))
5488 err = 0;
5491 /* Ignore */
5492 if (err == -ENOENT)
5493 err = 0;
5494 goto out;
5497 err = sock_has_perm(sk, perm);
5498 out:
5499 return err;
5502 #ifdef CONFIG_NETFILTER
5504 static unsigned int selinux_ip_forward(struct sk_buff *skb,
5505 const struct net_device *indev,
5506 u16 family)
5508 int err;
5509 char *addrp;
5510 u32 peer_sid;
5511 struct common_audit_data ad;
5512 struct lsm_network_audit net = {0,};
5513 u8 secmark_active;
5514 u8 netlbl_active;
5515 u8 peerlbl_active;
5517 if (!selinux_policycap_netpeer())
5518 return NF_ACCEPT;
5520 secmark_active = selinux_secmark_enabled();
5521 netlbl_active = netlbl_enabled();
5522 peerlbl_active = selinux_peerlbl_enabled();
5523 if (!secmark_active && !peerlbl_active)
5524 return NF_ACCEPT;
5526 if (selinux_skb_peerlbl_sid(skb, family, &peer_sid) != 0)
5527 return NF_DROP;
5529 ad.type = LSM_AUDIT_DATA_NET;
5530 ad.u.net = &net;
5531 ad.u.net->netif = indev->ifindex;
5532 ad.u.net->family = family;
5533 if (selinux_parse_skb(skb, &ad, &addrp, 1, NULL) != 0)
5534 return NF_DROP;
5536 if (peerlbl_active) {
5537 err = selinux_inet_sys_rcv_skb(dev_net(indev), indev->ifindex,
5538 addrp, family, peer_sid, &ad);
5539 if (err) {
5540 selinux_netlbl_err(skb, family, err, 1);
5541 return NF_DROP;
5545 if (secmark_active)
5546 if (avc_has_perm(&selinux_state,
5547 peer_sid, skb->secmark,
5548 SECCLASS_PACKET, PACKET__FORWARD_IN, &ad))
5549 return NF_DROP;
5551 if (netlbl_active)
5552 /* we do this in the FORWARD path and not the POST_ROUTING
5553 * path because we want to make sure we apply the necessary
5554 * labeling before IPsec is applied so we can leverage AH
5555 * protection */
5556 if (selinux_netlbl_skbuff_setsid(skb, family, peer_sid) != 0)
5557 return NF_DROP;
5559 return NF_ACCEPT;
5562 static unsigned int selinux_ipv4_forward(void *priv,
5563 struct sk_buff *skb,
5564 const struct nf_hook_state *state)
5566 return selinux_ip_forward(skb, state->in, PF_INET);
5569 #if IS_ENABLED(CONFIG_IPV6)
5570 static unsigned int selinux_ipv6_forward(void *priv,
5571 struct sk_buff *skb,
5572 const struct nf_hook_state *state)
5574 return selinux_ip_forward(skb, state->in, PF_INET6);
5576 #endif /* IPV6 */
5578 static unsigned int selinux_ip_output(struct sk_buff *skb,
5579 u16 family)
5581 struct sock *sk;
5582 u32 sid;
5584 if (!netlbl_enabled())
5585 return NF_ACCEPT;
5587 /* we do this in the LOCAL_OUT path and not the POST_ROUTING path
5588 * because we want to make sure we apply the necessary labeling
5589 * before IPsec is applied so we can leverage AH protection */
5590 sk = skb->sk;
5591 if (sk) {
5592 struct sk_security_struct *sksec;
5594 if (sk_listener(sk))
5595 /* if the socket is the listening state then this
5596 * packet is a SYN-ACK packet which means it needs to
5597 * be labeled based on the connection/request_sock and
5598 * not the parent socket. unfortunately, we can't
5599 * lookup the request_sock yet as it isn't queued on
5600 * the parent socket until after the SYN-ACK is sent.
5601 * the "solution" is to simply pass the packet as-is
5602 * as any IP option based labeling should be copied
5603 * from the initial connection request (in the IP
5604 * layer). it is far from ideal, but until we get a
5605 * security label in the packet itself this is the
5606 * best we can do. */
5607 return NF_ACCEPT;
5609 /* standard practice, label using the parent socket */
5610 sksec = sk->sk_security;
5611 sid = sksec->sid;
5612 } else
5613 sid = SECINITSID_KERNEL;
5614 if (selinux_netlbl_skbuff_setsid(skb, family, sid) != 0)
5615 return NF_DROP;
5617 return NF_ACCEPT;
5620 static unsigned int selinux_ipv4_output(void *priv,
5621 struct sk_buff *skb,
5622 const struct nf_hook_state *state)
5624 return selinux_ip_output(skb, PF_INET);
5627 #if IS_ENABLED(CONFIG_IPV6)
5628 static unsigned int selinux_ipv6_output(void *priv,
5629 struct sk_buff *skb,
5630 const struct nf_hook_state *state)
5632 return selinux_ip_output(skb, PF_INET6);
5634 #endif /* IPV6 */
5636 static unsigned int selinux_ip_postroute_compat(struct sk_buff *skb,
5637 int ifindex,
5638 u16 family)
5640 struct sock *sk = skb_to_full_sk(skb);
5641 struct sk_security_struct *sksec;
5642 struct common_audit_data ad;
5643 struct lsm_network_audit net = {0,};
5644 char *addrp;
5645 u8 proto;
5647 if (sk == NULL)
5648 return NF_ACCEPT;
5649 sksec = sk->sk_security;
5651 ad.type = LSM_AUDIT_DATA_NET;
5652 ad.u.net = &net;
5653 ad.u.net->netif = ifindex;
5654 ad.u.net->family = family;
5655 if (selinux_parse_skb(skb, &ad, &addrp, 0, &proto))
5656 return NF_DROP;
5658 if (selinux_secmark_enabled())
5659 if (avc_has_perm(&selinux_state,
5660 sksec->sid, skb->secmark,
5661 SECCLASS_PACKET, PACKET__SEND, &ad))
5662 return NF_DROP_ERR(-ECONNREFUSED);
5664 if (selinux_xfrm_postroute_last(sksec->sid, skb, &ad, proto))
5665 return NF_DROP_ERR(-ECONNREFUSED);
5667 return NF_ACCEPT;
5670 static unsigned int selinux_ip_postroute(struct sk_buff *skb,
5671 const struct net_device *outdev,
5672 u16 family)
5674 u32 secmark_perm;
5675 u32 peer_sid;
5676 int ifindex = outdev->ifindex;
5677 struct sock *sk;
5678 struct common_audit_data ad;
5679 struct lsm_network_audit net = {0,};
5680 char *addrp;
5681 u8 secmark_active;
5682 u8 peerlbl_active;
5684 /* If any sort of compatibility mode is enabled then handoff processing
5685 * to the selinux_ip_postroute_compat() function to deal with the
5686 * special handling. We do this in an attempt to keep this function
5687 * as fast and as clean as possible. */
5688 if (!selinux_policycap_netpeer())
5689 return selinux_ip_postroute_compat(skb, ifindex, family);
5691 secmark_active = selinux_secmark_enabled();
5692 peerlbl_active = selinux_peerlbl_enabled();
5693 if (!secmark_active && !peerlbl_active)
5694 return NF_ACCEPT;
5696 sk = skb_to_full_sk(skb);
5698 #ifdef CONFIG_XFRM
5699 /* If skb->dst->xfrm is non-NULL then the packet is undergoing an IPsec
5700 * packet transformation so allow the packet to pass without any checks
5701 * since we'll have another chance to perform access control checks
5702 * when the packet is on it's final way out.
5703 * NOTE: there appear to be some IPv6 multicast cases where skb->dst
5704 * is NULL, in this case go ahead and apply access control.
5705 * NOTE: if this is a local socket (skb->sk != NULL) that is in the
5706 * TCP listening state we cannot wait until the XFRM processing
5707 * is done as we will miss out on the SA label if we do;
5708 * unfortunately, this means more work, but it is only once per
5709 * connection. */
5710 if (skb_dst(skb) != NULL && skb_dst(skb)->xfrm != NULL &&
5711 !(sk && sk_listener(sk)))
5712 return NF_ACCEPT;
5713 #endif
5715 if (sk == NULL) {
5716 /* Without an associated socket the packet is either coming
5717 * from the kernel or it is being forwarded; check the packet
5718 * to determine which and if the packet is being forwarded
5719 * query the packet directly to determine the security label. */
5720 if (skb->skb_iif) {
5721 secmark_perm = PACKET__FORWARD_OUT;
5722 if (selinux_skb_peerlbl_sid(skb, family, &peer_sid))
5723 return NF_DROP;
5724 } else {
5725 secmark_perm = PACKET__SEND;
5726 peer_sid = SECINITSID_KERNEL;
5728 } else if (sk_listener(sk)) {
5729 /* Locally generated packet but the associated socket is in the
5730 * listening state which means this is a SYN-ACK packet. In
5731 * this particular case the correct security label is assigned
5732 * to the connection/request_sock but unfortunately we can't
5733 * query the request_sock as it isn't queued on the parent
5734 * socket until after the SYN-ACK packet is sent; the only
5735 * viable choice is to regenerate the label like we do in
5736 * selinux_inet_conn_request(). See also selinux_ip_output()
5737 * for similar problems. */
5738 u32 skb_sid;
5739 struct sk_security_struct *sksec;
5741 sksec = sk->sk_security;
5742 if (selinux_skb_peerlbl_sid(skb, family, &skb_sid))
5743 return NF_DROP;
5744 /* At this point, if the returned skb peerlbl is SECSID_NULL
5745 * and the packet has been through at least one XFRM
5746 * transformation then we must be dealing with the "final"
5747 * form of labeled IPsec packet; since we've already applied
5748 * all of our access controls on this packet we can safely
5749 * pass the packet. */
5750 if (skb_sid == SECSID_NULL) {
5751 switch (family) {
5752 case PF_INET:
5753 if (IPCB(skb)->flags & IPSKB_XFRM_TRANSFORMED)
5754 return NF_ACCEPT;
5755 break;
5756 case PF_INET6:
5757 if (IP6CB(skb)->flags & IP6SKB_XFRM_TRANSFORMED)
5758 return NF_ACCEPT;
5759 break;
5760 default:
5761 return NF_DROP_ERR(-ECONNREFUSED);
5764 if (selinux_conn_sid(sksec->sid, skb_sid, &peer_sid))
5765 return NF_DROP;
5766 secmark_perm = PACKET__SEND;
5767 } else {
5768 /* Locally generated packet, fetch the security label from the
5769 * associated socket. */
5770 struct sk_security_struct *sksec = sk->sk_security;
5771 peer_sid = sksec->sid;
5772 secmark_perm = PACKET__SEND;
5775 ad.type = LSM_AUDIT_DATA_NET;
5776 ad.u.net = &net;
5777 ad.u.net->netif = ifindex;
5778 ad.u.net->family = family;
5779 if (selinux_parse_skb(skb, &ad, &addrp, 0, NULL))
5780 return NF_DROP;
5782 if (secmark_active)
5783 if (avc_has_perm(&selinux_state,
5784 peer_sid, skb->secmark,
5785 SECCLASS_PACKET, secmark_perm, &ad))
5786 return NF_DROP_ERR(-ECONNREFUSED);
5788 if (peerlbl_active) {
5789 u32 if_sid;
5790 u32 node_sid;
5792 if (sel_netif_sid(dev_net(outdev), ifindex, &if_sid))
5793 return NF_DROP;
5794 if (avc_has_perm(&selinux_state,
5795 peer_sid, if_sid,
5796 SECCLASS_NETIF, NETIF__EGRESS, &ad))
5797 return NF_DROP_ERR(-ECONNREFUSED);
5799 if (sel_netnode_sid(addrp, family, &node_sid))
5800 return NF_DROP;
5801 if (avc_has_perm(&selinux_state,
5802 peer_sid, node_sid,
5803 SECCLASS_NODE, NODE__SENDTO, &ad))
5804 return NF_DROP_ERR(-ECONNREFUSED);
5807 return NF_ACCEPT;
5810 static unsigned int selinux_ipv4_postroute(void *priv,
5811 struct sk_buff *skb,
5812 const struct nf_hook_state *state)
5814 return selinux_ip_postroute(skb, state->out, PF_INET);
5817 #if IS_ENABLED(CONFIG_IPV6)
5818 static unsigned int selinux_ipv6_postroute(void *priv,
5819 struct sk_buff *skb,
5820 const struct nf_hook_state *state)
5822 return selinux_ip_postroute(skb, state->out, PF_INET6);
5824 #endif /* IPV6 */
5826 #endif /* CONFIG_NETFILTER */
5828 static int selinux_netlink_send(struct sock *sk, struct sk_buff *skb)
5830 return selinux_nlmsg_perm(sk, skb);
5833 static void ipc_init_security(struct ipc_security_struct *isec, u16 sclass)
5835 isec->sclass = sclass;
5836 isec->sid = current_sid();
5839 static int msg_msg_alloc_security(struct msg_msg *msg)
5841 struct msg_security_struct *msec;
5843 msec = selinux_msg_msg(msg);
5844 msec->sid = SECINITSID_UNLABELED;
5846 return 0;
5849 static int ipc_has_perm(struct kern_ipc_perm *ipc_perms,
5850 u32 perms)
5852 struct ipc_security_struct *isec;
5853 struct common_audit_data ad;
5854 u32 sid = current_sid();
5856 isec = selinux_ipc(ipc_perms);
5858 ad.type = LSM_AUDIT_DATA_IPC;
5859 ad.u.ipc_id = ipc_perms->key;
5861 return avc_has_perm(&selinux_state,
5862 sid, isec->sid, isec->sclass, perms, &ad);
5865 static int selinux_msg_msg_alloc_security(struct msg_msg *msg)
5867 return msg_msg_alloc_security(msg);
5870 /* message queue security operations */
5871 static int selinux_msg_queue_alloc_security(struct kern_ipc_perm *msq)
5873 struct ipc_security_struct *isec;
5874 struct common_audit_data ad;
5875 u32 sid = current_sid();
5876 int rc;
5878 isec = selinux_ipc(msq);
5879 ipc_init_security(isec, SECCLASS_MSGQ);
5881 ad.type = LSM_AUDIT_DATA_IPC;
5882 ad.u.ipc_id = msq->key;
5884 rc = avc_has_perm(&selinux_state,
5885 sid, isec->sid, SECCLASS_MSGQ,
5886 MSGQ__CREATE, &ad);
5887 return rc;
5890 static int selinux_msg_queue_associate(struct kern_ipc_perm *msq, int msqflg)
5892 struct ipc_security_struct *isec;
5893 struct common_audit_data ad;
5894 u32 sid = current_sid();
5896 isec = selinux_ipc(msq);
5898 ad.type = LSM_AUDIT_DATA_IPC;
5899 ad.u.ipc_id = msq->key;
5901 return avc_has_perm(&selinux_state,
5902 sid, isec->sid, SECCLASS_MSGQ,
5903 MSGQ__ASSOCIATE, &ad);
5906 static int selinux_msg_queue_msgctl(struct kern_ipc_perm *msq, int cmd)
5908 int err;
5909 int perms;
5911 switch (cmd) {
5912 case IPC_INFO:
5913 case MSG_INFO:
5914 /* No specific object, just general system-wide information. */
5915 return avc_has_perm(&selinux_state,
5916 current_sid(), SECINITSID_KERNEL,
5917 SECCLASS_SYSTEM, SYSTEM__IPC_INFO, NULL);
5918 case IPC_STAT:
5919 case MSG_STAT:
5920 case MSG_STAT_ANY:
5921 perms = MSGQ__GETATTR | MSGQ__ASSOCIATE;
5922 break;
5923 case IPC_SET:
5924 perms = MSGQ__SETATTR;
5925 break;
5926 case IPC_RMID:
5927 perms = MSGQ__DESTROY;
5928 break;
5929 default:
5930 return 0;
5933 err = ipc_has_perm(msq, perms);
5934 return err;
5937 static int selinux_msg_queue_msgsnd(struct kern_ipc_perm *msq, struct msg_msg *msg, int msqflg)
5939 struct ipc_security_struct *isec;
5940 struct msg_security_struct *msec;
5941 struct common_audit_data ad;
5942 u32 sid = current_sid();
5943 int rc;
5945 isec = selinux_ipc(msq);
5946 msec = selinux_msg_msg(msg);
5949 * First time through, need to assign label to the message
5951 if (msec->sid == SECINITSID_UNLABELED) {
5953 * Compute new sid based on current process and
5954 * message queue this message will be stored in
5956 rc = security_transition_sid(&selinux_state, sid, isec->sid,
5957 SECCLASS_MSG, NULL, &msec->sid);
5958 if (rc)
5959 return rc;
5962 ad.type = LSM_AUDIT_DATA_IPC;
5963 ad.u.ipc_id = msq->key;
5965 /* Can this process write to the queue? */
5966 rc = avc_has_perm(&selinux_state,
5967 sid, isec->sid, SECCLASS_MSGQ,
5968 MSGQ__WRITE, &ad);
5969 if (!rc)
5970 /* Can this process send the message */
5971 rc = avc_has_perm(&selinux_state,
5972 sid, msec->sid, SECCLASS_MSG,
5973 MSG__SEND, &ad);
5974 if (!rc)
5975 /* Can the message be put in the queue? */
5976 rc = avc_has_perm(&selinux_state,
5977 msec->sid, isec->sid, SECCLASS_MSGQ,
5978 MSGQ__ENQUEUE, &ad);
5980 return rc;
5983 static int selinux_msg_queue_msgrcv(struct kern_ipc_perm *msq, struct msg_msg *msg,
5984 struct task_struct *target,
5985 long type, int mode)
5987 struct ipc_security_struct *isec;
5988 struct msg_security_struct *msec;
5989 struct common_audit_data ad;
5990 u32 sid = task_sid(target);
5991 int rc;
5993 isec = selinux_ipc(msq);
5994 msec = selinux_msg_msg(msg);
5996 ad.type = LSM_AUDIT_DATA_IPC;
5997 ad.u.ipc_id = msq->key;
5999 rc = avc_has_perm(&selinux_state,
6000 sid, isec->sid,
6001 SECCLASS_MSGQ, MSGQ__READ, &ad);
6002 if (!rc)
6003 rc = avc_has_perm(&selinux_state,
6004 sid, msec->sid,
6005 SECCLASS_MSG, MSG__RECEIVE, &ad);
6006 return rc;
6009 /* Shared Memory security operations */
6010 static int selinux_shm_alloc_security(struct kern_ipc_perm *shp)
6012 struct ipc_security_struct *isec;
6013 struct common_audit_data ad;
6014 u32 sid = current_sid();
6015 int rc;
6017 isec = selinux_ipc(shp);
6018 ipc_init_security(isec, SECCLASS_SHM);
6020 ad.type = LSM_AUDIT_DATA_IPC;
6021 ad.u.ipc_id = shp->key;
6023 rc = avc_has_perm(&selinux_state,
6024 sid, isec->sid, SECCLASS_SHM,
6025 SHM__CREATE, &ad);
6026 return rc;
6029 static int selinux_shm_associate(struct kern_ipc_perm *shp, int shmflg)
6031 struct ipc_security_struct *isec;
6032 struct common_audit_data ad;
6033 u32 sid = current_sid();
6035 isec = selinux_ipc(shp);
6037 ad.type = LSM_AUDIT_DATA_IPC;
6038 ad.u.ipc_id = shp->key;
6040 return avc_has_perm(&selinux_state,
6041 sid, isec->sid, SECCLASS_SHM,
6042 SHM__ASSOCIATE, &ad);
6045 /* Note, at this point, shp is locked down */
6046 static int selinux_shm_shmctl(struct kern_ipc_perm *shp, int cmd)
6048 int perms;
6049 int err;
6051 switch (cmd) {
6052 case IPC_INFO:
6053 case SHM_INFO:
6054 /* No specific object, just general system-wide information. */
6055 return avc_has_perm(&selinux_state,
6056 current_sid(), SECINITSID_KERNEL,
6057 SECCLASS_SYSTEM, SYSTEM__IPC_INFO, NULL);
6058 case IPC_STAT:
6059 case SHM_STAT:
6060 case SHM_STAT_ANY:
6061 perms = SHM__GETATTR | SHM__ASSOCIATE;
6062 break;
6063 case IPC_SET:
6064 perms = SHM__SETATTR;
6065 break;
6066 case SHM_LOCK:
6067 case SHM_UNLOCK:
6068 perms = SHM__LOCK;
6069 break;
6070 case IPC_RMID:
6071 perms = SHM__DESTROY;
6072 break;
6073 default:
6074 return 0;
6077 err = ipc_has_perm(shp, perms);
6078 return err;
6081 static int selinux_shm_shmat(struct kern_ipc_perm *shp,
6082 char __user *shmaddr, int shmflg)
6084 u32 perms;
6086 if (shmflg & SHM_RDONLY)
6087 perms = SHM__READ;
6088 else
6089 perms = SHM__READ | SHM__WRITE;
6091 return ipc_has_perm(shp, perms);
6094 /* Semaphore security operations */
6095 static int selinux_sem_alloc_security(struct kern_ipc_perm *sma)
6097 struct ipc_security_struct *isec;
6098 struct common_audit_data ad;
6099 u32 sid = current_sid();
6100 int rc;
6102 isec = selinux_ipc(sma);
6103 ipc_init_security(isec, SECCLASS_SEM);
6105 ad.type = LSM_AUDIT_DATA_IPC;
6106 ad.u.ipc_id = sma->key;
6108 rc = avc_has_perm(&selinux_state,
6109 sid, isec->sid, SECCLASS_SEM,
6110 SEM__CREATE, &ad);
6111 return rc;
6114 static int selinux_sem_associate(struct kern_ipc_perm *sma, int semflg)
6116 struct ipc_security_struct *isec;
6117 struct common_audit_data ad;
6118 u32 sid = current_sid();
6120 isec = selinux_ipc(sma);
6122 ad.type = LSM_AUDIT_DATA_IPC;
6123 ad.u.ipc_id = sma->key;
6125 return avc_has_perm(&selinux_state,
6126 sid, isec->sid, SECCLASS_SEM,
6127 SEM__ASSOCIATE, &ad);
6130 /* Note, at this point, sma is locked down */
6131 static int selinux_sem_semctl(struct kern_ipc_perm *sma, int cmd)
6133 int err;
6134 u32 perms;
6136 switch (cmd) {
6137 case IPC_INFO:
6138 case SEM_INFO:
6139 /* No specific object, just general system-wide information. */
6140 return avc_has_perm(&selinux_state,
6141 current_sid(), SECINITSID_KERNEL,
6142 SECCLASS_SYSTEM, SYSTEM__IPC_INFO, NULL);
6143 case GETPID:
6144 case GETNCNT:
6145 case GETZCNT:
6146 perms = SEM__GETATTR;
6147 break;
6148 case GETVAL:
6149 case GETALL:
6150 perms = SEM__READ;
6151 break;
6152 case SETVAL:
6153 case SETALL:
6154 perms = SEM__WRITE;
6155 break;
6156 case IPC_RMID:
6157 perms = SEM__DESTROY;
6158 break;
6159 case IPC_SET:
6160 perms = SEM__SETATTR;
6161 break;
6162 case IPC_STAT:
6163 case SEM_STAT:
6164 case SEM_STAT_ANY:
6165 perms = SEM__GETATTR | SEM__ASSOCIATE;
6166 break;
6167 default:
6168 return 0;
6171 err = ipc_has_perm(sma, perms);
6172 return err;
6175 static int selinux_sem_semop(struct kern_ipc_perm *sma,
6176 struct sembuf *sops, unsigned nsops, int alter)
6178 u32 perms;
6180 if (alter)
6181 perms = SEM__READ | SEM__WRITE;
6182 else
6183 perms = SEM__READ;
6185 return ipc_has_perm(sma, perms);
6188 static int selinux_ipc_permission(struct kern_ipc_perm *ipcp, short flag)
6190 u32 av = 0;
6192 av = 0;
6193 if (flag & S_IRUGO)
6194 av |= IPC__UNIX_READ;
6195 if (flag & S_IWUGO)
6196 av |= IPC__UNIX_WRITE;
6198 if (av == 0)
6199 return 0;
6201 return ipc_has_perm(ipcp, av);
6204 static void selinux_ipc_getsecid(struct kern_ipc_perm *ipcp, u32 *secid)
6206 struct ipc_security_struct *isec = selinux_ipc(ipcp);
6207 *secid = isec->sid;
6210 static void selinux_d_instantiate(struct dentry *dentry, struct inode *inode)
6212 if (inode)
6213 inode_doinit_with_dentry(inode, dentry);
6216 static int selinux_getprocattr(struct task_struct *p,
6217 char *name, char **value)
6219 const struct task_security_struct *__tsec;
6220 u32 sid;
6221 int error;
6222 unsigned len;
6224 rcu_read_lock();
6225 __tsec = selinux_cred(__task_cred(p));
6227 if (current != p) {
6228 error = avc_has_perm(&selinux_state,
6229 current_sid(), __tsec->sid,
6230 SECCLASS_PROCESS, PROCESS__GETATTR, NULL);
6231 if (error)
6232 goto bad;
6235 if (!strcmp(name, "current"))
6236 sid = __tsec->sid;
6237 else if (!strcmp(name, "prev"))
6238 sid = __tsec->osid;
6239 else if (!strcmp(name, "exec"))
6240 sid = __tsec->exec_sid;
6241 else if (!strcmp(name, "fscreate"))
6242 sid = __tsec->create_sid;
6243 else if (!strcmp(name, "keycreate"))
6244 sid = __tsec->keycreate_sid;
6245 else if (!strcmp(name, "sockcreate"))
6246 sid = __tsec->sockcreate_sid;
6247 else {
6248 error = -EINVAL;
6249 goto bad;
6251 rcu_read_unlock();
6253 if (!sid)
6254 return 0;
6256 error = security_sid_to_context(&selinux_state, sid, value, &len);
6257 if (error)
6258 return error;
6259 return len;
6261 bad:
6262 rcu_read_unlock();
6263 return error;
6266 static int selinux_setprocattr(const char *name, void *value, size_t size)
6268 struct task_security_struct *tsec;
6269 struct cred *new;
6270 u32 mysid = current_sid(), sid = 0, ptsid;
6271 int error;
6272 char *str = value;
6275 * Basic control over ability to set these attributes at all.
6277 if (!strcmp(name, "exec"))
6278 error = avc_has_perm(&selinux_state,
6279 mysid, mysid, SECCLASS_PROCESS,
6280 PROCESS__SETEXEC, NULL);
6281 else if (!strcmp(name, "fscreate"))
6282 error = avc_has_perm(&selinux_state,
6283 mysid, mysid, SECCLASS_PROCESS,
6284 PROCESS__SETFSCREATE, NULL);
6285 else if (!strcmp(name, "keycreate"))
6286 error = avc_has_perm(&selinux_state,
6287 mysid, mysid, SECCLASS_PROCESS,
6288 PROCESS__SETKEYCREATE, NULL);
6289 else if (!strcmp(name, "sockcreate"))
6290 error = avc_has_perm(&selinux_state,
6291 mysid, mysid, SECCLASS_PROCESS,
6292 PROCESS__SETSOCKCREATE, NULL);
6293 else if (!strcmp(name, "current"))
6294 error = avc_has_perm(&selinux_state,
6295 mysid, mysid, SECCLASS_PROCESS,
6296 PROCESS__SETCURRENT, NULL);
6297 else
6298 error = -EINVAL;
6299 if (error)
6300 return error;
6302 /* Obtain a SID for the context, if one was specified. */
6303 if (size && str[0] && str[0] != '\n') {
6304 if (str[size-1] == '\n') {
6305 str[size-1] = 0;
6306 size--;
6308 error = security_context_to_sid(&selinux_state, value, size,
6309 &sid, GFP_KERNEL);
6310 if (error == -EINVAL && !strcmp(name, "fscreate")) {
6311 if (!has_cap_mac_admin(true)) {
6312 struct audit_buffer *ab;
6313 size_t audit_size;
6315 /* We strip a nul only if it is at the end, otherwise the
6316 * context contains a nul and we should audit that */
6317 if (str[size - 1] == '\0')
6318 audit_size = size - 1;
6319 else
6320 audit_size = size;
6321 ab = audit_log_start(audit_context(),
6322 GFP_ATOMIC,
6323 AUDIT_SELINUX_ERR);
6324 audit_log_format(ab, "op=fscreate invalid_context=");
6325 audit_log_n_untrustedstring(ab, value, audit_size);
6326 audit_log_end(ab);
6328 return error;
6330 error = security_context_to_sid_force(
6331 &selinux_state,
6332 value, size, &sid);
6334 if (error)
6335 return error;
6338 new = prepare_creds();
6339 if (!new)
6340 return -ENOMEM;
6342 /* Permission checking based on the specified context is
6343 performed during the actual operation (execve,
6344 open/mkdir/...), when we know the full context of the
6345 operation. See selinux_bprm_set_creds for the execve
6346 checks and may_create for the file creation checks. The
6347 operation will then fail if the context is not permitted. */
6348 tsec = selinux_cred(new);
6349 if (!strcmp(name, "exec")) {
6350 tsec->exec_sid = sid;
6351 } else if (!strcmp(name, "fscreate")) {
6352 tsec->create_sid = sid;
6353 } else if (!strcmp(name, "keycreate")) {
6354 if (sid) {
6355 error = avc_has_perm(&selinux_state, mysid, sid,
6356 SECCLASS_KEY, KEY__CREATE, NULL);
6357 if (error)
6358 goto abort_change;
6360 tsec->keycreate_sid = sid;
6361 } else if (!strcmp(name, "sockcreate")) {
6362 tsec->sockcreate_sid = sid;
6363 } else if (!strcmp(name, "current")) {
6364 error = -EINVAL;
6365 if (sid == 0)
6366 goto abort_change;
6368 /* Only allow single threaded processes to change context */
6369 error = -EPERM;
6370 if (!current_is_single_threaded()) {
6371 error = security_bounded_transition(&selinux_state,
6372 tsec->sid, sid);
6373 if (error)
6374 goto abort_change;
6377 /* Check permissions for the transition. */
6378 error = avc_has_perm(&selinux_state,
6379 tsec->sid, sid, SECCLASS_PROCESS,
6380 PROCESS__DYNTRANSITION, NULL);
6381 if (error)
6382 goto abort_change;
6384 /* Check for ptracing, and update the task SID if ok.
6385 Otherwise, leave SID unchanged and fail. */
6386 ptsid = ptrace_parent_sid();
6387 if (ptsid != 0) {
6388 error = avc_has_perm(&selinux_state,
6389 ptsid, sid, SECCLASS_PROCESS,
6390 PROCESS__PTRACE, NULL);
6391 if (error)
6392 goto abort_change;
6395 tsec->sid = sid;
6396 } else {
6397 error = -EINVAL;
6398 goto abort_change;
6401 commit_creds(new);
6402 return size;
6404 abort_change:
6405 abort_creds(new);
6406 return error;
6409 static int selinux_ismaclabel(const char *name)
6411 return (strcmp(name, XATTR_SELINUX_SUFFIX) == 0);
6414 static int selinux_secid_to_secctx(u32 secid, char **secdata, u32 *seclen)
6416 return security_sid_to_context(&selinux_state, secid,
6417 secdata, seclen);
6420 static int selinux_secctx_to_secid(const char *secdata, u32 seclen, u32 *secid)
6422 return security_context_to_sid(&selinux_state, secdata, seclen,
6423 secid, GFP_KERNEL);
6426 static void selinux_release_secctx(char *secdata, u32 seclen)
6428 kfree(secdata);
6431 static void selinux_inode_invalidate_secctx(struct inode *inode)
6433 struct inode_security_struct *isec = selinux_inode(inode);
6435 spin_lock(&isec->lock);
6436 isec->initialized = LABEL_INVALID;
6437 spin_unlock(&isec->lock);
6441 * called with inode->i_mutex locked
6443 static int selinux_inode_notifysecctx(struct inode *inode, void *ctx, u32 ctxlen)
6445 int rc = selinux_inode_setsecurity(inode, XATTR_SELINUX_SUFFIX,
6446 ctx, ctxlen, 0);
6447 /* Do not return error when suppressing label (SBLABEL_MNT not set). */
6448 return rc == -EOPNOTSUPP ? 0 : rc;
6452 * called with inode->i_mutex locked
6454 static int selinux_inode_setsecctx(struct dentry *dentry, void *ctx, u32 ctxlen)
6456 return __vfs_setxattr_noperm(dentry, XATTR_NAME_SELINUX, ctx, ctxlen, 0);
6459 static int selinux_inode_getsecctx(struct inode *inode, void **ctx, u32 *ctxlen)
6461 int len = 0;
6462 len = selinux_inode_getsecurity(inode, XATTR_SELINUX_SUFFIX,
6463 ctx, true);
6464 if (len < 0)
6465 return len;
6466 *ctxlen = len;
6467 return 0;
6469 #ifdef CONFIG_KEYS
6471 static int selinux_key_alloc(struct key *k, const struct cred *cred,
6472 unsigned long flags)
6474 const struct task_security_struct *tsec;
6475 struct key_security_struct *ksec;
6477 ksec = kzalloc(sizeof(struct key_security_struct), GFP_KERNEL);
6478 if (!ksec)
6479 return -ENOMEM;
6481 tsec = selinux_cred(cred);
6482 if (tsec->keycreate_sid)
6483 ksec->sid = tsec->keycreate_sid;
6484 else
6485 ksec->sid = tsec->sid;
6487 k->security = ksec;
6488 return 0;
6491 static void selinux_key_free(struct key *k)
6493 struct key_security_struct *ksec = k->security;
6495 k->security = NULL;
6496 kfree(ksec);
6499 static int selinux_key_permission(key_ref_t key_ref,
6500 const struct cred *cred,
6501 unsigned perm)
6503 struct key *key;
6504 struct key_security_struct *ksec;
6505 u32 sid;
6507 /* if no specific permissions are requested, we skip the
6508 permission check. No serious, additional covert channels
6509 appear to be created. */
6510 if (perm == 0)
6511 return 0;
6513 sid = cred_sid(cred);
6515 key = key_ref_to_ptr(key_ref);
6516 ksec = key->security;
6518 return avc_has_perm(&selinux_state,
6519 sid, ksec->sid, SECCLASS_KEY, perm, NULL);
6522 static int selinux_key_getsecurity(struct key *key, char **_buffer)
6524 struct key_security_struct *ksec = key->security;
6525 char *context = NULL;
6526 unsigned len;
6527 int rc;
6529 rc = security_sid_to_context(&selinux_state, ksec->sid,
6530 &context, &len);
6531 if (!rc)
6532 rc = len;
6533 *_buffer = context;
6534 return rc;
6536 #endif
6538 #ifdef CONFIG_SECURITY_INFINIBAND
6539 static int selinux_ib_pkey_access(void *ib_sec, u64 subnet_prefix, u16 pkey_val)
6541 struct common_audit_data ad;
6542 int err;
6543 u32 sid = 0;
6544 struct ib_security_struct *sec = ib_sec;
6545 struct lsm_ibpkey_audit ibpkey;
6547 err = sel_ib_pkey_sid(subnet_prefix, pkey_val, &sid);
6548 if (err)
6549 return err;
6551 ad.type = LSM_AUDIT_DATA_IBPKEY;
6552 ibpkey.subnet_prefix = subnet_prefix;
6553 ibpkey.pkey = pkey_val;
6554 ad.u.ibpkey = &ibpkey;
6555 return avc_has_perm(&selinux_state,
6556 sec->sid, sid,
6557 SECCLASS_INFINIBAND_PKEY,
6558 INFINIBAND_PKEY__ACCESS, &ad);
6561 static int selinux_ib_endport_manage_subnet(void *ib_sec, const char *dev_name,
6562 u8 port_num)
6564 struct common_audit_data ad;
6565 int err;
6566 u32 sid = 0;
6567 struct ib_security_struct *sec = ib_sec;
6568 struct lsm_ibendport_audit ibendport;
6570 err = security_ib_endport_sid(&selinux_state, dev_name, port_num,
6571 &sid);
6573 if (err)
6574 return err;
6576 ad.type = LSM_AUDIT_DATA_IBENDPORT;
6577 strncpy(ibendport.dev_name, dev_name, sizeof(ibendport.dev_name));
6578 ibendport.port = port_num;
6579 ad.u.ibendport = &ibendport;
6580 return avc_has_perm(&selinux_state,
6581 sec->sid, sid,
6582 SECCLASS_INFINIBAND_ENDPORT,
6583 INFINIBAND_ENDPORT__MANAGE_SUBNET, &ad);
6586 static int selinux_ib_alloc_security(void **ib_sec)
6588 struct ib_security_struct *sec;
6590 sec = kzalloc(sizeof(*sec), GFP_KERNEL);
6591 if (!sec)
6592 return -ENOMEM;
6593 sec->sid = current_sid();
6595 *ib_sec = sec;
6596 return 0;
6599 static void selinux_ib_free_security(void *ib_sec)
6601 kfree(ib_sec);
6603 #endif
6605 #ifdef CONFIG_BPF_SYSCALL
6606 static int selinux_bpf(int cmd, union bpf_attr *attr,
6607 unsigned int size)
6609 u32 sid = current_sid();
6610 int ret;
6612 switch (cmd) {
6613 case BPF_MAP_CREATE:
6614 ret = avc_has_perm(&selinux_state,
6615 sid, sid, SECCLASS_BPF, BPF__MAP_CREATE,
6616 NULL);
6617 break;
6618 case BPF_PROG_LOAD:
6619 ret = avc_has_perm(&selinux_state,
6620 sid, sid, SECCLASS_BPF, BPF__PROG_LOAD,
6621 NULL);
6622 break;
6623 default:
6624 ret = 0;
6625 break;
6628 return ret;
6631 static u32 bpf_map_fmode_to_av(fmode_t fmode)
6633 u32 av = 0;
6635 if (fmode & FMODE_READ)
6636 av |= BPF__MAP_READ;
6637 if (fmode & FMODE_WRITE)
6638 av |= BPF__MAP_WRITE;
6639 return av;
6642 /* This function will check the file pass through unix socket or binder to see
6643 * if it is a bpf related object. And apply correspinding checks on the bpf
6644 * object based on the type. The bpf maps and programs, not like other files and
6645 * socket, are using a shared anonymous inode inside the kernel as their inode.
6646 * So checking that inode cannot identify if the process have privilege to
6647 * access the bpf object and that's why we have to add this additional check in
6648 * selinux_file_receive and selinux_binder_transfer_files.
6650 static int bpf_fd_pass(struct file *file, u32 sid)
6652 struct bpf_security_struct *bpfsec;
6653 struct bpf_prog *prog;
6654 struct bpf_map *map;
6655 int ret;
6657 if (file->f_op == &bpf_map_fops) {
6658 map = file->private_data;
6659 bpfsec = map->security;
6660 ret = avc_has_perm(&selinux_state,
6661 sid, bpfsec->sid, SECCLASS_BPF,
6662 bpf_map_fmode_to_av(file->f_mode), NULL);
6663 if (ret)
6664 return ret;
6665 } else if (file->f_op == &bpf_prog_fops) {
6666 prog = file->private_data;
6667 bpfsec = prog->aux->security;
6668 ret = avc_has_perm(&selinux_state,
6669 sid, bpfsec->sid, SECCLASS_BPF,
6670 BPF__PROG_RUN, NULL);
6671 if (ret)
6672 return ret;
6674 return 0;
6677 static int selinux_bpf_map(struct bpf_map *map, fmode_t fmode)
6679 u32 sid = current_sid();
6680 struct bpf_security_struct *bpfsec;
6682 bpfsec = map->security;
6683 return avc_has_perm(&selinux_state,
6684 sid, bpfsec->sid, SECCLASS_BPF,
6685 bpf_map_fmode_to_av(fmode), NULL);
6688 static int selinux_bpf_prog(struct bpf_prog *prog)
6690 u32 sid = current_sid();
6691 struct bpf_security_struct *bpfsec;
6693 bpfsec = prog->aux->security;
6694 return avc_has_perm(&selinux_state,
6695 sid, bpfsec->sid, SECCLASS_BPF,
6696 BPF__PROG_RUN, NULL);
6699 static int selinux_bpf_map_alloc(struct bpf_map *map)
6701 struct bpf_security_struct *bpfsec;
6703 bpfsec = kzalloc(sizeof(*bpfsec), GFP_KERNEL);
6704 if (!bpfsec)
6705 return -ENOMEM;
6707 bpfsec->sid = current_sid();
6708 map->security = bpfsec;
6710 return 0;
6713 static void selinux_bpf_map_free(struct bpf_map *map)
6715 struct bpf_security_struct *bpfsec = map->security;
6717 map->security = NULL;
6718 kfree(bpfsec);
6721 static int selinux_bpf_prog_alloc(struct bpf_prog_aux *aux)
6723 struct bpf_security_struct *bpfsec;
6725 bpfsec = kzalloc(sizeof(*bpfsec), GFP_KERNEL);
6726 if (!bpfsec)
6727 return -ENOMEM;
6729 bpfsec->sid = current_sid();
6730 aux->security = bpfsec;
6732 return 0;
6735 static void selinux_bpf_prog_free(struct bpf_prog_aux *aux)
6737 struct bpf_security_struct *bpfsec = aux->security;
6739 aux->security = NULL;
6740 kfree(bpfsec);
6742 #endif
6744 struct lsm_blob_sizes selinux_blob_sizes __lsm_ro_after_init = {
6745 .lbs_cred = sizeof(struct task_security_struct),
6746 .lbs_file = sizeof(struct file_security_struct),
6747 .lbs_inode = sizeof(struct inode_security_struct),
6748 .lbs_ipc = sizeof(struct ipc_security_struct),
6749 .lbs_msg_msg = sizeof(struct msg_security_struct),
6752 static struct security_hook_list selinux_hooks[] __lsm_ro_after_init = {
6753 LSM_HOOK_INIT(binder_set_context_mgr, selinux_binder_set_context_mgr),
6754 LSM_HOOK_INIT(binder_transaction, selinux_binder_transaction),
6755 LSM_HOOK_INIT(binder_transfer_binder, selinux_binder_transfer_binder),
6756 LSM_HOOK_INIT(binder_transfer_file, selinux_binder_transfer_file),
6758 LSM_HOOK_INIT(ptrace_access_check, selinux_ptrace_access_check),
6759 LSM_HOOK_INIT(ptrace_traceme, selinux_ptrace_traceme),
6760 LSM_HOOK_INIT(capget, selinux_capget),
6761 LSM_HOOK_INIT(capset, selinux_capset),
6762 LSM_HOOK_INIT(capable, selinux_capable),
6763 LSM_HOOK_INIT(quotactl, selinux_quotactl),
6764 LSM_HOOK_INIT(quota_on, selinux_quota_on),
6765 LSM_HOOK_INIT(syslog, selinux_syslog),
6766 LSM_HOOK_INIT(vm_enough_memory, selinux_vm_enough_memory),
6768 LSM_HOOK_INIT(netlink_send, selinux_netlink_send),
6770 LSM_HOOK_INIT(bprm_set_creds, selinux_bprm_set_creds),
6771 LSM_HOOK_INIT(bprm_committing_creds, selinux_bprm_committing_creds),
6772 LSM_HOOK_INIT(bprm_committed_creds, selinux_bprm_committed_creds),
6774 LSM_HOOK_INIT(fs_context_dup, selinux_fs_context_dup),
6775 LSM_HOOK_INIT(fs_context_parse_param, selinux_fs_context_parse_param),
6777 LSM_HOOK_INIT(sb_alloc_security, selinux_sb_alloc_security),
6778 LSM_HOOK_INIT(sb_free_security, selinux_sb_free_security),
6779 LSM_HOOK_INIT(sb_eat_lsm_opts, selinux_sb_eat_lsm_opts),
6780 LSM_HOOK_INIT(sb_free_mnt_opts, selinux_free_mnt_opts),
6781 LSM_HOOK_INIT(sb_remount, selinux_sb_remount),
6782 LSM_HOOK_INIT(sb_kern_mount, selinux_sb_kern_mount),
6783 LSM_HOOK_INIT(sb_show_options, selinux_sb_show_options),
6784 LSM_HOOK_INIT(sb_statfs, selinux_sb_statfs),
6785 LSM_HOOK_INIT(sb_mount, selinux_mount),
6786 LSM_HOOK_INIT(sb_umount, selinux_umount),
6787 LSM_HOOK_INIT(sb_set_mnt_opts, selinux_set_mnt_opts),
6788 LSM_HOOK_INIT(sb_clone_mnt_opts, selinux_sb_clone_mnt_opts),
6789 LSM_HOOK_INIT(sb_add_mnt_opt, selinux_add_mnt_opt),
6791 LSM_HOOK_INIT(dentry_init_security, selinux_dentry_init_security),
6792 LSM_HOOK_INIT(dentry_create_files_as, selinux_dentry_create_files_as),
6794 LSM_HOOK_INIT(inode_alloc_security, selinux_inode_alloc_security),
6795 LSM_HOOK_INIT(inode_free_security, selinux_inode_free_security),
6796 LSM_HOOK_INIT(inode_init_security, selinux_inode_init_security),
6797 LSM_HOOK_INIT(inode_create, selinux_inode_create),
6798 LSM_HOOK_INIT(inode_link, selinux_inode_link),
6799 LSM_HOOK_INIT(inode_unlink, selinux_inode_unlink),
6800 LSM_HOOK_INIT(inode_symlink, selinux_inode_symlink),
6801 LSM_HOOK_INIT(inode_mkdir, selinux_inode_mkdir),
6802 LSM_HOOK_INIT(inode_rmdir, selinux_inode_rmdir),
6803 LSM_HOOK_INIT(inode_mknod, selinux_inode_mknod),
6804 LSM_HOOK_INIT(inode_rename, selinux_inode_rename),
6805 LSM_HOOK_INIT(inode_readlink, selinux_inode_readlink),
6806 LSM_HOOK_INIT(inode_follow_link, selinux_inode_follow_link),
6807 LSM_HOOK_INIT(inode_permission, selinux_inode_permission),
6808 LSM_HOOK_INIT(inode_setattr, selinux_inode_setattr),
6809 LSM_HOOK_INIT(inode_getattr, selinux_inode_getattr),
6810 LSM_HOOK_INIT(inode_setxattr, selinux_inode_setxattr),
6811 LSM_HOOK_INIT(inode_post_setxattr, selinux_inode_post_setxattr),
6812 LSM_HOOK_INIT(inode_getxattr, selinux_inode_getxattr),
6813 LSM_HOOK_INIT(inode_listxattr, selinux_inode_listxattr),
6814 LSM_HOOK_INIT(inode_removexattr, selinux_inode_removexattr),
6815 LSM_HOOK_INIT(inode_getsecurity, selinux_inode_getsecurity),
6816 LSM_HOOK_INIT(inode_setsecurity, selinux_inode_setsecurity),
6817 LSM_HOOK_INIT(inode_listsecurity, selinux_inode_listsecurity),
6818 LSM_HOOK_INIT(inode_getsecid, selinux_inode_getsecid),
6819 LSM_HOOK_INIT(inode_copy_up, selinux_inode_copy_up),
6820 LSM_HOOK_INIT(inode_copy_up_xattr, selinux_inode_copy_up_xattr),
6822 LSM_HOOK_INIT(kernfs_init_security, selinux_kernfs_init_security),
6824 LSM_HOOK_INIT(file_permission, selinux_file_permission),
6825 LSM_HOOK_INIT(file_alloc_security, selinux_file_alloc_security),
6826 LSM_HOOK_INIT(file_ioctl, selinux_file_ioctl),
6827 LSM_HOOK_INIT(mmap_file, selinux_mmap_file),
6828 LSM_HOOK_INIT(mmap_addr, selinux_mmap_addr),
6829 LSM_HOOK_INIT(file_mprotect, selinux_file_mprotect),
6830 LSM_HOOK_INIT(file_lock, selinux_file_lock),
6831 LSM_HOOK_INIT(file_fcntl, selinux_file_fcntl),
6832 LSM_HOOK_INIT(file_set_fowner, selinux_file_set_fowner),
6833 LSM_HOOK_INIT(file_send_sigiotask, selinux_file_send_sigiotask),
6834 LSM_HOOK_INIT(file_receive, selinux_file_receive),
6836 LSM_HOOK_INIT(file_open, selinux_file_open),
6838 LSM_HOOK_INIT(task_alloc, selinux_task_alloc),
6839 LSM_HOOK_INIT(cred_prepare, selinux_cred_prepare),
6840 LSM_HOOK_INIT(cred_transfer, selinux_cred_transfer),
6841 LSM_HOOK_INIT(cred_getsecid, selinux_cred_getsecid),
6842 LSM_HOOK_INIT(kernel_act_as, selinux_kernel_act_as),
6843 LSM_HOOK_INIT(kernel_create_files_as, selinux_kernel_create_files_as),
6844 LSM_HOOK_INIT(kernel_module_request, selinux_kernel_module_request),
6845 LSM_HOOK_INIT(kernel_load_data, selinux_kernel_load_data),
6846 LSM_HOOK_INIT(kernel_read_file, selinux_kernel_read_file),
6847 LSM_HOOK_INIT(task_setpgid, selinux_task_setpgid),
6848 LSM_HOOK_INIT(task_getpgid, selinux_task_getpgid),
6849 LSM_HOOK_INIT(task_getsid, selinux_task_getsid),
6850 LSM_HOOK_INIT(task_getsecid, selinux_task_getsecid),
6851 LSM_HOOK_INIT(task_setnice, selinux_task_setnice),
6852 LSM_HOOK_INIT(task_setioprio, selinux_task_setioprio),
6853 LSM_HOOK_INIT(task_getioprio, selinux_task_getioprio),
6854 LSM_HOOK_INIT(task_prlimit, selinux_task_prlimit),
6855 LSM_HOOK_INIT(task_setrlimit, selinux_task_setrlimit),
6856 LSM_HOOK_INIT(task_setscheduler, selinux_task_setscheduler),
6857 LSM_HOOK_INIT(task_getscheduler, selinux_task_getscheduler),
6858 LSM_HOOK_INIT(task_movememory, selinux_task_movememory),
6859 LSM_HOOK_INIT(task_kill, selinux_task_kill),
6860 LSM_HOOK_INIT(task_to_inode, selinux_task_to_inode),
6862 LSM_HOOK_INIT(ipc_permission, selinux_ipc_permission),
6863 LSM_HOOK_INIT(ipc_getsecid, selinux_ipc_getsecid),
6865 LSM_HOOK_INIT(msg_msg_alloc_security, selinux_msg_msg_alloc_security),
6867 LSM_HOOK_INIT(msg_queue_alloc_security,
6868 selinux_msg_queue_alloc_security),
6869 LSM_HOOK_INIT(msg_queue_associate, selinux_msg_queue_associate),
6870 LSM_HOOK_INIT(msg_queue_msgctl, selinux_msg_queue_msgctl),
6871 LSM_HOOK_INIT(msg_queue_msgsnd, selinux_msg_queue_msgsnd),
6872 LSM_HOOK_INIT(msg_queue_msgrcv, selinux_msg_queue_msgrcv),
6874 LSM_HOOK_INIT(shm_alloc_security, selinux_shm_alloc_security),
6875 LSM_HOOK_INIT(shm_associate, selinux_shm_associate),
6876 LSM_HOOK_INIT(shm_shmctl, selinux_shm_shmctl),
6877 LSM_HOOK_INIT(shm_shmat, selinux_shm_shmat),
6879 LSM_HOOK_INIT(sem_alloc_security, selinux_sem_alloc_security),
6880 LSM_HOOK_INIT(sem_associate, selinux_sem_associate),
6881 LSM_HOOK_INIT(sem_semctl, selinux_sem_semctl),
6882 LSM_HOOK_INIT(sem_semop, selinux_sem_semop),
6884 LSM_HOOK_INIT(d_instantiate, selinux_d_instantiate),
6886 LSM_HOOK_INIT(getprocattr, selinux_getprocattr),
6887 LSM_HOOK_INIT(setprocattr, selinux_setprocattr),
6889 LSM_HOOK_INIT(ismaclabel, selinux_ismaclabel),
6890 LSM_HOOK_INIT(secid_to_secctx, selinux_secid_to_secctx),
6891 LSM_HOOK_INIT(secctx_to_secid, selinux_secctx_to_secid),
6892 LSM_HOOK_INIT(release_secctx, selinux_release_secctx),
6893 LSM_HOOK_INIT(inode_invalidate_secctx, selinux_inode_invalidate_secctx),
6894 LSM_HOOK_INIT(inode_notifysecctx, selinux_inode_notifysecctx),
6895 LSM_HOOK_INIT(inode_setsecctx, selinux_inode_setsecctx),
6896 LSM_HOOK_INIT(inode_getsecctx, selinux_inode_getsecctx),
6898 LSM_HOOK_INIT(unix_stream_connect, selinux_socket_unix_stream_connect),
6899 LSM_HOOK_INIT(unix_may_send, selinux_socket_unix_may_send),
6901 LSM_HOOK_INIT(socket_create, selinux_socket_create),
6902 LSM_HOOK_INIT(socket_post_create, selinux_socket_post_create),
6903 LSM_HOOK_INIT(socket_socketpair, selinux_socket_socketpair),
6904 LSM_HOOK_INIT(socket_bind, selinux_socket_bind),
6905 LSM_HOOK_INIT(socket_connect, selinux_socket_connect),
6906 LSM_HOOK_INIT(socket_listen, selinux_socket_listen),
6907 LSM_HOOK_INIT(socket_accept, selinux_socket_accept),
6908 LSM_HOOK_INIT(socket_sendmsg, selinux_socket_sendmsg),
6909 LSM_HOOK_INIT(socket_recvmsg, selinux_socket_recvmsg),
6910 LSM_HOOK_INIT(socket_getsockname, selinux_socket_getsockname),
6911 LSM_HOOK_INIT(socket_getpeername, selinux_socket_getpeername),
6912 LSM_HOOK_INIT(socket_getsockopt, selinux_socket_getsockopt),
6913 LSM_HOOK_INIT(socket_setsockopt, selinux_socket_setsockopt),
6914 LSM_HOOK_INIT(socket_shutdown, selinux_socket_shutdown),
6915 LSM_HOOK_INIT(socket_sock_rcv_skb, selinux_socket_sock_rcv_skb),
6916 LSM_HOOK_INIT(socket_getpeersec_stream,
6917 selinux_socket_getpeersec_stream),
6918 LSM_HOOK_INIT(socket_getpeersec_dgram, selinux_socket_getpeersec_dgram),
6919 LSM_HOOK_INIT(sk_alloc_security, selinux_sk_alloc_security),
6920 LSM_HOOK_INIT(sk_free_security, selinux_sk_free_security),
6921 LSM_HOOK_INIT(sk_clone_security, selinux_sk_clone_security),
6922 LSM_HOOK_INIT(sk_getsecid, selinux_sk_getsecid),
6923 LSM_HOOK_INIT(sock_graft, selinux_sock_graft),
6924 LSM_HOOK_INIT(sctp_assoc_request, selinux_sctp_assoc_request),
6925 LSM_HOOK_INIT(sctp_sk_clone, selinux_sctp_sk_clone),
6926 LSM_HOOK_INIT(sctp_bind_connect, selinux_sctp_bind_connect),
6927 LSM_HOOK_INIT(inet_conn_request, selinux_inet_conn_request),
6928 LSM_HOOK_INIT(inet_csk_clone, selinux_inet_csk_clone),
6929 LSM_HOOK_INIT(inet_conn_established, selinux_inet_conn_established),
6930 LSM_HOOK_INIT(secmark_relabel_packet, selinux_secmark_relabel_packet),
6931 LSM_HOOK_INIT(secmark_refcount_inc, selinux_secmark_refcount_inc),
6932 LSM_HOOK_INIT(secmark_refcount_dec, selinux_secmark_refcount_dec),
6933 LSM_HOOK_INIT(req_classify_flow, selinux_req_classify_flow),
6934 LSM_HOOK_INIT(tun_dev_alloc_security, selinux_tun_dev_alloc_security),
6935 LSM_HOOK_INIT(tun_dev_free_security, selinux_tun_dev_free_security),
6936 LSM_HOOK_INIT(tun_dev_create, selinux_tun_dev_create),
6937 LSM_HOOK_INIT(tun_dev_attach_queue, selinux_tun_dev_attach_queue),
6938 LSM_HOOK_INIT(tun_dev_attach, selinux_tun_dev_attach),
6939 LSM_HOOK_INIT(tun_dev_open, selinux_tun_dev_open),
6940 #ifdef CONFIG_SECURITY_INFINIBAND
6941 LSM_HOOK_INIT(ib_pkey_access, selinux_ib_pkey_access),
6942 LSM_HOOK_INIT(ib_endport_manage_subnet,
6943 selinux_ib_endport_manage_subnet),
6944 LSM_HOOK_INIT(ib_alloc_security, selinux_ib_alloc_security),
6945 LSM_HOOK_INIT(ib_free_security, selinux_ib_free_security),
6946 #endif
6947 #ifdef CONFIG_SECURITY_NETWORK_XFRM
6948 LSM_HOOK_INIT(xfrm_policy_alloc_security, selinux_xfrm_policy_alloc),
6949 LSM_HOOK_INIT(xfrm_policy_clone_security, selinux_xfrm_policy_clone),
6950 LSM_HOOK_INIT(xfrm_policy_free_security, selinux_xfrm_policy_free),
6951 LSM_HOOK_INIT(xfrm_policy_delete_security, selinux_xfrm_policy_delete),
6952 LSM_HOOK_INIT(xfrm_state_alloc, selinux_xfrm_state_alloc),
6953 LSM_HOOK_INIT(xfrm_state_alloc_acquire,
6954 selinux_xfrm_state_alloc_acquire),
6955 LSM_HOOK_INIT(xfrm_state_free_security, selinux_xfrm_state_free),
6956 LSM_HOOK_INIT(xfrm_state_delete_security, selinux_xfrm_state_delete),
6957 LSM_HOOK_INIT(xfrm_policy_lookup, selinux_xfrm_policy_lookup),
6958 LSM_HOOK_INIT(xfrm_state_pol_flow_match,
6959 selinux_xfrm_state_pol_flow_match),
6960 LSM_HOOK_INIT(xfrm_decode_session, selinux_xfrm_decode_session),
6961 #endif
6963 #ifdef CONFIG_KEYS
6964 LSM_HOOK_INIT(key_alloc, selinux_key_alloc),
6965 LSM_HOOK_INIT(key_free, selinux_key_free),
6966 LSM_HOOK_INIT(key_permission, selinux_key_permission),
6967 LSM_HOOK_INIT(key_getsecurity, selinux_key_getsecurity),
6968 #endif
6970 #ifdef CONFIG_AUDIT
6971 LSM_HOOK_INIT(audit_rule_init, selinux_audit_rule_init),
6972 LSM_HOOK_INIT(audit_rule_known, selinux_audit_rule_known),
6973 LSM_HOOK_INIT(audit_rule_match, selinux_audit_rule_match),
6974 LSM_HOOK_INIT(audit_rule_free, selinux_audit_rule_free),
6975 #endif
6977 #ifdef CONFIG_BPF_SYSCALL
6978 LSM_HOOK_INIT(bpf, selinux_bpf),
6979 LSM_HOOK_INIT(bpf_map, selinux_bpf_map),
6980 LSM_HOOK_INIT(bpf_prog, selinux_bpf_prog),
6981 LSM_HOOK_INIT(bpf_map_alloc_security, selinux_bpf_map_alloc),
6982 LSM_HOOK_INIT(bpf_prog_alloc_security, selinux_bpf_prog_alloc),
6983 LSM_HOOK_INIT(bpf_map_free_security, selinux_bpf_map_free),
6984 LSM_HOOK_INIT(bpf_prog_free_security, selinux_bpf_prog_free),
6985 #endif
6988 static __init int selinux_init(void)
6990 pr_info("SELinux: Initializing.\n");
6992 memset(&selinux_state, 0, sizeof(selinux_state));
6993 enforcing_set(&selinux_state, selinux_enforcing_boot);
6994 selinux_state.checkreqprot = selinux_checkreqprot_boot;
6995 selinux_ss_init(&selinux_state.ss);
6996 selinux_avc_init(&selinux_state.avc);
6998 /* Set the security state for the initial task. */
6999 cred_init_security();
7001 default_noexec = !(VM_DATA_DEFAULT_FLAGS & VM_EXEC);
7003 avc_init();
7005 avtab_cache_init();
7007 ebitmap_cache_init();
7009 hashtab_cache_init();
7011 security_add_hooks(selinux_hooks, ARRAY_SIZE(selinux_hooks), "selinux");
7013 if (avc_add_callback(selinux_netcache_avc_callback, AVC_CALLBACK_RESET))
7014 panic("SELinux: Unable to register AVC netcache callback\n");
7016 if (avc_add_callback(selinux_lsm_notifier_avc_callback, AVC_CALLBACK_RESET))
7017 panic("SELinux: Unable to register AVC LSM notifier callback\n");
7019 if (selinux_enforcing_boot)
7020 pr_debug("SELinux: Starting in enforcing mode\n");
7021 else
7022 pr_debug("SELinux: Starting in permissive mode\n");
7024 fs_validate_description(&selinux_fs_parameters);
7026 return 0;
7029 static void delayed_superblock_init(struct super_block *sb, void *unused)
7031 selinux_set_mnt_opts(sb, NULL, 0, NULL);
7034 void selinux_complete_init(void)
7036 pr_debug("SELinux: Completing initialization.\n");
7038 /* Set up any superblocks initialized prior to the policy load. */
7039 pr_debug("SELinux: Setting up existing superblocks.\n");
7040 iterate_supers(delayed_superblock_init, NULL);
7043 /* SELinux requires early initialization in order to label
7044 all processes and objects when they are created. */
7045 DEFINE_LSM(selinux) = {
7046 .name = "selinux",
7047 .flags = LSM_FLAG_LEGACY_MAJOR | LSM_FLAG_EXCLUSIVE,
7048 .enabled = &selinux_enabled,
7049 .blobs = &selinux_blob_sizes,
7050 .init = selinux_init,
7053 #if defined(CONFIG_NETFILTER)
7055 static const struct nf_hook_ops selinux_nf_ops[] = {
7057 .hook = selinux_ipv4_postroute,
7058 .pf = NFPROTO_IPV4,
7059 .hooknum = NF_INET_POST_ROUTING,
7060 .priority = NF_IP_PRI_SELINUX_LAST,
7063 .hook = selinux_ipv4_forward,
7064 .pf = NFPROTO_IPV4,
7065 .hooknum = NF_INET_FORWARD,
7066 .priority = NF_IP_PRI_SELINUX_FIRST,
7069 .hook = selinux_ipv4_output,
7070 .pf = NFPROTO_IPV4,
7071 .hooknum = NF_INET_LOCAL_OUT,
7072 .priority = NF_IP_PRI_SELINUX_FIRST,
7074 #if IS_ENABLED(CONFIG_IPV6)
7076 .hook = selinux_ipv6_postroute,
7077 .pf = NFPROTO_IPV6,
7078 .hooknum = NF_INET_POST_ROUTING,
7079 .priority = NF_IP6_PRI_SELINUX_LAST,
7082 .hook = selinux_ipv6_forward,
7083 .pf = NFPROTO_IPV6,
7084 .hooknum = NF_INET_FORWARD,
7085 .priority = NF_IP6_PRI_SELINUX_FIRST,
7088 .hook = selinux_ipv6_output,
7089 .pf = NFPROTO_IPV6,
7090 .hooknum = NF_INET_LOCAL_OUT,
7091 .priority = NF_IP6_PRI_SELINUX_FIRST,
7093 #endif /* IPV6 */
7096 static int __net_init selinux_nf_register(struct net *net)
7098 return nf_register_net_hooks(net, selinux_nf_ops,
7099 ARRAY_SIZE(selinux_nf_ops));
7102 static void __net_exit selinux_nf_unregister(struct net *net)
7104 nf_unregister_net_hooks(net, selinux_nf_ops,
7105 ARRAY_SIZE(selinux_nf_ops));
7108 static struct pernet_operations selinux_net_ops = {
7109 .init = selinux_nf_register,
7110 .exit = selinux_nf_unregister,
7113 static int __init selinux_nf_ip_init(void)
7115 int err;
7117 if (!selinux_enabled)
7118 return 0;
7120 pr_debug("SELinux: Registering netfilter hooks\n");
7122 err = register_pernet_subsys(&selinux_net_ops);
7123 if (err)
7124 panic("SELinux: register_pernet_subsys: error %d\n", err);
7126 return 0;
7128 __initcall(selinux_nf_ip_init);
7130 #ifdef CONFIG_SECURITY_SELINUX_DISABLE
7131 static void selinux_nf_ip_exit(void)
7133 pr_debug("SELinux: Unregistering netfilter hooks\n");
7135 unregister_pernet_subsys(&selinux_net_ops);
7137 #endif
7139 #else /* CONFIG_NETFILTER */
7141 #ifdef CONFIG_SECURITY_SELINUX_DISABLE
7142 #define selinux_nf_ip_exit()
7143 #endif
7145 #endif /* CONFIG_NETFILTER */
7147 #ifdef CONFIG_SECURITY_SELINUX_DISABLE
7148 int selinux_disable(struct selinux_state *state)
7150 if (state->initialized) {
7151 /* Not permitted after initial policy load. */
7152 return -EINVAL;
7155 if (state->disabled) {
7156 /* Only do this once. */
7157 return -EINVAL;
7160 state->disabled = 1;
7162 pr_info("SELinux: Disabled at runtime.\n");
7164 selinux_enabled = 0;
7166 security_delete_hooks(selinux_hooks, ARRAY_SIZE(selinux_hooks));
7168 /* Try to destroy the avc node cache */
7169 avc_disable();
7171 /* Unregister netfilter hooks. */
7172 selinux_nf_ip_exit();
7174 /* Unregister selinuxfs. */
7175 exit_sel_fs();
7177 return 0;
7179 #endif