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.
7 * Authors: Stephen Smalley, <sds@tycho.nsa.gov>
8 * Chris Vance, <cvance@nai.com>
9 * Wayne Salamon, <wsalamon@nai.com>
10 * James Morris <jmorris@redhat.com>
12 * Copyright (C) 2001,2002 Networks Associates Technology, Inc.
13 * Copyright (C) 2003-2008 Red Hat, Inc., James Morris <jmorris@redhat.com>
14 * Eric Paris <eparis@redhat.com>
15 * Copyright (C) 2004-2005 Trusted Computer Solutions, Inc.
16 * <dgoeddel@trustedcs.com>
17 * Copyright (C) 2006, 2007, 2009 Hewlett-Packard Development Company, L.P.
18 * Paul Moore <paul@paul-moore.com>
19 * Copyright (C) 2007 Hitachi Software Engineering Co., Ltd.
20 * Yuichi Nakamura <ynakam@hitachisoft.jp>
21 * Copyright (C) 2016 Mellanox Technologies
24 #include <linux/init.h>
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;
364 static void selinux_free_mnt_opts(void *mnt_opts)
366 struct selinux_mnt_opts *opts = mnt_opts;
367 kfree(opts->fscontext);
368 kfree(opts->context);
369 kfree(opts->rootcontext);
370 kfree(opts->defcontext);
383 #define A(s, has_arg) {#s, sizeof(#s) - 1, Opt_##s, has_arg}
393 A(rootcontext, true),
398 static int match_opt_prefix(char *s, int l, char **arg)
402 for (i = 0; i < ARRAY_SIZE(tokens); i++) {
403 size_t len = tokens[i].len;
404 if (len > l || memcmp(s, tokens[i].name, len))
406 if (tokens[i].has_arg) {
407 if (len == l || s[len] != '=')
412 return tokens[i].opt;
417 #define SEL_MOUNT_FAIL_MSG "SELinux: duplicate or incompatible mount options\n"
419 static int may_context_mount_sb_relabel(u32 sid,
420 struct superblock_security_struct *sbsec,
421 const struct cred *cred)
423 const struct task_security_struct *tsec = selinux_cred(cred);
426 rc = avc_has_perm(&selinux_state,
427 tsec->sid, sbsec->sid, SECCLASS_FILESYSTEM,
428 FILESYSTEM__RELABELFROM, NULL);
432 rc = avc_has_perm(&selinux_state,
433 tsec->sid, sid, SECCLASS_FILESYSTEM,
434 FILESYSTEM__RELABELTO, NULL);
438 static int may_context_mount_inode_relabel(u32 sid,
439 struct superblock_security_struct *sbsec,
440 const struct cred *cred)
442 const struct task_security_struct *tsec = selinux_cred(cred);
444 rc = avc_has_perm(&selinux_state,
445 tsec->sid, sbsec->sid, SECCLASS_FILESYSTEM,
446 FILESYSTEM__RELABELFROM, NULL);
450 rc = avc_has_perm(&selinux_state,
451 sid, sbsec->sid, SECCLASS_FILESYSTEM,
452 FILESYSTEM__ASSOCIATE, NULL);
456 static int selinux_is_genfs_special_handling(struct super_block *sb)
458 /* Special handling. Genfs but also in-core setxattr handler */
459 return !strcmp(sb->s_type->name, "sysfs") ||
460 !strcmp(sb->s_type->name, "pstore") ||
461 !strcmp(sb->s_type->name, "debugfs") ||
462 !strcmp(sb->s_type->name, "tracefs") ||
463 !strcmp(sb->s_type->name, "rootfs") ||
464 (selinux_policycap_cgroupseclabel() &&
465 (!strcmp(sb->s_type->name, "cgroup") ||
466 !strcmp(sb->s_type->name, "cgroup2")));
469 static int selinux_is_sblabel_mnt(struct super_block *sb)
471 struct superblock_security_struct *sbsec = selinux_superblock(sb);
474 * IMPORTANT: Double-check logic in this function when adding a new
475 * SECURITY_FS_USE_* definition!
477 BUILD_BUG_ON(SECURITY_FS_USE_MAX != 7);
479 switch (sbsec->behavior) {
480 case SECURITY_FS_USE_XATTR:
481 case SECURITY_FS_USE_TRANS:
482 case SECURITY_FS_USE_TASK:
483 case SECURITY_FS_USE_NATIVE:
486 case SECURITY_FS_USE_GENFS:
487 return selinux_is_genfs_special_handling(sb);
489 /* Never allow relabeling on context mounts */
490 case SECURITY_FS_USE_MNTPOINT:
491 case SECURITY_FS_USE_NONE:
497 static int sb_check_xattr_support(struct super_block *sb)
499 struct superblock_security_struct *sbsec = selinux_superblock(sb);
500 struct dentry *root = sb->s_root;
501 struct inode *root_inode = d_backing_inode(root);
506 * Make sure that the xattr handler exists and that no
507 * error other than -ENODATA is returned by getxattr on
508 * the root directory. -ENODATA is ok, as this may be
509 * the first boot of the SELinux kernel before we have
510 * assigned xattr values to the filesystem.
512 if (!(root_inode->i_opflags & IOP_XATTR)) {
513 pr_warn("SELinux: (dev %s, type %s) has no xattr support\n",
514 sb->s_id, sb->s_type->name);
518 rc = __vfs_getxattr(root, root_inode, XATTR_NAME_SELINUX, NULL, 0);
519 if (rc < 0 && rc != -ENODATA) {
520 if (rc == -EOPNOTSUPP) {
521 pr_warn("SELinux: (dev %s, type %s) has no security xattr handler\n",
522 sb->s_id, sb->s_type->name);
525 pr_warn("SELinux: (dev %s, type %s) getxattr errno %d\n",
526 sb->s_id, sb->s_type->name, -rc);
533 /* No xattr support - try to fallback to genfs if possible. */
534 rc = security_genfs_sid(&selinux_state, sb->s_type->name, "/",
539 pr_warn("SELinux: (dev %s, type %s) falling back to genfs\n",
540 sb->s_id, sb->s_type->name);
541 sbsec->behavior = SECURITY_FS_USE_GENFS;
546 static int sb_finish_set_opts(struct super_block *sb)
548 struct superblock_security_struct *sbsec = selinux_superblock(sb);
549 struct dentry *root = sb->s_root;
550 struct inode *root_inode = d_backing_inode(root);
553 if (sbsec->behavior == SECURITY_FS_USE_XATTR) {
554 rc = sb_check_xattr_support(sb);
559 sbsec->flags |= SE_SBINITIALIZED;
562 * Explicitly set or clear SBLABEL_MNT. It's not sufficient to simply
563 * leave the flag untouched because sb_clone_mnt_opts might be handing
564 * us a superblock that needs the flag to be cleared.
566 if (selinux_is_sblabel_mnt(sb))
567 sbsec->flags |= SBLABEL_MNT;
569 sbsec->flags &= ~SBLABEL_MNT;
571 /* Initialize the root inode. */
572 rc = inode_doinit_with_dentry(root_inode, root);
574 /* Initialize any other inodes associated with the superblock, e.g.
575 inodes created prior to initial policy load or inodes created
576 during get_sb by a pseudo filesystem that directly
578 spin_lock(&sbsec->isec_lock);
579 while (!list_empty(&sbsec->isec_head)) {
580 struct inode_security_struct *isec =
581 list_first_entry(&sbsec->isec_head,
582 struct inode_security_struct, list);
583 struct inode *inode = isec->inode;
584 list_del_init(&isec->list);
585 spin_unlock(&sbsec->isec_lock);
586 inode = igrab(inode);
588 if (!IS_PRIVATE(inode))
589 inode_doinit_with_dentry(inode, NULL);
592 spin_lock(&sbsec->isec_lock);
594 spin_unlock(&sbsec->isec_lock);
598 static int bad_option(struct superblock_security_struct *sbsec, char flag,
599 u32 old_sid, u32 new_sid)
601 char mnt_flags = sbsec->flags & SE_MNTMASK;
603 /* check if the old mount command had the same options */
604 if (sbsec->flags & SE_SBINITIALIZED)
605 if (!(sbsec->flags & flag) ||
606 (old_sid != new_sid))
609 /* check if we were passed the same options twice,
610 * aka someone passed context=a,context=b
612 if (!(sbsec->flags & SE_SBINITIALIZED))
613 if (mnt_flags & flag)
618 static int parse_sid(struct super_block *sb, const char *s, u32 *sid)
620 int rc = security_context_str_to_sid(&selinux_state, s,
623 pr_warn("SELinux: security_context_str_to_sid"
624 "(%s) failed for (dev %s, type %s) errno=%d\n",
625 s, sb ? sb->s_id : "?", sb ? sb->s_type->name : "?", rc);
630 * Allow filesystems with binary mount data to explicitly set mount point
631 * labeling information.
633 static int selinux_set_mnt_opts(struct super_block *sb,
635 unsigned long kern_flags,
636 unsigned long *set_kern_flags)
638 const struct cred *cred = current_cred();
639 struct superblock_security_struct *sbsec = selinux_superblock(sb);
640 struct dentry *root = sb->s_root;
641 struct selinux_mnt_opts *opts = mnt_opts;
642 struct inode_security_struct *root_isec;
643 u32 fscontext_sid = 0, context_sid = 0, rootcontext_sid = 0;
644 u32 defcontext_sid = 0;
647 mutex_lock(&sbsec->lock);
649 if (!selinux_initialized(&selinux_state)) {
651 /* Defer initialization until selinux_complete_init,
652 after the initial policy is loaded and the security
653 server is ready to handle calls. */
657 pr_warn("SELinux: Unable to set superblock options "
658 "before the security server is initialized\n");
661 if (kern_flags && !set_kern_flags) {
662 /* Specifying internal flags without providing a place to
663 * place the results is not allowed */
669 * Binary mount data FS will come through this function twice. Once
670 * from an explicit call and once from the generic calls from the vfs.
671 * Since the generic VFS calls will not contain any security mount data
672 * we need to skip the double mount verification.
674 * This does open a hole in which we will not notice if the first
675 * mount using this sb set explict options and a second mount using
676 * this sb does not set any security options. (The first options
677 * will be used for both mounts)
679 if ((sbsec->flags & SE_SBINITIALIZED) && (sb->s_type->fs_flags & FS_BINARY_MOUNTDATA)
683 root_isec = backing_inode_security_novalidate(root);
686 * parse the mount options, check if they are valid sids.
687 * also check if someone is trying to mount the same sb more
688 * than once with different security options.
691 if (opts->fscontext) {
692 rc = parse_sid(sb, opts->fscontext, &fscontext_sid);
695 if (bad_option(sbsec, FSCONTEXT_MNT, sbsec->sid,
697 goto out_double_mount;
698 sbsec->flags |= FSCONTEXT_MNT;
701 rc = parse_sid(sb, opts->context, &context_sid);
704 if (bad_option(sbsec, CONTEXT_MNT, sbsec->mntpoint_sid,
706 goto out_double_mount;
707 sbsec->flags |= CONTEXT_MNT;
709 if (opts->rootcontext) {
710 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);
722 if (bad_option(sbsec, DEFCONTEXT_MNT, sbsec->def_sid,
724 goto out_double_mount;
725 sbsec->flags |= DEFCONTEXT_MNT;
729 if (sbsec->flags & SE_SBINITIALIZED) {
730 /* previously mounted with options, but not on this attempt? */
731 if ((sbsec->flags & SE_MNTMASK) && !opts)
732 goto out_double_mount;
737 if (strcmp(sb->s_type->name, "proc") == 0)
738 sbsec->flags |= SE_SBPROC | SE_SBGENFS;
740 if (!strcmp(sb->s_type->name, "debugfs") ||
741 !strcmp(sb->s_type->name, "tracefs") ||
742 !strcmp(sb->s_type->name, "binder") ||
743 !strcmp(sb->s_type->name, "bpf") ||
744 !strcmp(sb->s_type->name, "pstore"))
745 sbsec->flags |= SE_SBGENFS;
747 if (!strcmp(sb->s_type->name, "sysfs") ||
748 !strcmp(sb->s_type->name, "cgroup") ||
749 !strcmp(sb->s_type->name, "cgroup2"))
750 sbsec->flags |= SE_SBGENFS | SE_SBGENFS_XATTR;
752 if (!sbsec->behavior) {
754 * Determine the labeling behavior to use for this
757 rc = security_fs_use(&selinux_state, sb);
759 pr_warn("%s: security_fs_use(%s) returned %d\n",
760 __func__, sb->s_type->name, rc);
766 * If this is a user namespace mount and the filesystem type is not
767 * explicitly whitelisted, then no contexts are allowed on the command
768 * line and security labels must be ignored.
770 if (sb->s_user_ns != &init_user_ns &&
771 strcmp(sb->s_type->name, "tmpfs") &&
772 strcmp(sb->s_type->name, "ramfs") &&
773 strcmp(sb->s_type->name, "devpts") &&
774 strcmp(sb->s_type->name, "overlay")) {
775 if (context_sid || fscontext_sid || rootcontext_sid ||
780 if (sbsec->behavior == SECURITY_FS_USE_XATTR) {
781 sbsec->behavior = SECURITY_FS_USE_MNTPOINT;
782 rc = security_transition_sid(&selinux_state,
786 &sbsec->mntpoint_sid);
793 /* sets the context of the superblock for the fs being mounted. */
795 rc = may_context_mount_sb_relabel(fscontext_sid, sbsec, cred);
799 sbsec->sid = fscontext_sid;
803 * Switch to using mount point labeling behavior.
804 * sets the label used on all file below the mountpoint, and will set
805 * the superblock context if not already set.
807 if (kern_flags & SECURITY_LSM_NATIVE_LABELS && !context_sid) {
808 sbsec->behavior = SECURITY_FS_USE_NATIVE;
809 *set_kern_flags |= SECURITY_LSM_NATIVE_LABELS;
813 if (!fscontext_sid) {
814 rc = may_context_mount_sb_relabel(context_sid, sbsec,
818 sbsec->sid = context_sid;
820 rc = may_context_mount_inode_relabel(context_sid, sbsec,
825 if (!rootcontext_sid)
826 rootcontext_sid = context_sid;
828 sbsec->mntpoint_sid = context_sid;
829 sbsec->behavior = SECURITY_FS_USE_MNTPOINT;
832 if (rootcontext_sid) {
833 rc = may_context_mount_inode_relabel(rootcontext_sid, sbsec,
838 root_isec->sid = rootcontext_sid;
839 root_isec->initialized = LABEL_INITIALIZED;
842 if (defcontext_sid) {
843 if (sbsec->behavior != SECURITY_FS_USE_XATTR &&
844 sbsec->behavior != SECURITY_FS_USE_NATIVE) {
846 pr_warn("SELinux: defcontext option is "
847 "invalid for this filesystem type\n");
851 if (defcontext_sid != sbsec->def_sid) {
852 rc = may_context_mount_inode_relabel(defcontext_sid,
858 sbsec->def_sid = defcontext_sid;
862 rc = sb_finish_set_opts(sb);
864 mutex_unlock(&sbsec->lock);
868 pr_warn("SELinux: mount invalid. Same superblock, different "
869 "security settings for (dev %s, type %s)\n", sb->s_id,
874 static int selinux_cmp_sb_context(const struct super_block *oldsb,
875 const struct super_block *newsb)
877 struct superblock_security_struct *old = selinux_superblock(oldsb);
878 struct superblock_security_struct *new = selinux_superblock(newsb);
879 char oldflags = old->flags & SE_MNTMASK;
880 char newflags = new->flags & SE_MNTMASK;
882 if (oldflags != newflags)
884 if ((oldflags & FSCONTEXT_MNT) && old->sid != new->sid)
886 if ((oldflags & CONTEXT_MNT) && old->mntpoint_sid != new->mntpoint_sid)
888 if ((oldflags & DEFCONTEXT_MNT) && old->def_sid != new->def_sid)
890 if (oldflags & ROOTCONTEXT_MNT) {
891 struct inode_security_struct *oldroot = backing_inode_security(oldsb->s_root);
892 struct inode_security_struct *newroot = backing_inode_security(newsb->s_root);
893 if (oldroot->sid != newroot->sid)
898 pr_warn("SELinux: mount invalid. Same superblock, "
899 "different security settings for (dev %s, "
900 "type %s)\n", newsb->s_id, newsb->s_type->name);
904 static int selinux_sb_clone_mnt_opts(const struct super_block *oldsb,
905 struct super_block *newsb,
906 unsigned long kern_flags,
907 unsigned long *set_kern_flags)
910 const struct superblock_security_struct *oldsbsec =
911 selinux_superblock(oldsb);
912 struct superblock_security_struct *newsbsec = selinux_superblock(newsb);
914 int set_fscontext = (oldsbsec->flags & FSCONTEXT_MNT);
915 int set_context = (oldsbsec->flags & CONTEXT_MNT);
916 int set_rootcontext = (oldsbsec->flags & ROOTCONTEXT_MNT);
919 * if the parent was able to be mounted it clearly had no special lsm
920 * mount options. thus we can safely deal with this superblock later
922 if (!selinux_initialized(&selinux_state))
926 * Specifying internal flags without providing a place to
927 * place the results is not allowed.
929 if (kern_flags && !set_kern_flags)
932 /* how can we clone if the old one wasn't set up?? */
933 BUG_ON(!(oldsbsec->flags & SE_SBINITIALIZED));
935 /* if fs is reusing a sb, make sure that the contexts match */
936 if (newsbsec->flags & SE_SBINITIALIZED) {
937 if ((kern_flags & SECURITY_LSM_NATIVE_LABELS) && !set_context)
938 *set_kern_flags |= SECURITY_LSM_NATIVE_LABELS;
939 return selinux_cmp_sb_context(oldsb, newsb);
942 mutex_lock(&newsbsec->lock);
944 newsbsec->flags = oldsbsec->flags;
946 newsbsec->sid = oldsbsec->sid;
947 newsbsec->def_sid = oldsbsec->def_sid;
948 newsbsec->behavior = oldsbsec->behavior;
950 if (newsbsec->behavior == SECURITY_FS_USE_NATIVE &&
951 !(kern_flags & SECURITY_LSM_NATIVE_LABELS) && !set_context) {
952 rc = security_fs_use(&selinux_state, newsb);
957 if (kern_flags & SECURITY_LSM_NATIVE_LABELS && !set_context) {
958 newsbsec->behavior = SECURITY_FS_USE_NATIVE;
959 *set_kern_flags |= SECURITY_LSM_NATIVE_LABELS;
963 u32 sid = oldsbsec->mntpoint_sid;
967 if (!set_rootcontext) {
968 struct inode_security_struct *newisec = backing_inode_security(newsb->s_root);
971 newsbsec->mntpoint_sid = sid;
973 if (set_rootcontext) {
974 const struct inode_security_struct *oldisec = backing_inode_security(oldsb->s_root);
975 struct inode_security_struct *newisec = backing_inode_security(newsb->s_root);
977 newisec->sid = oldisec->sid;
980 sb_finish_set_opts(newsb);
982 mutex_unlock(&newsbsec->lock);
986 static int selinux_add_opt(int token, const char *s, void **mnt_opts)
988 struct selinux_mnt_opts *opts = *mnt_opts;
989 bool is_alloc_opts = false;
991 if (token == Opt_seclabel) /* eaten and completely ignored */
998 opts = kzalloc(sizeof(struct selinux_mnt_opts), GFP_KERNEL);
1002 is_alloc_opts = true;
1007 if (opts->context || opts->defcontext)
1010 if (selinux_initialized(&selinux_state))
1011 parse_sid(NULL, s, &opts->context_sid);
1014 if (opts->fscontext)
1016 opts->fscontext = s;
1017 if (selinux_initialized(&selinux_state))
1018 parse_sid(NULL, s, &opts->fscontext_sid);
1020 case Opt_rootcontext:
1021 if (opts->rootcontext)
1023 opts->rootcontext = s;
1024 if (selinux_initialized(&selinux_state))
1025 parse_sid(NULL, s, &opts->rootcontext_sid);
1027 case Opt_defcontext:
1028 if (opts->context || opts->defcontext)
1030 opts->defcontext = s;
1031 if (selinux_initialized(&selinux_state))
1032 parse_sid(NULL, s, &opts->defcontext_sid);
1037 if (is_alloc_opts) {
1041 pr_warn(SEL_MOUNT_FAIL_MSG);
1045 static int selinux_add_mnt_opt(const char *option, const char *val, int len,
1048 int token = Opt_error;
1051 for (i = 0; i < ARRAY_SIZE(tokens); i++) {
1052 if (strcmp(option, tokens[i].name) == 0) {
1053 token = tokens[i].opt;
1058 if (token == Opt_error)
1061 if (token != Opt_seclabel) {
1062 val = kmemdup_nul(val, len, GFP_KERNEL);
1068 rc = selinux_add_opt(token, val, mnt_opts);
1077 selinux_free_mnt_opts(*mnt_opts);
1083 static int show_sid(struct seq_file *m, u32 sid)
1085 char *context = NULL;
1089 rc = security_sid_to_context(&selinux_state, sid,
1092 bool has_comma = context && strchr(context, ',');
1097 seq_escape(m, context, "\"\n\\");
1105 static int selinux_sb_show_options(struct seq_file *m, struct super_block *sb)
1107 struct superblock_security_struct *sbsec = selinux_superblock(sb);
1110 if (!(sbsec->flags & SE_SBINITIALIZED))
1113 if (!selinux_initialized(&selinux_state))
1116 if (sbsec->flags & FSCONTEXT_MNT) {
1118 seq_puts(m, FSCONTEXT_STR);
1119 rc = show_sid(m, sbsec->sid);
1123 if (sbsec->flags & CONTEXT_MNT) {
1125 seq_puts(m, CONTEXT_STR);
1126 rc = show_sid(m, sbsec->mntpoint_sid);
1130 if (sbsec->flags & DEFCONTEXT_MNT) {
1132 seq_puts(m, DEFCONTEXT_STR);
1133 rc = show_sid(m, sbsec->def_sid);
1137 if (sbsec->flags & ROOTCONTEXT_MNT) {
1138 struct dentry *root = sb->s_root;
1139 struct inode_security_struct *isec = backing_inode_security(root);
1141 seq_puts(m, ROOTCONTEXT_STR);
1142 rc = show_sid(m, isec->sid);
1146 if (sbsec->flags & SBLABEL_MNT) {
1148 seq_puts(m, SECLABEL_STR);
1153 static inline u16 inode_mode_to_security_class(umode_t mode)
1155 switch (mode & S_IFMT) {
1157 return SECCLASS_SOCK_FILE;
1159 return SECCLASS_LNK_FILE;
1161 return SECCLASS_FILE;
1163 return SECCLASS_BLK_FILE;
1165 return SECCLASS_DIR;
1167 return SECCLASS_CHR_FILE;
1169 return SECCLASS_FIFO_FILE;
1173 return SECCLASS_FILE;
1176 static inline int default_protocol_stream(int protocol)
1178 return (protocol == IPPROTO_IP || protocol == IPPROTO_TCP ||
1179 protocol == IPPROTO_MPTCP);
1182 static inline int default_protocol_dgram(int protocol)
1184 return (protocol == IPPROTO_IP || protocol == IPPROTO_UDP);
1187 static inline u16 socket_type_to_security_class(int family, int type, int protocol)
1189 int extsockclass = selinux_policycap_extsockclass();
1195 case SOCK_SEQPACKET:
1196 return SECCLASS_UNIX_STREAM_SOCKET;
1199 return SECCLASS_UNIX_DGRAM_SOCKET;
1206 case SOCK_SEQPACKET:
1207 if (default_protocol_stream(protocol))
1208 return SECCLASS_TCP_SOCKET;
1209 else if (extsockclass && protocol == IPPROTO_SCTP)
1210 return SECCLASS_SCTP_SOCKET;
1212 return SECCLASS_RAWIP_SOCKET;
1214 if (default_protocol_dgram(protocol))
1215 return SECCLASS_UDP_SOCKET;
1216 else if (extsockclass && (protocol == IPPROTO_ICMP ||
1217 protocol == IPPROTO_ICMPV6))
1218 return SECCLASS_ICMP_SOCKET;
1220 return SECCLASS_RAWIP_SOCKET;
1222 return SECCLASS_DCCP_SOCKET;
1224 return SECCLASS_RAWIP_SOCKET;
1230 return SECCLASS_NETLINK_ROUTE_SOCKET;
1231 case NETLINK_SOCK_DIAG:
1232 return SECCLASS_NETLINK_TCPDIAG_SOCKET;
1234 return SECCLASS_NETLINK_NFLOG_SOCKET;
1236 return SECCLASS_NETLINK_XFRM_SOCKET;
1237 case NETLINK_SELINUX:
1238 return SECCLASS_NETLINK_SELINUX_SOCKET;
1240 return SECCLASS_NETLINK_ISCSI_SOCKET;
1242 return SECCLASS_NETLINK_AUDIT_SOCKET;
1243 case NETLINK_FIB_LOOKUP:
1244 return SECCLASS_NETLINK_FIB_LOOKUP_SOCKET;
1245 case NETLINK_CONNECTOR:
1246 return SECCLASS_NETLINK_CONNECTOR_SOCKET;
1247 case NETLINK_NETFILTER:
1248 return SECCLASS_NETLINK_NETFILTER_SOCKET;
1249 case NETLINK_DNRTMSG:
1250 return SECCLASS_NETLINK_DNRT_SOCKET;
1251 case NETLINK_KOBJECT_UEVENT:
1252 return SECCLASS_NETLINK_KOBJECT_UEVENT_SOCKET;
1253 case NETLINK_GENERIC:
1254 return SECCLASS_NETLINK_GENERIC_SOCKET;
1255 case NETLINK_SCSITRANSPORT:
1256 return SECCLASS_NETLINK_SCSITRANSPORT_SOCKET;
1258 return SECCLASS_NETLINK_RDMA_SOCKET;
1259 case NETLINK_CRYPTO:
1260 return SECCLASS_NETLINK_CRYPTO_SOCKET;
1262 return SECCLASS_NETLINK_SOCKET;
1265 return SECCLASS_PACKET_SOCKET;
1267 return SECCLASS_KEY_SOCKET;
1269 return SECCLASS_APPLETALK_SOCKET;
1275 return SECCLASS_AX25_SOCKET;
1277 return SECCLASS_IPX_SOCKET;
1279 return SECCLASS_NETROM_SOCKET;
1281 return SECCLASS_ATMPVC_SOCKET;
1283 return SECCLASS_X25_SOCKET;
1285 return SECCLASS_ROSE_SOCKET;
1287 return SECCLASS_DECNET_SOCKET;
1289 return SECCLASS_ATMSVC_SOCKET;
1291 return SECCLASS_RDS_SOCKET;
1293 return SECCLASS_IRDA_SOCKET;
1295 return SECCLASS_PPPOX_SOCKET;
1297 return SECCLASS_LLC_SOCKET;
1299 return SECCLASS_CAN_SOCKET;
1301 return SECCLASS_TIPC_SOCKET;
1303 return SECCLASS_BLUETOOTH_SOCKET;
1305 return SECCLASS_IUCV_SOCKET;
1307 return SECCLASS_RXRPC_SOCKET;
1309 return SECCLASS_ISDN_SOCKET;
1311 return SECCLASS_PHONET_SOCKET;
1313 return SECCLASS_IEEE802154_SOCKET;
1315 return SECCLASS_CAIF_SOCKET;
1317 return SECCLASS_ALG_SOCKET;
1319 return SECCLASS_NFC_SOCKET;
1321 return SECCLASS_VSOCK_SOCKET;
1323 return SECCLASS_KCM_SOCKET;
1325 return SECCLASS_QIPCRTR_SOCKET;
1327 return SECCLASS_SMC_SOCKET;
1329 return SECCLASS_XDP_SOCKET;
1331 return SECCLASS_MCTP_SOCKET;
1333 #error New address family defined, please update this function.
1338 return SECCLASS_SOCKET;
1341 static int selinux_genfs_get_sid(struct dentry *dentry,
1347 struct super_block *sb = dentry->d_sb;
1348 char *buffer, *path;
1350 buffer = (char *)__get_free_page(GFP_KERNEL);
1354 path = dentry_path_raw(dentry, buffer, PAGE_SIZE);
1358 if (flags & SE_SBPROC) {
1359 /* each process gets a /proc/PID/ entry. Strip off the
1360 * PID part to get a valid selinux labeling.
1361 * e.g. /proc/1/net/rpc/nfs -> /net/rpc/nfs */
1362 while (path[1] >= '0' && path[1] <= '9') {
1367 rc = security_genfs_sid(&selinux_state, sb->s_type->name,
1369 if (rc == -ENOENT) {
1370 /* No match in policy, mark as unlabeled. */
1371 *sid = SECINITSID_UNLABELED;
1375 free_page((unsigned long)buffer);
1379 static int inode_doinit_use_xattr(struct inode *inode, struct dentry *dentry,
1380 u32 def_sid, u32 *sid)
1382 #define INITCONTEXTLEN 255
1387 len = INITCONTEXTLEN;
1388 context = kmalloc(len + 1, GFP_NOFS);
1392 context[len] = '\0';
1393 rc = __vfs_getxattr(dentry, inode, XATTR_NAME_SELINUX, context, len);
1394 if (rc == -ERANGE) {
1397 /* Need a larger buffer. Query for the right size. */
1398 rc = __vfs_getxattr(dentry, inode, XATTR_NAME_SELINUX, NULL, 0);
1403 context = kmalloc(len + 1, GFP_NOFS);
1407 context[len] = '\0';
1408 rc = __vfs_getxattr(dentry, inode, XATTR_NAME_SELINUX,
1413 if (rc != -ENODATA) {
1414 pr_warn("SELinux: %s: getxattr returned %d for dev=%s ino=%ld\n",
1415 __func__, -rc, inode->i_sb->s_id, inode->i_ino);
1422 rc = security_context_to_sid_default(&selinux_state, context, rc, sid,
1425 char *dev = inode->i_sb->s_id;
1426 unsigned long ino = inode->i_ino;
1428 if (rc == -EINVAL) {
1429 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",
1432 pr_warn("SELinux: %s: context_to_sid(%s) returned %d for dev=%s ino=%ld\n",
1433 __func__, context, -rc, dev, ino);
1440 /* The inode's security attributes must be initialized before first use. */
1441 static int inode_doinit_with_dentry(struct inode *inode, struct dentry *opt_dentry)
1443 struct superblock_security_struct *sbsec = NULL;
1444 struct inode_security_struct *isec = selinux_inode(inode);
1445 u32 task_sid, sid = 0;
1447 struct dentry *dentry;
1450 if (isec->initialized == LABEL_INITIALIZED)
1453 spin_lock(&isec->lock);
1454 if (isec->initialized == LABEL_INITIALIZED)
1457 if (isec->sclass == SECCLASS_FILE)
1458 isec->sclass = inode_mode_to_security_class(inode->i_mode);
1460 sbsec = selinux_superblock(inode->i_sb);
1461 if (!(sbsec->flags & SE_SBINITIALIZED)) {
1462 /* Defer initialization until selinux_complete_init,
1463 after the initial policy is loaded and the security
1464 server is ready to handle calls. */
1465 spin_lock(&sbsec->isec_lock);
1466 if (list_empty(&isec->list))
1467 list_add(&isec->list, &sbsec->isec_head);
1468 spin_unlock(&sbsec->isec_lock);
1472 sclass = isec->sclass;
1473 task_sid = isec->task_sid;
1475 isec->initialized = LABEL_PENDING;
1476 spin_unlock(&isec->lock);
1478 switch (sbsec->behavior) {
1479 case SECURITY_FS_USE_NATIVE:
1481 case SECURITY_FS_USE_XATTR:
1482 if (!(inode->i_opflags & IOP_XATTR)) {
1483 sid = sbsec->def_sid;
1486 /* Need a dentry, since the xattr API requires one.
1487 Life would be simpler if we could just pass the inode. */
1489 /* Called from d_instantiate or d_splice_alias. */
1490 dentry = dget(opt_dentry);
1493 * Called from selinux_complete_init, try to find a dentry.
1494 * Some filesystems really want a connected one, so try
1495 * that first. We could split SECURITY_FS_USE_XATTR in
1496 * two, depending upon that...
1498 dentry = d_find_alias(inode);
1500 dentry = d_find_any_alias(inode);
1504 * this is can be hit on boot when a file is accessed
1505 * before the policy is loaded. When we load policy we
1506 * may find inodes that have no dentry on the
1507 * sbsec->isec_head list. No reason to complain as these
1508 * will get fixed up the next time we go through
1509 * inode_doinit with a dentry, before these inodes could
1510 * be used again by userspace.
1515 rc = inode_doinit_use_xattr(inode, dentry, sbsec->def_sid,
1521 case SECURITY_FS_USE_TASK:
1524 case SECURITY_FS_USE_TRANS:
1525 /* Default to the fs SID. */
1528 /* Try to obtain a transition SID. */
1529 rc = security_transition_sid(&selinux_state, task_sid, sid,
1530 sclass, NULL, &sid);
1534 case SECURITY_FS_USE_MNTPOINT:
1535 sid = sbsec->mntpoint_sid;
1538 /* Default to the fs superblock SID. */
1541 if ((sbsec->flags & SE_SBGENFS) &&
1542 (!S_ISLNK(inode->i_mode) ||
1543 selinux_policycap_genfs_seclabel_symlinks())) {
1544 /* We must have a dentry to determine the label on
1547 /* Called from d_instantiate or
1548 * d_splice_alias. */
1549 dentry = dget(opt_dentry);
1551 /* Called from selinux_complete_init, try to
1552 * find a dentry. Some filesystems really want
1553 * a connected one, so try that first.
1555 dentry = d_find_alias(inode);
1557 dentry = d_find_any_alias(inode);
1560 * This can be hit on boot when a file is accessed
1561 * before the policy is loaded. When we load policy we
1562 * may find inodes that have no dentry on the
1563 * sbsec->isec_head list. No reason to complain as
1564 * these will get fixed up the next time we go through
1565 * inode_doinit() with a dentry, before these inodes
1566 * could be used again by userspace.
1570 rc = selinux_genfs_get_sid(dentry, sclass,
1571 sbsec->flags, &sid);
1577 if ((sbsec->flags & SE_SBGENFS_XATTR) &&
1578 (inode->i_opflags & IOP_XATTR)) {
1579 rc = inode_doinit_use_xattr(inode, dentry,
1592 spin_lock(&isec->lock);
1593 if (isec->initialized == LABEL_PENDING) {
1595 isec->initialized = LABEL_INVALID;
1598 isec->initialized = LABEL_INITIALIZED;
1603 spin_unlock(&isec->lock);
1607 spin_lock(&isec->lock);
1608 if (isec->initialized == LABEL_PENDING) {
1609 isec->initialized = LABEL_INVALID;
1612 spin_unlock(&isec->lock);
1616 /* Convert a Linux signal to an access vector. */
1617 static inline u32 signal_to_av(int sig)
1623 /* Commonly granted from child to parent. */
1624 perm = PROCESS__SIGCHLD;
1627 /* Cannot be caught or ignored */
1628 perm = PROCESS__SIGKILL;
1631 /* Cannot be caught or ignored */
1632 perm = PROCESS__SIGSTOP;
1635 /* All other signals. */
1636 perm = PROCESS__SIGNAL;
1643 #if CAP_LAST_CAP > 63
1644 #error Fix SELinux to handle capabilities > 63.
1647 /* Check whether a task is allowed to use a capability. */
1648 static int cred_has_capability(const struct cred *cred,
1649 int cap, unsigned int opts, bool initns)
1651 struct common_audit_data ad;
1652 struct av_decision avd;
1654 u32 sid = cred_sid(cred);
1655 u32 av = CAP_TO_MASK(cap);
1658 ad.type = LSM_AUDIT_DATA_CAP;
1661 switch (CAP_TO_INDEX(cap)) {
1663 sclass = initns ? SECCLASS_CAPABILITY : SECCLASS_CAP_USERNS;
1666 sclass = initns ? SECCLASS_CAPABILITY2 : SECCLASS_CAP2_USERNS;
1669 pr_err("SELinux: out of range capability %d\n", cap);
1674 rc = avc_has_perm_noaudit(&selinux_state,
1675 sid, sid, sclass, av, 0, &avd);
1676 if (!(opts & CAP_OPT_NOAUDIT)) {
1677 int rc2 = avc_audit(&selinux_state,
1678 sid, sid, sclass, av, &avd, rc, &ad);
1685 /* Check whether a task has a particular permission to an inode.
1686 The 'adp' parameter is optional and allows other audit
1687 data to be passed (e.g. the dentry). */
1688 static int inode_has_perm(const struct cred *cred,
1689 struct inode *inode,
1691 struct common_audit_data *adp)
1693 struct inode_security_struct *isec;
1696 validate_creds(cred);
1698 if (unlikely(IS_PRIVATE(inode)))
1701 sid = cred_sid(cred);
1702 isec = selinux_inode(inode);
1704 return avc_has_perm(&selinux_state,
1705 sid, isec->sid, isec->sclass, perms, adp);
1708 /* Same as inode_has_perm, but pass explicit audit data containing
1709 the dentry to help the auditing code to more easily generate the
1710 pathname if needed. */
1711 static inline int dentry_has_perm(const struct cred *cred,
1712 struct dentry *dentry,
1715 struct inode *inode = d_backing_inode(dentry);
1716 struct common_audit_data ad;
1718 ad.type = LSM_AUDIT_DATA_DENTRY;
1719 ad.u.dentry = dentry;
1720 __inode_security_revalidate(inode, dentry, true);
1721 return inode_has_perm(cred, inode, av, &ad);
1724 /* Same as inode_has_perm, but pass explicit audit data containing
1725 the path to help the auditing code to more easily generate the
1726 pathname if needed. */
1727 static inline int path_has_perm(const struct cred *cred,
1728 const struct path *path,
1731 struct inode *inode = d_backing_inode(path->dentry);
1732 struct common_audit_data ad;
1734 ad.type = LSM_AUDIT_DATA_PATH;
1736 __inode_security_revalidate(inode, path->dentry, true);
1737 return inode_has_perm(cred, inode, av, &ad);
1740 /* Same as path_has_perm, but uses the inode from the file struct. */
1741 static inline int file_path_has_perm(const struct cred *cred,
1745 struct common_audit_data ad;
1747 ad.type = LSM_AUDIT_DATA_FILE;
1749 return inode_has_perm(cred, file_inode(file), av, &ad);
1752 #ifdef CONFIG_BPF_SYSCALL
1753 static int bpf_fd_pass(struct file *file, u32 sid);
1756 /* Check whether a task can use an open file descriptor to
1757 access an inode in a given way. Check access to the
1758 descriptor itself, and then use dentry_has_perm to
1759 check a particular permission to the file.
1760 Access to the descriptor is implicitly granted if it
1761 has the same SID as the process. If av is zero, then
1762 access to the file is not checked, e.g. for cases
1763 where only the descriptor is affected like seek. */
1764 static int file_has_perm(const struct cred *cred,
1768 struct file_security_struct *fsec = selinux_file(file);
1769 struct inode *inode = file_inode(file);
1770 struct common_audit_data ad;
1771 u32 sid = cred_sid(cred);
1774 ad.type = LSM_AUDIT_DATA_FILE;
1777 if (sid != fsec->sid) {
1778 rc = avc_has_perm(&selinux_state,
1787 #ifdef CONFIG_BPF_SYSCALL
1788 rc = bpf_fd_pass(file, cred_sid(cred));
1793 /* av is zero if only checking access to the descriptor. */
1796 rc = inode_has_perm(cred, inode, av, &ad);
1803 * Determine the label for an inode that might be unioned.
1806 selinux_determine_inode_label(const struct task_security_struct *tsec,
1808 const struct qstr *name, u16 tclass,
1811 const struct superblock_security_struct *sbsec =
1812 selinux_superblock(dir->i_sb);
1814 if ((sbsec->flags & SE_SBINITIALIZED) &&
1815 (sbsec->behavior == SECURITY_FS_USE_MNTPOINT)) {
1816 *_new_isid = sbsec->mntpoint_sid;
1817 } else if ((sbsec->flags & SBLABEL_MNT) &&
1819 *_new_isid = tsec->create_sid;
1821 const struct inode_security_struct *dsec = inode_security(dir);
1822 return security_transition_sid(&selinux_state, tsec->sid,
1830 /* Check whether a task can create a file. */
1831 static int may_create(struct inode *dir,
1832 struct dentry *dentry,
1835 const struct task_security_struct *tsec = selinux_cred(current_cred());
1836 struct inode_security_struct *dsec;
1837 struct superblock_security_struct *sbsec;
1839 struct common_audit_data ad;
1842 dsec = inode_security(dir);
1843 sbsec = selinux_superblock(dir->i_sb);
1847 ad.type = LSM_AUDIT_DATA_DENTRY;
1848 ad.u.dentry = dentry;
1850 rc = avc_has_perm(&selinux_state,
1851 sid, dsec->sid, SECCLASS_DIR,
1852 DIR__ADD_NAME | DIR__SEARCH,
1857 rc = selinux_determine_inode_label(tsec, dir, &dentry->d_name, tclass,
1862 rc = avc_has_perm(&selinux_state,
1863 sid, newsid, tclass, FILE__CREATE, &ad);
1867 return avc_has_perm(&selinux_state,
1869 SECCLASS_FILESYSTEM,
1870 FILESYSTEM__ASSOCIATE, &ad);
1874 #define MAY_UNLINK 1
1877 /* Check whether a task can link, unlink, or rmdir a file/directory. */
1878 static int may_link(struct inode *dir,
1879 struct dentry *dentry,
1883 struct inode_security_struct *dsec, *isec;
1884 struct common_audit_data ad;
1885 u32 sid = current_sid();
1889 dsec = inode_security(dir);
1890 isec = backing_inode_security(dentry);
1892 ad.type = LSM_AUDIT_DATA_DENTRY;
1893 ad.u.dentry = dentry;
1896 av |= (kind ? DIR__REMOVE_NAME : DIR__ADD_NAME);
1897 rc = avc_has_perm(&selinux_state,
1898 sid, dsec->sid, SECCLASS_DIR, av, &ad);
1913 pr_warn("SELinux: %s: unrecognized kind %d\n",
1918 rc = avc_has_perm(&selinux_state,
1919 sid, isec->sid, isec->sclass, av, &ad);
1923 static inline int may_rename(struct inode *old_dir,
1924 struct dentry *old_dentry,
1925 struct inode *new_dir,
1926 struct dentry *new_dentry)
1928 struct inode_security_struct *old_dsec, *new_dsec, *old_isec, *new_isec;
1929 struct common_audit_data ad;
1930 u32 sid = current_sid();
1932 int old_is_dir, new_is_dir;
1935 old_dsec = inode_security(old_dir);
1936 old_isec = backing_inode_security(old_dentry);
1937 old_is_dir = d_is_dir(old_dentry);
1938 new_dsec = inode_security(new_dir);
1940 ad.type = LSM_AUDIT_DATA_DENTRY;
1942 ad.u.dentry = old_dentry;
1943 rc = avc_has_perm(&selinux_state,
1944 sid, old_dsec->sid, SECCLASS_DIR,
1945 DIR__REMOVE_NAME | DIR__SEARCH, &ad);
1948 rc = avc_has_perm(&selinux_state,
1950 old_isec->sclass, FILE__RENAME, &ad);
1953 if (old_is_dir && new_dir != old_dir) {
1954 rc = avc_has_perm(&selinux_state,
1956 old_isec->sclass, DIR__REPARENT, &ad);
1961 ad.u.dentry = new_dentry;
1962 av = DIR__ADD_NAME | DIR__SEARCH;
1963 if (d_is_positive(new_dentry))
1964 av |= DIR__REMOVE_NAME;
1965 rc = avc_has_perm(&selinux_state,
1966 sid, new_dsec->sid, SECCLASS_DIR, av, &ad);
1969 if (d_is_positive(new_dentry)) {
1970 new_isec = backing_inode_security(new_dentry);
1971 new_is_dir = d_is_dir(new_dentry);
1972 rc = avc_has_perm(&selinux_state,
1975 (new_is_dir ? DIR__RMDIR : FILE__UNLINK), &ad);
1983 /* Check whether a task can perform a filesystem operation. */
1984 static int superblock_has_perm(const struct cred *cred,
1985 struct super_block *sb,
1987 struct common_audit_data *ad)
1989 struct superblock_security_struct *sbsec;
1990 u32 sid = cred_sid(cred);
1992 sbsec = selinux_superblock(sb);
1993 return avc_has_perm(&selinux_state,
1994 sid, sbsec->sid, SECCLASS_FILESYSTEM, perms, ad);
1997 /* Convert a Linux mode and permission mask to an access vector. */
1998 static inline u32 file_mask_to_av(int mode, int mask)
2002 if (!S_ISDIR(mode)) {
2003 if (mask & MAY_EXEC)
2004 av |= FILE__EXECUTE;
2005 if (mask & MAY_READ)
2008 if (mask & MAY_APPEND)
2010 else if (mask & MAY_WRITE)
2014 if (mask & MAY_EXEC)
2016 if (mask & MAY_WRITE)
2018 if (mask & MAY_READ)
2025 /* Convert a Linux file to an access vector. */
2026 static inline u32 file_to_av(struct file *file)
2030 if (file->f_mode & FMODE_READ)
2032 if (file->f_mode & FMODE_WRITE) {
2033 if (file->f_flags & O_APPEND)
2040 * Special file opened with flags 3 for ioctl-only use.
2049 * Convert a file to an access vector and include the correct
2052 static inline u32 open_file_to_av(struct file *file)
2054 u32 av = file_to_av(file);
2055 struct inode *inode = file_inode(file);
2057 if (selinux_policycap_openperm() &&
2058 inode->i_sb->s_magic != SOCKFS_MAGIC)
2064 /* Hook functions begin here. */
2066 static int selinux_binder_set_context_mgr(const struct cred *mgr)
2068 return avc_has_perm(&selinux_state,
2069 current_sid(), cred_sid(mgr), SECCLASS_BINDER,
2070 BINDER__SET_CONTEXT_MGR, NULL);
2073 static int selinux_binder_transaction(const struct cred *from,
2074 const struct cred *to)
2076 u32 mysid = current_sid();
2077 u32 fromsid = cred_sid(from);
2078 u32 tosid = cred_sid(to);
2081 if (mysid != fromsid) {
2082 rc = avc_has_perm(&selinux_state,
2083 mysid, fromsid, SECCLASS_BINDER,
2084 BINDER__IMPERSONATE, NULL);
2089 return avc_has_perm(&selinux_state, fromsid, tosid,
2090 SECCLASS_BINDER, BINDER__CALL, NULL);
2093 static int selinux_binder_transfer_binder(const struct cred *from,
2094 const struct cred *to)
2096 return avc_has_perm(&selinux_state,
2097 cred_sid(from), cred_sid(to),
2098 SECCLASS_BINDER, BINDER__TRANSFER,
2102 static int selinux_binder_transfer_file(const struct cred *from,
2103 const struct cred *to,
2106 u32 sid = cred_sid(to);
2107 struct file_security_struct *fsec = selinux_file(file);
2108 struct dentry *dentry = file->f_path.dentry;
2109 struct inode_security_struct *isec;
2110 struct common_audit_data ad;
2113 ad.type = LSM_AUDIT_DATA_PATH;
2114 ad.u.path = file->f_path;
2116 if (sid != fsec->sid) {
2117 rc = avc_has_perm(&selinux_state,
2126 #ifdef CONFIG_BPF_SYSCALL
2127 rc = bpf_fd_pass(file, sid);
2132 if (unlikely(IS_PRIVATE(d_backing_inode(dentry))))
2135 isec = backing_inode_security(dentry);
2136 return avc_has_perm(&selinux_state,
2137 sid, isec->sid, isec->sclass, file_to_av(file),
2141 static int selinux_ptrace_access_check(struct task_struct *child,
2144 u32 sid = current_sid();
2145 u32 csid = task_sid_obj(child);
2147 if (mode & PTRACE_MODE_READ)
2148 return avc_has_perm(&selinux_state,
2149 sid, csid, SECCLASS_FILE, FILE__READ, NULL);
2151 return avc_has_perm(&selinux_state,
2152 sid, csid, SECCLASS_PROCESS, PROCESS__PTRACE, NULL);
2155 static int selinux_ptrace_traceme(struct task_struct *parent)
2157 return avc_has_perm(&selinux_state,
2158 task_sid_obj(parent), task_sid_obj(current),
2159 SECCLASS_PROCESS, PROCESS__PTRACE, NULL);
2162 static int selinux_capget(struct task_struct *target, kernel_cap_t *effective,
2163 kernel_cap_t *inheritable, kernel_cap_t *permitted)
2165 return avc_has_perm(&selinux_state,
2166 current_sid(), task_sid_obj(target), SECCLASS_PROCESS,
2167 PROCESS__GETCAP, NULL);
2170 static int selinux_capset(struct cred *new, const struct cred *old,
2171 const kernel_cap_t *effective,
2172 const kernel_cap_t *inheritable,
2173 const kernel_cap_t *permitted)
2175 return avc_has_perm(&selinux_state,
2176 cred_sid(old), cred_sid(new), SECCLASS_PROCESS,
2177 PROCESS__SETCAP, NULL);
2181 * (This comment used to live with the selinux_task_setuid hook,
2182 * which was removed).
2184 * Since setuid only affects the current process, and since the SELinux
2185 * controls are not based on the Linux identity attributes, SELinux does not
2186 * need to control this operation. However, SELinux does control the use of
2187 * the CAP_SETUID and CAP_SETGID capabilities using the capable hook.
2190 static int selinux_capable(const struct cred *cred, struct user_namespace *ns,
2191 int cap, unsigned int opts)
2193 return cred_has_capability(cred, cap, opts, ns == &init_user_ns);
2196 static int selinux_quotactl(int cmds, int type, int id, struct super_block *sb)
2198 const struct cred *cred = current_cred();
2213 rc = superblock_has_perm(cred, sb, FILESYSTEM__QUOTAMOD, NULL);
2221 case Q_XGETNEXTQUOTA:
2222 rc = superblock_has_perm(cred, sb, FILESYSTEM__QUOTAGET, NULL);
2225 rc = 0; /* let the kernel handle invalid cmds */
2231 static int selinux_quota_on(struct dentry *dentry)
2233 const struct cred *cred = current_cred();
2235 return dentry_has_perm(cred, dentry, FILE__QUOTAON);
2238 static int selinux_syslog(int type)
2241 case SYSLOG_ACTION_READ_ALL: /* Read last kernel messages */
2242 case SYSLOG_ACTION_SIZE_BUFFER: /* Return size of the log buffer */
2243 return avc_has_perm(&selinux_state,
2244 current_sid(), SECINITSID_KERNEL,
2245 SECCLASS_SYSTEM, SYSTEM__SYSLOG_READ, NULL);
2246 case SYSLOG_ACTION_CONSOLE_OFF: /* Disable logging to console */
2247 case SYSLOG_ACTION_CONSOLE_ON: /* Enable logging to console */
2248 /* Set level of messages printed to console */
2249 case SYSLOG_ACTION_CONSOLE_LEVEL:
2250 return avc_has_perm(&selinux_state,
2251 current_sid(), SECINITSID_KERNEL,
2252 SECCLASS_SYSTEM, SYSTEM__SYSLOG_CONSOLE,
2255 /* All other syslog types */
2256 return avc_has_perm(&selinux_state,
2257 current_sid(), SECINITSID_KERNEL,
2258 SECCLASS_SYSTEM, SYSTEM__SYSLOG_MOD, NULL);
2262 * Check that a process has enough memory to allocate a new virtual
2263 * mapping. 0 means there is enough memory for the allocation to
2264 * succeed and -ENOMEM implies there is not.
2266 * Do not audit the selinux permission check, as this is applied to all
2267 * processes that allocate mappings.
2269 static int selinux_vm_enough_memory(struct mm_struct *mm, long pages)
2271 int rc, cap_sys_admin = 0;
2273 rc = cred_has_capability(current_cred(), CAP_SYS_ADMIN,
2274 CAP_OPT_NOAUDIT, true);
2278 return cap_sys_admin;
2281 /* binprm security operations */
2283 static u32 ptrace_parent_sid(void)
2286 struct task_struct *tracer;
2289 tracer = ptrace_parent(current);
2291 sid = task_sid_obj(tracer);
2297 static int check_nnp_nosuid(const struct linux_binprm *bprm,
2298 const struct task_security_struct *old_tsec,
2299 const struct task_security_struct *new_tsec)
2301 int nnp = (bprm->unsafe & LSM_UNSAFE_NO_NEW_PRIVS);
2302 int nosuid = !mnt_may_suid(bprm->file->f_path.mnt);
2306 if (!nnp && !nosuid)
2307 return 0; /* neither NNP nor nosuid */
2309 if (new_tsec->sid == old_tsec->sid)
2310 return 0; /* No change in credentials */
2313 * If the policy enables the nnp_nosuid_transition policy capability,
2314 * then we permit transitions under NNP or nosuid if the
2315 * policy allows the corresponding permission between
2316 * the old and new contexts.
2318 if (selinux_policycap_nnp_nosuid_transition()) {
2321 av |= PROCESS2__NNP_TRANSITION;
2323 av |= PROCESS2__NOSUID_TRANSITION;
2324 rc = avc_has_perm(&selinux_state,
2325 old_tsec->sid, new_tsec->sid,
2326 SECCLASS_PROCESS2, av, NULL);
2332 * We also permit NNP or nosuid transitions to bounded SIDs,
2333 * i.e. SIDs that are guaranteed to only be allowed a subset
2334 * of the permissions of the current SID.
2336 rc = security_bounded_transition(&selinux_state, old_tsec->sid,
2342 * On failure, preserve the errno values for NNP vs nosuid.
2343 * NNP: Operation not permitted for caller.
2344 * nosuid: Permission denied to file.
2351 static int selinux_bprm_creds_for_exec(struct linux_binprm *bprm)
2353 const struct task_security_struct *old_tsec;
2354 struct task_security_struct *new_tsec;
2355 struct inode_security_struct *isec;
2356 struct common_audit_data ad;
2357 struct inode *inode = file_inode(bprm->file);
2360 /* SELinux context only depends on initial program or script and not
2361 * the script interpreter */
2363 old_tsec = selinux_cred(current_cred());
2364 new_tsec = selinux_cred(bprm->cred);
2365 isec = inode_security(inode);
2367 /* Default to the current task SID. */
2368 new_tsec->sid = old_tsec->sid;
2369 new_tsec->osid = old_tsec->sid;
2371 /* Reset fs, key, and sock SIDs on execve. */
2372 new_tsec->create_sid = 0;
2373 new_tsec->keycreate_sid = 0;
2374 new_tsec->sockcreate_sid = 0;
2376 if (old_tsec->exec_sid) {
2377 new_tsec->sid = old_tsec->exec_sid;
2378 /* Reset exec SID on execve. */
2379 new_tsec->exec_sid = 0;
2381 /* Fail on NNP or nosuid if not an allowed transition. */
2382 rc = check_nnp_nosuid(bprm, old_tsec, new_tsec);
2386 /* Check for a default transition on this program. */
2387 rc = security_transition_sid(&selinux_state, old_tsec->sid,
2388 isec->sid, SECCLASS_PROCESS, NULL,
2394 * Fallback to old SID on NNP or nosuid if not an allowed
2397 rc = check_nnp_nosuid(bprm, old_tsec, new_tsec);
2399 new_tsec->sid = old_tsec->sid;
2402 ad.type = LSM_AUDIT_DATA_FILE;
2403 ad.u.file = bprm->file;
2405 if (new_tsec->sid == old_tsec->sid) {
2406 rc = avc_has_perm(&selinux_state,
2407 old_tsec->sid, isec->sid,
2408 SECCLASS_FILE, FILE__EXECUTE_NO_TRANS, &ad);
2412 /* Check permissions for the transition. */
2413 rc = avc_has_perm(&selinux_state,
2414 old_tsec->sid, new_tsec->sid,
2415 SECCLASS_PROCESS, PROCESS__TRANSITION, &ad);
2419 rc = avc_has_perm(&selinux_state,
2420 new_tsec->sid, isec->sid,
2421 SECCLASS_FILE, FILE__ENTRYPOINT, &ad);
2425 /* Check for shared state */
2426 if (bprm->unsafe & LSM_UNSAFE_SHARE) {
2427 rc = avc_has_perm(&selinux_state,
2428 old_tsec->sid, new_tsec->sid,
2429 SECCLASS_PROCESS, PROCESS__SHARE,
2435 /* Make sure that anyone attempting to ptrace over a task that
2436 * changes its SID has the appropriate permit */
2437 if (bprm->unsafe & LSM_UNSAFE_PTRACE) {
2438 u32 ptsid = ptrace_parent_sid();
2440 rc = avc_has_perm(&selinux_state,
2441 ptsid, new_tsec->sid,
2443 PROCESS__PTRACE, NULL);
2449 /* Clear any possibly unsafe personality bits on exec: */
2450 bprm->per_clear |= PER_CLEAR_ON_SETID;
2452 /* Enable secure mode for SIDs transitions unless
2453 the noatsecure permission is granted between
2454 the two SIDs, i.e. ahp returns 0. */
2455 rc = avc_has_perm(&selinux_state,
2456 old_tsec->sid, new_tsec->sid,
2457 SECCLASS_PROCESS, PROCESS__NOATSECURE,
2459 bprm->secureexec |= !!rc;
2465 static int match_file(const void *p, struct file *file, unsigned fd)
2467 return file_has_perm(p, file, file_to_av(file)) ? fd + 1 : 0;
2470 /* Derived from fs/exec.c:flush_old_files. */
2471 static inline void flush_unauthorized_files(const struct cred *cred,
2472 struct files_struct *files)
2474 struct file *file, *devnull = NULL;
2475 struct tty_struct *tty;
2479 tty = get_current_tty();
2481 spin_lock(&tty->files_lock);
2482 if (!list_empty(&tty->tty_files)) {
2483 struct tty_file_private *file_priv;
2485 /* Revalidate access to controlling tty.
2486 Use file_path_has_perm on the tty path directly
2487 rather than using file_has_perm, as this particular
2488 open file may belong to another process and we are
2489 only interested in the inode-based check here. */
2490 file_priv = list_first_entry(&tty->tty_files,
2491 struct tty_file_private, list);
2492 file = file_priv->file;
2493 if (file_path_has_perm(cred, file, FILE__READ | FILE__WRITE))
2496 spin_unlock(&tty->files_lock);
2499 /* Reset controlling tty. */
2503 /* Revalidate access to inherited open files. */
2504 n = iterate_fd(files, 0, match_file, cred);
2505 if (!n) /* none found? */
2508 devnull = dentry_open(&selinux_null, O_RDWR, cred);
2509 if (IS_ERR(devnull))
2511 /* replace all the matching ones with this */
2513 replace_fd(n - 1, devnull, 0);
2514 } while ((n = iterate_fd(files, n, match_file, cred)) != 0);
2520 * Prepare a process for imminent new credential changes due to exec
2522 static void selinux_bprm_committing_creds(struct linux_binprm *bprm)
2524 struct task_security_struct *new_tsec;
2525 struct rlimit *rlim, *initrlim;
2528 new_tsec = selinux_cred(bprm->cred);
2529 if (new_tsec->sid == new_tsec->osid)
2532 /* Close files for which the new task SID is not authorized. */
2533 flush_unauthorized_files(bprm->cred, current->files);
2535 /* Always clear parent death signal on SID transitions. */
2536 current->pdeath_signal = 0;
2538 /* Check whether the new SID can inherit resource limits from the old
2539 * SID. If not, reset all soft limits to the lower of the current
2540 * task's hard limit and the init task's soft limit.
2542 * Note that the setting of hard limits (even to lower them) can be
2543 * controlled by the setrlimit check. The inclusion of the init task's
2544 * soft limit into the computation is to avoid resetting soft limits
2545 * higher than the default soft limit for cases where the default is
2546 * lower than the hard limit, e.g. RLIMIT_CORE or RLIMIT_STACK.
2548 rc = avc_has_perm(&selinux_state,
2549 new_tsec->osid, new_tsec->sid, SECCLASS_PROCESS,
2550 PROCESS__RLIMITINH, NULL);
2552 /* protect against do_prlimit() */
2554 for (i = 0; i < RLIM_NLIMITS; i++) {
2555 rlim = current->signal->rlim + i;
2556 initrlim = init_task.signal->rlim + i;
2557 rlim->rlim_cur = min(rlim->rlim_max, initrlim->rlim_cur);
2559 task_unlock(current);
2560 if (IS_ENABLED(CONFIG_POSIX_TIMERS))
2561 update_rlimit_cpu(current, rlimit(RLIMIT_CPU));
2566 * Clean up the process immediately after the installation of new credentials
2569 static void selinux_bprm_committed_creds(struct linux_binprm *bprm)
2571 const struct task_security_struct *tsec = selinux_cred(current_cred());
2581 /* Check whether the new SID can inherit signal state from the old SID.
2582 * If not, clear itimers to avoid subsequent signal generation and
2583 * flush and unblock signals.
2585 * This must occur _after_ the task SID has been updated so that any
2586 * kill done after the flush will be checked against the new SID.
2588 rc = avc_has_perm(&selinux_state,
2589 osid, sid, SECCLASS_PROCESS, PROCESS__SIGINH, NULL);
2593 spin_lock_irq(¤t->sighand->siglock);
2594 if (!fatal_signal_pending(current)) {
2595 flush_sigqueue(¤t->pending);
2596 flush_sigqueue(¤t->signal->shared_pending);
2597 flush_signal_handlers(current, 1);
2598 sigemptyset(¤t->blocked);
2599 recalc_sigpending();
2601 spin_unlock_irq(¤t->sighand->siglock);
2604 /* Wake up the parent if it is waiting so that it can recheck
2605 * wait permission to the new task SID. */
2606 read_lock(&tasklist_lock);
2607 __wake_up_parent(current, current->real_parent);
2608 read_unlock(&tasklist_lock);
2611 /* superblock security operations */
2613 static int selinux_sb_alloc_security(struct super_block *sb)
2615 struct superblock_security_struct *sbsec = selinux_superblock(sb);
2617 mutex_init(&sbsec->lock);
2618 INIT_LIST_HEAD(&sbsec->isec_head);
2619 spin_lock_init(&sbsec->isec_lock);
2620 sbsec->sid = SECINITSID_UNLABELED;
2621 sbsec->def_sid = SECINITSID_FILE;
2622 sbsec->mntpoint_sid = SECINITSID_UNLABELED;
2627 static inline int opt_len(const char *s)
2629 bool open_quote = false;
2633 for (len = 0; (c = s[len]) != '\0'; len++) {
2635 open_quote = !open_quote;
2636 if (c == ',' && !open_quote)
2642 static int selinux_sb_eat_lsm_opts(char *options, void **mnt_opts)
2644 char *from = options;
2650 int len = opt_len(from);
2654 token = match_opt_prefix(from, len, &arg);
2656 if (token != Opt_error) {
2661 for (p = q = arg; p < from + len; p++) {
2666 arg = kmemdup_nul(arg, q - arg, GFP_KERNEL);
2672 rc = selinux_add_opt(token, arg, mnt_opts);
2678 if (!first) { // copy with preceding comma
2683 memmove(to, from, len);
2696 selinux_free_mnt_opts(*mnt_opts);
2702 static int selinux_sb_mnt_opts_compat(struct super_block *sb, void *mnt_opts)
2704 struct selinux_mnt_opts *opts = mnt_opts;
2705 struct superblock_security_struct *sbsec = selinux_superblock(sb);
2708 * Superblock not initialized (i.e. no options) - reject if any
2709 * options specified, otherwise accept.
2711 if (!(sbsec->flags & SE_SBINITIALIZED))
2712 return opts ? 1 : 0;
2715 * Superblock initialized and no options specified - reject if
2716 * superblock has any options set, otherwise accept.
2719 return (sbsec->flags & SE_MNTMASK) ? 1 : 0;
2721 if (opts->fscontext) {
2722 if (opts->fscontext_sid == SECSID_NULL)
2724 else if (bad_option(sbsec, FSCONTEXT_MNT, sbsec->sid,
2725 opts->fscontext_sid))
2728 if (opts->context) {
2729 if (opts->context_sid == SECSID_NULL)
2731 else if (bad_option(sbsec, CONTEXT_MNT, sbsec->mntpoint_sid,
2735 if (opts->rootcontext) {
2736 if (opts->rootcontext_sid == SECSID_NULL)
2739 struct inode_security_struct *root_isec;
2741 root_isec = backing_inode_security(sb->s_root);
2742 if (bad_option(sbsec, ROOTCONTEXT_MNT, root_isec->sid,
2743 opts->rootcontext_sid))
2747 if (opts->defcontext) {
2748 if (opts->defcontext_sid == SECSID_NULL)
2750 else if (bad_option(sbsec, DEFCONTEXT_MNT, sbsec->def_sid,
2751 opts->defcontext_sid))
2757 static int selinux_sb_remount(struct super_block *sb, void *mnt_opts)
2759 struct selinux_mnt_opts *opts = mnt_opts;
2760 struct superblock_security_struct *sbsec = selinux_superblock(sb);
2764 if (!(sbsec->flags & SE_SBINITIALIZED))
2770 if (opts->fscontext) {
2771 rc = parse_sid(sb, opts->fscontext, &sid);
2774 if (bad_option(sbsec, FSCONTEXT_MNT, sbsec->sid, sid))
2775 goto out_bad_option;
2777 if (opts->context) {
2778 rc = parse_sid(sb, opts->context, &sid);
2781 if (bad_option(sbsec, CONTEXT_MNT, sbsec->mntpoint_sid, sid))
2782 goto out_bad_option;
2784 if (opts->rootcontext) {
2785 struct inode_security_struct *root_isec;
2786 root_isec = backing_inode_security(sb->s_root);
2787 rc = parse_sid(sb, opts->rootcontext, &sid);
2790 if (bad_option(sbsec, ROOTCONTEXT_MNT, root_isec->sid, sid))
2791 goto out_bad_option;
2793 if (opts->defcontext) {
2794 rc = parse_sid(sb, opts->defcontext, &sid);
2797 if (bad_option(sbsec, DEFCONTEXT_MNT, sbsec->def_sid, sid))
2798 goto out_bad_option;
2803 pr_warn("SELinux: unable to change security options "
2804 "during remount (dev %s, type=%s)\n", sb->s_id,
2809 static int selinux_sb_kern_mount(struct super_block *sb)
2811 const struct cred *cred = current_cred();
2812 struct common_audit_data ad;
2814 ad.type = LSM_AUDIT_DATA_DENTRY;
2815 ad.u.dentry = sb->s_root;
2816 return superblock_has_perm(cred, sb, FILESYSTEM__MOUNT, &ad);
2819 static int selinux_sb_statfs(struct dentry *dentry)
2821 const struct cred *cred = current_cred();
2822 struct common_audit_data ad;
2824 ad.type = LSM_AUDIT_DATA_DENTRY;
2825 ad.u.dentry = dentry->d_sb->s_root;
2826 return superblock_has_perm(cred, dentry->d_sb, FILESYSTEM__GETATTR, &ad);
2829 static int selinux_mount(const char *dev_name,
2830 const struct path *path,
2832 unsigned long flags,
2835 const struct cred *cred = current_cred();
2837 if (flags & MS_REMOUNT)
2838 return superblock_has_perm(cred, path->dentry->d_sb,
2839 FILESYSTEM__REMOUNT, NULL);
2841 return path_has_perm(cred, path, FILE__MOUNTON);
2844 static int selinux_move_mount(const struct path *from_path,
2845 const struct path *to_path)
2847 const struct cred *cred = current_cred();
2849 return path_has_perm(cred, to_path, FILE__MOUNTON);
2852 static int selinux_umount(struct vfsmount *mnt, int flags)
2854 const struct cred *cred = current_cred();
2856 return superblock_has_perm(cred, mnt->mnt_sb,
2857 FILESYSTEM__UNMOUNT, NULL);
2860 static int selinux_fs_context_dup(struct fs_context *fc,
2861 struct fs_context *src_fc)
2863 const struct selinux_mnt_opts *src = src_fc->security;
2864 struct selinux_mnt_opts *opts;
2869 fc->security = kzalloc(sizeof(struct selinux_mnt_opts), GFP_KERNEL);
2873 opts = fc->security;
2875 if (src->fscontext) {
2876 opts->fscontext = kstrdup(src->fscontext, GFP_KERNEL);
2877 if (!opts->fscontext)
2881 opts->context = kstrdup(src->context, GFP_KERNEL);
2885 if (src->rootcontext) {
2886 opts->rootcontext = kstrdup(src->rootcontext, GFP_KERNEL);
2887 if (!opts->rootcontext)
2890 if (src->defcontext) {
2891 opts->defcontext = kstrdup(src->defcontext, GFP_KERNEL);
2892 if (!opts->defcontext)
2898 static const struct fs_parameter_spec selinux_fs_parameters[] = {
2899 fsparam_string(CONTEXT_STR, Opt_context),
2900 fsparam_string(DEFCONTEXT_STR, Opt_defcontext),
2901 fsparam_string(FSCONTEXT_STR, Opt_fscontext),
2902 fsparam_string(ROOTCONTEXT_STR, Opt_rootcontext),
2903 fsparam_flag (SECLABEL_STR, Opt_seclabel),
2907 static int selinux_fs_context_parse_param(struct fs_context *fc,
2908 struct fs_parameter *param)
2910 struct fs_parse_result result;
2913 opt = fs_parse(fc, selinux_fs_parameters, param, &result);
2917 rc = selinux_add_opt(opt, param->string, &fc->security);
2919 param->string = NULL;
2924 /* inode security operations */
2926 static int selinux_inode_alloc_security(struct inode *inode)
2928 struct inode_security_struct *isec = selinux_inode(inode);
2929 u32 sid = current_sid();
2931 spin_lock_init(&isec->lock);
2932 INIT_LIST_HEAD(&isec->list);
2933 isec->inode = inode;
2934 isec->sid = SECINITSID_UNLABELED;
2935 isec->sclass = SECCLASS_FILE;
2936 isec->task_sid = sid;
2937 isec->initialized = LABEL_INVALID;
2942 static void selinux_inode_free_security(struct inode *inode)
2944 inode_free_security(inode);
2947 static int selinux_dentry_init_security(struct dentry *dentry, int mode,
2948 const struct qstr *name, void **ctx,
2954 rc = selinux_determine_inode_label(selinux_cred(current_cred()),
2955 d_inode(dentry->d_parent), name,
2956 inode_mode_to_security_class(mode),
2961 return security_sid_to_context(&selinux_state, newsid, (char **)ctx,
2965 static int selinux_dentry_create_files_as(struct dentry *dentry, int mode,
2967 const struct cred *old,
2972 struct task_security_struct *tsec;
2974 rc = selinux_determine_inode_label(selinux_cred(old),
2975 d_inode(dentry->d_parent), name,
2976 inode_mode_to_security_class(mode),
2981 tsec = selinux_cred(new);
2982 tsec->create_sid = newsid;
2986 static int selinux_inode_init_security(struct inode *inode, struct inode *dir,
2987 const struct qstr *qstr,
2989 void **value, size_t *len)
2991 const struct task_security_struct *tsec = selinux_cred(current_cred());
2992 struct superblock_security_struct *sbsec;
2997 sbsec = selinux_superblock(dir->i_sb);
2999 newsid = tsec->create_sid;
3001 rc = selinux_determine_inode_label(tsec, dir, qstr,
3002 inode_mode_to_security_class(inode->i_mode),
3007 /* Possibly defer initialization to selinux_complete_init. */
3008 if (sbsec->flags & SE_SBINITIALIZED) {
3009 struct inode_security_struct *isec = selinux_inode(inode);
3010 isec->sclass = inode_mode_to_security_class(inode->i_mode);
3012 isec->initialized = LABEL_INITIALIZED;
3015 if (!selinux_initialized(&selinux_state) ||
3016 !(sbsec->flags & SBLABEL_MNT))
3020 *name = XATTR_SELINUX_SUFFIX;
3023 rc = security_sid_to_context_force(&selinux_state, newsid,
3034 static int selinux_inode_init_security_anon(struct inode *inode,
3035 const struct qstr *name,
3036 const struct inode *context_inode)
3038 const struct task_security_struct *tsec = selinux_cred(current_cred());
3039 struct common_audit_data ad;
3040 struct inode_security_struct *isec;
3043 if (unlikely(!selinux_initialized(&selinux_state)))
3046 isec = selinux_inode(inode);
3049 * We only get here once per ephemeral inode. The inode has
3050 * been initialized via inode_alloc_security but is otherwise
3054 if (context_inode) {
3055 struct inode_security_struct *context_isec =
3056 selinux_inode(context_inode);
3057 if (context_isec->initialized != LABEL_INITIALIZED) {
3058 pr_err("SELinux: context_inode is not initialized");
3062 isec->sclass = context_isec->sclass;
3063 isec->sid = context_isec->sid;
3065 isec->sclass = SECCLASS_ANON_INODE;
3066 rc = security_transition_sid(
3067 &selinux_state, tsec->sid, tsec->sid,
3068 isec->sclass, name, &isec->sid);
3073 isec->initialized = LABEL_INITIALIZED;
3075 * Now that we've initialized security, check whether we're
3076 * allowed to actually create this type of anonymous inode.
3079 ad.type = LSM_AUDIT_DATA_INODE;
3082 return avc_has_perm(&selinux_state,
3090 static int selinux_inode_create(struct inode *dir, struct dentry *dentry, umode_t mode)
3092 return may_create(dir, dentry, SECCLASS_FILE);
3095 static int selinux_inode_link(struct dentry *old_dentry, struct inode *dir, struct dentry *new_dentry)
3097 return may_link(dir, old_dentry, MAY_LINK);
3100 static int selinux_inode_unlink(struct inode *dir, struct dentry *dentry)
3102 return may_link(dir, dentry, MAY_UNLINK);
3105 static int selinux_inode_symlink(struct inode *dir, struct dentry *dentry, const char *name)
3107 return may_create(dir, dentry, SECCLASS_LNK_FILE);
3110 static int selinux_inode_mkdir(struct inode *dir, struct dentry *dentry, umode_t mask)
3112 return may_create(dir, dentry, SECCLASS_DIR);
3115 static int selinux_inode_rmdir(struct inode *dir, struct dentry *dentry)
3117 return may_link(dir, dentry, MAY_RMDIR);
3120 static int selinux_inode_mknod(struct inode *dir, struct dentry *dentry, umode_t mode, dev_t dev)
3122 return may_create(dir, dentry, inode_mode_to_security_class(mode));
3125 static int selinux_inode_rename(struct inode *old_inode, struct dentry *old_dentry,
3126 struct inode *new_inode, struct dentry *new_dentry)
3128 return may_rename(old_inode, old_dentry, new_inode, new_dentry);
3131 static int selinux_inode_readlink(struct dentry *dentry)
3133 const struct cred *cred = current_cred();
3135 return dentry_has_perm(cred, dentry, FILE__READ);
3138 static int selinux_inode_follow_link(struct dentry *dentry, struct inode *inode,
3141 const struct cred *cred = current_cred();
3142 struct common_audit_data ad;
3143 struct inode_security_struct *isec;
3146 validate_creds(cred);
3148 ad.type = LSM_AUDIT_DATA_DENTRY;
3149 ad.u.dentry = dentry;
3150 sid = cred_sid(cred);
3151 isec = inode_security_rcu(inode, rcu);
3153 return PTR_ERR(isec);
3155 return avc_has_perm(&selinux_state,
3156 sid, isec->sid, isec->sclass, FILE__READ, &ad);
3159 static noinline int audit_inode_permission(struct inode *inode,
3160 u32 perms, u32 audited, u32 denied,
3163 struct common_audit_data ad;
3164 struct inode_security_struct *isec = selinux_inode(inode);
3166 ad.type = LSM_AUDIT_DATA_INODE;
3169 return slow_avc_audit(&selinux_state,
3170 current_sid(), isec->sid, isec->sclass, perms,
3171 audited, denied, result, &ad);
3174 static int selinux_inode_permission(struct inode *inode, int mask)
3176 const struct cred *cred = current_cred();
3179 bool no_block = mask & MAY_NOT_BLOCK;
3180 struct inode_security_struct *isec;
3182 struct av_decision avd;
3184 u32 audited, denied;
3186 from_access = mask & MAY_ACCESS;
3187 mask &= (MAY_READ|MAY_WRITE|MAY_EXEC|MAY_APPEND);
3189 /* No permission to check. Existence test. */
3193 validate_creds(cred);
3195 if (unlikely(IS_PRIVATE(inode)))
3198 perms = file_mask_to_av(inode->i_mode, mask);
3200 sid = cred_sid(cred);
3201 isec = inode_security_rcu(inode, no_block);
3203 return PTR_ERR(isec);
3205 rc = avc_has_perm_noaudit(&selinux_state,
3206 sid, isec->sid, isec->sclass, perms, 0,
3208 audited = avc_audit_required(perms, &avd, rc,
3209 from_access ? FILE__AUDIT_ACCESS : 0,
3211 if (likely(!audited))
3214 rc2 = audit_inode_permission(inode, perms, audited, denied, rc);
3220 static int selinux_inode_setattr(struct dentry *dentry, struct iattr *iattr)
3222 const struct cred *cred = current_cred();
3223 struct inode *inode = d_backing_inode(dentry);
3224 unsigned int ia_valid = iattr->ia_valid;
3225 __u32 av = FILE__WRITE;
3227 /* ATTR_FORCE is just used for ATTR_KILL_S[UG]ID. */
3228 if (ia_valid & ATTR_FORCE) {
3229 ia_valid &= ~(ATTR_KILL_SUID | ATTR_KILL_SGID | ATTR_MODE |
3235 if (ia_valid & (ATTR_MODE | ATTR_UID | ATTR_GID |
3236 ATTR_ATIME_SET | ATTR_MTIME_SET | ATTR_TIMES_SET))
3237 return dentry_has_perm(cred, dentry, FILE__SETATTR);
3239 if (selinux_policycap_openperm() &&
3240 inode->i_sb->s_magic != SOCKFS_MAGIC &&
3241 (ia_valid & ATTR_SIZE) &&
3242 !(ia_valid & ATTR_FILE))
3245 return dentry_has_perm(cred, dentry, av);
3248 static int selinux_inode_getattr(const struct path *path)
3250 return path_has_perm(current_cred(), path, FILE__GETATTR);
3253 static bool has_cap_mac_admin(bool audit)
3255 const struct cred *cred = current_cred();
3256 unsigned int opts = audit ? CAP_OPT_NONE : CAP_OPT_NOAUDIT;
3258 if (cap_capable(cred, &init_user_ns, CAP_MAC_ADMIN, opts))
3260 if (cred_has_capability(cred, CAP_MAC_ADMIN, opts, true))
3265 static int selinux_inode_setxattr(struct user_namespace *mnt_userns,
3266 struct dentry *dentry, const char *name,
3267 const void *value, size_t size, int flags)
3269 struct inode *inode = d_backing_inode(dentry);
3270 struct inode_security_struct *isec;
3271 struct superblock_security_struct *sbsec;
3272 struct common_audit_data ad;
3273 u32 newsid, sid = current_sid();
3276 if (strcmp(name, XATTR_NAME_SELINUX)) {
3277 rc = cap_inode_setxattr(dentry, name, value, size, flags);
3281 /* Not an attribute we recognize, so just check the
3282 ordinary setattr permission. */
3283 return dentry_has_perm(current_cred(), dentry, FILE__SETATTR);
3286 if (!selinux_initialized(&selinux_state))
3287 return (inode_owner_or_capable(mnt_userns, inode) ? 0 : -EPERM);
3289 sbsec = selinux_superblock(inode->i_sb);
3290 if (!(sbsec->flags & SBLABEL_MNT))
3293 if (!inode_owner_or_capable(mnt_userns, inode))
3296 ad.type = LSM_AUDIT_DATA_DENTRY;
3297 ad.u.dentry = dentry;
3299 isec = backing_inode_security(dentry);
3300 rc = avc_has_perm(&selinux_state,
3301 sid, isec->sid, isec->sclass,
3302 FILE__RELABELFROM, &ad);
3306 rc = security_context_to_sid(&selinux_state, value, size, &newsid,
3308 if (rc == -EINVAL) {
3309 if (!has_cap_mac_admin(true)) {
3310 struct audit_buffer *ab;
3313 /* We strip a nul only if it is at the end, otherwise the
3314 * context contains a nul and we should audit that */
3316 const char *str = value;
3318 if (str[size - 1] == '\0')
3319 audit_size = size - 1;
3325 ab = audit_log_start(audit_context(),
3326 GFP_ATOMIC, AUDIT_SELINUX_ERR);
3329 audit_log_format(ab, "op=setxattr invalid_context=");
3330 audit_log_n_untrustedstring(ab, value, audit_size);
3335 rc = security_context_to_sid_force(&selinux_state, value,
3341 rc = avc_has_perm(&selinux_state,
3342 sid, newsid, isec->sclass,
3343 FILE__RELABELTO, &ad);
3347 rc = security_validate_transition(&selinux_state, isec->sid, newsid,
3352 return avc_has_perm(&selinux_state,
3355 SECCLASS_FILESYSTEM,
3356 FILESYSTEM__ASSOCIATE,
3360 static void selinux_inode_post_setxattr(struct dentry *dentry, const char *name,
3361 const void *value, size_t size,
3364 struct inode *inode = d_backing_inode(dentry);
3365 struct inode_security_struct *isec;
3369 if (strcmp(name, XATTR_NAME_SELINUX)) {
3370 /* Not an attribute we recognize, so nothing to do. */
3374 if (!selinux_initialized(&selinux_state)) {
3375 /* If we haven't even been initialized, then we can't validate
3376 * against a policy, so leave the label as invalid. It may
3377 * resolve to a valid label on the next revalidation try if
3378 * we've since initialized.
3383 rc = security_context_to_sid_force(&selinux_state, value, size,
3386 pr_err("SELinux: unable to map context to SID"
3387 "for (%s, %lu), rc=%d\n",
3388 inode->i_sb->s_id, inode->i_ino, -rc);
3392 isec = backing_inode_security(dentry);
3393 spin_lock(&isec->lock);
3394 isec->sclass = inode_mode_to_security_class(inode->i_mode);
3396 isec->initialized = LABEL_INITIALIZED;
3397 spin_unlock(&isec->lock);
3402 static int selinux_inode_getxattr(struct dentry *dentry, const char *name)
3404 const struct cred *cred = current_cred();
3406 return dentry_has_perm(cred, dentry, FILE__GETATTR);
3409 static int selinux_inode_listxattr(struct dentry *dentry)
3411 const struct cred *cred = current_cred();
3413 return dentry_has_perm(cred, dentry, FILE__GETATTR);
3416 static int selinux_inode_removexattr(struct user_namespace *mnt_userns,
3417 struct dentry *dentry, const char *name)
3419 if (strcmp(name, XATTR_NAME_SELINUX)) {
3420 int rc = cap_inode_removexattr(mnt_userns, dentry, name);
3424 /* Not an attribute we recognize, so just check the
3425 ordinary setattr permission. */
3426 return dentry_has_perm(current_cred(), dentry, FILE__SETATTR);
3429 if (!selinux_initialized(&selinux_state))
3432 /* No one is allowed to remove a SELinux security label.
3433 You can change the label, but all data must be labeled. */
3437 static int selinux_path_notify(const struct path *path, u64 mask,
3438 unsigned int obj_type)
3443 struct common_audit_data ad;
3445 ad.type = LSM_AUDIT_DATA_PATH;
3449 * Set permission needed based on the type of mark being set.
3450 * Performs an additional check for sb watches.
3453 case FSNOTIFY_OBJ_TYPE_VFSMOUNT:
3454 perm = FILE__WATCH_MOUNT;
3456 case FSNOTIFY_OBJ_TYPE_SB:
3457 perm = FILE__WATCH_SB;
3458 ret = superblock_has_perm(current_cred(), path->dentry->d_sb,
3459 FILESYSTEM__WATCH, &ad);
3463 case FSNOTIFY_OBJ_TYPE_INODE:
3470 /* blocking watches require the file:watch_with_perm permission */
3471 if (mask & (ALL_FSNOTIFY_PERM_EVENTS))
3472 perm |= FILE__WATCH_WITH_PERM;
3474 /* watches on read-like events need the file:watch_reads permission */
3475 if (mask & (FS_ACCESS | FS_ACCESS_PERM | FS_CLOSE_NOWRITE))
3476 perm |= FILE__WATCH_READS;
3478 return path_has_perm(current_cred(), path, perm);
3482 * Copy the inode security context value to the user.
3484 * Permission check is handled by selinux_inode_getxattr hook.
3486 static int selinux_inode_getsecurity(struct user_namespace *mnt_userns,
3487 struct inode *inode, const char *name,
3488 void **buffer, bool alloc)
3492 char *context = NULL;
3493 struct inode_security_struct *isec;
3496 * If we're not initialized yet, then we can't validate contexts, so
3497 * just let vfs_getxattr fall back to using the on-disk xattr.
3499 if (!selinux_initialized(&selinux_state) ||
3500 strcmp(name, XATTR_SELINUX_SUFFIX))
3504 * If the caller has CAP_MAC_ADMIN, then get the raw context
3505 * value even if it is not defined by current policy; otherwise,
3506 * use the in-core value under current policy.
3507 * Use the non-auditing forms of the permission checks since
3508 * getxattr may be called by unprivileged processes commonly
3509 * and lack of permission just means that we fall back to the
3510 * in-core context value, not a denial.
3512 isec = inode_security(inode);
3513 if (has_cap_mac_admin(false))
3514 error = security_sid_to_context_force(&selinux_state,
3515 isec->sid, &context,
3518 error = security_sid_to_context(&selinux_state, isec->sid,
3532 static int selinux_inode_setsecurity(struct inode *inode, const char *name,
3533 const void *value, size_t size, int flags)
3535 struct inode_security_struct *isec = inode_security_novalidate(inode);
3536 struct superblock_security_struct *sbsec;
3540 if (strcmp(name, XATTR_SELINUX_SUFFIX))
3543 sbsec = selinux_superblock(inode->i_sb);
3544 if (!(sbsec->flags & SBLABEL_MNT))
3547 if (!value || !size)
3550 rc = security_context_to_sid(&selinux_state, value, size, &newsid,
3555 spin_lock(&isec->lock);
3556 isec->sclass = inode_mode_to_security_class(inode->i_mode);
3558 isec->initialized = LABEL_INITIALIZED;
3559 spin_unlock(&isec->lock);
3563 static int selinux_inode_listsecurity(struct inode *inode, char *buffer, size_t buffer_size)
3565 const int len = sizeof(XATTR_NAME_SELINUX);
3567 if (!selinux_initialized(&selinux_state))
3570 if (buffer && len <= buffer_size)
3571 memcpy(buffer, XATTR_NAME_SELINUX, len);
3575 static void selinux_inode_getsecid(struct inode *inode, u32 *secid)
3577 struct inode_security_struct *isec = inode_security_novalidate(inode);
3581 static int selinux_inode_copy_up(struct dentry *src, struct cred **new)
3584 struct task_security_struct *tsec;
3585 struct cred *new_creds = *new;
3587 if (new_creds == NULL) {
3588 new_creds = prepare_creds();
3593 tsec = selinux_cred(new_creds);
3594 /* Get label from overlay inode and set it in create_sid */
3595 selinux_inode_getsecid(d_inode(src), &sid);
3596 tsec->create_sid = sid;
3601 static int selinux_inode_copy_up_xattr(const char *name)
3603 /* The copy_up hook above sets the initial context on an inode, but we
3604 * don't then want to overwrite it by blindly copying all the lower
3605 * xattrs up. Instead, we have to filter out SELinux-related xattrs.
3607 if (strcmp(name, XATTR_NAME_SELINUX) == 0)
3608 return 1; /* Discard */
3610 * Any other attribute apart from SELINUX is not claimed, supported
3616 /* kernfs node operations */
3618 static int selinux_kernfs_init_security(struct kernfs_node *kn_dir,
3619 struct kernfs_node *kn)
3621 const struct task_security_struct *tsec = selinux_cred(current_cred());
3622 u32 parent_sid, newsid, clen;
3626 rc = kernfs_xattr_get(kn_dir, XATTR_NAME_SELINUX, NULL, 0);
3633 context = kmalloc(clen, GFP_KERNEL);
3637 rc = kernfs_xattr_get(kn_dir, XATTR_NAME_SELINUX, context, clen);
3643 rc = security_context_to_sid(&selinux_state, context, clen, &parent_sid,
3649 if (tsec->create_sid) {
3650 newsid = tsec->create_sid;
3652 u16 secclass = inode_mode_to_security_class(kn->mode);
3656 q.hash_len = hashlen_string(kn_dir, kn->name);
3658 rc = security_transition_sid(&selinux_state, tsec->sid,
3659 parent_sid, secclass, &q,
3665 rc = security_sid_to_context_force(&selinux_state, newsid,
3670 rc = kernfs_xattr_set(kn, XATTR_NAME_SELINUX, context, clen,
3677 /* file security operations */
3679 static int selinux_revalidate_file_permission(struct file *file, int mask)
3681 const struct cred *cred = current_cred();
3682 struct inode *inode = file_inode(file);
3684 /* file_mask_to_av won't add FILE__WRITE if MAY_APPEND is set */
3685 if ((file->f_flags & O_APPEND) && (mask & MAY_WRITE))
3688 return file_has_perm(cred, file,
3689 file_mask_to_av(inode->i_mode, mask));
3692 static int selinux_file_permission(struct file *file, int mask)
3694 struct inode *inode = file_inode(file);
3695 struct file_security_struct *fsec = selinux_file(file);
3696 struct inode_security_struct *isec;
3697 u32 sid = current_sid();
3700 /* No permission to check. Existence test. */
3703 isec = inode_security(inode);
3704 if (sid == fsec->sid && fsec->isid == isec->sid &&
3705 fsec->pseqno == avc_policy_seqno(&selinux_state))
3706 /* No change since file_open check. */
3709 return selinux_revalidate_file_permission(file, mask);
3712 static int selinux_file_alloc_security(struct file *file)
3714 struct file_security_struct *fsec = selinux_file(file);
3715 u32 sid = current_sid();
3718 fsec->fown_sid = sid;
3724 * Check whether a task has the ioctl permission and cmd
3725 * operation to an inode.
3727 static int ioctl_has_perm(const struct cred *cred, struct file *file,
3728 u32 requested, u16 cmd)
3730 struct common_audit_data ad;
3731 struct file_security_struct *fsec = selinux_file(file);
3732 struct inode *inode = file_inode(file);
3733 struct inode_security_struct *isec;
3734 struct lsm_ioctlop_audit ioctl;
3735 u32 ssid = cred_sid(cred);
3737 u8 driver = cmd >> 8;
3738 u8 xperm = cmd & 0xff;
3740 ad.type = LSM_AUDIT_DATA_IOCTL_OP;
3743 ad.u.op->path = file->f_path;
3745 if (ssid != fsec->sid) {
3746 rc = avc_has_perm(&selinux_state,
3755 if (unlikely(IS_PRIVATE(inode)))
3758 isec = inode_security(inode);
3759 rc = avc_has_extended_perms(&selinux_state,
3760 ssid, isec->sid, isec->sclass,
3761 requested, driver, xperm, &ad);
3766 static int selinux_file_ioctl(struct file *file, unsigned int cmd,
3769 const struct cred *cred = current_cred();
3776 case FS_IOC_GETFLAGS:
3777 case FS_IOC_GETVERSION:
3778 error = file_has_perm(cred, file, FILE__GETATTR);
3781 case FS_IOC_SETFLAGS:
3782 case FS_IOC_SETVERSION:
3783 error = file_has_perm(cred, file, FILE__SETATTR);
3786 /* sys_ioctl() checks */
3789 error = file_has_perm(cred, file, 0);
3794 error = cred_has_capability(cred, CAP_SYS_TTY_CONFIG,
3795 CAP_OPT_NONE, true);
3800 if (!selinux_policycap_ioctl_skip_cloexec())
3801 error = ioctl_has_perm(cred, file, FILE__IOCTL, (u16) cmd);
3804 /* default case assumes that the command will go
3805 * to the file's ioctl() function.
3808 error = ioctl_has_perm(cred, file, FILE__IOCTL, (u16) cmd);
3813 static int default_noexec __ro_after_init;
3815 static int file_map_prot_check(struct file *file, unsigned long prot, int shared)
3817 const struct cred *cred = current_cred();
3818 u32 sid = cred_sid(cred);
3821 if (default_noexec &&
3822 (prot & PROT_EXEC) && (!file || IS_PRIVATE(file_inode(file)) ||
3823 (!shared && (prot & PROT_WRITE)))) {
3825 * We are making executable an anonymous mapping or a
3826 * private file mapping that will also be writable.
3827 * This has an additional check.
3829 rc = avc_has_perm(&selinux_state,
3830 sid, sid, SECCLASS_PROCESS,
3831 PROCESS__EXECMEM, NULL);
3837 /* read access is always possible with a mapping */
3838 u32 av = FILE__READ;
3840 /* write access only matters if the mapping is shared */
3841 if (shared && (prot & PROT_WRITE))
3844 if (prot & PROT_EXEC)
3845 av |= FILE__EXECUTE;
3847 return file_has_perm(cred, file, av);
3854 static int selinux_mmap_addr(unsigned long addr)
3858 if (addr < CONFIG_LSM_MMAP_MIN_ADDR) {
3859 u32 sid = current_sid();
3860 rc = avc_has_perm(&selinux_state,
3861 sid, sid, SECCLASS_MEMPROTECT,
3862 MEMPROTECT__MMAP_ZERO, NULL);
3868 static int selinux_mmap_file(struct file *file, unsigned long reqprot,
3869 unsigned long prot, unsigned long flags)
3871 struct common_audit_data ad;
3875 ad.type = LSM_AUDIT_DATA_FILE;
3877 rc = inode_has_perm(current_cred(), file_inode(file),
3883 if (checkreqprot_get(&selinux_state))
3886 return file_map_prot_check(file, prot,
3887 (flags & MAP_TYPE) == MAP_SHARED);
3890 static int selinux_file_mprotect(struct vm_area_struct *vma,
3891 unsigned long reqprot,
3894 const struct cred *cred = current_cred();
3895 u32 sid = cred_sid(cred);
3897 if (checkreqprot_get(&selinux_state))
3900 if (default_noexec &&
3901 (prot & PROT_EXEC) && !(vma->vm_flags & VM_EXEC)) {
3903 if (vma->vm_start >= vma->vm_mm->start_brk &&
3904 vma->vm_end <= vma->vm_mm->brk) {
3905 rc = avc_has_perm(&selinux_state,
3906 sid, sid, SECCLASS_PROCESS,
3907 PROCESS__EXECHEAP, NULL);
3908 } else if (!vma->vm_file &&
3909 ((vma->vm_start <= vma->vm_mm->start_stack &&
3910 vma->vm_end >= vma->vm_mm->start_stack) ||
3911 vma_is_stack_for_current(vma))) {
3912 rc = avc_has_perm(&selinux_state,
3913 sid, sid, SECCLASS_PROCESS,
3914 PROCESS__EXECSTACK, NULL);
3915 } else if (vma->vm_file && vma->anon_vma) {
3917 * We are making executable a file mapping that has
3918 * had some COW done. Since pages might have been
3919 * written, check ability to execute the possibly
3920 * modified content. This typically should only
3921 * occur for text relocations.
3923 rc = file_has_perm(cred, vma->vm_file, FILE__EXECMOD);
3929 return file_map_prot_check(vma->vm_file, prot, vma->vm_flags&VM_SHARED);
3932 static int selinux_file_lock(struct file *file, unsigned int cmd)
3934 const struct cred *cred = current_cred();
3936 return file_has_perm(cred, file, FILE__LOCK);
3939 static int selinux_file_fcntl(struct file *file, unsigned int cmd,
3942 const struct cred *cred = current_cred();
3947 if ((file->f_flags & O_APPEND) && !(arg & O_APPEND)) {
3948 err = file_has_perm(cred, file, FILE__WRITE);
3957 case F_GETOWNER_UIDS:
3958 /* Just check FD__USE permission */
3959 err = file_has_perm(cred, file, 0);
3967 #if BITS_PER_LONG == 32
3972 err = file_has_perm(cred, file, FILE__LOCK);
3979 static void selinux_file_set_fowner(struct file *file)
3981 struct file_security_struct *fsec;
3983 fsec = selinux_file(file);
3984 fsec->fown_sid = current_sid();
3987 static int selinux_file_send_sigiotask(struct task_struct *tsk,
3988 struct fown_struct *fown, int signum)
3991 u32 sid = task_sid_obj(tsk);
3993 struct file_security_struct *fsec;
3995 /* struct fown_struct is never outside the context of a struct file */
3996 file = container_of(fown, struct file, f_owner);
3998 fsec = selinux_file(file);
4001 perm = signal_to_av(SIGIO); /* as per send_sigio_to_task */
4003 perm = signal_to_av(signum);
4005 return avc_has_perm(&selinux_state,
4006 fsec->fown_sid, sid,
4007 SECCLASS_PROCESS, perm, NULL);
4010 static int selinux_file_receive(struct file *file)
4012 const struct cred *cred = current_cred();
4014 return file_has_perm(cred, file, file_to_av(file));
4017 static int selinux_file_open(struct file *file)
4019 struct file_security_struct *fsec;
4020 struct inode_security_struct *isec;
4022 fsec = selinux_file(file);
4023 isec = inode_security(file_inode(file));
4025 * Save inode label and policy sequence number
4026 * at open-time so that selinux_file_permission
4027 * can determine whether revalidation is necessary.
4028 * Task label is already saved in the file security
4029 * struct as its SID.
4031 fsec->isid = isec->sid;
4032 fsec->pseqno = avc_policy_seqno(&selinux_state);
4034 * Since the inode label or policy seqno may have changed
4035 * between the selinux_inode_permission check and the saving
4036 * of state above, recheck that access is still permitted.
4037 * Otherwise, access might never be revalidated against the
4038 * new inode label or new policy.
4039 * This check is not redundant - do not remove.
4041 return file_path_has_perm(file->f_cred, file, open_file_to_av(file));
4044 /* task security operations */
4046 static int selinux_task_alloc(struct task_struct *task,
4047 unsigned long clone_flags)
4049 u32 sid = current_sid();
4051 return avc_has_perm(&selinux_state,
4052 sid, sid, SECCLASS_PROCESS, PROCESS__FORK, NULL);
4056 * prepare a new set of credentials for modification
4058 static int selinux_cred_prepare(struct cred *new, const struct cred *old,
4061 const struct task_security_struct *old_tsec = selinux_cred(old);
4062 struct task_security_struct *tsec = selinux_cred(new);
4069 * transfer the SELinux data to a blank set of creds
4071 static void selinux_cred_transfer(struct cred *new, const struct cred *old)
4073 const struct task_security_struct *old_tsec = selinux_cred(old);
4074 struct task_security_struct *tsec = selinux_cred(new);
4079 static void selinux_cred_getsecid(const struct cred *c, u32 *secid)
4081 *secid = cred_sid(c);
4085 * set the security data for a kernel service
4086 * - all the creation contexts are set to unlabelled
4088 static int selinux_kernel_act_as(struct cred *new, u32 secid)
4090 struct task_security_struct *tsec = selinux_cred(new);
4091 u32 sid = current_sid();
4094 ret = avc_has_perm(&selinux_state,
4096 SECCLASS_KERNEL_SERVICE,
4097 KERNEL_SERVICE__USE_AS_OVERRIDE,
4101 tsec->create_sid = 0;
4102 tsec->keycreate_sid = 0;
4103 tsec->sockcreate_sid = 0;
4109 * set the file creation context in a security record to the same as the
4110 * objective context of the specified inode
4112 static int selinux_kernel_create_files_as(struct cred *new, struct inode *inode)
4114 struct inode_security_struct *isec = inode_security(inode);
4115 struct task_security_struct *tsec = selinux_cred(new);
4116 u32 sid = current_sid();
4119 ret = avc_has_perm(&selinux_state,
4121 SECCLASS_KERNEL_SERVICE,
4122 KERNEL_SERVICE__CREATE_FILES_AS,
4126 tsec->create_sid = isec->sid;
4130 static int selinux_kernel_module_request(char *kmod_name)
4132 struct common_audit_data ad;
4134 ad.type = LSM_AUDIT_DATA_KMOD;
4135 ad.u.kmod_name = kmod_name;
4137 return avc_has_perm(&selinux_state,
4138 current_sid(), SECINITSID_KERNEL, SECCLASS_SYSTEM,
4139 SYSTEM__MODULE_REQUEST, &ad);
4142 static int selinux_kernel_module_from_file(struct file *file)
4144 struct common_audit_data ad;
4145 struct inode_security_struct *isec;
4146 struct file_security_struct *fsec;
4147 u32 sid = current_sid();
4152 return avc_has_perm(&selinux_state,
4153 sid, sid, SECCLASS_SYSTEM,
4154 SYSTEM__MODULE_LOAD, NULL);
4158 ad.type = LSM_AUDIT_DATA_FILE;
4161 fsec = selinux_file(file);
4162 if (sid != fsec->sid) {
4163 rc = avc_has_perm(&selinux_state,
4164 sid, fsec->sid, SECCLASS_FD, FD__USE, &ad);
4169 isec = inode_security(file_inode(file));
4170 return avc_has_perm(&selinux_state,
4171 sid, isec->sid, SECCLASS_SYSTEM,
4172 SYSTEM__MODULE_LOAD, &ad);
4175 static int selinux_kernel_read_file(struct file *file,
4176 enum kernel_read_file_id id,
4182 case READING_MODULE:
4183 rc = selinux_kernel_module_from_file(contents ? file : NULL);
4192 static int selinux_kernel_load_data(enum kernel_load_data_id id, bool contents)
4197 case LOADING_MODULE:
4198 rc = selinux_kernel_module_from_file(NULL);
4207 static int selinux_task_setpgid(struct task_struct *p, pid_t pgid)
4209 return avc_has_perm(&selinux_state,
4210 current_sid(), task_sid_obj(p), SECCLASS_PROCESS,
4211 PROCESS__SETPGID, NULL);
4214 static int selinux_task_getpgid(struct task_struct *p)
4216 return avc_has_perm(&selinux_state,
4217 current_sid(), task_sid_obj(p), SECCLASS_PROCESS,
4218 PROCESS__GETPGID, NULL);
4221 static int selinux_task_getsid(struct task_struct *p)
4223 return avc_has_perm(&selinux_state,
4224 current_sid(), task_sid_obj(p), SECCLASS_PROCESS,
4225 PROCESS__GETSESSION, NULL);
4228 static void selinux_task_getsecid_subj(struct task_struct *p, u32 *secid)
4230 *secid = task_sid_subj(p);
4233 static void selinux_task_getsecid_obj(struct task_struct *p, u32 *secid)
4235 *secid = task_sid_obj(p);
4238 static int selinux_task_setnice(struct task_struct *p, int nice)
4240 return avc_has_perm(&selinux_state,
4241 current_sid(), task_sid_obj(p), SECCLASS_PROCESS,
4242 PROCESS__SETSCHED, NULL);
4245 static int selinux_task_setioprio(struct task_struct *p, int ioprio)
4247 return avc_has_perm(&selinux_state,
4248 current_sid(), task_sid_obj(p), SECCLASS_PROCESS,
4249 PROCESS__SETSCHED, NULL);
4252 static int selinux_task_getioprio(struct task_struct *p)
4254 return avc_has_perm(&selinux_state,
4255 current_sid(), task_sid_obj(p), SECCLASS_PROCESS,
4256 PROCESS__GETSCHED, NULL);
4259 static int selinux_task_prlimit(const struct cred *cred, const struct cred *tcred,
4266 if (flags & LSM_PRLIMIT_WRITE)
4267 av |= PROCESS__SETRLIMIT;
4268 if (flags & LSM_PRLIMIT_READ)
4269 av |= PROCESS__GETRLIMIT;
4270 return avc_has_perm(&selinux_state,
4271 cred_sid(cred), cred_sid(tcred),
4272 SECCLASS_PROCESS, av, NULL);
4275 static int selinux_task_setrlimit(struct task_struct *p, unsigned int resource,
4276 struct rlimit *new_rlim)
4278 struct rlimit *old_rlim = p->signal->rlim + resource;
4280 /* Control the ability to change the hard limit (whether
4281 lowering or raising it), so that the hard limit can
4282 later be used as a safe reset point for the soft limit
4283 upon context transitions. See selinux_bprm_committing_creds. */
4284 if (old_rlim->rlim_max != new_rlim->rlim_max)
4285 return avc_has_perm(&selinux_state,
4286 current_sid(), task_sid_obj(p),
4287 SECCLASS_PROCESS, PROCESS__SETRLIMIT, NULL);
4292 static int selinux_task_setscheduler(struct task_struct *p)
4294 return avc_has_perm(&selinux_state,
4295 current_sid(), task_sid_obj(p), SECCLASS_PROCESS,
4296 PROCESS__SETSCHED, NULL);
4299 static int selinux_task_getscheduler(struct task_struct *p)
4301 return avc_has_perm(&selinux_state,
4302 current_sid(), task_sid_obj(p), SECCLASS_PROCESS,
4303 PROCESS__GETSCHED, NULL);
4306 static int selinux_task_movememory(struct task_struct *p)
4308 return avc_has_perm(&selinux_state,
4309 current_sid(), task_sid_obj(p), SECCLASS_PROCESS,
4310 PROCESS__SETSCHED, NULL);
4313 static int selinux_task_kill(struct task_struct *p, struct kernel_siginfo *info,
4314 int sig, const struct cred *cred)
4320 perm = PROCESS__SIGNULL; /* null signal; existence test */
4322 perm = signal_to_av(sig);
4324 secid = current_sid();
4326 secid = cred_sid(cred);
4327 return avc_has_perm(&selinux_state,
4328 secid, task_sid_obj(p), SECCLASS_PROCESS, perm, NULL);
4331 static void selinux_task_to_inode(struct task_struct *p,
4332 struct inode *inode)
4334 struct inode_security_struct *isec = selinux_inode(inode);
4335 u32 sid = task_sid_obj(p);
4337 spin_lock(&isec->lock);
4338 isec->sclass = inode_mode_to_security_class(inode->i_mode);
4340 isec->initialized = LABEL_INITIALIZED;
4341 spin_unlock(&isec->lock);
4344 /* Returns error only if unable to parse addresses */
4345 static int selinux_parse_skb_ipv4(struct sk_buff *skb,
4346 struct common_audit_data *ad, u8 *proto)
4348 int offset, ihlen, ret = -EINVAL;
4349 struct iphdr _iph, *ih;
4351 offset = skb_network_offset(skb);
4352 ih = skb_header_pointer(skb, offset, sizeof(_iph), &_iph);
4356 ihlen = ih->ihl * 4;
4357 if (ihlen < sizeof(_iph))
4360 ad->u.net->v4info.saddr = ih->saddr;
4361 ad->u.net->v4info.daddr = ih->daddr;
4365 *proto = ih->protocol;
4367 switch (ih->protocol) {
4369 struct tcphdr _tcph, *th;
4371 if (ntohs(ih->frag_off) & IP_OFFSET)
4375 th = skb_header_pointer(skb, offset, sizeof(_tcph), &_tcph);
4379 ad->u.net->sport = th->source;
4380 ad->u.net->dport = th->dest;
4385 struct udphdr _udph, *uh;
4387 if (ntohs(ih->frag_off) & IP_OFFSET)
4391 uh = skb_header_pointer(skb, offset, sizeof(_udph), &_udph);
4395 ad->u.net->sport = uh->source;
4396 ad->u.net->dport = uh->dest;
4400 case IPPROTO_DCCP: {
4401 struct dccp_hdr _dccph, *dh;
4403 if (ntohs(ih->frag_off) & IP_OFFSET)
4407 dh = skb_header_pointer(skb, offset, sizeof(_dccph), &_dccph);
4411 ad->u.net->sport = dh->dccph_sport;
4412 ad->u.net->dport = dh->dccph_dport;
4416 #if IS_ENABLED(CONFIG_IP_SCTP)
4417 case IPPROTO_SCTP: {
4418 struct sctphdr _sctph, *sh;
4420 if (ntohs(ih->frag_off) & IP_OFFSET)
4424 sh = skb_header_pointer(skb, offset, sizeof(_sctph), &_sctph);
4428 ad->u.net->sport = sh->source;
4429 ad->u.net->dport = sh->dest;
4440 #if IS_ENABLED(CONFIG_IPV6)
4442 /* Returns error only if unable to parse addresses */
4443 static int selinux_parse_skb_ipv6(struct sk_buff *skb,
4444 struct common_audit_data *ad, u8 *proto)
4447 int ret = -EINVAL, offset;
4448 struct ipv6hdr _ipv6h, *ip6;
4451 offset = skb_network_offset(skb);
4452 ip6 = skb_header_pointer(skb, offset, sizeof(_ipv6h), &_ipv6h);
4456 ad->u.net->v6info.saddr = ip6->saddr;
4457 ad->u.net->v6info.daddr = ip6->daddr;
4460 nexthdr = ip6->nexthdr;
4461 offset += sizeof(_ipv6h);
4462 offset = ipv6_skip_exthdr(skb, offset, &nexthdr, &frag_off);
4471 struct tcphdr _tcph, *th;
4473 th = skb_header_pointer(skb, offset, sizeof(_tcph), &_tcph);
4477 ad->u.net->sport = th->source;
4478 ad->u.net->dport = th->dest;
4483 struct udphdr _udph, *uh;
4485 uh = skb_header_pointer(skb, offset, sizeof(_udph), &_udph);
4489 ad->u.net->sport = uh->source;
4490 ad->u.net->dport = uh->dest;
4494 case IPPROTO_DCCP: {
4495 struct dccp_hdr _dccph, *dh;
4497 dh = skb_header_pointer(skb, offset, sizeof(_dccph), &_dccph);
4501 ad->u.net->sport = dh->dccph_sport;
4502 ad->u.net->dport = dh->dccph_dport;
4506 #if IS_ENABLED(CONFIG_IP_SCTP)
4507 case IPPROTO_SCTP: {
4508 struct sctphdr _sctph, *sh;
4510 sh = skb_header_pointer(skb, offset, sizeof(_sctph), &_sctph);
4514 ad->u.net->sport = sh->source;
4515 ad->u.net->dport = sh->dest;
4519 /* includes fragments */
4529 static int selinux_parse_skb(struct sk_buff *skb, struct common_audit_data *ad,
4530 char **_addrp, int src, u8 *proto)
4535 switch (ad->u.net->family) {
4537 ret = selinux_parse_skb_ipv4(skb, ad, proto);
4540 addrp = (char *)(src ? &ad->u.net->v4info.saddr :
4541 &ad->u.net->v4info.daddr);
4544 #if IS_ENABLED(CONFIG_IPV6)
4546 ret = selinux_parse_skb_ipv6(skb, ad, proto);
4549 addrp = (char *)(src ? &ad->u.net->v6info.saddr :
4550 &ad->u.net->v6info.daddr);
4560 "SELinux: failure in selinux_parse_skb(),"
4561 " unable to parse packet\n");
4571 * selinux_skb_peerlbl_sid - Determine the peer label of a packet
4573 * @family: protocol family
4574 * @sid: the packet's peer label SID
4577 * Check the various different forms of network peer labeling and determine
4578 * the peer label/SID for the packet; most of the magic actually occurs in
4579 * the security server function security_net_peersid_cmp(). The function
4580 * returns zero if the value in @sid is valid (although it may be SECSID_NULL)
4581 * or -EACCES if @sid is invalid due to inconsistencies with the different
4585 static int selinux_skb_peerlbl_sid(struct sk_buff *skb, u16 family, u32 *sid)
4592 err = selinux_xfrm_skb_sid(skb, &xfrm_sid);
4595 err = selinux_netlbl_skbuff_getsid(skb, family, &nlbl_type, &nlbl_sid);
4599 err = security_net_peersid_resolve(&selinux_state, nlbl_sid,
4600 nlbl_type, xfrm_sid, sid);
4601 if (unlikely(err)) {
4603 "SELinux: failure in selinux_skb_peerlbl_sid(),"
4604 " unable to determine packet's peer label\n");
4612 * selinux_conn_sid - Determine the child socket label for a connection
4613 * @sk_sid: the parent socket's SID
4614 * @skb_sid: the packet's SID
4615 * @conn_sid: the resulting connection SID
4617 * If @skb_sid is valid then the user:role:type information from @sk_sid is
4618 * combined with the MLS information from @skb_sid in order to create
4619 * @conn_sid. If @skb_sid is not valid then @conn_sid is simply a copy
4620 * of @sk_sid. Returns zero on success, negative values on failure.
4623 static int selinux_conn_sid(u32 sk_sid, u32 skb_sid, u32 *conn_sid)
4627 if (skb_sid != SECSID_NULL)
4628 err = security_sid_mls_copy(&selinux_state, sk_sid, skb_sid,
4636 /* socket security operations */
4638 static int socket_sockcreate_sid(const struct task_security_struct *tsec,
4639 u16 secclass, u32 *socksid)
4641 if (tsec->sockcreate_sid > SECSID_NULL) {
4642 *socksid = tsec->sockcreate_sid;
4646 return security_transition_sid(&selinux_state, tsec->sid, tsec->sid,
4647 secclass, NULL, socksid);
4650 static int sock_has_perm(struct sock *sk, u32 perms)
4652 struct sk_security_struct *sksec = sk->sk_security;
4653 struct common_audit_data ad;
4654 struct lsm_network_audit net = {0,};
4656 if (sksec->sid == SECINITSID_KERNEL)
4659 ad.type = LSM_AUDIT_DATA_NET;
4663 return avc_has_perm(&selinux_state,
4664 current_sid(), sksec->sid, sksec->sclass, perms,
4668 static int selinux_socket_create(int family, int type,
4669 int protocol, int kern)
4671 const struct task_security_struct *tsec = selinux_cred(current_cred());
4679 secclass = socket_type_to_security_class(family, type, protocol);
4680 rc = socket_sockcreate_sid(tsec, secclass, &newsid);
4684 return avc_has_perm(&selinux_state,
4685 tsec->sid, newsid, secclass, SOCKET__CREATE, NULL);
4688 static int selinux_socket_post_create(struct socket *sock, int family,
4689 int type, int protocol, int kern)
4691 const struct task_security_struct *tsec = selinux_cred(current_cred());
4692 struct inode_security_struct *isec = inode_security_novalidate(SOCK_INODE(sock));
4693 struct sk_security_struct *sksec;
4694 u16 sclass = socket_type_to_security_class(family, type, protocol);
4695 u32 sid = SECINITSID_KERNEL;
4699 err = socket_sockcreate_sid(tsec, sclass, &sid);
4704 isec->sclass = sclass;
4706 isec->initialized = LABEL_INITIALIZED;
4709 sksec = sock->sk->sk_security;
4710 sksec->sclass = sclass;
4712 /* Allows detection of the first association on this socket */
4713 if (sksec->sclass == SECCLASS_SCTP_SOCKET)
4714 sksec->sctp_assoc_state = SCTP_ASSOC_UNSET;
4716 err = selinux_netlbl_socket_post_create(sock->sk, family);
4722 static int selinux_socket_socketpair(struct socket *socka,
4723 struct socket *sockb)
4725 struct sk_security_struct *sksec_a = socka->sk->sk_security;
4726 struct sk_security_struct *sksec_b = sockb->sk->sk_security;
4728 sksec_a->peer_sid = sksec_b->sid;
4729 sksec_b->peer_sid = sksec_a->sid;
4734 /* Range of port numbers used to automatically bind.
4735 Need to determine whether we should perform a name_bind
4736 permission check between the socket and the port number. */
4738 static int selinux_socket_bind(struct socket *sock, struct sockaddr *address, int addrlen)
4740 struct sock *sk = sock->sk;
4741 struct sk_security_struct *sksec = sk->sk_security;
4745 err = sock_has_perm(sk, SOCKET__BIND);
4749 /* If PF_INET or PF_INET6, check name_bind permission for the port. */
4750 family = sk->sk_family;
4751 if (family == PF_INET || family == PF_INET6) {
4753 struct common_audit_data ad;
4754 struct lsm_network_audit net = {0,};
4755 struct sockaddr_in *addr4 = NULL;
4756 struct sockaddr_in6 *addr6 = NULL;
4758 unsigned short snum;
4762 * sctp_bindx(3) calls via selinux_sctp_bind_connect()
4763 * that validates multiple binding addresses. Because of this
4764 * need to check address->sa_family as it is possible to have
4765 * sk->sk_family = PF_INET6 with addr->sa_family = AF_INET.
4767 if (addrlen < offsetofend(struct sockaddr, sa_family))
4769 family_sa = address->sa_family;
4770 switch (family_sa) {
4773 if (addrlen < sizeof(struct sockaddr_in))
4775 addr4 = (struct sockaddr_in *)address;
4776 if (family_sa == AF_UNSPEC) {
4777 /* see __inet_bind(), we only want to allow
4778 * AF_UNSPEC if the address is INADDR_ANY
4780 if (addr4->sin_addr.s_addr != htonl(INADDR_ANY))
4782 family_sa = AF_INET;
4784 snum = ntohs(addr4->sin_port);
4785 addrp = (char *)&addr4->sin_addr.s_addr;
4788 if (addrlen < SIN6_LEN_RFC2133)
4790 addr6 = (struct sockaddr_in6 *)address;
4791 snum = ntohs(addr6->sin6_port);
4792 addrp = (char *)&addr6->sin6_addr.s6_addr;
4798 ad.type = LSM_AUDIT_DATA_NET;
4800 ad.u.net->sport = htons(snum);
4801 ad.u.net->family = family_sa;
4806 inet_get_local_port_range(sock_net(sk), &low, &high);
4808 if (inet_port_requires_bind_service(sock_net(sk), snum) ||
4809 snum < low || snum > high) {
4810 err = sel_netport_sid(sk->sk_protocol,
4814 err = avc_has_perm(&selinux_state,
4817 SOCKET__NAME_BIND, &ad);
4823 switch (sksec->sclass) {
4824 case SECCLASS_TCP_SOCKET:
4825 node_perm = TCP_SOCKET__NODE_BIND;
4828 case SECCLASS_UDP_SOCKET:
4829 node_perm = UDP_SOCKET__NODE_BIND;
4832 case SECCLASS_DCCP_SOCKET:
4833 node_perm = DCCP_SOCKET__NODE_BIND;
4836 case SECCLASS_SCTP_SOCKET:
4837 node_perm = SCTP_SOCKET__NODE_BIND;
4841 node_perm = RAWIP_SOCKET__NODE_BIND;
4845 err = sel_netnode_sid(addrp, family_sa, &sid);
4849 if (family_sa == AF_INET)
4850 ad.u.net->v4info.saddr = addr4->sin_addr.s_addr;
4852 ad.u.net->v6info.saddr = addr6->sin6_addr;
4854 err = avc_has_perm(&selinux_state,
4856 sksec->sclass, node_perm, &ad);
4863 /* Note that SCTP services expect -EINVAL, others -EAFNOSUPPORT. */
4864 if (sksec->sclass == SECCLASS_SCTP_SOCKET)
4866 return -EAFNOSUPPORT;
4869 /* This supports connect(2) and SCTP connect services such as sctp_connectx(3)
4870 * and sctp_sendmsg(3) as described in Documentation/security/SCTP.rst
4872 static int selinux_socket_connect_helper(struct socket *sock,
4873 struct sockaddr *address, int addrlen)
4875 struct sock *sk = sock->sk;
4876 struct sk_security_struct *sksec = sk->sk_security;
4879 err = sock_has_perm(sk, SOCKET__CONNECT);
4882 if (addrlen < offsetofend(struct sockaddr, sa_family))
4885 /* connect(AF_UNSPEC) has special handling, as it is a documented
4886 * way to disconnect the socket
4888 if (address->sa_family == AF_UNSPEC)
4892 * If a TCP, DCCP or SCTP socket, check name_connect permission
4895 if (sksec->sclass == SECCLASS_TCP_SOCKET ||
4896 sksec->sclass == SECCLASS_DCCP_SOCKET ||
4897 sksec->sclass == SECCLASS_SCTP_SOCKET) {
4898 struct common_audit_data ad;
4899 struct lsm_network_audit net = {0,};
4900 struct sockaddr_in *addr4 = NULL;
4901 struct sockaddr_in6 *addr6 = NULL;
4902 unsigned short snum;
4905 /* sctp_connectx(3) calls via selinux_sctp_bind_connect()
4906 * that validates multiple connect addresses. Because of this
4907 * need to check address->sa_family as it is possible to have
4908 * sk->sk_family = PF_INET6 with addr->sa_family = AF_INET.
4910 switch (address->sa_family) {
4912 addr4 = (struct sockaddr_in *)address;
4913 if (addrlen < sizeof(struct sockaddr_in))
4915 snum = ntohs(addr4->sin_port);
4918 addr6 = (struct sockaddr_in6 *)address;
4919 if (addrlen < SIN6_LEN_RFC2133)
4921 snum = ntohs(addr6->sin6_port);
4924 /* Note that SCTP services expect -EINVAL, whereas
4925 * others expect -EAFNOSUPPORT.
4927 if (sksec->sclass == SECCLASS_SCTP_SOCKET)
4930 return -EAFNOSUPPORT;
4933 err = sel_netport_sid(sk->sk_protocol, snum, &sid);
4937 switch (sksec->sclass) {
4938 case SECCLASS_TCP_SOCKET:
4939 perm = TCP_SOCKET__NAME_CONNECT;
4941 case SECCLASS_DCCP_SOCKET:
4942 perm = DCCP_SOCKET__NAME_CONNECT;
4944 case SECCLASS_SCTP_SOCKET:
4945 perm = SCTP_SOCKET__NAME_CONNECT;
4949 ad.type = LSM_AUDIT_DATA_NET;
4951 ad.u.net->dport = htons(snum);
4952 ad.u.net->family = address->sa_family;
4953 err = avc_has_perm(&selinux_state,
4954 sksec->sid, sid, sksec->sclass, perm, &ad);
4962 /* Supports connect(2), see comments in selinux_socket_connect_helper() */
4963 static int selinux_socket_connect(struct socket *sock,
4964 struct sockaddr *address, int addrlen)
4967 struct sock *sk = sock->sk;
4969 err = selinux_socket_connect_helper(sock, address, addrlen);
4973 return selinux_netlbl_socket_connect(sk, address);
4976 static int selinux_socket_listen(struct socket *sock, int backlog)
4978 return sock_has_perm(sock->sk, SOCKET__LISTEN);
4981 static int selinux_socket_accept(struct socket *sock, struct socket *newsock)
4984 struct inode_security_struct *isec;
4985 struct inode_security_struct *newisec;
4989 err = sock_has_perm(sock->sk, SOCKET__ACCEPT);
4993 isec = inode_security_novalidate(SOCK_INODE(sock));
4994 spin_lock(&isec->lock);
4995 sclass = isec->sclass;
4997 spin_unlock(&isec->lock);
4999 newisec = inode_security_novalidate(SOCK_INODE(newsock));
5000 newisec->sclass = sclass;
5002 newisec->initialized = LABEL_INITIALIZED;
5007 static int selinux_socket_sendmsg(struct socket *sock, struct msghdr *msg,
5010 return sock_has_perm(sock->sk, SOCKET__WRITE);
5013 static int selinux_socket_recvmsg(struct socket *sock, struct msghdr *msg,
5014 int size, int flags)
5016 return sock_has_perm(sock->sk, SOCKET__READ);
5019 static int selinux_socket_getsockname(struct socket *sock)
5021 return sock_has_perm(sock->sk, SOCKET__GETATTR);
5024 static int selinux_socket_getpeername(struct socket *sock)
5026 return sock_has_perm(sock->sk, SOCKET__GETATTR);
5029 static int selinux_socket_setsockopt(struct socket *sock, int level, int optname)
5033 err = sock_has_perm(sock->sk, SOCKET__SETOPT);
5037 return selinux_netlbl_socket_setsockopt(sock, level, optname);
5040 static int selinux_socket_getsockopt(struct socket *sock, int level,
5043 return sock_has_perm(sock->sk, SOCKET__GETOPT);
5046 static int selinux_socket_shutdown(struct socket *sock, int how)
5048 return sock_has_perm(sock->sk, SOCKET__SHUTDOWN);
5051 static int selinux_socket_unix_stream_connect(struct sock *sock,
5055 struct sk_security_struct *sksec_sock = sock->sk_security;
5056 struct sk_security_struct *sksec_other = other->sk_security;
5057 struct sk_security_struct *sksec_new = newsk->sk_security;
5058 struct common_audit_data ad;
5059 struct lsm_network_audit net = {0,};
5062 ad.type = LSM_AUDIT_DATA_NET;
5064 ad.u.net->sk = other;
5066 err = avc_has_perm(&selinux_state,
5067 sksec_sock->sid, sksec_other->sid,
5068 sksec_other->sclass,
5069 UNIX_STREAM_SOCKET__CONNECTTO, &ad);
5073 /* server child socket */
5074 sksec_new->peer_sid = sksec_sock->sid;
5075 err = security_sid_mls_copy(&selinux_state, sksec_other->sid,
5076 sksec_sock->sid, &sksec_new->sid);
5080 /* connecting socket */
5081 sksec_sock->peer_sid = sksec_new->sid;
5086 static int selinux_socket_unix_may_send(struct socket *sock,
5087 struct socket *other)
5089 struct sk_security_struct *ssec = sock->sk->sk_security;
5090 struct sk_security_struct *osec = other->sk->sk_security;
5091 struct common_audit_data ad;
5092 struct lsm_network_audit net = {0,};
5094 ad.type = LSM_AUDIT_DATA_NET;
5096 ad.u.net->sk = other->sk;
5098 return avc_has_perm(&selinux_state,
5099 ssec->sid, osec->sid, osec->sclass, SOCKET__SENDTO,
5103 static int selinux_inet_sys_rcv_skb(struct net *ns, int ifindex,
5104 char *addrp, u16 family, u32 peer_sid,
5105 struct common_audit_data *ad)
5111 err = sel_netif_sid(ns, ifindex, &if_sid);
5114 err = avc_has_perm(&selinux_state,
5116 SECCLASS_NETIF, NETIF__INGRESS, ad);
5120 err = sel_netnode_sid(addrp, family, &node_sid);
5123 return avc_has_perm(&selinux_state,
5125 SECCLASS_NODE, NODE__RECVFROM, ad);
5128 static int selinux_sock_rcv_skb_compat(struct sock *sk, struct sk_buff *skb,
5132 struct sk_security_struct *sksec = sk->sk_security;
5133 u32 sk_sid = sksec->sid;
5134 struct common_audit_data ad;
5135 struct lsm_network_audit net = {0,};
5138 ad.type = LSM_AUDIT_DATA_NET;
5140 ad.u.net->netif = skb->skb_iif;
5141 ad.u.net->family = family;
5142 err = selinux_parse_skb(skb, &ad, &addrp, 1, NULL);
5146 if (selinux_secmark_enabled()) {
5147 err = avc_has_perm(&selinux_state,
5148 sk_sid, skb->secmark, SECCLASS_PACKET,
5154 err = selinux_netlbl_sock_rcv_skb(sksec, skb, family, &ad);
5157 err = selinux_xfrm_sock_rcv_skb(sksec->sid, skb, &ad);
5162 static int selinux_socket_sock_rcv_skb(struct sock *sk, struct sk_buff *skb)
5165 struct sk_security_struct *sksec = sk->sk_security;
5166 u16 family = sk->sk_family;
5167 u32 sk_sid = sksec->sid;
5168 struct common_audit_data ad;
5169 struct lsm_network_audit net = {0,};
5174 if (family != PF_INET && family != PF_INET6)
5177 /* Handle mapped IPv4 packets arriving via IPv6 sockets */
5178 if (family == PF_INET6 && skb->protocol == htons(ETH_P_IP))
5181 /* If any sort of compatibility mode is enabled then handoff processing
5182 * to the selinux_sock_rcv_skb_compat() function to deal with the
5183 * special handling. We do this in an attempt to keep this function
5184 * as fast and as clean as possible. */
5185 if (!selinux_policycap_netpeer())
5186 return selinux_sock_rcv_skb_compat(sk, skb, family);
5188 secmark_active = selinux_secmark_enabled();
5189 peerlbl_active = selinux_peerlbl_enabled();
5190 if (!secmark_active && !peerlbl_active)
5193 ad.type = LSM_AUDIT_DATA_NET;
5195 ad.u.net->netif = skb->skb_iif;
5196 ad.u.net->family = family;
5197 err = selinux_parse_skb(skb, &ad, &addrp, 1, NULL);
5201 if (peerlbl_active) {
5204 err = selinux_skb_peerlbl_sid(skb, family, &peer_sid);
5207 err = selinux_inet_sys_rcv_skb(sock_net(sk), skb->skb_iif,
5208 addrp, family, peer_sid, &ad);
5210 selinux_netlbl_err(skb, family, err, 0);
5213 err = avc_has_perm(&selinux_state,
5214 sk_sid, peer_sid, SECCLASS_PEER,
5217 selinux_netlbl_err(skb, family, err, 0);
5222 if (secmark_active) {
5223 err = avc_has_perm(&selinux_state,
5224 sk_sid, skb->secmark, SECCLASS_PACKET,
5233 static int selinux_socket_getpeersec_stream(struct socket *sock, char __user *optval,
5234 int __user *optlen, unsigned len)
5239 struct sk_security_struct *sksec = sock->sk->sk_security;
5240 u32 peer_sid = SECSID_NULL;
5242 if (sksec->sclass == SECCLASS_UNIX_STREAM_SOCKET ||
5243 sksec->sclass == SECCLASS_TCP_SOCKET ||
5244 sksec->sclass == SECCLASS_SCTP_SOCKET)
5245 peer_sid = sksec->peer_sid;
5246 if (peer_sid == SECSID_NULL)
5247 return -ENOPROTOOPT;
5249 err = security_sid_to_context(&selinux_state, peer_sid, &scontext,
5254 if (scontext_len > len) {
5259 if (copy_to_user(optval, scontext, scontext_len))
5263 if (put_user(scontext_len, optlen))
5269 static int selinux_socket_getpeersec_dgram(struct socket *sock, struct sk_buff *skb, u32 *secid)
5271 u32 peer_secid = SECSID_NULL;
5273 struct inode_security_struct *isec;
5275 if (skb && skb->protocol == htons(ETH_P_IP))
5277 else if (skb && skb->protocol == htons(ETH_P_IPV6))
5280 family = sock->sk->sk_family;
5284 if (sock && family == PF_UNIX) {
5285 isec = inode_security_novalidate(SOCK_INODE(sock));
5286 peer_secid = isec->sid;
5288 selinux_skb_peerlbl_sid(skb, family, &peer_secid);
5291 *secid = peer_secid;
5292 if (peer_secid == SECSID_NULL)
5297 static int selinux_sk_alloc_security(struct sock *sk, int family, gfp_t priority)
5299 struct sk_security_struct *sksec;
5301 sksec = kzalloc(sizeof(*sksec), priority);
5305 sksec->peer_sid = SECINITSID_UNLABELED;
5306 sksec->sid = SECINITSID_UNLABELED;
5307 sksec->sclass = SECCLASS_SOCKET;
5308 selinux_netlbl_sk_security_reset(sksec);
5309 sk->sk_security = sksec;
5314 static void selinux_sk_free_security(struct sock *sk)
5316 struct sk_security_struct *sksec = sk->sk_security;
5318 sk->sk_security = NULL;
5319 selinux_netlbl_sk_security_free(sksec);
5323 static void selinux_sk_clone_security(const struct sock *sk, struct sock *newsk)
5325 struct sk_security_struct *sksec = sk->sk_security;
5326 struct sk_security_struct *newsksec = newsk->sk_security;
5328 newsksec->sid = sksec->sid;
5329 newsksec->peer_sid = sksec->peer_sid;
5330 newsksec->sclass = sksec->sclass;
5332 selinux_netlbl_sk_security_reset(newsksec);
5335 static void selinux_sk_getsecid(struct sock *sk, u32 *secid)
5338 *secid = SECINITSID_ANY_SOCKET;
5340 struct sk_security_struct *sksec = sk->sk_security;
5342 *secid = sksec->sid;
5346 static void selinux_sock_graft(struct sock *sk, struct socket *parent)
5348 struct inode_security_struct *isec =
5349 inode_security_novalidate(SOCK_INODE(parent));
5350 struct sk_security_struct *sksec = sk->sk_security;
5352 if (sk->sk_family == PF_INET || sk->sk_family == PF_INET6 ||
5353 sk->sk_family == PF_UNIX)
5354 isec->sid = sksec->sid;
5355 sksec->sclass = isec->sclass;
5358 /* Called whenever SCTP receives an INIT chunk. This happens when an incoming
5359 * connect(2), sctp_connectx(3) or sctp_sendmsg(3) (with no association
5362 static int selinux_sctp_assoc_request(struct sctp_endpoint *ep,
5363 struct sk_buff *skb)
5365 struct sk_security_struct *sksec = ep->base.sk->sk_security;
5366 struct common_audit_data ad;
5367 struct lsm_network_audit net = {0,};
5369 u32 peer_sid = SECINITSID_UNLABELED;
5373 if (!selinux_policycap_extsockclass())
5376 peerlbl_active = selinux_peerlbl_enabled();
5378 if (peerlbl_active) {
5379 /* This will return peer_sid = SECSID_NULL if there are
5380 * no peer labels, see security_net_peersid_resolve().
5382 err = selinux_skb_peerlbl_sid(skb, ep->base.sk->sk_family,
5387 if (peer_sid == SECSID_NULL)
5388 peer_sid = SECINITSID_UNLABELED;
5391 if (sksec->sctp_assoc_state == SCTP_ASSOC_UNSET) {
5392 sksec->sctp_assoc_state = SCTP_ASSOC_SET;
5394 /* Here as first association on socket. As the peer SID
5395 * was allowed by peer recv (and the netif/node checks),
5396 * then it is approved by policy and used as the primary
5397 * peer SID for getpeercon(3).
5399 sksec->peer_sid = peer_sid;
5400 } else if (sksec->peer_sid != peer_sid) {
5401 /* Other association peer SIDs are checked to enforce
5402 * consistency among the peer SIDs.
5404 ad.type = LSM_AUDIT_DATA_NET;
5406 ad.u.net->sk = ep->base.sk;
5407 err = avc_has_perm(&selinux_state,
5408 sksec->peer_sid, peer_sid, sksec->sclass,
5409 SCTP_SOCKET__ASSOCIATION, &ad);
5414 /* Compute the MLS component for the connection and store
5415 * the information in ep. This will be used by SCTP TCP type
5416 * sockets and peeled off connections as they cause a new
5417 * socket to be generated. selinux_sctp_sk_clone() will then
5418 * plug this into the new socket.
5420 err = selinux_conn_sid(sksec->sid, peer_sid, &conn_sid);
5424 ep->secid = conn_sid;
5425 ep->peer_secid = peer_sid;
5427 /* Set any NetLabel labels including CIPSO/CALIPSO options. */
5428 return selinux_netlbl_sctp_assoc_request(ep, skb);
5431 /* Check if sctp IPv4/IPv6 addresses are valid for binding or connecting
5432 * based on their @optname.
5434 static int selinux_sctp_bind_connect(struct sock *sk, int optname,
5435 struct sockaddr *address,
5438 int len, err = 0, walk_size = 0;
5440 struct sockaddr *addr;
5441 struct socket *sock;
5443 if (!selinux_policycap_extsockclass())
5446 /* Process one or more addresses that may be IPv4 or IPv6 */
5447 sock = sk->sk_socket;
5450 while (walk_size < addrlen) {
5451 if (walk_size + sizeof(sa_family_t) > addrlen)
5455 switch (addr->sa_family) {
5458 len = sizeof(struct sockaddr_in);
5461 len = sizeof(struct sockaddr_in6);
5467 if (walk_size + len > addrlen)
5473 case SCTP_PRIMARY_ADDR:
5474 case SCTP_SET_PEER_PRIMARY_ADDR:
5475 case SCTP_SOCKOPT_BINDX_ADD:
5476 err = selinux_socket_bind(sock, addr, len);
5478 /* Connect checks */
5479 case SCTP_SOCKOPT_CONNECTX:
5480 case SCTP_PARAM_SET_PRIMARY:
5481 case SCTP_PARAM_ADD_IP:
5482 case SCTP_SENDMSG_CONNECT:
5483 err = selinux_socket_connect_helper(sock, addr, len);
5487 /* As selinux_sctp_bind_connect() is called by the
5488 * SCTP protocol layer, the socket is already locked,
5489 * therefore selinux_netlbl_socket_connect_locked()
5490 * is called here. The situations handled are:
5491 * sctp_connectx(3), sctp_sendmsg(3), sendmsg(2),
5492 * whenever a new IP address is added or when a new
5493 * primary address is selected.
5494 * Note that an SCTP connect(2) call happens before
5495 * the SCTP protocol layer and is handled via
5496 * selinux_socket_connect().
5498 err = selinux_netlbl_socket_connect_locked(sk, addr);
5512 /* Called whenever a new socket is created by accept(2) or sctp_peeloff(3). */
5513 static void selinux_sctp_sk_clone(struct sctp_endpoint *ep, struct sock *sk,
5516 struct sk_security_struct *sksec = sk->sk_security;
5517 struct sk_security_struct *newsksec = newsk->sk_security;
5519 /* If policy does not support SECCLASS_SCTP_SOCKET then call
5520 * the non-sctp clone version.
5522 if (!selinux_policycap_extsockclass())
5523 return selinux_sk_clone_security(sk, newsk);
5525 newsksec->sid = ep->secid;
5526 newsksec->peer_sid = ep->peer_secid;
5527 newsksec->sclass = sksec->sclass;
5528 selinux_netlbl_sctp_sk_clone(sk, newsk);
5531 static int selinux_inet_conn_request(const struct sock *sk, struct sk_buff *skb,
5532 struct request_sock *req)
5534 struct sk_security_struct *sksec = sk->sk_security;
5536 u16 family = req->rsk_ops->family;
5540 err = selinux_skb_peerlbl_sid(skb, family, &peersid);
5543 err = selinux_conn_sid(sksec->sid, peersid, &connsid);
5546 req->secid = connsid;
5547 req->peer_secid = peersid;
5549 return selinux_netlbl_inet_conn_request(req, family);
5552 static void selinux_inet_csk_clone(struct sock *newsk,
5553 const struct request_sock *req)
5555 struct sk_security_struct *newsksec = newsk->sk_security;
5557 newsksec->sid = req->secid;
5558 newsksec->peer_sid = req->peer_secid;
5559 /* NOTE: Ideally, we should also get the isec->sid for the
5560 new socket in sync, but we don't have the isec available yet.
5561 So we will wait until sock_graft to do it, by which
5562 time it will have been created and available. */
5564 /* We don't need to take any sort of lock here as we are the only
5565 * thread with access to newsksec */
5566 selinux_netlbl_inet_csk_clone(newsk, req->rsk_ops->family);
5569 static void selinux_inet_conn_established(struct sock *sk, struct sk_buff *skb)
5571 u16 family = sk->sk_family;
5572 struct sk_security_struct *sksec = sk->sk_security;
5574 /* handle mapped IPv4 packets arriving via IPv6 sockets */
5575 if (family == PF_INET6 && skb->protocol == htons(ETH_P_IP))
5578 selinux_skb_peerlbl_sid(skb, family, &sksec->peer_sid);
5581 static int selinux_secmark_relabel_packet(u32 sid)
5583 const struct task_security_struct *__tsec;
5586 __tsec = selinux_cred(current_cred());
5589 return avc_has_perm(&selinux_state,
5590 tsid, sid, SECCLASS_PACKET, PACKET__RELABELTO,
5594 static void selinux_secmark_refcount_inc(void)
5596 atomic_inc(&selinux_secmark_refcount);
5599 static void selinux_secmark_refcount_dec(void)
5601 atomic_dec(&selinux_secmark_refcount);
5604 static void selinux_req_classify_flow(const struct request_sock *req,
5605 struct flowi_common *flic)
5607 flic->flowic_secid = req->secid;
5610 static int selinux_tun_dev_alloc_security(void **security)
5612 struct tun_security_struct *tunsec;
5614 tunsec = kzalloc(sizeof(*tunsec), GFP_KERNEL);
5617 tunsec->sid = current_sid();
5623 static void selinux_tun_dev_free_security(void *security)
5628 static int selinux_tun_dev_create(void)
5630 u32 sid = current_sid();
5632 /* we aren't taking into account the "sockcreate" SID since the socket
5633 * that is being created here is not a socket in the traditional sense,
5634 * instead it is a private sock, accessible only to the kernel, and
5635 * representing a wide range of network traffic spanning multiple
5636 * connections unlike traditional sockets - check the TUN driver to
5637 * get a better understanding of why this socket is special */
5639 return avc_has_perm(&selinux_state,
5640 sid, sid, SECCLASS_TUN_SOCKET, TUN_SOCKET__CREATE,
5644 static int selinux_tun_dev_attach_queue(void *security)
5646 struct tun_security_struct *tunsec = security;
5648 return avc_has_perm(&selinux_state,
5649 current_sid(), tunsec->sid, SECCLASS_TUN_SOCKET,
5650 TUN_SOCKET__ATTACH_QUEUE, NULL);
5653 static int selinux_tun_dev_attach(struct sock *sk, void *security)
5655 struct tun_security_struct *tunsec = security;
5656 struct sk_security_struct *sksec = sk->sk_security;
5658 /* we don't currently perform any NetLabel based labeling here and it
5659 * isn't clear that we would want to do so anyway; while we could apply
5660 * labeling without the support of the TUN user the resulting labeled
5661 * traffic from the other end of the connection would almost certainly
5662 * cause confusion to the TUN user that had no idea network labeling
5663 * protocols were being used */
5665 sksec->sid = tunsec->sid;
5666 sksec->sclass = SECCLASS_TUN_SOCKET;
5671 static int selinux_tun_dev_open(void *security)
5673 struct tun_security_struct *tunsec = security;
5674 u32 sid = current_sid();
5677 err = avc_has_perm(&selinux_state,
5678 sid, tunsec->sid, SECCLASS_TUN_SOCKET,
5679 TUN_SOCKET__RELABELFROM, NULL);
5682 err = avc_has_perm(&selinux_state,
5683 sid, sid, SECCLASS_TUN_SOCKET,
5684 TUN_SOCKET__RELABELTO, NULL);
5692 #ifdef CONFIG_NETFILTER
5694 static unsigned int selinux_ip_forward(struct sk_buff *skb,
5695 const struct net_device *indev,
5701 struct common_audit_data ad;
5702 struct lsm_network_audit net = {0,};
5707 if (!selinux_policycap_netpeer())
5710 secmark_active = selinux_secmark_enabled();
5711 netlbl_active = netlbl_enabled();
5712 peerlbl_active = selinux_peerlbl_enabled();
5713 if (!secmark_active && !peerlbl_active)
5716 if (selinux_skb_peerlbl_sid(skb, family, &peer_sid) != 0)
5719 ad.type = LSM_AUDIT_DATA_NET;
5721 ad.u.net->netif = indev->ifindex;
5722 ad.u.net->family = family;
5723 if (selinux_parse_skb(skb, &ad, &addrp, 1, NULL) != 0)
5726 if (peerlbl_active) {
5727 err = selinux_inet_sys_rcv_skb(dev_net(indev), indev->ifindex,
5728 addrp, family, peer_sid, &ad);
5730 selinux_netlbl_err(skb, family, err, 1);
5736 if (avc_has_perm(&selinux_state,
5737 peer_sid, skb->secmark,
5738 SECCLASS_PACKET, PACKET__FORWARD_IN, &ad))
5742 /* we do this in the FORWARD path and not the POST_ROUTING
5743 * path because we want to make sure we apply the necessary
5744 * labeling before IPsec is applied so we can leverage AH
5746 if (selinux_netlbl_skbuff_setsid(skb, family, peer_sid) != 0)
5752 static unsigned int selinux_ipv4_forward(void *priv,
5753 struct sk_buff *skb,
5754 const struct nf_hook_state *state)
5756 return selinux_ip_forward(skb, state->in, PF_INET);
5759 #if IS_ENABLED(CONFIG_IPV6)
5760 static unsigned int selinux_ipv6_forward(void *priv,
5761 struct sk_buff *skb,
5762 const struct nf_hook_state *state)
5764 return selinux_ip_forward(skb, state->in, PF_INET6);
5768 static unsigned int selinux_ip_output(struct sk_buff *skb,
5774 if (!netlbl_enabled())
5777 /* we do this in the LOCAL_OUT path and not the POST_ROUTING path
5778 * because we want to make sure we apply the necessary labeling
5779 * before IPsec is applied so we can leverage AH protection */
5782 struct sk_security_struct *sksec;
5784 if (sk_listener(sk))
5785 /* if the socket is the listening state then this
5786 * packet is a SYN-ACK packet which means it needs to
5787 * be labeled based on the connection/request_sock and
5788 * not the parent socket. unfortunately, we can't
5789 * lookup the request_sock yet as it isn't queued on
5790 * the parent socket until after the SYN-ACK is sent.
5791 * the "solution" is to simply pass the packet as-is
5792 * as any IP option based labeling should be copied
5793 * from the initial connection request (in the IP
5794 * layer). it is far from ideal, but until we get a
5795 * security label in the packet itself this is the
5796 * best we can do. */
5799 /* standard practice, label using the parent socket */
5800 sksec = sk->sk_security;
5803 sid = SECINITSID_KERNEL;
5804 if (selinux_netlbl_skbuff_setsid(skb, family, sid) != 0)
5810 static unsigned int selinux_ipv4_output(void *priv,
5811 struct sk_buff *skb,
5812 const struct nf_hook_state *state)
5814 return selinux_ip_output(skb, PF_INET);
5817 #if IS_ENABLED(CONFIG_IPV6)
5818 static unsigned int selinux_ipv6_output(void *priv,
5819 struct sk_buff *skb,
5820 const struct nf_hook_state *state)
5822 return selinux_ip_output(skb, PF_INET6);
5826 static unsigned int selinux_ip_postroute_compat(struct sk_buff *skb,
5830 struct sock *sk = skb_to_full_sk(skb);
5831 struct sk_security_struct *sksec;
5832 struct common_audit_data ad;
5833 struct lsm_network_audit net = {0,};
5839 sksec = sk->sk_security;
5841 ad.type = LSM_AUDIT_DATA_NET;
5843 ad.u.net->netif = ifindex;
5844 ad.u.net->family = family;
5845 if (selinux_parse_skb(skb, &ad, &addrp, 0, &proto))
5848 if (selinux_secmark_enabled())
5849 if (avc_has_perm(&selinux_state,
5850 sksec->sid, skb->secmark,
5851 SECCLASS_PACKET, PACKET__SEND, &ad))
5852 return NF_DROP_ERR(-ECONNREFUSED);
5854 if (selinux_xfrm_postroute_last(sksec->sid, skb, &ad, proto))
5855 return NF_DROP_ERR(-ECONNREFUSED);
5860 static unsigned int selinux_ip_postroute(struct sk_buff *skb,
5861 const struct net_device *outdev,
5866 int ifindex = outdev->ifindex;
5868 struct common_audit_data ad;
5869 struct lsm_network_audit net = {0,};
5874 /* If any sort of compatibility mode is enabled then handoff processing
5875 * to the selinux_ip_postroute_compat() function to deal with the
5876 * special handling. We do this in an attempt to keep this function
5877 * as fast and as clean as possible. */
5878 if (!selinux_policycap_netpeer())
5879 return selinux_ip_postroute_compat(skb, ifindex, family);
5881 secmark_active = selinux_secmark_enabled();
5882 peerlbl_active = selinux_peerlbl_enabled();
5883 if (!secmark_active && !peerlbl_active)
5886 sk = skb_to_full_sk(skb);
5889 /* If skb->dst->xfrm is non-NULL then the packet is undergoing an IPsec
5890 * packet transformation so allow the packet to pass without any checks
5891 * since we'll have another chance to perform access control checks
5892 * when the packet is on it's final way out.
5893 * NOTE: there appear to be some IPv6 multicast cases where skb->dst
5894 * is NULL, in this case go ahead and apply access control.
5895 * NOTE: if this is a local socket (skb->sk != NULL) that is in the
5896 * TCP listening state we cannot wait until the XFRM processing
5897 * is done as we will miss out on the SA label if we do;
5898 * unfortunately, this means more work, but it is only once per
5900 if (skb_dst(skb) != NULL && skb_dst(skb)->xfrm != NULL &&
5901 !(sk && sk_listener(sk)))
5906 /* Without an associated socket the packet is either coming
5907 * from the kernel or it is being forwarded; check the packet
5908 * to determine which and if the packet is being forwarded
5909 * query the packet directly to determine the security label. */
5911 secmark_perm = PACKET__FORWARD_OUT;
5912 if (selinux_skb_peerlbl_sid(skb, family, &peer_sid))
5915 secmark_perm = PACKET__SEND;
5916 peer_sid = SECINITSID_KERNEL;
5918 } else if (sk_listener(sk)) {
5919 /* Locally generated packet but the associated socket is in the
5920 * listening state which means this is a SYN-ACK packet. In
5921 * this particular case the correct security label is assigned
5922 * to the connection/request_sock but unfortunately we can't
5923 * query the request_sock as it isn't queued on the parent
5924 * socket until after the SYN-ACK packet is sent; the only
5925 * viable choice is to regenerate the label like we do in
5926 * selinux_inet_conn_request(). See also selinux_ip_output()
5927 * for similar problems. */
5929 struct sk_security_struct *sksec;
5931 sksec = sk->sk_security;
5932 if (selinux_skb_peerlbl_sid(skb, family, &skb_sid))
5934 /* At this point, if the returned skb peerlbl is SECSID_NULL
5935 * and the packet has been through at least one XFRM
5936 * transformation then we must be dealing with the "final"
5937 * form of labeled IPsec packet; since we've already applied
5938 * all of our access controls on this packet we can safely
5939 * pass the packet. */
5940 if (skb_sid == SECSID_NULL) {
5943 if (IPCB(skb)->flags & IPSKB_XFRM_TRANSFORMED)
5947 if (IP6CB(skb)->flags & IP6SKB_XFRM_TRANSFORMED)
5951 return NF_DROP_ERR(-ECONNREFUSED);
5954 if (selinux_conn_sid(sksec->sid, skb_sid, &peer_sid))
5956 secmark_perm = PACKET__SEND;
5958 /* Locally generated packet, fetch the security label from the
5959 * associated socket. */
5960 struct sk_security_struct *sksec = sk->sk_security;
5961 peer_sid = sksec->sid;
5962 secmark_perm = PACKET__SEND;
5965 ad.type = LSM_AUDIT_DATA_NET;
5967 ad.u.net->netif = ifindex;
5968 ad.u.net->family = family;
5969 if (selinux_parse_skb(skb, &ad, &addrp, 0, NULL))
5973 if (avc_has_perm(&selinux_state,
5974 peer_sid, skb->secmark,
5975 SECCLASS_PACKET, secmark_perm, &ad))
5976 return NF_DROP_ERR(-ECONNREFUSED);
5978 if (peerlbl_active) {
5982 if (sel_netif_sid(dev_net(outdev), ifindex, &if_sid))
5984 if (avc_has_perm(&selinux_state,
5986 SECCLASS_NETIF, NETIF__EGRESS, &ad))
5987 return NF_DROP_ERR(-ECONNREFUSED);
5989 if (sel_netnode_sid(addrp, family, &node_sid))
5991 if (avc_has_perm(&selinux_state,
5993 SECCLASS_NODE, NODE__SENDTO, &ad))
5994 return NF_DROP_ERR(-ECONNREFUSED);
6000 static unsigned int selinux_ipv4_postroute(void *priv,
6001 struct sk_buff *skb,
6002 const struct nf_hook_state *state)
6004 return selinux_ip_postroute(skb, state->out, PF_INET);
6007 #if IS_ENABLED(CONFIG_IPV6)
6008 static unsigned int selinux_ipv6_postroute(void *priv,
6009 struct sk_buff *skb,
6010 const struct nf_hook_state *state)
6012 return selinux_ip_postroute(skb, state->out, PF_INET6);
6016 #endif /* CONFIG_NETFILTER */
6018 static int selinux_netlink_send(struct sock *sk, struct sk_buff *skb)
6021 unsigned int msg_len;
6022 unsigned int data_len = skb->len;
6023 unsigned char *data = skb->data;
6024 struct nlmsghdr *nlh;
6025 struct sk_security_struct *sksec = sk->sk_security;
6026 u16 sclass = sksec->sclass;
6029 while (data_len >= nlmsg_total_size(0)) {
6030 nlh = (struct nlmsghdr *)data;
6032 /* NOTE: the nlmsg_len field isn't reliably set by some netlink
6033 * users which means we can't reject skb's with bogus
6034 * length fields; our solution is to follow what
6035 * netlink_rcv_skb() does and simply skip processing at
6036 * messages with length fields that are clearly junk
6038 if (nlh->nlmsg_len < NLMSG_HDRLEN || nlh->nlmsg_len > data_len)
6041 rc = selinux_nlmsg_lookup(sclass, nlh->nlmsg_type, &perm);
6043 rc = sock_has_perm(sk, perm);
6046 } else if (rc == -EINVAL) {
6047 /* -EINVAL is a missing msg/perm mapping */
6048 pr_warn_ratelimited("SELinux: unrecognized netlink"
6049 " message: protocol=%hu nlmsg_type=%hu sclass=%s"
6050 " pid=%d comm=%s\n",
6051 sk->sk_protocol, nlh->nlmsg_type,
6052 secclass_map[sclass - 1].name,
6053 task_pid_nr(current), current->comm);
6054 if (enforcing_enabled(&selinux_state) &&
6055 !security_get_allow_unknown(&selinux_state))
6058 } else if (rc == -ENOENT) {
6059 /* -ENOENT is a missing socket/class mapping, ignore */
6065 /* move to the next message after applying netlink padding */
6066 msg_len = NLMSG_ALIGN(nlh->nlmsg_len);
6067 if (msg_len >= data_len)
6069 data_len -= msg_len;
6076 static void ipc_init_security(struct ipc_security_struct *isec, u16 sclass)
6078 isec->sclass = sclass;
6079 isec->sid = current_sid();
6082 static int ipc_has_perm(struct kern_ipc_perm *ipc_perms,
6085 struct ipc_security_struct *isec;
6086 struct common_audit_data ad;
6087 u32 sid = current_sid();
6089 isec = selinux_ipc(ipc_perms);
6091 ad.type = LSM_AUDIT_DATA_IPC;
6092 ad.u.ipc_id = ipc_perms->key;
6094 return avc_has_perm(&selinux_state,
6095 sid, isec->sid, isec->sclass, perms, &ad);
6098 static int selinux_msg_msg_alloc_security(struct msg_msg *msg)
6100 struct msg_security_struct *msec;
6102 msec = selinux_msg_msg(msg);
6103 msec->sid = SECINITSID_UNLABELED;
6108 /* message queue security operations */
6109 static int selinux_msg_queue_alloc_security(struct kern_ipc_perm *msq)
6111 struct ipc_security_struct *isec;
6112 struct common_audit_data ad;
6113 u32 sid = current_sid();
6116 isec = selinux_ipc(msq);
6117 ipc_init_security(isec, SECCLASS_MSGQ);
6119 ad.type = LSM_AUDIT_DATA_IPC;
6120 ad.u.ipc_id = msq->key;
6122 rc = avc_has_perm(&selinux_state,
6123 sid, isec->sid, SECCLASS_MSGQ,
6128 static int selinux_msg_queue_associate(struct kern_ipc_perm *msq, int msqflg)
6130 struct ipc_security_struct *isec;
6131 struct common_audit_data ad;
6132 u32 sid = current_sid();
6134 isec = selinux_ipc(msq);
6136 ad.type = LSM_AUDIT_DATA_IPC;
6137 ad.u.ipc_id = msq->key;
6139 return avc_has_perm(&selinux_state,
6140 sid, isec->sid, SECCLASS_MSGQ,
6141 MSGQ__ASSOCIATE, &ad);
6144 static int selinux_msg_queue_msgctl(struct kern_ipc_perm *msq, int cmd)
6152 /* No specific object, just general system-wide information. */
6153 return avc_has_perm(&selinux_state,
6154 current_sid(), SECINITSID_KERNEL,
6155 SECCLASS_SYSTEM, SYSTEM__IPC_INFO, NULL);
6159 perms = MSGQ__GETATTR | MSGQ__ASSOCIATE;
6162 perms = MSGQ__SETATTR;
6165 perms = MSGQ__DESTROY;
6171 err = ipc_has_perm(msq, perms);
6175 static int selinux_msg_queue_msgsnd(struct kern_ipc_perm *msq, struct msg_msg *msg, int msqflg)
6177 struct ipc_security_struct *isec;
6178 struct msg_security_struct *msec;
6179 struct common_audit_data ad;
6180 u32 sid = current_sid();
6183 isec = selinux_ipc(msq);
6184 msec = selinux_msg_msg(msg);
6187 * First time through, need to assign label to the message
6189 if (msec->sid == SECINITSID_UNLABELED) {
6191 * Compute new sid based on current process and
6192 * message queue this message will be stored in
6194 rc = security_transition_sid(&selinux_state, sid, isec->sid,
6195 SECCLASS_MSG, NULL, &msec->sid);
6200 ad.type = LSM_AUDIT_DATA_IPC;
6201 ad.u.ipc_id = msq->key;
6203 /* Can this process write to the queue? */
6204 rc = avc_has_perm(&selinux_state,
6205 sid, isec->sid, SECCLASS_MSGQ,
6208 /* Can this process send the message */
6209 rc = avc_has_perm(&selinux_state,
6210 sid, msec->sid, SECCLASS_MSG,
6213 /* Can the message be put in the queue? */
6214 rc = avc_has_perm(&selinux_state,
6215 msec->sid, isec->sid, SECCLASS_MSGQ,
6216 MSGQ__ENQUEUE, &ad);
6221 static int selinux_msg_queue_msgrcv(struct kern_ipc_perm *msq, struct msg_msg *msg,
6222 struct task_struct *target,
6223 long type, int mode)
6225 struct ipc_security_struct *isec;
6226 struct msg_security_struct *msec;
6227 struct common_audit_data ad;
6228 u32 sid = task_sid_obj(target);
6231 isec = selinux_ipc(msq);
6232 msec = selinux_msg_msg(msg);
6234 ad.type = LSM_AUDIT_DATA_IPC;
6235 ad.u.ipc_id = msq->key;
6237 rc = avc_has_perm(&selinux_state,
6239 SECCLASS_MSGQ, MSGQ__READ, &ad);
6241 rc = avc_has_perm(&selinux_state,
6243 SECCLASS_MSG, MSG__RECEIVE, &ad);
6247 /* Shared Memory security operations */
6248 static int selinux_shm_alloc_security(struct kern_ipc_perm *shp)
6250 struct ipc_security_struct *isec;
6251 struct common_audit_data ad;
6252 u32 sid = current_sid();
6255 isec = selinux_ipc(shp);
6256 ipc_init_security(isec, SECCLASS_SHM);
6258 ad.type = LSM_AUDIT_DATA_IPC;
6259 ad.u.ipc_id = shp->key;
6261 rc = avc_has_perm(&selinux_state,
6262 sid, isec->sid, SECCLASS_SHM,
6267 static int selinux_shm_associate(struct kern_ipc_perm *shp, int shmflg)
6269 struct ipc_security_struct *isec;
6270 struct common_audit_data ad;
6271 u32 sid = current_sid();
6273 isec = selinux_ipc(shp);
6275 ad.type = LSM_AUDIT_DATA_IPC;
6276 ad.u.ipc_id = shp->key;
6278 return avc_has_perm(&selinux_state,
6279 sid, isec->sid, SECCLASS_SHM,
6280 SHM__ASSOCIATE, &ad);
6283 /* Note, at this point, shp is locked down */
6284 static int selinux_shm_shmctl(struct kern_ipc_perm *shp, int cmd)
6292 /* No specific object, just general system-wide information. */
6293 return avc_has_perm(&selinux_state,
6294 current_sid(), SECINITSID_KERNEL,
6295 SECCLASS_SYSTEM, SYSTEM__IPC_INFO, NULL);
6299 perms = SHM__GETATTR | SHM__ASSOCIATE;
6302 perms = SHM__SETATTR;
6309 perms = SHM__DESTROY;
6315 err = ipc_has_perm(shp, perms);
6319 static int selinux_shm_shmat(struct kern_ipc_perm *shp,
6320 char __user *shmaddr, int shmflg)
6324 if (shmflg & SHM_RDONLY)
6327 perms = SHM__READ | SHM__WRITE;
6329 return ipc_has_perm(shp, perms);
6332 /* Semaphore security operations */
6333 static int selinux_sem_alloc_security(struct kern_ipc_perm *sma)
6335 struct ipc_security_struct *isec;
6336 struct common_audit_data ad;
6337 u32 sid = current_sid();
6340 isec = selinux_ipc(sma);
6341 ipc_init_security(isec, SECCLASS_SEM);
6343 ad.type = LSM_AUDIT_DATA_IPC;
6344 ad.u.ipc_id = sma->key;
6346 rc = avc_has_perm(&selinux_state,
6347 sid, isec->sid, SECCLASS_SEM,
6352 static int selinux_sem_associate(struct kern_ipc_perm *sma, int semflg)
6354 struct ipc_security_struct *isec;
6355 struct common_audit_data ad;
6356 u32 sid = current_sid();
6358 isec = selinux_ipc(sma);
6360 ad.type = LSM_AUDIT_DATA_IPC;
6361 ad.u.ipc_id = sma->key;
6363 return avc_has_perm(&selinux_state,
6364 sid, isec->sid, SECCLASS_SEM,
6365 SEM__ASSOCIATE, &ad);
6368 /* Note, at this point, sma is locked down */
6369 static int selinux_sem_semctl(struct kern_ipc_perm *sma, int cmd)
6377 /* No specific object, just general system-wide information. */
6378 return avc_has_perm(&selinux_state,
6379 current_sid(), SECINITSID_KERNEL,
6380 SECCLASS_SYSTEM, SYSTEM__IPC_INFO, NULL);
6384 perms = SEM__GETATTR;
6395 perms = SEM__DESTROY;
6398 perms = SEM__SETATTR;
6403 perms = SEM__GETATTR | SEM__ASSOCIATE;
6409 err = ipc_has_perm(sma, perms);
6413 static int selinux_sem_semop(struct kern_ipc_perm *sma,
6414 struct sembuf *sops, unsigned nsops, int alter)
6419 perms = SEM__READ | SEM__WRITE;
6423 return ipc_has_perm(sma, perms);
6426 static int selinux_ipc_permission(struct kern_ipc_perm *ipcp, short flag)
6432 av |= IPC__UNIX_READ;
6434 av |= IPC__UNIX_WRITE;
6439 return ipc_has_perm(ipcp, av);
6442 static void selinux_ipc_getsecid(struct kern_ipc_perm *ipcp, u32 *secid)
6444 struct ipc_security_struct *isec = selinux_ipc(ipcp);
6448 static void selinux_d_instantiate(struct dentry *dentry, struct inode *inode)
6451 inode_doinit_with_dentry(inode, dentry);
6454 static int selinux_getprocattr(struct task_struct *p,
6455 char *name, char **value)
6457 const struct task_security_struct *__tsec;
6463 __tsec = selinux_cred(__task_cred(p));
6466 error = avc_has_perm(&selinux_state,
6467 current_sid(), __tsec->sid,
6468 SECCLASS_PROCESS, PROCESS__GETATTR, NULL);
6473 if (!strcmp(name, "current"))
6475 else if (!strcmp(name, "prev"))
6477 else if (!strcmp(name, "exec"))
6478 sid = __tsec->exec_sid;
6479 else if (!strcmp(name, "fscreate"))
6480 sid = __tsec->create_sid;
6481 else if (!strcmp(name, "keycreate"))
6482 sid = __tsec->keycreate_sid;
6483 else if (!strcmp(name, "sockcreate"))
6484 sid = __tsec->sockcreate_sid;
6494 error = security_sid_to_context(&selinux_state, sid, value, &len);
6504 static int selinux_setprocattr(const char *name, void *value, size_t size)
6506 struct task_security_struct *tsec;
6508 u32 mysid = current_sid(), sid = 0, ptsid;
6513 * Basic control over ability to set these attributes at all.
6515 if (!strcmp(name, "exec"))
6516 error = avc_has_perm(&selinux_state,
6517 mysid, mysid, SECCLASS_PROCESS,
6518 PROCESS__SETEXEC, NULL);
6519 else if (!strcmp(name, "fscreate"))
6520 error = avc_has_perm(&selinux_state,
6521 mysid, mysid, SECCLASS_PROCESS,
6522 PROCESS__SETFSCREATE, NULL);
6523 else if (!strcmp(name, "keycreate"))
6524 error = avc_has_perm(&selinux_state,
6525 mysid, mysid, SECCLASS_PROCESS,
6526 PROCESS__SETKEYCREATE, NULL);
6527 else if (!strcmp(name, "sockcreate"))
6528 error = avc_has_perm(&selinux_state,
6529 mysid, mysid, SECCLASS_PROCESS,
6530 PROCESS__SETSOCKCREATE, NULL);
6531 else if (!strcmp(name, "current"))
6532 error = avc_has_perm(&selinux_state,
6533 mysid, mysid, SECCLASS_PROCESS,
6534 PROCESS__SETCURRENT, NULL);
6540 /* Obtain a SID for the context, if one was specified. */
6541 if (size && str[0] && str[0] != '\n') {
6542 if (str[size-1] == '\n') {
6546 error = security_context_to_sid(&selinux_state, value, size,
6548 if (error == -EINVAL && !strcmp(name, "fscreate")) {
6549 if (!has_cap_mac_admin(true)) {
6550 struct audit_buffer *ab;
6553 /* We strip a nul only if it is at the end, otherwise the
6554 * context contains a nul and we should audit that */
6555 if (str[size - 1] == '\0')
6556 audit_size = size - 1;
6559 ab = audit_log_start(audit_context(),
6564 audit_log_format(ab, "op=fscreate invalid_context=");
6565 audit_log_n_untrustedstring(ab, value, audit_size);
6570 error = security_context_to_sid_force(
6578 new = prepare_creds();
6582 /* Permission checking based on the specified context is
6583 performed during the actual operation (execve,
6584 open/mkdir/...), when we know the full context of the
6585 operation. See selinux_bprm_creds_for_exec for the execve
6586 checks and may_create for the file creation checks. The
6587 operation will then fail if the context is not permitted. */
6588 tsec = selinux_cred(new);
6589 if (!strcmp(name, "exec")) {
6590 tsec->exec_sid = sid;
6591 } else if (!strcmp(name, "fscreate")) {
6592 tsec->create_sid = sid;
6593 } else if (!strcmp(name, "keycreate")) {
6595 error = avc_has_perm(&selinux_state, mysid, sid,
6596 SECCLASS_KEY, KEY__CREATE, NULL);
6600 tsec->keycreate_sid = sid;
6601 } else if (!strcmp(name, "sockcreate")) {
6602 tsec->sockcreate_sid = sid;
6603 } else if (!strcmp(name, "current")) {
6608 /* Only allow single threaded processes to change context */
6610 if (!current_is_single_threaded()) {
6611 error = security_bounded_transition(&selinux_state,
6617 /* Check permissions for the transition. */
6618 error = avc_has_perm(&selinux_state,
6619 tsec->sid, sid, SECCLASS_PROCESS,
6620 PROCESS__DYNTRANSITION, NULL);
6624 /* Check for ptracing, and update the task SID if ok.
6625 Otherwise, leave SID unchanged and fail. */
6626 ptsid = ptrace_parent_sid();
6628 error = avc_has_perm(&selinux_state,
6629 ptsid, sid, SECCLASS_PROCESS,
6630 PROCESS__PTRACE, NULL);
6649 static int selinux_ismaclabel(const char *name)
6651 return (strcmp(name, XATTR_SELINUX_SUFFIX) == 0);
6654 static int selinux_secid_to_secctx(u32 secid, char **secdata, u32 *seclen)
6656 return security_sid_to_context(&selinux_state, secid,
6660 static int selinux_secctx_to_secid(const char *secdata, u32 seclen, u32 *secid)
6662 return security_context_to_sid(&selinux_state, secdata, seclen,
6666 static void selinux_release_secctx(char *secdata, u32 seclen)
6671 static void selinux_inode_invalidate_secctx(struct inode *inode)
6673 struct inode_security_struct *isec = selinux_inode(inode);
6675 spin_lock(&isec->lock);
6676 isec->initialized = LABEL_INVALID;
6677 spin_unlock(&isec->lock);
6681 * called with inode->i_mutex locked
6683 static int selinux_inode_notifysecctx(struct inode *inode, void *ctx, u32 ctxlen)
6685 int rc = selinux_inode_setsecurity(inode, XATTR_SELINUX_SUFFIX,
6687 /* Do not return error when suppressing label (SBLABEL_MNT not set). */
6688 return rc == -EOPNOTSUPP ? 0 : rc;
6692 * called with inode->i_mutex locked
6694 static int selinux_inode_setsecctx(struct dentry *dentry, void *ctx, u32 ctxlen)
6696 return __vfs_setxattr_noperm(&init_user_ns, dentry, XATTR_NAME_SELINUX,
6700 static int selinux_inode_getsecctx(struct inode *inode, void **ctx, u32 *ctxlen)
6703 len = selinux_inode_getsecurity(&init_user_ns, inode,
6704 XATTR_SELINUX_SUFFIX, ctx, true);
6712 static int selinux_key_alloc(struct key *k, const struct cred *cred,
6713 unsigned long flags)
6715 const struct task_security_struct *tsec;
6716 struct key_security_struct *ksec;
6718 ksec = kzalloc(sizeof(struct key_security_struct), GFP_KERNEL);
6722 tsec = selinux_cred(cred);
6723 if (tsec->keycreate_sid)
6724 ksec->sid = tsec->keycreate_sid;
6726 ksec->sid = tsec->sid;
6732 static void selinux_key_free(struct key *k)
6734 struct key_security_struct *ksec = k->security;
6740 static int selinux_key_permission(key_ref_t key_ref,
6741 const struct cred *cred,
6742 enum key_need_perm need_perm)
6745 struct key_security_struct *ksec;
6748 switch (need_perm) {
6755 case KEY_NEED_WRITE:
6758 case KEY_NEED_SEARCH:
6764 case KEY_NEED_SETATTR:
6765 perm = KEY__SETATTR;
6767 case KEY_NEED_UNLINK:
6768 case KEY_SYSADMIN_OVERRIDE:
6769 case KEY_AUTHTOKEN_OVERRIDE:
6770 case KEY_DEFER_PERM_CHECK:
6778 sid = cred_sid(cred);
6779 key = key_ref_to_ptr(key_ref);
6780 ksec = key->security;
6782 return avc_has_perm(&selinux_state,
6783 sid, ksec->sid, SECCLASS_KEY, perm, NULL);
6786 static int selinux_key_getsecurity(struct key *key, char **_buffer)
6788 struct key_security_struct *ksec = key->security;
6789 char *context = NULL;
6793 rc = security_sid_to_context(&selinux_state, ksec->sid,
6801 #ifdef CONFIG_KEY_NOTIFICATIONS
6802 static int selinux_watch_key(struct key *key)
6804 struct key_security_struct *ksec = key->security;
6805 u32 sid = current_sid();
6807 return avc_has_perm(&selinux_state,
6808 sid, ksec->sid, SECCLASS_KEY, KEY__VIEW, NULL);
6813 #ifdef CONFIG_SECURITY_INFINIBAND
6814 static int selinux_ib_pkey_access(void *ib_sec, u64 subnet_prefix, u16 pkey_val)
6816 struct common_audit_data ad;
6819 struct ib_security_struct *sec = ib_sec;
6820 struct lsm_ibpkey_audit ibpkey;
6822 err = sel_ib_pkey_sid(subnet_prefix, pkey_val, &sid);
6826 ad.type = LSM_AUDIT_DATA_IBPKEY;
6827 ibpkey.subnet_prefix = subnet_prefix;
6828 ibpkey.pkey = pkey_val;
6829 ad.u.ibpkey = &ibpkey;
6830 return avc_has_perm(&selinux_state,
6832 SECCLASS_INFINIBAND_PKEY,
6833 INFINIBAND_PKEY__ACCESS, &ad);
6836 static int selinux_ib_endport_manage_subnet(void *ib_sec, const char *dev_name,
6839 struct common_audit_data ad;
6842 struct ib_security_struct *sec = ib_sec;
6843 struct lsm_ibendport_audit ibendport;
6845 err = security_ib_endport_sid(&selinux_state, dev_name, port_num,
6851 ad.type = LSM_AUDIT_DATA_IBENDPORT;
6852 ibendport.dev_name = dev_name;
6853 ibendport.port = port_num;
6854 ad.u.ibendport = &ibendport;
6855 return avc_has_perm(&selinux_state,
6857 SECCLASS_INFINIBAND_ENDPORT,
6858 INFINIBAND_ENDPORT__MANAGE_SUBNET, &ad);
6861 static int selinux_ib_alloc_security(void **ib_sec)
6863 struct ib_security_struct *sec;
6865 sec = kzalloc(sizeof(*sec), GFP_KERNEL);
6868 sec->sid = current_sid();
6874 static void selinux_ib_free_security(void *ib_sec)
6880 #ifdef CONFIG_BPF_SYSCALL
6881 static int selinux_bpf(int cmd, union bpf_attr *attr,
6884 u32 sid = current_sid();
6888 case BPF_MAP_CREATE:
6889 ret = avc_has_perm(&selinux_state,
6890 sid, sid, SECCLASS_BPF, BPF__MAP_CREATE,
6894 ret = avc_has_perm(&selinux_state,
6895 sid, sid, SECCLASS_BPF, BPF__PROG_LOAD,
6906 static u32 bpf_map_fmode_to_av(fmode_t fmode)
6910 if (fmode & FMODE_READ)
6911 av |= BPF__MAP_READ;
6912 if (fmode & FMODE_WRITE)
6913 av |= BPF__MAP_WRITE;
6917 /* This function will check the file pass through unix socket or binder to see
6918 * if it is a bpf related object. And apply correspinding checks on the bpf
6919 * object based on the type. The bpf maps and programs, not like other files and
6920 * socket, are using a shared anonymous inode inside the kernel as their inode.
6921 * So checking that inode cannot identify if the process have privilege to
6922 * access the bpf object and that's why we have to add this additional check in
6923 * selinux_file_receive and selinux_binder_transfer_files.
6925 static int bpf_fd_pass(struct file *file, u32 sid)
6927 struct bpf_security_struct *bpfsec;
6928 struct bpf_prog *prog;
6929 struct bpf_map *map;
6932 if (file->f_op == &bpf_map_fops) {
6933 map = file->private_data;
6934 bpfsec = map->security;
6935 ret = avc_has_perm(&selinux_state,
6936 sid, bpfsec->sid, SECCLASS_BPF,
6937 bpf_map_fmode_to_av(file->f_mode), NULL);
6940 } else if (file->f_op == &bpf_prog_fops) {
6941 prog = file->private_data;
6942 bpfsec = prog->aux->security;
6943 ret = avc_has_perm(&selinux_state,
6944 sid, bpfsec->sid, SECCLASS_BPF,
6945 BPF__PROG_RUN, NULL);
6952 static int selinux_bpf_map(struct bpf_map *map, fmode_t fmode)
6954 u32 sid = current_sid();
6955 struct bpf_security_struct *bpfsec;
6957 bpfsec = map->security;
6958 return avc_has_perm(&selinux_state,
6959 sid, bpfsec->sid, SECCLASS_BPF,
6960 bpf_map_fmode_to_av(fmode), NULL);
6963 static int selinux_bpf_prog(struct bpf_prog *prog)
6965 u32 sid = current_sid();
6966 struct bpf_security_struct *bpfsec;
6968 bpfsec = prog->aux->security;
6969 return avc_has_perm(&selinux_state,
6970 sid, bpfsec->sid, SECCLASS_BPF,
6971 BPF__PROG_RUN, NULL);
6974 static int selinux_bpf_map_alloc(struct bpf_map *map)
6976 struct bpf_security_struct *bpfsec;
6978 bpfsec = kzalloc(sizeof(*bpfsec), GFP_KERNEL);
6982 bpfsec->sid = current_sid();
6983 map->security = bpfsec;
6988 static void selinux_bpf_map_free(struct bpf_map *map)
6990 struct bpf_security_struct *bpfsec = map->security;
6992 map->security = NULL;
6996 static int selinux_bpf_prog_alloc(struct bpf_prog_aux *aux)
6998 struct bpf_security_struct *bpfsec;
7000 bpfsec = kzalloc(sizeof(*bpfsec), GFP_KERNEL);
7004 bpfsec->sid = current_sid();
7005 aux->security = bpfsec;
7010 static void selinux_bpf_prog_free(struct bpf_prog_aux *aux)
7012 struct bpf_security_struct *bpfsec = aux->security;
7014 aux->security = NULL;
7019 static int selinux_lockdown(enum lockdown_reason what)
7021 struct common_audit_data ad;
7022 u32 sid = current_sid();
7023 int invalid_reason = (what <= LOCKDOWN_NONE) ||
7024 (what == LOCKDOWN_INTEGRITY_MAX) ||
7025 (what >= LOCKDOWN_CONFIDENTIALITY_MAX);
7027 if (WARN(invalid_reason, "Invalid lockdown reason")) {
7028 audit_log(audit_context(),
7029 GFP_ATOMIC, AUDIT_SELINUX_ERR,
7030 "lockdown_reason=invalid");
7034 ad.type = LSM_AUDIT_DATA_LOCKDOWN;
7037 if (what <= LOCKDOWN_INTEGRITY_MAX)
7038 return avc_has_perm(&selinux_state,
7039 sid, sid, SECCLASS_LOCKDOWN,
7040 LOCKDOWN__INTEGRITY, &ad);
7042 return avc_has_perm(&selinux_state,
7043 sid, sid, SECCLASS_LOCKDOWN,
7044 LOCKDOWN__CONFIDENTIALITY, &ad);
7047 struct lsm_blob_sizes selinux_blob_sizes __lsm_ro_after_init = {
7048 .lbs_cred = sizeof(struct task_security_struct),
7049 .lbs_file = sizeof(struct file_security_struct),
7050 .lbs_inode = sizeof(struct inode_security_struct),
7051 .lbs_ipc = sizeof(struct ipc_security_struct),
7052 .lbs_msg_msg = sizeof(struct msg_security_struct),
7053 .lbs_superblock = sizeof(struct superblock_security_struct),
7056 #ifdef CONFIG_PERF_EVENTS
7057 static int selinux_perf_event_open(struct perf_event_attr *attr, int type)
7059 u32 requested, sid = current_sid();
7061 if (type == PERF_SECURITY_OPEN)
7062 requested = PERF_EVENT__OPEN;
7063 else if (type == PERF_SECURITY_CPU)
7064 requested = PERF_EVENT__CPU;
7065 else if (type == PERF_SECURITY_KERNEL)
7066 requested = PERF_EVENT__KERNEL;
7067 else if (type == PERF_SECURITY_TRACEPOINT)
7068 requested = PERF_EVENT__TRACEPOINT;
7072 return avc_has_perm(&selinux_state, sid, sid, SECCLASS_PERF_EVENT,
7076 static int selinux_perf_event_alloc(struct perf_event *event)
7078 struct perf_event_security_struct *perfsec;
7080 perfsec = kzalloc(sizeof(*perfsec), GFP_KERNEL);
7084 perfsec->sid = current_sid();
7085 event->security = perfsec;
7090 static void selinux_perf_event_free(struct perf_event *event)
7092 struct perf_event_security_struct *perfsec = event->security;
7094 event->security = NULL;
7098 static int selinux_perf_event_read(struct perf_event *event)
7100 struct perf_event_security_struct *perfsec = event->security;
7101 u32 sid = current_sid();
7103 return avc_has_perm(&selinux_state, sid, perfsec->sid,
7104 SECCLASS_PERF_EVENT, PERF_EVENT__READ, NULL);
7107 static int selinux_perf_event_write(struct perf_event *event)
7109 struct perf_event_security_struct *perfsec = event->security;
7110 u32 sid = current_sid();
7112 return avc_has_perm(&selinux_state, sid, perfsec->sid,
7113 SECCLASS_PERF_EVENT, PERF_EVENT__WRITE, NULL);
7118 * IMPORTANT NOTE: When adding new hooks, please be careful to keep this order:
7119 * 1. any hooks that don't belong to (2.) or (3.) below,
7120 * 2. hooks that both access structures allocated by other hooks, and allocate
7121 * structures that can be later accessed by other hooks (mostly "cloning"
7123 * 3. hooks that only allocate structures that can be later accessed by other
7124 * hooks ("allocating" hooks).
7126 * Please follow block comment delimiters in the list to keep this order.
7128 * This ordering is needed for SELinux runtime disable to work at least somewhat
7129 * safely. Breaking the ordering rules above might lead to NULL pointer derefs
7130 * when disabling SELinux at runtime.
7132 static struct security_hook_list selinux_hooks[] __lsm_ro_after_init = {
7133 LSM_HOOK_INIT(binder_set_context_mgr, selinux_binder_set_context_mgr),
7134 LSM_HOOK_INIT(binder_transaction, selinux_binder_transaction),
7135 LSM_HOOK_INIT(binder_transfer_binder, selinux_binder_transfer_binder),
7136 LSM_HOOK_INIT(binder_transfer_file, selinux_binder_transfer_file),
7138 LSM_HOOK_INIT(ptrace_access_check, selinux_ptrace_access_check),
7139 LSM_HOOK_INIT(ptrace_traceme, selinux_ptrace_traceme),
7140 LSM_HOOK_INIT(capget, selinux_capget),
7141 LSM_HOOK_INIT(capset, selinux_capset),
7142 LSM_HOOK_INIT(capable, selinux_capable),
7143 LSM_HOOK_INIT(quotactl, selinux_quotactl),
7144 LSM_HOOK_INIT(quota_on, selinux_quota_on),
7145 LSM_HOOK_INIT(syslog, selinux_syslog),
7146 LSM_HOOK_INIT(vm_enough_memory, selinux_vm_enough_memory),
7148 LSM_HOOK_INIT(netlink_send, selinux_netlink_send),
7150 LSM_HOOK_INIT(bprm_creds_for_exec, selinux_bprm_creds_for_exec),
7151 LSM_HOOK_INIT(bprm_committing_creds, selinux_bprm_committing_creds),
7152 LSM_HOOK_INIT(bprm_committed_creds, selinux_bprm_committed_creds),
7154 LSM_HOOK_INIT(sb_free_mnt_opts, selinux_free_mnt_opts),
7155 LSM_HOOK_INIT(sb_mnt_opts_compat, selinux_sb_mnt_opts_compat),
7156 LSM_HOOK_INIT(sb_remount, selinux_sb_remount),
7157 LSM_HOOK_INIT(sb_kern_mount, selinux_sb_kern_mount),
7158 LSM_HOOK_INIT(sb_show_options, selinux_sb_show_options),
7159 LSM_HOOK_INIT(sb_statfs, selinux_sb_statfs),
7160 LSM_HOOK_INIT(sb_mount, selinux_mount),
7161 LSM_HOOK_INIT(sb_umount, selinux_umount),
7162 LSM_HOOK_INIT(sb_set_mnt_opts, selinux_set_mnt_opts),
7163 LSM_HOOK_INIT(sb_clone_mnt_opts, selinux_sb_clone_mnt_opts),
7165 LSM_HOOK_INIT(move_mount, selinux_move_mount),
7167 LSM_HOOK_INIT(dentry_init_security, selinux_dentry_init_security),
7168 LSM_HOOK_INIT(dentry_create_files_as, selinux_dentry_create_files_as),
7170 LSM_HOOK_INIT(inode_free_security, selinux_inode_free_security),
7171 LSM_HOOK_INIT(inode_init_security, selinux_inode_init_security),
7172 LSM_HOOK_INIT(inode_init_security_anon, selinux_inode_init_security_anon),
7173 LSM_HOOK_INIT(inode_create, selinux_inode_create),
7174 LSM_HOOK_INIT(inode_link, selinux_inode_link),
7175 LSM_HOOK_INIT(inode_unlink, selinux_inode_unlink),
7176 LSM_HOOK_INIT(inode_symlink, selinux_inode_symlink),
7177 LSM_HOOK_INIT(inode_mkdir, selinux_inode_mkdir),
7178 LSM_HOOK_INIT(inode_rmdir, selinux_inode_rmdir),
7179 LSM_HOOK_INIT(inode_mknod, selinux_inode_mknod),
7180 LSM_HOOK_INIT(inode_rename, selinux_inode_rename),
7181 LSM_HOOK_INIT(inode_readlink, selinux_inode_readlink),
7182 LSM_HOOK_INIT(inode_follow_link, selinux_inode_follow_link),
7183 LSM_HOOK_INIT(inode_permission, selinux_inode_permission),
7184 LSM_HOOK_INIT(inode_setattr, selinux_inode_setattr),
7185 LSM_HOOK_INIT(inode_getattr, selinux_inode_getattr),
7186 LSM_HOOK_INIT(inode_setxattr, selinux_inode_setxattr),
7187 LSM_HOOK_INIT(inode_post_setxattr, selinux_inode_post_setxattr),
7188 LSM_HOOK_INIT(inode_getxattr, selinux_inode_getxattr),
7189 LSM_HOOK_INIT(inode_listxattr, selinux_inode_listxattr),
7190 LSM_HOOK_INIT(inode_removexattr, selinux_inode_removexattr),
7191 LSM_HOOK_INIT(inode_getsecurity, selinux_inode_getsecurity),
7192 LSM_HOOK_INIT(inode_setsecurity, selinux_inode_setsecurity),
7193 LSM_HOOK_INIT(inode_listsecurity, selinux_inode_listsecurity),
7194 LSM_HOOK_INIT(inode_getsecid, selinux_inode_getsecid),
7195 LSM_HOOK_INIT(inode_copy_up, selinux_inode_copy_up),
7196 LSM_HOOK_INIT(inode_copy_up_xattr, selinux_inode_copy_up_xattr),
7197 LSM_HOOK_INIT(path_notify, selinux_path_notify),
7199 LSM_HOOK_INIT(kernfs_init_security, selinux_kernfs_init_security),
7201 LSM_HOOK_INIT(file_permission, selinux_file_permission),
7202 LSM_HOOK_INIT(file_alloc_security, selinux_file_alloc_security),
7203 LSM_HOOK_INIT(file_ioctl, selinux_file_ioctl),
7204 LSM_HOOK_INIT(mmap_file, selinux_mmap_file),
7205 LSM_HOOK_INIT(mmap_addr, selinux_mmap_addr),
7206 LSM_HOOK_INIT(file_mprotect, selinux_file_mprotect),
7207 LSM_HOOK_INIT(file_lock, selinux_file_lock),
7208 LSM_HOOK_INIT(file_fcntl, selinux_file_fcntl),
7209 LSM_HOOK_INIT(file_set_fowner, selinux_file_set_fowner),
7210 LSM_HOOK_INIT(file_send_sigiotask, selinux_file_send_sigiotask),
7211 LSM_HOOK_INIT(file_receive, selinux_file_receive),
7213 LSM_HOOK_INIT(file_open, selinux_file_open),
7215 LSM_HOOK_INIT(task_alloc, selinux_task_alloc),
7216 LSM_HOOK_INIT(cred_prepare, selinux_cred_prepare),
7217 LSM_HOOK_INIT(cred_transfer, selinux_cred_transfer),
7218 LSM_HOOK_INIT(cred_getsecid, selinux_cred_getsecid),
7219 LSM_HOOK_INIT(kernel_act_as, selinux_kernel_act_as),
7220 LSM_HOOK_INIT(kernel_create_files_as, selinux_kernel_create_files_as),
7221 LSM_HOOK_INIT(kernel_module_request, selinux_kernel_module_request),
7222 LSM_HOOK_INIT(kernel_load_data, selinux_kernel_load_data),
7223 LSM_HOOK_INIT(kernel_read_file, selinux_kernel_read_file),
7224 LSM_HOOK_INIT(task_setpgid, selinux_task_setpgid),
7225 LSM_HOOK_INIT(task_getpgid, selinux_task_getpgid),
7226 LSM_HOOK_INIT(task_getsid, selinux_task_getsid),
7227 LSM_HOOK_INIT(task_getsecid_subj, selinux_task_getsecid_subj),
7228 LSM_HOOK_INIT(task_getsecid_obj, selinux_task_getsecid_obj),
7229 LSM_HOOK_INIT(task_setnice, selinux_task_setnice),
7230 LSM_HOOK_INIT(task_setioprio, selinux_task_setioprio),
7231 LSM_HOOK_INIT(task_getioprio, selinux_task_getioprio),
7232 LSM_HOOK_INIT(task_prlimit, selinux_task_prlimit),
7233 LSM_HOOK_INIT(task_setrlimit, selinux_task_setrlimit),
7234 LSM_HOOK_INIT(task_setscheduler, selinux_task_setscheduler),
7235 LSM_HOOK_INIT(task_getscheduler, selinux_task_getscheduler),
7236 LSM_HOOK_INIT(task_movememory, selinux_task_movememory),
7237 LSM_HOOK_INIT(task_kill, selinux_task_kill),
7238 LSM_HOOK_INIT(task_to_inode, selinux_task_to_inode),
7240 LSM_HOOK_INIT(ipc_permission, selinux_ipc_permission),
7241 LSM_HOOK_INIT(ipc_getsecid, selinux_ipc_getsecid),
7243 LSM_HOOK_INIT(msg_queue_associate, selinux_msg_queue_associate),
7244 LSM_HOOK_INIT(msg_queue_msgctl, selinux_msg_queue_msgctl),
7245 LSM_HOOK_INIT(msg_queue_msgsnd, selinux_msg_queue_msgsnd),
7246 LSM_HOOK_INIT(msg_queue_msgrcv, selinux_msg_queue_msgrcv),
7248 LSM_HOOK_INIT(shm_associate, selinux_shm_associate),
7249 LSM_HOOK_INIT(shm_shmctl, selinux_shm_shmctl),
7250 LSM_HOOK_INIT(shm_shmat, selinux_shm_shmat),
7252 LSM_HOOK_INIT(sem_associate, selinux_sem_associate),
7253 LSM_HOOK_INIT(sem_semctl, selinux_sem_semctl),
7254 LSM_HOOK_INIT(sem_semop, selinux_sem_semop),
7256 LSM_HOOK_INIT(d_instantiate, selinux_d_instantiate),
7258 LSM_HOOK_INIT(getprocattr, selinux_getprocattr),
7259 LSM_HOOK_INIT(setprocattr, selinux_setprocattr),
7261 LSM_HOOK_INIT(ismaclabel, selinux_ismaclabel),
7262 LSM_HOOK_INIT(secctx_to_secid, selinux_secctx_to_secid),
7263 LSM_HOOK_INIT(release_secctx, selinux_release_secctx),
7264 LSM_HOOK_INIT(inode_invalidate_secctx, selinux_inode_invalidate_secctx),
7265 LSM_HOOK_INIT(inode_notifysecctx, selinux_inode_notifysecctx),
7266 LSM_HOOK_INIT(inode_setsecctx, selinux_inode_setsecctx),
7268 LSM_HOOK_INIT(unix_stream_connect, selinux_socket_unix_stream_connect),
7269 LSM_HOOK_INIT(unix_may_send, selinux_socket_unix_may_send),
7271 LSM_HOOK_INIT(socket_create, selinux_socket_create),
7272 LSM_HOOK_INIT(socket_post_create, selinux_socket_post_create),
7273 LSM_HOOK_INIT(socket_socketpair, selinux_socket_socketpair),
7274 LSM_HOOK_INIT(socket_bind, selinux_socket_bind),
7275 LSM_HOOK_INIT(socket_connect, selinux_socket_connect),
7276 LSM_HOOK_INIT(socket_listen, selinux_socket_listen),
7277 LSM_HOOK_INIT(socket_accept, selinux_socket_accept),
7278 LSM_HOOK_INIT(socket_sendmsg, selinux_socket_sendmsg),
7279 LSM_HOOK_INIT(socket_recvmsg, selinux_socket_recvmsg),
7280 LSM_HOOK_INIT(socket_getsockname, selinux_socket_getsockname),
7281 LSM_HOOK_INIT(socket_getpeername, selinux_socket_getpeername),
7282 LSM_HOOK_INIT(socket_getsockopt, selinux_socket_getsockopt),
7283 LSM_HOOK_INIT(socket_setsockopt, selinux_socket_setsockopt),
7284 LSM_HOOK_INIT(socket_shutdown, selinux_socket_shutdown),
7285 LSM_HOOK_INIT(socket_sock_rcv_skb, selinux_socket_sock_rcv_skb),
7286 LSM_HOOK_INIT(socket_getpeersec_stream,
7287 selinux_socket_getpeersec_stream),
7288 LSM_HOOK_INIT(socket_getpeersec_dgram, selinux_socket_getpeersec_dgram),
7289 LSM_HOOK_INIT(sk_free_security, selinux_sk_free_security),
7290 LSM_HOOK_INIT(sk_clone_security, selinux_sk_clone_security),
7291 LSM_HOOK_INIT(sk_getsecid, selinux_sk_getsecid),
7292 LSM_HOOK_INIT(sock_graft, selinux_sock_graft),
7293 LSM_HOOK_INIT(sctp_assoc_request, selinux_sctp_assoc_request),
7294 LSM_HOOK_INIT(sctp_sk_clone, selinux_sctp_sk_clone),
7295 LSM_HOOK_INIT(sctp_bind_connect, selinux_sctp_bind_connect),
7296 LSM_HOOK_INIT(inet_conn_request, selinux_inet_conn_request),
7297 LSM_HOOK_INIT(inet_csk_clone, selinux_inet_csk_clone),
7298 LSM_HOOK_INIT(inet_conn_established, selinux_inet_conn_established),
7299 LSM_HOOK_INIT(secmark_relabel_packet, selinux_secmark_relabel_packet),
7300 LSM_HOOK_INIT(secmark_refcount_inc, selinux_secmark_refcount_inc),
7301 LSM_HOOK_INIT(secmark_refcount_dec, selinux_secmark_refcount_dec),
7302 LSM_HOOK_INIT(req_classify_flow, selinux_req_classify_flow),
7303 LSM_HOOK_INIT(tun_dev_free_security, selinux_tun_dev_free_security),
7304 LSM_HOOK_INIT(tun_dev_create, selinux_tun_dev_create),
7305 LSM_HOOK_INIT(tun_dev_attach_queue, selinux_tun_dev_attach_queue),
7306 LSM_HOOK_INIT(tun_dev_attach, selinux_tun_dev_attach),
7307 LSM_HOOK_INIT(tun_dev_open, selinux_tun_dev_open),
7308 #ifdef CONFIG_SECURITY_INFINIBAND
7309 LSM_HOOK_INIT(ib_pkey_access, selinux_ib_pkey_access),
7310 LSM_HOOK_INIT(ib_endport_manage_subnet,
7311 selinux_ib_endport_manage_subnet),
7312 LSM_HOOK_INIT(ib_free_security, selinux_ib_free_security),
7314 #ifdef CONFIG_SECURITY_NETWORK_XFRM
7315 LSM_HOOK_INIT(xfrm_policy_free_security, selinux_xfrm_policy_free),
7316 LSM_HOOK_INIT(xfrm_policy_delete_security, selinux_xfrm_policy_delete),
7317 LSM_HOOK_INIT(xfrm_state_free_security, selinux_xfrm_state_free),
7318 LSM_HOOK_INIT(xfrm_state_delete_security, selinux_xfrm_state_delete),
7319 LSM_HOOK_INIT(xfrm_policy_lookup, selinux_xfrm_policy_lookup),
7320 LSM_HOOK_INIT(xfrm_state_pol_flow_match,
7321 selinux_xfrm_state_pol_flow_match),
7322 LSM_HOOK_INIT(xfrm_decode_session, selinux_xfrm_decode_session),
7326 LSM_HOOK_INIT(key_free, selinux_key_free),
7327 LSM_HOOK_INIT(key_permission, selinux_key_permission),
7328 LSM_HOOK_INIT(key_getsecurity, selinux_key_getsecurity),
7329 #ifdef CONFIG_KEY_NOTIFICATIONS
7330 LSM_HOOK_INIT(watch_key, selinux_watch_key),
7335 LSM_HOOK_INIT(audit_rule_known, selinux_audit_rule_known),
7336 LSM_HOOK_INIT(audit_rule_match, selinux_audit_rule_match),
7337 LSM_HOOK_INIT(audit_rule_free, selinux_audit_rule_free),
7340 #ifdef CONFIG_BPF_SYSCALL
7341 LSM_HOOK_INIT(bpf, selinux_bpf),
7342 LSM_HOOK_INIT(bpf_map, selinux_bpf_map),
7343 LSM_HOOK_INIT(bpf_prog, selinux_bpf_prog),
7344 LSM_HOOK_INIT(bpf_map_free_security, selinux_bpf_map_free),
7345 LSM_HOOK_INIT(bpf_prog_free_security, selinux_bpf_prog_free),
7348 #ifdef CONFIG_PERF_EVENTS
7349 LSM_HOOK_INIT(perf_event_open, selinux_perf_event_open),
7350 LSM_HOOK_INIT(perf_event_free, selinux_perf_event_free),
7351 LSM_HOOK_INIT(perf_event_read, selinux_perf_event_read),
7352 LSM_HOOK_INIT(perf_event_write, selinux_perf_event_write),
7355 LSM_HOOK_INIT(locked_down, selinux_lockdown),
7358 * PUT "CLONING" (ACCESSING + ALLOCATING) HOOKS HERE
7360 LSM_HOOK_INIT(fs_context_dup, selinux_fs_context_dup),
7361 LSM_HOOK_INIT(fs_context_parse_param, selinux_fs_context_parse_param),
7362 LSM_HOOK_INIT(sb_eat_lsm_opts, selinux_sb_eat_lsm_opts),
7363 LSM_HOOK_INIT(sb_add_mnt_opt, selinux_add_mnt_opt),
7364 #ifdef CONFIG_SECURITY_NETWORK_XFRM
7365 LSM_HOOK_INIT(xfrm_policy_clone_security, selinux_xfrm_policy_clone),
7369 * PUT "ALLOCATING" HOOKS HERE
7371 LSM_HOOK_INIT(msg_msg_alloc_security, selinux_msg_msg_alloc_security),
7372 LSM_HOOK_INIT(msg_queue_alloc_security,
7373 selinux_msg_queue_alloc_security),
7374 LSM_HOOK_INIT(shm_alloc_security, selinux_shm_alloc_security),
7375 LSM_HOOK_INIT(sb_alloc_security, selinux_sb_alloc_security),
7376 LSM_HOOK_INIT(inode_alloc_security, selinux_inode_alloc_security),
7377 LSM_HOOK_INIT(sem_alloc_security, selinux_sem_alloc_security),
7378 LSM_HOOK_INIT(secid_to_secctx, selinux_secid_to_secctx),
7379 LSM_HOOK_INIT(inode_getsecctx, selinux_inode_getsecctx),
7380 LSM_HOOK_INIT(sk_alloc_security, selinux_sk_alloc_security),
7381 LSM_HOOK_INIT(tun_dev_alloc_security, selinux_tun_dev_alloc_security),
7382 #ifdef CONFIG_SECURITY_INFINIBAND
7383 LSM_HOOK_INIT(ib_alloc_security, selinux_ib_alloc_security),
7385 #ifdef CONFIG_SECURITY_NETWORK_XFRM
7386 LSM_HOOK_INIT(xfrm_policy_alloc_security, selinux_xfrm_policy_alloc),
7387 LSM_HOOK_INIT(xfrm_state_alloc, selinux_xfrm_state_alloc),
7388 LSM_HOOK_INIT(xfrm_state_alloc_acquire,
7389 selinux_xfrm_state_alloc_acquire),
7392 LSM_HOOK_INIT(key_alloc, selinux_key_alloc),
7395 LSM_HOOK_INIT(audit_rule_init, selinux_audit_rule_init),
7397 #ifdef CONFIG_BPF_SYSCALL
7398 LSM_HOOK_INIT(bpf_map_alloc_security, selinux_bpf_map_alloc),
7399 LSM_HOOK_INIT(bpf_prog_alloc_security, selinux_bpf_prog_alloc),
7401 #ifdef CONFIG_PERF_EVENTS
7402 LSM_HOOK_INIT(perf_event_alloc, selinux_perf_event_alloc),
7406 static __init int selinux_init(void)
7408 pr_info("SELinux: Initializing.\n");
7410 memset(&selinux_state, 0, sizeof(selinux_state));
7411 enforcing_set(&selinux_state, selinux_enforcing_boot);
7412 checkreqprot_set(&selinux_state, selinux_checkreqprot_boot);
7413 selinux_avc_init(&selinux_state.avc);
7414 mutex_init(&selinux_state.status_lock);
7415 mutex_init(&selinux_state.policy_mutex);
7417 /* Set the security state for the initial task. */
7418 cred_init_security();
7420 default_noexec = !(VM_DATA_DEFAULT_FLAGS & VM_EXEC);
7426 ebitmap_cache_init();
7428 hashtab_cache_init();
7430 security_add_hooks(selinux_hooks, ARRAY_SIZE(selinux_hooks), "selinux");
7432 if (avc_add_callback(selinux_netcache_avc_callback, AVC_CALLBACK_RESET))
7433 panic("SELinux: Unable to register AVC netcache callback\n");
7435 if (avc_add_callback(selinux_lsm_notifier_avc_callback, AVC_CALLBACK_RESET))
7436 panic("SELinux: Unable to register AVC LSM notifier callback\n");
7438 if (selinux_enforcing_boot)
7439 pr_debug("SELinux: Starting in enforcing mode\n");
7441 pr_debug("SELinux: Starting in permissive mode\n");
7443 fs_validate_description("selinux", selinux_fs_parameters);
7448 static void delayed_superblock_init(struct super_block *sb, void *unused)
7450 selinux_set_mnt_opts(sb, NULL, 0, NULL);
7453 void selinux_complete_init(void)
7455 pr_debug("SELinux: Completing initialization.\n");
7457 /* Set up any superblocks initialized prior to the policy load. */
7458 pr_debug("SELinux: Setting up existing superblocks.\n");
7459 iterate_supers(delayed_superblock_init, NULL);
7462 /* SELinux requires early initialization in order to label
7463 all processes and objects when they are created. */
7464 DEFINE_LSM(selinux) = {
7466 .flags = LSM_FLAG_LEGACY_MAJOR | LSM_FLAG_EXCLUSIVE,
7467 .enabled = &selinux_enabled_boot,
7468 .blobs = &selinux_blob_sizes,
7469 .init = selinux_init,
7472 #if defined(CONFIG_NETFILTER)
7474 static const struct nf_hook_ops selinux_nf_ops[] = {
7476 .hook = selinux_ipv4_postroute,
7478 .hooknum = NF_INET_POST_ROUTING,
7479 .priority = NF_IP_PRI_SELINUX_LAST,
7482 .hook = selinux_ipv4_forward,
7484 .hooknum = NF_INET_FORWARD,
7485 .priority = NF_IP_PRI_SELINUX_FIRST,
7488 .hook = selinux_ipv4_output,
7490 .hooknum = NF_INET_LOCAL_OUT,
7491 .priority = NF_IP_PRI_SELINUX_FIRST,
7493 #if IS_ENABLED(CONFIG_IPV6)
7495 .hook = selinux_ipv6_postroute,
7497 .hooknum = NF_INET_POST_ROUTING,
7498 .priority = NF_IP6_PRI_SELINUX_LAST,
7501 .hook = selinux_ipv6_forward,
7503 .hooknum = NF_INET_FORWARD,
7504 .priority = NF_IP6_PRI_SELINUX_FIRST,
7507 .hook = selinux_ipv6_output,
7509 .hooknum = NF_INET_LOCAL_OUT,
7510 .priority = NF_IP6_PRI_SELINUX_FIRST,
7515 static int __net_init selinux_nf_register(struct net *net)
7517 return nf_register_net_hooks(net, selinux_nf_ops,
7518 ARRAY_SIZE(selinux_nf_ops));
7521 static void __net_exit selinux_nf_unregister(struct net *net)
7523 nf_unregister_net_hooks(net, selinux_nf_ops,
7524 ARRAY_SIZE(selinux_nf_ops));
7527 static struct pernet_operations selinux_net_ops = {
7528 .init = selinux_nf_register,
7529 .exit = selinux_nf_unregister,
7532 static int __init selinux_nf_ip_init(void)
7536 if (!selinux_enabled_boot)
7539 pr_debug("SELinux: Registering netfilter hooks\n");
7541 err = register_pernet_subsys(&selinux_net_ops);
7543 panic("SELinux: register_pernet_subsys: error %d\n", err);
7547 __initcall(selinux_nf_ip_init);
7549 #ifdef CONFIG_SECURITY_SELINUX_DISABLE
7550 static void selinux_nf_ip_exit(void)
7552 pr_debug("SELinux: Unregistering netfilter hooks\n");
7554 unregister_pernet_subsys(&selinux_net_ops);
7558 #else /* CONFIG_NETFILTER */
7560 #ifdef CONFIG_SECURITY_SELINUX_DISABLE
7561 #define selinux_nf_ip_exit()
7564 #endif /* CONFIG_NETFILTER */
7566 #ifdef CONFIG_SECURITY_SELINUX_DISABLE
7567 int selinux_disable(struct selinux_state *state)
7569 if (selinux_initialized(state)) {
7570 /* Not permitted after initial policy load. */
7574 if (selinux_disabled(state)) {
7575 /* Only do this once. */
7579 selinux_mark_disabled(state);
7581 pr_info("SELinux: Disabled at runtime.\n");
7584 * Unregister netfilter hooks.
7585 * Must be done before security_delete_hooks() to avoid breaking
7588 selinux_nf_ip_exit();
7590 security_delete_hooks(selinux_hooks, ARRAY_SIZE(selinux_hooks));
7592 /* Try to destroy the avc node cache */
7595 /* Unregister selinuxfs. */