1 // SPDX-License-Identifier: GPL-2.0-only
3 * NSA Security-Enhanced Linux (SELinux) security module
5 * This file contains the SELinux hook function implementations.
12 * Copyright (C) 2001,2002 Networks Associates Technology, Inc.
15 * Copyright (C) 2004-2005 Trusted Computer Solutions, Inc.
17 * Copyright (C) 2006, 2007, 2009 Hewlett-Packard Development Company, L.P.
19 * Copyright (C) 2007 Hitachi Software Engineering Co., Ltd.
21 * Copyright (C) 2016 Mellanox Technologies
24 #include <linux/init.h>
26 #include <linux/kernel.h>
27 #include <linux/kernel_read_file.h>
28 #include <linux/tracehook.h>
29 #include <linux/errno.h>
30 #include <linux/sched/signal.h>
31 #include <linux/sched/task.h>
32 #include <linux/lsm_hooks.h>
33 #include <linux/xattr.h>
34 #include <linux/capability.h>
35 #include <linux/unistd.h>
37 #include <linux/mman.h>
38 #include <linux/slab.h>
39 #include <linux/pagemap.h>
40 #include <linux/proc_fs.h>
41 #include <linux/swap.h>
42 #include <linux/spinlock.h>
43 #include <linux/syscalls.h>
44 #include <linux/dcache.h>
45 #include <linux/file.h>
46 #include <linux/fdtable.h>
47 #include <linux/namei.h>
48 #include <linux/mount.h>
49 #include <linux/fs_context.h>
50 #include <linux/fs_parser.h>
51 #include <linux/netfilter_ipv4.h>
52 #include <linux/netfilter_ipv6.h>
53 #include <linux/tty.h>
55 #include <net/ip.h> /* for local_port_range[] */
56 #include <net/tcp.h> /* struct or_callable used in sock_rcv_skb */
57 #include <net/inet_connection_sock.h>
58 #include <net/net_namespace.h>
59 #include <net/netlabel.h>
60 #include <linux/uaccess.h>
61 #include <asm/ioctls.h>
62 #include <linux/atomic.h>
63 #include <linux/bitops.h>
64 #include <linux/interrupt.h>
65 #include <linux/netdevice.h> /* for network interface checks */
66 #include <net/netlink.h>
67 #include <linux/tcp.h>
68 #include <linux/udp.h>
69 #include <linux/dccp.h>
70 #include <linux/sctp.h>
71 #include <net/sctp/structs.h>
72 #include <linux/quota.h>
73 #include <linux/un.h> /* for Unix socket types */
74 #include <net/af_unix.h> /* for Unix socket types */
75 #include <linux/parser.h>
76 #include <linux/nfs_mount.h>
78 #include <linux/hugetlb.h>
79 #include <linux/personality.h>
80 #include <linux/audit.h>
81 #include <linux/string.h>
82 #include <linux/mutex.h>
83 #include <linux/posix-timers.h>
84 #include <linux/syslog.h>
85 #include <linux/user_namespace.h>
86 #include <linux/export.h>
87 #include <linux/msg.h>
88 #include <linux/shm.h>
89 #include <linux/bpf.h>
90 #include <linux/kernfs.h>
91 #include <linux/stringhash.h> /* for hashlen_string() */
92 #include <uapi/linux/mount.h>
93 #include <linux/fsnotify.h>
94 #include <linux/fanotify.h>
103 #include "netlabel.h"
107 struct selinux_state selinux_state;
109 /* SECMARK reference count */
110 static atomic_t selinux_secmark_refcount = ATOMIC_INIT(0);
112 #ifdef CONFIG_SECURITY_SELINUX_DEVELOP
113 static int selinux_enforcing_boot __initdata;
115 static int __init enforcing_setup(char *str)
117 unsigned long enforcing;
118 if (!kstrtoul(str, 0, &enforcing))
119 selinux_enforcing_boot = enforcing ? 1 : 0;
122 __setup("enforcing=", enforcing_setup);
124 #define selinux_enforcing_boot 1
127 int selinux_enabled_boot __initdata = 1;
128 #ifdef CONFIG_SECURITY_SELINUX_BOOTPARAM
129 static int __init selinux_enabled_setup(char *str)
131 unsigned long enabled;
132 if (!kstrtoul(str, 0, &enabled))
133 selinux_enabled_boot = enabled ? 1 : 0;
136 __setup("selinux=", selinux_enabled_setup);
139 static unsigned int selinux_checkreqprot_boot =
140 CONFIG_SECURITY_SELINUX_CHECKREQPROT_VALUE;
142 static int __init checkreqprot_setup(char *str)
144 unsigned long checkreqprot;
146 if (!kstrtoul(str, 0, &checkreqprot)) {
147 selinux_checkreqprot_boot = checkreqprot ? 1 : 0;
149 pr_warn("SELinux: checkreqprot set to 1 via kernel parameter. This is deprecated and will be rejected in a future kernel release.\n");
153 __setup("checkreqprot=", checkreqprot_setup);
156 * selinux_secmark_enabled - Check to see if SECMARK is currently enabled
159 * This function checks the SECMARK reference counter to see if any SECMARK
160 * targets are currently configured, if the reference counter is greater than
161 * zero SECMARK is considered to be enabled. Returns true (1) if SECMARK is
162 * enabled, false (0) if SECMARK is disabled. If the always_check_network
163 * policy capability is enabled, SECMARK is always considered enabled.
166 static int selinux_secmark_enabled(void)
168 return (selinux_policycap_alwaysnetwork() ||
169 atomic_read(&selinux_secmark_refcount));
173 * selinux_peerlbl_enabled - Check to see if peer labeling is currently enabled
176 * This function checks if NetLabel or labeled IPSEC is enabled. Returns true
177 * (1) if any are enabled or false (0) if neither are enabled. If the
178 * always_check_network policy capability is enabled, peer labeling
179 * is always considered enabled.
182 static int selinux_peerlbl_enabled(void)
184 return (selinux_policycap_alwaysnetwork() ||
185 netlbl_enabled() || selinux_xfrm_enabled());
188 static int selinux_netcache_avc_callback(u32 event)
190 if (event == AVC_CALLBACK_RESET) {
199 static int selinux_lsm_notifier_avc_callback(u32 event)
201 if (event == AVC_CALLBACK_RESET) {
203 call_blocking_lsm_notifier(LSM_POLICY_CHANGE, NULL);
210 * initialise the security for the init task
212 static void cred_init_security(void)
214 struct cred *cred = (struct cred *) current->real_cred;
215 struct task_security_struct *tsec;
217 tsec = selinux_cred(cred);
218 tsec->osid = tsec->sid = SECINITSID_KERNEL;
222 * get the security ID of a set of credentials
224 static inline u32 cred_sid(const struct cred *cred)
226 const struct task_security_struct *tsec;
228 tsec = selinux_cred(cred);
233 * get the subjective security ID of a task
235 static inline u32 task_sid_subj(const struct task_struct *task)
240 sid = cred_sid(rcu_dereference(task->cred));
246 * get the objective security ID of a task
248 static inline u32 task_sid_obj(const struct task_struct *task)
253 sid = cred_sid(__task_cred(task));
258 static int inode_doinit_with_dentry(struct inode *inode, struct dentry *opt_dentry);
261 * Try reloading inode security labels that have been marked as invalid. The
262 * @may_sleep parameter indicates when sleeping and thus reloading labels is
263 * allowed; when set to false, returns -ECHILD when the label is
264 * invalid. The @dentry parameter should be set to a dentry of the inode.
266 static int __inode_security_revalidate(struct inode *inode,
267 struct dentry *dentry,
270 struct inode_security_struct *isec = selinux_inode(inode);
272 might_sleep_if(may_sleep);
274 if (selinux_initialized(&selinux_state) &&
275 isec->initialized != LABEL_INITIALIZED) {
280 * Try reloading the inode security label. This will fail if
281 * @opt_dentry is NULL and no dentry for this inode can be
282 * found; in that case, continue using the old label.
284 inode_doinit_with_dentry(inode, dentry);
289 static struct inode_security_struct *inode_security_novalidate(struct inode *inode)
291 return selinux_inode(inode);
294 static struct inode_security_struct *inode_security_rcu(struct inode *inode, bool rcu)
298 error = __inode_security_revalidate(inode, NULL, !rcu);
300 return ERR_PTR(error);
301 return selinux_inode(inode);
305 * Get the security label of an inode.
307 static struct inode_security_struct *inode_security(struct inode *inode)
309 __inode_security_revalidate(inode, NULL, true);
310 return selinux_inode(inode);
313 static struct inode_security_struct *backing_inode_security_novalidate(struct dentry *dentry)
315 struct inode *inode = d_backing_inode(dentry);
317 return selinux_inode(inode);
321 * Get the security label of a dentry's backing inode.
323 static struct inode_security_struct *backing_inode_security(struct dentry *dentry)
325 struct inode *inode = d_backing_inode(dentry);
327 __inode_security_revalidate(inode, dentry, true);
328 return selinux_inode(inode);
331 static void inode_free_security(struct inode *inode)
333 struct inode_security_struct *isec = selinux_inode(inode);
334 struct superblock_security_struct *sbsec;
338 sbsec = selinux_superblock(inode->i_sb);
340 * As not all inode security structures are in a list, we check for
341 * empty list outside of the lock to make sure that we won't waste
342 * time taking a lock doing nothing.
344 * The list_del_init() function can be safely called more than once.
345 * It should not be possible for this function to be called with
346 * concurrent list_add(), but for better safety against future changes
347 * in the code, we use list_empty_careful() here.
349 if (!list_empty_careful(&isec->list)) {
350 spin_lock(&sbsec->isec_lock);
351 list_del_init(&isec->list);
352 spin_unlock(&sbsec->isec_lock);
356 struct selinux_mnt_opts {
357 const char *fscontext, *context, *rootcontext, *defcontext;
360 static void selinux_free_mnt_opts(void *mnt_opts)
362 struct selinux_mnt_opts *opts = mnt_opts;
363 kfree(opts->fscontext);
364 kfree(opts->context);
365 kfree(opts->rootcontext);
366 kfree(opts->defcontext);
379 #define A(s, has_arg) {#s, sizeof(#s) - 1, Opt_##s, has_arg}
389 A(rootcontext, true),
394 static int match_opt_prefix(char *s, int l, char **arg)
398 for (i = 0; i < ARRAY_SIZE(tokens); i++) {
399 size_t len = tokens[i].len;
400 if (len > l || memcmp(s, tokens[i].name, len))
402 if (tokens[i].has_arg) {
403 if (len == l || s[len] != '=')
408 return tokens[i].opt;
413 #define SEL_MOUNT_FAIL_MSG "SELinux: duplicate or incompatible mount options\n"
415 static int may_context_mount_sb_relabel(u32 sid,
416 struct superblock_security_struct *sbsec,
417 const struct cred *cred)
419 const struct task_security_struct *tsec = selinux_cred(cred);
422 rc = avc_has_perm(&selinux_state,
423 tsec->sid, sbsec->sid, SECCLASS_FILESYSTEM,
424 FILESYSTEM__RELABELFROM, NULL);
428 rc = avc_has_perm(&selinux_state,
429 tsec->sid, sid, SECCLASS_FILESYSTEM,
430 FILESYSTEM__RELABELTO, NULL);
434 static int may_context_mount_inode_relabel(u32 sid,
435 struct superblock_security_struct *sbsec,
436 const struct cred *cred)
438 const struct task_security_struct *tsec = selinux_cred(cred);
440 rc = avc_has_perm(&selinux_state,
441 tsec->sid, sbsec->sid, SECCLASS_FILESYSTEM,
442 FILESYSTEM__RELABELFROM, NULL);
446 rc = avc_has_perm(&selinux_state,
447 sid, sbsec->sid, SECCLASS_FILESYSTEM,
448 FILESYSTEM__ASSOCIATE, NULL);
452 static int selinux_is_genfs_special_handling(struct super_block *sb)
454 /* Special handling. Genfs but also in-core setxattr handler */
455 return !strcmp(sb->s_type->name, "sysfs") ||
456 !strcmp(sb->s_type->name, "pstore") ||
457 !strcmp(sb->s_type->name, "debugfs") ||
458 !strcmp(sb->s_type->name, "tracefs") ||
459 !strcmp(sb->s_type->name, "rootfs") ||
460 (selinux_policycap_cgroupseclabel() &&
461 (!strcmp(sb->s_type->name, "cgroup") ||
462 !strcmp(sb->s_type->name, "cgroup2")));
465 static int selinux_is_sblabel_mnt(struct super_block *sb)
467 struct superblock_security_struct *sbsec = selinux_superblock(sb);
470 * IMPORTANT: Double-check logic in this function when adding a new
471 * SECURITY_FS_USE_* definition!
473 BUILD_BUG_ON(SECURITY_FS_USE_MAX != 7);
475 switch (sbsec->behavior) {
476 case SECURITY_FS_USE_XATTR:
477 case SECURITY_FS_USE_TRANS:
478 case SECURITY_FS_USE_TASK:
479 case SECURITY_FS_USE_NATIVE:
482 case SECURITY_FS_USE_GENFS:
483 return selinux_is_genfs_special_handling(sb);
485 /* Never allow relabeling on context mounts */
486 case SECURITY_FS_USE_MNTPOINT:
487 case SECURITY_FS_USE_NONE:
493 static int sb_check_xattr_support(struct super_block *sb)
495 struct superblock_security_struct *sbsec = sb->s_security;
496 struct dentry *root = sb->s_root;
497 struct inode *root_inode = d_backing_inode(root);
502 * Make sure that the xattr handler exists and that no
503 * error other than -ENODATA is returned by getxattr on
504 * the root directory. -ENODATA is ok, as this may be
505 * the first boot of the SELinux kernel before we have
506 * assigned xattr values to the filesystem.
508 if (!(root_inode->i_opflags & IOP_XATTR)) {
509 pr_warn("SELinux: (dev %s, type %s) has no xattr support\n",
510 sb->s_id, sb->s_type->name);
514 rc = __vfs_getxattr(root, root_inode, XATTR_NAME_SELINUX, NULL, 0);
515 if (rc < 0 && rc != -ENODATA) {
516 if (rc == -EOPNOTSUPP) {
517 pr_warn("SELinux: (dev %s, type %s) has no security xattr handler\n",
518 sb->s_id, sb->s_type->name);
521 pr_warn("SELinux: (dev %s, type %s) getxattr errno %d\n",
522 sb->s_id, sb->s_type->name, -rc);
529 /* No xattr support - try to fallback to genfs if possible. */
530 rc = security_genfs_sid(&selinux_state, sb->s_type->name, "/",
535 pr_warn("SELinux: (dev %s, type %s) falling back to genfs\n",
536 sb->s_id, sb->s_type->name);
537 sbsec->behavior = SECURITY_FS_USE_GENFS;
542 static int sb_finish_set_opts(struct super_block *sb)
544 struct superblock_security_struct *sbsec = selinux_superblock(sb);
545 struct dentry *root = sb->s_root;
546 struct inode *root_inode = d_backing_inode(root);
549 if (sbsec->behavior == SECURITY_FS_USE_XATTR) {
550 rc = sb_check_xattr_support(sb);
555 sbsec->flags |= SE_SBINITIALIZED;
558 * Explicitly set or clear SBLABEL_MNT. It's not sufficient to simply
559 * leave the flag untouched because sb_clone_mnt_opts might be handing
560 * us a superblock that needs the flag to be cleared.
562 if (selinux_is_sblabel_mnt(sb))
563 sbsec->flags |= SBLABEL_MNT;
565 sbsec->flags &= ~SBLABEL_MNT;
567 /* Initialize the root inode. */
568 rc = inode_doinit_with_dentry(root_inode, root);
570 /* Initialize any other inodes associated with the superblock, e.g.
571 inodes created prior to initial policy load or inodes created
572 during get_sb by a pseudo filesystem that directly
574 spin_lock(&sbsec->isec_lock);
575 while (!list_empty(&sbsec->isec_head)) {
576 struct inode_security_struct *isec =
577 list_first_entry(&sbsec->isec_head,
578 struct inode_security_struct, list);
579 struct inode *inode = isec->inode;
580 list_del_init(&isec->list);
581 spin_unlock(&sbsec->isec_lock);
582 inode = igrab(inode);
584 if (!IS_PRIVATE(inode))
585 inode_doinit_with_dentry(inode, NULL);
588 spin_lock(&sbsec->isec_lock);
590 spin_unlock(&sbsec->isec_lock);
594 static int bad_option(struct superblock_security_struct *sbsec, char flag,
595 u32 old_sid, u32 new_sid)
597 char mnt_flags = sbsec->flags & SE_MNTMASK;
599 /* check if the old mount command had the same options */
600 if (sbsec->flags & SE_SBINITIALIZED)
601 if (!(sbsec->flags & flag) ||
602 (old_sid != new_sid))
605 /* check if we were passed the same options twice,
606 * aka someone passed context=a,context=b
608 if (!(sbsec->flags & SE_SBINITIALIZED))
609 if (mnt_flags & flag)
614 static int parse_sid(struct super_block *sb, const char *s, u32 *sid,
617 int rc = security_context_str_to_sid(&selinux_state, s,
620 pr_warn("SELinux: security_context_str_to_sid"
621 "(%s) failed for (dev %s, type %s) errno=%d\n",
622 s, sb->s_id, sb->s_type->name, rc);
627 * Allow filesystems with binary mount data to explicitly set mount point
628 * labeling information.
630 static int selinux_set_mnt_opts(struct super_block *sb,
632 unsigned long kern_flags,
633 unsigned long *set_kern_flags)
635 const struct cred *cred = current_cred();
636 struct superblock_security_struct *sbsec = selinux_superblock(sb);
637 struct dentry *root = sb->s_root;
638 struct selinux_mnt_opts *opts = mnt_opts;
639 struct inode_security_struct *root_isec;
640 u32 fscontext_sid = 0, context_sid = 0, rootcontext_sid = 0;
641 u32 defcontext_sid = 0;
644 mutex_lock(&sbsec->lock);
646 if (!selinux_initialized(&selinux_state)) {
648 /* Defer initialization until selinux_complete_init,
649 after the initial policy is loaded and the security
650 server is ready to handle calls. */
654 pr_warn("SELinux: Unable to set superblock options "
655 "before the security server is initialized\n");
658 if (kern_flags && !set_kern_flags) {
659 /* Specifying internal flags without providing a place to
660 * place the results is not allowed */
666 * Binary mount data FS will come through this function twice. Once
667 * from an explicit call and once from the generic calls from the vfs.
668 * Since the generic VFS calls will not contain any security mount data
669 * we need to skip the double mount verification.
671 * This does open a hole in which we will not notice if the first
672 * mount using this sb set explict options and a second mount using
673 * this sb does not set any security options. (The first options
674 * will be used for both mounts)
676 if ((sbsec->flags & SE_SBINITIALIZED) && (sb->s_type->fs_flags & FS_BINARY_MOUNTDATA)
680 root_isec = backing_inode_security_novalidate(root);
683 * parse the mount options, check if they are valid sids.
684 * also check if someone is trying to mount the same sb more
685 * than once with different security options.
688 if (opts->fscontext) {
689 rc = parse_sid(sb, opts->fscontext, &fscontext_sid,
693 if (bad_option(sbsec, FSCONTEXT_MNT, sbsec->sid,
695 goto out_double_mount;
696 sbsec->flags |= FSCONTEXT_MNT;
699 rc = parse_sid(sb, opts->context, &context_sid,
703 if (bad_option(sbsec, CONTEXT_MNT, sbsec->mntpoint_sid,
705 goto out_double_mount;
706 sbsec->flags |= CONTEXT_MNT;
708 if (opts->rootcontext) {
709 rc = parse_sid(sb, opts->rootcontext, &rootcontext_sid,
713 if (bad_option(sbsec, ROOTCONTEXT_MNT, root_isec->sid,
715 goto out_double_mount;
716 sbsec->flags |= ROOTCONTEXT_MNT;
718 if (opts->defcontext) {
719 rc = parse_sid(sb, opts->defcontext, &defcontext_sid,
723 if (bad_option(sbsec, DEFCONTEXT_MNT, sbsec->def_sid,
725 goto out_double_mount;
726 sbsec->flags |= DEFCONTEXT_MNT;
730 if (sbsec->flags & SE_SBINITIALIZED) {
731 /* previously mounted with options, but not on this attempt? */
732 if ((sbsec->flags & SE_MNTMASK) && !opts)
733 goto out_double_mount;
738 if (strcmp(sb->s_type->name, "proc") == 0)
739 sbsec->flags |= SE_SBPROC | SE_SBGENFS;
741 if (!strcmp(sb->s_type->name, "debugfs") ||
742 !strcmp(sb->s_type->name, "tracefs") ||
743 !strcmp(sb->s_type->name, "binder") ||
744 !strcmp(sb->s_type->name, "bpf") ||
745 !strcmp(sb->s_type->name, "pstore") ||
746 !strcmp(sb->s_type->name, "securityfs"))
747 sbsec->flags |= SE_SBGENFS;
749 if (!strcmp(sb->s_type->name, "sysfs") ||
750 !strcmp(sb->s_type->name, "cgroup") ||
751 !strcmp(sb->s_type->name, "cgroup2"))
752 sbsec->flags |= SE_SBGENFS | SE_SBGENFS_XATTR;
754 if (!sbsec->behavior) {
756 * Determine the labeling behavior to use for this
759 rc = security_fs_use(&selinux_state, sb);
761 pr_warn("%s: security_fs_use(%s) returned %d\n",
762 __func__, sb->s_type->name, rc);
768 * If this is a user namespace mount and the filesystem type is not
769 * explicitly whitelisted, then no contexts are allowed on the command
770 * line and security labels must be ignored.
772 if (sb->s_user_ns != &init_user_ns &&
773 strcmp(sb->s_type->name, "tmpfs") &&
774 strcmp(sb->s_type->name, "ramfs") &&
775 strcmp(sb->s_type->name, "devpts") &&
776 strcmp(sb->s_type->name, "overlay")) {
777 if (context_sid || fscontext_sid || rootcontext_sid ||
782 if (sbsec->behavior == SECURITY_FS_USE_XATTR) {
783 sbsec->behavior = SECURITY_FS_USE_MNTPOINT;
784 rc = security_transition_sid(&selinux_state,
788 &sbsec->mntpoint_sid);
795 /* sets the context of the superblock for the fs being mounted. */
797 rc = may_context_mount_sb_relabel(fscontext_sid, sbsec, cred);
801 sbsec->sid = fscontext_sid;
805 * Switch to using mount point labeling behavior.
806 * sets the label used on all file below the mountpoint, and will set
807 * the superblock context if not already set.
809 if (kern_flags & SECURITY_LSM_NATIVE_LABELS && !context_sid) {
810 sbsec->behavior = SECURITY_FS_USE_NATIVE;
811 *set_kern_flags |= SECURITY_LSM_NATIVE_LABELS;
815 if (!fscontext_sid) {
816 rc = may_context_mount_sb_relabel(context_sid, sbsec,
820 sbsec->sid = context_sid;
822 rc = may_context_mount_inode_relabel(context_sid, sbsec,
827 if (!rootcontext_sid)
828 rootcontext_sid = context_sid;
830 sbsec->mntpoint_sid = context_sid;
831 sbsec->behavior = SECURITY_FS_USE_MNTPOINT;
834 if (rootcontext_sid) {
835 rc = may_context_mount_inode_relabel(rootcontext_sid, sbsec,
840 root_isec->sid = rootcontext_sid;
841 root_isec->initialized = LABEL_INITIALIZED;
844 if (defcontext_sid) {
845 if (sbsec->behavior != SECURITY_FS_USE_XATTR &&
846 sbsec->behavior != SECURITY_FS_USE_NATIVE) {
848 pr_warn("SELinux: defcontext option is "
849 "invalid for this filesystem type\n");
853 if (defcontext_sid != sbsec->def_sid) {
854 rc = may_context_mount_inode_relabel(defcontext_sid,
860 sbsec->def_sid = defcontext_sid;
864 rc = sb_finish_set_opts(sb);
866 mutex_unlock(&sbsec->lock);
870 pr_warn("SELinux: mount invalid. Same superblock, different "
871 "security settings for (dev %s, type %s)\n", sb->s_id,
876 static int selinux_cmp_sb_context(const struct super_block *oldsb,
877 const struct super_block *newsb)
879 struct superblock_security_struct *old = selinux_superblock(oldsb);
880 struct superblock_security_struct *new = selinux_superblock(newsb);
881 char oldflags = old->flags & SE_MNTMASK;
882 char newflags = new->flags & SE_MNTMASK;
884 if (oldflags != newflags)
886 if ((oldflags & FSCONTEXT_MNT) && old->sid != new->sid)
888 if ((oldflags & CONTEXT_MNT) && old->mntpoint_sid != new->mntpoint_sid)
890 if ((oldflags & DEFCONTEXT_MNT) && old->def_sid != new->def_sid)
892 if (oldflags & ROOTCONTEXT_MNT) {
893 struct inode_security_struct *oldroot = backing_inode_security(oldsb->s_root);
894 struct inode_security_struct *newroot = backing_inode_security(newsb->s_root);
895 if (oldroot->sid != newroot->sid)
900 pr_warn("SELinux: mount invalid. Same superblock, "
901 "different security settings for (dev %s, "
902 "type %s)\n", newsb->s_id, newsb->s_type->name);
906 static int selinux_sb_clone_mnt_opts(const struct super_block *oldsb,
907 struct super_block *newsb,
908 unsigned long kern_flags,
909 unsigned long *set_kern_flags)
912 const struct superblock_security_struct *oldsbsec =
913 selinux_superblock(oldsb);
914 struct superblock_security_struct *newsbsec = selinux_superblock(newsb);
916 int set_fscontext = (oldsbsec->flags & FSCONTEXT_MNT);
917 int set_context = (oldsbsec->flags & CONTEXT_MNT);
918 int set_rootcontext = (oldsbsec->flags & ROOTCONTEXT_MNT);
921 * if the parent was able to be mounted it clearly had no special lsm
922 * mount options. thus we can safely deal with this superblock later
924 if (!selinux_initialized(&selinux_state))
928 * Specifying internal flags without providing a place to
929 * place the results is not allowed.
931 if (kern_flags && !set_kern_flags)
934 /* how can we clone if the old one wasn't set up?? */
935 BUG_ON(!(oldsbsec->flags & SE_SBINITIALIZED));
937 /* if fs is reusing a sb, make sure that the contexts match */
938 if (newsbsec->flags & SE_SBINITIALIZED) {
939 if ((kern_flags & SECURITY_LSM_NATIVE_LABELS) && !set_context)
940 *set_kern_flags |= SECURITY_LSM_NATIVE_LABELS;
941 return selinux_cmp_sb_context(oldsb, newsb);
944 mutex_lock(&newsbsec->lock);
946 newsbsec->flags = oldsbsec->flags;
948 newsbsec->sid = oldsbsec->sid;
949 newsbsec->def_sid = oldsbsec->def_sid;
950 newsbsec->behavior = oldsbsec->behavior;
952 if (newsbsec->behavior == SECURITY_FS_USE_NATIVE &&
953 !(kern_flags & SECURITY_LSM_NATIVE_LABELS) && !set_context) {
954 rc = security_fs_use(&selinux_state, newsb);
959 if (kern_flags & SECURITY_LSM_NATIVE_LABELS && !set_context) {
960 newsbsec->behavior = SECURITY_FS_USE_NATIVE;
961 *set_kern_flags |= SECURITY_LSM_NATIVE_LABELS;
965 u32 sid = oldsbsec->mntpoint_sid;
969 if (!set_rootcontext) {
970 struct inode_security_struct *newisec = backing_inode_security(newsb->s_root);
973 newsbsec->mntpoint_sid = sid;
975 if (set_rootcontext) {
976 const struct inode_security_struct *oldisec = backing_inode_security(oldsb->s_root);
977 struct inode_security_struct *newisec = backing_inode_security(newsb->s_root);
979 newisec->sid = oldisec->sid;
982 sb_finish_set_opts(newsb);
984 mutex_unlock(&newsbsec->lock);
988 static int selinux_add_opt(int token, const char *s, void **mnt_opts)
990 struct selinux_mnt_opts *opts = *mnt_opts;
992 if (token == Opt_seclabel) /* eaten and completely ignored */
996 opts = kzalloc(sizeof(struct selinux_mnt_opts), GFP_KERNEL);
1005 if (opts->context || opts->defcontext)
1010 if (opts->fscontext)
1012 opts->fscontext = s;
1014 case Opt_rootcontext:
1015 if (opts->rootcontext)
1017 opts->rootcontext = s;
1019 case Opt_defcontext:
1020 if (opts->context || opts->defcontext)
1022 opts->defcontext = s;
1027 pr_warn(SEL_MOUNT_FAIL_MSG);
1031 static int selinux_add_mnt_opt(const char *option, const char *val, int len,
1034 int token = Opt_error;
1037 for (i = 0; i < ARRAY_SIZE(tokens); i++) {
1038 if (strcmp(option, tokens[i].name) == 0) {
1039 token = tokens[i].opt;
1044 if (token == Opt_error)
1047 if (token != Opt_seclabel) {
1048 val = kmemdup_nul(val, len, GFP_KERNEL);
1054 rc = selinux_add_opt(token, val, mnt_opts);
1063 selinux_free_mnt_opts(*mnt_opts);
1069 static int show_sid(struct seq_file *m, u32 sid)
1071 char *context = NULL;
1075 rc = security_sid_to_context(&selinux_state, sid,
1078 bool has_comma = context && strchr(context, ',');
1083 seq_escape(m, context, "\"\n\\");
1091 static int selinux_sb_show_options(struct seq_file *m, struct super_block *sb)
1093 struct superblock_security_struct *sbsec = selinux_superblock(sb);
1096 if (!(sbsec->flags & SE_SBINITIALIZED))
1099 if (!selinux_initialized(&selinux_state))
1102 if (sbsec->flags & FSCONTEXT_MNT) {
1104 seq_puts(m, FSCONTEXT_STR);
1105 rc = show_sid(m, sbsec->sid);
1109 if (sbsec->flags & CONTEXT_MNT) {
1111 seq_puts(m, CONTEXT_STR);
1112 rc = show_sid(m, sbsec->mntpoint_sid);
1116 if (sbsec->flags & DEFCONTEXT_MNT) {
1118 seq_puts(m, DEFCONTEXT_STR);
1119 rc = show_sid(m, sbsec->def_sid);
1123 if (sbsec->flags & ROOTCONTEXT_MNT) {
1124 struct dentry *root = sb->s_root;
1125 struct inode_security_struct *isec = backing_inode_security(root);
1127 seq_puts(m, ROOTCONTEXT_STR);
1128 rc = show_sid(m, isec->sid);
1132 if (sbsec->flags & SBLABEL_MNT) {
1134 seq_puts(m, SECLABEL_STR);
1139 static inline u16 inode_mode_to_security_class(umode_t mode)
1141 switch (mode & S_IFMT) {
1143 return SECCLASS_SOCK_FILE;
1145 return SECCLASS_LNK_FILE;
1147 return SECCLASS_FILE;
1149 return SECCLASS_BLK_FILE;
1151 return SECCLASS_DIR;
1153 return SECCLASS_CHR_FILE;
1155 return SECCLASS_FIFO_FILE;
1159 return SECCLASS_FILE;
1162 static inline int default_protocol_stream(int protocol)
1164 return (protocol == IPPROTO_IP || protocol == IPPROTO_TCP ||
1165 protocol == IPPROTO_MPTCP);
1168 static inline int default_protocol_dgram(int protocol)
1170 return (protocol == IPPROTO_IP || protocol == IPPROTO_UDP);
1173 static inline u16 socket_type_to_security_class(int family, int type, int protocol)
1175 int extsockclass = selinux_policycap_extsockclass();
1181 case SOCK_SEQPACKET:
1182 return SECCLASS_UNIX_STREAM_SOCKET;
1185 return SECCLASS_UNIX_DGRAM_SOCKET;
1192 case SOCK_SEQPACKET:
1193 if (default_protocol_stream(protocol))
1194 return SECCLASS_TCP_SOCKET;
1195 else if (extsockclass && protocol == IPPROTO_SCTP)
1196 return SECCLASS_SCTP_SOCKET;
1198 return SECCLASS_RAWIP_SOCKET;
1200 if (default_protocol_dgram(protocol))
1201 return SECCLASS_UDP_SOCKET;
1202 else if (extsockclass && (protocol == IPPROTO_ICMP ||
1203 protocol == IPPROTO_ICMPV6))
1204 return SECCLASS_ICMP_SOCKET;
1206 return SECCLASS_RAWIP_SOCKET;
1208 return SECCLASS_DCCP_SOCKET;
1210 return SECCLASS_RAWIP_SOCKET;
1216 return SECCLASS_NETLINK_ROUTE_SOCKET;
1217 case NETLINK_SOCK_DIAG:
1218 return SECCLASS_NETLINK_TCPDIAG_SOCKET;
1220 return SECCLASS_NETLINK_NFLOG_SOCKET;
1222 return SECCLASS_NETLINK_XFRM_SOCKET;
1223 case NETLINK_SELINUX:
1224 return SECCLASS_NETLINK_SELINUX_SOCKET;
1226 return SECCLASS_NETLINK_ISCSI_SOCKET;
1228 return SECCLASS_NETLINK_AUDIT_SOCKET;
1229 case NETLINK_FIB_LOOKUP:
1230 return SECCLASS_NETLINK_FIB_LOOKUP_SOCKET;
1231 case NETLINK_CONNECTOR:
1232 return SECCLASS_NETLINK_CONNECTOR_SOCKET;
1233 case NETLINK_NETFILTER:
1234 return SECCLASS_NETLINK_NETFILTER_SOCKET;
1235 case NETLINK_DNRTMSG:
1236 return SECCLASS_NETLINK_DNRT_SOCKET;
1237 case NETLINK_KOBJECT_UEVENT:
1238 return SECCLASS_NETLINK_KOBJECT_UEVENT_SOCKET;
1239 case NETLINK_GENERIC:
1240 return SECCLASS_NETLINK_GENERIC_SOCKET;
1241 case NETLINK_SCSITRANSPORT:
1242 return SECCLASS_NETLINK_SCSITRANSPORT_SOCKET;
1244 return SECCLASS_NETLINK_RDMA_SOCKET;
1245 case NETLINK_CRYPTO:
1246 return SECCLASS_NETLINK_CRYPTO_SOCKET;
1248 return SECCLASS_NETLINK_SOCKET;
1251 return SECCLASS_PACKET_SOCKET;
1253 return SECCLASS_KEY_SOCKET;
1255 return SECCLASS_APPLETALK_SOCKET;
1261 return SECCLASS_AX25_SOCKET;
1263 return SECCLASS_IPX_SOCKET;
1265 return SECCLASS_NETROM_SOCKET;
1267 return SECCLASS_ATMPVC_SOCKET;
1269 return SECCLASS_X25_SOCKET;
1271 return SECCLASS_ROSE_SOCKET;
1273 return SECCLASS_DECNET_SOCKET;
1275 return SECCLASS_ATMSVC_SOCKET;
1277 return SECCLASS_RDS_SOCKET;
1279 return SECCLASS_IRDA_SOCKET;
1281 return SECCLASS_PPPOX_SOCKET;
1283 return SECCLASS_LLC_SOCKET;
1285 return SECCLASS_CAN_SOCKET;
1287 return SECCLASS_TIPC_SOCKET;
1289 return SECCLASS_BLUETOOTH_SOCKET;
1291 return SECCLASS_IUCV_SOCKET;
1293 return SECCLASS_RXRPC_SOCKET;
1295 return SECCLASS_ISDN_SOCKET;
1297 return SECCLASS_PHONET_SOCKET;
1299 return SECCLASS_IEEE802154_SOCKET;
1301 return SECCLASS_CAIF_SOCKET;
1303 return SECCLASS_ALG_SOCKET;
1305 return SECCLASS_NFC_SOCKET;
1307 return SECCLASS_VSOCK_SOCKET;
1309 return SECCLASS_KCM_SOCKET;
1311 return SECCLASS_QIPCRTR_SOCKET;
1313 return SECCLASS_SMC_SOCKET;
1315 return SECCLASS_XDP_SOCKET;
1317 return SECCLASS_MCTP_SOCKET;
1319 #error New address family defined, please update this function.
1324 return SECCLASS_SOCKET;
1327 static int selinux_genfs_get_sid(struct dentry *dentry,
1333 struct super_block *sb = dentry->d_sb;
1334 char *buffer, *path;
1336 buffer = (char *)__get_free_page(GFP_KERNEL);
1340 path = dentry_path_raw(dentry, buffer, PAGE_SIZE);
1344 if (flags & SE_SBPROC) {
1345 /* each process gets a /proc/PID/ entry. Strip off the
1346 * PID part to get a valid selinux labeling.
1347 * e.g. /proc/1/net/rpc/nfs -> /net/rpc/nfs */
1348 while (path[1] >= '0' && path[1] <= '9') {
1353 rc = security_genfs_sid(&selinux_state, sb->s_type->name,
1355 if (rc == -ENOENT) {
1356 /* No match in policy, mark as unlabeled. */
1357 *sid = SECINITSID_UNLABELED;
1361 free_page((unsigned long)buffer);
1365 static int inode_doinit_use_xattr(struct inode *inode, struct dentry *dentry,
1366 u32 def_sid, u32 *sid)
1368 #define INITCONTEXTLEN 255
1373 len = INITCONTEXTLEN;
1374 context = kmalloc(len + 1, GFP_NOFS);
1378 context[len] = '\0';
1379 rc = __vfs_getxattr(dentry, inode, XATTR_NAME_SELINUX, context, len);
1380 if (rc == -ERANGE) {
1383 /* Need a larger buffer. Query for the right size. */
1384 rc = __vfs_getxattr(dentry, inode, XATTR_NAME_SELINUX, NULL, 0);
1389 context = kmalloc(len + 1, GFP_NOFS);
1393 context[len] = '\0';
1394 rc = __vfs_getxattr(dentry, inode, XATTR_NAME_SELINUX,
1399 if (rc != -ENODATA) {
1400 pr_warn("SELinux: %s: getxattr returned %d for dev=%s ino=%ld\n",
1401 __func__, -rc, inode->i_sb->s_id, inode->i_ino);
1408 rc = security_context_to_sid_default(&selinux_state, context, rc, sid,
1411 char *dev = inode->i_sb->s_id;
1412 unsigned long ino = inode->i_ino;
1414 if (rc == -EINVAL) {
1415 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 pr_warn("SELinux: %s: context_to_sid(%s) returned %d for dev=%s ino=%ld\n",
1419 __func__, context, -rc, dev, ino);
1426 /* The inode's security attributes must be initialized before first use. */
1427 static int inode_doinit_with_dentry(struct inode *inode, struct dentry *opt_dentry)
1429 struct superblock_security_struct *sbsec = NULL;
1430 struct inode_security_struct *isec = selinux_inode(inode);
1431 u32 task_sid, sid = 0;
1433 struct dentry *dentry;
1436 if (isec->initialized == LABEL_INITIALIZED)
1439 spin_lock(&isec->lock);
1440 if (isec->initialized == LABEL_INITIALIZED)
1443 if (isec->sclass == SECCLASS_FILE)
1444 isec->sclass = inode_mode_to_security_class(inode->i_mode);
1446 sbsec = selinux_superblock(inode->i_sb);
1447 if (!(sbsec->flags & SE_SBINITIALIZED)) {
1448 /* Defer initialization until selinux_complete_init,
1449 after the initial policy is loaded and the security
1450 server is ready to handle calls. */
1451 spin_lock(&sbsec->isec_lock);
1452 if (list_empty(&isec->list))
1453 list_add(&isec->list, &sbsec->isec_head);
1454 spin_unlock(&sbsec->isec_lock);
1458 sclass = isec->sclass;
1459 task_sid = isec->task_sid;
1461 isec->initialized = LABEL_PENDING;
1462 spin_unlock(&isec->lock);
1464 switch (sbsec->behavior) {
1465 case SECURITY_FS_USE_NATIVE:
1467 case SECURITY_FS_USE_XATTR:
1468 if (!(inode->i_opflags & IOP_XATTR)) {
1469 sid = sbsec->def_sid;
1472 /* Need a dentry, since the xattr API requires one.
1473 Life would be simpler if we could just pass the inode. */
1475 /* Called from d_instantiate or d_splice_alias. */
1476 dentry = dget(opt_dentry);
1479 * Called from selinux_complete_init, try to find a dentry.
1480 * Some filesystems really want a connected one, so try
1481 * that first. We could split SECURITY_FS_USE_XATTR in
1482 * two, depending upon that...
1484 dentry = d_find_alias(inode);
1486 dentry = d_find_any_alias(inode);
1490 * this is can be hit on boot when a file is accessed
1491 * before the policy is loaded. When we load policy we
1492 * may find inodes that have no dentry on the
1493 * sbsec->isec_head list. No reason to complain as these
1494 * will get fixed up the next time we go through
1495 * inode_doinit with a dentry, before these inodes could
1496 * be used again by userspace.
1501 rc = inode_doinit_use_xattr(inode, dentry, sbsec->def_sid,
1507 case SECURITY_FS_USE_TASK:
1510 case SECURITY_FS_USE_TRANS:
1511 /* Default to the fs SID. */
1514 /* Try to obtain a transition SID. */
1515 rc = security_transition_sid(&selinux_state, task_sid, sid,
1516 sclass, NULL, &sid);
1520 case SECURITY_FS_USE_MNTPOINT:
1521 sid = sbsec->mntpoint_sid;
1524 /* Default to the fs superblock SID. */
1527 if ((sbsec->flags & SE_SBGENFS) &&
1528 (!S_ISLNK(inode->i_mode) ||
1529 selinux_policycap_genfs_seclabel_symlinks())) {
1530 /* We must have a dentry to determine the label on
1533 /* Called from d_instantiate or
1534 * d_splice_alias. */
1535 dentry = dget(opt_dentry);
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);
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.
1556 rc = selinux_genfs_get_sid(dentry, sclass,
1557 sbsec->flags, &sid);
1563 if ((sbsec->flags & SE_SBGENFS_XATTR) &&
1564 (inode->i_opflags & IOP_XATTR)) {
1565 rc = inode_doinit_use_xattr(inode, dentry,
1578 spin_lock(&isec->lock);
1579 if (isec->initialized == LABEL_PENDING) {
1581 isec->initialized = LABEL_INVALID;
1584 isec->initialized = LABEL_INITIALIZED;
1589 spin_unlock(&isec->lock);
1593 spin_lock(&isec->lock);
1594 if (isec->initialized == LABEL_PENDING) {
1595 isec->initialized = LABEL_INVALID;
1598 spin_unlock(&isec->lock);
1602 /* Convert a Linux signal to an access vector. */
1603 static inline u32 signal_to_av(int sig)
1609 /* Commonly granted from child to parent. */
1610 perm = PROCESS__SIGCHLD;
1613 /* Cannot be caught or ignored */
1614 perm = PROCESS__SIGKILL;
1617 /* Cannot be caught or ignored */
1618 perm = PROCESS__SIGSTOP;
1621 /* All other signals. */
1622 perm = PROCESS__SIGNAL;
1629 #if CAP_LAST_CAP > 63
1630 #error Fix SELinux to handle capabilities > 63.
1633 /* Check whether a task is allowed to use a capability. */
1634 static int cred_has_capability(const struct cred *cred,
1635 int cap, unsigned int opts, bool initns)
1637 struct common_audit_data ad;
1638 struct av_decision avd;
1640 u32 sid = cred_sid(cred);
1641 u32 av = CAP_TO_MASK(cap);
1644 ad.type = LSM_AUDIT_DATA_CAP;
1647 switch (CAP_TO_INDEX(cap)) {
1649 sclass = initns ? SECCLASS_CAPABILITY : SECCLASS_CAP_USERNS;
1652 sclass = initns ? SECCLASS_CAPABILITY2 : SECCLASS_CAP2_USERNS;
1655 pr_err("SELinux: out of range capability %d\n", cap);
1660 rc = avc_has_perm_noaudit(&selinux_state,
1661 sid, sid, sclass, av, 0, &avd);
1662 if (!(opts & CAP_OPT_NOAUDIT)) {
1663 int rc2 = avc_audit(&selinux_state,
1664 sid, sid, sclass, av, &avd, rc, &ad);
1671 /* Check whether a task has a particular permission to an inode.
1672 The 'adp' parameter is optional and allows other audit
1673 data to be passed (e.g. the dentry). */
1674 static int inode_has_perm(const struct cred *cred,
1675 struct inode *inode,
1677 struct common_audit_data *adp)
1679 struct inode_security_struct *isec;
1682 validate_creds(cred);
1684 if (unlikely(IS_PRIVATE(inode)))
1687 sid = cred_sid(cred);
1688 isec = selinux_inode(inode);
1690 return avc_has_perm(&selinux_state,
1691 sid, isec->sid, isec->sclass, perms, adp);
1694 /* Same as inode_has_perm, but pass explicit audit data containing
1695 the dentry to help the auditing code to more easily generate the
1696 pathname if needed. */
1697 static inline int dentry_has_perm(const struct cred *cred,
1698 struct dentry *dentry,
1701 struct inode *inode = d_backing_inode(dentry);
1702 struct common_audit_data ad;
1704 ad.type = LSM_AUDIT_DATA_DENTRY;
1705 ad.u.dentry = dentry;
1706 __inode_security_revalidate(inode, dentry, true);
1707 return inode_has_perm(cred, inode, av, &ad);
1710 /* Same as inode_has_perm, but pass explicit audit data containing
1711 the path to help the auditing code to more easily generate the
1712 pathname if needed. */
1713 static inline int path_has_perm(const struct cred *cred,
1714 const struct path *path,
1717 struct inode *inode = d_backing_inode(path->dentry);
1718 struct common_audit_data ad;
1720 ad.type = LSM_AUDIT_DATA_PATH;
1722 __inode_security_revalidate(inode, path->dentry, true);
1723 return inode_has_perm(cred, inode, av, &ad);
1726 /* Same as path_has_perm, but uses the inode from the file struct. */
1727 static inline int file_path_has_perm(const struct cred *cred,
1731 struct common_audit_data ad;
1733 ad.type = LSM_AUDIT_DATA_FILE;
1735 return inode_has_perm(cred, file_inode(file), av, &ad);
1738 #ifdef CONFIG_BPF_SYSCALL
1739 static int bpf_fd_pass(struct file *file, u32 sid);
1742 /* Check whether a task can use an open file descriptor to
1743 access an inode in a given way. Check access to the
1744 descriptor itself, and then use dentry_has_perm to
1745 check a particular permission to the file.
1746 Access to the descriptor is implicitly granted if it
1747 has the same SID as the process. If av is zero, then
1748 access to the file is not checked, e.g. for cases
1749 where only the descriptor is affected like seek. */
1750 static int file_has_perm(const struct cred *cred,
1754 struct file_security_struct *fsec = selinux_file(file);
1755 struct inode *inode = file_inode(file);
1756 struct common_audit_data ad;
1757 u32 sid = cred_sid(cred);
1760 ad.type = LSM_AUDIT_DATA_FILE;
1763 if (sid != fsec->sid) {
1764 rc = avc_has_perm(&selinux_state,
1773 #ifdef CONFIG_BPF_SYSCALL
1774 rc = bpf_fd_pass(file, cred_sid(cred));
1779 /* av is zero if only checking access to the descriptor. */
1782 rc = inode_has_perm(cred, inode, av, &ad);
1789 * Determine the label for an inode that might be unioned.
1792 selinux_determine_inode_label(const struct task_security_struct *tsec,
1794 const struct qstr *name, u16 tclass,
1797 const struct superblock_security_struct *sbsec =
1798 selinux_superblock(dir->i_sb);
1800 if ((sbsec->flags & SE_SBINITIALIZED) &&
1801 (sbsec->behavior == SECURITY_FS_USE_MNTPOINT)) {
1802 *_new_isid = sbsec->mntpoint_sid;
1803 } else if ((sbsec->flags & SBLABEL_MNT) &&
1805 *_new_isid = tsec->create_sid;
1807 const struct inode_security_struct *dsec = inode_security(dir);
1808 return security_transition_sid(&selinux_state, tsec->sid,
1816 /* Check whether a task can create a file. */
1817 static int may_create(struct inode *dir,
1818 struct dentry *dentry,
1821 const struct task_security_struct *tsec = selinux_cred(current_cred());
1822 struct inode_security_struct *dsec;
1823 struct superblock_security_struct *sbsec;
1825 struct common_audit_data ad;
1828 dsec = inode_security(dir);
1829 sbsec = selinux_superblock(dir->i_sb);
1833 ad.type = LSM_AUDIT_DATA_DENTRY;
1834 ad.u.dentry = dentry;
1836 rc = avc_has_perm(&selinux_state,
1837 sid, dsec->sid, SECCLASS_DIR,
1838 DIR__ADD_NAME | DIR__SEARCH,
1843 rc = selinux_determine_inode_label(tsec, dir, &dentry->d_name, tclass,
1848 rc = avc_has_perm(&selinux_state,
1849 sid, newsid, tclass, FILE__CREATE, &ad);
1853 return avc_has_perm(&selinux_state,
1855 SECCLASS_FILESYSTEM,
1856 FILESYSTEM__ASSOCIATE, &ad);
1860 #define MAY_UNLINK 1
1863 /* Check whether a task can link, unlink, or rmdir a file/directory. */
1864 static int may_link(struct inode *dir,
1865 struct dentry *dentry,
1869 struct inode_security_struct *dsec, *isec;
1870 struct common_audit_data ad;
1871 u32 sid = current_sid();
1875 dsec = inode_security(dir);
1876 isec = backing_inode_security(dentry);
1878 ad.type = LSM_AUDIT_DATA_DENTRY;
1879 ad.u.dentry = dentry;
1882 av |= (kind ? DIR__REMOVE_NAME : DIR__ADD_NAME);
1883 rc = avc_has_perm(&selinux_state,
1884 sid, dsec->sid, SECCLASS_DIR, av, &ad);
1899 pr_warn("SELinux: %s: unrecognized kind %d\n",
1904 rc = avc_has_perm(&selinux_state,
1905 sid, isec->sid, isec->sclass, av, &ad);
1909 static inline int may_rename(struct inode *old_dir,
1910 struct dentry *old_dentry,
1911 struct inode *new_dir,
1912 struct dentry *new_dentry)
1914 struct inode_security_struct *old_dsec, *new_dsec, *old_isec, *new_isec;
1915 struct common_audit_data ad;
1916 u32 sid = current_sid();
1918 int old_is_dir, new_is_dir;
1921 old_dsec = inode_security(old_dir);
1922 old_isec = backing_inode_security(old_dentry);
1923 old_is_dir = d_is_dir(old_dentry);
1924 new_dsec = inode_security(new_dir);
1926 ad.type = LSM_AUDIT_DATA_DENTRY;
1928 ad.u.dentry = old_dentry;
1929 rc = avc_has_perm(&selinux_state,
1930 sid, old_dsec->sid, SECCLASS_DIR,
1931 DIR__REMOVE_NAME | DIR__SEARCH, &ad);
1934 rc = avc_has_perm(&selinux_state,
1936 old_isec->sclass, FILE__RENAME, &ad);
1939 if (old_is_dir && new_dir != old_dir) {
1940 rc = avc_has_perm(&selinux_state,
1942 old_isec->sclass, DIR__REPARENT, &ad);
1947 ad.u.dentry = new_dentry;
1948 av = DIR__ADD_NAME | DIR__SEARCH;
1949 if (d_is_positive(new_dentry))
1950 av |= DIR__REMOVE_NAME;
1951 rc = avc_has_perm(&selinux_state,
1952 sid, new_dsec->sid, SECCLASS_DIR, av, &ad);
1955 if (d_is_positive(new_dentry)) {
1956 new_isec = backing_inode_security(new_dentry);
1957 new_is_dir = d_is_dir(new_dentry);
1958 rc = avc_has_perm(&selinux_state,
1961 (new_is_dir ? DIR__RMDIR : FILE__UNLINK), &ad);
1969 /* Check whether a task can perform a filesystem operation. */
1970 static int superblock_has_perm(const struct cred *cred,
1971 struct super_block *sb,
1973 struct common_audit_data *ad)
1975 struct superblock_security_struct *sbsec;
1976 u32 sid = cred_sid(cred);
1978 sbsec = selinux_superblock(sb);
1979 return avc_has_perm(&selinux_state,
1980 sid, sbsec->sid, SECCLASS_FILESYSTEM, perms, ad);
1983 /* Convert a Linux mode and permission mask to an access vector. */
1984 static inline u32 file_mask_to_av(int mode, int mask)
1988 if (!S_ISDIR(mode)) {
1989 if (mask & MAY_EXEC)
1990 av |= FILE__EXECUTE;
1991 if (mask & MAY_READ)
1994 if (mask & MAY_APPEND)
1996 else if (mask & MAY_WRITE)
2000 if (mask & MAY_EXEC)
2002 if (mask & MAY_WRITE)
2004 if (mask & MAY_READ)
2011 /* Convert a Linux file to an access vector. */
2012 static inline u32 file_to_av(struct file *file)
2016 if (file->f_mode & FMODE_READ)
2018 if (file->f_mode & FMODE_WRITE) {
2019 if (file->f_flags & O_APPEND)
2026 * Special file opened with flags 3 for ioctl-only use.
2035 * Convert a file to an access vector and include the correct
2038 static inline u32 open_file_to_av(struct file *file)
2040 u32 av = file_to_av(file);
2041 struct inode *inode = file_inode(file);
2043 if (selinux_policycap_openperm() &&
2044 inode->i_sb->s_magic != SOCKFS_MAGIC)
2050 /* Hook functions begin here. */
2052 static int selinux_binder_set_context_mgr(const struct cred *mgr)
2054 return avc_has_perm(&selinux_state,
2055 current_sid(), cred_sid(mgr), SECCLASS_BINDER,
2056 BINDER__SET_CONTEXT_MGR, NULL);
2059 static int selinux_binder_transaction(const struct cred *from,
2060 const struct cred *to)
2062 u32 mysid = current_sid();
2063 u32 fromsid = cred_sid(from);
2064 u32 tosid = cred_sid(to);
2067 if (mysid != fromsid) {
2068 rc = avc_has_perm(&selinux_state,
2069 mysid, fromsid, SECCLASS_BINDER,
2070 BINDER__IMPERSONATE, NULL);
2075 return avc_has_perm(&selinux_state, fromsid, tosid,
2076 SECCLASS_BINDER, BINDER__CALL, NULL);
2079 static int selinux_binder_transfer_binder(const struct cred *from,
2080 const struct cred *to)
2082 return avc_has_perm(&selinux_state,
2083 cred_sid(from), cred_sid(to),
2084 SECCLASS_BINDER, BINDER__TRANSFER,
2088 static int selinux_binder_transfer_file(const struct cred *from,
2089 const struct cred *to,
2092 u32 sid = cred_sid(to);
2093 struct file_security_struct *fsec = selinux_file(file);
2094 struct dentry *dentry = file->f_path.dentry;
2095 struct inode_security_struct *isec;
2096 struct common_audit_data ad;
2099 ad.type = LSM_AUDIT_DATA_PATH;
2100 ad.u.path = file->f_path;
2102 if (sid != fsec->sid) {
2103 rc = avc_has_perm(&selinux_state,
2112 #ifdef CONFIG_BPF_SYSCALL
2113 rc = bpf_fd_pass(file, sid);
2118 if (unlikely(IS_PRIVATE(d_backing_inode(dentry))))
2121 isec = backing_inode_security(dentry);
2122 return avc_has_perm(&selinux_state,
2123 sid, isec->sid, isec->sclass, file_to_av(file),
2127 static int selinux_ptrace_access_check(struct task_struct *child,
2130 u32 sid = current_sid();
2131 u32 csid = task_sid_obj(child);
2133 if (mode & PTRACE_MODE_READ)
2134 return avc_has_perm(&selinux_state,
2135 sid, csid, SECCLASS_FILE, FILE__READ, NULL);
2137 return avc_has_perm(&selinux_state,
2138 sid, csid, SECCLASS_PROCESS, PROCESS__PTRACE, NULL);
2141 static int selinux_ptrace_traceme(struct task_struct *parent)
2143 return avc_has_perm(&selinux_state,
2144 task_sid_obj(parent), task_sid_obj(current),
2145 SECCLASS_PROCESS, PROCESS__PTRACE, NULL);
2148 static int selinux_capget(struct task_struct *target, kernel_cap_t *effective,
2149 kernel_cap_t *inheritable, kernel_cap_t *permitted)
2151 return avc_has_perm(&selinux_state,
2152 current_sid(), task_sid_obj(target), SECCLASS_PROCESS,
2153 PROCESS__GETCAP, NULL);
2156 static int selinux_capset(struct cred *new, const struct cred *old,
2157 const kernel_cap_t *effective,
2158 const kernel_cap_t *inheritable,
2159 const kernel_cap_t *permitted)
2161 return avc_has_perm(&selinux_state,
2162 cred_sid(old), cred_sid(new), SECCLASS_PROCESS,
2163 PROCESS__SETCAP, NULL);
2167 * (This comment used to live with the selinux_task_setuid hook,
2168 * which was removed).
2170 * Since setuid only affects the current process, and since the SELinux
2171 * controls are not based on the Linux identity attributes, SELinux does not
2172 * need to control this operation. However, SELinux does control the use of
2173 * the CAP_SETUID and CAP_SETGID capabilities using the capable hook.
2176 static int selinux_capable(const struct cred *cred, struct user_namespace *ns,
2177 int cap, unsigned int opts)
2179 return cred_has_capability(cred, cap, opts, ns == &init_user_ns);
2182 static int selinux_quotactl(int cmds, int type, int id, struct super_block *sb)
2184 const struct cred *cred = current_cred();
2199 rc = superblock_has_perm(cred, sb, FILESYSTEM__QUOTAMOD, NULL);
2207 case Q_XGETNEXTQUOTA:
2208 rc = superblock_has_perm(cred, sb, FILESYSTEM__QUOTAGET, NULL);
2211 rc = 0; /* let the kernel handle invalid cmds */
2217 static int selinux_quota_on(struct dentry *dentry)
2219 const struct cred *cred = current_cred();
2221 return dentry_has_perm(cred, dentry, FILE__QUOTAON);
2224 static int selinux_syslog(int type)
2227 case SYSLOG_ACTION_READ_ALL: /* Read last kernel messages */
2228 case SYSLOG_ACTION_SIZE_BUFFER: /* Return size of the log buffer */
2229 return avc_has_perm(&selinux_state,
2230 current_sid(), SECINITSID_KERNEL,
2231 SECCLASS_SYSTEM, SYSTEM__SYSLOG_READ, NULL);
2232 case SYSLOG_ACTION_CONSOLE_OFF: /* Disable logging to console */
2233 case SYSLOG_ACTION_CONSOLE_ON: /* Enable logging to console */
2234 /* Set level of messages printed to console */
2235 case SYSLOG_ACTION_CONSOLE_LEVEL:
2236 return avc_has_perm(&selinux_state,
2237 current_sid(), SECINITSID_KERNEL,
2238 SECCLASS_SYSTEM, SYSTEM__SYSLOG_CONSOLE,
2241 /* All other syslog types */
2242 return avc_has_perm(&selinux_state,
2243 current_sid(), SECINITSID_KERNEL,
2244 SECCLASS_SYSTEM, SYSTEM__SYSLOG_MOD, NULL);
2248 * Check that a process has enough memory to allocate a new virtual
2249 * mapping. 0 means there is enough memory for the allocation to
2250 * succeed and -ENOMEM implies there is not.
2252 * Do not audit the selinux permission check, as this is applied to all
2253 * processes that allocate mappings.
2255 static int selinux_vm_enough_memory(struct mm_struct *mm, long pages)
2257 int rc, cap_sys_admin = 0;
2259 rc = cred_has_capability(current_cred(), CAP_SYS_ADMIN,
2260 CAP_OPT_NOAUDIT, true);
2264 return cap_sys_admin;
2267 /* binprm security operations */
2269 static u32 ptrace_parent_sid(void)
2272 struct task_struct *tracer;
2275 tracer = ptrace_parent(current);
2277 sid = task_sid_obj(tracer);
2283 static int check_nnp_nosuid(const struct linux_binprm *bprm,
2284 const struct task_security_struct *old_tsec,
2285 const struct task_security_struct *new_tsec)
2287 int nnp = (bprm->unsafe & LSM_UNSAFE_NO_NEW_PRIVS);
2288 int nosuid = !mnt_may_suid(bprm->file->f_path.mnt);
2292 if (!nnp && !nosuid)
2293 return 0; /* neither NNP nor nosuid */
2295 if (new_tsec->sid == old_tsec->sid)
2296 return 0; /* No change in credentials */
2299 * If the policy enables the nnp_nosuid_transition policy capability,
2300 * then we permit transitions under NNP or nosuid if the
2301 * policy allows the corresponding permission between
2302 * the old and new contexts.
2304 if (selinux_policycap_nnp_nosuid_transition()) {
2307 av |= PROCESS2__NNP_TRANSITION;
2309 av |= PROCESS2__NOSUID_TRANSITION;
2310 rc = avc_has_perm(&selinux_state,
2311 old_tsec->sid, new_tsec->sid,
2312 SECCLASS_PROCESS2, av, NULL);
2318 * We also permit NNP or nosuid transitions to bounded SIDs,
2319 * i.e. SIDs that are guaranteed to only be allowed a subset
2320 * of the permissions of the current SID.
2322 rc = security_bounded_transition(&selinux_state, old_tsec->sid,
2328 * On failure, preserve the errno values for NNP vs nosuid.
2329 * NNP: Operation not permitted for caller.
2330 * nosuid: Permission denied to file.
2337 static int selinux_bprm_creds_for_exec(struct linux_binprm *bprm)
2339 const struct task_security_struct *old_tsec;
2340 struct task_security_struct *new_tsec;
2341 struct inode_security_struct *isec;
2342 struct common_audit_data ad;
2343 struct inode *inode = file_inode(bprm->file);
2346 /* SELinux context only depends on initial program or script and not
2347 * the script interpreter */
2349 old_tsec = selinux_cred(current_cred());
2350 new_tsec = selinux_cred(bprm->cred);
2351 isec = inode_security(inode);
2353 /* Default to the current task SID. */
2354 new_tsec->sid = old_tsec->sid;
2355 new_tsec->osid = old_tsec->sid;
2357 /* Reset fs, key, and sock SIDs on execve. */
2358 new_tsec->create_sid = 0;
2359 new_tsec->keycreate_sid = 0;
2360 new_tsec->sockcreate_sid = 0;
2362 if (old_tsec->exec_sid) {
2363 new_tsec->sid = old_tsec->exec_sid;
2364 /* Reset exec SID on execve. */
2365 new_tsec->exec_sid = 0;
2367 /* Fail on NNP or nosuid if not an allowed transition. */
2368 rc = check_nnp_nosuid(bprm, old_tsec, new_tsec);
2372 /* Check for a default transition on this program. */
2373 rc = security_transition_sid(&selinux_state, old_tsec->sid,
2374 isec->sid, SECCLASS_PROCESS, NULL,
2380 * Fallback to old SID on NNP or nosuid if not an allowed
2383 rc = check_nnp_nosuid(bprm, old_tsec, new_tsec);
2385 new_tsec->sid = old_tsec->sid;
2388 ad.type = LSM_AUDIT_DATA_FILE;
2389 ad.u.file = bprm->file;
2391 if (new_tsec->sid == old_tsec->sid) {
2392 rc = avc_has_perm(&selinux_state,
2393 old_tsec->sid, isec->sid,
2394 SECCLASS_FILE, FILE__EXECUTE_NO_TRANS, &ad);
2398 /* Check permissions for the transition. */
2399 rc = avc_has_perm(&selinux_state,
2400 old_tsec->sid, new_tsec->sid,
2401 SECCLASS_PROCESS, PROCESS__TRANSITION, &ad);
2405 rc = avc_has_perm(&selinux_state,
2406 new_tsec->sid, isec->sid,
2407 SECCLASS_FILE, FILE__ENTRYPOINT, &ad);
2411 /* Check for shared state */
2412 if (bprm->unsafe & LSM_UNSAFE_SHARE) {
2413 rc = avc_has_perm(&selinux_state,
2414 old_tsec->sid, new_tsec->sid,
2415 SECCLASS_PROCESS, PROCESS__SHARE,
2421 /* Make sure that anyone attempting to ptrace over a task that
2422 * changes its SID has the appropriate permit */
2423 if (bprm->unsafe & LSM_UNSAFE_PTRACE) {
2424 u32 ptsid = ptrace_parent_sid();
2426 rc = avc_has_perm(&selinux_state,
2427 ptsid, new_tsec->sid,
2429 PROCESS__PTRACE, NULL);
2435 /* Clear any possibly unsafe personality bits on exec: */
2436 bprm->per_clear |= PER_CLEAR_ON_SETID;
2438 /* Enable secure mode for SIDs transitions unless
2439 the noatsecure permission is granted between
2440 the two SIDs, i.e. ahp returns 0. */
2441 rc = avc_has_perm(&selinux_state,
2442 old_tsec->sid, new_tsec->sid,
2443 SECCLASS_PROCESS, PROCESS__NOATSECURE,
2445 bprm->secureexec |= !!rc;
2451 static int match_file(const void *p, struct file *file, unsigned fd)
2453 return file_has_perm(p, file, file_to_av(file)) ? fd + 1 : 0;
2456 /* Derived from fs/exec.c:flush_old_files. */
2457 static inline void flush_unauthorized_files(const struct cred *cred,
2458 struct files_struct *files)
2460 struct file *file, *devnull = NULL;
2461 struct tty_struct *tty;
2465 tty = get_current_tty();
2467 spin_lock(&tty->files_lock);
2468 if (!list_empty(&tty->tty_files)) {
2469 struct tty_file_private *file_priv;
2471 /* Revalidate access to controlling tty.
2472 Use file_path_has_perm on the tty path directly
2473 rather than using file_has_perm, as this particular
2474 open file may belong to another process and we are
2475 only interested in the inode-based check here. */
2476 file_priv = list_first_entry(&tty->tty_files,
2477 struct tty_file_private, list);
2478 file = file_priv->file;
2479 if (file_path_has_perm(cred, file, FILE__READ | FILE__WRITE))
2482 spin_unlock(&tty->files_lock);
2485 /* Reset controlling tty. */
2489 /* Revalidate access to inherited open files. */
2490 n = iterate_fd(files, 0, match_file, cred);
2491 if (!n) /* none found? */
2494 devnull = dentry_open(&selinux_null, O_RDWR, cred);
2495 if (IS_ERR(devnull))
2497 /* replace all the matching ones with this */
2499 replace_fd(n - 1, devnull, 0);
2500 } while ((n = iterate_fd(files, n, match_file, cred)) != 0);
2506 * Prepare a process for imminent new credential changes due to exec
2508 static void selinux_bprm_committing_creds(struct linux_binprm *bprm)
2510 struct task_security_struct *new_tsec;
2511 struct rlimit *rlim, *initrlim;
2514 new_tsec = selinux_cred(bprm->cred);
2515 if (new_tsec->sid == new_tsec->osid)
2518 /* Close files for which the new task SID is not authorized. */
2519 flush_unauthorized_files(bprm->cred, current->files);
2521 /* Always clear parent death signal on SID transitions. */
2522 current->pdeath_signal = 0;
2524 /* Check whether the new SID can inherit resource limits from the old
2525 * SID. If not, reset all soft limits to the lower of the current
2526 * task's hard limit and the init task's soft limit.
2528 * Note that the setting of hard limits (even to lower them) can be
2529 * controlled by the setrlimit check. The inclusion of the init task's
2530 * soft limit into the computation is to avoid resetting soft limits
2531 * higher than the default soft limit for cases where the default is
2532 * lower than the hard limit, e.g. RLIMIT_CORE or RLIMIT_STACK.
2534 rc = avc_has_perm(&selinux_state,
2535 new_tsec->osid, new_tsec->sid, SECCLASS_PROCESS,
2536 PROCESS__RLIMITINH, NULL);
2538 /* protect against do_prlimit() */
2540 for (i = 0; i < RLIM_NLIMITS; i++) {
2541 rlim = current->signal->rlim + i;
2542 initrlim = init_task.signal->rlim + i;
2543 rlim->rlim_cur = min(rlim->rlim_max, initrlim->rlim_cur);
2545 task_unlock(current);
2546 if (IS_ENABLED(CONFIG_POSIX_TIMERS))
2547 update_rlimit_cpu(current, rlimit(RLIMIT_CPU));
2552 * Clean up the process immediately after the installation of new credentials
2555 static void selinux_bprm_committed_creds(struct linux_binprm *bprm)
2557 const struct task_security_struct *tsec = selinux_cred(current_cred());
2567 /* Check whether the new SID can inherit signal state from the old SID.
2568 * If not, clear itimers to avoid subsequent signal generation and
2569 * flush and unblock signals.
2571 * This must occur _after_ the task SID has been updated so that any
2572 * kill done after the flush will be checked against the new SID.
2574 rc = avc_has_perm(&selinux_state,
2575 osid, sid, SECCLASS_PROCESS, PROCESS__SIGINH, NULL);
2579 spin_lock_irq(¤t->sighand->siglock);
2580 if (!fatal_signal_pending(current)) {
2581 flush_sigqueue(¤t->pending);
2582 flush_sigqueue(¤t->signal->shared_pending);
2583 flush_signal_handlers(current, 1);
2584 sigemptyset(¤t->blocked);
2585 recalc_sigpending();
2587 spin_unlock_irq(¤t->sighand->siglock);
2590 /* Wake up the parent if it is waiting so that it can recheck
2591 * wait permission to the new task SID. */
2592 read_lock(&tasklist_lock);
2593 __wake_up_parent(current, current->real_parent);
2594 read_unlock(&tasklist_lock);
2597 /* superblock security operations */
2599 static int selinux_sb_alloc_security(struct super_block *sb)
2601 struct superblock_security_struct *sbsec = selinux_superblock(sb);
2603 mutex_init(&sbsec->lock);
2604 INIT_LIST_HEAD(&sbsec->isec_head);
2605 spin_lock_init(&sbsec->isec_lock);
2606 sbsec->sid = SECINITSID_UNLABELED;
2607 sbsec->def_sid = SECINITSID_FILE;
2608 sbsec->mntpoint_sid = SECINITSID_UNLABELED;
2613 static inline int opt_len(const char *s)
2615 bool open_quote = false;
2619 for (len = 0; (c = s[len]) != '\0'; len++) {
2621 open_quote = !open_quote;
2622 if (c == ',' && !open_quote)
2628 static int selinux_sb_eat_lsm_opts(char *options, void **mnt_opts)
2630 char *from = options;
2636 int len = opt_len(from);
2640 token = match_opt_prefix(from, len, &arg);
2642 if (token != Opt_error) {
2647 for (p = q = arg; p < from + len; p++) {
2652 arg = kmemdup_nul(arg, q - arg, GFP_KERNEL);
2658 rc = selinux_add_opt(token, arg, mnt_opts);
2664 if (!first) { // copy with preceding comma
2669 memmove(to, from, len);
2682 selinux_free_mnt_opts(*mnt_opts);
2688 static int selinux_sb_mnt_opts_compat(struct super_block *sb, void *mnt_opts)
2690 struct selinux_mnt_opts *opts = mnt_opts;
2691 struct superblock_security_struct *sbsec = sb->s_security;
2696 * Superblock not initialized (i.e. no options) - reject if any
2697 * options specified, otherwise accept.
2699 if (!(sbsec->flags & SE_SBINITIALIZED))
2700 return opts ? 1 : 0;
2703 * Superblock initialized and no options specified - reject if
2704 * superblock has any options set, otherwise accept.
2707 return (sbsec->flags & SE_MNTMASK) ? 1 : 0;
2709 if (opts->fscontext) {
2710 rc = parse_sid(sb, opts->fscontext, &sid, GFP_NOWAIT);
2713 if (bad_option(sbsec, FSCONTEXT_MNT, sbsec->sid, sid))
2716 if (opts->context) {
2717 rc = parse_sid(sb, opts->context, &sid, GFP_NOWAIT);
2720 if (bad_option(sbsec, CONTEXT_MNT, sbsec->mntpoint_sid, sid))
2723 if (opts->rootcontext) {
2724 struct inode_security_struct *root_isec;
2726 root_isec = backing_inode_security(sb->s_root);
2727 rc = parse_sid(sb, opts->rootcontext, &sid, GFP_NOWAIT);
2730 if (bad_option(sbsec, ROOTCONTEXT_MNT, root_isec->sid, sid))
2733 if (opts->defcontext) {
2734 rc = parse_sid(sb, opts->defcontext, &sid, GFP_NOWAIT);
2737 if (bad_option(sbsec, DEFCONTEXT_MNT, sbsec->def_sid, sid))
2743 static int selinux_sb_remount(struct super_block *sb, void *mnt_opts)
2745 struct selinux_mnt_opts *opts = mnt_opts;
2746 struct superblock_security_struct *sbsec = selinux_superblock(sb);
2750 if (!(sbsec->flags & SE_SBINITIALIZED))
2756 if (opts->fscontext) {
2757 rc = parse_sid(sb, opts->fscontext, &sid, GFP_KERNEL);
2760 if (bad_option(sbsec, FSCONTEXT_MNT, sbsec->sid, sid))
2761 goto out_bad_option;
2763 if (opts->context) {
2764 rc = parse_sid(sb, opts->context, &sid, GFP_KERNEL);
2767 if (bad_option(sbsec, CONTEXT_MNT, sbsec->mntpoint_sid, sid))
2768 goto out_bad_option;
2770 if (opts->rootcontext) {
2771 struct inode_security_struct *root_isec;
2772 root_isec = backing_inode_security(sb->s_root);
2773 rc = parse_sid(sb, opts->rootcontext, &sid, GFP_KERNEL);
2776 if (bad_option(sbsec, ROOTCONTEXT_MNT, root_isec->sid, sid))
2777 goto out_bad_option;
2779 if (opts->defcontext) {
2780 rc = parse_sid(sb, opts->defcontext, &sid, GFP_KERNEL);
2783 if (bad_option(sbsec, DEFCONTEXT_MNT, sbsec->def_sid, sid))
2784 goto out_bad_option;
2789 pr_warn("SELinux: unable to change security options "
2790 "during remount (dev %s, type=%s)\n", sb->s_id,
2795 static int selinux_sb_kern_mount(struct super_block *sb)
2797 const struct cred *cred = current_cred();
2798 struct common_audit_data ad;
2800 ad.type = LSM_AUDIT_DATA_DENTRY;
2801 ad.u.dentry = sb->s_root;
2802 return superblock_has_perm(cred, sb, FILESYSTEM__MOUNT, &ad);
2805 static int selinux_sb_statfs(struct dentry *dentry)
2807 const struct cred *cred = current_cred();
2808 struct common_audit_data ad;
2810 ad.type = LSM_AUDIT_DATA_DENTRY;
2811 ad.u.dentry = dentry->d_sb->s_root;
2812 return superblock_has_perm(cred, dentry->d_sb, FILESYSTEM__GETATTR, &ad);
2815 static int selinux_mount(const char *dev_name,
2816 const struct path *path,
2818 unsigned long flags,
2821 const struct cred *cred = current_cred();
2823 if (flags & MS_REMOUNT)
2824 return superblock_has_perm(cred, path->dentry->d_sb,
2825 FILESYSTEM__REMOUNT, NULL);
2827 return path_has_perm(cred, path, FILE__MOUNTON);
2830 static int selinux_move_mount(const struct path *from_path,
2831 const struct path *to_path)
2833 const struct cred *cred = current_cred();
2835 return path_has_perm(cred, to_path, FILE__MOUNTON);
2838 static int selinux_umount(struct vfsmount *mnt, int flags)
2840 const struct cred *cred = current_cred();
2842 return superblock_has_perm(cred, mnt->mnt_sb,
2843 FILESYSTEM__UNMOUNT, NULL);
2846 static int selinux_fs_context_dup(struct fs_context *fc,
2847 struct fs_context *src_fc)
2849 const struct selinux_mnt_opts *src = src_fc->security;
2850 struct selinux_mnt_opts *opts;
2855 fc->security = kzalloc(sizeof(struct selinux_mnt_opts), GFP_KERNEL);
2859 opts = fc->security;
2861 if (src->fscontext) {
2862 opts->fscontext = kstrdup(src->fscontext, GFP_KERNEL);
2863 if (!opts->fscontext)
2867 opts->context = kstrdup(src->context, GFP_KERNEL);
2871 if (src->rootcontext) {
2872 opts->rootcontext = kstrdup(src->rootcontext, GFP_KERNEL);
2873 if (!opts->rootcontext)
2876 if (src->defcontext) {
2877 opts->defcontext = kstrdup(src->defcontext, GFP_KERNEL);
2878 if (!opts->defcontext)
2884 static const struct fs_parameter_spec selinux_fs_parameters[] = {
2885 fsparam_string(CONTEXT_STR, Opt_context),
2886 fsparam_string(DEFCONTEXT_STR, Opt_defcontext),
2887 fsparam_string(FSCONTEXT_STR, Opt_fscontext),
2888 fsparam_string(ROOTCONTEXT_STR, Opt_rootcontext),
2889 fsparam_flag (SECLABEL_STR, Opt_seclabel),
2893 static int selinux_fs_context_parse_param(struct fs_context *fc,
2894 struct fs_parameter *param)
2896 struct fs_parse_result result;
2899 opt = fs_parse(fc, selinux_fs_parameters, param, &result);
2903 rc = selinux_add_opt(opt, param->string, &fc->security);
2905 param->string = NULL;
2911 /* inode security operations */
2913 static int selinux_inode_alloc_security(struct inode *inode)
2915 struct inode_security_struct *isec = selinux_inode(inode);
2916 u32 sid = current_sid();
2918 spin_lock_init(&isec->lock);
2919 INIT_LIST_HEAD(&isec->list);
2920 isec->inode = inode;
2921 isec->sid = SECINITSID_UNLABELED;
2922 isec->sclass = SECCLASS_FILE;
2923 isec->task_sid = sid;
2924 isec->initialized = LABEL_INVALID;
2929 static void selinux_inode_free_security(struct inode *inode)
2931 inode_free_security(inode);
2934 static int selinux_dentry_init_security(struct dentry *dentry, int mode,
2935 const struct qstr *name,
2936 const char **xattr_name, void **ctx,
2942 rc = selinux_determine_inode_label(selinux_cred(current_cred()),
2943 d_inode(dentry->d_parent), name,
2944 inode_mode_to_security_class(mode),
2950 *xattr_name = XATTR_NAME_SELINUX;
2952 return security_sid_to_context(&selinux_state, newsid, (char **)ctx,
2956 static int selinux_dentry_create_files_as(struct dentry *dentry, int mode,
2958 const struct cred *old,
2963 struct task_security_struct *tsec;
2965 rc = selinux_determine_inode_label(selinux_cred(old),
2966 d_inode(dentry->d_parent), name,
2967 inode_mode_to_security_class(mode),
2972 tsec = selinux_cred(new);
2973 tsec->create_sid = newsid;
2977 static int selinux_inode_init_security(struct inode *inode, struct inode *dir,
2978 const struct qstr *qstr,
2980 void **value, size_t *len)
2982 const struct task_security_struct *tsec = selinux_cred(current_cred());
2983 struct superblock_security_struct *sbsec;
2988 sbsec = selinux_superblock(dir->i_sb);
2990 newsid = tsec->create_sid;
2992 rc = selinux_determine_inode_label(tsec, dir, qstr,
2993 inode_mode_to_security_class(inode->i_mode),
2998 /* Possibly defer initialization to selinux_complete_init. */
2999 if (sbsec->flags & SE_SBINITIALIZED) {
3000 struct inode_security_struct *isec = selinux_inode(inode);
3001 isec->sclass = inode_mode_to_security_class(inode->i_mode);
3003 isec->initialized = LABEL_INITIALIZED;
3006 if (!selinux_initialized(&selinux_state) ||
3007 !(sbsec->flags & SBLABEL_MNT))
3011 *name = XATTR_SELINUX_SUFFIX;
3014 rc = security_sid_to_context_force(&selinux_state, newsid,
3025 static int selinux_inode_init_security_anon(struct inode *inode,
3026 const struct qstr *name,
3027 const struct inode *context_inode)
3029 const struct task_security_struct *tsec = selinux_cred(current_cred());
3030 struct common_audit_data ad;
3031 struct inode_security_struct *isec;
3034 if (unlikely(!selinux_initialized(&selinux_state)))
3037 isec = selinux_inode(inode);
3040 * We only get here once per ephemeral inode. The inode has
3041 * been initialized via inode_alloc_security but is otherwise
3045 if (context_inode) {
3046 struct inode_security_struct *context_isec =
3047 selinux_inode(context_inode);
3048 if (context_isec->initialized != LABEL_INITIALIZED) {
3049 pr_err("SELinux: context_inode is not initialized");
3053 isec->sclass = context_isec->sclass;
3054 isec->sid = context_isec->sid;
3056 isec->sclass = SECCLASS_ANON_INODE;
3057 rc = security_transition_sid(
3058 &selinux_state, tsec->sid, tsec->sid,
3059 isec->sclass, name, &isec->sid);
3064 isec->initialized = LABEL_INITIALIZED;
3066 * Now that we've initialized security, check whether we're
3067 * allowed to actually create this type of anonymous inode.
3070 ad.type = LSM_AUDIT_DATA_INODE;
3073 return avc_has_perm(&selinux_state,
3081 static int selinux_inode_create(struct inode *dir, struct dentry *dentry, umode_t mode)
3083 return may_create(dir, dentry, SECCLASS_FILE);
3086 static int selinux_inode_link(struct dentry *old_dentry, struct inode *dir, struct dentry *new_dentry)
3088 return may_link(dir, old_dentry, MAY_LINK);
3091 static int selinux_inode_unlink(struct inode *dir, struct dentry *dentry)
3093 return may_link(dir, dentry, MAY_UNLINK);
3096 static int selinux_inode_symlink(struct inode *dir, struct dentry *dentry, const char *name)
3098 return may_create(dir, dentry, SECCLASS_LNK_FILE);
3101 static int selinux_inode_mkdir(struct inode *dir, struct dentry *dentry, umode_t mask)
3103 return may_create(dir, dentry, SECCLASS_DIR);
3106 static int selinux_inode_rmdir(struct inode *dir, struct dentry *dentry)
3108 return may_link(dir, dentry, MAY_RMDIR);
3111 static int selinux_inode_mknod(struct inode *dir, struct dentry *dentry, umode_t mode, dev_t dev)
3113 return may_create(dir, dentry, inode_mode_to_security_class(mode));
3116 static int selinux_inode_rename(struct inode *old_inode, struct dentry *old_dentry,
3117 struct inode *new_inode, struct dentry *new_dentry)
3119 return may_rename(old_inode, old_dentry, new_inode, new_dentry);
3122 static int selinux_inode_readlink(struct dentry *dentry)
3124 const struct cred *cred = current_cred();
3126 return dentry_has_perm(cred, dentry, FILE__READ);
3129 static int selinux_inode_follow_link(struct dentry *dentry, struct inode *inode,
3132 const struct cred *cred = current_cred();
3133 struct common_audit_data ad;
3134 struct inode_security_struct *isec;
3137 validate_creds(cred);
3139 ad.type = LSM_AUDIT_DATA_DENTRY;
3140 ad.u.dentry = dentry;
3141 sid = cred_sid(cred);
3142 isec = inode_security_rcu(inode, rcu);
3144 return PTR_ERR(isec);
3146 return avc_has_perm(&selinux_state,
3147 sid, isec->sid, isec->sclass, FILE__READ, &ad);
3150 static noinline int audit_inode_permission(struct inode *inode,
3151 u32 perms, u32 audited, u32 denied,
3154 struct common_audit_data ad;
3155 struct inode_security_struct *isec = selinux_inode(inode);
3157 ad.type = LSM_AUDIT_DATA_INODE;
3160 return slow_avc_audit(&selinux_state,
3161 current_sid(), isec->sid, isec->sclass, perms,
3162 audited, denied, result, &ad);
3165 static int selinux_inode_permission(struct inode *inode, int mask)
3167 const struct cred *cred = current_cred();
3170 bool no_block = mask & MAY_NOT_BLOCK;
3171 struct inode_security_struct *isec;
3173 struct av_decision avd;
3175 u32 audited, denied;
3177 from_access = mask & MAY_ACCESS;
3178 mask &= (MAY_READ|MAY_WRITE|MAY_EXEC|MAY_APPEND);
3180 /* No permission to check. Existence test. */
3184 validate_creds(cred);
3186 if (unlikely(IS_PRIVATE(inode)))
3189 perms = file_mask_to_av(inode->i_mode, mask);
3191 sid = cred_sid(cred);
3192 isec = inode_security_rcu(inode, no_block);
3194 return PTR_ERR(isec);
3196 rc = avc_has_perm_noaudit(&selinux_state,
3197 sid, isec->sid, isec->sclass, perms, 0,
3199 audited = avc_audit_required(perms, &avd, rc,
3200 from_access ? FILE__AUDIT_ACCESS : 0,
3202 if (likely(!audited))
3205 rc2 = audit_inode_permission(inode, perms, audited, denied, rc);
3211 static int selinux_inode_setattr(struct dentry *dentry, struct iattr *iattr)
3213 const struct cred *cred = current_cred();
3214 struct inode *inode = d_backing_inode(dentry);
3215 unsigned int ia_valid = iattr->ia_valid;
3216 __u32 av = FILE__WRITE;
3218 /* ATTR_FORCE is just used for ATTR_KILL_S[UG]ID. */
3219 if (ia_valid & ATTR_FORCE) {
3220 ia_valid &= ~(ATTR_KILL_SUID | ATTR_KILL_SGID | ATTR_MODE |
3226 if (ia_valid & (ATTR_MODE | ATTR_UID | ATTR_GID |
3227 ATTR_ATIME_SET | ATTR_MTIME_SET | ATTR_TIMES_SET))
3228 return dentry_has_perm(cred, dentry, FILE__SETATTR);
3230 if (selinux_policycap_openperm() &&
3231 inode->i_sb->s_magic != SOCKFS_MAGIC &&
3232 (ia_valid & ATTR_SIZE) &&
3233 !(ia_valid & ATTR_FILE))
3236 return dentry_has_perm(cred, dentry, av);
3239 static int selinux_inode_getattr(const struct path *path)
3241 return path_has_perm(current_cred(), path, FILE__GETATTR);
3244 static bool has_cap_mac_admin(bool audit)
3246 const struct cred *cred = current_cred();
3247 unsigned int opts = audit ? CAP_OPT_NONE : CAP_OPT_NOAUDIT;
3249 if (cap_capable(cred, &init_user_ns, CAP_MAC_ADMIN, opts))
3251 if (cred_has_capability(cred, CAP_MAC_ADMIN, opts, true))
3256 static int selinux_inode_setxattr(struct user_namespace *mnt_userns,
3257 struct dentry *dentry, const char *name,
3258 const void *value, size_t size, int flags)
3260 struct inode *inode = d_backing_inode(dentry);
3261 struct inode_security_struct *isec;
3262 struct superblock_security_struct *sbsec;
3263 struct common_audit_data ad;
3264 u32 newsid, sid = current_sid();
3267 if (strcmp(name, XATTR_NAME_SELINUX)) {
3268 rc = cap_inode_setxattr(dentry, name, value, size, flags);
3272 /* Not an attribute we recognize, so just check the
3273 ordinary setattr permission. */
3274 return dentry_has_perm(current_cred(), dentry, FILE__SETATTR);
3277 if (!selinux_initialized(&selinux_state))
3278 return (inode_owner_or_capable(mnt_userns, inode) ? 0 : -EPERM);
3280 sbsec = selinux_superblock(inode->i_sb);
3281 if (!(sbsec->flags & SBLABEL_MNT))
3284 if (!inode_owner_or_capable(mnt_userns, inode))
3287 ad.type = LSM_AUDIT_DATA_DENTRY;
3288 ad.u.dentry = dentry;
3290 isec = backing_inode_security(dentry);
3291 rc = avc_has_perm(&selinux_state,
3292 sid, isec->sid, isec->sclass,
3293 FILE__RELABELFROM, &ad);
3297 rc = security_context_to_sid(&selinux_state, value, size, &newsid,
3299 if (rc == -EINVAL) {
3300 if (!has_cap_mac_admin(true)) {
3301 struct audit_buffer *ab;
3304 /* We strip a nul only if it is at the end, otherwise the
3305 * context contains a nul and we should audit that */
3307 const char *str = value;
3309 if (str[size - 1] == '\0')
3310 audit_size = size - 1;
3316 ab = audit_log_start(audit_context(),
3317 GFP_ATOMIC, AUDIT_SELINUX_ERR);
3320 audit_log_format(ab, "op=setxattr invalid_context=");
3321 audit_log_n_untrustedstring(ab, value, audit_size);
3326 rc = security_context_to_sid_force(&selinux_state, value,
3332 rc = avc_has_perm(&selinux_state,
3333 sid, newsid, isec->sclass,
3334 FILE__RELABELTO, &ad);
3338 rc = security_validate_transition(&selinux_state, isec->sid, newsid,
3343 return avc_has_perm(&selinux_state,
3346 SECCLASS_FILESYSTEM,
3347 FILESYSTEM__ASSOCIATE,
3351 static void selinux_inode_post_setxattr(struct dentry *dentry, const char *name,
3352 const void *value, size_t size,
3355 struct inode *inode = d_backing_inode(dentry);
3356 struct inode_security_struct *isec;
3360 if (strcmp(name, XATTR_NAME_SELINUX)) {
3361 /* Not an attribute we recognize, so nothing to do. */
3365 if (!selinux_initialized(&selinux_state)) {
3366 /* If we haven't even been initialized, then we can't validate
3367 * against a policy, so leave the label as invalid. It may
3368 * resolve to a valid label on the next revalidation try if
3369 * we've since initialized.
3374 rc = security_context_to_sid_force(&selinux_state, value, size,
3377 pr_err("SELinux: unable to map context to SID"
3378 "for (%s, %lu), rc=%d\n",
3379 inode->i_sb->s_id, inode->i_ino, -rc);
3383 isec = backing_inode_security(dentry);
3384 spin_lock(&isec->lock);
3385 isec->sclass = inode_mode_to_security_class(inode->i_mode);
3387 isec->initialized = LABEL_INITIALIZED;
3388 spin_unlock(&isec->lock);
3393 static int selinux_inode_getxattr(struct dentry *dentry, const char *name)
3395 const struct cred *cred = current_cred();
3397 return dentry_has_perm(cred, dentry, FILE__GETATTR);
3400 static int selinux_inode_listxattr(struct dentry *dentry)
3402 const struct cred *cred = current_cred();
3404 return dentry_has_perm(cred, dentry, FILE__GETATTR);
3407 static int selinux_inode_removexattr(struct user_namespace *mnt_userns,
3408 struct dentry *dentry, const char *name)
3410 if (strcmp(name, XATTR_NAME_SELINUX)) {
3411 int rc = cap_inode_removexattr(mnt_userns, dentry, name);
3415 /* Not an attribute we recognize, so just check the
3416 ordinary setattr permission. */
3417 return dentry_has_perm(current_cred(), dentry, FILE__SETATTR);
3420 if (!selinux_initialized(&selinux_state))
3423 /* No one is allowed to remove a SELinux security label.
3424 You can change the label, but all data must be labeled. */
3428 static int selinux_path_notify(const struct path *path, u64 mask,
3429 unsigned int obj_type)
3434 struct common_audit_data ad;
3436 ad.type = LSM_AUDIT_DATA_PATH;
3440 * Set permission needed based on the type of mark being set.
3441 * Performs an additional check for sb watches.
3444 case FSNOTIFY_OBJ_TYPE_VFSMOUNT:
3445 perm = FILE__WATCH_MOUNT;
3447 case FSNOTIFY_OBJ_TYPE_SB:
3448 perm = FILE__WATCH_SB;
3449 ret = superblock_has_perm(current_cred(), path->dentry->d_sb,
3450 FILESYSTEM__WATCH, &ad);
3454 case FSNOTIFY_OBJ_TYPE_INODE:
3461 /* blocking watches require the file:watch_with_perm permission */
3462 if (mask & (ALL_FSNOTIFY_PERM_EVENTS))
3463 perm |= FILE__WATCH_WITH_PERM;
3465 /* watches on read-like events need the file:watch_reads permission */
3466 if (mask & (FS_ACCESS | FS_ACCESS_PERM | FS_CLOSE_NOWRITE))
3467 perm |= FILE__WATCH_READS;
3469 return path_has_perm(current_cred(), path, perm);
3473 * Copy the inode security context value to the user.
3475 * Permission check is handled by selinux_inode_getxattr hook.
3477 static int selinux_inode_getsecurity(struct user_namespace *mnt_userns,
3478 struct inode *inode, const char *name,
3479 void **buffer, bool alloc)
3483 char *context = NULL;
3484 struct inode_security_struct *isec;
3487 * If we're not initialized yet, then we can't validate contexts, so
3488 * just let vfs_getxattr fall back to using the on-disk xattr.
3490 if (!selinux_initialized(&selinux_state) ||
3491 strcmp(name, XATTR_SELINUX_SUFFIX))
3495 * If the caller has CAP_MAC_ADMIN, then get the raw context
3496 * value even if it is not defined by current policy; otherwise,
3497 * use the in-core value under current policy.
3498 * Use the non-auditing forms of the permission checks since
3499 * getxattr may be called by unprivileged processes commonly
3500 * and lack of permission just means that we fall back to the
3501 * in-core context value, not a denial.
3503 isec = inode_security(inode);
3504 if (has_cap_mac_admin(false))
3505 error = security_sid_to_context_force(&selinux_state,
3506 isec->sid, &context,
3509 error = security_sid_to_context(&selinux_state, isec->sid,
3523 static int selinux_inode_setsecurity(struct inode *inode, const char *name,
3524 const void *value, size_t size, int flags)
3526 struct inode_security_struct *isec = inode_security_novalidate(inode);
3527 struct superblock_security_struct *sbsec;
3531 if (strcmp(name, XATTR_SELINUX_SUFFIX))
3534 sbsec = selinux_superblock(inode->i_sb);
3535 if (!(sbsec->flags & SBLABEL_MNT))
3538 if (!value || !size)
3541 rc = security_context_to_sid(&selinux_state, value, size, &newsid,
3546 spin_lock(&isec->lock);
3547 isec->sclass = inode_mode_to_security_class(inode->i_mode);
3549 isec->initialized = LABEL_INITIALIZED;
3550 spin_unlock(&isec->lock);
3554 static int selinux_inode_listsecurity(struct inode *inode, char *buffer, size_t buffer_size)
3556 const int len = sizeof(XATTR_NAME_SELINUX);
3558 if (!selinux_initialized(&selinux_state))
3561 if (buffer && len <= buffer_size)
3562 memcpy(buffer, XATTR_NAME_SELINUX, len);
3566 static void selinux_inode_getsecid(struct inode *inode, u32 *secid)
3568 struct inode_security_struct *isec = inode_security_novalidate(inode);
3572 static int selinux_inode_copy_up(struct dentry *src, struct cred **new)
3575 struct task_security_struct *tsec;
3576 struct cred *new_creds = *new;
3578 if (new_creds == NULL) {
3579 new_creds = prepare_creds();
3584 tsec = selinux_cred(new_creds);
3585 /* Get label from overlay inode and set it in create_sid */
3586 selinux_inode_getsecid(d_inode(src), &sid);
3587 tsec->create_sid = sid;
3592 static int selinux_inode_copy_up_xattr(const char *name)
3594 /* The copy_up hook above sets the initial context on an inode, but we
3595 * don't then want to overwrite it by blindly copying all the lower
3596 * xattrs up. Instead, we have to filter out SELinux-related xattrs.
3598 if (strcmp(name, XATTR_NAME_SELINUX) == 0)
3599 return 1; /* Discard */
3601 * Any other attribute apart from SELINUX is not claimed, supported
3607 /* kernfs node operations */
3609 static int selinux_kernfs_init_security(struct kernfs_node *kn_dir,
3610 struct kernfs_node *kn)
3612 const struct task_security_struct *tsec = selinux_cred(current_cred());
3613 u32 parent_sid, newsid, clen;
3617 rc = kernfs_xattr_get(kn_dir, XATTR_NAME_SELINUX, NULL, 0);
3624 context = kmalloc(clen, GFP_KERNEL);
3628 rc = kernfs_xattr_get(kn_dir, XATTR_NAME_SELINUX, context, clen);
3634 rc = security_context_to_sid(&selinux_state, context, clen, &parent_sid,
3640 if (tsec->create_sid) {
3641 newsid = tsec->create_sid;
3643 u16 secclass = inode_mode_to_security_class(kn->mode);
3647 q.hash_len = hashlen_string(kn_dir, kn->name);
3649 rc = security_transition_sid(&selinux_state, tsec->sid,
3650 parent_sid, secclass, &q,
3656 rc = security_sid_to_context_force(&selinux_state, newsid,
3661 rc = kernfs_xattr_set(kn, XATTR_NAME_SELINUX, context, clen,
3668 /* file security operations */
3670 static int selinux_revalidate_file_permission(struct file *file, int mask)
3672 const struct cred *cred = current_cred();
3673 struct inode *inode = file_inode(file);
3675 /* file_mask_to_av won't add FILE__WRITE if MAY_APPEND is set */
3676 if ((file->f_flags & O_APPEND) && (mask & MAY_WRITE))
3679 return file_has_perm(cred, file,
3680 file_mask_to_av(inode->i_mode, mask));
3683 static int selinux_file_permission(struct file *file, int mask)
3685 struct inode *inode = file_inode(file);
3686 struct file_security_struct *fsec = selinux_file(file);
3687 struct inode_security_struct *isec;
3688 u32 sid = current_sid();
3691 /* No permission to check. Existence test. */
3694 isec = inode_security(inode);
3695 if (sid == fsec->sid && fsec->isid == isec->sid &&
3696 fsec->pseqno == avc_policy_seqno(&selinux_state))
3697 /* No change since file_open check. */
3700 return selinux_revalidate_file_permission(file, mask);
3703 static int selinux_file_alloc_security(struct file *file)
3705 struct file_security_struct *fsec = selinux_file(file);
3706 u32 sid = current_sid();
3709 fsec->fown_sid = sid;
3715 * Check whether a task has the ioctl permission and cmd
3716 * operation to an inode.
3718 static int ioctl_has_perm(const struct cred *cred, struct file *file,
3719 u32 requested, u16 cmd)
3721 struct common_audit_data ad;
3722 struct file_security_struct *fsec = selinux_file(file);
3723 struct inode *inode = file_inode(file);
3724 struct inode_security_struct *isec;
3725 struct lsm_ioctlop_audit ioctl;
3726 u32 ssid = cred_sid(cred);
3728 u8 driver = cmd >> 8;
3729 u8 xperm = cmd & 0xff;
3731 ad.type = LSM_AUDIT_DATA_IOCTL_OP;
3734 ad.u.op->path = file->f_path;
3736 if (ssid != fsec->sid) {
3737 rc = avc_has_perm(&selinux_state,
3746 if (unlikely(IS_PRIVATE(inode)))
3749 isec = inode_security(inode);
3750 rc = avc_has_extended_perms(&selinux_state,
3751 ssid, isec->sid, isec->sclass,
3752 requested, driver, xperm, &ad);
3757 static int selinux_file_ioctl(struct file *file, unsigned int cmd,
3760 const struct cred *cred = current_cred();
3767 case FS_IOC_GETFLAGS:
3768 case FS_IOC_GETVERSION:
3769 error = file_has_perm(cred, file, FILE__GETATTR);
3772 case FS_IOC_SETFLAGS:
3773 case FS_IOC_SETVERSION:
3774 error = file_has_perm(cred, file, FILE__SETATTR);
3777 /* sys_ioctl() checks */
3780 error = file_has_perm(cred, file, 0);
3785 error = cred_has_capability(cred, CAP_SYS_TTY_CONFIG,
3786 CAP_OPT_NONE, true);
3789 /* default case assumes that the command will go
3790 * to the file's ioctl() function.
3793 error = ioctl_has_perm(cred, file, FILE__IOCTL, (u16) cmd);
3798 static int default_noexec __ro_after_init;
3800 static int file_map_prot_check(struct file *file, unsigned long prot, int shared)
3802 const struct cred *cred = current_cred();
3803 u32 sid = cred_sid(cred);
3806 if (default_noexec &&
3807 (prot & PROT_EXEC) && (!file || IS_PRIVATE(file_inode(file)) ||
3808 (!shared && (prot & PROT_WRITE)))) {
3810 * We are making executable an anonymous mapping or a
3811 * private file mapping that will also be writable.
3812 * This has an additional check.
3814 rc = avc_has_perm(&selinux_state,
3815 sid, sid, SECCLASS_PROCESS,
3816 PROCESS__EXECMEM, NULL);
3822 /* read access is always possible with a mapping */
3823 u32 av = FILE__READ;
3825 /* write access only matters if the mapping is shared */
3826 if (shared && (prot & PROT_WRITE))
3829 if (prot & PROT_EXEC)
3830 av |= FILE__EXECUTE;
3832 return file_has_perm(cred, file, av);
3839 static int selinux_mmap_addr(unsigned long addr)
3843 if (addr < CONFIG_LSM_MMAP_MIN_ADDR) {
3844 u32 sid = current_sid();
3845 rc = avc_has_perm(&selinux_state,
3846 sid, sid, SECCLASS_MEMPROTECT,
3847 MEMPROTECT__MMAP_ZERO, NULL);
3853 static int selinux_mmap_file(struct file *file, unsigned long reqprot,
3854 unsigned long prot, unsigned long flags)
3856 struct common_audit_data ad;
3860 ad.type = LSM_AUDIT_DATA_FILE;
3862 rc = inode_has_perm(current_cred(), file_inode(file),
3868 if (checkreqprot_get(&selinux_state))
3871 return file_map_prot_check(file, prot,
3872 (flags & MAP_TYPE) == MAP_SHARED);
3875 static int selinux_file_mprotect(struct vm_area_struct *vma,
3876 unsigned long reqprot,
3879 const struct cred *cred = current_cred();
3880 u32 sid = cred_sid(cred);
3882 if (checkreqprot_get(&selinux_state))
3885 if (default_noexec &&
3886 (prot & PROT_EXEC) && !(vma->vm_flags & VM_EXEC)) {
3888 if (vma->vm_start >= vma->vm_mm->start_brk &&
3889 vma->vm_end <= vma->vm_mm->brk) {
3890 rc = avc_has_perm(&selinux_state,
3891 sid, sid, SECCLASS_PROCESS,
3892 PROCESS__EXECHEAP, NULL);
3893 } else if (!vma->vm_file &&
3894 ((vma->vm_start <= vma->vm_mm->start_stack &&
3895 vma->vm_end >= vma->vm_mm->start_stack) ||
3896 vma_is_stack_for_current(vma))) {
3897 rc = avc_has_perm(&selinux_state,
3898 sid, sid, SECCLASS_PROCESS,
3899 PROCESS__EXECSTACK, NULL);
3900 } else if (vma->vm_file && vma->anon_vma) {
3902 * We are making executable a file mapping that has
3903 * had some COW done. Since pages might have been
3904 * written, check ability to execute the possibly
3905 * modified content. This typically should only
3906 * occur for text relocations.
3908 rc = file_has_perm(cred, vma->vm_file, FILE__EXECMOD);
3914 return file_map_prot_check(vma->vm_file, prot, vma->vm_flags&VM_SHARED);
3917 static int selinux_file_lock(struct file *file, unsigned int cmd)
3919 const struct cred *cred = current_cred();
3921 return file_has_perm(cred, file, FILE__LOCK);
3924 static int selinux_file_fcntl(struct file *file, unsigned int cmd,
3927 const struct cred *cred = current_cred();
3932 if ((file->f_flags & O_APPEND) && !(arg & O_APPEND)) {
3933 err = file_has_perm(cred, file, FILE__WRITE);
3942 case F_GETOWNER_UIDS:
3943 /* Just check FD__USE permission */
3944 err = file_has_perm(cred, file, 0);
3952 #if BITS_PER_LONG == 32
3957 err = file_has_perm(cred, file, FILE__LOCK);
3964 static void selinux_file_set_fowner(struct file *file)
3966 struct file_security_struct *fsec;
3968 fsec = selinux_file(file);
3969 fsec->fown_sid = current_sid();
3972 static int selinux_file_send_sigiotask(struct task_struct *tsk,
3973 struct fown_struct *fown, int signum)
3976 u32 sid = task_sid_obj(tsk);
3978 struct file_security_struct *fsec;
3980 /* struct fown_struct is never outside the context of a struct file */
3981 file = container_of(fown, struct file, f_owner);
3983 fsec = selinux_file(file);
3986 perm = signal_to_av(SIGIO); /* as per send_sigio_to_task */
3988 perm = signal_to_av(signum);
3990 return avc_has_perm(&selinux_state,
3991 fsec->fown_sid, sid,
3992 SECCLASS_PROCESS, perm, NULL);
3995 static int selinux_file_receive(struct file *file)
3997 const struct cred *cred = current_cred();
3999 return file_has_perm(cred, file, file_to_av(file));
4002 static int selinux_file_open(struct file *file)
4004 struct file_security_struct *fsec;
4005 struct inode_security_struct *isec;
4007 fsec = selinux_file(file);
4008 isec = inode_security(file_inode(file));
4010 * Save inode label and policy sequence number
4011 * at open-time so that selinux_file_permission
4012 * can determine whether revalidation is necessary.
4013 * Task label is already saved in the file security
4014 * struct as its SID.
4016 fsec->isid = isec->sid;
4017 fsec->pseqno = avc_policy_seqno(&selinux_state);
4019 * Since the inode label or policy seqno may have changed
4020 * between the selinux_inode_permission check and the saving
4021 * of state above, recheck that access is still permitted.
4022 * Otherwise, access might never be revalidated against the
4023 * new inode label or new policy.
4024 * This check is not redundant - do not remove.
4026 return file_path_has_perm(file->f_cred, file, open_file_to_av(file));
4029 /* task security operations */
4031 static int selinux_task_alloc(struct task_struct *task,
4032 unsigned long clone_flags)
4034 u32 sid = current_sid();
4036 return avc_has_perm(&selinux_state,
4037 sid, sid, SECCLASS_PROCESS, PROCESS__FORK, NULL);
4041 * prepare a new set of credentials for modification
4043 static int selinux_cred_prepare(struct cred *new, const struct cred *old,
4046 const struct task_security_struct *old_tsec = selinux_cred(old);
4047 struct task_security_struct *tsec = selinux_cred(new);
4054 * transfer the SELinux data to a blank set of creds
4056 static void selinux_cred_transfer(struct cred *new, const struct cred *old)
4058 const struct task_security_struct *old_tsec = selinux_cred(old);
4059 struct task_security_struct *tsec = selinux_cred(new);
4064 static void selinux_cred_getsecid(const struct cred *c, u32 *secid)
4066 *secid = cred_sid(c);
4070 * set the security data for a kernel service
4071 * - all the creation contexts are set to unlabelled
4073 static int selinux_kernel_act_as(struct cred *new, u32 secid)
4075 struct task_security_struct *tsec = selinux_cred(new);
4076 u32 sid = current_sid();
4079 ret = avc_has_perm(&selinux_state,
4081 SECCLASS_KERNEL_SERVICE,
4082 KERNEL_SERVICE__USE_AS_OVERRIDE,
4086 tsec->create_sid = 0;
4087 tsec->keycreate_sid = 0;
4088 tsec->sockcreate_sid = 0;
4094 * set the file creation context in a security record to the same as the
4095 * objective context of the specified inode
4097 static int selinux_kernel_create_files_as(struct cred *new, struct inode *inode)
4099 struct inode_security_struct *isec = inode_security(inode);
4100 struct task_security_struct *tsec = selinux_cred(new);
4101 u32 sid = current_sid();
4104 ret = avc_has_perm(&selinux_state,
4106 SECCLASS_KERNEL_SERVICE,
4107 KERNEL_SERVICE__CREATE_FILES_AS,
4111 tsec->create_sid = isec->sid;
4115 static int selinux_kernel_module_request(char *kmod_name)
4117 struct common_audit_data ad;
4119 ad.type = LSM_AUDIT_DATA_KMOD;
4120 ad.u.kmod_name = kmod_name;
4122 return avc_has_perm(&selinux_state,
4123 current_sid(), SECINITSID_KERNEL, SECCLASS_SYSTEM,
4124 SYSTEM__MODULE_REQUEST, &ad);
4127 static int selinux_kernel_module_from_file(struct file *file)
4129 struct common_audit_data ad;
4130 struct inode_security_struct *isec;
4131 struct file_security_struct *fsec;
4132 u32 sid = current_sid();
4137 return avc_has_perm(&selinux_state,
4138 sid, sid, SECCLASS_SYSTEM,
4139 SYSTEM__MODULE_LOAD, NULL);
4143 ad.type = LSM_AUDIT_DATA_FILE;
4146 fsec = selinux_file(file);
4147 if (sid != fsec->sid) {
4148 rc = avc_has_perm(&selinux_state,
4149 sid, fsec->sid, SECCLASS_FD, FD__USE, &ad);
4154 isec = inode_security(file_inode(file));
4155 return avc_has_perm(&selinux_state,
4156 sid, isec->sid, SECCLASS_SYSTEM,
4157 SYSTEM__MODULE_LOAD, &ad);
4160 static int selinux_kernel_read_file(struct file *file,
4161 enum kernel_read_file_id id,
4167 case READING_MODULE:
4168 rc = selinux_kernel_module_from_file(contents ? file : NULL);
4177 static int selinux_kernel_load_data(enum kernel_load_data_id id, bool contents)
4182 case LOADING_MODULE:
4183 rc = selinux_kernel_module_from_file(NULL);
4192 static int selinux_task_setpgid(struct task_struct *p, pid_t pgid)
4194 return avc_has_perm(&selinux_state,
4195 current_sid(), task_sid_obj(p), SECCLASS_PROCESS,
4196 PROCESS__SETPGID, NULL);
4199 static int selinux_task_getpgid(struct task_struct *p)
4201 return avc_has_perm(&selinux_state,
4202 current_sid(), task_sid_obj(p), SECCLASS_PROCESS,
4203 PROCESS__GETPGID, NULL);
4206 static int selinux_task_getsid(struct task_struct *p)
4208 return avc_has_perm(&selinux_state,
4209 current_sid(), task_sid_obj(p), SECCLASS_PROCESS,
4210 PROCESS__GETSESSION, NULL);
4213 static void selinux_task_getsecid_subj(struct task_struct *p, u32 *secid)
4215 *secid = task_sid_subj(p);
4218 static void selinux_task_getsecid_obj(struct task_struct *p, u32 *secid)
4220 *secid = task_sid_obj(p);
4223 static int selinux_task_setnice(struct task_struct *p, int nice)
4225 return avc_has_perm(&selinux_state,
4226 current_sid(), task_sid_obj(p), SECCLASS_PROCESS,
4227 PROCESS__SETSCHED, NULL);
4230 static int selinux_task_setioprio(struct task_struct *p, int ioprio)
4232 return avc_has_perm(&selinux_state,
4233 current_sid(), task_sid_obj(p), SECCLASS_PROCESS,
4234 PROCESS__SETSCHED, NULL);
4237 static int selinux_task_getioprio(struct task_struct *p)
4239 return avc_has_perm(&selinux_state,
4240 current_sid(), task_sid_obj(p), SECCLASS_PROCESS,
4241 PROCESS__GETSCHED, NULL);
4244 static int selinux_task_prlimit(const struct cred *cred, const struct cred *tcred,
4251 if (flags & LSM_PRLIMIT_WRITE)
4252 av |= PROCESS__SETRLIMIT;
4253 if (flags & LSM_PRLIMIT_READ)
4254 av |= PROCESS__GETRLIMIT;
4255 return avc_has_perm(&selinux_state,
4256 cred_sid(cred), cred_sid(tcred),
4257 SECCLASS_PROCESS, av, NULL);
4260 static int selinux_task_setrlimit(struct task_struct *p, unsigned int resource,
4261 struct rlimit *new_rlim)
4263 struct rlimit *old_rlim = p->signal->rlim + resource;
4265 /* Control the ability to change the hard limit (whether
4266 lowering or raising it), so that the hard limit can
4267 later be used as a safe reset point for the soft limit
4268 upon context transitions. See selinux_bprm_committing_creds. */
4269 if (old_rlim->rlim_max != new_rlim->rlim_max)
4270 return avc_has_perm(&selinux_state,
4271 current_sid(), task_sid_obj(p),
4272 SECCLASS_PROCESS, PROCESS__SETRLIMIT, NULL);
4277 static int selinux_task_setscheduler(struct task_struct *p)
4279 return avc_has_perm(&selinux_state,
4280 current_sid(), task_sid_obj(p), SECCLASS_PROCESS,
4281 PROCESS__SETSCHED, NULL);
4284 static int selinux_task_getscheduler(struct task_struct *p)
4286 return avc_has_perm(&selinux_state,
4287 current_sid(), task_sid_obj(p), SECCLASS_PROCESS,
4288 PROCESS__GETSCHED, NULL);
4291 static int selinux_task_movememory(struct task_struct *p)
4293 return avc_has_perm(&selinux_state,
4294 current_sid(), task_sid_obj(p), SECCLASS_PROCESS,
4295 PROCESS__SETSCHED, NULL);
4298 static int selinux_task_kill(struct task_struct *p, struct kernel_siginfo *info,
4299 int sig, const struct cred *cred)
4305 perm = PROCESS__SIGNULL; /* null signal; existence test */
4307 perm = signal_to_av(sig);
4309 secid = current_sid();
4311 secid = cred_sid(cred);
4312 return avc_has_perm(&selinux_state,
4313 secid, task_sid_obj(p), SECCLASS_PROCESS, perm, NULL);
4316 static void selinux_task_to_inode(struct task_struct *p,
4317 struct inode *inode)
4319 struct inode_security_struct *isec = selinux_inode(inode);
4320 u32 sid = task_sid_obj(p);
4322 spin_lock(&isec->lock);
4323 isec->sclass = inode_mode_to_security_class(inode->i_mode);
4325 isec->initialized = LABEL_INITIALIZED;
4326 spin_unlock(&isec->lock);
4329 /* Returns error only if unable to parse addresses */
4330 static int selinux_parse_skb_ipv4(struct sk_buff *skb,
4331 struct common_audit_data *ad, u8 *proto)
4333 int offset, ihlen, ret = -EINVAL;
4334 struct iphdr _iph, *ih;
4336 offset = skb_network_offset(skb);
4337 ih = skb_header_pointer(skb, offset, sizeof(_iph), &_iph);
4341 ihlen = ih->ihl * 4;
4342 if (ihlen < sizeof(_iph))
4345 ad->u.net->v4info.saddr = ih->saddr;
4346 ad->u.net->v4info.daddr = ih->daddr;
4350 *proto = ih->protocol;
4352 switch (ih->protocol) {
4354 struct tcphdr _tcph, *th;
4356 if (ntohs(ih->frag_off) & IP_OFFSET)
4360 th = skb_header_pointer(skb, offset, sizeof(_tcph), &_tcph);
4364 ad->u.net->sport = th->source;
4365 ad->u.net->dport = th->dest;
4370 struct udphdr _udph, *uh;
4372 if (ntohs(ih->frag_off) & IP_OFFSET)
4376 uh = skb_header_pointer(skb, offset, sizeof(_udph), &_udph);
4380 ad->u.net->sport = uh->source;
4381 ad->u.net->dport = uh->dest;
4385 case IPPROTO_DCCP: {
4386 struct dccp_hdr _dccph, *dh;
4388 if (ntohs(ih->frag_off) & IP_OFFSET)
4392 dh = skb_header_pointer(skb, offset, sizeof(_dccph), &_dccph);
4396 ad->u.net->sport = dh->dccph_sport;
4397 ad->u.net->dport = dh->dccph_dport;
4401 #if IS_ENABLED(CONFIG_IP_SCTP)
4402 case IPPROTO_SCTP: {
4403 struct sctphdr _sctph, *sh;
4405 if (ntohs(ih->frag_off) & IP_OFFSET)
4409 sh = skb_header_pointer(skb, offset, sizeof(_sctph), &_sctph);
4413 ad->u.net->sport = sh->source;
4414 ad->u.net->dport = sh->dest;
4425 #if IS_ENABLED(CONFIG_IPV6)
4427 /* Returns error only if unable to parse addresses */
4428 static int selinux_parse_skb_ipv6(struct sk_buff *skb,
4429 struct common_audit_data *ad, u8 *proto)
4432 int ret = -EINVAL, offset;
4433 struct ipv6hdr _ipv6h, *ip6;
4436 offset = skb_network_offset(skb);
4437 ip6 = skb_header_pointer(skb, offset, sizeof(_ipv6h), &_ipv6h);
4441 ad->u.net->v6info.saddr = ip6->saddr;
4442 ad->u.net->v6info.daddr = ip6->daddr;
4445 nexthdr = ip6->nexthdr;
4446 offset += sizeof(_ipv6h);
4447 offset = ipv6_skip_exthdr(skb, offset, &nexthdr, &frag_off);
4456 struct tcphdr _tcph, *th;
4458 th = skb_header_pointer(skb, offset, sizeof(_tcph), &_tcph);
4462 ad->u.net->sport = th->source;
4463 ad->u.net->dport = th->dest;
4468 struct udphdr _udph, *uh;
4470 uh = skb_header_pointer(skb, offset, sizeof(_udph), &_udph);
4474 ad->u.net->sport = uh->source;
4475 ad->u.net->dport = uh->dest;
4479 case IPPROTO_DCCP: {
4480 struct dccp_hdr _dccph, *dh;
4482 dh = skb_header_pointer(skb, offset, sizeof(_dccph), &_dccph);
4486 ad->u.net->sport = dh->dccph_sport;
4487 ad->u.net->dport = dh->dccph_dport;
4491 #if IS_ENABLED(CONFIG_IP_SCTP)
4492 case IPPROTO_SCTP: {
4493 struct sctphdr _sctph, *sh;
4495 sh = skb_header_pointer(skb, offset, sizeof(_sctph), &_sctph);
4499 ad->u.net->sport = sh->source;
4500 ad->u.net->dport = sh->dest;
4504 /* includes fragments */
4514 static int selinux_parse_skb(struct sk_buff *skb, struct common_audit_data *ad,
4515 char **_addrp, int src, u8 *proto)
4520 switch (ad->u.net->family) {
4522 ret = selinux_parse_skb_ipv4(skb, ad, proto);
4525 addrp = (char *)(src ? &ad->u.net->v4info.saddr :
4526 &ad->u.net->v4info.daddr);
4529 #if IS_ENABLED(CONFIG_IPV6)
4531 ret = selinux_parse_skb_ipv6(skb, ad, proto);
4534 addrp = (char *)(src ? &ad->u.net->v6info.saddr :
4535 &ad->u.net->v6info.daddr);
4545 "SELinux: failure in selinux_parse_skb(),"
4546 " unable to parse packet\n");
4556 * selinux_skb_peerlbl_sid - Determine the peer label of a packet
4558 * @family: protocol family
4559 * @sid: the packet's peer label SID
4562 * Check the various different forms of network peer labeling and determine
4563 * the peer label/SID for the packet; most of the magic actually occurs in
4564 * the security server function security_net_peersid_cmp(). The function
4565 * returns zero if the value in @sid is valid (although it may be SECSID_NULL)
4566 * or -EACCES if @sid is invalid due to inconsistencies with the different
4570 static int selinux_skb_peerlbl_sid(struct sk_buff *skb, u16 family, u32 *sid)
4577 err = selinux_xfrm_skb_sid(skb, &xfrm_sid);
4580 err = selinux_netlbl_skbuff_getsid(skb, family, &nlbl_type, &nlbl_sid);
4584 err = security_net_peersid_resolve(&selinux_state, nlbl_sid,
4585 nlbl_type, xfrm_sid, sid);
4586 if (unlikely(err)) {
4588 "SELinux: failure in selinux_skb_peerlbl_sid(),"
4589 " unable to determine packet's peer label\n");
4597 * selinux_conn_sid - Determine the child socket label for a connection
4598 * @sk_sid: the parent socket's SID
4599 * @skb_sid: the packet's SID
4600 * @conn_sid: the resulting connection SID
4602 * If @skb_sid is valid then the user:role:type information from @sk_sid is
4603 * combined with the MLS information from @skb_sid in order to create
4604 * @conn_sid. If @skb_sid is not valid then @conn_sid is simply a copy
4605 * of @sk_sid. Returns zero on success, negative values on failure.
4608 static int selinux_conn_sid(u32 sk_sid, u32 skb_sid, u32 *conn_sid)
4612 if (skb_sid != SECSID_NULL)
4613 err = security_sid_mls_copy(&selinux_state, sk_sid, skb_sid,
4621 /* socket security operations */
4623 static int socket_sockcreate_sid(const struct task_security_struct *tsec,
4624 u16 secclass, u32 *socksid)
4626 if (tsec->sockcreate_sid > SECSID_NULL) {
4627 *socksid = tsec->sockcreate_sid;
4631 return security_transition_sid(&selinux_state, tsec->sid, tsec->sid,
4632 secclass, NULL, socksid);
4635 static int sock_has_perm(struct sock *sk, u32 perms)
4637 struct sk_security_struct *sksec = sk->sk_security;
4638 struct common_audit_data ad;
4639 struct lsm_network_audit net = {0,};
4641 if (sksec->sid == SECINITSID_KERNEL)
4644 ad.type = LSM_AUDIT_DATA_NET;
4648 return avc_has_perm(&selinux_state,
4649 current_sid(), sksec->sid, sksec->sclass, perms,
4653 static int selinux_socket_create(int family, int type,
4654 int protocol, int kern)
4656 const struct task_security_struct *tsec = selinux_cred(current_cred());
4664 secclass = socket_type_to_security_class(family, type, protocol);
4665 rc = socket_sockcreate_sid(tsec, secclass, &newsid);
4669 return avc_has_perm(&selinux_state,
4670 tsec->sid, newsid, secclass, SOCKET__CREATE, NULL);
4673 static int selinux_socket_post_create(struct socket *sock, int family,
4674 int type, int protocol, int kern)
4676 const struct task_security_struct *tsec = selinux_cred(current_cred());
4677 struct inode_security_struct *isec = inode_security_novalidate(SOCK_INODE(sock));
4678 struct sk_security_struct *sksec;
4679 u16 sclass = socket_type_to_security_class(family, type, protocol);
4680 u32 sid = SECINITSID_KERNEL;
4684 err = socket_sockcreate_sid(tsec, sclass, &sid);
4689 isec->sclass = sclass;
4691 isec->initialized = LABEL_INITIALIZED;
4694 sksec = sock->sk->sk_security;
4695 sksec->sclass = sclass;
4697 /* Allows detection of the first association on this socket */
4698 if (sksec->sclass == SECCLASS_SCTP_SOCKET)
4699 sksec->sctp_assoc_state = SCTP_ASSOC_UNSET;
4701 err = selinux_netlbl_socket_post_create(sock->sk, family);
4707 static int selinux_socket_socketpair(struct socket *socka,
4708 struct socket *sockb)
4710 struct sk_security_struct *sksec_a = socka->sk->sk_security;
4711 struct sk_security_struct *sksec_b = sockb->sk->sk_security;
4713 sksec_a->peer_sid = sksec_b->sid;
4714 sksec_b->peer_sid = sksec_a->sid;
4719 /* Range of port numbers used to automatically bind.
4720 Need to determine whether we should perform a name_bind
4721 permission check between the socket and the port number. */
4723 static int selinux_socket_bind(struct socket *sock, struct sockaddr *address, int addrlen)
4725 struct sock *sk = sock->sk;
4726 struct sk_security_struct *sksec = sk->sk_security;
4730 err = sock_has_perm(sk, SOCKET__BIND);
4734 /* If PF_INET or PF_INET6, check name_bind permission for the port. */
4735 family = sk->sk_family;
4736 if (family == PF_INET || family == PF_INET6) {
4738 struct common_audit_data ad;
4739 struct lsm_network_audit net = {0,};
4740 struct sockaddr_in *addr4 = NULL;
4741 struct sockaddr_in6 *addr6 = NULL;
4743 unsigned short snum;
4747 * sctp_bindx(3) calls via selinux_sctp_bind_connect()
4748 * that validates multiple binding addresses. Because of this
4749 * need to check address->sa_family as it is possible to have
4750 * sk->sk_family = PF_INET6 with addr->sa_family = AF_INET.
4752 if (addrlen < offsetofend(struct sockaddr, sa_family))
4754 family_sa = address->sa_family;
4755 switch (family_sa) {
4758 if (addrlen < sizeof(struct sockaddr_in))
4760 addr4 = (struct sockaddr_in *)address;
4761 if (family_sa == AF_UNSPEC) {
4762 /* see __inet_bind(), we only want to allow
4763 * AF_UNSPEC if the address is INADDR_ANY
4765 if (addr4->sin_addr.s_addr != htonl(INADDR_ANY))
4767 family_sa = AF_INET;
4769 snum = ntohs(addr4->sin_port);
4770 addrp = (char *)&addr4->sin_addr.s_addr;
4773 if (addrlen < SIN6_LEN_RFC2133)
4775 addr6 = (struct sockaddr_in6 *)address;
4776 snum = ntohs(addr6->sin6_port);
4777 addrp = (char *)&addr6->sin6_addr.s6_addr;
4783 ad.type = LSM_AUDIT_DATA_NET;
4785 ad.u.net->sport = htons(snum);
4786 ad.u.net->family = family_sa;
4791 inet_get_local_port_range(sock_net(sk), &low, &high);
4793 if (inet_port_requires_bind_service(sock_net(sk), snum) ||
4794 snum < low || snum > high) {
4795 err = sel_netport_sid(sk->sk_protocol,
4799 err = avc_has_perm(&selinux_state,
4802 SOCKET__NAME_BIND, &ad);
4808 switch (sksec->sclass) {
4809 case SECCLASS_TCP_SOCKET:
4810 node_perm = TCP_SOCKET__NODE_BIND;
4813 case SECCLASS_UDP_SOCKET:
4814 node_perm = UDP_SOCKET__NODE_BIND;
4817 case SECCLASS_DCCP_SOCKET:
4818 node_perm = DCCP_SOCKET__NODE_BIND;
4821 case SECCLASS_SCTP_SOCKET:
4822 node_perm = SCTP_SOCKET__NODE_BIND;
4826 node_perm = RAWIP_SOCKET__NODE_BIND;
4830 err = sel_netnode_sid(addrp, family_sa, &sid);
4834 if (family_sa == AF_INET)
4835 ad.u.net->v4info.saddr = addr4->sin_addr.s_addr;
4837 ad.u.net->v6info.saddr = addr6->sin6_addr;
4839 err = avc_has_perm(&selinux_state,
4841 sksec->sclass, node_perm, &ad);
4848 /* Note that SCTP services expect -EINVAL, others -EAFNOSUPPORT. */
4849 if (sksec->sclass == SECCLASS_SCTP_SOCKET)
4851 return -EAFNOSUPPORT;
4854 /* This supports connect(2) and SCTP connect services such as sctp_connectx(3)
4855 * and sctp_sendmsg(3) as described in Documentation/security/SCTP.rst
4857 static int selinux_socket_connect_helper(struct socket *sock,
4858 struct sockaddr *address, int addrlen)
4860 struct sock *sk = sock->sk;
4861 struct sk_security_struct *sksec = sk->sk_security;
4864 err = sock_has_perm(sk, SOCKET__CONNECT);
4867 if (addrlen < offsetofend(struct sockaddr, sa_family))
4870 /* connect(AF_UNSPEC) has special handling, as it is a documented
4871 * way to disconnect the socket
4873 if (address->sa_family == AF_UNSPEC)
4877 * If a TCP, DCCP or SCTP socket, check name_connect permission
4880 if (sksec->sclass == SECCLASS_TCP_SOCKET ||
4881 sksec->sclass == SECCLASS_DCCP_SOCKET ||
4882 sksec->sclass == SECCLASS_SCTP_SOCKET) {
4883 struct common_audit_data ad;
4884 struct lsm_network_audit net = {0,};
4885 struct sockaddr_in *addr4 = NULL;
4886 struct sockaddr_in6 *addr6 = NULL;
4887 unsigned short snum;
4890 /* sctp_connectx(3) calls via selinux_sctp_bind_connect()
4891 * that validates multiple connect addresses. Because of this
4892 * need to check address->sa_family as it is possible to have
4893 * sk->sk_family = PF_INET6 with addr->sa_family = AF_INET.
4895 switch (address->sa_family) {
4897 addr4 = (struct sockaddr_in *)address;
4898 if (addrlen < sizeof(struct sockaddr_in))
4900 snum = ntohs(addr4->sin_port);
4903 addr6 = (struct sockaddr_in6 *)address;
4904 if (addrlen < SIN6_LEN_RFC2133)
4906 snum = ntohs(addr6->sin6_port);
4909 /* Note that SCTP services expect -EINVAL, whereas
4910 * others expect -EAFNOSUPPORT.
4912 if (sksec->sclass == SECCLASS_SCTP_SOCKET)
4915 return -EAFNOSUPPORT;
4918 err = sel_netport_sid(sk->sk_protocol, snum, &sid);
4922 switch (sksec->sclass) {
4923 case SECCLASS_TCP_SOCKET:
4924 perm = TCP_SOCKET__NAME_CONNECT;
4926 case SECCLASS_DCCP_SOCKET:
4927 perm = DCCP_SOCKET__NAME_CONNECT;
4929 case SECCLASS_SCTP_SOCKET:
4930 perm = SCTP_SOCKET__NAME_CONNECT;
4934 ad.type = LSM_AUDIT_DATA_NET;
4936 ad.u.net->dport = htons(snum);
4937 ad.u.net->family = address->sa_family;
4938 err = avc_has_perm(&selinux_state,
4939 sksec->sid, sid, sksec->sclass, perm, &ad);
4947 /* Supports connect(2), see comments in selinux_socket_connect_helper() */
4948 static int selinux_socket_connect(struct socket *sock,
4949 struct sockaddr *address, int addrlen)
4952 struct sock *sk = sock->sk;
4954 err = selinux_socket_connect_helper(sock, address, addrlen);
4958 return selinux_netlbl_socket_connect(sk, address);
4961 static int selinux_socket_listen(struct socket *sock, int backlog)
4963 return sock_has_perm(sock->sk, SOCKET__LISTEN);
4966 static int selinux_socket_accept(struct socket *sock, struct socket *newsock)
4969 struct inode_security_struct *isec;
4970 struct inode_security_struct *newisec;
4974 err = sock_has_perm(sock->sk, SOCKET__ACCEPT);
4978 isec = inode_security_novalidate(SOCK_INODE(sock));
4979 spin_lock(&isec->lock);
4980 sclass = isec->sclass;
4982 spin_unlock(&isec->lock);
4984 newisec = inode_security_novalidate(SOCK_INODE(newsock));
4985 newisec->sclass = sclass;
4987 newisec->initialized = LABEL_INITIALIZED;
4992 static int selinux_socket_sendmsg(struct socket *sock, struct msghdr *msg,
4995 return sock_has_perm(sock->sk, SOCKET__WRITE);
4998 static int selinux_socket_recvmsg(struct socket *sock, struct msghdr *msg,
4999 int size, int flags)
5001 return sock_has_perm(sock->sk, SOCKET__READ);
5004 static int selinux_socket_getsockname(struct socket *sock)
5006 return sock_has_perm(sock->sk, SOCKET__GETATTR);
5009 static int selinux_socket_getpeername(struct socket *sock)
5011 return sock_has_perm(sock->sk, SOCKET__GETATTR);
5014 static int selinux_socket_setsockopt(struct socket *sock, int level, int optname)
5018 err = sock_has_perm(sock->sk, SOCKET__SETOPT);
5022 return selinux_netlbl_socket_setsockopt(sock, level, optname);
5025 static int selinux_socket_getsockopt(struct socket *sock, int level,
5028 return sock_has_perm(sock->sk, SOCKET__GETOPT);
5031 static int selinux_socket_shutdown(struct socket *sock, int how)
5033 return sock_has_perm(sock->sk, SOCKET__SHUTDOWN);
5036 static int selinux_socket_unix_stream_connect(struct sock *sock,
5040 struct sk_security_struct *sksec_sock = sock->sk_security;
5041 struct sk_security_struct *sksec_other = other->sk_security;
5042 struct sk_security_struct *sksec_new = newsk->sk_security;
5043 struct common_audit_data ad;
5044 struct lsm_network_audit net = {0,};
5047 ad.type = LSM_AUDIT_DATA_NET;
5049 ad.u.net->sk = other;
5051 err = avc_has_perm(&selinux_state,
5052 sksec_sock->sid, sksec_other->sid,
5053 sksec_other->sclass,
5054 UNIX_STREAM_SOCKET__CONNECTTO, &ad);
5058 /* server child socket */
5059 sksec_new->peer_sid = sksec_sock->sid;
5060 err = security_sid_mls_copy(&selinux_state, sksec_other->sid,
5061 sksec_sock->sid, &sksec_new->sid);
5065 /* connecting socket */
5066 sksec_sock->peer_sid = sksec_new->sid;
5071 static int selinux_socket_unix_may_send(struct socket *sock,
5072 struct socket *other)
5074 struct sk_security_struct *ssec = sock->sk->sk_security;
5075 struct sk_security_struct *osec = other->sk->sk_security;
5076 struct common_audit_data ad;
5077 struct lsm_network_audit net = {0,};
5079 ad.type = LSM_AUDIT_DATA_NET;
5081 ad.u.net->sk = other->sk;
5083 return avc_has_perm(&selinux_state,
5084 ssec->sid, osec->sid, osec->sclass, SOCKET__SENDTO,
5088 static int selinux_inet_sys_rcv_skb(struct net *ns, int ifindex,
5089 char *addrp, u16 family, u32 peer_sid,
5090 struct common_audit_data *ad)
5096 err = sel_netif_sid(ns, ifindex, &if_sid);
5099 err = avc_has_perm(&selinux_state,
5101 SECCLASS_NETIF, NETIF__INGRESS, ad);
5105 err = sel_netnode_sid(addrp, family, &node_sid);
5108 return avc_has_perm(&selinux_state,
5110 SECCLASS_NODE, NODE__RECVFROM, ad);
5113 static int selinux_sock_rcv_skb_compat(struct sock *sk, struct sk_buff *skb,
5117 struct sk_security_struct *sksec = sk->sk_security;
5118 u32 sk_sid = sksec->sid;
5119 struct common_audit_data ad;
5120 struct lsm_network_audit net = {0,};
5123 ad.type = LSM_AUDIT_DATA_NET;
5125 ad.u.net->netif = skb->skb_iif;
5126 ad.u.net->family = family;
5127 err = selinux_parse_skb(skb, &ad, &addrp, 1, NULL);
5131 if (selinux_secmark_enabled()) {
5132 err = avc_has_perm(&selinux_state,
5133 sk_sid, skb->secmark, SECCLASS_PACKET,
5139 err = selinux_netlbl_sock_rcv_skb(sksec, skb, family, &ad);
5142 err = selinux_xfrm_sock_rcv_skb(sksec->sid, skb, &ad);
5147 static int selinux_socket_sock_rcv_skb(struct sock *sk, struct sk_buff *skb)
5150 struct sk_security_struct *sksec = sk->sk_security;
5151 u16 family = sk->sk_family;
5152 u32 sk_sid = sksec->sid;
5153 struct common_audit_data ad;
5154 struct lsm_network_audit net = {0,};
5159 if (family != PF_INET && family != PF_INET6)
5162 /* Handle mapped IPv4 packets arriving via IPv6 sockets */
5163 if (family == PF_INET6 && skb->protocol == htons(ETH_P_IP))
5166 /* If any sort of compatibility mode is enabled then handoff processing
5167 * to the selinux_sock_rcv_skb_compat() function to deal with the
5168 * special handling. We do this in an attempt to keep this function
5169 * as fast and as clean as possible. */
5170 if (!selinux_policycap_netpeer())
5171 return selinux_sock_rcv_skb_compat(sk, skb, family);
5173 secmark_active = selinux_secmark_enabled();
5174 peerlbl_active = selinux_peerlbl_enabled();
5175 if (!secmark_active && !peerlbl_active)
5178 ad.type = LSM_AUDIT_DATA_NET;
5180 ad.u.net->netif = skb->skb_iif;
5181 ad.u.net->family = family;
5182 err = selinux_parse_skb(skb, &ad, &addrp, 1, NULL);
5186 if (peerlbl_active) {
5189 err = selinux_skb_peerlbl_sid(skb, family, &peer_sid);
5192 err = selinux_inet_sys_rcv_skb(sock_net(sk), skb->skb_iif,
5193 addrp, family, peer_sid, &ad);
5195 selinux_netlbl_err(skb, family, err, 0);
5198 err = avc_has_perm(&selinux_state,
5199 sk_sid, peer_sid, SECCLASS_PEER,
5202 selinux_netlbl_err(skb, family, err, 0);
5207 if (secmark_active) {
5208 err = avc_has_perm(&selinux_state,
5209 sk_sid, skb->secmark, SECCLASS_PACKET,
5218 static int selinux_socket_getpeersec_stream(struct socket *sock, char __user *optval,
5219 int __user *optlen, unsigned len)
5224 struct sk_security_struct *sksec = sock->sk->sk_security;
5225 u32 peer_sid = SECSID_NULL;
5227 if (sksec->sclass == SECCLASS_UNIX_STREAM_SOCKET ||
5228 sksec->sclass == SECCLASS_TCP_SOCKET ||
5229 sksec->sclass == SECCLASS_SCTP_SOCKET)
5230 peer_sid = sksec->peer_sid;
5231 if (peer_sid == SECSID_NULL)
5232 return -ENOPROTOOPT;
5234 err = security_sid_to_context(&selinux_state, peer_sid, &scontext,
5239 if (scontext_len > len) {
5244 if (copy_to_user(optval, scontext, scontext_len))
5248 if (put_user(scontext_len, optlen))
5254 static int selinux_socket_getpeersec_dgram(struct socket *sock, struct sk_buff *skb, u32 *secid)
5256 u32 peer_secid = SECSID_NULL;
5258 struct inode_security_struct *isec;
5260 if (skb && skb->protocol == htons(ETH_P_IP))
5262 else if (skb && skb->protocol == htons(ETH_P_IPV6))
5265 family = sock->sk->sk_family;
5269 if (sock && family == PF_UNIX) {
5270 isec = inode_security_novalidate(SOCK_INODE(sock));
5271 peer_secid = isec->sid;
5273 selinux_skb_peerlbl_sid(skb, family, &peer_secid);
5276 *secid = peer_secid;
5277 if (peer_secid == SECSID_NULL)
5282 static int selinux_sk_alloc_security(struct sock *sk, int family, gfp_t priority)
5284 struct sk_security_struct *sksec;
5286 sksec = kzalloc(sizeof(*sksec), priority);
5290 sksec->peer_sid = SECINITSID_UNLABELED;
5291 sksec->sid = SECINITSID_UNLABELED;
5292 sksec->sclass = SECCLASS_SOCKET;
5293 selinux_netlbl_sk_security_reset(sksec);
5294 sk->sk_security = sksec;
5299 static void selinux_sk_free_security(struct sock *sk)
5301 struct sk_security_struct *sksec = sk->sk_security;
5303 sk->sk_security = NULL;
5304 selinux_netlbl_sk_security_free(sksec);
5308 static void selinux_sk_clone_security(const struct sock *sk, struct sock *newsk)
5310 struct sk_security_struct *sksec = sk->sk_security;
5311 struct sk_security_struct *newsksec = newsk->sk_security;
5313 newsksec->sid = sksec->sid;
5314 newsksec->peer_sid = sksec->peer_sid;
5315 newsksec->sclass = sksec->sclass;
5317 selinux_netlbl_sk_security_reset(newsksec);
5320 static void selinux_sk_getsecid(struct sock *sk, u32 *secid)
5323 *secid = SECINITSID_ANY_SOCKET;
5325 struct sk_security_struct *sksec = sk->sk_security;
5327 *secid = sksec->sid;
5331 static void selinux_sock_graft(struct sock *sk, struct socket *parent)
5333 struct inode_security_struct *isec =
5334 inode_security_novalidate(SOCK_INODE(parent));
5335 struct sk_security_struct *sksec = sk->sk_security;
5337 if (sk->sk_family == PF_INET || sk->sk_family == PF_INET6 ||
5338 sk->sk_family == PF_UNIX)
5339 isec->sid = sksec->sid;
5340 sksec->sclass = isec->sclass;
5343 /* Called whenever SCTP receives an INIT chunk. This happens when an incoming
5344 * connect(2), sctp_connectx(3) or sctp_sendmsg(3) (with no association
5347 static int selinux_sctp_assoc_request(struct sctp_association *asoc,
5348 struct sk_buff *skb)
5350 struct sk_security_struct *sksec = asoc->base.sk->sk_security;
5351 struct common_audit_data ad;
5352 struct lsm_network_audit net = {0,};
5354 u32 peer_sid = SECINITSID_UNLABELED;
5358 if (!selinux_policycap_extsockclass())
5361 peerlbl_active = selinux_peerlbl_enabled();
5363 if (peerlbl_active) {
5364 /* This will return peer_sid = SECSID_NULL if there are
5365 * no peer labels, see security_net_peersid_resolve().
5367 err = selinux_skb_peerlbl_sid(skb, asoc->base.sk->sk_family,
5372 if (peer_sid == SECSID_NULL)
5373 peer_sid = SECINITSID_UNLABELED;
5376 if (sksec->sctp_assoc_state == SCTP_ASSOC_UNSET) {
5377 sksec->sctp_assoc_state = SCTP_ASSOC_SET;
5379 /* Here as first association on socket. As the peer SID
5380 * was allowed by peer recv (and the netif/node checks),
5381 * then it is approved by policy and used as the primary
5382 * peer SID for getpeercon(3).
5384 sksec->peer_sid = peer_sid;
5385 } else if (sksec->peer_sid != peer_sid) {
5386 /* Other association peer SIDs are checked to enforce
5387 * consistency among the peer SIDs.
5389 ad.type = LSM_AUDIT_DATA_NET;
5391 ad.u.net->sk = asoc->base.sk;
5392 err = avc_has_perm(&selinux_state,
5393 sksec->peer_sid, peer_sid, sksec->sclass,
5394 SCTP_SOCKET__ASSOCIATION, &ad);
5399 /* Compute the MLS component for the connection and store
5400 * the information in asoc. This will be used by SCTP TCP type
5401 * sockets and peeled off connections as they cause a new
5402 * socket to be generated. selinux_sctp_sk_clone() will then
5403 * plug this into the new socket.
5405 err = selinux_conn_sid(sksec->sid, peer_sid, &conn_sid);
5409 asoc->secid = conn_sid;
5410 asoc->peer_secid = peer_sid;
5412 /* Set any NetLabel labels including CIPSO/CALIPSO options. */
5413 return selinux_netlbl_sctp_assoc_request(asoc, skb);
5416 /* Check if sctp IPv4/IPv6 addresses are valid for binding or connecting
5417 * based on their @optname.
5419 static int selinux_sctp_bind_connect(struct sock *sk, int optname,
5420 struct sockaddr *address,
5423 int len, err = 0, walk_size = 0;
5425 struct sockaddr *addr;
5426 struct socket *sock;
5428 if (!selinux_policycap_extsockclass())
5431 /* Process one or more addresses that may be IPv4 or IPv6 */
5432 sock = sk->sk_socket;
5435 while (walk_size < addrlen) {
5436 if (walk_size + sizeof(sa_family_t) > addrlen)
5440 switch (addr->sa_family) {
5443 len = sizeof(struct sockaddr_in);
5446 len = sizeof(struct sockaddr_in6);
5452 if (walk_size + len > addrlen)
5458 case SCTP_PRIMARY_ADDR:
5459 case SCTP_SET_PEER_PRIMARY_ADDR:
5460 case SCTP_SOCKOPT_BINDX_ADD:
5461 err = selinux_socket_bind(sock, addr, len);
5463 /* Connect checks */
5464 case SCTP_SOCKOPT_CONNECTX:
5465 case SCTP_PARAM_SET_PRIMARY:
5466 case SCTP_PARAM_ADD_IP:
5467 case SCTP_SENDMSG_CONNECT:
5468 err = selinux_socket_connect_helper(sock, addr, len);
5472 /* As selinux_sctp_bind_connect() is called by the
5473 * SCTP protocol layer, the socket is already locked,
5474 * therefore selinux_netlbl_socket_connect_locked()
5475 * is called here. The situations handled are:
5476 * sctp_connectx(3), sctp_sendmsg(3), sendmsg(2),
5477 * whenever a new IP address is added or when a new
5478 * primary address is selected.
5479 * Note that an SCTP connect(2) call happens before
5480 * the SCTP protocol layer and is handled via
5481 * selinux_socket_connect().
5483 err = selinux_netlbl_socket_connect_locked(sk, addr);
5497 /* Called whenever a new socket is created by accept(2) or sctp_peeloff(3). */
5498 static void selinux_sctp_sk_clone(struct sctp_association *asoc, struct sock *sk,
5501 struct sk_security_struct *sksec = sk->sk_security;
5502 struct sk_security_struct *newsksec = newsk->sk_security;
5504 /* If policy does not support SECCLASS_SCTP_SOCKET then call
5505 * the non-sctp clone version.
5507 if (!selinux_policycap_extsockclass())
5508 return selinux_sk_clone_security(sk, newsk);
5510 newsksec->sid = asoc->secid;
5511 newsksec->peer_sid = asoc->peer_secid;
5512 newsksec->sclass = sksec->sclass;
5513 selinux_netlbl_sctp_sk_clone(sk, newsk);
5516 static int selinux_inet_conn_request(const struct sock *sk, struct sk_buff *skb,
5517 struct request_sock *req)
5519 struct sk_security_struct *sksec = sk->sk_security;
5521 u16 family = req->rsk_ops->family;
5525 err = selinux_skb_peerlbl_sid(skb, family, &peersid);
5528 err = selinux_conn_sid(sksec->sid, peersid, &connsid);
5531 req->secid = connsid;
5532 req->peer_secid = peersid;
5534 return selinux_netlbl_inet_conn_request(req, family);
5537 static void selinux_inet_csk_clone(struct sock *newsk,
5538 const struct request_sock *req)
5540 struct sk_security_struct *newsksec = newsk->sk_security;
5542 newsksec->sid = req->secid;
5543 newsksec->peer_sid = req->peer_secid;
5544 /* NOTE: Ideally, we should also get the isec->sid for the
5545 new socket in sync, but we don't have the isec available yet.
5546 So we will wait until sock_graft to do it, by which
5547 time it will have been created and available. */
5549 /* We don't need to take any sort of lock here as we are the only
5550 * thread with access to newsksec */
5551 selinux_netlbl_inet_csk_clone(newsk, req->rsk_ops->family);
5554 static void selinux_inet_conn_established(struct sock *sk, struct sk_buff *skb)
5556 u16 family = sk->sk_family;
5557 struct sk_security_struct *sksec = sk->sk_security;
5559 /* handle mapped IPv4 packets arriving via IPv6 sockets */
5560 if (family == PF_INET6 && skb->protocol == htons(ETH_P_IP))
5563 selinux_skb_peerlbl_sid(skb, family, &sksec->peer_sid);
5566 static int selinux_secmark_relabel_packet(u32 sid)
5568 const struct task_security_struct *__tsec;
5571 __tsec = selinux_cred(current_cred());
5574 return avc_has_perm(&selinux_state,
5575 tsid, sid, SECCLASS_PACKET, PACKET__RELABELTO,
5579 static void selinux_secmark_refcount_inc(void)
5581 atomic_inc(&selinux_secmark_refcount);
5584 static void selinux_secmark_refcount_dec(void)
5586 atomic_dec(&selinux_secmark_refcount);
5589 static void selinux_req_classify_flow(const struct request_sock *req,
5590 struct flowi_common *flic)
5592 flic->flowic_secid = req->secid;
5595 static int selinux_tun_dev_alloc_security(void **security)
5597 struct tun_security_struct *tunsec;
5599 tunsec = kzalloc(sizeof(*tunsec), GFP_KERNEL);
5602 tunsec->sid = current_sid();
5608 static void selinux_tun_dev_free_security(void *security)
5613 static int selinux_tun_dev_create(void)
5615 u32 sid = current_sid();
5617 /* we aren't taking into account the "sockcreate" SID since the socket
5618 * that is being created here is not a socket in the traditional sense,
5619 * instead it is a private sock, accessible only to the kernel, and
5620 * representing a wide range of network traffic spanning multiple
5621 * connections unlike traditional sockets - check the TUN driver to
5622 * get a better understanding of why this socket is special */
5624 return avc_has_perm(&selinux_state,
5625 sid, sid, SECCLASS_TUN_SOCKET, TUN_SOCKET__CREATE,
5629 static int selinux_tun_dev_attach_queue(void *security)
5631 struct tun_security_struct *tunsec = security;
5633 return avc_has_perm(&selinux_state,
5634 current_sid(), tunsec->sid, SECCLASS_TUN_SOCKET,
5635 TUN_SOCKET__ATTACH_QUEUE, NULL);
5638 static int selinux_tun_dev_attach(struct sock *sk, void *security)
5640 struct tun_security_struct *tunsec = security;
5641 struct sk_security_struct *sksec = sk->sk_security;
5643 /* we don't currently perform any NetLabel based labeling here and it
5644 * isn't clear that we would want to do so anyway; while we could apply
5645 * labeling without the support of the TUN user the resulting labeled
5646 * traffic from the other end of the connection would almost certainly
5647 * cause confusion to the TUN user that had no idea network labeling
5648 * protocols were being used */
5650 sksec->sid = tunsec->sid;
5651 sksec->sclass = SECCLASS_TUN_SOCKET;
5656 static int selinux_tun_dev_open(void *security)
5658 struct tun_security_struct *tunsec = security;
5659 u32 sid = current_sid();
5662 err = avc_has_perm(&selinux_state,
5663 sid, tunsec->sid, SECCLASS_TUN_SOCKET,
5664 TUN_SOCKET__RELABELFROM, NULL);
5667 err = avc_has_perm(&selinux_state,
5668 sid, sid, SECCLASS_TUN_SOCKET,
5669 TUN_SOCKET__RELABELTO, NULL);
5677 #ifdef CONFIG_NETFILTER
5679 static unsigned int selinux_ip_forward(void *priv, struct sk_buff *skb,
5680 const struct nf_hook_state *state)
5686 struct common_audit_data ad;
5687 struct lsm_network_audit net = {0,};
5688 int secmark_active, peerlbl_active;
5690 if (!selinux_policycap_netpeer())
5693 secmark_active = selinux_secmark_enabled();
5694 peerlbl_active = selinux_peerlbl_enabled();
5695 if (!secmark_active && !peerlbl_active)
5699 if (selinux_skb_peerlbl_sid(skb, family, &peer_sid) != 0)
5702 ifindex = state->in->ifindex;
5703 ad.type = LSM_AUDIT_DATA_NET;
5705 ad.u.net->netif = ifindex;
5706 ad.u.net->family = family;
5707 if (selinux_parse_skb(skb, &ad, &addrp, 1, NULL) != 0)
5710 if (peerlbl_active) {
5713 err = selinux_inet_sys_rcv_skb(state->net, ifindex,
5714 addrp, family, peer_sid, &ad);
5716 selinux_netlbl_err(skb, family, err, 1);
5722 if (avc_has_perm(&selinux_state,
5723 peer_sid, skb->secmark,
5724 SECCLASS_PACKET, PACKET__FORWARD_IN, &ad))
5727 if (netlbl_enabled())
5728 /* we do this in the FORWARD path and not the POST_ROUTING
5729 * path because we want to make sure we apply the necessary
5730 * labeling before IPsec is applied so we can leverage AH
5732 if (selinux_netlbl_skbuff_setsid(skb, family, peer_sid) != 0)
5738 static unsigned int selinux_ip_output(void *priv, struct sk_buff *skb,
5739 const struct nf_hook_state *state)
5744 if (!netlbl_enabled())
5747 /* we do this in the LOCAL_OUT path and not the POST_ROUTING path
5748 * because we want to make sure we apply the necessary labeling
5749 * before IPsec is applied so we can leverage AH protection */
5752 struct sk_security_struct *sksec;
5754 if (sk_listener(sk))
5755 /* if the socket is the listening state then this
5756 * packet is a SYN-ACK packet which means it needs to
5757 * be labeled based on the connection/request_sock and
5758 * not the parent socket. unfortunately, we can't
5759 * lookup the request_sock yet as it isn't queued on
5760 * the parent socket until after the SYN-ACK is sent.
5761 * the "solution" is to simply pass the packet as-is
5762 * as any IP option based labeling should be copied
5763 * from the initial connection request (in the IP
5764 * layer). it is far from ideal, but until we get a
5765 * security label in the packet itself this is the
5766 * best we can do. */
5769 /* standard practice, label using the parent socket */
5770 sksec = sk->sk_security;
5773 sid = SECINITSID_KERNEL;
5774 if (selinux_netlbl_skbuff_setsid(skb, state->pf, sid) != 0)
5781 static unsigned int selinux_ip_postroute_compat(struct sk_buff *skb,
5782 const struct nf_hook_state *state)
5785 struct sk_security_struct *sksec;
5786 struct common_audit_data ad;
5787 struct lsm_network_audit net = {0,};
5790 sk = skb_to_full_sk(skb);
5793 sksec = sk->sk_security;
5795 ad.type = LSM_AUDIT_DATA_NET;
5797 ad.u.net->netif = state->out->ifindex;
5798 ad.u.net->family = state->pf;
5799 if (selinux_parse_skb(skb, &ad, NULL, 0, &proto))
5802 if (selinux_secmark_enabled())
5803 if (avc_has_perm(&selinux_state,
5804 sksec->sid, skb->secmark,
5805 SECCLASS_PACKET, PACKET__SEND, &ad))
5806 return NF_DROP_ERR(-ECONNREFUSED);
5808 if (selinux_xfrm_postroute_last(sksec->sid, skb, &ad, proto))
5809 return NF_DROP_ERR(-ECONNREFUSED);
5814 static unsigned int selinux_ip_postroute(void *priv,
5815 struct sk_buff *skb,
5816 const struct nf_hook_state *state)
5823 struct common_audit_data ad;
5824 struct lsm_network_audit net = {0,};
5826 int secmark_active, peerlbl_active;
5828 /* If any sort of compatibility mode is enabled then handoff processing
5829 * to the selinux_ip_postroute_compat() function to deal with the
5830 * special handling. We do this in an attempt to keep this function
5831 * as fast and as clean as possible. */
5832 if (!selinux_policycap_netpeer())
5833 return selinux_ip_postroute_compat(skb, state);
5835 secmark_active = selinux_secmark_enabled();
5836 peerlbl_active = selinux_peerlbl_enabled();
5837 if (!secmark_active && !peerlbl_active)
5840 sk = skb_to_full_sk(skb);
5843 /* If skb->dst->xfrm is non-NULL then the packet is undergoing an IPsec
5844 * packet transformation so allow the packet to pass without any checks
5845 * since we'll have another chance to perform access control checks
5846 * when the packet is on it's final way out.
5847 * NOTE: there appear to be some IPv6 multicast cases where skb->dst
5848 * is NULL, in this case go ahead and apply access control.
5849 * NOTE: if this is a local socket (skb->sk != NULL) that is in the
5850 * TCP listening state we cannot wait until the XFRM processing
5851 * is done as we will miss out on the SA label if we do;
5852 * unfortunately, this means more work, but it is only once per
5854 if (skb_dst(skb) != NULL && skb_dst(skb)->xfrm != NULL &&
5855 !(sk && sk_listener(sk)))
5861 /* Without an associated socket the packet is either coming
5862 * from the kernel or it is being forwarded; check the packet
5863 * to determine which and if the packet is being forwarded
5864 * query the packet directly to determine the security label. */
5866 secmark_perm = PACKET__FORWARD_OUT;
5867 if (selinux_skb_peerlbl_sid(skb, family, &peer_sid))
5870 secmark_perm = PACKET__SEND;
5871 peer_sid = SECINITSID_KERNEL;
5873 } else if (sk_listener(sk)) {
5874 /* Locally generated packet but the associated socket is in the
5875 * listening state which means this is a SYN-ACK packet. In
5876 * this particular case the correct security label is assigned
5877 * to the connection/request_sock but unfortunately we can't
5878 * query the request_sock as it isn't queued on the parent
5879 * socket until after the SYN-ACK packet is sent; the only
5880 * viable choice is to regenerate the label like we do in
5881 * selinux_inet_conn_request(). See also selinux_ip_output()
5882 * for similar problems. */
5884 struct sk_security_struct *sksec;
5886 sksec = sk->sk_security;
5887 if (selinux_skb_peerlbl_sid(skb, family, &skb_sid))
5889 /* At this point, if the returned skb peerlbl is SECSID_NULL
5890 * and the packet has been through at least one XFRM
5891 * transformation then we must be dealing with the "final"
5892 * form of labeled IPsec packet; since we've already applied
5893 * all of our access controls on this packet we can safely
5894 * pass the packet. */
5895 if (skb_sid == SECSID_NULL) {
5898 if (IPCB(skb)->flags & IPSKB_XFRM_TRANSFORMED)
5902 if (IP6CB(skb)->flags & IP6SKB_XFRM_TRANSFORMED)
5906 return NF_DROP_ERR(-ECONNREFUSED);
5909 if (selinux_conn_sid(sksec->sid, skb_sid, &peer_sid))
5911 secmark_perm = PACKET__SEND;
5913 /* Locally generated packet, fetch the security label from the
5914 * associated socket. */
5915 struct sk_security_struct *sksec = sk->sk_security;
5916 peer_sid = sksec->sid;
5917 secmark_perm = PACKET__SEND;
5920 ifindex = state->out->ifindex;
5921 ad.type = LSM_AUDIT_DATA_NET;
5923 ad.u.net->netif = ifindex;
5924 ad.u.net->family = family;
5925 if (selinux_parse_skb(skb, &ad, &addrp, 0, NULL))
5929 if (avc_has_perm(&selinux_state,
5930 peer_sid, skb->secmark,
5931 SECCLASS_PACKET, secmark_perm, &ad))
5932 return NF_DROP_ERR(-ECONNREFUSED);
5934 if (peerlbl_active) {
5938 if (sel_netif_sid(state->net, ifindex, &if_sid))
5940 if (avc_has_perm(&selinux_state,
5942 SECCLASS_NETIF, NETIF__EGRESS, &ad))
5943 return NF_DROP_ERR(-ECONNREFUSED);
5945 if (sel_netnode_sid(addrp, family, &node_sid))
5947 if (avc_has_perm(&selinux_state,
5949 SECCLASS_NODE, NODE__SENDTO, &ad))
5950 return NF_DROP_ERR(-ECONNREFUSED);
5955 #endif /* CONFIG_NETFILTER */
5957 static int selinux_netlink_send(struct sock *sk, struct sk_buff *skb)
5960 unsigned int msg_len;
5961 unsigned int data_len = skb->len;
5962 unsigned char *data = skb->data;
5963 struct nlmsghdr *nlh;
5964 struct sk_security_struct *sksec = sk->sk_security;
5965 u16 sclass = sksec->sclass;
5968 while (data_len >= nlmsg_total_size(0)) {
5969 nlh = (struct nlmsghdr *)data;
5971 /* NOTE: the nlmsg_len field isn't reliably set by some netlink
5972 * users which means we can't reject skb's with bogus
5973 * length fields; our solution is to follow what
5974 * netlink_rcv_skb() does and simply skip processing at
5975 * messages with length fields that are clearly junk
5977 if (nlh->nlmsg_len < NLMSG_HDRLEN || nlh->nlmsg_len > data_len)
5980 rc = selinux_nlmsg_lookup(sclass, nlh->nlmsg_type, &perm);
5982 rc = sock_has_perm(sk, perm);
5985 } else if (rc == -EINVAL) {
5986 /* -EINVAL is a missing msg/perm mapping */
5987 pr_warn_ratelimited("SELinux: unrecognized netlink"
5988 " message: protocol=%hu nlmsg_type=%hu sclass=%s"
5989 " pid=%d comm=%s\n",
5990 sk->sk_protocol, nlh->nlmsg_type,
5991 secclass_map[sclass - 1].name,
5992 task_pid_nr(current), current->comm);
5993 if (enforcing_enabled(&selinux_state) &&
5994 !security_get_allow_unknown(&selinux_state))
5997 } else if (rc == -ENOENT) {
5998 /* -ENOENT is a missing socket/class mapping, ignore */
6004 /* move to the next message after applying netlink padding */
6005 msg_len = NLMSG_ALIGN(nlh->nlmsg_len);
6006 if (msg_len >= data_len)
6008 data_len -= msg_len;
6015 static void ipc_init_security(struct ipc_security_struct *isec, u16 sclass)
6017 isec->sclass = sclass;
6018 isec->sid = current_sid();
6021 static int ipc_has_perm(struct kern_ipc_perm *ipc_perms,
6024 struct ipc_security_struct *isec;
6025 struct common_audit_data ad;
6026 u32 sid = current_sid();
6028 isec = selinux_ipc(ipc_perms);
6030 ad.type = LSM_AUDIT_DATA_IPC;
6031 ad.u.ipc_id = ipc_perms->key;
6033 return avc_has_perm(&selinux_state,
6034 sid, isec->sid, isec->sclass, perms, &ad);
6037 static int selinux_msg_msg_alloc_security(struct msg_msg *msg)
6039 struct msg_security_struct *msec;
6041 msec = selinux_msg_msg(msg);
6042 msec->sid = SECINITSID_UNLABELED;
6047 /* message queue security operations */
6048 static int selinux_msg_queue_alloc_security(struct kern_ipc_perm *msq)
6050 struct ipc_security_struct *isec;
6051 struct common_audit_data ad;
6052 u32 sid = current_sid();
6055 isec = selinux_ipc(msq);
6056 ipc_init_security(isec, SECCLASS_MSGQ);
6058 ad.type = LSM_AUDIT_DATA_IPC;
6059 ad.u.ipc_id = msq->key;
6061 rc = avc_has_perm(&selinux_state,
6062 sid, isec->sid, SECCLASS_MSGQ,
6067 static int selinux_msg_queue_associate(struct kern_ipc_perm *msq, int msqflg)
6069 struct ipc_security_struct *isec;
6070 struct common_audit_data ad;
6071 u32 sid = current_sid();
6073 isec = selinux_ipc(msq);
6075 ad.type = LSM_AUDIT_DATA_IPC;
6076 ad.u.ipc_id = msq->key;
6078 return avc_has_perm(&selinux_state,
6079 sid, isec->sid, SECCLASS_MSGQ,
6080 MSGQ__ASSOCIATE, &ad);
6083 static int selinux_msg_queue_msgctl(struct kern_ipc_perm *msq, int cmd)
6091 /* No specific object, just general system-wide information. */
6092 return avc_has_perm(&selinux_state,
6093 current_sid(), SECINITSID_KERNEL,
6094 SECCLASS_SYSTEM, SYSTEM__IPC_INFO, NULL);
6098 perms = MSGQ__GETATTR | MSGQ__ASSOCIATE;
6101 perms = MSGQ__SETATTR;
6104 perms = MSGQ__DESTROY;
6110 err = ipc_has_perm(msq, perms);
6114 static int selinux_msg_queue_msgsnd(struct kern_ipc_perm *msq, struct msg_msg *msg, int msqflg)
6116 struct ipc_security_struct *isec;
6117 struct msg_security_struct *msec;
6118 struct common_audit_data ad;
6119 u32 sid = current_sid();
6122 isec = selinux_ipc(msq);
6123 msec = selinux_msg_msg(msg);
6126 * First time through, need to assign label to the message
6128 if (msec->sid == SECINITSID_UNLABELED) {
6130 * Compute new sid based on current process and
6131 * message queue this message will be stored in
6133 rc = security_transition_sid(&selinux_state, sid, isec->sid,
6134 SECCLASS_MSG, NULL, &msec->sid);
6139 ad.type = LSM_AUDIT_DATA_IPC;
6140 ad.u.ipc_id = msq->key;
6142 /* Can this process write to the queue? */
6143 rc = avc_has_perm(&selinux_state,
6144 sid, isec->sid, SECCLASS_MSGQ,
6147 /* Can this process send the message */
6148 rc = avc_has_perm(&selinux_state,
6149 sid, msec->sid, SECCLASS_MSG,
6152 /* Can the message be put in the queue? */
6153 rc = avc_has_perm(&selinux_state,
6154 msec->sid, isec->sid, SECCLASS_MSGQ,
6155 MSGQ__ENQUEUE, &ad);
6160 static int selinux_msg_queue_msgrcv(struct kern_ipc_perm *msq, struct msg_msg *msg,
6161 struct task_struct *target,
6162 long type, int mode)
6164 struct ipc_security_struct *isec;
6165 struct msg_security_struct *msec;
6166 struct common_audit_data ad;
6167 u32 sid = task_sid_obj(target);
6170 isec = selinux_ipc(msq);
6171 msec = selinux_msg_msg(msg);
6173 ad.type = LSM_AUDIT_DATA_IPC;
6174 ad.u.ipc_id = msq->key;
6176 rc = avc_has_perm(&selinux_state,
6178 SECCLASS_MSGQ, MSGQ__READ, &ad);
6180 rc = avc_has_perm(&selinux_state,
6182 SECCLASS_MSG, MSG__RECEIVE, &ad);
6186 /* Shared Memory security operations */
6187 static int selinux_shm_alloc_security(struct kern_ipc_perm *shp)
6189 struct ipc_security_struct *isec;
6190 struct common_audit_data ad;
6191 u32 sid = current_sid();
6194 isec = selinux_ipc(shp);
6195 ipc_init_security(isec, SECCLASS_SHM);
6197 ad.type = LSM_AUDIT_DATA_IPC;
6198 ad.u.ipc_id = shp->key;
6200 rc = avc_has_perm(&selinux_state,
6201 sid, isec->sid, SECCLASS_SHM,
6206 static int selinux_shm_associate(struct kern_ipc_perm *shp, int shmflg)
6208 struct ipc_security_struct *isec;
6209 struct common_audit_data ad;
6210 u32 sid = current_sid();
6212 isec = selinux_ipc(shp);
6214 ad.type = LSM_AUDIT_DATA_IPC;
6215 ad.u.ipc_id = shp->key;
6217 return avc_has_perm(&selinux_state,
6218 sid, isec->sid, SECCLASS_SHM,
6219 SHM__ASSOCIATE, &ad);
6222 /* Note, at this point, shp is locked down */
6223 static int selinux_shm_shmctl(struct kern_ipc_perm *shp, int cmd)
6231 /* No specific object, just general system-wide information. */
6232 return avc_has_perm(&selinux_state,
6233 current_sid(), SECINITSID_KERNEL,
6234 SECCLASS_SYSTEM, SYSTEM__IPC_INFO, NULL);
6238 perms = SHM__GETATTR | SHM__ASSOCIATE;
6241 perms = SHM__SETATTR;
6248 perms = SHM__DESTROY;
6254 err = ipc_has_perm(shp, perms);
6258 static int selinux_shm_shmat(struct kern_ipc_perm *shp,
6259 char __user *shmaddr, int shmflg)
6263 if (shmflg & SHM_RDONLY)
6266 perms = SHM__READ | SHM__WRITE;
6268 return ipc_has_perm(shp, perms);
6271 /* Semaphore security operations */
6272 static int selinux_sem_alloc_security(struct kern_ipc_perm *sma)
6274 struct ipc_security_struct *isec;
6275 struct common_audit_data ad;
6276 u32 sid = current_sid();
6279 isec = selinux_ipc(sma);
6280 ipc_init_security(isec, SECCLASS_SEM);
6282 ad.type = LSM_AUDIT_DATA_IPC;
6283 ad.u.ipc_id = sma->key;
6285 rc = avc_has_perm(&selinux_state,
6286 sid, isec->sid, SECCLASS_SEM,
6291 static int selinux_sem_associate(struct kern_ipc_perm *sma, int semflg)
6293 struct ipc_security_struct *isec;
6294 struct common_audit_data ad;
6295 u32 sid = current_sid();
6297 isec = selinux_ipc(sma);
6299 ad.type = LSM_AUDIT_DATA_IPC;
6300 ad.u.ipc_id = sma->key;
6302 return avc_has_perm(&selinux_state,
6303 sid, isec->sid, SECCLASS_SEM,
6304 SEM__ASSOCIATE, &ad);
6307 /* Note, at this point, sma is locked down */
6308 static int selinux_sem_semctl(struct kern_ipc_perm *sma, int cmd)
6316 /* No specific object, just general system-wide information. */
6317 return avc_has_perm(&selinux_state,
6318 current_sid(), SECINITSID_KERNEL,
6319 SECCLASS_SYSTEM, SYSTEM__IPC_INFO, NULL);
6323 perms = SEM__GETATTR;
6334 perms = SEM__DESTROY;
6337 perms = SEM__SETATTR;
6342 perms = SEM__GETATTR | SEM__ASSOCIATE;
6348 err = ipc_has_perm(sma, perms);
6352 static int selinux_sem_semop(struct kern_ipc_perm *sma,
6353 struct sembuf *sops, unsigned nsops, int alter)
6358 perms = SEM__READ | SEM__WRITE;
6362 return ipc_has_perm(sma, perms);
6365 static int selinux_ipc_permission(struct kern_ipc_perm *ipcp, short flag)
6371 av |= IPC__UNIX_READ;
6373 av |= IPC__UNIX_WRITE;
6378 return ipc_has_perm(ipcp, av);
6381 static void selinux_ipc_getsecid(struct kern_ipc_perm *ipcp, u32 *secid)
6383 struct ipc_security_struct *isec = selinux_ipc(ipcp);
6387 static void selinux_d_instantiate(struct dentry *dentry, struct inode *inode)
6390 inode_doinit_with_dentry(inode, dentry);
6393 static int selinux_getprocattr(struct task_struct *p,
6394 char *name, char **value)
6396 const struct task_security_struct *__tsec;
6402 __tsec = selinux_cred(__task_cred(p));
6405 error = avc_has_perm(&selinux_state,
6406 current_sid(), __tsec->sid,
6407 SECCLASS_PROCESS, PROCESS__GETATTR, NULL);
6412 if (!strcmp(name, "current"))
6414 else if (!strcmp(name, "prev"))
6416 else if (!strcmp(name, "exec"))
6417 sid = __tsec->exec_sid;
6418 else if (!strcmp(name, "fscreate"))
6419 sid = __tsec->create_sid;
6420 else if (!strcmp(name, "keycreate"))
6421 sid = __tsec->keycreate_sid;
6422 else if (!strcmp(name, "sockcreate"))
6423 sid = __tsec->sockcreate_sid;
6433 error = security_sid_to_context(&selinux_state, sid, value, &len);
6443 static int selinux_setprocattr(const char *name, void *value, size_t size)
6445 struct task_security_struct *tsec;
6447 u32 mysid = current_sid(), sid = 0, ptsid;
6452 * Basic control over ability to set these attributes at all.
6454 if (!strcmp(name, "exec"))
6455 error = avc_has_perm(&selinux_state,
6456 mysid, mysid, SECCLASS_PROCESS,
6457 PROCESS__SETEXEC, NULL);
6458 else if (!strcmp(name, "fscreate"))
6459 error = avc_has_perm(&selinux_state,
6460 mysid, mysid, SECCLASS_PROCESS,
6461 PROCESS__SETFSCREATE, NULL);
6462 else if (!strcmp(name, "keycreate"))
6463 error = avc_has_perm(&selinux_state,
6464 mysid, mysid, SECCLASS_PROCESS,
6465 PROCESS__SETKEYCREATE, NULL);
6466 else if (!strcmp(name, "sockcreate"))
6467 error = avc_has_perm(&selinux_state,
6468 mysid, mysid, SECCLASS_PROCESS,
6469 PROCESS__SETSOCKCREATE, NULL);
6470 else if (!strcmp(name, "current"))
6471 error = avc_has_perm(&selinux_state,
6472 mysid, mysid, SECCLASS_PROCESS,
6473 PROCESS__SETCURRENT, NULL);
6479 /* Obtain a SID for the context, if one was specified. */
6480 if (size && str[0] && str[0] != '\n') {
6481 if (str[size-1] == '\n') {
6485 error = security_context_to_sid(&selinux_state, value, size,
6487 if (error == -EINVAL && !strcmp(name, "fscreate")) {
6488 if (!has_cap_mac_admin(true)) {
6489 struct audit_buffer *ab;
6492 /* We strip a nul only if it is at the end, otherwise the
6493 * context contains a nul and we should audit that */
6494 if (str[size - 1] == '\0')
6495 audit_size = size - 1;
6498 ab = audit_log_start(audit_context(),
6503 audit_log_format(ab, "op=fscreate invalid_context=");
6504 audit_log_n_untrustedstring(ab, value, audit_size);
6509 error = security_context_to_sid_force(
6517 new = prepare_creds();
6521 /* Permission checking based on the specified context is
6522 performed during the actual operation (execve,
6523 open/mkdir/...), when we know the full context of the
6524 operation. See selinux_bprm_creds_for_exec for the execve
6525 checks and may_create for the file creation checks. The
6526 operation will then fail if the context is not permitted. */
6527 tsec = selinux_cred(new);
6528 if (!strcmp(name, "exec")) {
6529 tsec->exec_sid = sid;
6530 } else if (!strcmp(name, "fscreate")) {
6531 tsec->create_sid = sid;
6532 } else if (!strcmp(name, "keycreate")) {
6534 error = avc_has_perm(&selinux_state, mysid, sid,
6535 SECCLASS_KEY, KEY__CREATE, NULL);
6539 tsec->keycreate_sid = sid;
6540 } else if (!strcmp(name, "sockcreate")) {
6541 tsec->sockcreate_sid = sid;
6542 } else if (!strcmp(name, "current")) {
6547 /* Only allow single threaded processes to change context */
6549 if (!current_is_single_threaded()) {
6550 error = security_bounded_transition(&selinux_state,
6556 /* Check permissions for the transition. */
6557 error = avc_has_perm(&selinux_state,
6558 tsec->sid, sid, SECCLASS_PROCESS,
6559 PROCESS__DYNTRANSITION, NULL);
6563 /* Check for ptracing, and update the task SID if ok.
6564 Otherwise, leave SID unchanged and fail. */
6565 ptsid = ptrace_parent_sid();
6567 error = avc_has_perm(&selinux_state,
6568 ptsid, sid, SECCLASS_PROCESS,
6569 PROCESS__PTRACE, NULL);
6588 static int selinux_ismaclabel(const char *name)
6590 return (strcmp(name, XATTR_SELINUX_SUFFIX) == 0);
6593 static int selinux_secid_to_secctx(u32 secid, char **secdata, u32 *seclen)
6595 return security_sid_to_context(&selinux_state, secid,
6599 static int selinux_secctx_to_secid(const char *secdata, u32 seclen, u32 *secid)
6601 return security_context_to_sid(&selinux_state, secdata, seclen,
6605 static void selinux_release_secctx(char *secdata, u32 seclen)
6610 static void selinux_inode_invalidate_secctx(struct inode *inode)
6612 struct inode_security_struct *isec = selinux_inode(inode);
6614 spin_lock(&isec->lock);
6615 isec->initialized = LABEL_INVALID;
6616 spin_unlock(&isec->lock);
6620 * called with inode->i_mutex locked
6622 static int selinux_inode_notifysecctx(struct inode *inode, void *ctx, u32 ctxlen)
6624 int rc = selinux_inode_setsecurity(inode, XATTR_SELINUX_SUFFIX,
6626 /* Do not return error when suppressing label (SBLABEL_MNT not set). */
6627 return rc == -EOPNOTSUPP ? 0 : rc;
6631 * called with inode->i_mutex locked
6633 static int selinux_inode_setsecctx(struct dentry *dentry, void *ctx, u32 ctxlen)
6635 return __vfs_setxattr_noperm(&init_user_ns, dentry, XATTR_NAME_SELINUX,
6639 static int selinux_inode_getsecctx(struct inode *inode, void **ctx, u32 *ctxlen)
6642 len = selinux_inode_getsecurity(&init_user_ns, inode,
6643 XATTR_SELINUX_SUFFIX, ctx, true);
6651 static int selinux_key_alloc(struct key *k, const struct cred *cred,
6652 unsigned long flags)
6654 const struct task_security_struct *tsec;
6655 struct key_security_struct *ksec;
6657 ksec = kzalloc(sizeof(struct key_security_struct), GFP_KERNEL);
6661 tsec = selinux_cred(cred);
6662 if (tsec->keycreate_sid)
6663 ksec->sid = tsec->keycreate_sid;
6665 ksec->sid = tsec->sid;
6671 static void selinux_key_free(struct key *k)
6673 struct key_security_struct *ksec = k->security;
6679 static int selinux_key_permission(key_ref_t key_ref,
6680 const struct cred *cred,
6681 enum key_need_perm need_perm)
6684 struct key_security_struct *ksec;
6687 switch (need_perm) {
6694 case KEY_NEED_WRITE:
6697 case KEY_NEED_SEARCH:
6703 case KEY_NEED_SETATTR:
6704 perm = KEY__SETATTR;
6706 case KEY_NEED_UNLINK:
6707 case KEY_SYSADMIN_OVERRIDE:
6708 case KEY_AUTHTOKEN_OVERRIDE:
6709 case KEY_DEFER_PERM_CHECK:
6717 sid = cred_sid(cred);
6718 key = key_ref_to_ptr(key_ref);
6719 ksec = key->security;
6721 return avc_has_perm(&selinux_state,
6722 sid, ksec->sid, SECCLASS_KEY, perm, NULL);
6725 static int selinux_key_getsecurity(struct key *key, char **_buffer)
6727 struct key_security_struct *ksec = key->security;
6728 char *context = NULL;
6732 rc = security_sid_to_context(&selinux_state, ksec->sid,
6740 #ifdef CONFIG_KEY_NOTIFICATIONS
6741 static int selinux_watch_key(struct key *key)
6743 struct key_security_struct *ksec = key->security;
6744 u32 sid = current_sid();
6746 return avc_has_perm(&selinux_state,
6747 sid, ksec->sid, SECCLASS_KEY, KEY__VIEW, NULL);
6752 #ifdef CONFIG_SECURITY_INFINIBAND
6753 static int selinux_ib_pkey_access(void *ib_sec, u64 subnet_prefix, u16 pkey_val)
6755 struct common_audit_data ad;
6758 struct ib_security_struct *sec = ib_sec;
6759 struct lsm_ibpkey_audit ibpkey;
6761 err = sel_ib_pkey_sid(subnet_prefix, pkey_val, &sid);
6765 ad.type = LSM_AUDIT_DATA_IBPKEY;
6766 ibpkey.subnet_prefix = subnet_prefix;
6767 ibpkey.pkey = pkey_val;
6768 ad.u.ibpkey = &ibpkey;
6769 return avc_has_perm(&selinux_state,
6771 SECCLASS_INFINIBAND_PKEY,
6772 INFINIBAND_PKEY__ACCESS, &ad);
6775 static int selinux_ib_endport_manage_subnet(void *ib_sec, const char *dev_name,
6778 struct common_audit_data ad;
6781 struct ib_security_struct *sec = ib_sec;
6782 struct lsm_ibendport_audit ibendport;
6784 err = security_ib_endport_sid(&selinux_state, dev_name, port_num,
6790 ad.type = LSM_AUDIT_DATA_IBENDPORT;
6791 ibendport.dev_name = dev_name;
6792 ibendport.port = port_num;
6793 ad.u.ibendport = &ibendport;
6794 return avc_has_perm(&selinux_state,
6796 SECCLASS_INFINIBAND_ENDPORT,
6797 INFINIBAND_ENDPORT__MANAGE_SUBNET, &ad);
6800 static int selinux_ib_alloc_security(void **ib_sec)
6802 struct ib_security_struct *sec;
6804 sec = kzalloc(sizeof(*sec), GFP_KERNEL);
6807 sec->sid = current_sid();
6813 static void selinux_ib_free_security(void *ib_sec)
6819 #ifdef CONFIG_BPF_SYSCALL
6820 static int selinux_bpf(int cmd, union bpf_attr *attr,
6823 u32 sid = current_sid();
6827 case BPF_MAP_CREATE:
6828 ret = avc_has_perm(&selinux_state,
6829 sid, sid, SECCLASS_BPF, BPF__MAP_CREATE,
6833 ret = avc_has_perm(&selinux_state,
6834 sid, sid, SECCLASS_BPF, BPF__PROG_LOAD,
6845 static u32 bpf_map_fmode_to_av(fmode_t fmode)
6849 if (fmode & FMODE_READ)
6850 av |= BPF__MAP_READ;
6851 if (fmode & FMODE_WRITE)
6852 av |= BPF__MAP_WRITE;
6856 /* This function will check the file pass through unix socket or binder to see
6857 * if it is a bpf related object. And apply correspinding checks on the bpf
6858 * object based on the type. The bpf maps and programs, not like other files and
6859 * socket, are using a shared anonymous inode inside the kernel as their inode.
6860 * So checking that inode cannot identify if the process have privilege to
6861 * access the bpf object and that's why we have to add this additional check in
6862 * selinux_file_receive and selinux_binder_transfer_files.
6864 static int bpf_fd_pass(struct file *file, u32 sid)
6866 struct bpf_security_struct *bpfsec;
6867 struct bpf_prog *prog;
6868 struct bpf_map *map;
6871 if (file->f_op == &bpf_map_fops) {
6872 map = file->private_data;
6873 bpfsec = map->security;
6874 ret = avc_has_perm(&selinux_state,
6875 sid, bpfsec->sid, SECCLASS_BPF,
6876 bpf_map_fmode_to_av(file->f_mode), NULL);
6879 } else if (file->f_op == &bpf_prog_fops) {
6880 prog = file->private_data;
6881 bpfsec = prog->aux->security;
6882 ret = avc_has_perm(&selinux_state,
6883 sid, bpfsec->sid, SECCLASS_BPF,
6884 BPF__PROG_RUN, NULL);
6891 static int selinux_bpf_map(struct bpf_map *map, fmode_t fmode)
6893 u32 sid = current_sid();
6894 struct bpf_security_struct *bpfsec;
6896 bpfsec = map->security;
6897 return avc_has_perm(&selinux_state,
6898 sid, bpfsec->sid, SECCLASS_BPF,
6899 bpf_map_fmode_to_av(fmode), NULL);
6902 static int selinux_bpf_prog(struct bpf_prog *prog)
6904 u32 sid = current_sid();
6905 struct bpf_security_struct *bpfsec;
6907 bpfsec = prog->aux->security;
6908 return avc_has_perm(&selinux_state,
6909 sid, bpfsec->sid, SECCLASS_BPF,
6910 BPF__PROG_RUN, NULL);
6913 static int selinux_bpf_map_alloc(struct bpf_map *map)
6915 struct bpf_security_struct *bpfsec;
6917 bpfsec = kzalloc(sizeof(*bpfsec), GFP_KERNEL);
6921 bpfsec->sid = current_sid();
6922 map->security = bpfsec;
6927 static void selinux_bpf_map_free(struct bpf_map *map)
6929 struct bpf_security_struct *bpfsec = map->security;
6931 map->security = NULL;
6935 static int selinux_bpf_prog_alloc(struct bpf_prog_aux *aux)
6937 struct bpf_security_struct *bpfsec;
6939 bpfsec = kzalloc(sizeof(*bpfsec), GFP_KERNEL);
6943 bpfsec->sid = current_sid();
6944 aux->security = bpfsec;
6949 static void selinux_bpf_prog_free(struct bpf_prog_aux *aux)
6951 struct bpf_security_struct *bpfsec = aux->security;
6953 aux->security = NULL;
6958 struct lsm_blob_sizes selinux_blob_sizes __lsm_ro_after_init = {
6959 .lbs_cred = sizeof(struct task_security_struct),
6960 .lbs_file = sizeof(struct file_security_struct),
6961 .lbs_inode = sizeof(struct inode_security_struct),
6962 .lbs_ipc = sizeof(struct ipc_security_struct),
6963 .lbs_msg_msg = sizeof(struct msg_security_struct),
6964 .lbs_superblock = sizeof(struct superblock_security_struct),
6967 #ifdef CONFIG_PERF_EVENTS
6968 static int selinux_perf_event_open(struct perf_event_attr *attr, int type)
6970 u32 requested, sid = current_sid();
6972 if (type == PERF_SECURITY_OPEN)
6973 requested = PERF_EVENT__OPEN;
6974 else if (type == PERF_SECURITY_CPU)
6975 requested = PERF_EVENT__CPU;
6976 else if (type == PERF_SECURITY_KERNEL)
6977 requested = PERF_EVENT__KERNEL;
6978 else if (type == PERF_SECURITY_TRACEPOINT)
6979 requested = PERF_EVENT__TRACEPOINT;
6983 return avc_has_perm(&selinux_state, sid, sid, SECCLASS_PERF_EVENT,
6987 static int selinux_perf_event_alloc(struct perf_event *event)
6989 struct perf_event_security_struct *perfsec;
6991 perfsec = kzalloc(sizeof(*perfsec), GFP_KERNEL);
6995 perfsec->sid = current_sid();
6996 event->security = perfsec;
7001 static void selinux_perf_event_free(struct perf_event *event)
7003 struct perf_event_security_struct *perfsec = event->security;
7005 event->security = NULL;
7009 static int selinux_perf_event_read(struct perf_event *event)
7011 struct perf_event_security_struct *perfsec = event->security;
7012 u32 sid = current_sid();
7014 return avc_has_perm(&selinux_state, sid, perfsec->sid,
7015 SECCLASS_PERF_EVENT, PERF_EVENT__READ, NULL);
7018 static int selinux_perf_event_write(struct perf_event *event)
7020 struct perf_event_security_struct *perfsec = event->security;
7021 u32 sid = current_sid();
7023 return avc_has_perm(&selinux_state, sid, perfsec->sid,
7024 SECCLASS_PERF_EVENT, PERF_EVENT__WRITE, NULL);
7028 #ifdef CONFIG_IO_URING
7030 * selinux_uring_override_creds - check the requested cred override
7031 * @new: the target creds
7033 * Check to see if the current task is allowed to override it's credentials
7034 * to service an io_uring operation.
7036 static int selinux_uring_override_creds(const struct cred *new)
7038 return avc_has_perm(&selinux_state, current_sid(), cred_sid(new),
7039 SECCLASS_IO_URING, IO_URING__OVERRIDE_CREDS, NULL);
7043 * selinux_uring_sqpoll - check if a io_uring polling thread can be created
7045 * Check to see if the current task is allowed to create a new io_uring
7046 * kernel polling thread.
7048 static int selinux_uring_sqpoll(void)
7050 int sid = current_sid();
7052 return avc_has_perm(&selinux_state, sid, sid,
7053 SECCLASS_IO_URING, IO_URING__SQPOLL, NULL);
7055 #endif /* CONFIG_IO_URING */
7058 * IMPORTANT NOTE: When adding new hooks, please be careful to keep this order:
7059 * 1. any hooks that don't belong to (2.) or (3.) below,
7060 * 2. hooks that both access structures allocated by other hooks, and allocate
7061 * structures that can be later accessed by other hooks (mostly "cloning"
7063 * 3. hooks that only allocate structures that can be later accessed by other
7064 * hooks ("allocating" hooks).
7066 * Please follow block comment delimiters in the list to keep this order.
7068 * This ordering is needed for SELinux runtime disable to work at least somewhat
7069 * safely. Breaking the ordering rules above might lead to NULL pointer derefs
7070 * when disabling SELinux at runtime.
7072 static struct security_hook_list selinux_hooks[] __lsm_ro_after_init = {
7073 LSM_HOOK_INIT(binder_set_context_mgr, selinux_binder_set_context_mgr),
7074 LSM_HOOK_INIT(binder_transaction, selinux_binder_transaction),
7075 LSM_HOOK_INIT(binder_transfer_binder, selinux_binder_transfer_binder),
7076 LSM_HOOK_INIT(binder_transfer_file, selinux_binder_transfer_file),
7078 LSM_HOOK_INIT(ptrace_access_check, selinux_ptrace_access_check),
7079 LSM_HOOK_INIT(ptrace_traceme, selinux_ptrace_traceme),
7080 LSM_HOOK_INIT(capget, selinux_capget),
7081 LSM_HOOK_INIT(capset, selinux_capset),
7082 LSM_HOOK_INIT(capable, selinux_capable),
7083 LSM_HOOK_INIT(quotactl, selinux_quotactl),
7084 LSM_HOOK_INIT(quota_on, selinux_quota_on),
7085 LSM_HOOK_INIT(syslog, selinux_syslog),
7086 LSM_HOOK_INIT(vm_enough_memory, selinux_vm_enough_memory),
7088 LSM_HOOK_INIT(netlink_send, selinux_netlink_send),
7090 LSM_HOOK_INIT(bprm_creds_for_exec, selinux_bprm_creds_for_exec),
7091 LSM_HOOK_INIT(bprm_committing_creds, selinux_bprm_committing_creds),
7092 LSM_HOOK_INIT(bprm_committed_creds, selinux_bprm_committed_creds),
7094 LSM_HOOK_INIT(sb_free_mnt_opts, selinux_free_mnt_opts),
7095 LSM_HOOK_INIT(sb_mnt_opts_compat, selinux_sb_mnt_opts_compat),
7096 LSM_HOOK_INIT(sb_remount, selinux_sb_remount),
7097 LSM_HOOK_INIT(sb_kern_mount, selinux_sb_kern_mount),
7098 LSM_HOOK_INIT(sb_show_options, selinux_sb_show_options),
7099 LSM_HOOK_INIT(sb_statfs, selinux_sb_statfs),
7100 LSM_HOOK_INIT(sb_mount, selinux_mount),
7101 LSM_HOOK_INIT(sb_umount, selinux_umount),
7102 LSM_HOOK_INIT(sb_set_mnt_opts, selinux_set_mnt_opts),
7103 LSM_HOOK_INIT(sb_clone_mnt_opts, selinux_sb_clone_mnt_opts),
7105 LSM_HOOK_INIT(move_mount, selinux_move_mount),
7107 LSM_HOOK_INIT(dentry_init_security, selinux_dentry_init_security),
7108 LSM_HOOK_INIT(dentry_create_files_as, selinux_dentry_create_files_as),
7110 LSM_HOOK_INIT(inode_free_security, selinux_inode_free_security),
7111 LSM_HOOK_INIT(inode_init_security, selinux_inode_init_security),
7112 LSM_HOOK_INIT(inode_init_security_anon, selinux_inode_init_security_anon),
7113 LSM_HOOK_INIT(inode_create, selinux_inode_create),
7114 LSM_HOOK_INIT(inode_link, selinux_inode_link),
7115 LSM_HOOK_INIT(inode_unlink, selinux_inode_unlink),
7116 LSM_HOOK_INIT(inode_symlink, selinux_inode_symlink),
7117 LSM_HOOK_INIT(inode_mkdir, selinux_inode_mkdir),
7118 LSM_HOOK_INIT(inode_rmdir, selinux_inode_rmdir),
7119 LSM_HOOK_INIT(inode_mknod, selinux_inode_mknod),
7120 LSM_HOOK_INIT(inode_rename, selinux_inode_rename),
7121 LSM_HOOK_INIT(inode_readlink, selinux_inode_readlink),
7122 LSM_HOOK_INIT(inode_follow_link, selinux_inode_follow_link),
7123 LSM_HOOK_INIT(inode_permission, selinux_inode_permission),
7124 LSM_HOOK_INIT(inode_setattr, selinux_inode_setattr),
7125 LSM_HOOK_INIT(inode_getattr, selinux_inode_getattr),
7126 LSM_HOOK_INIT(inode_setxattr, selinux_inode_setxattr),
7127 LSM_HOOK_INIT(inode_post_setxattr, selinux_inode_post_setxattr),
7128 LSM_HOOK_INIT(inode_getxattr, selinux_inode_getxattr),
7129 LSM_HOOK_INIT(inode_listxattr, selinux_inode_listxattr),
7130 LSM_HOOK_INIT(inode_removexattr, selinux_inode_removexattr),
7131 LSM_HOOK_INIT(inode_getsecurity, selinux_inode_getsecurity),
7132 LSM_HOOK_INIT(inode_setsecurity, selinux_inode_setsecurity),
7133 LSM_HOOK_INIT(inode_listsecurity, selinux_inode_listsecurity),
7134 LSM_HOOK_INIT(inode_getsecid, selinux_inode_getsecid),
7135 LSM_HOOK_INIT(inode_copy_up, selinux_inode_copy_up),
7136 LSM_HOOK_INIT(inode_copy_up_xattr, selinux_inode_copy_up_xattr),
7137 LSM_HOOK_INIT(path_notify, selinux_path_notify),
7139 LSM_HOOK_INIT(kernfs_init_security, selinux_kernfs_init_security),
7141 LSM_HOOK_INIT(file_permission, selinux_file_permission),
7142 LSM_HOOK_INIT(file_alloc_security, selinux_file_alloc_security),
7143 LSM_HOOK_INIT(file_ioctl, selinux_file_ioctl),
7144 LSM_HOOK_INIT(mmap_file, selinux_mmap_file),
7145 LSM_HOOK_INIT(mmap_addr, selinux_mmap_addr),
7146 LSM_HOOK_INIT(file_mprotect, selinux_file_mprotect),
7147 LSM_HOOK_INIT(file_lock, selinux_file_lock),
7148 LSM_HOOK_INIT(file_fcntl, selinux_file_fcntl),
7149 LSM_HOOK_INIT(file_set_fowner, selinux_file_set_fowner),
7150 LSM_HOOK_INIT(file_send_sigiotask, selinux_file_send_sigiotask),
7151 LSM_HOOK_INIT(file_receive, selinux_file_receive),
7153 LSM_HOOK_INIT(file_open, selinux_file_open),
7155 LSM_HOOK_INIT(task_alloc, selinux_task_alloc),
7156 LSM_HOOK_INIT(cred_prepare, selinux_cred_prepare),
7157 LSM_HOOK_INIT(cred_transfer, selinux_cred_transfer),
7158 LSM_HOOK_INIT(cred_getsecid, selinux_cred_getsecid),
7159 LSM_HOOK_INIT(kernel_act_as, selinux_kernel_act_as),
7160 LSM_HOOK_INIT(kernel_create_files_as, selinux_kernel_create_files_as),
7161 LSM_HOOK_INIT(kernel_module_request, selinux_kernel_module_request),
7162 LSM_HOOK_INIT(kernel_load_data, selinux_kernel_load_data),
7163 LSM_HOOK_INIT(kernel_read_file, selinux_kernel_read_file),
7164 LSM_HOOK_INIT(task_setpgid, selinux_task_setpgid),
7165 LSM_HOOK_INIT(task_getpgid, selinux_task_getpgid),
7166 LSM_HOOK_INIT(task_getsid, selinux_task_getsid),
7167 LSM_HOOK_INIT(task_getsecid_subj, selinux_task_getsecid_subj),
7168 LSM_HOOK_INIT(task_getsecid_obj, selinux_task_getsecid_obj),
7169 LSM_HOOK_INIT(task_setnice, selinux_task_setnice),
7170 LSM_HOOK_INIT(task_setioprio, selinux_task_setioprio),
7171 LSM_HOOK_INIT(task_getioprio, selinux_task_getioprio),
7172 LSM_HOOK_INIT(task_prlimit, selinux_task_prlimit),
7173 LSM_HOOK_INIT(task_setrlimit, selinux_task_setrlimit),
7174 LSM_HOOK_INIT(task_setscheduler, selinux_task_setscheduler),
7175 LSM_HOOK_INIT(task_getscheduler, selinux_task_getscheduler),
7176 LSM_HOOK_INIT(task_movememory, selinux_task_movememory),
7177 LSM_HOOK_INIT(task_kill, selinux_task_kill),
7178 LSM_HOOK_INIT(task_to_inode, selinux_task_to_inode),
7180 LSM_HOOK_INIT(ipc_permission, selinux_ipc_permission),
7181 LSM_HOOK_INIT(ipc_getsecid, selinux_ipc_getsecid),
7183 LSM_HOOK_INIT(msg_queue_associate, selinux_msg_queue_associate),
7184 LSM_HOOK_INIT(msg_queue_msgctl, selinux_msg_queue_msgctl),
7185 LSM_HOOK_INIT(msg_queue_msgsnd, selinux_msg_queue_msgsnd),
7186 LSM_HOOK_INIT(msg_queue_msgrcv, selinux_msg_queue_msgrcv),
7188 LSM_HOOK_INIT(shm_associate, selinux_shm_associate),
7189 LSM_HOOK_INIT(shm_shmctl, selinux_shm_shmctl),
7190 LSM_HOOK_INIT(shm_shmat, selinux_shm_shmat),
7192 LSM_HOOK_INIT(sem_associate, selinux_sem_associate),
7193 LSM_HOOK_INIT(sem_semctl, selinux_sem_semctl),
7194 LSM_HOOK_INIT(sem_semop, selinux_sem_semop),
7196 LSM_HOOK_INIT(d_instantiate, selinux_d_instantiate),
7198 LSM_HOOK_INIT(getprocattr, selinux_getprocattr),
7199 LSM_HOOK_INIT(setprocattr, selinux_setprocattr),
7201 LSM_HOOK_INIT(ismaclabel, selinux_ismaclabel),
7202 LSM_HOOK_INIT(secctx_to_secid, selinux_secctx_to_secid),
7203 LSM_HOOK_INIT(release_secctx, selinux_release_secctx),
7204 LSM_HOOK_INIT(inode_invalidate_secctx, selinux_inode_invalidate_secctx),
7205 LSM_HOOK_INIT(inode_notifysecctx, selinux_inode_notifysecctx),
7206 LSM_HOOK_INIT(inode_setsecctx, selinux_inode_setsecctx),
7208 LSM_HOOK_INIT(unix_stream_connect, selinux_socket_unix_stream_connect),
7209 LSM_HOOK_INIT(unix_may_send, selinux_socket_unix_may_send),
7211 LSM_HOOK_INIT(socket_create, selinux_socket_create),
7212 LSM_HOOK_INIT(socket_post_create, selinux_socket_post_create),
7213 LSM_HOOK_INIT(socket_socketpair, selinux_socket_socketpair),
7214 LSM_HOOK_INIT(socket_bind, selinux_socket_bind),
7215 LSM_HOOK_INIT(socket_connect, selinux_socket_connect),
7216 LSM_HOOK_INIT(socket_listen, selinux_socket_listen),
7217 LSM_HOOK_INIT(socket_accept, selinux_socket_accept),
7218 LSM_HOOK_INIT(socket_sendmsg, selinux_socket_sendmsg),
7219 LSM_HOOK_INIT(socket_recvmsg, selinux_socket_recvmsg),
7220 LSM_HOOK_INIT(socket_getsockname, selinux_socket_getsockname),
7221 LSM_HOOK_INIT(socket_getpeername, selinux_socket_getpeername),
7222 LSM_HOOK_INIT(socket_getsockopt, selinux_socket_getsockopt),
7223 LSM_HOOK_INIT(socket_setsockopt, selinux_socket_setsockopt),
7224 LSM_HOOK_INIT(socket_shutdown, selinux_socket_shutdown),
7225 LSM_HOOK_INIT(socket_sock_rcv_skb, selinux_socket_sock_rcv_skb),
7226 LSM_HOOK_INIT(socket_getpeersec_stream,
7227 selinux_socket_getpeersec_stream),
7228 LSM_HOOK_INIT(socket_getpeersec_dgram, selinux_socket_getpeersec_dgram),
7229 LSM_HOOK_INIT(sk_free_security, selinux_sk_free_security),
7230 LSM_HOOK_INIT(sk_clone_security, selinux_sk_clone_security),
7231 LSM_HOOK_INIT(sk_getsecid, selinux_sk_getsecid),
7232 LSM_HOOK_INIT(sock_graft, selinux_sock_graft),
7233 LSM_HOOK_INIT(sctp_assoc_request, selinux_sctp_assoc_request),
7234 LSM_HOOK_INIT(sctp_sk_clone, selinux_sctp_sk_clone),
7235 LSM_HOOK_INIT(sctp_bind_connect, selinux_sctp_bind_connect),
7236 LSM_HOOK_INIT(inet_conn_request, selinux_inet_conn_request),
7237 LSM_HOOK_INIT(inet_csk_clone, selinux_inet_csk_clone),
7238 LSM_HOOK_INIT(inet_conn_established, selinux_inet_conn_established),
7239 LSM_HOOK_INIT(secmark_relabel_packet, selinux_secmark_relabel_packet),
7240 LSM_HOOK_INIT(secmark_refcount_inc, selinux_secmark_refcount_inc),
7241 LSM_HOOK_INIT(secmark_refcount_dec, selinux_secmark_refcount_dec),
7242 LSM_HOOK_INIT(req_classify_flow, selinux_req_classify_flow),
7243 LSM_HOOK_INIT(tun_dev_free_security, selinux_tun_dev_free_security),
7244 LSM_HOOK_INIT(tun_dev_create, selinux_tun_dev_create),
7245 LSM_HOOK_INIT(tun_dev_attach_queue, selinux_tun_dev_attach_queue),
7246 LSM_HOOK_INIT(tun_dev_attach, selinux_tun_dev_attach),
7247 LSM_HOOK_INIT(tun_dev_open, selinux_tun_dev_open),
7248 #ifdef CONFIG_SECURITY_INFINIBAND
7249 LSM_HOOK_INIT(ib_pkey_access, selinux_ib_pkey_access),
7250 LSM_HOOK_INIT(ib_endport_manage_subnet,
7251 selinux_ib_endport_manage_subnet),
7252 LSM_HOOK_INIT(ib_free_security, selinux_ib_free_security),
7254 #ifdef CONFIG_SECURITY_NETWORK_XFRM
7255 LSM_HOOK_INIT(xfrm_policy_free_security, selinux_xfrm_policy_free),
7256 LSM_HOOK_INIT(xfrm_policy_delete_security, selinux_xfrm_policy_delete),
7257 LSM_HOOK_INIT(xfrm_state_free_security, selinux_xfrm_state_free),
7258 LSM_HOOK_INIT(xfrm_state_delete_security, selinux_xfrm_state_delete),
7259 LSM_HOOK_INIT(xfrm_policy_lookup, selinux_xfrm_policy_lookup),
7260 LSM_HOOK_INIT(xfrm_state_pol_flow_match,
7261 selinux_xfrm_state_pol_flow_match),
7262 LSM_HOOK_INIT(xfrm_decode_session, selinux_xfrm_decode_session),
7266 LSM_HOOK_INIT(key_free, selinux_key_free),
7267 LSM_HOOK_INIT(key_permission, selinux_key_permission),
7268 LSM_HOOK_INIT(key_getsecurity, selinux_key_getsecurity),
7269 #ifdef CONFIG_KEY_NOTIFICATIONS
7270 LSM_HOOK_INIT(watch_key, selinux_watch_key),
7275 LSM_HOOK_INIT(audit_rule_known, selinux_audit_rule_known),
7276 LSM_HOOK_INIT(audit_rule_match, selinux_audit_rule_match),
7277 LSM_HOOK_INIT(audit_rule_free, selinux_audit_rule_free),
7280 #ifdef CONFIG_BPF_SYSCALL
7281 LSM_HOOK_INIT(bpf, selinux_bpf),
7282 LSM_HOOK_INIT(bpf_map, selinux_bpf_map),
7283 LSM_HOOK_INIT(bpf_prog, selinux_bpf_prog),
7284 LSM_HOOK_INIT(bpf_map_free_security, selinux_bpf_map_free),
7285 LSM_HOOK_INIT(bpf_prog_free_security, selinux_bpf_prog_free),
7288 #ifdef CONFIG_PERF_EVENTS
7289 LSM_HOOK_INIT(perf_event_open, selinux_perf_event_open),
7290 LSM_HOOK_INIT(perf_event_free, selinux_perf_event_free),
7291 LSM_HOOK_INIT(perf_event_read, selinux_perf_event_read),
7292 LSM_HOOK_INIT(perf_event_write, selinux_perf_event_write),
7295 #ifdef CONFIG_IO_URING
7296 LSM_HOOK_INIT(uring_override_creds, selinux_uring_override_creds),
7297 LSM_HOOK_INIT(uring_sqpoll, selinux_uring_sqpoll),
7301 * PUT "CLONING" (ACCESSING + ALLOCATING) HOOKS HERE
7303 LSM_HOOK_INIT(fs_context_dup, selinux_fs_context_dup),
7304 LSM_HOOK_INIT(fs_context_parse_param, selinux_fs_context_parse_param),
7305 LSM_HOOK_INIT(sb_eat_lsm_opts, selinux_sb_eat_lsm_opts),
7306 LSM_HOOK_INIT(sb_add_mnt_opt, selinux_add_mnt_opt),
7307 #ifdef CONFIG_SECURITY_NETWORK_XFRM
7308 LSM_HOOK_INIT(xfrm_policy_clone_security, selinux_xfrm_policy_clone),
7312 * PUT "ALLOCATING" HOOKS HERE
7314 LSM_HOOK_INIT(msg_msg_alloc_security, selinux_msg_msg_alloc_security),
7315 LSM_HOOK_INIT(msg_queue_alloc_security,
7316 selinux_msg_queue_alloc_security),
7317 LSM_HOOK_INIT(shm_alloc_security, selinux_shm_alloc_security),
7318 LSM_HOOK_INIT(sb_alloc_security, selinux_sb_alloc_security),
7319 LSM_HOOK_INIT(inode_alloc_security, selinux_inode_alloc_security),
7320 LSM_HOOK_INIT(sem_alloc_security, selinux_sem_alloc_security),
7321 LSM_HOOK_INIT(secid_to_secctx, selinux_secid_to_secctx),
7322 LSM_HOOK_INIT(inode_getsecctx, selinux_inode_getsecctx),
7323 LSM_HOOK_INIT(sk_alloc_security, selinux_sk_alloc_security),
7324 LSM_HOOK_INIT(tun_dev_alloc_security, selinux_tun_dev_alloc_security),
7325 #ifdef CONFIG_SECURITY_INFINIBAND
7326 LSM_HOOK_INIT(ib_alloc_security, selinux_ib_alloc_security),
7328 #ifdef CONFIG_SECURITY_NETWORK_XFRM
7329 LSM_HOOK_INIT(xfrm_policy_alloc_security, selinux_xfrm_policy_alloc),
7330 LSM_HOOK_INIT(xfrm_state_alloc, selinux_xfrm_state_alloc),
7331 LSM_HOOK_INIT(xfrm_state_alloc_acquire,
7332 selinux_xfrm_state_alloc_acquire),
7335 LSM_HOOK_INIT(key_alloc, selinux_key_alloc),
7338 LSM_HOOK_INIT(audit_rule_init, selinux_audit_rule_init),
7340 #ifdef CONFIG_BPF_SYSCALL
7341 LSM_HOOK_INIT(bpf_map_alloc_security, selinux_bpf_map_alloc),
7342 LSM_HOOK_INIT(bpf_prog_alloc_security, selinux_bpf_prog_alloc),
7344 #ifdef CONFIG_PERF_EVENTS
7345 LSM_HOOK_INIT(perf_event_alloc, selinux_perf_event_alloc),
7349 static __init int selinux_init(void)
7351 pr_info("SELinux: Initializing.\n");
7353 memset(&selinux_state, 0, sizeof(selinux_state));
7354 enforcing_set(&selinux_state, selinux_enforcing_boot);
7355 checkreqprot_set(&selinux_state, selinux_checkreqprot_boot);
7356 selinux_avc_init(&selinux_state.avc);
7357 mutex_init(&selinux_state.status_lock);
7358 mutex_init(&selinux_state.policy_mutex);
7360 /* Set the security state for the initial task. */
7361 cred_init_security();
7363 default_noexec = !(VM_DATA_DEFAULT_FLAGS & VM_EXEC);
7369 ebitmap_cache_init();
7371 hashtab_cache_init();
7373 security_add_hooks(selinux_hooks, ARRAY_SIZE(selinux_hooks), "selinux");
7375 if (avc_add_callback(selinux_netcache_avc_callback, AVC_CALLBACK_RESET))
7376 panic("SELinux: Unable to register AVC netcache callback\n");
7378 if (avc_add_callback(selinux_lsm_notifier_avc_callback, AVC_CALLBACK_RESET))
7379 panic("SELinux: Unable to register AVC LSM notifier callback\n");
7381 if (selinux_enforcing_boot)
7382 pr_debug("SELinux: Starting in enforcing mode\n");
7384 pr_debug("SELinux: Starting in permissive mode\n");
7386 fs_validate_description("selinux", selinux_fs_parameters);
7391 static void delayed_superblock_init(struct super_block *sb, void *unused)
7393 selinux_set_mnt_opts(sb, NULL, 0, NULL);
7396 void selinux_complete_init(void)
7398 pr_debug("SELinux: Completing initialization.\n");
7400 /* Set up any superblocks initialized prior to the policy load. */
7401 pr_debug("SELinux: Setting up existing superblocks.\n");
7402 iterate_supers(delayed_superblock_init, NULL);
7405 /* SELinux requires early initialization in order to label
7406 all processes and objects when they are created. */
7407 DEFINE_LSM(selinux) = {
7409 .flags = LSM_FLAG_LEGACY_MAJOR | LSM_FLAG_EXCLUSIVE,
7410 .enabled = &selinux_enabled_boot,
7411 .blobs = &selinux_blob_sizes,
7412 .init = selinux_init,
7415 #if defined(CONFIG_NETFILTER)
7417 static const struct nf_hook_ops selinux_nf_ops[] = {
7419 .hook = selinux_ip_postroute,
7421 .hooknum = NF_INET_POST_ROUTING,
7422 .priority = NF_IP_PRI_SELINUX_LAST,
7425 .hook = selinux_ip_forward,
7427 .hooknum = NF_INET_FORWARD,
7428 .priority = NF_IP_PRI_SELINUX_FIRST,
7431 .hook = selinux_ip_output,
7433 .hooknum = NF_INET_LOCAL_OUT,
7434 .priority = NF_IP_PRI_SELINUX_FIRST,
7436 #if IS_ENABLED(CONFIG_IPV6)
7438 .hook = selinux_ip_postroute,
7440 .hooknum = NF_INET_POST_ROUTING,
7441 .priority = NF_IP6_PRI_SELINUX_LAST,
7444 .hook = selinux_ip_forward,
7446 .hooknum = NF_INET_FORWARD,
7447 .priority = NF_IP6_PRI_SELINUX_FIRST,
7450 .hook = selinux_ip_output,
7452 .hooknum = NF_INET_LOCAL_OUT,
7453 .priority = NF_IP6_PRI_SELINUX_FIRST,
7458 static int __net_init selinux_nf_register(struct net *net)
7460 return nf_register_net_hooks(net, selinux_nf_ops,
7461 ARRAY_SIZE(selinux_nf_ops));
7464 static void __net_exit selinux_nf_unregister(struct net *net)
7466 nf_unregister_net_hooks(net, selinux_nf_ops,
7467 ARRAY_SIZE(selinux_nf_ops));
7470 static struct pernet_operations selinux_net_ops = {
7471 .init = selinux_nf_register,
7472 .exit = selinux_nf_unregister,
7475 static int __init selinux_nf_ip_init(void)
7479 if (!selinux_enabled_boot)
7482 pr_debug("SELinux: Registering netfilter hooks\n");
7484 err = register_pernet_subsys(&selinux_net_ops);
7486 panic("SELinux: register_pernet_subsys: error %d\n", err);
7490 __initcall(selinux_nf_ip_init);
7492 #ifdef CONFIG_SECURITY_SELINUX_DISABLE
7493 static void selinux_nf_ip_exit(void)
7495 pr_debug("SELinux: Unregistering netfilter hooks\n");
7497 unregister_pernet_subsys(&selinux_net_ops);
7501 #else /* CONFIG_NETFILTER */
7503 #ifdef CONFIG_SECURITY_SELINUX_DISABLE
7504 #define selinux_nf_ip_exit()
7507 #endif /* CONFIG_NETFILTER */
7509 #ifdef CONFIG_SECURITY_SELINUX_DISABLE
7510 int selinux_disable(struct selinux_state *state)
7512 if (selinux_initialized(state)) {
7513 /* Not permitted after initial policy load. */
7517 if (selinux_disabled(state)) {
7518 /* Only do this once. */
7522 selinux_mark_disabled(state);
7524 pr_info("SELinux: Disabled at runtime.\n");
7527 * Unregister netfilter hooks.
7528 * Must be done before security_delete_hooks() to avoid breaking
7531 selinux_nf_ip_exit();
7533 security_delete_hooks(selinux_hooks, ARRAY_SIZE(selinux_hooks));
7535 /* Try to destroy the avc node cache */
7538 /* Unregister selinuxfs. */