1 // SPDX-License-Identifier: GPL-2.0-only
3 * NSA Security-Enhanced Linux (SELinux) security module
5 * This file contains the SELinux hook function implementations.
12 * Copyright (C) 2001,2002 Networks Associates Technology, Inc.
15 * Copyright (C) 2004-2005 Trusted Computer Solutions, Inc.
17 * Copyright (C) 2006, 2007, 2009 Hewlett-Packard Development Company, L.P.
19 * Copyright (C) 2007 Hitachi Software Engineering Co., Ltd.
21 * Copyright (C) 2016 Mellanox Technologies
24 #include <linux/init.h>
26 #include <linux/kernel.h>
27 #include <linux/kernel_read_file.h>
28 #include <linux/tracehook.h>
29 #include <linux/errno.h>
30 #include <linux/sched/signal.h>
31 #include <linux/sched/task.h>
32 #include <linux/lsm_hooks.h>
33 #include <linux/xattr.h>
34 #include <linux/capability.h>
35 #include <linux/unistd.h>
37 #include <linux/mman.h>
38 #include <linux/slab.h>
39 #include <linux/pagemap.h>
40 #include <linux/proc_fs.h>
41 #include <linux/swap.h>
42 #include <linux/spinlock.h>
43 #include <linux/syscalls.h>
44 #include <linux/dcache.h>
45 #include <linux/file.h>
46 #include <linux/fdtable.h>
47 #include <linux/namei.h>
48 #include <linux/mount.h>
49 #include <linux/fs_context.h>
50 #include <linux/fs_parser.h>
51 #include <linux/netfilter_ipv4.h>
52 #include <linux/netfilter_ipv6.h>
53 #include <linux/tty.h>
55 #include <net/ip.h> /* for local_port_range[] */
56 #include <net/tcp.h> /* struct or_callable used in sock_rcv_skb */
57 #include <net/inet_connection_sock.h>
58 #include <net/net_namespace.h>
59 #include <net/netlabel.h>
60 #include <linux/uaccess.h>
61 #include <asm/ioctls.h>
62 #include <linux/atomic.h>
63 #include <linux/bitops.h>
64 #include <linux/interrupt.h>
65 #include <linux/netdevice.h> /* for network interface checks */
66 #include <net/netlink.h>
67 #include <linux/tcp.h>
68 #include <linux/udp.h>
69 #include <linux/dccp.h>
70 #include <linux/sctp.h>
71 #include <net/sctp/structs.h>
72 #include <linux/quota.h>
73 #include <linux/un.h> /* for Unix socket types */
74 #include <net/af_unix.h> /* for Unix socket types */
75 #include <linux/parser.h>
76 #include <linux/nfs_mount.h>
78 #include <linux/hugetlb.h>
79 #include <linux/personality.h>
80 #include <linux/audit.h>
81 #include <linux/string.h>
82 #include <linux/mutex.h>
83 #include <linux/posix-timers.h>
84 #include <linux/syslog.h>
85 #include <linux/user_namespace.h>
86 #include <linux/export.h>
87 #include <linux/msg.h>
88 #include <linux/shm.h>
89 #include <linux/bpf.h>
90 #include <linux/kernfs.h>
91 #include <linux/stringhash.h> /* for hashlen_string() */
92 #include <uapi/linux/mount.h>
93 #include <linux/fsnotify.h>
94 #include <linux/fanotify.h>
103 #include "netlabel.h"
107 struct selinux_state selinux_state;
109 /* SECMARK reference count */
110 static atomic_t selinux_secmark_refcount = ATOMIC_INIT(0);
112 #ifdef CONFIG_SECURITY_SELINUX_DEVELOP
113 static int selinux_enforcing_boot __initdata;
115 static int __init enforcing_setup(char *str)
117 unsigned long enforcing;
118 if (!kstrtoul(str, 0, &enforcing))
119 selinux_enforcing_boot = enforcing ? 1 : 0;
122 __setup("enforcing=", enforcing_setup);
124 #define selinux_enforcing_boot 1
127 int selinux_enabled_boot __initdata = 1;
128 #ifdef CONFIG_SECURITY_SELINUX_BOOTPARAM
129 static int __init selinux_enabled_setup(char *str)
131 unsigned long enabled;
132 if (!kstrtoul(str, 0, &enabled))
133 selinux_enabled_boot = enabled ? 1 : 0;
136 __setup("selinux=", selinux_enabled_setup);
139 static unsigned int selinux_checkreqprot_boot =
140 CONFIG_SECURITY_SELINUX_CHECKREQPROT_VALUE;
142 static int __init checkreqprot_setup(char *str)
144 unsigned long checkreqprot;
146 if (!kstrtoul(str, 0, &checkreqprot)) {
147 selinux_checkreqprot_boot = checkreqprot ? 1 : 0;
149 pr_warn("SELinux: checkreqprot set to 1 via kernel parameter. This is deprecated and will be rejected in a future kernel release.\n");
153 __setup("checkreqprot=", checkreqprot_setup);
156 * selinux_secmark_enabled - Check to see if SECMARK is currently enabled
159 * This function checks the SECMARK reference counter to see if any SECMARK
160 * targets are currently configured, if the reference counter is greater than
161 * zero SECMARK is considered to be enabled. Returns true (1) if SECMARK is
162 * enabled, false (0) if SECMARK is disabled. If the always_check_network
163 * policy capability is enabled, SECMARK is always considered enabled.
166 static int selinux_secmark_enabled(void)
168 return (selinux_policycap_alwaysnetwork() ||
169 atomic_read(&selinux_secmark_refcount));
173 * selinux_peerlbl_enabled - Check to see if peer labeling is currently enabled
176 * This function checks if NetLabel or labeled IPSEC is enabled. Returns true
177 * (1) if any are enabled or false (0) if neither are enabled. If the
178 * always_check_network policy capability is enabled, peer labeling
179 * is always considered enabled.
182 static int selinux_peerlbl_enabled(void)
184 return (selinux_policycap_alwaysnetwork() ||
185 netlbl_enabled() || selinux_xfrm_enabled());
188 static int selinux_netcache_avc_callback(u32 event)
190 if (event == AVC_CALLBACK_RESET) {
199 static int selinux_lsm_notifier_avc_callback(u32 event)
201 if (event == AVC_CALLBACK_RESET) {
203 call_blocking_lsm_notifier(LSM_POLICY_CHANGE, NULL);
210 * initialise the security for the init task
212 static void cred_init_security(void)
214 struct cred *cred = (struct cred *) current->real_cred;
215 struct task_security_struct *tsec;
217 tsec = selinux_cred(cred);
218 tsec->osid = tsec->sid = SECINITSID_KERNEL;
222 * get the security ID of a set of credentials
224 static inline u32 cred_sid(const struct cred *cred)
226 const struct task_security_struct *tsec;
228 tsec = selinux_cred(cred);
233 * get the objective security ID of a task
235 static inline u32 task_sid(const struct task_struct *task)
240 sid = cred_sid(__task_cred(task));
245 static int inode_doinit_with_dentry(struct inode *inode, struct dentry *opt_dentry);
248 * Try reloading inode security labels that have been marked as invalid. The
249 * @may_sleep parameter indicates when sleeping and thus reloading labels is
250 * allowed; when set to false, returns -ECHILD when the label is
251 * invalid. The @dentry parameter should be set to a dentry of the inode.
253 static int __inode_security_revalidate(struct inode *inode,
254 struct dentry *dentry,
257 struct inode_security_struct *isec = selinux_inode(inode);
259 might_sleep_if(may_sleep);
261 if (selinux_initialized(&selinux_state) &&
262 isec->initialized != LABEL_INITIALIZED) {
267 * Try reloading the inode security label. This will fail if
268 * @opt_dentry is NULL and no dentry for this inode can be
269 * found; in that case, continue using the old label.
271 inode_doinit_with_dentry(inode, dentry);
276 static struct inode_security_struct *inode_security_novalidate(struct inode *inode)
278 return selinux_inode(inode);
281 static struct inode_security_struct *inode_security_rcu(struct inode *inode, bool rcu)
285 error = __inode_security_revalidate(inode, NULL, !rcu);
287 return ERR_PTR(error);
288 return selinux_inode(inode);
292 * Get the security label of an inode.
294 static struct inode_security_struct *inode_security(struct inode *inode)
296 __inode_security_revalidate(inode, NULL, true);
297 return selinux_inode(inode);
300 static struct inode_security_struct *backing_inode_security_novalidate(struct dentry *dentry)
302 struct inode *inode = d_backing_inode(dentry);
304 return selinux_inode(inode);
308 * Get the security label of a dentry's backing inode.
310 static struct inode_security_struct *backing_inode_security(struct dentry *dentry)
312 struct inode *inode = d_backing_inode(dentry);
314 __inode_security_revalidate(inode, dentry, true);
315 return selinux_inode(inode);
318 static void inode_free_security(struct inode *inode)
320 struct inode_security_struct *isec = selinux_inode(inode);
321 struct superblock_security_struct *sbsec;
325 sbsec = inode->i_sb->s_security;
327 * As not all inode security structures are in a list, we check for
328 * empty list outside of the lock to make sure that we won't waste
329 * time taking a lock doing nothing.
331 * The list_del_init() function can be safely called more than once.
332 * It should not be possible for this function to be called with
333 * concurrent list_add(), but for better safety against future changes
334 * in the code, we use list_empty_careful() here.
336 if (!list_empty_careful(&isec->list)) {
337 spin_lock(&sbsec->isec_lock);
338 list_del_init(&isec->list);
339 spin_unlock(&sbsec->isec_lock);
343 static void superblock_free_security(struct super_block *sb)
345 struct superblock_security_struct *sbsec = sb->s_security;
346 sb->s_security = NULL;
350 struct selinux_mnt_opts {
351 const char *fscontext, *context, *rootcontext, *defcontext;
354 static void selinux_free_mnt_opts(void *mnt_opts)
356 struct selinux_mnt_opts *opts = mnt_opts;
357 kfree(opts->fscontext);
358 kfree(opts->context);
359 kfree(opts->rootcontext);
360 kfree(opts->defcontext);
373 #define A(s, has_arg) {#s, sizeof(#s) - 1, Opt_##s, has_arg}
383 A(rootcontext, true),
388 static int match_opt_prefix(char *s, int l, char **arg)
392 for (i = 0; i < ARRAY_SIZE(tokens); i++) {
393 size_t len = tokens[i].len;
394 if (len > l || memcmp(s, tokens[i].name, len))
396 if (tokens[i].has_arg) {
397 if (len == l || s[len] != '=')
402 return tokens[i].opt;
407 #define SEL_MOUNT_FAIL_MSG "SELinux: duplicate or incompatible mount options\n"
409 static int may_context_mount_sb_relabel(u32 sid,
410 struct superblock_security_struct *sbsec,
411 const struct cred *cred)
413 const struct task_security_struct *tsec = selinux_cred(cred);
416 rc = avc_has_perm(&selinux_state,
417 tsec->sid, sbsec->sid, SECCLASS_FILESYSTEM,
418 FILESYSTEM__RELABELFROM, NULL);
422 rc = avc_has_perm(&selinux_state,
423 tsec->sid, sid, SECCLASS_FILESYSTEM,
424 FILESYSTEM__RELABELTO, NULL);
428 static int may_context_mount_inode_relabel(u32 sid,
429 struct superblock_security_struct *sbsec,
430 const struct cred *cred)
432 const struct task_security_struct *tsec = selinux_cred(cred);
434 rc = avc_has_perm(&selinux_state,
435 tsec->sid, sbsec->sid, SECCLASS_FILESYSTEM,
436 FILESYSTEM__RELABELFROM, NULL);
440 rc = avc_has_perm(&selinux_state,
441 sid, sbsec->sid, SECCLASS_FILESYSTEM,
442 FILESYSTEM__ASSOCIATE, NULL);
446 static int selinux_is_genfs_special_handling(struct super_block *sb)
448 /* Special handling. Genfs but also in-core setxattr handler */
449 return !strcmp(sb->s_type->name, "sysfs") ||
450 !strcmp(sb->s_type->name, "pstore") ||
451 !strcmp(sb->s_type->name, "debugfs") ||
452 !strcmp(sb->s_type->name, "tracefs") ||
453 !strcmp(sb->s_type->name, "rootfs") ||
454 (selinux_policycap_cgroupseclabel() &&
455 (!strcmp(sb->s_type->name, "cgroup") ||
456 !strcmp(sb->s_type->name, "cgroup2")));
459 static int selinux_is_sblabel_mnt(struct super_block *sb)
461 struct superblock_security_struct *sbsec = sb->s_security;
464 * IMPORTANT: Double-check logic in this function when adding a new
465 * SECURITY_FS_USE_* definition!
467 BUILD_BUG_ON(SECURITY_FS_USE_MAX != 7);
469 switch (sbsec->behavior) {
470 case SECURITY_FS_USE_XATTR:
471 case SECURITY_FS_USE_TRANS:
472 case SECURITY_FS_USE_TASK:
473 case SECURITY_FS_USE_NATIVE:
476 case SECURITY_FS_USE_GENFS:
477 return selinux_is_genfs_special_handling(sb);
479 /* Never allow relabeling on context mounts */
480 case SECURITY_FS_USE_MNTPOINT:
481 case SECURITY_FS_USE_NONE:
487 static int sb_check_xattr_support(struct super_block *sb)
489 struct superblock_security_struct *sbsec = sb->s_security;
490 struct dentry *root = sb->s_root;
491 struct inode *root_inode = d_backing_inode(root);
496 * Make sure that the xattr handler exists and that no
497 * error other than -ENODATA is returned by getxattr on
498 * the root directory. -ENODATA is ok, as this may be
499 * the first boot of the SELinux kernel before we have
500 * assigned xattr values to the filesystem.
502 if (!(root_inode->i_opflags & IOP_XATTR)) {
503 pr_warn("SELinux: (dev %s, type %s) has no xattr support\n",
504 sb->s_id, sb->s_type->name);
508 rc = __vfs_getxattr(root, root_inode, XATTR_NAME_SELINUX, NULL, 0);
509 if (rc < 0 && rc != -ENODATA) {
510 if (rc == -EOPNOTSUPP) {
511 pr_warn("SELinux: (dev %s, type %s) has no security xattr handler\n",
512 sb->s_id, sb->s_type->name);
515 pr_warn("SELinux: (dev %s, type %s) getxattr errno %d\n",
516 sb->s_id, sb->s_type->name, -rc);
523 /* No xattr support - try to fallback to genfs if possible. */
524 rc = security_genfs_sid(&selinux_state, sb->s_type->name, "/",
529 pr_warn("SELinux: (dev %s, type %s) falling back to genfs\n",
530 sb->s_id, sb->s_type->name);
531 sbsec->behavior = SECURITY_FS_USE_GENFS;
536 static int sb_finish_set_opts(struct super_block *sb)
538 struct superblock_security_struct *sbsec = sb->s_security;
539 struct dentry *root = sb->s_root;
540 struct inode *root_inode = d_backing_inode(root);
543 if (sbsec->behavior == SECURITY_FS_USE_XATTR) {
544 rc = sb_check_xattr_support(sb);
549 sbsec->flags |= SE_SBINITIALIZED;
552 * Explicitly set or clear SBLABEL_MNT. It's not sufficient to simply
553 * leave the flag untouched because sb_clone_mnt_opts might be handing
554 * us a superblock that needs the flag to be cleared.
556 if (selinux_is_sblabel_mnt(sb))
557 sbsec->flags |= SBLABEL_MNT;
559 sbsec->flags &= ~SBLABEL_MNT;
561 /* Initialize the root inode. */
562 rc = inode_doinit_with_dentry(root_inode, root);
564 /* Initialize any other inodes associated with the superblock, e.g.
565 inodes created prior to initial policy load or inodes created
566 during get_sb by a pseudo filesystem that directly
568 spin_lock(&sbsec->isec_lock);
569 while (!list_empty(&sbsec->isec_head)) {
570 struct inode_security_struct *isec =
571 list_first_entry(&sbsec->isec_head,
572 struct inode_security_struct, list);
573 struct inode *inode = isec->inode;
574 list_del_init(&isec->list);
575 spin_unlock(&sbsec->isec_lock);
576 inode = igrab(inode);
578 if (!IS_PRIVATE(inode))
579 inode_doinit_with_dentry(inode, NULL);
582 spin_lock(&sbsec->isec_lock);
584 spin_unlock(&sbsec->isec_lock);
588 static int bad_option(struct superblock_security_struct *sbsec, char flag,
589 u32 old_sid, u32 new_sid)
591 char mnt_flags = sbsec->flags & SE_MNTMASK;
593 /* check if the old mount command had the same options */
594 if (sbsec->flags & SE_SBINITIALIZED)
595 if (!(sbsec->flags & flag) ||
596 (old_sid != new_sid))
599 /* check if we were passed the same options twice,
600 * aka someone passed context=a,context=b
602 if (!(sbsec->flags & SE_SBINITIALIZED))
603 if (mnt_flags & flag)
608 static int parse_sid(struct super_block *sb, const char *s, u32 *sid)
610 int rc = security_context_str_to_sid(&selinux_state, s,
613 pr_warn("SELinux: security_context_str_to_sid"
614 "(%s) failed for (dev %s, type %s) errno=%d\n",
615 s, sb->s_id, sb->s_type->name, rc);
620 * Allow filesystems with binary mount data to explicitly set mount point
621 * labeling information.
623 static int selinux_set_mnt_opts(struct super_block *sb,
625 unsigned long kern_flags,
626 unsigned long *set_kern_flags)
628 const struct cred *cred = current_cred();
629 struct superblock_security_struct *sbsec = sb->s_security;
630 struct dentry *root = sb->s_root;
631 struct selinux_mnt_opts *opts = mnt_opts;
632 struct inode_security_struct *root_isec;
633 u32 fscontext_sid = 0, context_sid = 0, rootcontext_sid = 0;
634 u32 defcontext_sid = 0;
637 mutex_lock(&sbsec->lock);
639 if (!selinux_initialized(&selinux_state)) {
641 /* Defer initialization until selinux_complete_init,
642 after the initial policy is loaded and the security
643 server is ready to handle calls. */
647 pr_warn("SELinux: Unable to set superblock options "
648 "before the security server is initialized\n");
651 if (kern_flags && !set_kern_flags) {
652 /* Specifying internal flags without providing a place to
653 * place the results is not allowed */
659 * Binary mount data FS will come through this function twice. Once
660 * from an explicit call and once from the generic calls from the vfs.
661 * Since the generic VFS calls will not contain any security mount data
662 * we need to skip the double mount verification.
664 * This does open a hole in which we will not notice if the first
665 * mount using this sb set explict options and a second mount using
666 * this sb does not set any security options. (The first options
667 * will be used for both mounts)
669 if ((sbsec->flags & SE_SBINITIALIZED) && (sb->s_type->fs_flags & FS_BINARY_MOUNTDATA)
673 root_isec = backing_inode_security_novalidate(root);
676 * parse the mount options, check if they are valid sids.
677 * also check if someone is trying to mount the same sb more
678 * than once with different security options.
681 if (opts->fscontext) {
682 rc = parse_sid(sb, opts->fscontext, &fscontext_sid);
685 if (bad_option(sbsec, FSCONTEXT_MNT, sbsec->sid,
687 goto out_double_mount;
688 sbsec->flags |= FSCONTEXT_MNT;
691 rc = parse_sid(sb, opts->context, &context_sid);
694 if (bad_option(sbsec, CONTEXT_MNT, sbsec->mntpoint_sid,
696 goto out_double_mount;
697 sbsec->flags |= CONTEXT_MNT;
699 if (opts->rootcontext) {
700 rc = parse_sid(sb, opts->rootcontext, &rootcontext_sid);
703 if (bad_option(sbsec, ROOTCONTEXT_MNT, root_isec->sid,
705 goto out_double_mount;
706 sbsec->flags |= ROOTCONTEXT_MNT;
708 if (opts->defcontext) {
709 rc = parse_sid(sb, opts->defcontext, &defcontext_sid);
712 if (bad_option(sbsec, DEFCONTEXT_MNT, sbsec->def_sid,
714 goto out_double_mount;
715 sbsec->flags |= DEFCONTEXT_MNT;
719 if (sbsec->flags & SE_SBINITIALIZED) {
720 /* previously mounted with options, but not on this attempt? */
721 if ((sbsec->flags & SE_MNTMASK) && !opts)
722 goto out_double_mount;
727 if (strcmp(sb->s_type->name, "proc") == 0)
728 sbsec->flags |= SE_SBPROC | SE_SBGENFS;
730 if (!strcmp(sb->s_type->name, "debugfs") ||
731 !strcmp(sb->s_type->name, "tracefs") ||
732 !strcmp(sb->s_type->name, "binder") ||
733 !strcmp(sb->s_type->name, "bpf") ||
734 !strcmp(sb->s_type->name, "pstore"))
735 sbsec->flags |= SE_SBGENFS;
737 if (!strcmp(sb->s_type->name, "sysfs") ||
738 !strcmp(sb->s_type->name, "cgroup") ||
739 !strcmp(sb->s_type->name, "cgroup2"))
740 sbsec->flags |= SE_SBGENFS | SE_SBGENFS_XATTR;
742 if (!sbsec->behavior) {
744 * Determine the labeling behavior to use for this
747 rc = security_fs_use(&selinux_state, sb);
749 pr_warn("%s: security_fs_use(%s) returned %d\n",
750 __func__, sb->s_type->name, rc);
756 * If this is a user namespace mount and the filesystem type is not
757 * explicitly whitelisted, then no contexts are allowed on the command
758 * line and security labels must be ignored.
760 if (sb->s_user_ns != &init_user_ns &&
761 strcmp(sb->s_type->name, "tmpfs") &&
762 strcmp(sb->s_type->name, "ramfs") &&
763 strcmp(sb->s_type->name, "devpts")) {
764 if (context_sid || fscontext_sid || rootcontext_sid ||
769 if (sbsec->behavior == SECURITY_FS_USE_XATTR) {
770 sbsec->behavior = SECURITY_FS_USE_MNTPOINT;
771 rc = security_transition_sid(&selinux_state,
775 &sbsec->mntpoint_sid);
782 /* sets the context of the superblock for the fs being mounted. */
784 rc = may_context_mount_sb_relabel(fscontext_sid, sbsec, cred);
788 sbsec->sid = fscontext_sid;
792 * Switch to using mount point labeling behavior.
793 * sets the label used on all file below the mountpoint, and will set
794 * the superblock context if not already set.
796 if (kern_flags & SECURITY_LSM_NATIVE_LABELS && !context_sid) {
797 sbsec->behavior = SECURITY_FS_USE_NATIVE;
798 *set_kern_flags |= SECURITY_LSM_NATIVE_LABELS;
802 if (!fscontext_sid) {
803 rc = may_context_mount_sb_relabel(context_sid, sbsec,
807 sbsec->sid = context_sid;
809 rc = may_context_mount_inode_relabel(context_sid, sbsec,
814 if (!rootcontext_sid)
815 rootcontext_sid = context_sid;
817 sbsec->mntpoint_sid = context_sid;
818 sbsec->behavior = SECURITY_FS_USE_MNTPOINT;
821 if (rootcontext_sid) {
822 rc = may_context_mount_inode_relabel(rootcontext_sid, sbsec,
827 root_isec->sid = rootcontext_sid;
828 root_isec->initialized = LABEL_INITIALIZED;
831 if (defcontext_sid) {
832 if (sbsec->behavior != SECURITY_FS_USE_XATTR &&
833 sbsec->behavior != SECURITY_FS_USE_NATIVE) {
835 pr_warn("SELinux: defcontext option is "
836 "invalid for this filesystem type\n");
840 if (defcontext_sid != sbsec->def_sid) {
841 rc = may_context_mount_inode_relabel(defcontext_sid,
847 sbsec->def_sid = defcontext_sid;
851 rc = sb_finish_set_opts(sb);
853 mutex_unlock(&sbsec->lock);
857 pr_warn("SELinux: mount invalid. Same superblock, different "
858 "security settings for (dev %s, type %s)\n", sb->s_id,
863 static int selinux_cmp_sb_context(const struct super_block *oldsb,
864 const struct super_block *newsb)
866 struct superblock_security_struct *old = oldsb->s_security;
867 struct superblock_security_struct *new = newsb->s_security;
868 char oldflags = old->flags & SE_MNTMASK;
869 char newflags = new->flags & SE_MNTMASK;
871 if (oldflags != newflags)
873 if ((oldflags & FSCONTEXT_MNT) && old->sid != new->sid)
875 if ((oldflags & CONTEXT_MNT) && old->mntpoint_sid != new->mntpoint_sid)
877 if ((oldflags & DEFCONTEXT_MNT) && old->def_sid != new->def_sid)
879 if (oldflags & ROOTCONTEXT_MNT) {
880 struct inode_security_struct *oldroot = backing_inode_security(oldsb->s_root);
881 struct inode_security_struct *newroot = backing_inode_security(newsb->s_root);
882 if (oldroot->sid != newroot->sid)
887 pr_warn("SELinux: mount invalid. Same superblock, "
888 "different security settings for (dev %s, "
889 "type %s)\n", newsb->s_id, newsb->s_type->name);
893 static int selinux_sb_clone_mnt_opts(const struct super_block *oldsb,
894 struct super_block *newsb,
895 unsigned long kern_flags,
896 unsigned long *set_kern_flags)
899 const struct superblock_security_struct *oldsbsec = oldsb->s_security;
900 struct superblock_security_struct *newsbsec = newsb->s_security;
902 int set_fscontext = (oldsbsec->flags & FSCONTEXT_MNT);
903 int set_context = (oldsbsec->flags & CONTEXT_MNT);
904 int set_rootcontext = (oldsbsec->flags & ROOTCONTEXT_MNT);
907 * if the parent was able to be mounted it clearly had no special lsm
908 * mount options. thus we can safely deal with this superblock later
910 if (!selinux_initialized(&selinux_state))
914 * Specifying internal flags without providing a place to
915 * place the results is not allowed.
917 if (kern_flags && !set_kern_flags)
920 /* how can we clone if the old one wasn't set up?? */
921 BUG_ON(!(oldsbsec->flags & SE_SBINITIALIZED));
923 /* if fs is reusing a sb, make sure that the contexts match */
924 if (newsbsec->flags & SE_SBINITIALIZED) {
925 if ((kern_flags & SECURITY_LSM_NATIVE_LABELS) && !set_context)
926 *set_kern_flags |= SECURITY_LSM_NATIVE_LABELS;
927 return selinux_cmp_sb_context(oldsb, newsb);
930 mutex_lock(&newsbsec->lock);
932 newsbsec->flags = oldsbsec->flags;
934 newsbsec->sid = oldsbsec->sid;
935 newsbsec->def_sid = oldsbsec->def_sid;
936 newsbsec->behavior = oldsbsec->behavior;
938 if (newsbsec->behavior == SECURITY_FS_USE_NATIVE &&
939 !(kern_flags & SECURITY_LSM_NATIVE_LABELS) && !set_context) {
940 rc = security_fs_use(&selinux_state, newsb);
945 if (kern_flags & SECURITY_LSM_NATIVE_LABELS && !set_context) {
946 newsbsec->behavior = SECURITY_FS_USE_NATIVE;
947 *set_kern_flags |= SECURITY_LSM_NATIVE_LABELS;
951 u32 sid = oldsbsec->mntpoint_sid;
955 if (!set_rootcontext) {
956 struct inode_security_struct *newisec = backing_inode_security(newsb->s_root);
959 newsbsec->mntpoint_sid = sid;
961 if (set_rootcontext) {
962 const struct inode_security_struct *oldisec = backing_inode_security(oldsb->s_root);
963 struct inode_security_struct *newisec = backing_inode_security(newsb->s_root);
965 newisec->sid = oldisec->sid;
968 sb_finish_set_opts(newsb);
970 mutex_unlock(&newsbsec->lock);
974 static int selinux_add_opt(int token, const char *s, void **mnt_opts)
976 struct selinux_mnt_opts *opts = *mnt_opts;
978 if (token == Opt_seclabel) /* eaten and completely ignored */
982 opts = kzalloc(sizeof(struct selinux_mnt_opts), GFP_KERNEL);
991 if (opts->context || opts->defcontext)
1000 case Opt_rootcontext:
1001 if (opts->rootcontext)
1003 opts->rootcontext = s;
1005 case Opt_defcontext:
1006 if (opts->context || opts->defcontext)
1008 opts->defcontext = s;
1013 pr_warn(SEL_MOUNT_FAIL_MSG);
1017 static int selinux_add_mnt_opt(const char *option, const char *val, int len,
1020 int token = Opt_error;
1023 for (i = 0; i < ARRAY_SIZE(tokens); i++) {
1024 if (strcmp(option, tokens[i].name) == 0) {
1025 token = tokens[i].opt;
1030 if (token == Opt_error)
1033 if (token != Opt_seclabel) {
1034 val = kmemdup_nul(val, len, GFP_KERNEL);
1040 rc = selinux_add_opt(token, val, mnt_opts);
1049 selinux_free_mnt_opts(*mnt_opts);
1055 static int show_sid(struct seq_file *m, u32 sid)
1057 char *context = NULL;
1061 rc = security_sid_to_context(&selinux_state, sid,
1064 bool has_comma = context && strchr(context, ',');
1069 seq_escape(m, context, "\"\n\\");
1077 static int selinux_sb_show_options(struct seq_file *m, struct super_block *sb)
1079 struct superblock_security_struct *sbsec = sb->s_security;
1082 if (!(sbsec->flags & SE_SBINITIALIZED))
1085 if (!selinux_initialized(&selinux_state))
1088 if (sbsec->flags & FSCONTEXT_MNT) {
1090 seq_puts(m, FSCONTEXT_STR);
1091 rc = show_sid(m, sbsec->sid);
1095 if (sbsec->flags & CONTEXT_MNT) {
1097 seq_puts(m, CONTEXT_STR);
1098 rc = show_sid(m, sbsec->mntpoint_sid);
1102 if (sbsec->flags & DEFCONTEXT_MNT) {
1104 seq_puts(m, DEFCONTEXT_STR);
1105 rc = show_sid(m, sbsec->def_sid);
1109 if (sbsec->flags & ROOTCONTEXT_MNT) {
1110 struct dentry *root = sb->s_root;
1111 struct inode_security_struct *isec = backing_inode_security(root);
1113 seq_puts(m, ROOTCONTEXT_STR);
1114 rc = show_sid(m, isec->sid);
1118 if (sbsec->flags & SBLABEL_MNT) {
1120 seq_puts(m, SECLABEL_STR);
1125 static inline u16 inode_mode_to_security_class(umode_t mode)
1127 switch (mode & S_IFMT) {
1129 return SECCLASS_SOCK_FILE;
1131 return SECCLASS_LNK_FILE;
1133 return SECCLASS_FILE;
1135 return SECCLASS_BLK_FILE;
1137 return SECCLASS_DIR;
1139 return SECCLASS_CHR_FILE;
1141 return SECCLASS_FIFO_FILE;
1145 return SECCLASS_FILE;
1148 static inline int default_protocol_stream(int protocol)
1150 return (protocol == IPPROTO_IP || protocol == IPPROTO_TCP ||
1151 protocol == IPPROTO_MPTCP);
1154 static inline int default_protocol_dgram(int protocol)
1156 return (protocol == IPPROTO_IP || protocol == IPPROTO_UDP);
1159 static inline u16 socket_type_to_security_class(int family, int type, int protocol)
1161 int extsockclass = selinux_policycap_extsockclass();
1167 case SOCK_SEQPACKET:
1168 return SECCLASS_UNIX_STREAM_SOCKET;
1171 return SECCLASS_UNIX_DGRAM_SOCKET;
1178 case SOCK_SEQPACKET:
1179 if (default_protocol_stream(protocol))
1180 return SECCLASS_TCP_SOCKET;
1181 else if (extsockclass && protocol == IPPROTO_SCTP)
1182 return SECCLASS_SCTP_SOCKET;
1184 return SECCLASS_RAWIP_SOCKET;
1186 if (default_protocol_dgram(protocol))
1187 return SECCLASS_UDP_SOCKET;
1188 else if (extsockclass && (protocol == IPPROTO_ICMP ||
1189 protocol == IPPROTO_ICMPV6))
1190 return SECCLASS_ICMP_SOCKET;
1192 return SECCLASS_RAWIP_SOCKET;
1194 return SECCLASS_DCCP_SOCKET;
1196 return SECCLASS_RAWIP_SOCKET;
1202 return SECCLASS_NETLINK_ROUTE_SOCKET;
1203 case NETLINK_SOCK_DIAG:
1204 return SECCLASS_NETLINK_TCPDIAG_SOCKET;
1206 return SECCLASS_NETLINK_NFLOG_SOCKET;
1208 return SECCLASS_NETLINK_XFRM_SOCKET;
1209 case NETLINK_SELINUX:
1210 return SECCLASS_NETLINK_SELINUX_SOCKET;
1212 return SECCLASS_NETLINK_ISCSI_SOCKET;
1214 return SECCLASS_NETLINK_AUDIT_SOCKET;
1215 case NETLINK_FIB_LOOKUP:
1216 return SECCLASS_NETLINK_FIB_LOOKUP_SOCKET;
1217 case NETLINK_CONNECTOR:
1218 return SECCLASS_NETLINK_CONNECTOR_SOCKET;
1219 case NETLINK_NETFILTER:
1220 return SECCLASS_NETLINK_NETFILTER_SOCKET;
1221 case NETLINK_DNRTMSG:
1222 return SECCLASS_NETLINK_DNRT_SOCKET;
1223 case NETLINK_KOBJECT_UEVENT:
1224 return SECCLASS_NETLINK_KOBJECT_UEVENT_SOCKET;
1225 case NETLINK_GENERIC:
1226 return SECCLASS_NETLINK_GENERIC_SOCKET;
1227 case NETLINK_SCSITRANSPORT:
1228 return SECCLASS_NETLINK_SCSITRANSPORT_SOCKET;
1230 return SECCLASS_NETLINK_RDMA_SOCKET;
1231 case NETLINK_CRYPTO:
1232 return SECCLASS_NETLINK_CRYPTO_SOCKET;
1234 return SECCLASS_NETLINK_SOCKET;
1237 return SECCLASS_PACKET_SOCKET;
1239 return SECCLASS_KEY_SOCKET;
1241 return SECCLASS_APPLETALK_SOCKET;
1247 return SECCLASS_AX25_SOCKET;
1249 return SECCLASS_IPX_SOCKET;
1251 return SECCLASS_NETROM_SOCKET;
1253 return SECCLASS_ATMPVC_SOCKET;
1255 return SECCLASS_X25_SOCKET;
1257 return SECCLASS_ROSE_SOCKET;
1259 return SECCLASS_DECNET_SOCKET;
1261 return SECCLASS_ATMSVC_SOCKET;
1263 return SECCLASS_RDS_SOCKET;
1265 return SECCLASS_IRDA_SOCKET;
1267 return SECCLASS_PPPOX_SOCKET;
1269 return SECCLASS_LLC_SOCKET;
1271 return SECCLASS_CAN_SOCKET;
1273 return SECCLASS_TIPC_SOCKET;
1275 return SECCLASS_BLUETOOTH_SOCKET;
1277 return SECCLASS_IUCV_SOCKET;
1279 return SECCLASS_RXRPC_SOCKET;
1281 return SECCLASS_ISDN_SOCKET;
1283 return SECCLASS_PHONET_SOCKET;
1285 return SECCLASS_IEEE802154_SOCKET;
1287 return SECCLASS_CAIF_SOCKET;
1289 return SECCLASS_ALG_SOCKET;
1291 return SECCLASS_NFC_SOCKET;
1293 return SECCLASS_VSOCK_SOCKET;
1295 return SECCLASS_KCM_SOCKET;
1297 return SECCLASS_QIPCRTR_SOCKET;
1299 return SECCLASS_SMC_SOCKET;
1301 return SECCLASS_XDP_SOCKET;
1303 #error New address family defined, please update this function.
1308 return SECCLASS_SOCKET;
1311 static int selinux_genfs_get_sid(struct dentry *dentry,
1317 struct super_block *sb = dentry->d_sb;
1318 char *buffer, *path;
1320 buffer = (char *)__get_free_page(GFP_KERNEL);
1324 path = dentry_path_raw(dentry, buffer, PAGE_SIZE);
1328 if (flags & SE_SBPROC) {
1329 /* each process gets a /proc/PID/ entry. Strip off the
1330 * PID part to get a valid selinux labeling.
1331 * e.g. /proc/1/net/rpc/nfs -> /net/rpc/nfs */
1332 while (path[1] >= '0' && path[1] <= '9') {
1337 rc = security_genfs_sid(&selinux_state, sb->s_type->name,
1339 if (rc == -ENOENT) {
1340 /* No match in policy, mark as unlabeled. */
1341 *sid = SECINITSID_UNLABELED;
1345 free_page((unsigned long)buffer);
1349 static int inode_doinit_use_xattr(struct inode *inode, struct dentry *dentry,
1350 u32 def_sid, u32 *sid)
1352 #define INITCONTEXTLEN 255
1357 len = INITCONTEXTLEN;
1358 context = kmalloc(len + 1, GFP_NOFS);
1362 context[len] = '\0';
1363 rc = __vfs_getxattr(dentry, inode, XATTR_NAME_SELINUX, context, len);
1364 if (rc == -ERANGE) {
1367 /* Need a larger buffer. Query for the right size. */
1368 rc = __vfs_getxattr(dentry, inode, XATTR_NAME_SELINUX, NULL, 0);
1373 context = kmalloc(len + 1, GFP_NOFS);
1377 context[len] = '\0';
1378 rc = __vfs_getxattr(dentry, inode, XATTR_NAME_SELINUX,
1383 if (rc != -ENODATA) {
1384 pr_warn("SELinux: %s: getxattr returned %d for dev=%s ino=%ld\n",
1385 __func__, -rc, inode->i_sb->s_id, inode->i_ino);
1392 rc = security_context_to_sid_default(&selinux_state, context, rc, sid,
1395 char *dev = inode->i_sb->s_id;
1396 unsigned long ino = inode->i_ino;
1398 if (rc == -EINVAL) {
1399 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",
1402 pr_warn("SELinux: %s: context_to_sid(%s) returned %d for dev=%s ino=%ld\n",
1403 __func__, context, -rc, dev, ino);
1410 /* The inode's security attributes must be initialized before first use. */
1411 static int inode_doinit_with_dentry(struct inode *inode, struct dentry *opt_dentry)
1413 struct superblock_security_struct *sbsec = NULL;
1414 struct inode_security_struct *isec = selinux_inode(inode);
1415 u32 task_sid, sid = 0;
1417 struct dentry *dentry;
1420 if (isec->initialized == LABEL_INITIALIZED)
1423 spin_lock(&isec->lock);
1424 if (isec->initialized == LABEL_INITIALIZED)
1427 if (isec->sclass == SECCLASS_FILE)
1428 isec->sclass = inode_mode_to_security_class(inode->i_mode);
1430 sbsec = inode->i_sb->s_security;
1431 if (!(sbsec->flags & SE_SBINITIALIZED)) {
1432 /* Defer initialization until selinux_complete_init,
1433 after the initial policy is loaded and the security
1434 server is ready to handle calls. */
1435 spin_lock(&sbsec->isec_lock);
1436 if (list_empty(&isec->list))
1437 list_add(&isec->list, &sbsec->isec_head);
1438 spin_unlock(&sbsec->isec_lock);
1442 sclass = isec->sclass;
1443 task_sid = isec->task_sid;
1445 isec->initialized = LABEL_PENDING;
1446 spin_unlock(&isec->lock);
1448 switch (sbsec->behavior) {
1449 case SECURITY_FS_USE_NATIVE:
1451 case SECURITY_FS_USE_XATTR:
1452 if (!(inode->i_opflags & IOP_XATTR)) {
1453 sid = sbsec->def_sid;
1456 /* Need a dentry, since the xattr API requires one.
1457 Life would be simpler if we could just pass the inode. */
1459 /* Called from d_instantiate or d_splice_alias. */
1460 dentry = dget(opt_dentry);
1463 * Called from selinux_complete_init, try to find a dentry.
1464 * Some filesystems really want a connected one, so try
1465 * that first. We could split SECURITY_FS_USE_XATTR in
1466 * two, depending upon that...
1468 dentry = d_find_alias(inode);
1470 dentry = d_find_any_alias(inode);
1474 * this is can be hit on boot when a file is accessed
1475 * before the policy is loaded. When we load policy we
1476 * may find inodes that have no dentry on the
1477 * sbsec->isec_head list. No reason to complain as these
1478 * will get fixed up the next time we go through
1479 * inode_doinit with a dentry, before these inodes could
1480 * be used again by userspace.
1485 rc = inode_doinit_use_xattr(inode, dentry, sbsec->def_sid,
1491 case SECURITY_FS_USE_TASK:
1494 case SECURITY_FS_USE_TRANS:
1495 /* Default to the fs SID. */
1498 /* Try to obtain a transition SID. */
1499 rc = security_transition_sid(&selinux_state, task_sid, sid,
1500 sclass, NULL, &sid);
1504 case SECURITY_FS_USE_MNTPOINT:
1505 sid = sbsec->mntpoint_sid;
1508 /* Default to the fs superblock SID. */
1511 if ((sbsec->flags & SE_SBGENFS) &&
1512 (!S_ISLNK(inode->i_mode) ||
1513 selinux_policycap_genfs_seclabel_symlinks())) {
1514 /* We must have a dentry to determine the label on
1517 /* Called from d_instantiate or
1518 * d_splice_alias. */
1519 dentry = dget(opt_dentry);
1521 /* Called from selinux_complete_init, try to
1522 * find a dentry. Some filesystems really want
1523 * a connected one, so try that first.
1525 dentry = d_find_alias(inode);
1527 dentry = d_find_any_alias(inode);
1530 * This can be hit on boot when a file is accessed
1531 * before the policy is loaded. When we load policy we
1532 * may find inodes that have no dentry on the
1533 * sbsec->isec_head list. No reason to complain as
1534 * these will get fixed up the next time we go through
1535 * inode_doinit() with a dentry, before these inodes
1536 * could be used again by userspace.
1540 rc = selinux_genfs_get_sid(dentry, sclass,
1541 sbsec->flags, &sid);
1547 if ((sbsec->flags & SE_SBGENFS_XATTR) &&
1548 (inode->i_opflags & IOP_XATTR)) {
1549 rc = inode_doinit_use_xattr(inode, dentry,
1562 spin_lock(&isec->lock);
1563 if (isec->initialized == LABEL_PENDING) {
1565 isec->initialized = LABEL_INVALID;
1568 isec->initialized = LABEL_INITIALIZED;
1573 spin_unlock(&isec->lock);
1577 spin_lock(&isec->lock);
1578 if (isec->initialized == LABEL_PENDING) {
1579 isec->initialized = LABEL_INVALID;
1582 spin_unlock(&isec->lock);
1586 /* Convert a Linux signal to an access vector. */
1587 static inline u32 signal_to_av(int sig)
1593 /* Commonly granted from child to parent. */
1594 perm = PROCESS__SIGCHLD;
1597 /* Cannot be caught or ignored */
1598 perm = PROCESS__SIGKILL;
1601 /* Cannot be caught or ignored */
1602 perm = PROCESS__SIGSTOP;
1605 /* All other signals. */
1606 perm = PROCESS__SIGNAL;
1613 #if CAP_LAST_CAP > 63
1614 #error Fix SELinux to handle capabilities > 63.
1617 /* Check whether a task is allowed to use a capability. */
1618 static int cred_has_capability(const struct cred *cred,
1619 int cap, unsigned int opts, bool initns)
1621 struct common_audit_data ad;
1622 struct av_decision avd;
1624 u32 sid = cred_sid(cred);
1625 u32 av = CAP_TO_MASK(cap);
1628 ad.type = LSM_AUDIT_DATA_CAP;
1631 switch (CAP_TO_INDEX(cap)) {
1633 sclass = initns ? SECCLASS_CAPABILITY : SECCLASS_CAP_USERNS;
1636 sclass = initns ? SECCLASS_CAPABILITY2 : SECCLASS_CAP2_USERNS;
1639 pr_err("SELinux: out of range capability %d\n", cap);
1644 rc = avc_has_perm_noaudit(&selinux_state,
1645 sid, sid, sclass, av, 0, &avd);
1646 if (!(opts & CAP_OPT_NOAUDIT)) {
1647 int rc2 = avc_audit(&selinux_state,
1648 sid, sid, sclass, av, &avd, rc, &ad, 0);
1655 /* Check whether a task has a particular permission to an inode.
1656 The 'adp' parameter is optional and allows other audit
1657 data to be passed (e.g. the dentry). */
1658 static int inode_has_perm(const struct cred *cred,
1659 struct inode *inode,
1661 struct common_audit_data *adp)
1663 struct inode_security_struct *isec;
1666 validate_creds(cred);
1668 if (unlikely(IS_PRIVATE(inode)))
1671 sid = cred_sid(cred);
1672 isec = selinux_inode(inode);
1674 return avc_has_perm(&selinux_state,
1675 sid, isec->sid, isec->sclass, perms, adp);
1678 /* Same as inode_has_perm, but pass explicit audit data containing
1679 the dentry to help the auditing code to more easily generate the
1680 pathname if needed. */
1681 static inline int dentry_has_perm(const struct cred *cred,
1682 struct dentry *dentry,
1685 struct inode *inode = d_backing_inode(dentry);
1686 struct common_audit_data ad;
1688 ad.type = LSM_AUDIT_DATA_DENTRY;
1689 ad.u.dentry = dentry;
1690 __inode_security_revalidate(inode, dentry, true);
1691 return inode_has_perm(cred, inode, av, &ad);
1694 /* Same as inode_has_perm, but pass explicit audit data containing
1695 the path to help the auditing code to more easily generate the
1696 pathname if needed. */
1697 static inline int path_has_perm(const struct cred *cred,
1698 const struct path *path,
1701 struct inode *inode = d_backing_inode(path->dentry);
1702 struct common_audit_data ad;
1704 ad.type = LSM_AUDIT_DATA_PATH;
1706 __inode_security_revalidate(inode, path->dentry, true);
1707 return inode_has_perm(cred, inode, av, &ad);
1710 /* Same as path_has_perm, but uses the inode from the file struct. */
1711 static inline int file_path_has_perm(const struct cred *cred,
1715 struct common_audit_data ad;
1717 ad.type = LSM_AUDIT_DATA_FILE;
1719 return inode_has_perm(cred, file_inode(file), av, &ad);
1722 #ifdef CONFIG_BPF_SYSCALL
1723 static int bpf_fd_pass(struct file *file, u32 sid);
1726 /* Check whether a task can use an open file descriptor to
1727 access an inode in a given way. Check access to the
1728 descriptor itself, and then use dentry_has_perm to
1729 check a particular permission to the file.
1730 Access to the descriptor is implicitly granted if it
1731 has the same SID as the process. If av is zero, then
1732 access to the file is not checked, e.g. for cases
1733 where only the descriptor is affected like seek. */
1734 static int file_has_perm(const struct cred *cred,
1738 struct file_security_struct *fsec = selinux_file(file);
1739 struct inode *inode = file_inode(file);
1740 struct common_audit_data ad;
1741 u32 sid = cred_sid(cred);
1744 ad.type = LSM_AUDIT_DATA_FILE;
1747 if (sid != fsec->sid) {
1748 rc = avc_has_perm(&selinux_state,
1757 #ifdef CONFIG_BPF_SYSCALL
1758 rc = bpf_fd_pass(file, cred_sid(cred));
1763 /* av is zero if only checking access to the descriptor. */
1766 rc = inode_has_perm(cred, inode, av, &ad);
1773 * Determine the label for an inode that might be unioned.
1776 selinux_determine_inode_label(const struct task_security_struct *tsec,
1778 const struct qstr *name, u16 tclass,
1781 const struct superblock_security_struct *sbsec = dir->i_sb->s_security;
1783 if ((sbsec->flags & SE_SBINITIALIZED) &&
1784 (sbsec->behavior == SECURITY_FS_USE_MNTPOINT)) {
1785 *_new_isid = sbsec->mntpoint_sid;
1786 } else if ((sbsec->flags & SBLABEL_MNT) &&
1788 *_new_isid = tsec->create_sid;
1790 const struct inode_security_struct *dsec = inode_security(dir);
1791 return security_transition_sid(&selinux_state, tsec->sid,
1799 /* Check whether a task can create a file. */
1800 static int may_create(struct inode *dir,
1801 struct dentry *dentry,
1804 const struct task_security_struct *tsec = selinux_cred(current_cred());
1805 struct inode_security_struct *dsec;
1806 struct superblock_security_struct *sbsec;
1808 struct common_audit_data ad;
1811 dsec = inode_security(dir);
1812 sbsec = dir->i_sb->s_security;
1816 ad.type = LSM_AUDIT_DATA_DENTRY;
1817 ad.u.dentry = dentry;
1819 rc = avc_has_perm(&selinux_state,
1820 sid, dsec->sid, SECCLASS_DIR,
1821 DIR__ADD_NAME | DIR__SEARCH,
1826 rc = selinux_determine_inode_label(tsec, dir, &dentry->d_name, tclass,
1831 rc = avc_has_perm(&selinux_state,
1832 sid, newsid, tclass, FILE__CREATE, &ad);
1836 return avc_has_perm(&selinux_state,
1838 SECCLASS_FILESYSTEM,
1839 FILESYSTEM__ASSOCIATE, &ad);
1843 #define MAY_UNLINK 1
1846 /* Check whether a task can link, unlink, or rmdir a file/directory. */
1847 static int may_link(struct inode *dir,
1848 struct dentry *dentry,
1852 struct inode_security_struct *dsec, *isec;
1853 struct common_audit_data ad;
1854 u32 sid = current_sid();
1858 dsec = inode_security(dir);
1859 isec = backing_inode_security(dentry);
1861 ad.type = LSM_AUDIT_DATA_DENTRY;
1862 ad.u.dentry = dentry;
1865 av |= (kind ? DIR__REMOVE_NAME : DIR__ADD_NAME);
1866 rc = avc_has_perm(&selinux_state,
1867 sid, dsec->sid, SECCLASS_DIR, av, &ad);
1882 pr_warn("SELinux: %s: unrecognized kind %d\n",
1887 rc = avc_has_perm(&selinux_state,
1888 sid, isec->sid, isec->sclass, av, &ad);
1892 static inline int may_rename(struct inode *old_dir,
1893 struct dentry *old_dentry,
1894 struct inode *new_dir,
1895 struct dentry *new_dentry)
1897 struct inode_security_struct *old_dsec, *new_dsec, *old_isec, *new_isec;
1898 struct common_audit_data ad;
1899 u32 sid = current_sid();
1901 int old_is_dir, new_is_dir;
1904 old_dsec = inode_security(old_dir);
1905 old_isec = backing_inode_security(old_dentry);
1906 old_is_dir = d_is_dir(old_dentry);
1907 new_dsec = inode_security(new_dir);
1909 ad.type = LSM_AUDIT_DATA_DENTRY;
1911 ad.u.dentry = old_dentry;
1912 rc = avc_has_perm(&selinux_state,
1913 sid, old_dsec->sid, SECCLASS_DIR,
1914 DIR__REMOVE_NAME | DIR__SEARCH, &ad);
1917 rc = avc_has_perm(&selinux_state,
1919 old_isec->sclass, FILE__RENAME, &ad);
1922 if (old_is_dir && new_dir != old_dir) {
1923 rc = avc_has_perm(&selinux_state,
1925 old_isec->sclass, DIR__REPARENT, &ad);
1930 ad.u.dentry = new_dentry;
1931 av = DIR__ADD_NAME | DIR__SEARCH;
1932 if (d_is_positive(new_dentry))
1933 av |= DIR__REMOVE_NAME;
1934 rc = avc_has_perm(&selinux_state,
1935 sid, new_dsec->sid, SECCLASS_DIR, av, &ad);
1938 if (d_is_positive(new_dentry)) {
1939 new_isec = backing_inode_security(new_dentry);
1940 new_is_dir = d_is_dir(new_dentry);
1941 rc = avc_has_perm(&selinux_state,
1944 (new_is_dir ? DIR__RMDIR : FILE__UNLINK), &ad);
1952 /* Check whether a task can perform a filesystem operation. */
1953 static int superblock_has_perm(const struct cred *cred,
1954 struct super_block *sb,
1956 struct common_audit_data *ad)
1958 struct superblock_security_struct *sbsec;
1959 u32 sid = cred_sid(cred);
1961 sbsec = sb->s_security;
1962 return avc_has_perm(&selinux_state,
1963 sid, sbsec->sid, SECCLASS_FILESYSTEM, perms, ad);
1966 /* Convert a Linux mode and permission mask to an access vector. */
1967 static inline u32 file_mask_to_av(int mode, int mask)
1971 if (!S_ISDIR(mode)) {
1972 if (mask & MAY_EXEC)
1973 av |= FILE__EXECUTE;
1974 if (mask & MAY_READ)
1977 if (mask & MAY_APPEND)
1979 else if (mask & MAY_WRITE)
1983 if (mask & MAY_EXEC)
1985 if (mask & MAY_WRITE)
1987 if (mask & MAY_READ)
1994 /* Convert a Linux file to an access vector. */
1995 static inline u32 file_to_av(struct file *file)
1999 if (file->f_mode & FMODE_READ)
2001 if (file->f_mode & FMODE_WRITE) {
2002 if (file->f_flags & O_APPEND)
2009 * Special file opened with flags 3 for ioctl-only use.
2018 * Convert a file to an access vector and include the correct
2021 static inline u32 open_file_to_av(struct file *file)
2023 u32 av = file_to_av(file);
2024 struct inode *inode = file_inode(file);
2026 if (selinux_policycap_openperm() &&
2027 inode->i_sb->s_magic != SOCKFS_MAGIC)
2033 /* Hook functions begin here. */
2035 static int selinux_binder_set_context_mgr(struct task_struct *mgr)
2037 u32 mysid = current_sid();
2038 u32 mgrsid = task_sid(mgr);
2040 return avc_has_perm(&selinux_state,
2041 mysid, mgrsid, SECCLASS_BINDER,
2042 BINDER__SET_CONTEXT_MGR, NULL);
2045 static int selinux_binder_transaction(struct task_struct *from,
2046 struct task_struct *to)
2048 u32 mysid = current_sid();
2049 u32 fromsid = task_sid(from);
2050 u32 tosid = task_sid(to);
2053 if (mysid != fromsid) {
2054 rc = avc_has_perm(&selinux_state,
2055 mysid, fromsid, SECCLASS_BINDER,
2056 BINDER__IMPERSONATE, NULL);
2061 return avc_has_perm(&selinux_state,
2062 fromsid, tosid, SECCLASS_BINDER, BINDER__CALL,
2066 static int selinux_binder_transfer_binder(struct task_struct *from,
2067 struct task_struct *to)
2069 u32 fromsid = task_sid(from);
2070 u32 tosid = task_sid(to);
2072 return avc_has_perm(&selinux_state,
2073 fromsid, tosid, SECCLASS_BINDER, BINDER__TRANSFER,
2077 static int selinux_binder_transfer_file(struct task_struct *from,
2078 struct task_struct *to,
2081 u32 sid = task_sid(to);
2082 struct file_security_struct *fsec = selinux_file(file);
2083 struct dentry *dentry = file->f_path.dentry;
2084 struct inode_security_struct *isec;
2085 struct common_audit_data ad;
2088 ad.type = LSM_AUDIT_DATA_PATH;
2089 ad.u.path = file->f_path;
2091 if (sid != fsec->sid) {
2092 rc = avc_has_perm(&selinux_state,
2101 #ifdef CONFIG_BPF_SYSCALL
2102 rc = bpf_fd_pass(file, sid);
2107 if (unlikely(IS_PRIVATE(d_backing_inode(dentry))))
2110 isec = backing_inode_security(dentry);
2111 return avc_has_perm(&selinux_state,
2112 sid, isec->sid, isec->sclass, file_to_av(file),
2116 static int selinux_ptrace_access_check(struct task_struct *child,
2119 u32 sid = current_sid();
2120 u32 csid = task_sid(child);
2122 if (mode & PTRACE_MODE_READ)
2123 return avc_has_perm(&selinux_state,
2124 sid, csid, SECCLASS_FILE, FILE__READ, NULL);
2126 return avc_has_perm(&selinux_state,
2127 sid, csid, SECCLASS_PROCESS, PROCESS__PTRACE, NULL);
2130 static int selinux_ptrace_traceme(struct task_struct *parent)
2132 return avc_has_perm(&selinux_state,
2133 task_sid(parent), current_sid(), SECCLASS_PROCESS,
2134 PROCESS__PTRACE, NULL);
2137 static int selinux_capget(struct task_struct *target, kernel_cap_t *effective,
2138 kernel_cap_t *inheritable, kernel_cap_t *permitted)
2140 return avc_has_perm(&selinux_state,
2141 current_sid(), task_sid(target), SECCLASS_PROCESS,
2142 PROCESS__GETCAP, NULL);
2145 static int selinux_capset(struct cred *new, const struct cred *old,
2146 const kernel_cap_t *effective,
2147 const kernel_cap_t *inheritable,
2148 const kernel_cap_t *permitted)
2150 return avc_has_perm(&selinux_state,
2151 cred_sid(old), cred_sid(new), SECCLASS_PROCESS,
2152 PROCESS__SETCAP, NULL);
2156 * (This comment used to live with the selinux_task_setuid hook,
2157 * which was removed).
2159 * Since setuid only affects the current process, and since the SELinux
2160 * controls are not based on the Linux identity attributes, SELinux does not
2161 * need to control this operation. However, SELinux does control the use of
2162 * the CAP_SETUID and CAP_SETGID capabilities using the capable hook.
2165 static int selinux_capable(const struct cred *cred, struct user_namespace *ns,
2166 int cap, unsigned int opts)
2168 return cred_has_capability(cred, cap, opts, ns == &init_user_ns);
2171 static int selinux_quotactl(int cmds, int type, int id, struct super_block *sb)
2173 const struct cred *cred = current_cred();
2188 rc = superblock_has_perm(cred, sb, FILESYSTEM__QUOTAMOD, NULL);
2196 case Q_XGETNEXTQUOTA:
2197 rc = superblock_has_perm(cred, sb, FILESYSTEM__QUOTAGET, NULL);
2200 rc = 0; /* let the kernel handle invalid cmds */
2206 static int selinux_quota_on(struct dentry *dentry)
2208 const struct cred *cred = current_cred();
2210 return dentry_has_perm(cred, dentry, FILE__QUOTAON);
2213 static int selinux_syslog(int type)
2216 case SYSLOG_ACTION_READ_ALL: /* Read last kernel messages */
2217 case SYSLOG_ACTION_SIZE_BUFFER: /* Return size of the log buffer */
2218 return avc_has_perm(&selinux_state,
2219 current_sid(), SECINITSID_KERNEL,
2220 SECCLASS_SYSTEM, SYSTEM__SYSLOG_READ, NULL);
2221 case SYSLOG_ACTION_CONSOLE_OFF: /* Disable logging to console */
2222 case SYSLOG_ACTION_CONSOLE_ON: /* Enable logging to console */
2223 /* Set level of messages printed to console */
2224 case SYSLOG_ACTION_CONSOLE_LEVEL:
2225 return avc_has_perm(&selinux_state,
2226 current_sid(), SECINITSID_KERNEL,
2227 SECCLASS_SYSTEM, SYSTEM__SYSLOG_CONSOLE,
2230 /* All other syslog types */
2231 return avc_has_perm(&selinux_state,
2232 current_sid(), SECINITSID_KERNEL,
2233 SECCLASS_SYSTEM, SYSTEM__SYSLOG_MOD, NULL);
2237 * Check that a process has enough memory to allocate a new virtual
2238 * mapping. 0 means there is enough memory for the allocation to
2239 * succeed and -ENOMEM implies there is not.
2241 * Do not audit the selinux permission check, as this is applied to all
2242 * processes that allocate mappings.
2244 static int selinux_vm_enough_memory(struct mm_struct *mm, long pages)
2246 int rc, cap_sys_admin = 0;
2248 rc = cred_has_capability(current_cred(), CAP_SYS_ADMIN,
2249 CAP_OPT_NOAUDIT, true);
2253 return cap_sys_admin;
2256 /* binprm security operations */
2258 static u32 ptrace_parent_sid(void)
2261 struct task_struct *tracer;
2264 tracer = ptrace_parent(current);
2266 sid = task_sid(tracer);
2272 static int check_nnp_nosuid(const struct linux_binprm *bprm,
2273 const struct task_security_struct *old_tsec,
2274 const struct task_security_struct *new_tsec)
2276 int nnp = (bprm->unsafe & LSM_UNSAFE_NO_NEW_PRIVS);
2277 int nosuid = !mnt_may_suid(bprm->file->f_path.mnt);
2281 if (!nnp && !nosuid)
2282 return 0; /* neither NNP nor nosuid */
2284 if (new_tsec->sid == old_tsec->sid)
2285 return 0; /* No change in credentials */
2288 * If the policy enables the nnp_nosuid_transition policy capability,
2289 * then we permit transitions under NNP or nosuid if the
2290 * policy allows the corresponding permission between
2291 * the old and new contexts.
2293 if (selinux_policycap_nnp_nosuid_transition()) {
2296 av |= PROCESS2__NNP_TRANSITION;
2298 av |= PROCESS2__NOSUID_TRANSITION;
2299 rc = avc_has_perm(&selinux_state,
2300 old_tsec->sid, new_tsec->sid,
2301 SECCLASS_PROCESS2, av, NULL);
2307 * We also permit NNP or nosuid transitions to bounded SIDs,
2308 * i.e. SIDs that are guaranteed to only be allowed a subset
2309 * of the permissions of the current SID.
2311 rc = security_bounded_transition(&selinux_state, old_tsec->sid,
2317 * On failure, preserve the errno values for NNP vs nosuid.
2318 * NNP: Operation not permitted for caller.
2319 * nosuid: Permission denied to file.
2326 static int selinux_bprm_creds_for_exec(struct linux_binprm *bprm)
2328 const struct task_security_struct *old_tsec;
2329 struct task_security_struct *new_tsec;
2330 struct inode_security_struct *isec;
2331 struct common_audit_data ad;
2332 struct inode *inode = file_inode(bprm->file);
2335 /* SELinux context only depends on initial program or script and not
2336 * the script interpreter */
2338 old_tsec = selinux_cred(current_cred());
2339 new_tsec = selinux_cred(bprm->cred);
2340 isec = inode_security(inode);
2342 /* Default to the current task SID. */
2343 new_tsec->sid = old_tsec->sid;
2344 new_tsec->osid = old_tsec->sid;
2346 /* Reset fs, key, and sock SIDs on execve. */
2347 new_tsec->create_sid = 0;
2348 new_tsec->keycreate_sid = 0;
2349 new_tsec->sockcreate_sid = 0;
2351 if (old_tsec->exec_sid) {
2352 new_tsec->sid = old_tsec->exec_sid;
2353 /* Reset exec SID on execve. */
2354 new_tsec->exec_sid = 0;
2356 /* Fail on NNP or nosuid if not an allowed transition. */
2357 rc = check_nnp_nosuid(bprm, old_tsec, new_tsec);
2361 /* Check for a default transition on this program. */
2362 rc = security_transition_sid(&selinux_state, old_tsec->sid,
2363 isec->sid, SECCLASS_PROCESS, NULL,
2369 * Fallback to old SID on NNP or nosuid if not an allowed
2372 rc = check_nnp_nosuid(bprm, old_tsec, new_tsec);
2374 new_tsec->sid = old_tsec->sid;
2377 ad.type = LSM_AUDIT_DATA_FILE;
2378 ad.u.file = bprm->file;
2380 if (new_tsec->sid == old_tsec->sid) {
2381 rc = avc_has_perm(&selinux_state,
2382 old_tsec->sid, isec->sid,
2383 SECCLASS_FILE, FILE__EXECUTE_NO_TRANS, &ad);
2387 /* Check permissions for the transition. */
2388 rc = avc_has_perm(&selinux_state,
2389 old_tsec->sid, new_tsec->sid,
2390 SECCLASS_PROCESS, PROCESS__TRANSITION, &ad);
2394 rc = avc_has_perm(&selinux_state,
2395 new_tsec->sid, isec->sid,
2396 SECCLASS_FILE, FILE__ENTRYPOINT, &ad);
2400 /* Check for shared state */
2401 if (bprm->unsafe & LSM_UNSAFE_SHARE) {
2402 rc = avc_has_perm(&selinux_state,
2403 old_tsec->sid, new_tsec->sid,
2404 SECCLASS_PROCESS, PROCESS__SHARE,
2410 /* Make sure that anyone attempting to ptrace over a task that
2411 * changes its SID has the appropriate permit */
2412 if (bprm->unsafe & LSM_UNSAFE_PTRACE) {
2413 u32 ptsid = ptrace_parent_sid();
2415 rc = avc_has_perm(&selinux_state,
2416 ptsid, new_tsec->sid,
2418 PROCESS__PTRACE, NULL);
2424 /* Clear any possibly unsafe personality bits on exec: */
2425 bprm->per_clear |= PER_CLEAR_ON_SETID;
2427 /* Enable secure mode for SIDs transitions unless
2428 the noatsecure permission is granted between
2429 the two SIDs, i.e. ahp returns 0. */
2430 rc = avc_has_perm(&selinux_state,
2431 old_tsec->sid, new_tsec->sid,
2432 SECCLASS_PROCESS, PROCESS__NOATSECURE,
2434 bprm->secureexec |= !!rc;
2440 static int match_file(const void *p, struct file *file, unsigned fd)
2442 return file_has_perm(p, file, file_to_av(file)) ? fd + 1 : 0;
2445 /* Derived from fs/exec.c:flush_old_files. */
2446 static inline void flush_unauthorized_files(const struct cred *cred,
2447 struct files_struct *files)
2449 struct file *file, *devnull = NULL;
2450 struct tty_struct *tty;
2454 tty = get_current_tty();
2456 spin_lock(&tty->files_lock);
2457 if (!list_empty(&tty->tty_files)) {
2458 struct tty_file_private *file_priv;
2460 /* Revalidate access to controlling tty.
2461 Use file_path_has_perm on the tty path directly
2462 rather than using file_has_perm, as this particular
2463 open file may belong to another process and we are
2464 only interested in the inode-based check here. */
2465 file_priv = list_first_entry(&tty->tty_files,
2466 struct tty_file_private, list);
2467 file = file_priv->file;
2468 if (file_path_has_perm(cred, file, FILE__READ | FILE__WRITE))
2471 spin_unlock(&tty->files_lock);
2474 /* Reset controlling tty. */
2478 /* Revalidate access to inherited open files. */
2479 n = iterate_fd(files, 0, match_file, cred);
2480 if (!n) /* none found? */
2483 devnull = dentry_open(&selinux_null, O_RDWR, cred);
2484 if (IS_ERR(devnull))
2486 /* replace all the matching ones with this */
2488 replace_fd(n - 1, devnull, 0);
2489 } while ((n = iterate_fd(files, n, match_file, cred)) != 0);
2495 * Prepare a process for imminent new credential changes due to exec
2497 static void selinux_bprm_committing_creds(struct linux_binprm *bprm)
2499 struct task_security_struct *new_tsec;
2500 struct rlimit *rlim, *initrlim;
2503 new_tsec = selinux_cred(bprm->cred);
2504 if (new_tsec->sid == new_tsec->osid)
2507 /* Close files for which the new task SID is not authorized. */
2508 flush_unauthorized_files(bprm->cred, current->files);
2510 /* Always clear parent death signal on SID transitions. */
2511 current->pdeath_signal = 0;
2513 /* Check whether the new SID can inherit resource limits from the old
2514 * SID. If not, reset all soft limits to the lower of the current
2515 * task's hard limit and the init task's soft limit.
2517 * Note that the setting of hard limits (even to lower them) can be
2518 * controlled by the setrlimit check. The inclusion of the init task's
2519 * soft limit into the computation is to avoid resetting soft limits
2520 * higher than the default soft limit for cases where the default is
2521 * lower than the hard limit, e.g. RLIMIT_CORE or RLIMIT_STACK.
2523 rc = avc_has_perm(&selinux_state,
2524 new_tsec->osid, new_tsec->sid, SECCLASS_PROCESS,
2525 PROCESS__RLIMITINH, NULL);
2527 /* protect against do_prlimit() */
2529 for (i = 0; i < RLIM_NLIMITS; i++) {
2530 rlim = current->signal->rlim + i;
2531 initrlim = init_task.signal->rlim + i;
2532 rlim->rlim_cur = min(rlim->rlim_max, initrlim->rlim_cur);
2534 task_unlock(current);
2535 if (IS_ENABLED(CONFIG_POSIX_TIMERS))
2536 update_rlimit_cpu(current, rlimit(RLIMIT_CPU));
2541 * Clean up the process immediately after the installation of new credentials
2544 static void selinux_bprm_committed_creds(struct linux_binprm *bprm)
2546 const struct task_security_struct *tsec = selinux_cred(current_cred());
2556 /* Check whether the new SID can inherit signal state from the old SID.
2557 * If not, clear itimers to avoid subsequent signal generation and
2558 * flush and unblock signals.
2560 * This must occur _after_ the task SID has been updated so that any
2561 * kill done after the flush will be checked against the new SID.
2563 rc = avc_has_perm(&selinux_state,
2564 osid, sid, SECCLASS_PROCESS, PROCESS__SIGINH, NULL);
2568 spin_lock_irq(¤t->sighand->siglock);
2569 if (!fatal_signal_pending(current)) {
2570 flush_sigqueue(¤t->pending);
2571 flush_sigqueue(¤t->signal->shared_pending);
2572 flush_signal_handlers(current, 1);
2573 sigemptyset(¤t->blocked);
2574 recalc_sigpending();
2576 spin_unlock_irq(¤t->sighand->siglock);
2579 /* Wake up the parent if it is waiting so that it can recheck
2580 * wait permission to the new task SID. */
2581 read_lock(&tasklist_lock);
2582 __wake_up_parent(current, current->real_parent);
2583 read_unlock(&tasklist_lock);
2586 /* superblock security operations */
2588 static int selinux_sb_alloc_security(struct super_block *sb)
2590 struct superblock_security_struct *sbsec;
2592 sbsec = kzalloc(sizeof(struct superblock_security_struct), GFP_KERNEL);
2596 mutex_init(&sbsec->lock);
2597 INIT_LIST_HEAD(&sbsec->isec_head);
2598 spin_lock_init(&sbsec->isec_lock);
2599 sbsec->sid = SECINITSID_UNLABELED;
2600 sbsec->def_sid = SECINITSID_FILE;
2601 sbsec->mntpoint_sid = SECINITSID_UNLABELED;
2602 sb->s_security = sbsec;
2607 static void selinux_sb_free_security(struct super_block *sb)
2609 superblock_free_security(sb);
2612 static inline int opt_len(const char *s)
2614 bool open_quote = false;
2618 for (len = 0; (c = s[len]) != '\0'; len++) {
2620 open_quote = !open_quote;
2621 if (c == ',' && !open_quote)
2627 static int selinux_sb_eat_lsm_opts(char *options, void **mnt_opts)
2629 char *from = options;
2635 int len = opt_len(from);
2639 token = match_opt_prefix(from, len, &arg);
2641 if (token != Opt_error) {
2646 for (p = q = arg; p < from + len; p++) {
2651 arg = kmemdup_nul(arg, q - arg, GFP_KERNEL);
2657 rc = selinux_add_opt(token, arg, mnt_opts);
2663 if (!first) { // copy with preceding comma
2668 memmove(to, from, len);
2681 selinux_free_mnt_opts(*mnt_opts);
2687 static int selinux_sb_remount(struct super_block *sb, void *mnt_opts)
2689 struct selinux_mnt_opts *opts = mnt_opts;
2690 struct superblock_security_struct *sbsec = sb->s_security;
2694 if (!(sbsec->flags & SE_SBINITIALIZED))
2700 if (opts->fscontext) {
2701 rc = parse_sid(sb, opts->fscontext, &sid);
2704 if (bad_option(sbsec, FSCONTEXT_MNT, sbsec->sid, sid))
2705 goto out_bad_option;
2707 if (opts->context) {
2708 rc = parse_sid(sb, opts->context, &sid);
2711 if (bad_option(sbsec, CONTEXT_MNT, sbsec->mntpoint_sid, sid))
2712 goto out_bad_option;
2714 if (opts->rootcontext) {
2715 struct inode_security_struct *root_isec;
2716 root_isec = backing_inode_security(sb->s_root);
2717 rc = parse_sid(sb, opts->rootcontext, &sid);
2720 if (bad_option(sbsec, ROOTCONTEXT_MNT, root_isec->sid, sid))
2721 goto out_bad_option;
2723 if (opts->defcontext) {
2724 rc = parse_sid(sb, opts->defcontext, &sid);
2727 if (bad_option(sbsec, DEFCONTEXT_MNT, sbsec->def_sid, sid))
2728 goto out_bad_option;
2733 pr_warn("SELinux: unable to change security options "
2734 "during remount (dev %s, type=%s)\n", sb->s_id,
2739 static int selinux_sb_kern_mount(struct super_block *sb)
2741 const struct cred *cred = current_cred();
2742 struct common_audit_data ad;
2744 ad.type = LSM_AUDIT_DATA_DENTRY;
2745 ad.u.dentry = sb->s_root;
2746 return superblock_has_perm(cred, sb, FILESYSTEM__MOUNT, &ad);
2749 static int selinux_sb_statfs(struct dentry *dentry)
2751 const struct cred *cred = current_cred();
2752 struct common_audit_data ad;
2754 ad.type = LSM_AUDIT_DATA_DENTRY;
2755 ad.u.dentry = dentry->d_sb->s_root;
2756 return superblock_has_perm(cred, dentry->d_sb, FILESYSTEM__GETATTR, &ad);
2759 static int selinux_mount(const char *dev_name,
2760 const struct path *path,
2762 unsigned long flags,
2765 const struct cred *cred = current_cred();
2767 if (flags & MS_REMOUNT)
2768 return superblock_has_perm(cred, path->dentry->d_sb,
2769 FILESYSTEM__REMOUNT, NULL);
2771 return path_has_perm(cred, path, FILE__MOUNTON);
2774 static int selinux_move_mount(const struct path *from_path,
2775 const struct path *to_path)
2777 const struct cred *cred = current_cred();
2779 return path_has_perm(cred, to_path, FILE__MOUNTON);
2782 static int selinux_umount(struct vfsmount *mnt, int flags)
2784 const struct cred *cred = current_cred();
2786 return superblock_has_perm(cred, mnt->mnt_sb,
2787 FILESYSTEM__UNMOUNT, NULL);
2790 static int selinux_fs_context_dup(struct fs_context *fc,
2791 struct fs_context *src_fc)
2793 const struct selinux_mnt_opts *src = src_fc->security;
2794 struct selinux_mnt_opts *opts;
2799 fc->security = kzalloc(sizeof(struct selinux_mnt_opts), GFP_KERNEL);
2803 opts = fc->security;
2805 if (src->fscontext) {
2806 opts->fscontext = kstrdup(src->fscontext, GFP_KERNEL);
2807 if (!opts->fscontext)
2811 opts->context = kstrdup(src->context, GFP_KERNEL);
2815 if (src->rootcontext) {
2816 opts->rootcontext = kstrdup(src->rootcontext, GFP_KERNEL);
2817 if (!opts->rootcontext)
2820 if (src->defcontext) {
2821 opts->defcontext = kstrdup(src->defcontext, GFP_KERNEL);
2822 if (!opts->defcontext)
2828 static const struct fs_parameter_spec selinux_fs_parameters[] = {
2829 fsparam_string(CONTEXT_STR, Opt_context),
2830 fsparam_string(DEFCONTEXT_STR, Opt_defcontext),
2831 fsparam_string(FSCONTEXT_STR, Opt_fscontext),
2832 fsparam_string(ROOTCONTEXT_STR, Opt_rootcontext),
2833 fsparam_flag (SECLABEL_STR, Opt_seclabel),
2837 static int selinux_fs_context_parse_param(struct fs_context *fc,
2838 struct fs_parameter *param)
2840 struct fs_parse_result result;
2843 opt = fs_parse(fc, selinux_fs_parameters, param, &result);
2847 rc = selinux_add_opt(opt, param->string, &fc->security);
2849 param->string = NULL;
2855 /* inode security operations */
2857 static int selinux_inode_alloc_security(struct inode *inode)
2859 struct inode_security_struct *isec = selinux_inode(inode);
2860 u32 sid = current_sid();
2862 spin_lock_init(&isec->lock);
2863 INIT_LIST_HEAD(&isec->list);
2864 isec->inode = inode;
2865 isec->sid = SECINITSID_UNLABELED;
2866 isec->sclass = SECCLASS_FILE;
2867 isec->task_sid = sid;
2868 isec->initialized = LABEL_INVALID;
2873 static void selinux_inode_free_security(struct inode *inode)
2875 inode_free_security(inode);
2878 static int selinux_dentry_init_security(struct dentry *dentry, int mode,
2879 const struct qstr *name, void **ctx,
2885 rc = selinux_determine_inode_label(selinux_cred(current_cred()),
2886 d_inode(dentry->d_parent), name,
2887 inode_mode_to_security_class(mode),
2892 return security_sid_to_context(&selinux_state, newsid, (char **)ctx,
2896 static int selinux_dentry_create_files_as(struct dentry *dentry, int mode,
2898 const struct cred *old,
2903 struct task_security_struct *tsec;
2905 rc = selinux_determine_inode_label(selinux_cred(old),
2906 d_inode(dentry->d_parent), name,
2907 inode_mode_to_security_class(mode),
2912 tsec = selinux_cred(new);
2913 tsec->create_sid = newsid;
2917 static int selinux_inode_init_security(struct inode *inode, struct inode *dir,
2918 const struct qstr *qstr,
2920 void **value, size_t *len)
2922 const struct task_security_struct *tsec = selinux_cred(current_cred());
2923 struct superblock_security_struct *sbsec;
2928 sbsec = dir->i_sb->s_security;
2930 newsid = tsec->create_sid;
2932 rc = selinux_determine_inode_label(tsec, dir, qstr,
2933 inode_mode_to_security_class(inode->i_mode),
2938 /* Possibly defer initialization to selinux_complete_init. */
2939 if (sbsec->flags & SE_SBINITIALIZED) {
2940 struct inode_security_struct *isec = selinux_inode(inode);
2941 isec->sclass = inode_mode_to_security_class(inode->i_mode);
2943 isec->initialized = LABEL_INITIALIZED;
2946 if (!selinux_initialized(&selinux_state) ||
2947 !(sbsec->flags & SBLABEL_MNT))
2951 *name = XATTR_SELINUX_SUFFIX;
2954 rc = security_sid_to_context_force(&selinux_state, newsid,
2965 static int selinux_inode_init_security_anon(struct inode *inode,
2966 const struct qstr *name,
2967 const struct inode *context_inode)
2969 const struct task_security_struct *tsec = selinux_cred(current_cred());
2970 struct common_audit_data ad;
2971 struct inode_security_struct *isec;
2974 if (unlikely(!selinux_initialized(&selinux_state)))
2977 isec = selinux_inode(inode);
2980 * We only get here once per ephemeral inode. The inode has
2981 * been initialized via inode_alloc_security but is otherwise
2985 if (context_inode) {
2986 struct inode_security_struct *context_isec =
2987 selinux_inode(context_inode);
2988 if (context_isec->initialized != LABEL_INITIALIZED) {
2989 pr_err("SELinux: context_inode is not initialized");
2993 isec->sclass = context_isec->sclass;
2994 isec->sid = context_isec->sid;
2996 isec->sclass = SECCLASS_ANON_INODE;
2997 rc = security_transition_sid(
2998 &selinux_state, tsec->sid, tsec->sid,
2999 isec->sclass, name, &isec->sid);
3004 isec->initialized = LABEL_INITIALIZED;
3006 * Now that we've initialized security, check whether we're
3007 * allowed to actually create this type of anonymous inode.
3010 ad.type = LSM_AUDIT_DATA_INODE;
3013 return avc_has_perm(&selinux_state,
3021 static int selinux_inode_create(struct inode *dir, struct dentry *dentry, umode_t mode)
3023 return may_create(dir, dentry, SECCLASS_FILE);
3026 static int selinux_inode_link(struct dentry *old_dentry, struct inode *dir, struct dentry *new_dentry)
3028 return may_link(dir, old_dentry, MAY_LINK);
3031 static int selinux_inode_unlink(struct inode *dir, struct dentry *dentry)
3033 return may_link(dir, dentry, MAY_UNLINK);
3036 static int selinux_inode_symlink(struct inode *dir, struct dentry *dentry, const char *name)
3038 return may_create(dir, dentry, SECCLASS_LNK_FILE);
3041 static int selinux_inode_mkdir(struct inode *dir, struct dentry *dentry, umode_t mask)
3043 return may_create(dir, dentry, SECCLASS_DIR);
3046 static int selinux_inode_rmdir(struct inode *dir, struct dentry *dentry)
3048 return may_link(dir, dentry, MAY_RMDIR);
3051 static int selinux_inode_mknod(struct inode *dir, struct dentry *dentry, umode_t mode, dev_t dev)
3053 return may_create(dir, dentry, inode_mode_to_security_class(mode));
3056 static int selinux_inode_rename(struct inode *old_inode, struct dentry *old_dentry,
3057 struct inode *new_inode, struct dentry *new_dentry)
3059 return may_rename(old_inode, old_dentry, new_inode, new_dentry);
3062 static int selinux_inode_readlink(struct dentry *dentry)
3064 const struct cred *cred = current_cred();
3066 return dentry_has_perm(cred, dentry, FILE__READ);
3069 static int selinux_inode_follow_link(struct dentry *dentry, struct inode *inode,
3072 const struct cred *cred = current_cred();
3073 struct common_audit_data ad;
3074 struct inode_security_struct *isec;
3077 validate_creds(cred);
3079 ad.type = LSM_AUDIT_DATA_DENTRY;
3080 ad.u.dentry = dentry;
3081 sid = cred_sid(cred);
3082 isec = inode_security_rcu(inode, rcu);
3084 return PTR_ERR(isec);
3086 return avc_has_perm_flags(&selinux_state,
3087 sid, isec->sid, isec->sclass, FILE__READ, &ad,
3088 rcu ? MAY_NOT_BLOCK : 0);
3091 static noinline int audit_inode_permission(struct inode *inode,
3092 u32 perms, u32 audited, u32 denied,
3095 struct common_audit_data ad;
3096 struct inode_security_struct *isec = selinux_inode(inode);
3099 ad.type = LSM_AUDIT_DATA_INODE;
3102 rc = slow_avc_audit(&selinux_state,
3103 current_sid(), isec->sid, isec->sclass, perms,
3104 audited, denied, result, &ad);
3110 static int selinux_inode_permission(struct inode *inode, int mask)
3112 const struct cred *cred = current_cred();
3115 bool no_block = mask & MAY_NOT_BLOCK;
3116 struct inode_security_struct *isec;
3118 struct av_decision avd;
3120 u32 audited, denied;
3122 from_access = mask & MAY_ACCESS;
3123 mask &= (MAY_READ|MAY_WRITE|MAY_EXEC|MAY_APPEND);
3125 /* No permission to check. Existence test. */
3129 validate_creds(cred);
3131 if (unlikely(IS_PRIVATE(inode)))
3134 perms = file_mask_to_av(inode->i_mode, mask);
3136 sid = cred_sid(cred);
3137 isec = inode_security_rcu(inode, no_block);
3139 return PTR_ERR(isec);
3141 rc = avc_has_perm_noaudit(&selinux_state,
3142 sid, isec->sid, isec->sclass, perms,
3143 no_block ? AVC_NONBLOCKING : 0,
3145 audited = avc_audit_required(perms, &avd, rc,
3146 from_access ? FILE__AUDIT_ACCESS : 0,
3148 if (likely(!audited))
3151 /* fall back to ref-walk if we have to generate audit */
3155 rc2 = audit_inode_permission(inode, perms, audited, denied, rc);
3161 static int selinux_inode_setattr(struct dentry *dentry, struct iattr *iattr)
3163 const struct cred *cred = current_cred();
3164 struct inode *inode = d_backing_inode(dentry);
3165 unsigned int ia_valid = iattr->ia_valid;
3166 __u32 av = FILE__WRITE;
3168 /* ATTR_FORCE is just used for ATTR_KILL_S[UG]ID. */
3169 if (ia_valid & ATTR_FORCE) {
3170 ia_valid &= ~(ATTR_KILL_SUID | ATTR_KILL_SGID | ATTR_MODE |
3176 if (ia_valid & (ATTR_MODE | ATTR_UID | ATTR_GID |
3177 ATTR_ATIME_SET | ATTR_MTIME_SET | ATTR_TIMES_SET))
3178 return dentry_has_perm(cred, dentry, FILE__SETATTR);
3180 if (selinux_policycap_openperm() &&
3181 inode->i_sb->s_magic != SOCKFS_MAGIC &&
3182 (ia_valid & ATTR_SIZE) &&
3183 !(ia_valid & ATTR_FILE))
3186 return dentry_has_perm(cred, dentry, av);
3189 static int selinux_inode_getattr(const struct path *path)
3191 return path_has_perm(current_cred(), path, FILE__GETATTR);
3194 static bool has_cap_mac_admin(bool audit)
3196 const struct cred *cred = current_cred();
3197 unsigned int opts = audit ? CAP_OPT_NONE : CAP_OPT_NOAUDIT;
3199 if (cap_capable(cred, &init_user_ns, CAP_MAC_ADMIN, opts))
3201 if (cred_has_capability(cred, CAP_MAC_ADMIN, opts, true))
3206 static int selinux_inode_setxattr(struct user_namespace *mnt_userns,
3207 struct dentry *dentry, const char *name,
3208 const void *value, size_t size, int flags)
3210 struct inode *inode = d_backing_inode(dentry);
3211 struct inode_security_struct *isec;
3212 struct superblock_security_struct *sbsec;
3213 struct common_audit_data ad;
3214 u32 newsid, sid = current_sid();
3217 if (strcmp(name, XATTR_NAME_SELINUX)) {
3218 rc = cap_inode_setxattr(dentry, name, value, size, flags);
3222 /* Not an attribute we recognize, so just check the
3223 ordinary setattr permission. */
3224 return dentry_has_perm(current_cred(), dentry, FILE__SETATTR);
3227 if (!selinux_initialized(&selinux_state))
3228 return (inode_owner_or_capable(mnt_userns, inode) ? 0 : -EPERM);
3230 sbsec = inode->i_sb->s_security;
3231 if (!(sbsec->flags & SBLABEL_MNT))
3234 if (!inode_owner_or_capable(mnt_userns, inode))
3237 ad.type = LSM_AUDIT_DATA_DENTRY;
3238 ad.u.dentry = dentry;
3240 isec = backing_inode_security(dentry);
3241 rc = avc_has_perm(&selinux_state,
3242 sid, isec->sid, isec->sclass,
3243 FILE__RELABELFROM, &ad);
3247 rc = security_context_to_sid(&selinux_state, value, size, &newsid,
3249 if (rc == -EINVAL) {
3250 if (!has_cap_mac_admin(true)) {
3251 struct audit_buffer *ab;
3254 /* We strip a nul only if it is at the end, otherwise the
3255 * context contains a nul and we should audit that */
3257 const char *str = value;
3259 if (str[size - 1] == '\0')
3260 audit_size = size - 1;
3266 ab = audit_log_start(audit_context(),
3267 GFP_ATOMIC, AUDIT_SELINUX_ERR);
3268 audit_log_format(ab, "op=setxattr invalid_context=");
3269 audit_log_n_untrustedstring(ab, value, audit_size);
3274 rc = security_context_to_sid_force(&selinux_state, value,
3280 rc = avc_has_perm(&selinux_state,
3281 sid, newsid, isec->sclass,
3282 FILE__RELABELTO, &ad);
3286 rc = security_validate_transition(&selinux_state, isec->sid, newsid,
3291 return avc_has_perm(&selinux_state,
3294 SECCLASS_FILESYSTEM,
3295 FILESYSTEM__ASSOCIATE,
3299 static void selinux_inode_post_setxattr(struct dentry *dentry, const char *name,
3300 const void *value, size_t size,
3303 struct inode *inode = d_backing_inode(dentry);
3304 struct inode_security_struct *isec;
3308 if (strcmp(name, XATTR_NAME_SELINUX)) {
3309 /* Not an attribute we recognize, so nothing to do. */
3313 if (!selinux_initialized(&selinux_state)) {
3314 /* If we haven't even been initialized, then we can't validate
3315 * against a policy, so leave the label as invalid. It may
3316 * resolve to a valid label on the next revalidation try if
3317 * we've since initialized.
3322 rc = security_context_to_sid_force(&selinux_state, value, size,
3325 pr_err("SELinux: unable to map context to SID"
3326 "for (%s, %lu), rc=%d\n",
3327 inode->i_sb->s_id, inode->i_ino, -rc);
3331 isec = backing_inode_security(dentry);
3332 spin_lock(&isec->lock);
3333 isec->sclass = inode_mode_to_security_class(inode->i_mode);
3335 isec->initialized = LABEL_INITIALIZED;
3336 spin_unlock(&isec->lock);
3341 static int selinux_inode_getxattr(struct dentry *dentry, const char *name)
3343 const struct cred *cred = current_cred();
3345 return dentry_has_perm(cred, dentry, FILE__GETATTR);
3348 static int selinux_inode_listxattr(struct dentry *dentry)
3350 const struct cred *cred = current_cred();
3352 return dentry_has_perm(cred, dentry, FILE__GETATTR);
3355 static int selinux_inode_removexattr(struct user_namespace *mnt_userns,
3356 struct dentry *dentry, const char *name)
3358 if (strcmp(name, XATTR_NAME_SELINUX)) {
3359 int rc = cap_inode_removexattr(mnt_userns, dentry, name);
3363 /* Not an attribute we recognize, so just check the
3364 ordinary setattr permission. */
3365 return dentry_has_perm(current_cred(), dentry, FILE__SETATTR);
3368 if (!selinux_initialized(&selinux_state))
3371 /* No one is allowed to remove a SELinux security label.
3372 You can change the label, but all data must be labeled. */
3376 static int selinux_path_notify(const struct path *path, u64 mask,
3377 unsigned int obj_type)
3382 struct common_audit_data ad;
3384 ad.type = LSM_AUDIT_DATA_PATH;
3388 * Set permission needed based on the type of mark being set.
3389 * Performs an additional check for sb watches.
3392 case FSNOTIFY_OBJ_TYPE_VFSMOUNT:
3393 perm = FILE__WATCH_MOUNT;
3395 case FSNOTIFY_OBJ_TYPE_SB:
3396 perm = FILE__WATCH_SB;
3397 ret = superblock_has_perm(current_cred(), path->dentry->d_sb,
3398 FILESYSTEM__WATCH, &ad);
3402 case FSNOTIFY_OBJ_TYPE_INODE:
3409 /* blocking watches require the file:watch_with_perm permission */
3410 if (mask & (ALL_FSNOTIFY_PERM_EVENTS))
3411 perm |= FILE__WATCH_WITH_PERM;
3413 /* watches on read-like events need the file:watch_reads permission */
3414 if (mask & (FS_ACCESS | FS_ACCESS_PERM | FS_CLOSE_NOWRITE))
3415 perm |= FILE__WATCH_READS;
3417 return path_has_perm(current_cred(), path, perm);
3421 * Copy the inode security context value to the user.
3423 * Permission check is handled by selinux_inode_getxattr hook.
3425 static int selinux_inode_getsecurity(struct user_namespace *mnt_userns,
3426 struct inode *inode, const char *name,
3427 void **buffer, bool alloc)
3431 char *context = NULL;
3432 struct inode_security_struct *isec;
3435 * If we're not initialized yet, then we can't validate contexts, so
3436 * just let vfs_getxattr fall back to using the on-disk xattr.
3438 if (!selinux_initialized(&selinux_state) ||
3439 strcmp(name, XATTR_SELINUX_SUFFIX))
3443 * If the caller has CAP_MAC_ADMIN, then get the raw context
3444 * value even if it is not defined by current policy; otherwise,
3445 * use the in-core value under current policy.
3446 * Use the non-auditing forms of the permission checks since
3447 * getxattr may be called by unprivileged processes commonly
3448 * and lack of permission just means that we fall back to the
3449 * in-core context value, not a denial.
3451 isec = inode_security(inode);
3452 if (has_cap_mac_admin(false))
3453 error = security_sid_to_context_force(&selinux_state,
3454 isec->sid, &context,
3457 error = security_sid_to_context(&selinux_state, isec->sid,
3471 static int selinux_inode_setsecurity(struct inode *inode, const char *name,
3472 const void *value, size_t size, int flags)
3474 struct inode_security_struct *isec = inode_security_novalidate(inode);
3475 struct superblock_security_struct *sbsec = inode->i_sb->s_security;
3479 if (strcmp(name, XATTR_SELINUX_SUFFIX))
3482 if (!(sbsec->flags & SBLABEL_MNT))
3485 if (!value || !size)
3488 rc = security_context_to_sid(&selinux_state, value, size, &newsid,
3493 spin_lock(&isec->lock);
3494 isec->sclass = inode_mode_to_security_class(inode->i_mode);
3496 isec->initialized = LABEL_INITIALIZED;
3497 spin_unlock(&isec->lock);
3501 static int selinux_inode_listsecurity(struct inode *inode, char *buffer, size_t buffer_size)
3503 const int len = sizeof(XATTR_NAME_SELINUX);
3505 if (!selinux_initialized(&selinux_state))
3508 if (buffer && len <= buffer_size)
3509 memcpy(buffer, XATTR_NAME_SELINUX, len);
3513 static void selinux_inode_getsecid(struct inode *inode, u32 *secid)
3515 struct inode_security_struct *isec = inode_security_novalidate(inode);
3519 static int selinux_inode_copy_up(struct dentry *src, struct cred **new)
3522 struct task_security_struct *tsec;
3523 struct cred *new_creds = *new;
3525 if (new_creds == NULL) {
3526 new_creds = prepare_creds();
3531 tsec = selinux_cred(new_creds);
3532 /* Get label from overlay inode and set it in create_sid */
3533 selinux_inode_getsecid(d_inode(src), &sid);
3534 tsec->create_sid = sid;
3539 static int selinux_inode_copy_up_xattr(const char *name)
3541 /* The copy_up hook above sets the initial context on an inode, but we
3542 * don't then want to overwrite it by blindly copying all the lower
3543 * xattrs up. Instead, we have to filter out SELinux-related xattrs.
3545 if (strcmp(name, XATTR_NAME_SELINUX) == 0)
3546 return 1; /* Discard */
3548 * Any other attribute apart from SELINUX is not claimed, supported
3554 /* kernfs node operations */
3556 static int selinux_kernfs_init_security(struct kernfs_node *kn_dir,
3557 struct kernfs_node *kn)
3559 const struct task_security_struct *tsec = selinux_cred(current_cred());
3560 u32 parent_sid, newsid, clen;
3564 rc = kernfs_xattr_get(kn_dir, XATTR_NAME_SELINUX, NULL, 0);
3571 context = kmalloc(clen, GFP_KERNEL);
3575 rc = kernfs_xattr_get(kn_dir, XATTR_NAME_SELINUX, context, clen);
3581 rc = security_context_to_sid(&selinux_state, context, clen, &parent_sid,
3587 if (tsec->create_sid) {
3588 newsid = tsec->create_sid;
3590 u16 secclass = inode_mode_to_security_class(kn->mode);
3594 q.hash_len = hashlen_string(kn_dir, kn->name);
3596 rc = security_transition_sid(&selinux_state, tsec->sid,
3597 parent_sid, secclass, &q,
3603 rc = security_sid_to_context_force(&selinux_state, newsid,
3608 rc = kernfs_xattr_set(kn, XATTR_NAME_SELINUX, context, clen,
3615 /* file security operations */
3617 static int selinux_revalidate_file_permission(struct file *file, int mask)
3619 const struct cred *cred = current_cred();
3620 struct inode *inode = file_inode(file);
3622 /* file_mask_to_av won't add FILE__WRITE if MAY_APPEND is set */
3623 if ((file->f_flags & O_APPEND) && (mask & MAY_WRITE))
3626 return file_has_perm(cred, file,
3627 file_mask_to_av(inode->i_mode, mask));
3630 static int selinux_file_permission(struct file *file, int mask)
3632 struct inode *inode = file_inode(file);
3633 struct file_security_struct *fsec = selinux_file(file);
3634 struct inode_security_struct *isec;
3635 u32 sid = current_sid();
3638 /* No permission to check. Existence test. */
3641 isec = inode_security(inode);
3642 if (sid == fsec->sid && fsec->isid == isec->sid &&
3643 fsec->pseqno == avc_policy_seqno(&selinux_state))
3644 /* No change since file_open check. */
3647 return selinux_revalidate_file_permission(file, mask);
3650 static int selinux_file_alloc_security(struct file *file)
3652 struct file_security_struct *fsec = selinux_file(file);
3653 u32 sid = current_sid();
3656 fsec->fown_sid = sid;
3662 * Check whether a task has the ioctl permission and cmd
3663 * operation to an inode.
3665 static int ioctl_has_perm(const struct cred *cred, struct file *file,
3666 u32 requested, u16 cmd)
3668 struct common_audit_data ad;
3669 struct file_security_struct *fsec = selinux_file(file);
3670 struct inode *inode = file_inode(file);
3671 struct inode_security_struct *isec;
3672 struct lsm_ioctlop_audit ioctl;
3673 u32 ssid = cred_sid(cred);
3675 u8 driver = cmd >> 8;
3676 u8 xperm = cmd & 0xff;
3678 ad.type = LSM_AUDIT_DATA_IOCTL_OP;
3681 ad.u.op->path = file->f_path;
3683 if (ssid != fsec->sid) {
3684 rc = avc_has_perm(&selinux_state,
3693 if (unlikely(IS_PRIVATE(inode)))
3696 isec = inode_security(inode);
3697 rc = avc_has_extended_perms(&selinux_state,
3698 ssid, isec->sid, isec->sclass,
3699 requested, driver, xperm, &ad);
3704 static int selinux_file_ioctl(struct file *file, unsigned int cmd,
3707 const struct cred *cred = current_cred();
3714 case FS_IOC_GETFLAGS:
3715 case FS_IOC_GETVERSION:
3716 error = file_has_perm(cred, file, FILE__GETATTR);
3719 case FS_IOC_SETFLAGS:
3720 case FS_IOC_SETVERSION:
3721 error = file_has_perm(cred, file, FILE__SETATTR);
3724 /* sys_ioctl() checks */
3727 error = file_has_perm(cred, file, 0);
3732 error = cred_has_capability(cred, CAP_SYS_TTY_CONFIG,
3733 CAP_OPT_NONE, true);
3736 /* default case assumes that the command will go
3737 * to the file's ioctl() function.
3740 error = ioctl_has_perm(cred, file, FILE__IOCTL, (u16) cmd);
3745 static int default_noexec __ro_after_init;
3747 static int file_map_prot_check(struct file *file, unsigned long prot, int shared)
3749 const struct cred *cred = current_cred();
3750 u32 sid = cred_sid(cred);
3753 if (default_noexec &&
3754 (prot & PROT_EXEC) && (!file || IS_PRIVATE(file_inode(file)) ||
3755 (!shared && (prot & PROT_WRITE)))) {
3757 * We are making executable an anonymous mapping or a
3758 * private file mapping that will also be writable.
3759 * This has an additional check.
3761 rc = avc_has_perm(&selinux_state,
3762 sid, sid, SECCLASS_PROCESS,
3763 PROCESS__EXECMEM, NULL);
3769 /* read access is always possible with a mapping */
3770 u32 av = FILE__READ;
3772 /* write access only matters if the mapping is shared */
3773 if (shared && (prot & PROT_WRITE))
3776 if (prot & PROT_EXEC)
3777 av |= FILE__EXECUTE;
3779 return file_has_perm(cred, file, av);
3786 static int selinux_mmap_addr(unsigned long addr)
3790 if (addr < CONFIG_LSM_MMAP_MIN_ADDR) {
3791 u32 sid = current_sid();
3792 rc = avc_has_perm(&selinux_state,
3793 sid, sid, SECCLASS_MEMPROTECT,
3794 MEMPROTECT__MMAP_ZERO, NULL);
3800 static int selinux_mmap_file(struct file *file, unsigned long reqprot,
3801 unsigned long prot, unsigned long flags)
3803 struct common_audit_data ad;
3807 ad.type = LSM_AUDIT_DATA_FILE;
3809 rc = inode_has_perm(current_cred(), file_inode(file),
3815 if (checkreqprot_get(&selinux_state))
3818 return file_map_prot_check(file, prot,
3819 (flags & MAP_TYPE) == MAP_SHARED);
3822 static int selinux_file_mprotect(struct vm_area_struct *vma,
3823 unsigned long reqprot,
3826 const struct cred *cred = current_cred();
3827 u32 sid = cred_sid(cred);
3829 if (checkreqprot_get(&selinux_state))
3832 if (default_noexec &&
3833 (prot & PROT_EXEC) && !(vma->vm_flags & VM_EXEC)) {
3835 if (vma->vm_start >= vma->vm_mm->start_brk &&
3836 vma->vm_end <= vma->vm_mm->brk) {
3837 rc = avc_has_perm(&selinux_state,
3838 sid, sid, SECCLASS_PROCESS,
3839 PROCESS__EXECHEAP, NULL);
3840 } else if (!vma->vm_file &&
3841 ((vma->vm_start <= vma->vm_mm->start_stack &&
3842 vma->vm_end >= vma->vm_mm->start_stack) ||
3843 vma_is_stack_for_current(vma))) {
3844 rc = avc_has_perm(&selinux_state,
3845 sid, sid, SECCLASS_PROCESS,
3846 PROCESS__EXECSTACK, NULL);
3847 } else if (vma->vm_file && vma->anon_vma) {
3849 * We are making executable a file mapping that has
3850 * had some COW done. Since pages might have been
3851 * written, check ability to execute the possibly
3852 * modified content. This typically should only
3853 * occur for text relocations.
3855 rc = file_has_perm(cred, vma->vm_file, FILE__EXECMOD);
3861 return file_map_prot_check(vma->vm_file, prot, vma->vm_flags&VM_SHARED);
3864 static int selinux_file_lock(struct file *file, unsigned int cmd)
3866 const struct cred *cred = current_cred();
3868 return file_has_perm(cred, file, FILE__LOCK);
3871 static int selinux_file_fcntl(struct file *file, unsigned int cmd,
3874 const struct cred *cred = current_cred();
3879 if ((file->f_flags & O_APPEND) && !(arg & O_APPEND)) {
3880 err = file_has_perm(cred, file, FILE__WRITE);
3889 case F_GETOWNER_UIDS:
3890 /* Just check FD__USE permission */
3891 err = file_has_perm(cred, file, 0);
3899 #if BITS_PER_LONG == 32
3904 err = file_has_perm(cred, file, FILE__LOCK);
3911 static void selinux_file_set_fowner(struct file *file)
3913 struct file_security_struct *fsec;
3915 fsec = selinux_file(file);
3916 fsec->fown_sid = current_sid();
3919 static int selinux_file_send_sigiotask(struct task_struct *tsk,
3920 struct fown_struct *fown, int signum)
3923 u32 sid = task_sid(tsk);
3925 struct file_security_struct *fsec;
3927 /* struct fown_struct is never outside the context of a struct file */
3928 file = container_of(fown, struct file, f_owner);
3930 fsec = selinux_file(file);
3933 perm = signal_to_av(SIGIO); /* as per send_sigio_to_task */
3935 perm = signal_to_av(signum);
3937 return avc_has_perm(&selinux_state,
3938 fsec->fown_sid, sid,
3939 SECCLASS_PROCESS, perm, NULL);
3942 static int selinux_file_receive(struct file *file)
3944 const struct cred *cred = current_cred();
3946 return file_has_perm(cred, file, file_to_av(file));
3949 static int selinux_file_open(struct file *file)
3951 struct file_security_struct *fsec;
3952 struct inode_security_struct *isec;
3954 fsec = selinux_file(file);
3955 isec = inode_security(file_inode(file));
3957 * Save inode label and policy sequence number
3958 * at open-time so that selinux_file_permission
3959 * can determine whether revalidation is necessary.
3960 * Task label is already saved in the file security
3961 * struct as its SID.
3963 fsec->isid = isec->sid;
3964 fsec->pseqno = avc_policy_seqno(&selinux_state);
3966 * Since the inode label or policy seqno may have changed
3967 * between the selinux_inode_permission check and the saving
3968 * of state above, recheck that access is still permitted.
3969 * Otherwise, access might never be revalidated against the
3970 * new inode label or new policy.
3971 * This check is not redundant - do not remove.
3973 return file_path_has_perm(file->f_cred, file, open_file_to_av(file));
3976 /* task security operations */
3978 static int selinux_task_alloc(struct task_struct *task,
3979 unsigned long clone_flags)
3981 u32 sid = current_sid();
3983 return avc_has_perm(&selinux_state,
3984 sid, sid, SECCLASS_PROCESS, PROCESS__FORK, NULL);
3988 * prepare a new set of credentials for modification
3990 static int selinux_cred_prepare(struct cred *new, const struct cred *old,
3993 const struct task_security_struct *old_tsec = selinux_cred(old);
3994 struct task_security_struct *tsec = selinux_cred(new);
4001 * transfer the SELinux data to a blank set of creds
4003 static void selinux_cred_transfer(struct cred *new, const struct cred *old)
4005 const struct task_security_struct *old_tsec = selinux_cred(old);
4006 struct task_security_struct *tsec = selinux_cred(new);
4011 static void selinux_cred_getsecid(const struct cred *c, u32 *secid)
4013 *secid = cred_sid(c);
4017 * set the security data for a kernel service
4018 * - all the creation contexts are set to unlabelled
4020 static int selinux_kernel_act_as(struct cred *new, u32 secid)
4022 struct task_security_struct *tsec = selinux_cred(new);
4023 u32 sid = current_sid();
4026 ret = avc_has_perm(&selinux_state,
4028 SECCLASS_KERNEL_SERVICE,
4029 KERNEL_SERVICE__USE_AS_OVERRIDE,
4033 tsec->create_sid = 0;
4034 tsec->keycreate_sid = 0;
4035 tsec->sockcreate_sid = 0;
4041 * set the file creation context in a security record to the same as the
4042 * objective context of the specified inode
4044 static int selinux_kernel_create_files_as(struct cred *new, struct inode *inode)
4046 struct inode_security_struct *isec = inode_security(inode);
4047 struct task_security_struct *tsec = selinux_cred(new);
4048 u32 sid = current_sid();
4051 ret = avc_has_perm(&selinux_state,
4053 SECCLASS_KERNEL_SERVICE,
4054 KERNEL_SERVICE__CREATE_FILES_AS,
4058 tsec->create_sid = isec->sid;
4062 static int selinux_kernel_module_request(char *kmod_name)
4064 struct common_audit_data ad;
4066 ad.type = LSM_AUDIT_DATA_KMOD;
4067 ad.u.kmod_name = kmod_name;
4069 return avc_has_perm(&selinux_state,
4070 current_sid(), SECINITSID_KERNEL, SECCLASS_SYSTEM,
4071 SYSTEM__MODULE_REQUEST, &ad);
4074 static int selinux_kernel_module_from_file(struct file *file)
4076 struct common_audit_data ad;
4077 struct inode_security_struct *isec;
4078 struct file_security_struct *fsec;
4079 u32 sid = current_sid();
4084 return avc_has_perm(&selinux_state,
4085 sid, sid, SECCLASS_SYSTEM,
4086 SYSTEM__MODULE_LOAD, NULL);
4090 ad.type = LSM_AUDIT_DATA_FILE;
4093 fsec = selinux_file(file);
4094 if (sid != fsec->sid) {
4095 rc = avc_has_perm(&selinux_state,
4096 sid, fsec->sid, SECCLASS_FD, FD__USE, &ad);
4101 isec = inode_security(file_inode(file));
4102 return avc_has_perm(&selinux_state,
4103 sid, isec->sid, SECCLASS_SYSTEM,
4104 SYSTEM__MODULE_LOAD, &ad);
4107 static int selinux_kernel_read_file(struct file *file,
4108 enum kernel_read_file_id id,
4114 case READING_MODULE:
4115 rc = selinux_kernel_module_from_file(contents ? file : NULL);
4124 static int selinux_kernel_load_data(enum kernel_load_data_id id, bool contents)
4129 case LOADING_MODULE:
4130 rc = selinux_kernel_module_from_file(NULL);
4139 static int selinux_task_setpgid(struct task_struct *p, pid_t pgid)
4141 return avc_has_perm(&selinux_state,
4142 current_sid(), task_sid(p), SECCLASS_PROCESS,
4143 PROCESS__SETPGID, NULL);
4146 static int selinux_task_getpgid(struct task_struct *p)
4148 return avc_has_perm(&selinux_state,
4149 current_sid(), task_sid(p), SECCLASS_PROCESS,
4150 PROCESS__GETPGID, NULL);
4153 static int selinux_task_getsid(struct task_struct *p)
4155 return avc_has_perm(&selinux_state,
4156 current_sid(), task_sid(p), SECCLASS_PROCESS,
4157 PROCESS__GETSESSION, NULL);
4160 static void selinux_task_getsecid(struct task_struct *p, u32 *secid)
4162 *secid = task_sid(p);
4165 static int selinux_task_setnice(struct task_struct *p, int nice)
4167 return avc_has_perm(&selinux_state,
4168 current_sid(), task_sid(p), SECCLASS_PROCESS,
4169 PROCESS__SETSCHED, NULL);
4172 static int selinux_task_setioprio(struct task_struct *p, int ioprio)
4174 return avc_has_perm(&selinux_state,
4175 current_sid(), task_sid(p), SECCLASS_PROCESS,
4176 PROCESS__SETSCHED, NULL);
4179 static int selinux_task_getioprio(struct task_struct *p)
4181 return avc_has_perm(&selinux_state,
4182 current_sid(), task_sid(p), SECCLASS_PROCESS,
4183 PROCESS__GETSCHED, NULL);
4186 static int selinux_task_prlimit(const struct cred *cred, const struct cred *tcred,
4193 if (flags & LSM_PRLIMIT_WRITE)
4194 av |= PROCESS__SETRLIMIT;
4195 if (flags & LSM_PRLIMIT_READ)
4196 av |= PROCESS__GETRLIMIT;
4197 return avc_has_perm(&selinux_state,
4198 cred_sid(cred), cred_sid(tcred),
4199 SECCLASS_PROCESS, av, NULL);
4202 static int selinux_task_setrlimit(struct task_struct *p, unsigned int resource,
4203 struct rlimit *new_rlim)
4205 struct rlimit *old_rlim = p->signal->rlim + resource;
4207 /* Control the ability to change the hard limit (whether
4208 lowering or raising it), so that the hard limit can
4209 later be used as a safe reset point for the soft limit
4210 upon context transitions. See selinux_bprm_committing_creds. */
4211 if (old_rlim->rlim_max != new_rlim->rlim_max)
4212 return avc_has_perm(&selinux_state,
4213 current_sid(), task_sid(p),
4214 SECCLASS_PROCESS, PROCESS__SETRLIMIT, NULL);
4219 static int selinux_task_setscheduler(struct task_struct *p)
4221 return avc_has_perm(&selinux_state,
4222 current_sid(), task_sid(p), SECCLASS_PROCESS,
4223 PROCESS__SETSCHED, NULL);
4226 static int selinux_task_getscheduler(struct task_struct *p)
4228 return avc_has_perm(&selinux_state,
4229 current_sid(), task_sid(p), SECCLASS_PROCESS,
4230 PROCESS__GETSCHED, NULL);
4233 static int selinux_task_movememory(struct task_struct *p)
4235 return avc_has_perm(&selinux_state,
4236 current_sid(), task_sid(p), SECCLASS_PROCESS,
4237 PROCESS__SETSCHED, NULL);
4240 static int selinux_task_kill(struct task_struct *p, struct kernel_siginfo *info,
4241 int sig, const struct cred *cred)
4247 perm = PROCESS__SIGNULL; /* null signal; existence test */
4249 perm = signal_to_av(sig);
4251 secid = current_sid();
4253 secid = cred_sid(cred);
4254 return avc_has_perm(&selinux_state,
4255 secid, task_sid(p), SECCLASS_PROCESS, perm, NULL);
4258 static void selinux_task_to_inode(struct task_struct *p,
4259 struct inode *inode)
4261 struct inode_security_struct *isec = selinux_inode(inode);
4262 u32 sid = task_sid(p);
4264 spin_lock(&isec->lock);
4265 isec->sclass = inode_mode_to_security_class(inode->i_mode);
4267 isec->initialized = LABEL_INITIALIZED;
4268 spin_unlock(&isec->lock);
4271 /* Returns error only if unable to parse addresses */
4272 static int selinux_parse_skb_ipv4(struct sk_buff *skb,
4273 struct common_audit_data *ad, u8 *proto)
4275 int offset, ihlen, ret = -EINVAL;
4276 struct iphdr _iph, *ih;
4278 offset = skb_network_offset(skb);
4279 ih = skb_header_pointer(skb, offset, sizeof(_iph), &_iph);
4283 ihlen = ih->ihl * 4;
4284 if (ihlen < sizeof(_iph))
4287 ad->u.net->v4info.saddr = ih->saddr;
4288 ad->u.net->v4info.daddr = ih->daddr;
4292 *proto = ih->protocol;
4294 switch (ih->protocol) {
4296 struct tcphdr _tcph, *th;
4298 if (ntohs(ih->frag_off) & IP_OFFSET)
4302 th = skb_header_pointer(skb, offset, sizeof(_tcph), &_tcph);
4306 ad->u.net->sport = th->source;
4307 ad->u.net->dport = th->dest;
4312 struct udphdr _udph, *uh;
4314 if (ntohs(ih->frag_off) & IP_OFFSET)
4318 uh = skb_header_pointer(skb, offset, sizeof(_udph), &_udph);
4322 ad->u.net->sport = uh->source;
4323 ad->u.net->dport = uh->dest;
4327 case IPPROTO_DCCP: {
4328 struct dccp_hdr _dccph, *dh;
4330 if (ntohs(ih->frag_off) & IP_OFFSET)
4334 dh = skb_header_pointer(skb, offset, sizeof(_dccph), &_dccph);
4338 ad->u.net->sport = dh->dccph_sport;
4339 ad->u.net->dport = dh->dccph_dport;
4343 #if IS_ENABLED(CONFIG_IP_SCTP)
4344 case IPPROTO_SCTP: {
4345 struct sctphdr _sctph, *sh;
4347 if (ntohs(ih->frag_off) & IP_OFFSET)
4351 sh = skb_header_pointer(skb, offset, sizeof(_sctph), &_sctph);
4355 ad->u.net->sport = sh->source;
4356 ad->u.net->dport = sh->dest;
4367 #if IS_ENABLED(CONFIG_IPV6)
4369 /* Returns error only if unable to parse addresses */
4370 static int selinux_parse_skb_ipv6(struct sk_buff *skb,
4371 struct common_audit_data *ad, u8 *proto)
4374 int ret = -EINVAL, offset;
4375 struct ipv6hdr _ipv6h, *ip6;
4378 offset = skb_network_offset(skb);
4379 ip6 = skb_header_pointer(skb, offset, sizeof(_ipv6h), &_ipv6h);
4383 ad->u.net->v6info.saddr = ip6->saddr;
4384 ad->u.net->v6info.daddr = ip6->daddr;
4387 nexthdr = ip6->nexthdr;
4388 offset += sizeof(_ipv6h);
4389 offset = ipv6_skip_exthdr(skb, offset, &nexthdr, &frag_off);
4398 struct tcphdr _tcph, *th;
4400 th = skb_header_pointer(skb, offset, sizeof(_tcph), &_tcph);
4404 ad->u.net->sport = th->source;
4405 ad->u.net->dport = th->dest;
4410 struct udphdr _udph, *uh;
4412 uh = skb_header_pointer(skb, offset, sizeof(_udph), &_udph);
4416 ad->u.net->sport = uh->source;
4417 ad->u.net->dport = uh->dest;
4421 case IPPROTO_DCCP: {
4422 struct dccp_hdr _dccph, *dh;
4424 dh = skb_header_pointer(skb, offset, sizeof(_dccph), &_dccph);
4428 ad->u.net->sport = dh->dccph_sport;
4429 ad->u.net->dport = dh->dccph_dport;
4433 #if IS_ENABLED(CONFIG_IP_SCTP)
4434 case IPPROTO_SCTP: {
4435 struct sctphdr _sctph, *sh;
4437 sh = skb_header_pointer(skb, offset, sizeof(_sctph), &_sctph);
4441 ad->u.net->sport = sh->source;
4442 ad->u.net->dport = sh->dest;
4446 /* includes fragments */
4456 static int selinux_parse_skb(struct sk_buff *skb, struct common_audit_data *ad,
4457 char **_addrp, int src, u8 *proto)
4462 switch (ad->u.net->family) {
4464 ret = selinux_parse_skb_ipv4(skb, ad, proto);
4467 addrp = (char *)(src ? &ad->u.net->v4info.saddr :
4468 &ad->u.net->v4info.daddr);
4471 #if IS_ENABLED(CONFIG_IPV6)
4473 ret = selinux_parse_skb_ipv6(skb, ad, proto);
4476 addrp = (char *)(src ? &ad->u.net->v6info.saddr :
4477 &ad->u.net->v6info.daddr);
4487 "SELinux: failure in selinux_parse_skb(),"
4488 " unable to parse packet\n");
4498 * selinux_skb_peerlbl_sid - Determine the peer label of a packet
4500 * @family: protocol family
4501 * @sid: the packet's peer label SID
4504 * Check the various different forms of network peer labeling and determine
4505 * the peer label/SID for the packet; most of the magic actually occurs in
4506 * the security server function security_net_peersid_cmp(). The function
4507 * returns zero if the value in @sid is valid (although it may be SECSID_NULL)
4508 * or -EACCES if @sid is invalid due to inconsistencies with the different
4512 static int selinux_skb_peerlbl_sid(struct sk_buff *skb, u16 family, u32 *sid)
4519 err = selinux_xfrm_skb_sid(skb, &xfrm_sid);
4522 err = selinux_netlbl_skbuff_getsid(skb, family, &nlbl_type, &nlbl_sid);
4526 err = security_net_peersid_resolve(&selinux_state, nlbl_sid,
4527 nlbl_type, xfrm_sid, sid);
4528 if (unlikely(err)) {
4530 "SELinux: failure in selinux_skb_peerlbl_sid(),"
4531 " unable to determine packet's peer label\n");
4539 * selinux_conn_sid - Determine the child socket label for a connection
4540 * @sk_sid: the parent socket's SID
4541 * @skb_sid: the packet's SID
4542 * @conn_sid: the resulting connection SID
4544 * If @skb_sid is valid then the user:role:type information from @sk_sid is
4545 * combined with the MLS information from @skb_sid in order to create
4546 * @conn_sid. If @skb_sid is not valid then @conn_sid is simply a copy
4547 * of @sk_sid. Returns zero on success, negative values on failure.
4550 static int selinux_conn_sid(u32 sk_sid, u32 skb_sid, u32 *conn_sid)
4554 if (skb_sid != SECSID_NULL)
4555 err = security_sid_mls_copy(&selinux_state, sk_sid, skb_sid,
4563 /* socket security operations */
4565 static int socket_sockcreate_sid(const struct task_security_struct *tsec,
4566 u16 secclass, u32 *socksid)
4568 if (tsec->sockcreate_sid > SECSID_NULL) {
4569 *socksid = tsec->sockcreate_sid;
4573 return security_transition_sid(&selinux_state, tsec->sid, tsec->sid,
4574 secclass, NULL, socksid);
4577 static int sock_has_perm(struct sock *sk, u32 perms)
4579 struct sk_security_struct *sksec = sk->sk_security;
4580 struct common_audit_data ad;
4581 struct lsm_network_audit net = {0,};
4583 if (sksec->sid == SECINITSID_KERNEL)
4586 ad.type = LSM_AUDIT_DATA_NET;
4590 return avc_has_perm(&selinux_state,
4591 current_sid(), sksec->sid, sksec->sclass, perms,
4595 static int selinux_socket_create(int family, int type,
4596 int protocol, int kern)
4598 const struct task_security_struct *tsec = selinux_cred(current_cred());
4606 secclass = socket_type_to_security_class(family, type, protocol);
4607 rc = socket_sockcreate_sid(tsec, secclass, &newsid);
4611 return avc_has_perm(&selinux_state,
4612 tsec->sid, newsid, secclass, SOCKET__CREATE, NULL);
4615 static int selinux_socket_post_create(struct socket *sock, int family,
4616 int type, int protocol, int kern)
4618 const struct task_security_struct *tsec = selinux_cred(current_cred());
4619 struct inode_security_struct *isec = inode_security_novalidate(SOCK_INODE(sock));
4620 struct sk_security_struct *sksec;
4621 u16 sclass = socket_type_to_security_class(family, type, protocol);
4622 u32 sid = SECINITSID_KERNEL;
4626 err = socket_sockcreate_sid(tsec, sclass, &sid);
4631 isec->sclass = sclass;
4633 isec->initialized = LABEL_INITIALIZED;
4636 sksec = sock->sk->sk_security;
4637 sksec->sclass = sclass;
4639 /* Allows detection of the first association on this socket */
4640 if (sksec->sclass == SECCLASS_SCTP_SOCKET)
4641 sksec->sctp_assoc_state = SCTP_ASSOC_UNSET;
4643 err = selinux_netlbl_socket_post_create(sock->sk, family);
4649 static int selinux_socket_socketpair(struct socket *socka,
4650 struct socket *sockb)
4652 struct sk_security_struct *sksec_a = socka->sk->sk_security;
4653 struct sk_security_struct *sksec_b = sockb->sk->sk_security;
4655 sksec_a->peer_sid = sksec_b->sid;
4656 sksec_b->peer_sid = sksec_a->sid;
4661 /* Range of port numbers used to automatically bind.
4662 Need to determine whether we should perform a name_bind
4663 permission check between the socket and the port number. */
4665 static int selinux_socket_bind(struct socket *sock, struct sockaddr *address, int addrlen)
4667 struct sock *sk = sock->sk;
4668 struct sk_security_struct *sksec = sk->sk_security;
4672 err = sock_has_perm(sk, SOCKET__BIND);
4676 /* If PF_INET or PF_INET6, check name_bind permission for the port. */
4677 family = sk->sk_family;
4678 if (family == PF_INET || family == PF_INET6) {
4680 struct common_audit_data ad;
4681 struct lsm_network_audit net = {0,};
4682 struct sockaddr_in *addr4 = NULL;
4683 struct sockaddr_in6 *addr6 = NULL;
4685 unsigned short snum;
4689 * sctp_bindx(3) calls via selinux_sctp_bind_connect()
4690 * that validates multiple binding addresses. Because of this
4691 * need to check address->sa_family as it is possible to have
4692 * sk->sk_family = PF_INET6 with addr->sa_family = AF_INET.
4694 if (addrlen < offsetofend(struct sockaddr, sa_family))
4696 family_sa = address->sa_family;
4697 switch (family_sa) {
4700 if (addrlen < sizeof(struct sockaddr_in))
4702 addr4 = (struct sockaddr_in *)address;
4703 if (family_sa == AF_UNSPEC) {
4704 /* see __inet_bind(), we only want to allow
4705 * AF_UNSPEC if the address is INADDR_ANY
4707 if (addr4->sin_addr.s_addr != htonl(INADDR_ANY))
4709 family_sa = AF_INET;
4711 snum = ntohs(addr4->sin_port);
4712 addrp = (char *)&addr4->sin_addr.s_addr;
4715 if (addrlen < SIN6_LEN_RFC2133)
4717 addr6 = (struct sockaddr_in6 *)address;
4718 snum = ntohs(addr6->sin6_port);
4719 addrp = (char *)&addr6->sin6_addr.s6_addr;
4725 ad.type = LSM_AUDIT_DATA_NET;
4727 ad.u.net->sport = htons(snum);
4728 ad.u.net->family = family_sa;
4733 inet_get_local_port_range(sock_net(sk), &low, &high);
4735 if (inet_port_requires_bind_service(sock_net(sk), snum) ||
4736 snum < low || snum > high) {
4737 err = sel_netport_sid(sk->sk_protocol,
4741 err = avc_has_perm(&selinux_state,
4744 SOCKET__NAME_BIND, &ad);
4750 switch (sksec->sclass) {
4751 case SECCLASS_TCP_SOCKET:
4752 node_perm = TCP_SOCKET__NODE_BIND;
4755 case SECCLASS_UDP_SOCKET:
4756 node_perm = UDP_SOCKET__NODE_BIND;
4759 case SECCLASS_DCCP_SOCKET:
4760 node_perm = DCCP_SOCKET__NODE_BIND;
4763 case SECCLASS_SCTP_SOCKET:
4764 node_perm = SCTP_SOCKET__NODE_BIND;
4768 node_perm = RAWIP_SOCKET__NODE_BIND;
4772 err = sel_netnode_sid(addrp, family_sa, &sid);
4776 if (family_sa == AF_INET)
4777 ad.u.net->v4info.saddr = addr4->sin_addr.s_addr;
4779 ad.u.net->v6info.saddr = addr6->sin6_addr;
4781 err = avc_has_perm(&selinux_state,
4783 sksec->sclass, node_perm, &ad);
4790 /* Note that SCTP services expect -EINVAL, others -EAFNOSUPPORT. */
4791 if (sksec->sclass == SECCLASS_SCTP_SOCKET)
4793 return -EAFNOSUPPORT;
4796 /* This supports connect(2) and SCTP connect services such as sctp_connectx(3)
4797 * and sctp_sendmsg(3) as described in Documentation/security/SCTP.rst
4799 static int selinux_socket_connect_helper(struct socket *sock,
4800 struct sockaddr *address, int addrlen)
4802 struct sock *sk = sock->sk;
4803 struct sk_security_struct *sksec = sk->sk_security;
4806 err = sock_has_perm(sk, SOCKET__CONNECT);
4809 if (addrlen < offsetofend(struct sockaddr, sa_family))
4812 /* connect(AF_UNSPEC) has special handling, as it is a documented
4813 * way to disconnect the socket
4815 if (address->sa_family == AF_UNSPEC)
4819 * If a TCP, DCCP or SCTP socket, check name_connect permission
4822 if (sksec->sclass == SECCLASS_TCP_SOCKET ||
4823 sksec->sclass == SECCLASS_DCCP_SOCKET ||
4824 sksec->sclass == SECCLASS_SCTP_SOCKET) {
4825 struct common_audit_data ad;
4826 struct lsm_network_audit net = {0,};
4827 struct sockaddr_in *addr4 = NULL;
4828 struct sockaddr_in6 *addr6 = NULL;
4829 unsigned short snum;
4832 /* sctp_connectx(3) calls via selinux_sctp_bind_connect()
4833 * that validates multiple connect addresses. Because of this
4834 * need to check address->sa_family as it is possible to have
4835 * sk->sk_family = PF_INET6 with addr->sa_family = AF_INET.
4837 switch (address->sa_family) {
4839 addr4 = (struct sockaddr_in *)address;
4840 if (addrlen < sizeof(struct sockaddr_in))
4842 snum = ntohs(addr4->sin_port);
4845 addr6 = (struct sockaddr_in6 *)address;
4846 if (addrlen < SIN6_LEN_RFC2133)
4848 snum = ntohs(addr6->sin6_port);
4851 /* Note that SCTP services expect -EINVAL, whereas
4852 * others expect -EAFNOSUPPORT.
4854 if (sksec->sclass == SECCLASS_SCTP_SOCKET)
4857 return -EAFNOSUPPORT;
4860 err = sel_netport_sid(sk->sk_protocol, snum, &sid);
4864 switch (sksec->sclass) {
4865 case SECCLASS_TCP_SOCKET:
4866 perm = TCP_SOCKET__NAME_CONNECT;
4868 case SECCLASS_DCCP_SOCKET:
4869 perm = DCCP_SOCKET__NAME_CONNECT;
4871 case SECCLASS_SCTP_SOCKET:
4872 perm = SCTP_SOCKET__NAME_CONNECT;
4876 ad.type = LSM_AUDIT_DATA_NET;
4878 ad.u.net->dport = htons(snum);
4879 ad.u.net->family = address->sa_family;
4880 err = avc_has_perm(&selinux_state,
4881 sksec->sid, sid, sksec->sclass, perm, &ad);
4889 /* Supports connect(2), see comments in selinux_socket_connect_helper() */
4890 static int selinux_socket_connect(struct socket *sock,
4891 struct sockaddr *address, int addrlen)
4894 struct sock *sk = sock->sk;
4896 err = selinux_socket_connect_helper(sock, address, addrlen);
4900 return selinux_netlbl_socket_connect(sk, address);
4903 static int selinux_socket_listen(struct socket *sock, int backlog)
4905 return sock_has_perm(sock->sk, SOCKET__LISTEN);
4908 static int selinux_socket_accept(struct socket *sock, struct socket *newsock)
4911 struct inode_security_struct *isec;
4912 struct inode_security_struct *newisec;
4916 err = sock_has_perm(sock->sk, SOCKET__ACCEPT);
4920 isec = inode_security_novalidate(SOCK_INODE(sock));
4921 spin_lock(&isec->lock);
4922 sclass = isec->sclass;
4924 spin_unlock(&isec->lock);
4926 newisec = inode_security_novalidate(SOCK_INODE(newsock));
4927 newisec->sclass = sclass;
4929 newisec->initialized = LABEL_INITIALIZED;
4934 static int selinux_socket_sendmsg(struct socket *sock, struct msghdr *msg,
4937 return sock_has_perm(sock->sk, SOCKET__WRITE);
4940 static int selinux_socket_recvmsg(struct socket *sock, struct msghdr *msg,
4941 int size, int flags)
4943 return sock_has_perm(sock->sk, SOCKET__READ);
4946 static int selinux_socket_getsockname(struct socket *sock)
4948 return sock_has_perm(sock->sk, SOCKET__GETATTR);
4951 static int selinux_socket_getpeername(struct socket *sock)
4953 return sock_has_perm(sock->sk, SOCKET__GETATTR);
4956 static int selinux_socket_setsockopt(struct socket *sock, int level, int optname)
4960 err = sock_has_perm(sock->sk, SOCKET__SETOPT);
4964 return selinux_netlbl_socket_setsockopt(sock, level, optname);
4967 static int selinux_socket_getsockopt(struct socket *sock, int level,
4970 return sock_has_perm(sock->sk, SOCKET__GETOPT);
4973 static int selinux_socket_shutdown(struct socket *sock, int how)
4975 return sock_has_perm(sock->sk, SOCKET__SHUTDOWN);
4978 static int selinux_socket_unix_stream_connect(struct sock *sock,
4982 struct sk_security_struct *sksec_sock = sock->sk_security;
4983 struct sk_security_struct *sksec_other = other->sk_security;
4984 struct sk_security_struct *sksec_new = newsk->sk_security;
4985 struct common_audit_data ad;
4986 struct lsm_network_audit net = {0,};
4989 ad.type = LSM_AUDIT_DATA_NET;
4991 ad.u.net->sk = other;
4993 err = avc_has_perm(&selinux_state,
4994 sksec_sock->sid, sksec_other->sid,
4995 sksec_other->sclass,
4996 UNIX_STREAM_SOCKET__CONNECTTO, &ad);
5000 /* server child socket */
5001 sksec_new->peer_sid = sksec_sock->sid;
5002 err = security_sid_mls_copy(&selinux_state, sksec_other->sid,
5003 sksec_sock->sid, &sksec_new->sid);
5007 /* connecting socket */
5008 sksec_sock->peer_sid = sksec_new->sid;
5013 static int selinux_socket_unix_may_send(struct socket *sock,
5014 struct socket *other)
5016 struct sk_security_struct *ssec = sock->sk->sk_security;
5017 struct sk_security_struct *osec = other->sk->sk_security;
5018 struct common_audit_data ad;
5019 struct lsm_network_audit net = {0,};
5021 ad.type = LSM_AUDIT_DATA_NET;
5023 ad.u.net->sk = other->sk;
5025 return avc_has_perm(&selinux_state,
5026 ssec->sid, osec->sid, osec->sclass, SOCKET__SENDTO,
5030 static int selinux_inet_sys_rcv_skb(struct net *ns, int ifindex,
5031 char *addrp, u16 family, u32 peer_sid,
5032 struct common_audit_data *ad)
5038 err = sel_netif_sid(ns, ifindex, &if_sid);
5041 err = avc_has_perm(&selinux_state,
5043 SECCLASS_NETIF, NETIF__INGRESS, ad);
5047 err = sel_netnode_sid(addrp, family, &node_sid);
5050 return avc_has_perm(&selinux_state,
5052 SECCLASS_NODE, NODE__RECVFROM, ad);
5055 static int selinux_sock_rcv_skb_compat(struct sock *sk, struct sk_buff *skb,
5059 struct sk_security_struct *sksec = sk->sk_security;
5060 u32 sk_sid = sksec->sid;
5061 struct common_audit_data ad;
5062 struct lsm_network_audit net = {0,};
5065 ad.type = LSM_AUDIT_DATA_NET;
5067 ad.u.net->netif = skb->skb_iif;
5068 ad.u.net->family = family;
5069 err = selinux_parse_skb(skb, &ad, &addrp, 1, NULL);
5073 if (selinux_secmark_enabled()) {
5074 err = avc_has_perm(&selinux_state,
5075 sk_sid, skb->secmark, SECCLASS_PACKET,
5081 err = selinux_netlbl_sock_rcv_skb(sksec, skb, family, &ad);
5084 err = selinux_xfrm_sock_rcv_skb(sksec->sid, skb, &ad);
5089 static int selinux_socket_sock_rcv_skb(struct sock *sk, struct sk_buff *skb)
5092 struct sk_security_struct *sksec = sk->sk_security;
5093 u16 family = sk->sk_family;
5094 u32 sk_sid = sksec->sid;
5095 struct common_audit_data ad;
5096 struct lsm_network_audit net = {0,};
5101 if (family != PF_INET && family != PF_INET6)
5104 /* Handle mapped IPv4 packets arriving via IPv6 sockets */
5105 if (family == PF_INET6 && skb->protocol == htons(ETH_P_IP))
5108 /* If any sort of compatibility mode is enabled then handoff processing
5109 * to the selinux_sock_rcv_skb_compat() function to deal with the
5110 * special handling. We do this in an attempt to keep this function
5111 * as fast and as clean as possible. */
5112 if (!selinux_policycap_netpeer())
5113 return selinux_sock_rcv_skb_compat(sk, skb, family);
5115 secmark_active = selinux_secmark_enabled();
5116 peerlbl_active = selinux_peerlbl_enabled();
5117 if (!secmark_active && !peerlbl_active)
5120 ad.type = LSM_AUDIT_DATA_NET;
5122 ad.u.net->netif = skb->skb_iif;
5123 ad.u.net->family = family;
5124 err = selinux_parse_skb(skb, &ad, &addrp, 1, NULL);
5128 if (peerlbl_active) {
5131 err = selinux_skb_peerlbl_sid(skb, family, &peer_sid);
5134 err = selinux_inet_sys_rcv_skb(sock_net(sk), skb->skb_iif,
5135 addrp, family, peer_sid, &ad);
5137 selinux_netlbl_err(skb, family, err, 0);
5140 err = avc_has_perm(&selinux_state,
5141 sk_sid, peer_sid, SECCLASS_PEER,
5144 selinux_netlbl_err(skb, family, err, 0);
5149 if (secmark_active) {
5150 err = avc_has_perm(&selinux_state,
5151 sk_sid, skb->secmark, SECCLASS_PACKET,
5160 static int selinux_socket_getpeersec_stream(struct socket *sock, char __user *optval,
5161 int __user *optlen, unsigned len)
5166 struct sk_security_struct *sksec = sock->sk->sk_security;
5167 u32 peer_sid = SECSID_NULL;
5169 if (sksec->sclass == SECCLASS_UNIX_STREAM_SOCKET ||
5170 sksec->sclass == SECCLASS_TCP_SOCKET ||
5171 sksec->sclass == SECCLASS_SCTP_SOCKET)
5172 peer_sid = sksec->peer_sid;
5173 if (peer_sid == SECSID_NULL)
5174 return -ENOPROTOOPT;
5176 err = security_sid_to_context(&selinux_state, peer_sid, &scontext,
5181 if (scontext_len > len) {
5186 if (copy_to_user(optval, scontext, scontext_len))
5190 if (put_user(scontext_len, optlen))
5196 static int selinux_socket_getpeersec_dgram(struct socket *sock, struct sk_buff *skb, u32 *secid)
5198 u32 peer_secid = SECSID_NULL;
5200 struct inode_security_struct *isec;
5202 if (skb && skb->protocol == htons(ETH_P_IP))
5204 else if (skb && skb->protocol == htons(ETH_P_IPV6))
5207 family = sock->sk->sk_family;
5211 if (sock && family == PF_UNIX) {
5212 isec = inode_security_novalidate(SOCK_INODE(sock));
5213 peer_secid = isec->sid;
5215 selinux_skb_peerlbl_sid(skb, family, &peer_secid);
5218 *secid = peer_secid;
5219 if (peer_secid == SECSID_NULL)
5224 static int selinux_sk_alloc_security(struct sock *sk, int family, gfp_t priority)
5226 struct sk_security_struct *sksec;
5228 sksec = kzalloc(sizeof(*sksec), priority);
5232 sksec->peer_sid = SECINITSID_UNLABELED;
5233 sksec->sid = SECINITSID_UNLABELED;
5234 sksec->sclass = SECCLASS_SOCKET;
5235 selinux_netlbl_sk_security_reset(sksec);
5236 sk->sk_security = sksec;
5241 static void selinux_sk_free_security(struct sock *sk)
5243 struct sk_security_struct *sksec = sk->sk_security;
5245 sk->sk_security = NULL;
5246 selinux_netlbl_sk_security_free(sksec);
5250 static void selinux_sk_clone_security(const struct sock *sk, struct sock *newsk)
5252 struct sk_security_struct *sksec = sk->sk_security;
5253 struct sk_security_struct *newsksec = newsk->sk_security;
5255 newsksec->sid = sksec->sid;
5256 newsksec->peer_sid = sksec->peer_sid;
5257 newsksec->sclass = sksec->sclass;
5259 selinux_netlbl_sk_security_reset(newsksec);
5262 static void selinux_sk_getsecid(struct sock *sk, u32 *secid)
5265 *secid = SECINITSID_ANY_SOCKET;
5267 struct sk_security_struct *sksec = sk->sk_security;
5269 *secid = sksec->sid;
5273 static void selinux_sock_graft(struct sock *sk, struct socket *parent)
5275 struct inode_security_struct *isec =
5276 inode_security_novalidate(SOCK_INODE(parent));
5277 struct sk_security_struct *sksec = sk->sk_security;
5279 if (sk->sk_family == PF_INET || sk->sk_family == PF_INET6 ||
5280 sk->sk_family == PF_UNIX)
5281 isec->sid = sksec->sid;
5282 sksec->sclass = isec->sclass;
5285 /* Called whenever SCTP receives an INIT chunk. This happens when an incoming
5286 * connect(2), sctp_connectx(3) or sctp_sendmsg(3) (with no association
5289 static int selinux_sctp_assoc_request(struct sctp_endpoint *ep,
5290 struct sk_buff *skb)
5292 struct sk_security_struct *sksec = ep->base.sk->sk_security;
5293 struct common_audit_data ad;
5294 struct lsm_network_audit net = {0,};
5296 u32 peer_sid = SECINITSID_UNLABELED;
5300 if (!selinux_policycap_extsockclass())
5303 peerlbl_active = selinux_peerlbl_enabled();
5305 if (peerlbl_active) {
5306 /* This will return peer_sid = SECSID_NULL if there are
5307 * no peer labels, see security_net_peersid_resolve().
5309 err = selinux_skb_peerlbl_sid(skb, ep->base.sk->sk_family,
5314 if (peer_sid == SECSID_NULL)
5315 peer_sid = SECINITSID_UNLABELED;
5318 if (sksec->sctp_assoc_state == SCTP_ASSOC_UNSET) {
5319 sksec->sctp_assoc_state = SCTP_ASSOC_SET;
5321 /* Here as first association on socket. As the peer SID
5322 * was allowed by peer recv (and the netif/node checks),
5323 * then it is approved by policy and used as the primary
5324 * peer SID for getpeercon(3).
5326 sksec->peer_sid = peer_sid;
5327 } else if (sksec->peer_sid != peer_sid) {
5328 /* Other association peer SIDs are checked to enforce
5329 * consistency among the peer SIDs.
5331 ad.type = LSM_AUDIT_DATA_NET;
5333 ad.u.net->sk = ep->base.sk;
5334 err = avc_has_perm(&selinux_state,
5335 sksec->peer_sid, peer_sid, sksec->sclass,
5336 SCTP_SOCKET__ASSOCIATION, &ad);
5341 /* Compute the MLS component for the connection and store
5342 * the information in ep. This will be used by SCTP TCP type
5343 * sockets and peeled off connections as they cause a new
5344 * socket to be generated. selinux_sctp_sk_clone() will then
5345 * plug this into the new socket.
5347 err = selinux_conn_sid(sksec->sid, peer_sid, &conn_sid);
5351 ep->secid = conn_sid;
5352 ep->peer_secid = peer_sid;
5354 /* Set any NetLabel labels including CIPSO/CALIPSO options. */
5355 return selinux_netlbl_sctp_assoc_request(ep, skb);
5358 /* Check if sctp IPv4/IPv6 addresses are valid for binding or connecting
5359 * based on their @optname.
5361 static int selinux_sctp_bind_connect(struct sock *sk, int optname,
5362 struct sockaddr *address,
5365 int len, err = 0, walk_size = 0;
5367 struct sockaddr *addr;
5368 struct socket *sock;
5370 if (!selinux_policycap_extsockclass())
5373 /* Process one or more addresses that may be IPv4 or IPv6 */
5374 sock = sk->sk_socket;
5377 while (walk_size < addrlen) {
5378 if (walk_size + sizeof(sa_family_t) > addrlen)
5382 switch (addr->sa_family) {
5385 len = sizeof(struct sockaddr_in);
5388 len = sizeof(struct sockaddr_in6);
5394 if (walk_size + len > addrlen)
5400 case SCTP_PRIMARY_ADDR:
5401 case SCTP_SET_PEER_PRIMARY_ADDR:
5402 case SCTP_SOCKOPT_BINDX_ADD:
5403 err = selinux_socket_bind(sock, addr, len);
5405 /* Connect checks */
5406 case SCTP_SOCKOPT_CONNECTX:
5407 case SCTP_PARAM_SET_PRIMARY:
5408 case SCTP_PARAM_ADD_IP:
5409 case SCTP_SENDMSG_CONNECT:
5410 err = selinux_socket_connect_helper(sock, addr, len);
5414 /* As selinux_sctp_bind_connect() is called by the
5415 * SCTP protocol layer, the socket is already locked,
5416 * therefore selinux_netlbl_socket_connect_locked()
5417 * is called here. The situations handled are:
5418 * sctp_connectx(3), sctp_sendmsg(3), sendmsg(2),
5419 * whenever a new IP address is added or when a new
5420 * primary address is selected.
5421 * Note that an SCTP connect(2) call happens before
5422 * the SCTP protocol layer and is handled via
5423 * selinux_socket_connect().
5425 err = selinux_netlbl_socket_connect_locked(sk, addr);
5439 /* Called whenever a new socket is created by accept(2) or sctp_peeloff(3). */
5440 static void selinux_sctp_sk_clone(struct sctp_endpoint *ep, struct sock *sk,
5443 struct sk_security_struct *sksec = sk->sk_security;
5444 struct sk_security_struct *newsksec = newsk->sk_security;
5446 /* If policy does not support SECCLASS_SCTP_SOCKET then call
5447 * the non-sctp clone version.
5449 if (!selinux_policycap_extsockclass())
5450 return selinux_sk_clone_security(sk, newsk);
5452 newsksec->sid = ep->secid;
5453 newsksec->peer_sid = ep->peer_secid;
5454 newsksec->sclass = sksec->sclass;
5455 selinux_netlbl_sctp_sk_clone(sk, newsk);
5458 static int selinux_inet_conn_request(const struct sock *sk, struct sk_buff *skb,
5459 struct request_sock *req)
5461 struct sk_security_struct *sksec = sk->sk_security;
5463 u16 family = req->rsk_ops->family;
5467 err = selinux_skb_peerlbl_sid(skb, family, &peersid);
5470 err = selinux_conn_sid(sksec->sid, peersid, &connsid);
5473 req->secid = connsid;
5474 req->peer_secid = peersid;
5476 return selinux_netlbl_inet_conn_request(req, family);
5479 static void selinux_inet_csk_clone(struct sock *newsk,
5480 const struct request_sock *req)
5482 struct sk_security_struct *newsksec = newsk->sk_security;
5484 newsksec->sid = req->secid;
5485 newsksec->peer_sid = req->peer_secid;
5486 /* NOTE: Ideally, we should also get the isec->sid for the
5487 new socket in sync, but we don't have the isec available yet.
5488 So we will wait until sock_graft to do it, by which
5489 time it will have been created and available. */
5491 /* We don't need to take any sort of lock here as we are the only
5492 * thread with access to newsksec */
5493 selinux_netlbl_inet_csk_clone(newsk, req->rsk_ops->family);
5496 static void selinux_inet_conn_established(struct sock *sk, struct sk_buff *skb)
5498 u16 family = sk->sk_family;
5499 struct sk_security_struct *sksec = sk->sk_security;
5501 /* handle mapped IPv4 packets arriving via IPv6 sockets */
5502 if (family == PF_INET6 && skb->protocol == htons(ETH_P_IP))
5505 selinux_skb_peerlbl_sid(skb, family, &sksec->peer_sid);
5508 static int selinux_secmark_relabel_packet(u32 sid)
5510 const struct task_security_struct *__tsec;
5513 __tsec = selinux_cred(current_cred());
5516 return avc_has_perm(&selinux_state,
5517 tsid, sid, SECCLASS_PACKET, PACKET__RELABELTO,
5521 static void selinux_secmark_refcount_inc(void)
5523 atomic_inc(&selinux_secmark_refcount);
5526 static void selinux_secmark_refcount_dec(void)
5528 atomic_dec(&selinux_secmark_refcount);
5531 static void selinux_req_classify_flow(const struct request_sock *req,
5532 struct flowi_common *flic)
5534 flic->flowic_secid = req->secid;
5537 static int selinux_tun_dev_alloc_security(void **security)
5539 struct tun_security_struct *tunsec;
5541 tunsec = kzalloc(sizeof(*tunsec), GFP_KERNEL);
5544 tunsec->sid = current_sid();
5550 static void selinux_tun_dev_free_security(void *security)
5555 static int selinux_tun_dev_create(void)
5557 u32 sid = current_sid();
5559 /* we aren't taking into account the "sockcreate" SID since the socket
5560 * that is being created here is not a socket in the traditional sense,
5561 * instead it is a private sock, accessible only to the kernel, and
5562 * representing a wide range of network traffic spanning multiple
5563 * connections unlike traditional sockets - check the TUN driver to
5564 * get a better understanding of why this socket is special */
5566 return avc_has_perm(&selinux_state,
5567 sid, sid, SECCLASS_TUN_SOCKET, TUN_SOCKET__CREATE,
5571 static int selinux_tun_dev_attach_queue(void *security)
5573 struct tun_security_struct *tunsec = security;
5575 return avc_has_perm(&selinux_state,
5576 current_sid(), tunsec->sid, SECCLASS_TUN_SOCKET,
5577 TUN_SOCKET__ATTACH_QUEUE, NULL);
5580 static int selinux_tun_dev_attach(struct sock *sk, void *security)
5582 struct tun_security_struct *tunsec = security;
5583 struct sk_security_struct *sksec = sk->sk_security;
5585 /* we don't currently perform any NetLabel based labeling here and it
5586 * isn't clear that we would want to do so anyway; while we could apply
5587 * labeling without the support of the TUN user the resulting labeled
5588 * traffic from the other end of the connection would almost certainly
5589 * cause confusion to the TUN user that had no idea network labeling
5590 * protocols were being used */
5592 sksec->sid = tunsec->sid;
5593 sksec->sclass = SECCLASS_TUN_SOCKET;
5598 static int selinux_tun_dev_open(void *security)
5600 struct tun_security_struct *tunsec = security;
5601 u32 sid = current_sid();
5604 err = avc_has_perm(&selinux_state,
5605 sid, tunsec->sid, SECCLASS_TUN_SOCKET,
5606 TUN_SOCKET__RELABELFROM, NULL);
5609 err = avc_has_perm(&selinux_state,
5610 sid, sid, SECCLASS_TUN_SOCKET,
5611 TUN_SOCKET__RELABELTO, NULL);
5619 #ifdef CONFIG_NETFILTER
5621 static unsigned int selinux_ip_forward(struct sk_buff *skb,
5622 const struct net_device *indev,
5628 struct common_audit_data ad;
5629 struct lsm_network_audit net = {0,};
5634 if (!selinux_policycap_netpeer())
5637 secmark_active = selinux_secmark_enabled();
5638 netlbl_active = netlbl_enabled();
5639 peerlbl_active = selinux_peerlbl_enabled();
5640 if (!secmark_active && !peerlbl_active)
5643 if (selinux_skb_peerlbl_sid(skb, family, &peer_sid) != 0)
5646 ad.type = LSM_AUDIT_DATA_NET;
5648 ad.u.net->netif = indev->ifindex;
5649 ad.u.net->family = family;
5650 if (selinux_parse_skb(skb, &ad, &addrp, 1, NULL) != 0)
5653 if (peerlbl_active) {
5654 err = selinux_inet_sys_rcv_skb(dev_net(indev), indev->ifindex,
5655 addrp, family, peer_sid, &ad);
5657 selinux_netlbl_err(skb, family, err, 1);
5663 if (avc_has_perm(&selinux_state,
5664 peer_sid, skb->secmark,
5665 SECCLASS_PACKET, PACKET__FORWARD_IN, &ad))
5669 /* we do this in the FORWARD path and not the POST_ROUTING
5670 * path because we want to make sure we apply the necessary
5671 * labeling before IPsec is applied so we can leverage AH
5673 if (selinux_netlbl_skbuff_setsid(skb, family, peer_sid) != 0)
5679 static unsigned int selinux_ipv4_forward(void *priv,
5680 struct sk_buff *skb,
5681 const struct nf_hook_state *state)
5683 return selinux_ip_forward(skb, state->in, PF_INET);
5686 #if IS_ENABLED(CONFIG_IPV6)
5687 static unsigned int selinux_ipv6_forward(void *priv,
5688 struct sk_buff *skb,
5689 const struct nf_hook_state *state)
5691 return selinux_ip_forward(skb, state->in, PF_INET6);
5695 static unsigned int selinux_ip_output(struct sk_buff *skb,
5701 if (!netlbl_enabled())
5704 /* we do this in the LOCAL_OUT path and not the POST_ROUTING path
5705 * because we want to make sure we apply the necessary labeling
5706 * before IPsec is applied so we can leverage AH protection */
5709 struct sk_security_struct *sksec;
5711 if (sk_listener(sk))
5712 /* if the socket is the listening state then this
5713 * packet is a SYN-ACK packet which means it needs to
5714 * be labeled based on the connection/request_sock and
5715 * not the parent socket. unfortunately, we can't
5716 * lookup the request_sock yet as it isn't queued on
5717 * the parent socket until after the SYN-ACK is sent.
5718 * the "solution" is to simply pass the packet as-is
5719 * as any IP option based labeling should be copied
5720 * from the initial connection request (in the IP
5721 * layer). it is far from ideal, but until we get a
5722 * security label in the packet itself this is the
5723 * best we can do. */
5726 /* standard practice, label using the parent socket */
5727 sksec = sk->sk_security;
5730 sid = SECINITSID_KERNEL;
5731 if (selinux_netlbl_skbuff_setsid(skb, family, sid) != 0)
5737 static unsigned int selinux_ipv4_output(void *priv,
5738 struct sk_buff *skb,
5739 const struct nf_hook_state *state)
5741 return selinux_ip_output(skb, PF_INET);
5744 #if IS_ENABLED(CONFIG_IPV6)
5745 static unsigned int selinux_ipv6_output(void *priv,
5746 struct sk_buff *skb,
5747 const struct nf_hook_state *state)
5749 return selinux_ip_output(skb, PF_INET6);
5753 static unsigned int selinux_ip_postroute_compat(struct sk_buff *skb,
5757 struct sock *sk = skb_to_full_sk(skb);
5758 struct sk_security_struct *sksec;
5759 struct common_audit_data ad;
5760 struct lsm_network_audit net = {0,};
5766 sksec = sk->sk_security;
5768 ad.type = LSM_AUDIT_DATA_NET;
5770 ad.u.net->netif = ifindex;
5771 ad.u.net->family = family;
5772 if (selinux_parse_skb(skb, &ad, &addrp, 0, &proto))
5775 if (selinux_secmark_enabled())
5776 if (avc_has_perm(&selinux_state,
5777 sksec->sid, skb->secmark,
5778 SECCLASS_PACKET, PACKET__SEND, &ad))
5779 return NF_DROP_ERR(-ECONNREFUSED);
5781 if (selinux_xfrm_postroute_last(sksec->sid, skb, &ad, proto))
5782 return NF_DROP_ERR(-ECONNREFUSED);
5787 static unsigned int selinux_ip_postroute(struct sk_buff *skb,
5788 const struct net_device *outdev,
5793 int ifindex = outdev->ifindex;
5795 struct common_audit_data ad;
5796 struct lsm_network_audit net = {0,};
5801 /* If any sort of compatibility mode is enabled then handoff processing
5802 * to the selinux_ip_postroute_compat() function to deal with the
5803 * special handling. We do this in an attempt to keep this function
5804 * as fast and as clean as possible. */
5805 if (!selinux_policycap_netpeer())
5806 return selinux_ip_postroute_compat(skb, ifindex, family);
5808 secmark_active = selinux_secmark_enabled();
5809 peerlbl_active = selinux_peerlbl_enabled();
5810 if (!secmark_active && !peerlbl_active)
5813 sk = skb_to_full_sk(skb);
5816 /* If skb->dst->xfrm is non-NULL then the packet is undergoing an IPsec
5817 * packet transformation so allow the packet to pass without any checks
5818 * since we'll have another chance to perform access control checks
5819 * when the packet is on it's final way out.
5820 * NOTE: there appear to be some IPv6 multicast cases where skb->dst
5821 * is NULL, in this case go ahead and apply access control.
5822 * NOTE: if this is a local socket (skb->sk != NULL) that is in the
5823 * TCP listening state we cannot wait until the XFRM processing
5824 * is done as we will miss out on the SA label if we do;
5825 * unfortunately, this means more work, but it is only once per
5827 if (skb_dst(skb) != NULL && skb_dst(skb)->xfrm != NULL &&
5828 !(sk && sk_listener(sk)))
5833 /* Without an associated socket the packet is either coming
5834 * from the kernel or it is being forwarded; check the packet
5835 * to determine which and if the packet is being forwarded
5836 * query the packet directly to determine the security label. */
5838 secmark_perm = PACKET__FORWARD_OUT;
5839 if (selinux_skb_peerlbl_sid(skb, family, &peer_sid))
5842 secmark_perm = PACKET__SEND;
5843 peer_sid = SECINITSID_KERNEL;
5845 } else if (sk_listener(sk)) {
5846 /* Locally generated packet but the associated socket is in the
5847 * listening state which means this is a SYN-ACK packet. In
5848 * this particular case the correct security label is assigned
5849 * to the connection/request_sock but unfortunately we can't
5850 * query the request_sock as it isn't queued on the parent
5851 * socket until after the SYN-ACK packet is sent; the only
5852 * viable choice is to regenerate the label like we do in
5853 * selinux_inet_conn_request(). See also selinux_ip_output()
5854 * for similar problems. */
5856 struct sk_security_struct *sksec;
5858 sksec = sk->sk_security;
5859 if (selinux_skb_peerlbl_sid(skb, family, &skb_sid))
5861 /* At this point, if the returned skb peerlbl is SECSID_NULL
5862 * and the packet has been through at least one XFRM
5863 * transformation then we must be dealing with the "final"
5864 * form of labeled IPsec packet; since we've already applied
5865 * all of our access controls on this packet we can safely
5866 * pass the packet. */
5867 if (skb_sid == SECSID_NULL) {
5870 if (IPCB(skb)->flags & IPSKB_XFRM_TRANSFORMED)
5874 if (IP6CB(skb)->flags & IP6SKB_XFRM_TRANSFORMED)
5878 return NF_DROP_ERR(-ECONNREFUSED);
5881 if (selinux_conn_sid(sksec->sid, skb_sid, &peer_sid))
5883 secmark_perm = PACKET__SEND;
5885 /* Locally generated packet, fetch the security label from the
5886 * associated socket. */
5887 struct sk_security_struct *sksec = sk->sk_security;
5888 peer_sid = sksec->sid;
5889 secmark_perm = PACKET__SEND;
5892 ad.type = LSM_AUDIT_DATA_NET;
5894 ad.u.net->netif = ifindex;
5895 ad.u.net->family = family;
5896 if (selinux_parse_skb(skb, &ad, &addrp, 0, NULL))
5900 if (avc_has_perm(&selinux_state,
5901 peer_sid, skb->secmark,
5902 SECCLASS_PACKET, secmark_perm, &ad))
5903 return NF_DROP_ERR(-ECONNREFUSED);
5905 if (peerlbl_active) {
5909 if (sel_netif_sid(dev_net(outdev), ifindex, &if_sid))
5911 if (avc_has_perm(&selinux_state,
5913 SECCLASS_NETIF, NETIF__EGRESS, &ad))
5914 return NF_DROP_ERR(-ECONNREFUSED);
5916 if (sel_netnode_sid(addrp, family, &node_sid))
5918 if (avc_has_perm(&selinux_state,
5920 SECCLASS_NODE, NODE__SENDTO, &ad))
5921 return NF_DROP_ERR(-ECONNREFUSED);
5927 static unsigned int selinux_ipv4_postroute(void *priv,
5928 struct sk_buff *skb,
5929 const struct nf_hook_state *state)
5931 return selinux_ip_postroute(skb, state->out, PF_INET);
5934 #if IS_ENABLED(CONFIG_IPV6)
5935 static unsigned int selinux_ipv6_postroute(void *priv,
5936 struct sk_buff *skb,
5937 const struct nf_hook_state *state)
5939 return selinux_ip_postroute(skb, state->out, PF_INET6);
5943 #endif /* CONFIG_NETFILTER */
5945 static int selinux_netlink_send(struct sock *sk, struct sk_buff *skb)
5948 unsigned int msg_len;
5949 unsigned int data_len = skb->len;
5950 unsigned char *data = skb->data;
5951 struct nlmsghdr *nlh;
5952 struct sk_security_struct *sksec = sk->sk_security;
5953 u16 sclass = sksec->sclass;
5956 while (data_len >= nlmsg_total_size(0)) {
5957 nlh = (struct nlmsghdr *)data;
5959 /* NOTE: the nlmsg_len field isn't reliably set by some netlink
5960 * users which means we can't reject skb's with bogus
5961 * length fields; our solution is to follow what
5962 * netlink_rcv_skb() does and simply skip processing at
5963 * messages with length fields that are clearly junk
5965 if (nlh->nlmsg_len < NLMSG_HDRLEN || nlh->nlmsg_len > data_len)
5968 rc = selinux_nlmsg_lookup(sclass, nlh->nlmsg_type, &perm);
5970 rc = sock_has_perm(sk, perm);
5973 } else if (rc == -EINVAL) {
5974 /* -EINVAL is a missing msg/perm mapping */
5975 pr_warn_ratelimited("SELinux: unrecognized netlink"
5976 " message: protocol=%hu nlmsg_type=%hu sclass=%s"
5977 " pid=%d comm=%s\n",
5978 sk->sk_protocol, nlh->nlmsg_type,
5979 secclass_map[sclass - 1].name,
5980 task_pid_nr(current), current->comm);
5981 if (enforcing_enabled(&selinux_state) &&
5982 !security_get_allow_unknown(&selinux_state))
5985 } else if (rc == -ENOENT) {
5986 /* -ENOENT is a missing socket/class mapping, ignore */
5992 /* move to the next message after applying netlink padding */
5993 msg_len = NLMSG_ALIGN(nlh->nlmsg_len);
5994 if (msg_len >= data_len)
5996 data_len -= msg_len;
6003 static void ipc_init_security(struct ipc_security_struct *isec, u16 sclass)
6005 isec->sclass = sclass;
6006 isec->sid = current_sid();
6009 static int ipc_has_perm(struct kern_ipc_perm *ipc_perms,
6012 struct ipc_security_struct *isec;
6013 struct common_audit_data ad;
6014 u32 sid = current_sid();
6016 isec = selinux_ipc(ipc_perms);
6018 ad.type = LSM_AUDIT_DATA_IPC;
6019 ad.u.ipc_id = ipc_perms->key;
6021 return avc_has_perm(&selinux_state,
6022 sid, isec->sid, isec->sclass, perms, &ad);
6025 static int selinux_msg_msg_alloc_security(struct msg_msg *msg)
6027 struct msg_security_struct *msec;
6029 msec = selinux_msg_msg(msg);
6030 msec->sid = SECINITSID_UNLABELED;
6035 /* message queue security operations */
6036 static int selinux_msg_queue_alloc_security(struct kern_ipc_perm *msq)
6038 struct ipc_security_struct *isec;
6039 struct common_audit_data ad;
6040 u32 sid = current_sid();
6043 isec = selinux_ipc(msq);
6044 ipc_init_security(isec, SECCLASS_MSGQ);
6046 ad.type = LSM_AUDIT_DATA_IPC;
6047 ad.u.ipc_id = msq->key;
6049 rc = avc_has_perm(&selinux_state,
6050 sid, isec->sid, SECCLASS_MSGQ,
6055 static int selinux_msg_queue_associate(struct kern_ipc_perm *msq, int msqflg)
6057 struct ipc_security_struct *isec;
6058 struct common_audit_data ad;
6059 u32 sid = current_sid();
6061 isec = selinux_ipc(msq);
6063 ad.type = LSM_AUDIT_DATA_IPC;
6064 ad.u.ipc_id = msq->key;
6066 return avc_has_perm(&selinux_state,
6067 sid, isec->sid, SECCLASS_MSGQ,
6068 MSGQ__ASSOCIATE, &ad);
6071 static int selinux_msg_queue_msgctl(struct kern_ipc_perm *msq, int cmd)
6079 /* No specific object, just general system-wide information. */
6080 return avc_has_perm(&selinux_state,
6081 current_sid(), SECINITSID_KERNEL,
6082 SECCLASS_SYSTEM, SYSTEM__IPC_INFO, NULL);
6086 perms = MSGQ__GETATTR | MSGQ__ASSOCIATE;
6089 perms = MSGQ__SETATTR;
6092 perms = MSGQ__DESTROY;
6098 err = ipc_has_perm(msq, perms);
6102 static int selinux_msg_queue_msgsnd(struct kern_ipc_perm *msq, struct msg_msg *msg, int msqflg)
6104 struct ipc_security_struct *isec;
6105 struct msg_security_struct *msec;
6106 struct common_audit_data ad;
6107 u32 sid = current_sid();
6110 isec = selinux_ipc(msq);
6111 msec = selinux_msg_msg(msg);
6114 * First time through, need to assign label to the message
6116 if (msec->sid == SECINITSID_UNLABELED) {
6118 * Compute new sid based on current process and
6119 * message queue this message will be stored in
6121 rc = security_transition_sid(&selinux_state, sid, isec->sid,
6122 SECCLASS_MSG, NULL, &msec->sid);
6127 ad.type = LSM_AUDIT_DATA_IPC;
6128 ad.u.ipc_id = msq->key;
6130 /* Can this process write to the queue? */
6131 rc = avc_has_perm(&selinux_state,
6132 sid, isec->sid, SECCLASS_MSGQ,
6135 /* Can this process send the message */
6136 rc = avc_has_perm(&selinux_state,
6137 sid, msec->sid, SECCLASS_MSG,
6140 /* Can the message be put in the queue? */
6141 rc = avc_has_perm(&selinux_state,
6142 msec->sid, isec->sid, SECCLASS_MSGQ,
6143 MSGQ__ENQUEUE, &ad);
6148 static int selinux_msg_queue_msgrcv(struct kern_ipc_perm *msq, struct msg_msg *msg,
6149 struct task_struct *target,
6150 long type, int mode)
6152 struct ipc_security_struct *isec;
6153 struct msg_security_struct *msec;
6154 struct common_audit_data ad;
6155 u32 sid = task_sid(target);
6158 isec = selinux_ipc(msq);
6159 msec = selinux_msg_msg(msg);
6161 ad.type = LSM_AUDIT_DATA_IPC;
6162 ad.u.ipc_id = msq->key;
6164 rc = avc_has_perm(&selinux_state,
6166 SECCLASS_MSGQ, MSGQ__READ, &ad);
6168 rc = avc_has_perm(&selinux_state,
6170 SECCLASS_MSG, MSG__RECEIVE, &ad);
6174 /* Shared Memory security operations */
6175 static int selinux_shm_alloc_security(struct kern_ipc_perm *shp)
6177 struct ipc_security_struct *isec;
6178 struct common_audit_data ad;
6179 u32 sid = current_sid();
6182 isec = selinux_ipc(shp);
6183 ipc_init_security(isec, SECCLASS_SHM);
6185 ad.type = LSM_AUDIT_DATA_IPC;
6186 ad.u.ipc_id = shp->key;
6188 rc = avc_has_perm(&selinux_state,
6189 sid, isec->sid, SECCLASS_SHM,
6194 static int selinux_shm_associate(struct kern_ipc_perm *shp, int shmflg)
6196 struct ipc_security_struct *isec;
6197 struct common_audit_data ad;
6198 u32 sid = current_sid();
6200 isec = selinux_ipc(shp);
6202 ad.type = LSM_AUDIT_DATA_IPC;
6203 ad.u.ipc_id = shp->key;
6205 return avc_has_perm(&selinux_state,
6206 sid, isec->sid, SECCLASS_SHM,
6207 SHM__ASSOCIATE, &ad);
6210 /* Note, at this point, shp is locked down */
6211 static int selinux_shm_shmctl(struct kern_ipc_perm *shp, int cmd)
6219 /* No specific object, just general system-wide information. */
6220 return avc_has_perm(&selinux_state,
6221 current_sid(), SECINITSID_KERNEL,
6222 SECCLASS_SYSTEM, SYSTEM__IPC_INFO, NULL);
6226 perms = SHM__GETATTR | SHM__ASSOCIATE;
6229 perms = SHM__SETATTR;
6236 perms = SHM__DESTROY;
6242 err = ipc_has_perm(shp, perms);
6246 static int selinux_shm_shmat(struct kern_ipc_perm *shp,
6247 char __user *shmaddr, int shmflg)
6251 if (shmflg & SHM_RDONLY)
6254 perms = SHM__READ | SHM__WRITE;
6256 return ipc_has_perm(shp, perms);
6259 /* Semaphore security operations */
6260 static int selinux_sem_alloc_security(struct kern_ipc_perm *sma)
6262 struct ipc_security_struct *isec;
6263 struct common_audit_data ad;
6264 u32 sid = current_sid();
6267 isec = selinux_ipc(sma);
6268 ipc_init_security(isec, SECCLASS_SEM);
6270 ad.type = LSM_AUDIT_DATA_IPC;
6271 ad.u.ipc_id = sma->key;
6273 rc = avc_has_perm(&selinux_state,
6274 sid, isec->sid, SECCLASS_SEM,
6279 static int selinux_sem_associate(struct kern_ipc_perm *sma, int semflg)
6281 struct ipc_security_struct *isec;
6282 struct common_audit_data ad;
6283 u32 sid = current_sid();
6285 isec = selinux_ipc(sma);
6287 ad.type = LSM_AUDIT_DATA_IPC;
6288 ad.u.ipc_id = sma->key;
6290 return avc_has_perm(&selinux_state,
6291 sid, isec->sid, SECCLASS_SEM,
6292 SEM__ASSOCIATE, &ad);
6295 /* Note, at this point, sma is locked down */
6296 static int selinux_sem_semctl(struct kern_ipc_perm *sma, int cmd)
6304 /* No specific object, just general system-wide information. */
6305 return avc_has_perm(&selinux_state,
6306 current_sid(), SECINITSID_KERNEL,
6307 SECCLASS_SYSTEM, SYSTEM__IPC_INFO, NULL);
6311 perms = SEM__GETATTR;
6322 perms = SEM__DESTROY;
6325 perms = SEM__SETATTR;
6330 perms = SEM__GETATTR | SEM__ASSOCIATE;
6336 err = ipc_has_perm(sma, perms);
6340 static int selinux_sem_semop(struct kern_ipc_perm *sma,
6341 struct sembuf *sops, unsigned nsops, int alter)
6346 perms = SEM__READ | SEM__WRITE;
6350 return ipc_has_perm(sma, perms);
6353 static int selinux_ipc_permission(struct kern_ipc_perm *ipcp, short flag)
6359 av |= IPC__UNIX_READ;
6361 av |= IPC__UNIX_WRITE;
6366 return ipc_has_perm(ipcp, av);
6369 static void selinux_ipc_getsecid(struct kern_ipc_perm *ipcp, u32 *secid)
6371 struct ipc_security_struct *isec = selinux_ipc(ipcp);
6375 static void selinux_d_instantiate(struct dentry *dentry, struct inode *inode)
6378 inode_doinit_with_dentry(inode, dentry);
6381 static int selinux_getprocattr(struct task_struct *p,
6382 char *name, char **value)
6384 const struct task_security_struct *__tsec;
6390 __tsec = selinux_cred(__task_cred(p));
6393 error = avc_has_perm(&selinux_state,
6394 current_sid(), __tsec->sid,
6395 SECCLASS_PROCESS, PROCESS__GETATTR, NULL);
6400 if (!strcmp(name, "current"))
6402 else if (!strcmp(name, "prev"))
6404 else if (!strcmp(name, "exec"))
6405 sid = __tsec->exec_sid;
6406 else if (!strcmp(name, "fscreate"))
6407 sid = __tsec->create_sid;
6408 else if (!strcmp(name, "keycreate"))
6409 sid = __tsec->keycreate_sid;
6410 else if (!strcmp(name, "sockcreate"))
6411 sid = __tsec->sockcreate_sid;
6421 error = security_sid_to_context(&selinux_state, sid, value, &len);
6431 static int selinux_setprocattr(const char *name, void *value, size_t size)
6433 struct task_security_struct *tsec;
6435 u32 mysid = current_sid(), sid = 0, ptsid;
6440 * Basic control over ability to set these attributes at all.
6442 if (!strcmp(name, "exec"))
6443 error = avc_has_perm(&selinux_state,
6444 mysid, mysid, SECCLASS_PROCESS,
6445 PROCESS__SETEXEC, NULL);
6446 else if (!strcmp(name, "fscreate"))
6447 error = avc_has_perm(&selinux_state,
6448 mysid, mysid, SECCLASS_PROCESS,
6449 PROCESS__SETFSCREATE, NULL);
6450 else if (!strcmp(name, "keycreate"))
6451 error = avc_has_perm(&selinux_state,
6452 mysid, mysid, SECCLASS_PROCESS,
6453 PROCESS__SETKEYCREATE, NULL);
6454 else if (!strcmp(name, "sockcreate"))
6455 error = avc_has_perm(&selinux_state,
6456 mysid, mysid, SECCLASS_PROCESS,
6457 PROCESS__SETSOCKCREATE, NULL);
6458 else if (!strcmp(name, "current"))
6459 error = avc_has_perm(&selinux_state,
6460 mysid, mysid, SECCLASS_PROCESS,
6461 PROCESS__SETCURRENT, NULL);
6467 /* Obtain a SID for the context, if one was specified. */
6468 if (size && str[0] && str[0] != '\n') {
6469 if (str[size-1] == '\n') {
6473 error = security_context_to_sid(&selinux_state, value, size,
6475 if (error == -EINVAL && !strcmp(name, "fscreate")) {
6476 if (!has_cap_mac_admin(true)) {
6477 struct audit_buffer *ab;
6480 /* We strip a nul only if it is at the end, otherwise the
6481 * context contains a nul and we should audit that */
6482 if (str[size - 1] == '\0')
6483 audit_size = size - 1;
6486 ab = audit_log_start(audit_context(),
6489 audit_log_format(ab, "op=fscreate invalid_context=");
6490 audit_log_n_untrustedstring(ab, value, audit_size);
6495 error = security_context_to_sid_force(
6503 new = prepare_creds();
6507 /* Permission checking based on the specified context is
6508 performed during the actual operation (execve,
6509 open/mkdir/...), when we know the full context of the
6510 operation. See selinux_bprm_creds_for_exec for the execve
6511 checks and may_create for the file creation checks. The
6512 operation will then fail if the context is not permitted. */
6513 tsec = selinux_cred(new);
6514 if (!strcmp(name, "exec")) {
6515 tsec->exec_sid = sid;
6516 } else if (!strcmp(name, "fscreate")) {
6517 tsec->create_sid = sid;
6518 } else if (!strcmp(name, "keycreate")) {
6520 error = avc_has_perm(&selinux_state, mysid, sid,
6521 SECCLASS_KEY, KEY__CREATE, NULL);
6525 tsec->keycreate_sid = sid;
6526 } else if (!strcmp(name, "sockcreate")) {
6527 tsec->sockcreate_sid = sid;
6528 } else if (!strcmp(name, "current")) {
6533 /* Only allow single threaded processes to change context */
6535 if (!current_is_single_threaded()) {
6536 error = security_bounded_transition(&selinux_state,
6542 /* Check permissions for the transition. */
6543 error = avc_has_perm(&selinux_state,
6544 tsec->sid, sid, SECCLASS_PROCESS,
6545 PROCESS__DYNTRANSITION, NULL);
6549 /* Check for ptracing, and update the task SID if ok.
6550 Otherwise, leave SID unchanged and fail. */
6551 ptsid = ptrace_parent_sid();
6553 error = avc_has_perm(&selinux_state,
6554 ptsid, sid, SECCLASS_PROCESS,
6555 PROCESS__PTRACE, NULL);
6574 static int selinux_ismaclabel(const char *name)
6576 return (strcmp(name, XATTR_SELINUX_SUFFIX) == 0);
6579 static int selinux_secid_to_secctx(u32 secid, char **secdata, u32 *seclen)
6581 return security_sid_to_context(&selinux_state, secid,
6585 static int selinux_secctx_to_secid(const char *secdata, u32 seclen, u32 *secid)
6587 return security_context_to_sid(&selinux_state, secdata, seclen,
6591 static void selinux_release_secctx(char *secdata, u32 seclen)
6596 static void selinux_inode_invalidate_secctx(struct inode *inode)
6598 struct inode_security_struct *isec = selinux_inode(inode);
6600 spin_lock(&isec->lock);
6601 isec->initialized = LABEL_INVALID;
6602 spin_unlock(&isec->lock);
6606 * called with inode->i_mutex locked
6608 static int selinux_inode_notifysecctx(struct inode *inode, void *ctx, u32 ctxlen)
6610 int rc = selinux_inode_setsecurity(inode, XATTR_SELINUX_SUFFIX,
6612 /* Do not return error when suppressing label (SBLABEL_MNT not set). */
6613 return rc == -EOPNOTSUPP ? 0 : rc;
6617 * called with inode->i_mutex locked
6619 static int selinux_inode_setsecctx(struct dentry *dentry, void *ctx, u32 ctxlen)
6621 return __vfs_setxattr_noperm(&init_user_ns, dentry, XATTR_NAME_SELINUX,
6625 static int selinux_inode_getsecctx(struct inode *inode, void **ctx, u32 *ctxlen)
6628 len = selinux_inode_getsecurity(&init_user_ns, inode,
6629 XATTR_SELINUX_SUFFIX, ctx, true);
6637 static int selinux_key_alloc(struct key *k, const struct cred *cred,
6638 unsigned long flags)
6640 const struct task_security_struct *tsec;
6641 struct key_security_struct *ksec;
6643 ksec = kzalloc(sizeof(struct key_security_struct), GFP_KERNEL);
6647 tsec = selinux_cred(cred);
6648 if (tsec->keycreate_sid)
6649 ksec->sid = tsec->keycreate_sid;
6651 ksec->sid = tsec->sid;
6657 static void selinux_key_free(struct key *k)
6659 struct key_security_struct *ksec = k->security;
6665 static int selinux_key_permission(key_ref_t key_ref,
6666 const struct cred *cred,
6667 enum key_need_perm need_perm)
6670 struct key_security_struct *ksec;
6673 switch (need_perm) {
6680 case KEY_NEED_WRITE:
6683 case KEY_NEED_SEARCH:
6689 case KEY_NEED_SETATTR:
6690 perm = KEY__SETATTR;
6692 case KEY_NEED_UNLINK:
6693 case KEY_SYSADMIN_OVERRIDE:
6694 case KEY_AUTHTOKEN_OVERRIDE:
6695 case KEY_DEFER_PERM_CHECK:
6703 sid = cred_sid(cred);
6704 key = key_ref_to_ptr(key_ref);
6705 ksec = key->security;
6707 return avc_has_perm(&selinux_state,
6708 sid, ksec->sid, SECCLASS_KEY, perm, NULL);
6711 static int selinux_key_getsecurity(struct key *key, char **_buffer)
6713 struct key_security_struct *ksec = key->security;
6714 char *context = NULL;
6718 rc = security_sid_to_context(&selinux_state, ksec->sid,
6726 #ifdef CONFIG_KEY_NOTIFICATIONS
6727 static int selinux_watch_key(struct key *key)
6729 struct key_security_struct *ksec = key->security;
6730 u32 sid = current_sid();
6732 return avc_has_perm(&selinux_state,
6733 sid, ksec->sid, SECCLASS_KEY, KEY__VIEW, NULL);
6738 #ifdef CONFIG_SECURITY_INFINIBAND
6739 static int selinux_ib_pkey_access(void *ib_sec, u64 subnet_prefix, u16 pkey_val)
6741 struct common_audit_data ad;
6744 struct ib_security_struct *sec = ib_sec;
6745 struct lsm_ibpkey_audit ibpkey;
6747 err = sel_ib_pkey_sid(subnet_prefix, pkey_val, &sid);
6751 ad.type = LSM_AUDIT_DATA_IBPKEY;
6752 ibpkey.subnet_prefix = subnet_prefix;
6753 ibpkey.pkey = pkey_val;
6754 ad.u.ibpkey = &ibpkey;
6755 return avc_has_perm(&selinux_state,
6757 SECCLASS_INFINIBAND_PKEY,
6758 INFINIBAND_PKEY__ACCESS, &ad);
6761 static int selinux_ib_endport_manage_subnet(void *ib_sec, const char *dev_name,
6764 struct common_audit_data ad;
6767 struct ib_security_struct *sec = ib_sec;
6768 struct lsm_ibendport_audit ibendport;
6770 err = security_ib_endport_sid(&selinux_state, dev_name, port_num,
6776 ad.type = LSM_AUDIT_DATA_IBENDPORT;
6777 strncpy(ibendport.dev_name, dev_name, sizeof(ibendport.dev_name));
6778 ibendport.port = port_num;
6779 ad.u.ibendport = &ibendport;
6780 return avc_has_perm(&selinux_state,
6782 SECCLASS_INFINIBAND_ENDPORT,
6783 INFINIBAND_ENDPORT__MANAGE_SUBNET, &ad);
6786 static int selinux_ib_alloc_security(void **ib_sec)
6788 struct ib_security_struct *sec;
6790 sec = kzalloc(sizeof(*sec), GFP_KERNEL);
6793 sec->sid = current_sid();
6799 static void selinux_ib_free_security(void *ib_sec)
6805 #ifdef CONFIG_BPF_SYSCALL
6806 static int selinux_bpf(int cmd, union bpf_attr *attr,
6809 u32 sid = current_sid();
6813 case BPF_MAP_CREATE:
6814 ret = avc_has_perm(&selinux_state,
6815 sid, sid, SECCLASS_BPF, BPF__MAP_CREATE,
6819 ret = avc_has_perm(&selinux_state,
6820 sid, sid, SECCLASS_BPF, BPF__PROG_LOAD,
6831 static u32 bpf_map_fmode_to_av(fmode_t fmode)
6835 if (fmode & FMODE_READ)
6836 av |= BPF__MAP_READ;
6837 if (fmode & FMODE_WRITE)
6838 av |= BPF__MAP_WRITE;
6842 /* This function will check the file pass through unix socket or binder to see
6843 * if it is a bpf related object. And apply correspinding checks on the bpf
6844 * object based on the type. The bpf maps and programs, not like other files and
6845 * socket, are using a shared anonymous inode inside the kernel as their inode.
6846 * So checking that inode cannot identify if the process have privilege to
6847 * access the bpf object and that's why we have to add this additional check in
6848 * selinux_file_receive and selinux_binder_transfer_files.
6850 static int bpf_fd_pass(struct file *file, u32 sid)
6852 struct bpf_security_struct *bpfsec;
6853 struct bpf_prog *prog;
6854 struct bpf_map *map;
6857 if (file->f_op == &bpf_map_fops) {
6858 map = file->private_data;
6859 bpfsec = map->security;
6860 ret = avc_has_perm(&selinux_state,
6861 sid, bpfsec->sid, SECCLASS_BPF,
6862 bpf_map_fmode_to_av(file->f_mode), NULL);
6865 } else if (file->f_op == &bpf_prog_fops) {
6866 prog = file->private_data;
6867 bpfsec = prog->aux->security;
6868 ret = avc_has_perm(&selinux_state,
6869 sid, bpfsec->sid, SECCLASS_BPF,
6870 BPF__PROG_RUN, NULL);
6877 static int selinux_bpf_map(struct bpf_map *map, fmode_t fmode)
6879 u32 sid = current_sid();
6880 struct bpf_security_struct *bpfsec;
6882 bpfsec = map->security;
6883 return avc_has_perm(&selinux_state,
6884 sid, bpfsec->sid, SECCLASS_BPF,
6885 bpf_map_fmode_to_av(fmode), NULL);
6888 static int selinux_bpf_prog(struct bpf_prog *prog)
6890 u32 sid = current_sid();
6891 struct bpf_security_struct *bpfsec;
6893 bpfsec = prog->aux->security;
6894 return avc_has_perm(&selinux_state,
6895 sid, bpfsec->sid, SECCLASS_BPF,
6896 BPF__PROG_RUN, NULL);
6899 static int selinux_bpf_map_alloc(struct bpf_map *map)
6901 struct bpf_security_struct *bpfsec;
6903 bpfsec = kzalloc(sizeof(*bpfsec), GFP_KERNEL);
6907 bpfsec->sid = current_sid();
6908 map->security = bpfsec;
6913 static void selinux_bpf_map_free(struct bpf_map *map)
6915 struct bpf_security_struct *bpfsec = map->security;
6917 map->security = NULL;
6921 static int selinux_bpf_prog_alloc(struct bpf_prog_aux *aux)
6923 struct bpf_security_struct *bpfsec;
6925 bpfsec = kzalloc(sizeof(*bpfsec), GFP_KERNEL);
6929 bpfsec->sid = current_sid();
6930 aux->security = bpfsec;
6935 static void selinux_bpf_prog_free(struct bpf_prog_aux *aux)
6937 struct bpf_security_struct *bpfsec = aux->security;
6939 aux->security = NULL;
6944 static int selinux_lockdown(enum lockdown_reason what)
6946 struct common_audit_data ad;
6947 u32 sid = current_sid();
6948 int invalid_reason = (what <= LOCKDOWN_NONE) ||
6949 (what == LOCKDOWN_INTEGRITY_MAX) ||
6950 (what >= LOCKDOWN_CONFIDENTIALITY_MAX);
6952 if (WARN(invalid_reason, "Invalid lockdown reason")) {
6953 audit_log(audit_context(),
6954 GFP_ATOMIC, AUDIT_SELINUX_ERR,
6955 "lockdown_reason=invalid");
6959 ad.type = LSM_AUDIT_DATA_LOCKDOWN;
6962 if (what <= LOCKDOWN_INTEGRITY_MAX)
6963 return avc_has_perm(&selinux_state,
6964 sid, sid, SECCLASS_LOCKDOWN,
6965 LOCKDOWN__INTEGRITY, &ad);
6967 return avc_has_perm(&selinux_state,
6968 sid, sid, SECCLASS_LOCKDOWN,
6969 LOCKDOWN__CONFIDENTIALITY, &ad);
6972 struct lsm_blob_sizes selinux_blob_sizes __lsm_ro_after_init = {
6973 .lbs_cred = sizeof(struct task_security_struct),
6974 .lbs_file = sizeof(struct file_security_struct),
6975 .lbs_inode = sizeof(struct inode_security_struct),
6976 .lbs_ipc = sizeof(struct ipc_security_struct),
6977 .lbs_msg_msg = sizeof(struct msg_security_struct),
6980 #ifdef CONFIG_PERF_EVENTS
6981 static int selinux_perf_event_open(struct perf_event_attr *attr, int type)
6983 u32 requested, sid = current_sid();
6985 if (type == PERF_SECURITY_OPEN)
6986 requested = PERF_EVENT__OPEN;
6987 else if (type == PERF_SECURITY_CPU)
6988 requested = PERF_EVENT__CPU;
6989 else if (type == PERF_SECURITY_KERNEL)
6990 requested = PERF_EVENT__KERNEL;
6991 else if (type == PERF_SECURITY_TRACEPOINT)
6992 requested = PERF_EVENT__TRACEPOINT;
6996 return avc_has_perm(&selinux_state, sid, sid, SECCLASS_PERF_EVENT,
7000 static int selinux_perf_event_alloc(struct perf_event *event)
7002 struct perf_event_security_struct *perfsec;
7004 perfsec = kzalloc(sizeof(*perfsec), GFP_KERNEL);
7008 perfsec->sid = current_sid();
7009 event->security = perfsec;
7014 static void selinux_perf_event_free(struct perf_event *event)
7016 struct perf_event_security_struct *perfsec = event->security;
7018 event->security = NULL;
7022 static int selinux_perf_event_read(struct perf_event *event)
7024 struct perf_event_security_struct *perfsec = event->security;
7025 u32 sid = current_sid();
7027 return avc_has_perm(&selinux_state, sid, perfsec->sid,
7028 SECCLASS_PERF_EVENT, PERF_EVENT__READ, NULL);
7031 static int selinux_perf_event_write(struct perf_event *event)
7033 struct perf_event_security_struct *perfsec = event->security;
7034 u32 sid = current_sid();
7036 return avc_has_perm(&selinux_state, sid, perfsec->sid,
7037 SECCLASS_PERF_EVENT, PERF_EVENT__WRITE, NULL);
7042 * IMPORTANT NOTE: When adding new hooks, please be careful to keep this order:
7043 * 1. any hooks that don't belong to (2.) or (3.) below,
7044 * 2. hooks that both access structures allocated by other hooks, and allocate
7045 * structures that can be later accessed by other hooks (mostly "cloning"
7047 * 3. hooks that only allocate structures that can be later accessed by other
7048 * hooks ("allocating" hooks).
7050 * Please follow block comment delimiters in the list to keep this order.
7052 * This ordering is needed for SELinux runtime disable to work at least somewhat
7053 * safely. Breaking the ordering rules above might lead to NULL pointer derefs
7054 * when disabling SELinux at runtime.
7056 static struct security_hook_list selinux_hooks[] __lsm_ro_after_init = {
7057 LSM_HOOK_INIT(binder_set_context_mgr, selinux_binder_set_context_mgr),
7058 LSM_HOOK_INIT(binder_transaction, selinux_binder_transaction),
7059 LSM_HOOK_INIT(binder_transfer_binder, selinux_binder_transfer_binder),
7060 LSM_HOOK_INIT(binder_transfer_file, selinux_binder_transfer_file),
7062 LSM_HOOK_INIT(ptrace_access_check, selinux_ptrace_access_check),
7063 LSM_HOOK_INIT(ptrace_traceme, selinux_ptrace_traceme),
7064 LSM_HOOK_INIT(capget, selinux_capget),
7065 LSM_HOOK_INIT(capset, selinux_capset),
7066 LSM_HOOK_INIT(capable, selinux_capable),
7067 LSM_HOOK_INIT(quotactl, selinux_quotactl),
7068 LSM_HOOK_INIT(quota_on, selinux_quota_on),
7069 LSM_HOOK_INIT(syslog, selinux_syslog),
7070 LSM_HOOK_INIT(vm_enough_memory, selinux_vm_enough_memory),
7072 LSM_HOOK_INIT(netlink_send, selinux_netlink_send),
7074 LSM_HOOK_INIT(bprm_creds_for_exec, selinux_bprm_creds_for_exec),
7075 LSM_HOOK_INIT(bprm_committing_creds, selinux_bprm_committing_creds),
7076 LSM_HOOK_INIT(bprm_committed_creds, selinux_bprm_committed_creds),
7078 LSM_HOOK_INIT(sb_free_security, selinux_sb_free_security),
7079 LSM_HOOK_INIT(sb_free_mnt_opts, selinux_free_mnt_opts),
7080 LSM_HOOK_INIT(sb_remount, selinux_sb_remount),
7081 LSM_HOOK_INIT(sb_kern_mount, selinux_sb_kern_mount),
7082 LSM_HOOK_INIT(sb_show_options, selinux_sb_show_options),
7083 LSM_HOOK_INIT(sb_statfs, selinux_sb_statfs),
7084 LSM_HOOK_INIT(sb_mount, selinux_mount),
7085 LSM_HOOK_INIT(sb_umount, selinux_umount),
7086 LSM_HOOK_INIT(sb_set_mnt_opts, selinux_set_mnt_opts),
7087 LSM_HOOK_INIT(sb_clone_mnt_opts, selinux_sb_clone_mnt_opts),
7089 LSM_HOOK_INIT(move_mount, selinux_move_mount),
7091 LSM_HOOK_INIT(dentry_init_security, selinux_dentry_init_security),
7092 LSM_HOOK_INIT(dentry_create_files_as, selinux_dentry_create_files_as),
7094 LSM_HOOK_INIT(inode_free_security, selinux_inode_free_security),
7095 LSM_HOOK_INIT(inode_init_security, selinux_inode_init_security),
7096 LSM_HOOK_INIT(inode_init_security_anon, selinux_inode_init_security_anon),
7097 LSM_HOOK_INIT(inode_create, selinux_inode_create),
7098 LSM_HOOK_INIT(inode_link, selinux_inode_link),
7099 LSM_HOOK_INIT(inode_unlink, selinux_inode_unlink),
7100 LSM_HOOK_INIT(inode_symlink, selinux_inode_symlink),
7101 LSM_HOOK_INIT(inode_mkdir, selinux_inode_mkdir),
7102 LSM_HOOK_INIT(inode_rmdir, selinux_inode_rmdir),
7103 LSM_HOOK_INIT(inode_mknod, selinux_inode_mknod),
7104 LSM_HOOK_INIT(inode_rename, selinux_inode_rename),
7105 LSM_HOOK_INIT(inode_readlink, selinux_inode_readlink),
7106 LSM_HOOK_INIT(inode_follow_link, selinux_inode_follow_link),
7107 LSM_HOOK_INIT(inode_permission, selinux_inode_permission),
7108 LSM_HOOK_INIT(inode_setattr, selinux_inode_setattr),
7109 LSM_HOOK_INIT(inode_getattr, selinux_inode_getattr),
7110 LSM_HOOK_INIT(inode_setxattr, selinux_inode_setxattr),
7111 LSM_HOOK_INIT(inode_post_setxattr, selinux_inode_post_setxattr),
7112 LSM_HOOK_INIT(inode_getxattr, selinux_inode_getxattr),
7113 LSM_HOOK_INIT(inode_listxattr, selinux_inode_listxattr),
7114 LSM_HOOK_INIT(inode_removexattr, selinux_inode_removexattr),
7115 LSM_HOOK_INIT(inode_getsecurity, selinux_inode_getsecurity),
7116 LSM_HOOK_INIT(inode_setsecurity, selinux_inode_setsecurity),
7117 LSM_HOOK_INIT(inode_listsecurity, selinux_inode_listsecurity),
7118 LSM_HOOK_INIT(inode_getsecid, selinux_inode_getsecid),
7119 LSM_HOOK_INIT(inode_copy_up, selinux_inode_copy_up),
7120 LSM_HOOK_INIT(inode_copy_up_xattr, selinux_inode_copy_up_xattr),
7121 LSM_HOOK_INIT(path_notify, selinux_path_notify),
7123 LSM_HOOK_INIT(kernfs_init_security, selinux_kernfs_init_security),
7125 LSM_HOOK_INIT(file_permission, selinux_file_permission),
7126 LSM_HOOK_INIT(file_alloc_security, selinux_file_alloc_security),
7127 LSM_HOOK_INIT(file_ioctl, selinux_file_ioctl),
7128 LSM_HOOK_INIT(mmap_file, selinux_mmap_file),
7129 LSM_HOOK_INIT(mmap_addr, selinux_mmap_addr),
7130 LSM_HOOK_INIT(file_mprotect, selinux_file_mprotect),
7131 LSM_HOOK_INIT(file_lock, selinux_file_lock),
7132 LSM_HOOK_INIT(file_fcntl, selinux_file_fcntl),
7133 LSM_HOOK_INIT(file_set_fowner, selinux_file_set_fowner),
7134 LSM_HOOK_INIT(file_send_sigiotask, selinux_file_send_sigiotask),
7135 LSM_HOOK_INIT(file_receive, selinux_file_receive),
7137 LSM_HOOK_INIT(file_open, selinux_file_open),
7139 LSM_HOOK_INIT(task_alloc, selinux_task_alloc),
7140 LSM_HOOK_INIT(cred_prepare, selinux_cred_prepare),
7141 LSM_HOOK_INIT(cred_transfer, selinux_cred_transfer),
7142 LSM_HOOK_INIT(cred_getsecid, selinux_cred_getsecid),
7143 LSM_HOOK_INIT(kernel_act_as, selinux_kernel_act_as),
7144 LSM_HOOK_INIT(kernel_create_files_as, selinux_kernel_create_files_as),
7145 LSM_HOOK_INIT(kernel_module_request, selinux_kernel_module_request),
7146 LSM_HOOK_INIT(kernel_load_data, selinux_kernel_load_data),
7147 LSM_HOOK_INIT(kernel_read_file, selinux_kernel_read_file),
7148 LSM_HOOK_INIT(task_setpgid, selinux_task_setpgid),
7149 LSM_HOOK_INIT(task_getpgid, selinux_task_getpgid),
7150 LSM_HOOK_INIT(task_getsid, selinux_task_getsid),
7151 LSM_HOOK_INIT(task_getsecid, selinux_task_getsecid),
7152 LSM_HOOK_INIT(task_setnice, selinux_task_setnice),
7153 LSM_HOOK_INIT(task_setioprio, selinux_task_setioprio),
7154 LSM_HOOK_INIT(task_getioprio, selinux_task_getioprio),
7155 LSM_HOOK_INIT(task_prlimit, selinux_task_prlimit),
7156 LSM_HOOK_INIT(task_setrlimit, selinux_task_setrlimit),
7157 LSM_HOOK_INIT(task_setscheduler, selinux_task_setscheduler),
7158 LSM_HOOK_INIT(task_getscheduler, selinux_task_getscheduler),
7159 LSM_HOOK_INIT(task_movememory, selinux_task_movememory),
7160 LSM_HOOK_INIT(task_kill, selinux_task_kill),
7161 LSM_HOOK_INIT(task_to_inode, selinux_task_to_inode),
7163 LSM_HOOK_INIT(ipc_permission, selinux_ipc_permission),
7164 LSM_HOOK_INIT(ipc_getsecid, selinux_ipc_getsecid),
7166 LSM_HOOK_INIT(msg_queue_associate, selinux_msg_queue_associate),
7167 LSM_HOOK_INIT(msg_queue_msgctl, selinux_msg_queue_msgctl),
7168 LSM_HOOK_INIT(msg_queue_msgsnd, selinux_msg_queue_msgsnd),
7169 LSM_HOOK_INIT(msg_queue_msgrcv, selinux_msg_queue_msgrcv),
7171 LSM_HOOK_INIT(shm_associate, selinux_shm_associate),
7172 LSM_HOOK_INIT(shm_shmctl, selinux_shm_shmctl),
7173 LSM_HOOK_INIT(shm_shmat, selinux_shm_shmat),
7175 LSM_HOOK_INIT(sem_associate, selinux_sem_associate),
7176 LSM_HOOK_INIT(sem_semctl, selinux_sem_semctl),
7177 LSM_HOOK_INIT(sem_semop, selinux_sem_semop),
7179 LSM_HOOK_INIT(d_instantiate, selinux_d_instantiate),
7181 LSM_HOOK_INIT(getprocattr, selinux_getprocattr),
7182 LSM_HOOK_INIT(setprocattr, selinux_setprocattr),
7184 LSM_HOOK_INIT(ismaclabel, selinux_ismaclabel),
7185 LSM_HOOK_INIT(secctx_to_secid, selinux_secctx_to_secid),
7186 LSM_HOOK_INIT(release_secctx, selinux_release_secctx),
7187 LSM_HOOK_INIT(inode_invalidate_secctx, selinux_inode_invalidate_secctx),
7188 LSM_HOOK_INIT(inode_notifysecctx, selinux_inode_notifysecctx),
7189 LSM_HOOK_INIT(inode_setsecctx, selinux_inode_setsecctx),
7191 LSM_HOOK_INIT(unix_stream_connect, selinux_socket_unix_stream_connect),
7192 LSM_HOOK_INIT(unix_may_send, selinux_socket_unix_may_send),
7194 LSM_HOOK_INIT(socket_create, selinux_socket_create),
7195 LSM_HOOK_INIT(socket_post_create, selinux_socket_post_create),
7196 LSM_HOOK_INIT(socket_socketpair, selinux_socket_socketpair),
7197 LSM_HOOK_INIT(socket_bind, selinux_socket_bind),
7198 LSM_HOOK_INIT(socket_connect, selinux_socket_connect),
7199 LSM_HOOK_INIT(socket_listen, selinux_socket_listen),
7200 LSM_HOOK_INIT(socket_accept, selinux_socket_accept),
7201 LSM_HOOK_INIT(socket_sendmsg, selinux_socket_sendmsg),
7202 LSM_HOOK_INIT(socket_recvmsg, selinux_socket_recvmsg),
7203 LSM_HOOK_INIT(socket_getsockname, selinux_socket_getsockname),
7204 LSM_HOOK_INIT(socket_getpeername, selinux_socket_getpeername),
7205 LSM_HOOK_INIT(socket_getsockopt, selinux_socket_getsockopt),
7206 LSM_HOOK_INIT(socket_setsockopt, selinux_socket_setsockopt),
7207 LSM_HOOK_INIT(socket_shutdown, selinux_socket_shutdown),
7208 LSM_HOOK_INIT(socket_sock_rcv_skb, selinux_socket_sock_rcv_skb),
7209 LSM_HOOK_INIT(socket_getpeersec_stream,
7210 selinux_socket_getpeersec_stream),
7211 LSM_HOOK_INIT(socket_getpeersec_dgram, selinux_socket_getpeersec_dgram),
7212 LSM_HOOK_INIT(sk_free_security, selinux_sk_free_security),
7213 LSM_HOOK_INIT(sk_clone_security, selinux_sk_clone_security),
7214 LSM_HOOK_INIT(sk_getsecid, selinux_sk_getsecid),
7215 LSM_HOOK_INIT(sock_graft, selinux_sock_graft),
7216 LSM_HOOK_INIT(sctp_assoc_request, selinux_sctp_assoc_request),
7217 LSM_HOOK_INIT(sctp_sk_clone, selinux_sctp_sk_clone),
7218 LSM_HOOK_INIT(sctp_bind_connect, selinux_sctp_bind_connect),
7219 LSM_HOOK_INIT(inet_conn_request, selinux_inet_conn_request),
7220 LSM_HOOK_INIT(inet_csk_clone, selinux_inet_csk_clone),
7221 LSM_HOOK_INIT(inet_conn_established, selinux_inet_conn_established),
7222 LSM_HOOK_INIT(secmark_relabel_packet, selinux_secmark_relabel_packet),
7223 LSM_HOOK_INIT(secmark_refcount_inc, selinux_secmark_refcount_inc),
7224 LSM_HOOK_INIT(secmark_refcount_dec, selinux_secmark_refcount_dec),
7225 LSM_HOOK_INIT(req_classify_flow, selinux_req_classify_flow),
7226 LSM_HOOK_INIT(tun_dev_free_security, selinux_tun_dev_free_security),
7227 LSM_HOOK_INIT(tun_dev_create, selinux_tun_dev_create),
7228 LSM_HOOK_INIT(tun_dev_attach_queue, selinux_tun_dev_attach_queue),
7229 LSM_HOOK_INIT(tun_dev_attach, selinux_tun_dev_attach),
7230 LSM_HOOK_INIT(tun_dev_open, selinux_tun_dev_open),
7231 #ifdef CONFIG_SECURITY_INFINIBAND
7232 LSM_HOOK_INIT(ib_pkey_access, selinux_ib_pkey_access),
7233 LSM_HOOK_INIT(ib_endport_manage_subnet,
7234 selinux_ib_endport_manage_subnet),
7235 LSM_HOOK_INIT(ib_free_security, selinux_ib_free_security),
7237 #ifdef CONFIG_SECURITY_NETWORK_XFRM
7238 LSM_HOOK_INIT(xfrm_policy_free_security, selinux_xfrm_policy_free),
7239 LSM_HOOK_INIT(xfrm_policy_delete_security, selinux_xfrm_policy_delete),
7240 LSM_HOOK_INIT(xfrm_state_free_security, selinux_xfrm_state_free),
7241 LSM_HOOK_INIT(xfrm_state_delete_security, selinux_xfrm_state_delete),
7242 LSM_HOOK_INIT(xfrm_policy_lookup, selinux_xfrm_policy_lookup),
7243 LSM_HOOK_INIT(xfrm_state_pol_flow_match,
7244 selinux_xfrm_state_pol_flow_match),
7245 LSM_HOOK_INIT(xfrm_decode_session, selinux_xfrm_decode_session),
7249 LSM_HOOK_INIT(key_free, selinux_key_free),
7250 LSM_HOOK_INIT(key_permission, selinux_key_permission),
7251 LSM_HOOK_INIT(key_getsecurity, selinux_key_getsecurity),
7252 #ifdef CONFIG_KEY_NOTIFICATIONS
7253 LSM_HOOK_INIT(watch_key, selinux_watch_key),
7258 LSM_HOOK_INIT(audit_rule_known, selinux_audit_rule_known),
7259 LSM_HOOK_INIT(audit_rule_match, selinux_audit_rule_match),
7260 LSM_HOOK_INIT(audit_rule_free, selinux_audit_rule_free),
7263 #ifdef CONFIG_BPF_SYSCALL
7264 LSM_HOOK_INIT(bpf, selinux_bpf),
7265 LSM_HOOK_INIT(bpf_map, selinux_bpf_map),
7266 LSM_HOOK_INIT(bpf_prog, selinux_bpf_prog),
7267 LSM_HOOK_INIT(bpf_map_free_security, selinux_bpf_map_free),
7268 LSM_HOOK_INIT(bpf_prog_free_security, selinux_bpf_prog_free),
7271 #ifdef CONFIG_PERF_EVENTS
7272 LSM_HOOK_INIT(perf_event_open, selinux_perf_event_open),
7273 LSM_HOOK_INIT(perf_event_free, selinux_perf_event_free),
7274 LSM_HOOK_INIT(perf_event_read, selinux_perf_event_read),
7275 LSM_HOOK_INIT(perf_event_write, selinux_perf_event_write),
7278 LSM_HOOK_INIT(locked_down, selinux_lockdown),
7281 * PUT "CLONING" (ACCESSING + ALLOCATING) HOOKS HERE
7283 LSM_HOOK_INIT(fs_context_dup, selinux_fs_context_dup),
7284 LSM_HOOK_INIT(fs_context_parse_param, selinux_fs_context_parse_param),
7285 LSM_HOOK_INIT(sb_eat_lsm_opts, selinux_sb_eat_lsm_opts),
7286 LSM_HOOK_INIT(sb_add_mnt_opt, selinux_add_mnt_opt),
7287 #ifdef CONFIG_SECURITY_NETWORK_XFRM
7288 LSM_HOOK_INIT(xfrm_policy_clone_security, selinux_xfrm_policy_clone),
7292 * PUT "ALLOCATING" HOOKS HERE
7294 LSM_HOOK_INIT(msg_msg_alloc_security, selinux_msg_msg_alloc_security),
7295 LSM_HOOK_INIT(msg_queue_alloc_security,
7296 selinux_msg_queue_alloc_security),
7297 LSM_HOOK_INIT(shm_alloc_security, selinux_shm_alloc_security),
7298 LSM_HOOK_INIT(sb_alloc_security, selinux_sb_alloc_security),
7299 LSM_HOOK_INIT(inode_alloc_security, selinux_inode_alloc_security),
7300 LSM_HOOK_INIT(sem_alloc_security, selinux_sem_alloc_security),
7301 LSM_HOOK_INIT(secid_to_secctx, selinux_secid_to_secctx),
7302 LSM_HOOK_INIT(inode_getsecctx, selinux_inode_getsecctx),
7303 LSM_HOOK_INIT(sk_alloc_security, selinux_sk_alloc_security),
7304 LSM_HOOK_INIT(tun_dev_alloc_security, selinux_tun_dev_alloc_security),
7305 #ifdef CONFIG_SECURITY_INFINIBAND
7306 LSM_HOOK_INIT(ib_alloc_security, selinux_ib_alloc_security),
7308 #ifdef CONFIG_SECURITY_NETWORK_XFRM
7309 LSM_HOOK_INIT(xfrm_policy_alloc_security, selinux_xfrm_policy_alloc),
7310 LSM_HOOK_INIT(xfrm_state_alloc, selinux_xfrm_state_alloc),
7311 LSM_HOOK_INIT(xfrm_state_alloc_acquire,
7312 selinux_xfrm_state_alloc_acquire),
7315 LSM_HOOK_INIT(key_alloc, selinux_key_alloc),
7318 LSM_HOOK_INIT(audit_rule_init, selinux_audit_rule_init),
7320 #ifdef CONFIG_BPF_SYSCALL
7321 LSM_HOOK_INIT(bpf_map_alloc_security, selinux_bpf_map_alloc),
7322 LSM_HOOK_INIT(bpf_prog_alloc_security, selinux_bpf_prog_alloc),
7324 #ifdef CONFIG_PERF_EVENTS
7325 LSM_HOOK_INIT(perf_event_alloc, selinux_perf_event_alloc),
7329 static __init int selinux_init(void)
7331 pr_info("SELinux: Initializing.\n");
7333 memset(&selinux_state, 0, sizeof(selinux_state));
7334 enforcing_set(&selinux_state, selinux_enforcing_boot);
7335 checkreqprot_set(&selinux_state, selinux_checkreqprot_boot);
7336 selinux_avc_init(&selinux_state.avc);
7337 mutex_init(&selinux_state.status_lock);
7338 mutex_init(&selinux_state.policy_mutex);
7340 /* Set the security state for the initial task. */
7341 cred_init_security();
7343 default_noexec = !(VM_DATA_DEFAULT_FLAGS & VM_EXEC);
7349 ebitmap_cache_init();
7351 hashtab_cache_init();
7353 security_add_hooks(selinux_hooks, ARRAY_SIZE(selinux_hooks), "selinux");
7355 if (avc_add_callback(selinux_netcache_avc_callback, AVC_CALLBACK_RESET))
7356 panic("SELinux: Unable to register AVC netcache callback\n");
7358 if (avc_add_callback(selinux_lsm_notifier_avc_callback, AVC_CALLBACK_RESET))
7359 panic("SELinux: Unable to register AVC LSM notifier callback\n");
7361 if (selinux_enforcing_boot)
7362 pr_debug("SELinux: Starting in enforcing mode\n");
7364 pr_debug("SELinux: Starting in permissive mode\n");
7366 fs_validate_description("selinux", selinux_fs_parameters);
7371 static void delayed_superblock_init(struct super_block *sb, void *unused)
7373 selinux_set_mnt_opts(sb, NULL, 0, NULL);
7376 void selinux_complete_init(void)
7378 pr_debug("SELinux: Completing initialization.\n");
7380 /* Set up any superblocks initialized prior to the policy load. */
7381 pr_debug("SELinux: Setting up existing superblocks.\n");
7382 iterate_supers(delayed_superblock_init, NULL);
7385 /* SELinux requires early initialization in order to label
7386 all processes and objects when they are created. */
7387 DEFINE_LSM(selinux) = {
7389 .flags = LSM_FLAG_LEGACY_MAJOR | LSM_FLAG_EXCLUSIVE,
7390 .enabled = &selinux_enabled_boot,
7391 .blobs = &selinux_blob_sizes,
7392 .init = selinux_init,
7395 #if defined(CONFIG_NETFILTER)
7397 static const struct nf_hook_ops selinux_nf_ops[] = {
7399 .hook = selinux_ipv4_postroute,
7401 .hooknum = NF_INET_POST_ROUTING,
7402 .priority = NF_IP_PRI_SELINUX_LAST,
7405 .hook = selinux_ipv4_forward,
7407 .hooknum = NF_INET_FORWARD,
7408 .priority = NF_IP_PRI_SELINUX_FIRST,
7411 .hook = selinux_ipv4_output,
7413 .hooknum = NF_INET_LOCAL_OUT,
7414 .priority = NF_IP_PRI_SELINUX_FIRST,
7416 #if IS_ENABLED(CONFIG_IPV6)
7418 .hook = selinux_ipv6_postroute,
7420 .hooknum = NF_INET_POST_ROUTING,
7421 .priority = NF_IP6_PRI_SELINUX_LAST,
7424 .hook = selinux_ipv6_forward,
7426 .hooknum = NF_INET_FORWARD,
7427 .priority = NF_IP6_PRI_SELINUX_FIRST,
7430 .hook = selinux_ipv6_output,
7432 .hooknum = NF_INET_LOCAL_OUT,
7433 .priority = NF_IP6_PRI_SELINUX_FIRST,
7438 static int __net_init selinux_nf_register(struct net *net)
7440 return nf_register_net_hooks(net, selinux_nf_ops,
7441 ARRAY_SIZE(selinux_nf_ops));
7444 static void __net_exit selinux_nf_unregister(struct net *net)
7446 nf_unregister_net_hooks(net, selinux_nf_ops,
7447 ARRAY_SIZE(selinux_nf_ops));
7450 static struct pernet_operations selinux_net_ops = {
7451 .init = selinux_nf_register,
7452 .exit = selinux_nf_unregister,
7455 static int __init selinux_nf_ip_init(void)
7459 if (!selinux_enabled_boot)
7462 pr_debug("SELinux: Registering netfilter hooks\n");
7464 err = register_pernet_subsys(&selinux_net_ops);
7466 panic("SELinux: register_pernet_subsys: error %d\n", err);
7470 __initcall(selinux_nf_ip_init);
7472 #ifdef CONFIG_SECURITY_SELINUX_DISABLE
7473 static void selinux_nf_ip_exit(void)
7475 pr_debug("SELinux: Unregistering netfilter hooks\n");
7477 unregister_pernet_subsys(&selinux_net_ops);
7481 #else /* CONFIG_NETFILTER */
7483 #ifdef CONFIG_SECURITY_SELINUX_DISABLE
7484 #define selinux_nf_ip_exit()
7487 #endif /* CONFIG_NETFILTER */
7489 #ifdef CONFIG_SECURITY_SELINUX_DISABLE
7490 int selinux_disable(struct selinux_state *state)
7492 if (selinux_initialized(state)) {
7493 /* Not permitted after initial policy load. */
7497 if (selinux_disabled(state)) {
7498 /* Only do this once. */
7502 selinux_mark_disabled(state);
7504 pr_info("SELinux: Disabled at runtime.\n");
7507 * Unregister netfilter hooks.
7508 * Must be done before security_delete_hooks() to avoid breaking
7511 selinux_nf_ip_exit();
7513 security_delete_hooks(selinux_hooks, ARRAY_SIZE(selinux_hooks));
7515 /* Try to destroy the avc node cache */
7518 /* Unregister selinuxfs. */