1 // SPDX-License-Identifier: GPL-2.0-only
3 * NSA Security-Enhanced Linux (SELinux) security module
5 * This file contains the SELinux hook function implementations.
7 * Authors: Stephen Smalley, <sds@tycho.nsa.gov>
8 * Chris Vance, <cvance@nai.com>
9 * Wayne Salamon, <wsalamon@nai.com>
10 * James Morris <jmorris@redhat.com>
12 * Copyright (C) 2001,2002 Networks Associates Technology, Inc.
13 * Copyright (C) 2003-2008 Red Hat, Inc., James Morris <jmorris@redhat.com>
14 * Eric Paris <eparis@redhat.com>
15 * Copyright (C) 2004-2005 Trusted Computer Solutions, Inc.
16 * <dgoeddel@trustedcs.com>
17 * Copyright (C) 2006, 2007, 2009 Hewlett-Packard Development Company, L.P.
18 * Paul Moore <paul@paul-moore.com>
19 * Copyright (C) 2007 Hitachi Software Engineering Co., Ltd.
20 * Yuichi Nakamura <ynakam@hitachisoft.jp>
21 * Copyright (C) 2016 Mellanox Technologies
24 #include <linux/init.h>
26 #include <linux/kernel.h>
27 #include <linux/kernel_read_file.h>
28 #include <linux/tracehook.h>
29 #include <linux/errno.h>
30 #include <linux/sched/signal.h>
31 #include <linux/sched/task.h>
32 #include <linux/lsm_hooks.h>
33 #include <linux/xattr.h>
34 #include <linux/capability.h>
35 #include <linux/unistd.h>
37 #include <linux/mman.h>
38 #include <linux/slab.h>
39 #include <linux/pagemap.h>
40 #include <linux/proc_fs.h>
41 #include <linux/swap.h>
42 #include <linux/spinlock.h>
43 #include <linux/syscalls.h>
44 #include <linux/dcache.h>
45 #include <linux/file.h>
46 #include <linux/fdtable.h>
47 #include <linux/namei.h>
48 #include <linux/mount.h>
49 #include <linux/fs_context.h>
50 #include <linux/fs_parser.h>
51 #include <linux/netfilter_ipv4.h>
52 #include <linux/netfilter_ipv6.h>
53 #include <linux/tty.h>
55 #include <net/ip.h> /* for local_port_range[] */
56 #include <net/tcp.h> /* struct or_callable used in sock_rcv_skb */
57 #include <net/inet_connection_sock.h>
58 #include <net/net_namespace.h>
59 #include <net/netlabel.h>
60 #include <linux/uaccess.h>
61 #include <asm/ioctls.h>
62 #include <linux/atomic.h>
63 #include <linux/bitops.h>
64 #include <linux/interrupt.h>
65 #include <linux/netdevice.h> /* for network interface checks */
66 #include <net/netlink.h>
67 #include <linux/tcp.h>
68 #include <linux/udp.h>
69 #include <linux/dccp.h>
70 #include <linux/sctp.h>
71 #include <net/sctp/structs.h>
72 #include <linux/quota.h>
73 #include <linux/un.h> /* for Unix socket types */
74 #include <net/af_unix.h> /* for Unix socket types */
75 #include <linux/parser.h>
76 #include <linux/nfs_mount.h>
78 #include <linux/hugetlb.h>
79 #include <linux/personality.h>
80 #include <linux/audit.h>
81 #include <linux/string.h>
82 #include <linux/mutex.h>
83 #include <linux/posix-timers.h>
84 #include <linux/syslog.h>
85 #include <linux/user_namespace.h>
86 #include <linux/export.h>
87 #include <linux/msg.h>
88 #include <linux/shm.h>
89 #include <linux/bpf.h>
90 #include <linux/kernfs.h>
91 #include <linux/stringhash.h> /* for hashlen_string() */
92 #include <uapi/linux/mount.h>
93 #include <linux/fsnotify.h>
94 #include <linux/fanotify.h>
103 #include "netlabel.h"
107 struct selinux_state selinux_state;
109 /* SECMARK reference count */
110 static atomic_t selinux_secmark_refcount = ATOMIC_INIT(0);
112 #ifdef CONFIG_SECURITY_SELINUX_DEVELOP
113 static int selinux_enforcing_boot __initdata;
115 static int __init enforcing_setup(char *str)
117 unsigned long enforcing;
118 if (!kstrtoul(str, 0, &enforcing))
119 selinux_enforcing_boot = enforcing ? 1 : 0;
122 __setup("enforcing=", enforcing_setup);
124 #define selinux_enforcing_boot 1
127 int selinux_enabled_boot __initdata = 1;
128 #ifdef CONFIG_SECURITY_SELINUX_BOOTPARAM
129 static int __init selinux_enabled_setup(char *str)
131 unsigned long enabled;
132 if (!kstrtoul(str, 0, &enabled))
133 selinux_enabled_boot = enabled ? 1 : 0;
136 __setup("selinux=", selinux_enabled_setup);
139 static unsigned int selinux_checkreqprot_boot =
140 CONFIG_SECURITY_SELINUX_CHECKREQPROT_VALUE;
142 static int __init checkreqprot_setup(char *str)
144 unsigned long checkreqprot;
146 if (!kstrtoul(str, 0, &checkreqprot)) {
147 selinux_checkreqprot_boot = checkreqprot ? 1 : 0;
149 pr_warn("SELinux: checkreqprot set to 1 via kernel parameter. This is deprecated and will be rejected in a future kernel release.\n");
153 __setup("checkreqprot=", checkreqprot_setup);
156 * selinux_secmark_enabled - Check to see if SECMARK is currently enabled
159 * This function checks the SECMARK reference counter to see if any SECMARK
160 * targets are currently configured, if the reference counter is greater than
161 * zero SECMARK is considered to be enabled. Returns true (1) if SECMARK is
162 * enabled, false (0) if SECMARK is disabled. If the always_check_network
163 * policy capability is enabled, SECMARK is always considered enabled.
166 static int selinux_secmark_enabled(void)
168 return (selinux_policycap_alwaysnetwork() ||
169 atomic_read(&selinux_secmark_refcount));
173 * selinux_peerlbl_enabled - Check to see if peer labeling is currently enabled
176 * This function checks if NetLabel or labeled IPSEC is enabled. Returns true
177 * (1) if any are enabled or false (0) if neither are enabled. If the
178 * always_check_network policy capability is enabled, peer labeling
179 * is always considered enabled.
182 static int selinux_peerlbl_enabled(void)
184 return (selinux_policycap_alwaysnetwork() ||
185 netlbl_enabled() || selinux_xfrm_enabled());
188 static int selinux_netcache_avc_callback(u32 event)
190 if (event == AVC_CALLBACK_RESET) {
199 static int selinux_lsm_notifier_avc_callback(u32 event)
201 if (event == AVC_CALLBACK_RESET) {
203 call_blocking_lsm_notifier(LSM_POLICY_CHANGE, NULL);
210 * initialise the security for the init task
212 static void cred_init_security(void)
214 struct cred *cred = (struct cred *) current->real_cred;
215 struct task_security_struct *tsec;
217 tsec = selinux_cred(cred);
218 tsec->osid = tsec->sid = SECINITSID_KERNEL;
222 * get the security ID of a set of credentials
224 static inline u32 cred_sid(const struct cred *cred)
226 const struct task_security_struct *tsec;
228 tsec = selinux_cred(cred);
233 * get the 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 strcmp(sb->s_type->name, "overlay")) {
765 if (context_sid || fscontext_sid || rootcontext_sid ||
770 if (sbsec->behavior == SECURITY_FS_USE_XATTR) {
771 sbsec->behavior = SECURITY_FS_USE_MNTPOINT;
772 rc = security_transition_sid(&selinux_state,
776 &sbsec->mntpoint_sid);
783 /* sets the context of the superblock for the fs being mounted. */
785 rc = may_context_mount_sb_relabel(fscontext_sid, sbsec, cred);
789 sbsec->sid = fscontext_sid;
793 * Switch to using mount point labeling behavior.
794 * sets the label used on all file below the mountpoint, and will set
795 * the superblock context if not already set.
797 if (kern_flags & SECURITY_LSM_NATIVE_LABELS && !context_sid) {
798 sbsec->behavior = SECURITY_FS_USE_NATIVE;
799 *set_kern_flags |= SECURITY_LSM_NATIVE_LABELS;
803 if (!fscontext_sid) {
804 rc = may_context_mount_sb_relabel(context_sid, sbsec,
808 sbsec->sid = context_sid;
810 rc = may_context_mount_inode_relabel(context_sid, sbsec,
815 if (!rootcontext_sid)
816 rootcontext_sid = context_sid;
818 sbsec->mntpoint_sid = context_sid;
819 sbsec->behavior = SECURITY_FS_USE_MNTPOINT;
822 if (rootcontext_sid) {
823 rc = may_context_mount_inode_relabel(rootcontext_sid, sbsec,
828 root_isec->sid = rootcontext_sid;
829 root_isec->initialized = LABEL_INITIALIZED;
832 if (defcontext_sid) {
833 if (sbsec->behavior != SECURITY_FS_USE_XATTR &&
834 sbsec->behavior != SECURITY_FS_USE_NATIVE) {
836 pr_warn("SELinux: defcontext option is "
837 "invalid for this filesystem type\n");
841 if (defcontext_sid != sbsec->def_sid) {
842 rc = may_context_mount_inode_relabel(defcontext_sid,
848 sbsec->def_sid = defcontext_sid;
852 rc = sb_finish_set_opts(sb);
854 mutex_unlock(&sbsec->lock);
858 pr_warn("SELinux: mount invalid. Same superblock, different "
859 "security settings for (dev %s, type %s)\n", sb->s_id,
864 static int selinux_cmp_sb_context(const struct super_block *oldsb,
865 const struct super_block *newsb)
867 struct superblock_security_struct *old = oldsb->s_security;
868 struct superblock_security_struct *new = newsb->s_security;
869 char oldflags = old->flags & SE_MNTMASK;
870 char newflags = new->flags & SE_MNTMASK;
872 if (oldflags != newflags)
874 if ((oldflags & FSCONTEXT_MNT) && old->sid != new->sid)
876 if ((oldflags & CONTEXT_MNT) && old->mntpoint_sid != new->mntpoint_sid)
878 if ((oldflags & DEFCONTEXT_MNT) && old->def_sid != new->def_sid)
880 if (oldflags & ROOTCONTEXT_MNT) {
881 struct inode_security_struct *oldroot = backing_inode_security(oldsb->s_root);
882 struct inode_security_struct *newroot = backing_inode_security(newsb->s_root);
883 if (oldroot->sid != newroot->sid)
888 pr_warn("SELinux: mount invalid. Same superblock, "
889 "different security settings for (dev %s, "
890 "type %s)\n", newsb->s_id, newsb->s_type->name);
894 static int selinux_sb_clone_mnt_opts(const struct super_block *oldsb,
895 struct super_block *newsb,
896 unsigned long kern_flags,
897 unsigned long *set_kern_flags)
900 const struct superblock_security_struct *oldsbsec = oldsb->s_security;
901 struct superblock_security_struct *newsbsec = newsb->s_security;
903 int set_fscontext = (oldsbsec->flags & FSCONTEXT_MNT);
904 int set_context = (oldsbsec->flags & CONTEXT_MNT);
905 int set_rootcontext = (oldsbsec->flags & ROOTCONTEXT_MNT);
908 * if the parent was able to be mounted it clearly had no special lsm
909 * mount options. thus we can safely deal with this superblock later
911 if (!selinux_initialized(&selinux_state))
915 * Specifying internal flags without providing a place to
916 * place the results is not allowed.
918 if (kern_flags && !set_kern_flags)
921 /* how can we clone if the old one wasn't set up?? */
922 BUG_ON(!(oldsbsec->flags & SE_SBINITIALIZED));
924 /* if fs is reusing a sb, make sure that the contexts match */
925 if (newsbsec->flags & SE_SBINITIALIZED) {
926 if ((kern_flags & SECURITY_LSM_NATIVE_LABELS) && !set_context)
927 *set_kern_flags |= SECURITY_LSM_NATIVE_LABELS;
928 return selinux_cmp_sb_context(oldsb, newsb);
931 mutex_lock(&newsbsec->lock);
933 newsbsec->flags = oldsbsec->flags;
935 newsbsec->sid = oldsbsec->sid;
936 newsbsec->def_sid = oldsbsec->def_sid;
937 newsbsec->behavior = oldsbsec->behavior;
939 if (newsbsec->behavior == SECURITY_FS_USE_NATIVE &&
940 !(kern_flags & SECURITY_LSM_NATIVE_LABELS) && !set_context) {
941 rc = security_fs_use(&selinux_state, newsb);
946 if (kern_flags & SECURITY_LSM_NATIVE_LABELS && !set_context) {
947 newsbsec->behavior = SECURITY_FS_USE_NATIVE;
948 *set_kern_flags |= SECURITY_LSM_NATIVE_LABELS;
952 u32 sid = oldsbsec->mntpoint_sid;
956 if (!set_rootcontext) {
957 struct inode_security_struct *newisec = backing_inode_security(newsb->s_root);
960 newsbsec->mntpoint_sid = sid;
962 if (set_rootcontext) {
963 const struct inode_security_struct *oldisec = backing_inode_security(oldsb->s_root);
964 struct inode_security_struct *newisec = backing_inode_security(newsb->s_root);
966 newisec->sid = oldisec->sid;
969 sb_finish_set_opts(newsb);
971 mutex_unlock(&newsbsec->lock);
975 static int selinux_add_opt(int token, const char *s, void **mnt_opts)
977 struct selinux_mnt_opts *opts = *mnt_opts;
979 if (token == Opt_seclabel) /* eaten and completely ignored */
983 opts = kzalloc(sizeof(struct selinux_mnt_opts), GFP_KERNEL);
992 if (opts->context || opts->defcontext)
1001 case Opt_rootcontext:
1002 if (opts->rootcontext)
1004 opts->rootcontext = s;
1006 case Opt_defcontext:
1007 if (opts->context || opts->defcontext)
1009 opts->defcontext = s;
1014 pr_warn(SEL_MOUNT_FAIL_MSG);
1018 static int selinux_add_mnt_opt(const char *option, const char *val, int len,
1021 int token = Opt_error;
1024 for (i = 0; i < ARRAY_SIZE(tokens); i++) {
1025 if (strcmp(option, tokens[i].name) == 0) {
1026 token = tokens[i].opt;
1031 if (token == Opt_error)
1034 if (token != Opt_seclabel) {
1035 val = kmemdup_nul(val, len, GFP_KERNEL);
1041 rc = selinux_add_opt(token, val, mnt_opts);
1050 selinux_free_mnt_opts(*mnt_opts);
1056 static int show_sid(struct seq_file *m, u32 sid)
1058 char *context = NULL;
1062 rc = security_sid_to_context(&selinux_state, sid,
1065 bool has_comma = context && strchr(context, ',');
1070 seq_escape(m, context, "\"\n\\");
1078 static int selinux_sb_show_options(struct seq_file *m, struct super_block *sb)
1080 struct superblock_security_struct *sbsec = sb->s_security;
1083 if (!(sbsec->flags & SE_SBINITIALIZED))
1086 if (!selinux_initialized(&selinux_state))
1089 if (sbsec->flags & FSCONTEXT_MNT) {
1091 seq_puts(m, FSCONTEXT_STR);
1092 rc = show_sid(m, sbsec->sid);
1096 if (sbsec->flags & CONTEXT_MNT) {
1098 seq_puts(m, CONTEXT_STR);
1099 rc = show_sid(m, sbsec->mntpoint_sid);
1103 if (sbsec->flags & DEFCONTEXT_MNT) {
1105 seq_puts(m, DEFCONTEXT_STR);
1106 rc = show_sid(m, sbsec->def_sid);
1110 if (sbsec->flags & ROOTCONTEXT_MNT) {
1111 struct dentry *root = sb->s_root;
1112 struct inode_security_struct *isec = backing_inode_security(root);
1114 seq_puts(m, ROOTCONTEXT_STR);
1115 rc = show_sid(m, isec->sid);
1119 if (sbsec->flags & SBLABEL_MNT) {
1121 seq_puts(m, SECLABEL_STR);
1126 static inline u16 inode_mode_to_security_class(umode_t mode)
1128 switch (mode & S_IFMT) {
1130 return SECCLASS_SOCK_FILE;
1132 return SECCLASS_LNK_FILE;
1134 return SECCLASS_FILE;
1136 return SECCLASS_BLK_FILE;
1138 return SECCLASS_DIR;
1140 return SECCLASS_CHR_FILE;
1142 return SECCLASS_FIFO_FILE;
1146 return SECCLASS_FILE;
1149 static inline int default_protocol_stream(int protocol)
1151 return (protocol == IPPROTO_IP || protocol == IPPROTO_TCP ||
1152 protocol == IPPROTO_MPTCP);
1155 static inline int default_protocol_dgram(int protocol)
1157 return (protocol == IPPROTO_IP || protocol == IPPROTO_UDP);
1160 static inline u16 socket_type_to_security_class(int family, int type, int protocol)
1162 int extsockclass = selinux_policycap_extsockclass();
1168 case SOCK_SEQPACKET:
1169 return SECCLASS_UNIX_STREAM_SOCKET;
1172 return SECCLASS_UNIX_DGRAM_SOCKET;
1179 case SOCK_SEQPACKET:
1180 if (default_protocol_stream(protocol))
1181 return SECCLASS_TCP_SOCKET;
1182 else if (extsockclass && protocol == IPPROTO_SCTP)
1183 return SECCLASS_SCTP_SOCKET;
1185 return SECCLASS_RAWIP_SOCKET;
1187 if (default_protocol_dgram(protocol))
1188 return SECCLASS_UDP_SOCKET;
1189 else if (extsockclass && (protocol == IPPROTO_ICMP ||
1190 protocol == IPPROTO_ICMPV6))
1191 return SECCLASS_ICMP_SOCKET;
1193 return SECCLASS_RAWIP_SOCKET;
1195 return SECCLASS_DCCP_SOCKET;
1197 return SECCLASS_RAWIP_SOCKET;
1203 return SECCLASS_NETLINK_ROUTE_SOCKET;
1204 case NETLINK_SOCK_DIAG:
1205 return SECCLASS_NETLINK_TCPDIAG_SOCKET;
1207 return SECCLASS_NETLINK_NFLOG_SOCKET;
1209 return SECCLASS_NETLINK_XFRM_SOCKET;
1210 case NETLINK_SELINUX:
1211 return SECCLASS_NETLINK_SELINUX_SOCKET;
1213 return SECCLASS_NETLINK_ISCSI_SOCKET;
1215 return SECCLASS_NETLINK_AUDIT_SOCKET;
1216 case NETLINK_FIB_LOOKUP:
1217 return SECCLASS_NETLINK_FIB_LOOKUP_SOCKET;
1218 case NETLINK_CONNECTOR:
1219 return SECCLASS_NETLINK_CONNECTOR_SOCKET;
1220 case NETLINK_NETFILTER:
1221 return SECCLASS_NETLINK_NETFILTER_SOCKET;
1222 case NETLINK_DNRTMSG:
1223 return SECCLASS_NETLINK_DNRT_SOCKET;
1224 case NETLINK_KOBJECT_UEVENT:
1225 return SECCLASS_NETLINK_KOBJECT_UEVENT_SOCKET;
1226 case NETLINK_GENERIC:
1227 return SECCLASS_NETLINK_GENERIC_SOCKET;
1228 case NETLINK_SCSITRANSPORT:
1229 return SECCLASS_NETLINK_SCSITRANSPORT_SOCKET;
1231 return SECCLASS_NETLINK_RDMA_SOCKET;
1232 case NETLINK_CRYPTO:
1233 return SECCLASS_NETLINK_CRYPTO_SOCKET;
1235 return SECCLASS_NETLINK_SOCKET;
1238 return SECCLASS_PACKET_SOCKET;
1240 return SECCLASS_KEY_SOCKET;
1242 return SECCLASS_APPLETALK_SOCKET;
1248 return SECCLASS_AX25_SOCKET;
1250 return SECCLASS_IPX_SOCKET;
1252 return SECCLASS_NETROM_SOCKET;
1254 return SECCLASS_ATMPVC_SOCKET;
1256 return SECCLASS_X25_SOCKET;
1258 return SECCLASS_ROSE_SOCKET;
1260 return SECCLASS_DECNET_SOCKET;
1262 return SECCLASS_ATMSVC_SOCKET;
1264 return SECCLASS_RDS_SOCKET;
1266 return SECCLASS_IRDA_SOCKET;
1268 return SECCLASS_PPPOX_SOCKET;
1270 return SECCLASS_LLC_SOCKET;
1272 return SECCLASS_CAN_SOCKET;
1274 return SECCLASS_TIPC_SOCKET;
1276 return SECCLASS_BLUETOOTH_SOCKET;
1278 return SECCLASS_IUCV_SOCKET;
1280 return SECCLASS_RXRPC_SOCKET;
1282 return SECCLASS_ISDN_SOCKET;
1284 return SECCLASS_PHONET_SOCKET;
1286 return SECCLASS_IEEE802154_SOCKET;
1288 return SECCLASS_CAIF_SOCKET;
1290 return SECCLASS_ALG_SOCKET;
1292 return SECCLASS_NFC_SOCKET;
1294 return SECCLASS_VSOCK_SOCKET;
1296 return SECCLASS_KCM_SOCKET;
1298 return SECCLASS_QIPCRTR_SOCKET;
1300 return SECCLASS_SMC_SOCKET;
1302 return SECCLASS_XDP_SOCKET;
1304 #error New address family defined, please update this function.
1309 return SECCLASS_SOCKET;
1312 static int selinux_genfs_get_sid(struct dentry *dentry,
1318 struct super_block *sb = dentry->d_sb;
1319 char *buffer, *path;
1321 buffer = (char *)__get_free_page(GFP_KERNEL);
1325 path = dentry_path_raw(dentry, buffer, PAGE_SIZE);
1329 if (flags & SE_SBPROC) {
1330 /* each process gets a /proc/PID/ entry. Strip off the
1331 * PID part to get a valid selinux labeling.
1332 * e.g. /proc/1/net/rpc/nfs -> /net/rpc/nfs */
1333 while (path[1] >= '0' && path[1] <= '9') {
1338 rc = security_genfs_sid(&selinux_state, sb->s_type->name,
1340 if (rc == -ENOENT) {
1341 /* No match in policy, mark as unlabeled. */
1342 *sid = SECINITSID_UNLABELED;
1346 free_page((unsigned long)buffer);
1350 static int inode_doinit_use_xattr(struct inode *inode, struct dentry *dentry,
1351 u32 def_sid, u32 *sid)
1353 #define INITCONTEXTLEN 255
1358 len = INITCONTEXTLEN;
1359 context = kmalloc(len + 1, GFP_NOFS);
1363 context[len] = '\0';
1364 rc = __vfs_getxattr(dentry, inode, XATTR_NAME_SELINUX, context, len);
1365 if (rc == -ERANGE) {
1368 /* Need a larger buffer. Query for the right size. */
1369 rc = __vfs_getxattr(dentry, inode, XATTR_NAME_SELINUX, NULL, 0);
1374 context = kmalloc(len + 1, GFP_NOFS);
1378 context[len] = '\0';
1379 rc = __vfs_getxattr(dentry, inode, XATTR_NAME_SELINUX,
1384 if (rc != -ENODATA) {
1385 pr_warn("SELinux: %s: getxattr returned %d for dev=%s ino=%ld\n",
1386 __func__, -rc, inode->i_sb->s_id, inode->i_ino);
1393 rc = security_context_to_sid_default(&selinux_state, context, rc, sid,
1396 char *dev = inode->i_sb->s_id;
1397 unsigned long ino = inode->i_ino;
1399 if (rc == -EINVAL) {
1400 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",
1403 pr_warn("SELinux: %s: context_to_sid(%s) returned %d for dev=%s ino=%ld\n",
1404 __func__, context, -rc, dev, ino);
1411 /* The inode's security attributes must be initialized before first use. */
1412 static int inode_doinit_with_dentry(struct inode *inode, struct dentry *opt_dentry)
1414 struct superblock_security_struct *sbsec = NULL;
1415 struct inode_security_struct *isec = selinux_inode(inode);
1416 u32 task_sid, sid = 0;
1418 struct dentry *dentry;
1421 if (isec->initialized == LABEL_INITIALIZED)
1424 spin_lock(&isec->lock);
1425 if (isec->initialized == LABEL_INITIALIZED)
1428 if (isec->sclass == SECCLASS_FILE)
1429 isec->sclass = inode_mode_to_security_class(inode->i_mode);
1431 sbsec = inode->i_sb->s_security;
1432 if (!(sbsec->flags & SE_SBINITIALIZED)) {
1433 /* Defer initialization until selinux_complete_init,
1434 after the initial policy is loaded and the security
1435 server is ready to handle calls. */
1436 spin_lock(&sbsec->isec_lock);
1437 if (list_empty(&isec->list))
1438 list_add(&isec->list, &sbsec->isec_head);
1439 spin_unlock(&sbsec->isec_lock);
1443 sclass = isec->sclass;
1444 task_sid = isec->task_sid;
1446 isec->initialized = LABEL_PENDING;
1447 spin_unlock(&isec->lock);
1449 switch (sbsec->behavior) {
1450 case SECURITY_FS_USE_NATIVE:
1452 case SECURITY_FS_USE_XATTR:
1453 if (!(inode->i_opflags & IOP_XATTR)) {
1454 sid = sbsec->def_sid;
1457 /* Need a dentry, since the xattr API requires one.
1458 Life would be simpler if we could just pass the inode. */
1460 /* Called from d_instantiate or d_splice_alias. */
1461 dentry = dget(opt_dentry);
1464 * Called from selinux_complete_init, try to find a dentry.
1465 * Some filesystems really want a connected one, so try
1466 * that first. We could split SECURITY_FS_USE_XATTR in
1467 * two, depending upon that...
1469 dentry = d_find_alias(inode);
1471 dentry = d_find_any_alias(inode);
1475 * this is can be hit on boot when a file is accessed
1476 * before the policy is loaded. When we load policy we
1477 * may find inodes that have no dentry on the
1478 * sbsec->isec_head list. No reason to complain as these
1479 * will get fixed up the next time we go through
1480 * inode_doinit with a dentry, before these inodes could
1481 * be used again by userspace.
1486 rc = inode_doinit_use_xattr(inode, dentry, sbsec->def_sid,
1492 case SECURITY_FS_USE_TASK:
1495 case SECURITY_FS_USE_TRANS:
1496 /* Default to the fs SID. */
1499 /* Try to obtain a transition SID. */
1500 rc = security_transition_sid(&selinux_state, task_sid, sid,
1501 sclass, NULL, &sid);
1505 case SECURITY_FS_USE_MNTPOINT:
1506 sid = sbsec->mntpoint_sid;
1509 /* Default to the fs superblock SID. */
1512 if ((sbsec->flags & SE_SBGENFS) &&
1513 (!S_ISLNK(inode->i_mode) ||
1514 selinux_policycap_genfs_seclabel_symlinks())) {
1515 /* We must have a dentry to determine the label on
1518 /* Called from d_instantiate or
1519 * d_splice_alias. */
1520 dentry = dget(opt_dentry);
1522 /* Called from selinux_complete_init, try to
1523 * find a dentry. Some filesystems really want
1524 * a connected one, so try that first.
1526 dentry = d_find_alias(inode);
1528 dentry = d_find_any_alias(inode);
1531 * This can be hit on boot when a file is accessed
1532 * before the policy is loaded. When we load policy we
1533 * may find inodes that have no dentry on the
1534 * sbsec->isec_head list. No reason to complain as
1535 * these will get fixed up the next time we go through
1536 * inode_doinit() with a dentry, before these inodes
1537 * could be used again by userspace.
1541 rc = selinux_genfs_get_sid(dentry, sclass,
1542 sbsec->flags, &sid);
1548 if ((sbsec->flags & SE_SBGENFS_XATTR) &&
1549 (inode->i_opflags & IOP_XATTR)) {
1550 rc = inode_doinit_use_xattr(inode, dentry,
1563 spin_lock(&isec->lock);
1564 if (isec->initialized == LABEL_PENDING) {
1566 isec->initialized = LABEL_INVALID;
1569 isec->initialized = LABEL_INITIALIZED;
1574 spin_unlock(&isec->lock);
1578 spin_lock(&isec->lock);
1579 if (isec->initialized == LABEL_PENDING) {
1580 isec->initialized = LABEL_INVALID;
1583 spin_unlock(&isec->lock);
1587 /* Convert a Linux signal to an access vector. */
1588 static inline u32 signal_to_av(int sig)
1594 /* Commonly granted from child to parent. */
1595 perm = PROCESS__SIGCHLD;
1598 /* Cannot be caught or ignored */
1599 perm = PROCESS__SIGKILL;
1602 /* Cannot be caught or ignored */
1603 perm = PROCESS__SIGSTOP;
1606 /* All other signals. */
1607 perm = PROCESS__SIGNAL;
1614 #if CAP_LAST_CAP > 63
1615 #error Fix SELinux to handle capabilities > 63.
1618 /* Check whether a task is allowed to use a capability. */
1619 static int cred_has_capability(const struct cred *cred,
1620 int cap, unsigned int opts, bool initns)
1622 struct common_audit_data ad;
1623 struct av_decision avd;
1625 u32 sid = cred_sid(cred);
1626 u32 av = CAP_TO_MASK(cap);
1629 ad.type = LSM_AUDIT_DATA_CAP;
1632 switch (CAP_TO_INDEX(cap)) {
1634 sclass = initns ? SECCLASS_CAPABILITY : SECCLASS_CAP_USERNS;
1637 sclass = initns ? SECCLASS_CAPABILITY2 : SECCLASS_CAP2_USERNS;
1640 pr_err("SELinux: out of range capability %d\n", cap);
1645 rc = avc_has_perm_noaudit(&selinux_state,
1646 sid, sid, sclass, av, 0, &avd);
1647 if (!(opts & CAP_OPT_NOAUDIT)) {
1648 int rc2 = avc_audit(&selinux_state,
1649 sid, sid, sclass, av, &avd, rc, &ad, 0);
1656 /* Check whether a task has a particular permission to an inode.
1657 The 'adp' parameter is optional and allows other audit
1658 data to be passed (e.g. the dentry). */
1659 static int inode_has_perm(const struct cred *cred,
1660 struct inode *inode,
1662 struct common_audit_data *adp)
1664 struct inode_security_struct *isec;
1667 validate_creds(cred);
1669 if (unlikely(IS_PRIVATE(inode)))
1672 sid = cred_sid(cred);
1673 isec = selinux_inode(inode);
1675 return avc_has_perm(&selinux_state,
1676 sid, isec->sid, isec->sclass, perms, adp);
1679 /* Same as inode_has_perm, but pass explicit audit data containing
1680 the dentry to help the auditing code to more easily generate the
1681 pathname if needed. */
1682 static inline int dentry_has_perm(const struct cred *cred,
1683 struct dentry *dentry,
1686 struct inode *inode = d_backing_inode(dentry);
1687 struct common_audit_data ad;
1689 ad.type = LSM_AUDIT_DATA_DENTRY;
1690 ad.u.dentry = dentry;
1691 __inode_security_revalidate(inode, dentry, true);
1692 return inode_has_perm(cred, inode, av, &ad);
1695 /* Same as inode_has_perm, but pass explicit audit data containing
1696 the path to help the auditing code to more easily generate the
1697 pathname if needed. */
1698 static inline int path_has_perm(const struct cred *cred,
1699 const struct path *path,
1702 struct inode *inode = d_backing_inode(path->dentry);
1703 struct common_audit_data ad;
1705 ad.type = LSM_AUDIT_DATA_PATH;
1707 __inode_security_revalidate(inode, path->dentry, true);
1708 return inode_has_perm(cred, inode, av, &ad);
1711 /* Same as path_has_perm, but uses the inode from the file struct. */
1712 static inline int file_path_has_perm(const struct cred *cred,
1716 struct common_audit_data ad;
1718 ad.type = LSM_AUDIT_DATA_FILE;
1720 return inode_has_perm(cred, file_inode(file), av, &ad);
1723 #ifdef CONFIG_BPF_SYSCALL
1724 static int bpf_fd_pass(struct file *file, u32 sid);
1727 /* Check whether a task can use an open file descriptor to
1728 access an inode in a given way. Check access to the
1729 descriptor itself, and then use dentry_has_perm to
1730 check a particular permission to the file.
1731 Access to the descriptor is implicitly granted if it
1732 has the same SID as the process. If av is zero, then
1733 access to the file is not checked, e.g. for cases
1734 where only the descriptor is affected like seek. */
1735 static int file_has_perm(const struct cred *cred,
1739 struct file_security_struct *fsec = selinux_file(file);
1740 struct inode *inode = file_inode(file);
1741 struct common_audit_data ad;
1742 u32 sid = cred_sid(cred);
1745 ad.type = LSM_AUDIT_DATA_FILE;
1748 if (sid != fsec->sid) {
1749 rc = avc_has_perm(&selinux_state,
1758 #ifdef CONFIG_BPF_SYSCALL
1759 rc = bpf_fd_pass(file, cred_sid(cred));
1764 /* av is zero if only checking access to the descriptor. */
1767 rc = inode_has_perm(cred, inode, av, &ad);
1774 * Determine the label for an inode that might be unioned.
1777 selinux_determine_inode_label(const struct task_security_struct *tsec,
1779 const struct qstr *name, u16 tclass,
1782 const struct superblock_security_struct *sbsec = dir->i_sb->s_security;
1784 if ((sbsec->flags & SE_SBINITIALIZED) &&
1785 (sbsec->behavior == SECURITY_FS_USE_MNTPOINT)) {
1786 *_new_isid = sbsec->mntpoint_sid;
1787 } else if ((sbsec->flags & SBLABEL_MNT) &&
1789 *_new_isid = tsec->create_sid;
1791 const struct inode_security_struct *dsec = inode_security(dir);
1792 return security_transition_sid(&selinux_state, tsec->sid,
1800 /* Check whether a task can create a file. */
1801 static int may_create(struct inode *dir,
1802 struct dentry *dentry,
1805 const struct task_security_struct *tsec = selinux_cred(current_cred());
1806 struct inode_security_struct *dsec;
1807 struct superblock_security_struct *sbsec;
1809 struct common_audit_data ad;
1812 dsec = inode_security(dir);
1813 sbsec = dir->i_sb->s_security;
1817 ad.type = LSM_AUDIT_DATA_DENTRY;
1818 ad.u.dentry = dentry;
1820 rc = avc_has_perm(&selinux_state,
1821 sid, dsec->sid, SECCLASS_DIR,
1822 DIR__ADD_NAME | DIR__SEARCH,
1827 rc = selinux_determine_inode_label(tsec, dir, &dentry->d_name, tclass,
1832 rc = avc_has_perm(&selinux_state,
1833 sid, newsid, tclass, FILE__CREATE, &ad);
1837 return avc_has_perm(&selinux_state,
1839 SECCLASS_FILESYSTEM,
1840 FILESYSTEM__ASSOCIATE, &ad);
1844 #define MAY_UNLINK 1
1847 /* Check whether a task can link, unlink, or rmdir a file/directory. */
1848 static int may_link(struct inode *dir,
1849 struct dentry *dentry,
1853 struct inode_security_struct *dsec, *isec;
1854 struct common_audit_data ad;
1855 u32 sid = current_sid();
1859 dsec = inode_security(dir);
1860 isec = backing_inode_security(dentry);
1862 ad.type = LSM_AUDIT_DATA_DENTRY;
1863 ad.u.dentry = dentry;
1866 av |= (kind ? DIR__REMOVE_NAME : DIR__ADD_NAME);
1867 rc = avc_has_perm(&selinux_state,
1868 sid, dsec->sid, SECCLASS_DIR, av, &ad);
1883 pr_warn("SELinux: %s: unrecognized kind %d\n",
1888 rc = avc_has_perm(&selinux_state,
1889 sid, isec->sid, isec->sclass, av, &ad);
1893 static inline int may_rename(struct inode *old_dir,
1894 struct dentry *old_dentry,
1895 struct inode *new_dir,
1896 struct dentry *new_dentry)
1898 struct inode_security_struct *old_dsec, *new_dsec, *old_isec, *new_isec;
1899 struct common_audit_data ad;
1900 u32 sid = current_sid();
1902 int old_is_dir, new_is_dir;
1905 old_dsec = inode_security(old_dir);
1906 old_isec = backing_inode_security(old_dentry);
1907 old_is_dir = d_is_dir(old_dentry);
1908 new_dsec = inode_security(new_dir);
1910 ad.type = LSM_AUDIT_DATA_DENTRY;
1912 ad.u.dentry = old_dentry;
1913 rc = avc_has_perm(&selinux_state,
1914 sid, old_dsec->sid, SECCLASS_DIR,
1915 DIR__REMOVE_NAME | DIR__SEARCH, &ad);
1918 rc = avc_has_perm(&selinux_state,
1920 old_isec->sclass, FILE__RENAME, &ad);
1923 if (old_is_dir && new_dir != old_dir) {
1924 rc = avc_has_perm(&selinux_state,
1926 old_isec->sclass, DIR__REPARENT, &ad);
1931 ad.u.dentry = new_dentry;
1932 av = DIR__ADD_NAME | DIR__SEARCH;
1933 if (d_is_positive(new_dentry))
1934 av |= DIR__REMOVE_NAME;
1935 rc = avc_has_perm(&selinux_state,
1936 sid, new_dsec->sid, SECCLASS_DIR, av, &ad);
1939 if (d_is_positive(new_dentry)) {
1940 new_isec = backing_inode_security(new_dentry);
1941 new_is_dir = d_is_dir(new_dentry);
1942 rc = avc_has_perm(&selinux_state,
1945 (new_is_dir ? DIR__RMDIR : FILE__UNLINK), &ad);
1953 /* Check whether a task can perform a filesystem operation. */
1954 static int superblock_has_perm(const struct cred *cred,
1955 struct super_block *sb,
1957 struct common_audit_data *ad)
1959 struct superblock_security_struct *sbsec;
1960 u32 sid = cred_sid(cred);
1962 sbsec = sb->s_security;
1963 return avc_has_perm(&selinux_state,
1964 sid, sbsec->sid, SECCLASS_FILESYSTEM, perms, ad);
1967 /* Convert a Linux mode and permission mask to an access vector. */
1968 static inline u32 file_mask_to_av(int mode, int mask)
1972 if (!S_ISDIR(mode)) {
1973 if (mask & MAY_EXEC)
1974 av |= FILE__EXECUTE;
1975 if (mask & MAY_READ)
1978 if (mask & MAY_APPEND)
1980 else if (mask & MAY_WRITE)
1984 if (mask & MAY_EXEC)
1986 if (mask & MAY_WRITE)
1988 if (mask & MAY_READ)
1995 /* Convert a Linux file to an access vector. */
1996 static inline u32 file_to_av(struct file *file)
2000 if (file->f_mode & FMODE_READ)
2002 if (file->f_mode & FMODE_WRITE) {
2003 if (file->f_flags & O_APPEND)
2010 * Special file opened with flags 3 for ioctl-only use.
2019 * Convert a file to an access vector and include the correct
2022 static inline u32 open_file_to_av(struct file *file)
2024 u32 av = file_to_av(file);
2025 struct inode *inode = file_inode(file);
2027 if (selinux_policycap_openperm() &&
2028 inode->i_sb->s_magic != SOCKFS_MAGIC)
2034 /* Hook functions begin here. */
2036 static int selinux_binder_set_context_mgr(struct task_struct *mgr)
2038 u32 mysid = current_sid();
2039 u32 mgrsid = task_sid(mgr);
2041 return avc_has_perm(&selinux_state,
2042 mysid, mgrsid, SECCLASS_BINDER,
2043 BINDER__SET_CONTEXT_MGR, NULL);
2046 static int selinux_binder_transaction(struct task_struct *from,
2047 struct task_struct *to)
2049 u32 mysid = current_sid();
2050 u32 fromsid = task_sid(from);
2051 u32 tosid = task_sid(to);
2054 if (mysid != fromsid) {
2055 rc = avc_has_perm(&selinux_state,
2056 mysid, fromsid, SECCLASS_BINDER,
2057 BINDER__IMPERSONATE, NULL);
2062 return avc_has_perm(&selinux_state,
2063 fromsid, tosid, SECCLASS_BINDER, BINDER__CALL,
2067 static int selinux_binder_transfer_binder(struct task_struct *from,
2068 struct task_struct *to)
2070 u32 fromsid = task_sid(from);
2071 u32 tosid = task_sid(to);
2073 return avc_has_perm(&selinux_state,
2074 fromsid, tosid, SECCLASS_BINDER, BINDER__TRANSFER,
2078 static int selinux_binder_transfer_file(struct task_struct *from,
2079 struct task_struct *to,
2082 u32 sid = task_sid(to);
2083 struct file_security_struct *fsec = selinux_file(file);
2084 struct dentry *dentry = file->f_path.dentry;
2085 struct inode_security_struct *isec;
2086 struct common_audit_data ad;
2089 ad.type = LSM_AUDIT_DATA_PATH;
2090 ad.u.path = file->f_path;
2092 if (sid != fsec->sid) {
2093 rc = avc_has_perm(&selinux_state,
2102 #ifdef CONFIG_BPF_SYSCALL
2103 rc = bpf_fd_pass(file, sid);
2108 if (unlikely(IS_PRIVATE(d_backing_inode(dentry))))
2111 isec = backing_inode_security(dentry);
2112 return avc_has_perm(&selinux_state,
2113 sid, isec->sid, isec->sclass, file_to_av(file),
2117 static int selinux_ptrace_access_check(struct task_struct *child,
2120 u32 sid = current_sid();
2121 u32 csid = task_sid(child);
2123 if (mode & PTRACE_MODE_READ)
2124 return avc_has_perm(&selinux_state,
2125 sid, csid, SECCLASS_FILE, FILE__READ, NULL);
2127 return avc_has_perm(&selinux_state,
2128 sid, csid, SECCLASS_PROCESS, PROCESS__PTRACE, NULL);
2131 static int selinux_ptrace_traceme(struct task_struct *parent)
2133 return avc_has_perm(&selinux_state,
2134 task_sid(parent), current_sid(), SECCLASS_PROCESS,
2135 PROCESS__PTRACE, NULL);
2138 static int selinux_capget(struct task_struct *target, kernel_cap_t *effective,
2139 kernel_cap_t *inheritable, kernel_cap_t *permitted)
2141 return avc_has_perm(&selinux_state,
2142 current_sid(), task_sid(target), SECCLASS_PROCESS,
2143 PROCESS__GETCAP, NULL);
2146 static int selinux_capset(struct cred *new, const struct cred *old,
2147 const kernel_cap_t *effective,
2148 const kernel_cap_t *inheritable,
2149 const kernel_cap_t *permitted)
2151 return avc_has_perm(&selinux_state,
2152 cred_sid(old), cred_sid(new), SECCLASS_PROCESS,
2153 PROCESS__SETCAP, NULL);
2157 * (This comment used to live with the selinux_task_setuid hook,
2158 * which was removed).
2160 * Since setuid only affects the current process, and since the SELinux
2161 * controls are not based on the Linux identity attributes, SELinux does not
2162 * need to control this operation. However, SELinux does control the use of
2163 * the CAP_SETUID and CAP_SETGID capabilities using the capable hook.
2166 static int selinux_capable(const struct cred *cred, struct user_namespace *ns,
2167 int cap, unsigned int opts)
2169 return cred_has_capability(cred, cap, opts, ns == &init_user_ns);
2172 static int selinux_quotactl(int cmds, int type, int id, struct super_block *sb)
2174 const struct cred *cred = current_cred();
2189 rc = superblock_has_perm(cred, sb, FILESYSTEM__QUOTAMOD, NULL);
2197 case Q_XGETNEXTQUOTA:
2198 rc = superblock_has_perm(cred, sb, FILESYSTEM__QUOTAGET, NULL);
2201 rc = 0; /* let the kernel handle invalid cmds */
2207 static int selinux_quota_on(struct dentry *dentry)
2209 const struct cred *cred = current_cred();
2211 return dentry_has_perm(cred, dentry, FILE__QUOTAON);
2214 static int selinux_syslog(int type)
2217 case SYSLOG_ACTION_READ_ALL: /* Read last kernel messages */
2218 case SYSLOG_ACTION_SIZE_BUFFER: /* Return size of the log buffer */
2219 return avc_has_perm(&selinux_state,
2220 current_sid(), SECINITSID_KERNEL,
2221 SECCLASS_SYSTEM, SYSTEM__SYSLOG_READ, NULL);
2222 case SYSLOG_ACTION_CONSOLE_OFF: /* Disable logging to console */
2223 case SYSLOG_ACTION_CONSOLE_ON: /* Enable logging to console */
2224 /* Set level of messages printed to console */
2225 case SYSLOG_ACTION_CONSOLE_LEVEL:
2226 return avc_has_perm(&selinux_state,
2227 current_sid(), SECINITSID_KERNEL,
2228 SECCLASS_SYSTEM, SYSTEM__SYSLOG_CONSOLE,
2231 /* All other syslog types */
2232 return avc_has_perm(&selinux_state,
2233 current_sid(), SECINITSID_KERNEL,
2234 SECCLASS_SYSTEM, SYSTEM__SYSLOG_MOD, NULL);
2238 * Check that a process has enough memory to allocate a new virtual
2239 * mapping. 0 means there is enough memory for the allocation to
2240 * succeed and -ENOMEM implies there is not.
2242 * Do not audit the selinux permission check, as this is applied to all
2243 * processes that allocate mappings.
2245 static int selinux_vm_enough_memory(struct mm_struct *mm, long pages)
2247 int rc, cap_sys_admin = 0;
2249 rc = cred_has_capability(current_cred(), CAP_SYS_ADMIN,
2250 CAP_OPT_NOAUDIT, true);
2254 return cap_sys_admin;
2257 /* binprm security operations */
2259 static u32 ptrace_parent_sid(void)
2262 struct task_struct *tracer;
2265 tracer = ptrace_parent(current);
2267 sid = task_sid(tracer);
2273 static int check_nnp_nosuid(const struct linux_binprm *bprm,
2274 const struct task_security_struct *old_tsec,
2275 const struct task_security_struct *new_tsec)
2277 int nnp = (bprm->unsafe & LSM_UNSAFE_NO_NEW_PRIVS);
2278 int nosuid = !mnt_may_suid(bprm->file->f_path.mnt);
2282 if (!nnp && !nosuid)
2283 return 0; /* neither NNP nor nosuid */
2285 if (new_tsec->sid == old_tsec->sid)
2286 return 0; /* No change in credentials */
2289 * If the policy enables the nnp_nosuid_transition policy capability,
2290 * then we permit transitions under NNP or nosuid if the
2291 * policy allows the corresponding permission between
2292 * the old and new contexts.
2294 if (selinux_policycap_nnp_nosuid_transition()) {
2297 av |= PROCESS2__NNP_TRANSITION;
2299 av |= PROCESS2__NOSUID_TRANSITION;
2300 rc = avc_has_perm(&selinux_state,
2301 old_tsec->sid, new_tsec->sid,
2302 SECCLASS_PROCESS2, av, NULL);
2308 * We also permit NNP or nosuid transitions to bounded SIDs,
2309 * i.e. SIDs that are guaranteed to only be allowed a subset
2310 * of the permissions of the current SID.
2312 rc = security_bounded_transition(&selinux_state, old_tsec->sid,
2318 * On failure, preserve the errno values for NNP vs nosuid.
2319 * NNP: Operation not permitted for caller.
2320 * nosuid: Permission denied to file.
2327 static int selinux_bprm_creds_for_exec(struct linux_binprm *bprm)
2329 const struct task_security_struct *old_tsec;
2330 struct task_security_struct *new_tsec;
2331 struct inode_security_struct *isec;
2332 struct common_audit_data ad;
2333 struct inode *inode = file_inode(bprm->file);
2336 /* SELinux context only depends on initial program or script and not
2337 * the script interpreter */
2339 old_tsec = selinux_cred(current_cred());
2340 new_tsec = selinux_cred(bprm->cred);
2341 isec = inode_security(inode);
2343 /* Default to the current task SID. */
2344 new_tsec->sid = old_tsec->sid;
2345 new_tsec->osid = old_tsec->sid;
2347 /* Reset fs, key, and sock SIDs on execve. */
2348 new_tsec->create_sid = 0;
2349 new_tsec->keycreate_sid = 0;
2350 new_tsec->sockcreate_sid = 0;
2352 if (old_tsec->exec_sid) {
2353 new_tsec->sid = old_tsec->exec_sid;
2354 /* Reset exec SID on execve. */
2355 new_tsec->exec_sid = 0;
2357 /* Fail on NNP or nosuid if not an allowed transition. */
2358 rc = check_nnp_nosuid(bprm, old_tsec, new_tsec);
2362 /* Check for a default transition on this program. */
2363 rc = security_transition_sid(&selinux_state, old_tsec->sid,
2364 isec->sid, SECCLASS_PROCESS, NULL,
2370 * Fallback to old SID on NNP or nosuid if not an allowed
2373 rc = check_nnp_nosuid(bprm, old_tsec, new_tsec);
2375 new_tsec->sid = old_tsec->sid;
2378 ad.type = LSM_AUDIT_DATA_FILE;
2379 ad.u.file = bprm->file;
2381 if (new_tsec->sid == old_tsec->sid) {
2382 rc = avc_has_perm(&selinux_state,
2383 old_tsec->sid, isec->sid,
2384 SECCLASS_FILE, FILE__EXECUTE_NO_TRANS, &ad);
2388 /* Check permissions for the transition. */
2389 rc = avc_has_perm(&selinux_state,
2390 old_tsec->sid, new_tsec->sid,
2391 SECCLASS_PROCESS, PROCESS__TRANSITION, &ad);
2395 rc = avc_has_perm(&selinux_state,
2396 new_tsec->sid, isec->sid,
2397 SECCLASS_FILE, FILE__ENTRYPOINT, &ad);
2401 /* Check for shared state */
2402 if (bprm->unsafe & LSM_UNSAFE_SHARE) {
2403 rc = avc_has_perm(&selinux_state,
2404 old_tsec->sid, new_tsec->sid,
2405 SECCLASS_PROCESS, PROCESS__SHARE,
2411 /* Make sure that anyone attempting to ptrace over a task that
2412 * changes its SID has the appropriate permit */
2413 if (bprm->unsafe & LSM_UNSAFE_PTRACE) {
2414 u32 ptsid = ptrace_parent_sid();
2416 rc = avc_has_perm(&selinux_state,
2417 ptsid, new_tsec->sid,
2419 PROCESS__PTRACE, NULL);
2425 /* Clear any possibly unsafe personality bits on exec: */
2426 bprm->per_clear |= PER_CLEAR_ON_SETID;
2428 /* Enable secure mode for SIDs transitions unless
2429 the noatsecure permission is granted between
2430 the two SIDs, i.e. ahp returns 0. */
2431 rc = avc_has_perm(&selinux_state,
2432 old_tsec->sid, new_tsec->sid,
2433 SECCLASS_PROCESS, PROCESS__NOATSECURE,
2435 bprm->secureexec |= !!rc;
2441 static int match_file(const void *p, struct file *file, unsigned fd)
2443 return file_has_perm(p, file, file_to_av(file)) ? fd + 1 : 0;
2446 /* Derived from fs/exec.c:flush_old_files. */
2447 static inline void flush_unauthorized_files(const struct cred *cred,
2448 struct files_struct *files)
2450 struct file *file, *devnull = NULL;
2451 struct tty_struct *tty;
2455 tty = get_current_tty();
2457 spin_lock(&tty->files_lock);
2458 if (!list_empty(&tty->tty_files)) {
2459 struct tty_file_private *file_priv;
2461 /* Revalidate access to controlling tty.
2462 Use file_path_has_perm on the tty path directly
2463 rather than using file_has_perm, as this particular
2464 open file may belong to another process and we are
2465 only interested in the inode-based check here. */
2466 file_priv = list_first_entry(&tty->tty_files,
2467 struct tty_file_private, list);
2468 file = file_priv->file;
2469 if (file_path_has_perm(cred, file, FILE__READ | FILE__WRITE))
2472 spin_unlock(&tty->files_lock);
2475 /* Reset controlling tty. */
2479 /* Revalidate access to inherited open files. */
2480 n = iterate_fd(files, 0, match_file, cred);
2481 if (!n) /* none found? */
2484 devnull = dentry_open(&selinux_null, O_RDWR, cred);
2485 if (IS_ERR(devnull))
2487 /* replace all the matching ones with this */
2489 replace_fd(n - 1, devnull, 0);
2490 } while ((n = iterate_fd(files, n, match_file, cred)) != 0);
2496 * Prepare a process for imminent new credential changes due to exec
2498 static void selinux_bprm_committing_creds(struct linux_binprm *bprm)
2500 struct task_security_struct *new_tsec;
2501 struct rlimit *rlim, *initrlim;
2504 new_tsec = selinux_cred(bprm->cred);
2505 if (new_tsec->sid == new_tsec->osid)
2508 /* Close files for which the new task SID is not authorized. */
2509 flush_unauthorized_files(bprm->cred, current->files);
2511 /* Always clear parent death signal on SID transitions. */
2512 current->pdeath_signal = 0;
2514 /* Check whether the new SID can inherit resource limits from the old
2515 * SID. If not, reset all soft limits to the lower of the current
2516 * task's hard limit and the init task's soft limit.
2518 * Note that the setting of hard limits (even to lower them) can be
2519 * controlled by the setrlimit check. The inclusion of the init task's
2520 * soft limit into the computation is to avoid resetting soft limits
2521 * higher than the default soft limit for cases where the default is
2522 * lower than the hard limit, e.g. RLIMIT_CORE or RLIMIT_STACK.
2524 rc = avc_has_perm(&selinux_state,
2525 new_tsec->osid, new_tsec->sid, SECCLASS_PROCESS,
2526 PROCESS__RLIMITINH, NULL);
2528 /* protect against do_prlimit() */
2530 for (i = 0; i < RLIM_NLIMITS; i++) {
2531 rlim = current->signal->rlim + i;
2532 initrlim = init_task.signal->rlim + i;
2533 rlim->rlim_cur = min(rlim->rlim_max, initrlim->rlim_cur);
2535 task_unlock(current);
2536 if (IS_ENABLED(CONFIG_POSIX_TIMERS))
2537 update_rlimit_cpu(current, rlimit(RLIMIT_CPU));
2542 * Clean up the process immediately after the installation of new credentials
2545 static void selinux_bprm_committed_creds(struct linux_binprm *bprm)
2547 const struct task_security_struct *tsec = selinux_cred(current_cred());
2557 /* Check whether the new SID can inherit signal state from the old SID.
2558 * If not, clear itimers to avoid subsequent signal generation and
2559 * flush and unblock signals.
2561 * This must occur _after_ the task SID has been updated so that any
2562 * kill done after the flush will be checked against the new SID.
2564 rc = avc_has_perm(&selinux_state,
2565 osid, sid, SECCLASS_PROCESS, PROCESS__SIGINH, NULL);
2569 spin_lock_irq(¤t->sighand->siglock);
2570 if (!fatal_signal_pending(current)) {
2571 flush_sigqueue(¤t->pending);
2572 flush_sigqueue(¤t->signal->shared_pending);
2573 flush_signal_handlers(current, 1);
2574 sigemptyset(¤t->blocked);
2575 recalc_sigpending();
2577 spin_unlock_irq(¤t->sighand->siglock);
2580 /* Wake up the parent if it is waiting so that it can recheck
2581 * wait permission to the new task SID. */
2582 read_lock(&tasklist_lock);
2583 __wake_up_parent(current, current->real_parent);
2584 read_unlock(&tasklist_lock);
2587 /* superblock security operations */
2589 static int selinux_sb_alloc_security(struct super_block *sb)
2591 struct superblock_security_struct *sbsec;
2593 sbsec = kzalloc(sizeof(struct superblock_security_struct), GFP_KERNEL);
2597 mutex_init(&sbsec->lock);
2598 INIT_LIST_HEAD(&sbsec->isec_head);
2599 spin_lock_init(&sbsec->isec_lock);
2600 sbsec->sid = SECINITSID_UNLABELED;
2601 sbsec->def_sid = SECINITSID_FILE;
2602 sbsec->mntpoint_sid = SECINITSID_UNLABELED;
2603 sb->s_security = sbsec;
2608 static void selinux_sb_free_security(struct super_block *sb)
2610 superblock_free_security(sb);
2613 static inline int opt_len(const char *s)
2615 bool open_quote = false;
2619 for (len = 0; (c = s[len]) != '\0'; len++) {
2621 open_quote = !open_quote;
2622 if (c == ',' && !open_quote)
2628 static int selinux_sb_eat_lsm_opts(char *options, void **mnt_opts)
2630 char *from = options;
2636 int len = opt_len(from);
2640 token = match_opt_prefix(from, len, &arg);
2642 if (token != Opt_error) {
2647 for (p = q = arg; p < from + len; p++) {
2652 arg = kmemdup_nul(arg, q - arg, GFP_KERNEL);
2658 rc = selinux_add_opt(token, arg, mnt_opts);
2664 if (!first) { // copy with preceding comma
2669 memmove(to, from, len);
2682 selinux_free_mnt_opts(*mnt_opts);
2688 static int selinux_sb_mnt_opts_compat(struct super_block *sb, void *mnt_opts)
2690 struct selinux_mnt_opts *opts = mnt_opts;
2691 struct superblock_security_struct *sbsec = sb->s_security;
2696 * Superblock not initialized (i.e. no options) - reject if any
2697 * options specified, otherwise accept.
2699 if (!(sbsec->flags & SE_SBINITIALIZED))
2700 return opts ? 1 : 0;
2703 * Superblock initialized and no options specified - reject if
2704 * superblock has any options set, otherwise accept.
2707 return (sbsec->flags & SE_MNTMASK) ? 1 : 0;
2709 if (opts->fscontext) {
2710 rc = parse_sid(sb, opts->fscontext, &sid);
2713 if (bad_option(sbsec, FSCONTEXT_MNT, sbsec->sid, sid))
2716 if (opts->context) {
2717 rc = parse_sid(sb, opts->context, &sid);
2720 if (bad_option(sbsec, CONTEXT_MNT, sbsec->mntpoint_sid, sid))
2723 if (opts->rootcontext) {
2724 struct inode_security_struct *root_isec;
2726 root_isec = backing_inode_security(sb->s_root);
2727 rc = parse_sid(sb, opts->rootcontext, &sid);
2730 if (bad_option(sbsec, ROOTCONTEXT_MNT, root_isec->sid, sid))
2733 if (opts->defcontext) {
2734 rc = parse_sid(sb, opts->defcontext, &sid);
2737 if (bad_option(sbsec, DEFCONTEXT_MNT, sbsec->def_sid, sid))
2743 static int selinux_sb_remount(struct super_block *sb, void *mnt_opts)
2745 struct selinux_mnt_opts *opts = mnt_opts;
2746 struct superblock_security_struct *sbsec = sb->s_security;
2750 if (!(sbsec->flags & SE_SBINITIALIZED))
2756 if (opts->fscontext) {
2757 rc = parse_sid(sb, opts->fscontext, &sid);
2760 if (bad_option(sbsec, FSCONTEXT_MNT, sbsec->sid, sid))
2761 goto out_bad_option;
2763 if (opts->context) {
2764 rc = parse_sid(sb, opts->context, &sid);
2767 if (bad_option(sbsec, CONTEXT_MNT, sbsec->mntpoint_sid, sid))
2768 goto out_bad_option;
2770 if (opts->rootcontext) {
2771 struct inode_security_struct *root_isec;
2772 root_isec = backing_inode_security(sb->s_root);
2773 rc = parse_sid(sb, opts->rootcontext, &sid);
2776 if (bad_option(sbsec, ROOTCONTEXT_MNT, root_isec->sid, sid))
2777 goto out_bad_option;
2779 if (opts->defcontext) {
2780 rc = parse_sid(sb, opts->defcontext, &sid);
2783 if (bad_option(sbsec, DEFCONTEXT_MNT, sbsec->def_sid, sid))
2784 goto out_bad_option;
2789 pr_warn("SELinux: unable to change security options "
2790 "during remount (dev %s, type=%s)\n", sb->s_id,
2795 static int selinux_sb_kern_mount(struct super_block *sb)
2797 const struct cred *cred = current_cred();
2798 struct common_audit_data ad;
2800 ad.type = LSM_AUDIT_DATA_DENTRY;
2801 ad.u.dentry = sb->s_root;
2802 return superblock_has_perm(cred, sb, FILESYSTEM__MOUNT, &ad);
2805 static int selinux_sb_statfs(struct dentry *dentry)
2807 const struct cred *cred = current_cred();
2808 struct common_audit_data ad;
2810 ad.type = LSM_AUDIT_DATA_DENTRY;
2811 ad.u.dentry = dentry->d_sb->s_root;
2812 return superblock_has_perm(cred, dentry->d_sb, FILESYSTEM__GETATTR, &ad);
2815 static int selinux_mount(const char *dev_name,
2816 const struct path *path,
2818 unsigned long flags,
2821 const struct cred *cred = current_cred();
2823 if (flags & MS_REMOUNT)
2824 return superblock_has_perm(cred, path->dentry->d_sb,
2825 FILESYSTEM__REMOUNT, NULL);
2827 return path_has_perm(cred, path, FILE__MOUNTON);
2830 static int selinux_move_mount(const struct path *from_path,
2831 const struct path *to_path)
2833 const struct cred *cred = current_cred();
2835 return path_has_perm(cred, to_path, FILE__MOUNTON);
2838 static int selinux_umount(struct vfsmount *mnt, int flags)
2840 const struct cred *cred = current_cred();
2842 return superblock_has_perm(cred, mnt->mnt_sb,
2843 FILESYSTEM__UNMOUNT, NULL);
2846 static int selinux_fs_context_dup(struct fs_context *fc,
2847 struct fs_context *src_fc)
2849 const struct selinux_mnt_opts *src = src_fc->security;
2850 struct selinux_mnt_opts *opts;
2855 fc->security = kzalloc(sizeof(struct selinux_mnt_opts), GFP_KERNEL);
2859 opts = fc->security;
2861 if (src->fscontext) {
2862 opts->fscontext = kstrdup(src->fscontext, GFP_KERNEL);
2863 if (!opts->fscontext)
2867 opts->context = kstrdup(src->context, GFP_KERNEL);
2871 if (src->rootcontext) {
2872 opts->rootcontext = kstrdup(src->rootcontext, GFP_KERNEL);
2873 if (!opts->rootcontext)
2876 if (src->defcontext) {
2877 opts->defcontext = kstrdup(src->defcontext, GFP_KERNEL);
2878 if (!opts->defcontext)
2884 static const struct fs_parameter_spec selinux_fs_parameters[] = {
2885 fsparam_string(CONTEXT_STR, Opt_context),
2886 fsparam_string(DEFCONTEXT_STR, Opt_defcontext),
2887 fsparam_string(FSCONTEXT_STR, Opt_fscontext),
2888 fsparam_string(ROOTCONTEXT_STR, Opt_rootcontext),
2889 fsparam_flag (SECLABEL_STR, Opt_seclabel),
2893 static int selinux_fs_context_parse_param(struct fs_context *fc,
2894 struct fs_parameter *param)
2896 struct fs_parse_result result;
2899 opt = fs_parse(fc, selinux_fs_parameters, param, &result);
2903 rc = selinux_add_opt(opt, param->string, &fc->security);
2905 param->string = NULL;
2911 /* inode security operations */
2913 static int selinux_inode_alloc_security(struct inode *inode)
2915 struct inode_security_struct *isec = selinux_inode(inode);
2916 u32 sid = current_sid();
2918 spin_lock_init(&isec->lock);
2919 INIT_LIST_HEAD(&isec->list);
2920 isec->inode = inode;
2921 isec->sid = SECINITSID_UNLABELED;
2922 isec->sclass = SECCLASS_FILE;
2923 isec->task_sid = sid;
2924 isec->initialized = LABEL_INVALID;
2929 static void selinux_inode_free_security(struct inode *inode)
2931 inode_free_security(inode);
2934 static int selinux_dentry_init_security(struct dentry *dentry, int mode,
2935 const struct qstr *name, void **ctx,
2941 rc = selinux_determine_inode_label(selinux_cred(current_cred()),
2942 d_inode(dentry->d_parent), name,
2943 inode_mode_to_security_class(mode),
2948 return security_sid_to_context(&selinux_state, newsid, (char **)ctx,
2952 static int selinux_dentry_create_files_as(struct dentry *dentry, int mode,
2954 const struct cred *old,
2959 struct task_security_struct *tsec;
2961 rc = selinux_determine_inode_label(selinux_cred(old),
2962 d_inode(dentry->d_parent), name,
2963 inode_mode_to_security_class(mode),
2968 tsec = selinux_cred(new);
2969 tsec->create_sid = newsid;
2973 static int selinux_inode_init_security(struct inode *inode, struct inode *dir,
2974 const struct qstr *qstr,
2976 void **value, size_t *len)
2978 const struct task_security_struct *tsec = selinux_cred(current_cred());
2979 struct superblock_security_struct *sbsec;
2984 sbsec = dir->i_sb->s_security;
2986 newsid = tsec->create_sid;
2988 rc = selinux_determine_inode_label(tsec, dir, qstr,
2989 inode_mode_to_security_class(inode->i_mode),
2994 /* Possibly defer initialization to selinux_complete_init. */
2995 if (sbsec->flags & SE_SBINITIALIZED) {
2996 struct inode_security_struct *isec = selinux_inode(inode);
2997 isec->sclass = inode_mode_to_security_class(inode->i_mode);
2999 isec->initialized = LABEL_INITIALIZED;
3002 if (!selinux_initialized(&selinux_state) ||
3003 !(sbsec->flags & SBLABEL_MNT))
3007 *name = XATTR_SELINUX_SUFFIX;
3010 rc = security_sid_to_context_force(&selinux_state, newsid,
3021 static int selinux_inode_init_security_anon(struct inode *inode,
3022 const struct qstr *name,
3023 const struct inode *context_inode)
3025 const struct task_security_struct *tsec = selinux_cred(current_cred());
3026 struct common_audit_data ad;
3027 struct inode_security_struct *isec;
3030 if (unlikely(!selinux_initialized(&selinux_state)))
3033 isec = selinux_inode(inode);
3036 * We only get here once per ephemeral inode. The inode has
3037 * been initialized via inode_alloc_security but is otherwise
3041 if (context_inode) {
3042 struct inode_security_struct *context_isec =
3043 selinux_inode(context_inode);
3044 if (context_isec->initialized != LABEL_INITIALIZED) {
3045 pr_err("SELinux: context_inode is not initialized");
3049 isec->sclass = context_isec->sclass;
3050 isec->sid = context_isec->sid;
3052 isec->sclass = SECCLASS_ANON_INODE;
3053 rc = security_transition_sid(
3054 &selinux_state, tsec->sid, tsec->sid,
3055 isec->sclass, name, &isec->sid);
3060 isec->initialized = LABEL_INITIALIZED;
3062 * Now that we've initialized security, check whether we're
3063 * allowed to actually create this type of anonymous inode.
3066 ad.type = LSM_AUDIT_DATA_INODE;
3069 return avc_has_perm(&selinux_state,
3077 static int selinux_inode_create(struct inode *dir, struct dentry *dentry, umode_t mode)
3079 return may_create(dir, dentry, SECCLASS_FILE);
3082 static int selinux_inode_link(struct dentry *old_dentry, struct inode *dir, struct dentry *new_dentry)
3084 return may_link(dir, old_dentry, MAY_LINK);
3087 static int selinux_inode_unlink(struct inode *dir, struct dentry *dentry)
3089 return may_link(dir, dentry, MAY_UNLINK);
3092 static int selinux_inode_symlink(struct inode *dir, struct dentry *dentry, const char *name)
3094 return may_create(dir, dentry, SECCLASS_LNK_FILE);
3097 static int selinux_inode_mkdir(struct inode *dir, struct dentry *dentry, umode_t mask)
3099 return may_create(dir, dentry, SECCLASS_DIR);
3102 static int selinux_inode_rmdir(struct inode *dir, struct dentry *dentry)
3104 return may_link(dir, dentry, MAY_RMDIR);
3107 static int selinux_inode_mknod(struct inode *dir, struct dentry *dentry, umode_t mode, dev_t dev)
3109 return may_create(dir, dentry, inode_mode_to_security_class(mode));
3112 static int selinux_inode_rename(struct inode *old_inode, struct dentry *old_dentry,
3113 struct inode *new_inode, struct dentry *new_dentry)
3115 return may_rename(old_inode, old_dentry, new_inode, new_dentry);
3118 static int selinux_inode_readlink(struct dentry *dentry)
3120 const struct cred *cred = current_cred();
3122 return dentry_has_perm(cred, dentry, FILE__READ);
3125 static int selinux_inode_follow_link(struct dentry *dentry, struct inode *inode,
3128 const struct cred *cred = current_cred();
3129 struct common_audit_data ad;
3130 struct inode_security_struct *isec;
3133 validate_creds(cred);
3135 ad.type = LSM_AUDIT_DATA_DENTRY;
3136 ad.u.dentry = dentry;
3137 sid = cred_sid(cred);
3138 isec = inode_security_rcu(inode, rcu);
3140 return PTR_ERR(isec);
3142 return avc_has_perm_flags(&selinux_state,
3143 sid, isec->sid, isec->sclass, FILE__READ, &ad,
3144 rcu ? MAY_NOT_BLOCK : 0);
3147 static noinline int audit_inode_permission(struct inode *inode,
3148 u32 perms, u32 audited, u32 denied,
3151 struct common_audit_data ad;
3152 struct inode_security_struct *isec = selinux_inode(inode);
3155 ad.type = LSM_AUDIT_DATA_INODE;
3158 rc = slow_avc_audit(&selinux_state,
3159 current_sid(), isec->sid, isec->sclass, perms,
3160 audited, denied, result, &ad);
3166 static int selinux_inode_permission(struct inode *inode, int mask)
3168 const struct cred *cred = current_cred();
3171 bool no_block = mask & MAY_NOT_BLOCK;
3172 struct inode_security_struct *isec;
3174 struct av_decision avd;
3176 u32 audited, denied;
3178 from_access = mask & MAY_ACCESS;
3179 mask &= (MAY_READ|MAY_WRITE|MAY_EXEC|MAY_APPEND);
3181 /* No permission to check. Existence test. */
3185 validate_creds(cred);
3187 if (unlikely(IS_PRIVATE(inode)))
3190 perms = file_mask_to_av(inode->i_mode, mask);
3192 sid = cred_sid(cred);
3193 isec = inode_security_rcu(inode, no_block);
3195 return PTR_ERR(isec);
3197 rc = avc_has_perm_noaudit(&selinux_state,
3198 sid, isec->sid, isec->sclass, perms,
3199 no_block ? AVC_NONBLOCKING : 0,
3201 audited = avc_audit_required(perms, &avd, rc,
3202 from_access ? FILE__AUDIT_ACCESS : 0,
3204 if (likely(!audited))
3207 /* fall back to ref-walk if we have to generate audit */
3211 rc2 = audit_inode_permission(inode, perms, audited, denied, rc);
3217 static int selinux_inode_setattr(struct dentry *dentry, struct iattr *iattr)
3219 const struct cred *cred = current_cred();
3220 struct inode *inode = d_backing_inode(dentry);
3221 unsigned int ia_valid = iattr->ia_valid;
3222 __u32 av = FILE__WRITE;
3224 /* ATTR_FORCE is just used for ATTR_KILL_S[UG]ID. */
3225 if (ia_valid & ATTR_FORCE) {
3226 ia_valid &= ~(ATTR_KILL_SUID | ATTR_KILL_SGID | ATTR_MODE |
3232 if (ia_valid & (ATTR_MODE | ATTR_UID | ATTR_GID |
3233 ATTR_ATIME_SET | ATTR_MTIME_SET | ATTR_TIMES_SET))
3234 return dentry_has_perm(cred, dentry, FILE__SETATTR);
3236 if (selinux_policycap_openperm() &&
3237 inode->i_sb->s_magic != SOCKFS_MAGIC &&
3238 (ia_valid & ATTR_SIZE) &&
3239 !(ia_valid & ATTR_FILE))
3242 return dentry_has_perm(cred, dentry, av);
3245 static int selinux_inode_getattr(const struct path *path)
3247 return path_has_perm(current_cred(), path, FILE__GETATTR);
3250 static bool has_cap_mac_admin(bool audit)
3252 const struct cred *cred = current_cred();
3253 unsigned int opts = audit ? CAP_OPT_NONE : CAP_OPT_NOAUDIT;
3255 if (cap_capable(cred, &init_user_ns, CAP_MAC_ADMIN, opts))
3257 if (cred_has_capability(cred, CAP_MAC_ADMIN, opts, true))
3262 static int selinux_inode_setxattr(struct user_namespace *mnt_userns,
3263 struct dentry *dentry, const char *name,
3264 const void *value, size_t size, int flags)
3266 struct inode *inode = d_backing_inode(dentry);
3267 struct inode_security_struct *isec;
3268 struct superblock_security_struct *sbsec;
3269 struct common_audit_data ad;
3270 u32 newsid, sid = current_sid();
3273 if (strcmp(name, XATTR_NAME_SELINUX)) {
3274 rc = cap_inode_setxattr(dentry, name, value, size, flags);
3278 /* Not an attribute we recognize, so just check the
3279 ordinary setattr permission. */
3280 return dentry_has_perm(current_cred(), dentry, FILE__SETATTR);
3283 if (!selinux_initialized(&selinux_state))
3284 return (inode_owner_or_capable(mnt_userns, inode) ? 0 : -EPERM);
3286 sbsec = inode->i_sb->s_security;
3287 if (!(sbsec->flags & SBLABEL_MNT))
3290 if (!inode_owner_or_capable(mnt_userns, inode))
3293 ad.type = LSM_AUDIT_DATA_DENTRY;
3294 ad.u.dentry = dentry;
3296 isec = backing_inode_security(dentry);
3297 rc = avc_has_perm(&selinux_state,
3298 sid, isec->sid, isec->sclass,
3299 FILE__RELABELFROM, &ad);
3303 rc = security_context_to_sid(&selinux_state, value, size, &newsid,
3305 if (rc == -EINVAL) {
3306 if (!has_cap_mac_admin(true)) {
3307 struct audit_buffer *ab;
3310 /* We strip a nul only if it is at the end, otherwise the
3311 * context contains a nul and we should audit that */
3313 const char *str = value;
3315 if (str[size - 1] == '\0')
3316 audit_size = size - 1;
3322 ab = audit_log_start(audit_context(),
3323 GFP_ATOMIC, AUDIT_SELINUX_ERR);
3324 audit_log_format(ab, "op=setxattr invalid_context=");
3325 audit_log_n_untrustedstring(ab, value, audit_size);
3330 rc = security_context_to_sid_force(&selinux_state, value,
3336 rc = avc_has_perm(&selinux_state,
3337 sid, newsid, isec->sclass,
3338 FILE__RELABELTO, &ad);
3342 rc = security_validate_transition(&selinux_state, isec->sid, newsid,
3347 return avc_has_perm(&selinux_state,
3350 SECCLASS_FILESYSTEM,
3351 FILESYSTEM__ASSOCIATE,
3355 static void selinux_inode_post_setxattr(struct dentry *dentry, const char *name,
3356 const void *value, size_t size,
3359 struct inode *inode = d_backing_inode(dentry);
3360 struct inode_security_struct *isec;
3364 if (strcmp(name, XATTR_NAME_SELINUX)) {
3365 /* Not an attribute we recognize, so nothing to do. */
3369 if (!selinux_initialized(&selinux_state)) {
3370 /* If we haven't even been initialized, then we can't validate
3371 * against a policy, so leave the label as invalid. It may
3372 * resolve to a valid label on the next revalidation try if
3373 * we've since initialized.
3378 rc = security_context_to_sid_force(&selinux_state, value, size,
3381 pr_err("SELinux: unable to map context to SID"
3382 "for (%s, %lu), rc=%d\n",
3383 inode->i_sb->s_id, inode->i_ino, -rc);
3387 isec = backing_inode_security(dentry);
3388 spin_lock(&isec->lock);
3389 isec->sclass = inode_mode_to_security_class(inode->i_mode);
3391 isec->initialized = LABEL_INITIALIZED;
3392 spin_unlock(&isec->lock);
3397 static int selinux_inode_getxattr(struct dentry *dentry, const char *name)
3399 const struct cred *cred = current_cred();
3401 return dentry_has_perm(cred, dentry, FILE__GETATTR);
3404 static int selinux_inode_listxattr(struct dentry *dentry)
3406 const struct cred *cred = current_cred();
3408 return dentry_has_perm(cred, dentry, FILE__GETATTR);
3411 static int selinux_inode_removexattr(struct user_namespace *mnt_userns,
3412 struct dentry *dentry, const char *name)
3414 if (strcmp(name, XATTR_NAME_SELINUX)) {
3415 int rc = cap_inode_removexattr(mnt_userns, dentry, name);
3419 /* Not an attribute we recognize, so just check the
3420 ordinary setattr permission. */
3421 return dentry_has_perm(current_cred(), dentry, FILE__SETATTR);
3424 if (!selinux_initialized(&selinux_state))
3427 /* No one is allowed to remove a SELinux security label.
3428 You can change the label, but all data must be labeled. */
3432 static int selinux_path_notify(const struct path *path, u64 mask,
3433 unsigned int obj_type)
3438 struct common_audit_data ad;
3440 ad.type = LSM_AUDIT_DATA_PATH;
3444 * Set permission needed based on the type of mark being set.
3445 * Performs an additional check for sb watches.
3448 case FSNOTIFY_OBJ_TYPE_VFSMOUNT:
3449 perm = FILE__WATCH_MOUNT;
3451 case FSNOTIFY_OBJ_TYPE_SB:
3452 perm = FILE__WATCH_SB;
3453 ret = superblock_has_perm(current_cred(), path->dentry->d_sb,
3454 FILESYSTEM__WATCH, &ad);
3458 case FSNOTIFY_OBJ_TYPE_INODE:
3465 /* blocking watches require the file:watch_with_perm permission */
3466 if (mask & (ALL_FSNOTIFY_PERM_EVENTS))
3467 perm |= FILE__WATCH_WITH_PERM;
3469 /* watches on read-like events need the file:watch_reads permission */
3470 if (mask & (FS_ACCESS | FS_ACCESS_PERM | FS_CLOSE_NOWRITE))
3471 perm |= FILE__WATCH_READS;
3473 return path_has_perm(current_cred(), path, perm);
3477 * Copy the inode security context value to the user.
3479 * Permission check is handled by selinux_inode_getxattr hook.
3481 static int selinux_inode_getsecurity(struct user_namespace *mnt_userns,
3482 struct inode *inode, const char *name,
3483 void **buffer, bool alloc)
3487 char *context = NULL;
3488 struct inode_security_struct *isec;
3491 * If we're not initialized yet, then we can't validate contexts, so
3492 * just let vfs_getxattr fall back to using the on-disk xattr.
3494 if (!selinux_initialized(&selinux_state) ||
3495 strcmp(name, XATTR_SELINUX_SUFFIX))
3499 * If the caller has CAP_MAC_ADMIN, then get the raw context
3500 * value even if it is not defined by current policy; otherwise,
3501 * use the in-core value under current policy.
3502 * Use the non-auditing forms of the permission checks since
3503 * getxattr may be called by unprivileged processes commonly
3504 * and lack of permission just means that we fall back to the
3505 * in-core context value, not a denial.
3507 isec = inode_security(inode);
3508 if (has_cap_mac_admin(false))
3509 error = security_sid_to_context_force(&selinux_state,
3510 isec->sid, &context,
3513 error = security_sid_to_context(&selinux_state, isec->sid,
3527 static int selinux_inode_setsecurity(struct inode *inode, const char *name,
3528 const void *value, size_t size, int flags)
3530 struct inode_security_struct *isec = inode_security_novalidate(inode);
3531 struct superblock_security_struct *sbsec = inode->i_sb->s_security;
3535 if (strcmp(name, XATTR_SELINUX_SUFFIX))
3538 if (!(sbsec->flags & SBLABEL_MNT))
3541 if (!value || !size)
3544 rc = security_context_to_sid(&selinux_state, value, size, &newsid,
3549 spin_lock(&isec->lock);
3550 isec->sclass = inode_mode_to_security_class(inode->i_mode);
3552 isec->initialized = LABEL_INITIALIZED;
3553 spin_unlock(&isec->lock);
3557 static int selinux_inode_listsecurity(struct inode *inode, char *buffer, size_t buffer_size)
3559 const int len = sizeof(XATTR_NAME_SELINUX);
3561 if (!selinux_initialized(&selinux_state))
3564 if (buffer && len <= buffer_size)
3565 memcpy(buffer, XATTR_NAME_SELINUX, len);
3569 static void selinux_inode_getsecid(struct inode *inode, u32 *secid)
3571 struct inode_security_struct *isec = inode_security_novalidate(inode);
3575 static int selinux_inode_copy_up(struct dentry *src, struct cred **new)
3578 struct task_security_struct *tsec;
3579 struct cred *new_creds = *new;
3581 if (new_creds == NULL) {
3582 new_creds = prepare_creds();
3587 tsec = selinux_cred(new_creds);
3588 /* Get label from overlay inode and set it in create_sid */
3589 selinux_inode_getsecid(d_inode(src), &sid);
3590 tsec->create_sid = sid;
3595 static int selinux_inode_copy_up_xattr(const char *name)
3597 /* The copy_up hook above sets the initial context on an inode, but we
3598 * don't then want to overwrite it by blindly copying all the lower
3599 * xattrs up. Instead, we have to filter out SELinux-related xattrs.
3601 if (strcmp(name, XATTR_NAME_SELINUX) == 0)
3602 return 1; /* Discard */
3604 * Any other attribute apart from SELINUX is not claimed, supported
3610 /* kernfs node operations */
3612 static int selinux_kernfs_init_security(struct kernfs_node *kn_dir,
3613 struct kernfs_node *kn)
3615 const struct task_security_struct *tsec = selinux_cred(current_cred());
3616 u32 parent_sid, newsid, clen;
3620 rc = kernfs_xattr_get(kn_dir, XATTR_NAME_SELINUX, NULL, 0);
3627 context = kmalloc(clen, GFP_KERNEL);
3631 rc = kernfs_xattr_get(kn_dir, XATTR_NAME_SELINUX, context, clen);
3637 rc = security_context_to_sid(&selinux_state, context, clen, &parent_sid,
3643 if (tsec->create_sid) {
3644 newsid = tsec->create_sid;
3646 u16 secclass = inode_mode_to_security_class(kn->mode);
3650 q.hash_len = hashlen_string(kn_dir, kn->name);
3652 rc = security_transition_sid(&selinux_state, tsec->sid,
3653 parent_sid, secclass, &q,
3659 rc = security_sid_to_context_force(&selinux_state, newsid,
3664 rc = kernfs_xattr_set(kn, XATTR_NAME_SELINUX, context, clen,
3671 /* file security operations */
3673 static int selinux_revalidate_file_permission(struct file *file, int mask)
3675 const struct cred *cred = current_cred();
3676 struct inode *inode = file_inode(file);
3678 /* file_mask_to_av won't add FILE__WRITE if MAY_APPEND is set */
3679 if ((file->f_flags & O_APPEND) && (mask & MAY_WRITE))
3682 return file_has_perm(cred, file,
3683 file_mask_to_av(inode->i_mode, mask));
3686 static int selinux_file_permission(struct file *file, int mask)
3688 struct inode *inode = file_inode(file);
3689 struct file_security_struct *fsec = selinux_file(file);
3690 struct inode_security_struct *isec;
3691 u32 sid = current_sid();
3694 /* No permission to check. Existence test. */
3697 isec = inode_security(inode);
3698 if (sid == fsec->sid && fsec->isid == isec->sid &&
3699 fsec->pseqno == avc_policy_seqno(&selinux_state))
3700 /* No change since file_open check. */
3703 return selinux_revalidate_file_permission(file, mask);
3706 static int selinux_file_alloc_security(struct file *file)
3708 struct file_security_struct *fsec = selinux_file(file);
3709 u32 sid = current_sid();
3712 fsec->fown_sid = sid;
3718 * Check whether a task has the ioctl permission and cmd
3719 * operation to an inode.
3721 static int ioctl_has_perm(const struct cred *cred, struct file *file,
3722 u32 requested, u16 cmd)
3724 struct common_audit_data ad;
3725 struct file_security_struct *fsec = selinux_file(file);
3726 struct inode *inode = file_inode(file);
3727 struct inode_security_struct *isec;
3728 struct lsm_ioctlop_audit ioctl;
3729 u32 ssid = cred_sid(cred);
3731 u8 driver = cmd >> 8;
3732 u8 xperm = cmd & 0xff;
3734 ad.type = LSM_AUDIT_DATA_IOCTL_OP;
3737 ad.u.op->path = file->f_path;
3739 if (ssid != fsec->sid) {
3740 rc = avc_has_perm(&selinux_state,
3749 if (unlikely(IS_PRIVATE(inode)))
3752 isec = inode_security(inode);
3753 rc = avc_has_extended_perms(&selinux_state,
3754 ssid, isec->sid, isec->sclass,
3755 requested, driver, xperm, &ad);
3760 static int selinux_file_ioctl(struct file *file, unsigned int cmd,
3763 const struct cred *cred = current_cred();
3770 case FS_IOC_GETFLAGS:
3771 case FS_IOC_GETVERSION:
3772 error = file_has_perm(cred, file, FILE__GETATTR);
3775 case FS_IOC_SETFLAGS:
3776 case FS_IOC_SETVERSION:
3777 error = file_has_perm(cred, file, FILE__SETATTR);
3780 /* sys_ioctl() checks */
3783 error = file_has_perm(cred, file, 0);
3788 error = cred_has_capability(cred, CAP_SYS_TTY_CONFIG,
3789 CAP_OPT_NONE, true);
3792 /* default case assumes that the command will go
3793 * to the file's ioctl() function.
3796 error = ioctl_has_perm(cred, file, FILE__IOCTL, (u16) cmd);
3801 static int default_noexec __ro_after_init;
3803 static int file_map_prot_check(struct file *file, unsigned long prot, int shared)
3805 const struct cred *cred = current_cred();
3806 u32 sid = cred_sid(cred);
3809 if (default_noexec &&
3810 (prot & PROT_EXEC) && (!file || IS_PRIVATE(file_inode(file)) ||
3811 (!shared && (prot & PROT_WRITE)))) {
3813 * We are making executable an anonymous mapping or a
3814 * private file mapping that will also be writable.
3815 * This has an additional check.
3817 rc = avc_has_perm(&selinux_state,
3818 sid, sid, SECCLASS_PROCESS,
3819 PROCESS__EXECMEM, NULL);
3825 /* read access is always possible with a mapping */
3826 u32 av = FILE__READ;
3828 /* write access only matters if the mapping is shared */
3829 if (shared && (prot & PROT_WRITE))
3832 if (prot & PROT_EXEC)
3833 av |= FILE__EXECUTE;
3835 return file_has_perm(cred, file, av);
3842 static int selinux_mmap_addr(unsigned long addr)
3846 if (addr < CONFIG_LSM_MMAP_MIN_ADDR) {
3847 u32 sid = current_sid();
3848 rc = avc_has_perm(&selinux_state,
3849 sid, sid, SECCLASS_MEMPROTECT,
3850 MEMPROTECT__MMAP_ZERO, NULL);
3856 static int selinux_mmap_file(struct file *file, unsigned long reqprot,
3857 unsigned long prot, unsigned long flags)
3859 struct common_audit_data ad;
3863 ad.type = LSM_AUDIT_DATA_FILE;
3865 rc = inode_has_perm(current_cred(), file_inode(file),
3871 if (checkreqprot_get(&selinux_state))
3874 return file_map_prot_check(file, prot,
3875 (flags & MAP_TYPE) == MAP_SHARED);
3878 static int selinux_file_mprotect(struct vm_area_struct *vma,
3879 unsigned long reqprot,
3882 const struct cred *cred = current_cred();
3883 u32 sid = cred_sid(cred);
3885 if (checkreqprot_get(&selinux_state))
3888 if (default_noexec &&
3889 (prot & PROT_EXEC) && !(vma->vm_flags & VM_EXEC)) {
3891 if (vma->vm_start >= vma->vm_mm->start_brk &&
3892 vma->vm_end <= vma->vm_mm->brk) {
3893 rc = avc_has_perm(&selinux_state,
3894 sid, sid, SECCLASS_PROCESS,
3895 PROCESS__EXECHEAP, NULL);
3896 } else if (!vma->vm_file &&
3897 ((vma->vm_start <= vma->vm_mm->start_stack &&
3898 vma->vm_end >= vma->vm_mm->start_stack) ||
3899 vma_is_stack_for_current(vma))) {
3900 rc = avc_has_perm(&selinux_state,
3901 sid, sid, SECCLASS_PROCESS,
3902 PROCESS__EXECSTACK, NULL);
3903 } else if (vma->vm_file && vma->anon_vma) {
3905 * We are making executable a file mapping that has
3906 * had some COW done. Since pages might have been
3907 * written, check ability to execute the possibly
3908 * modified content. This typically should only
3909 * occur for text relocations.
3911 rc = file_has_perm(cred, vma->vm_file, FILE__EXECMOD);
3917 return file_map_prot_check(vma->vm_file, prot, vma->vm_flags&VM_SHARED);
3920 static int selinux_file_lock(struct file *file, unsigned int cmd)
3922 const struct cred *cred = current_cred();
3924 return file_has_perm(cred, file, FILE__LOCK);
3927 static int selinux_file_fcntl(struct file *file, unsigned int cmd,
3930 const struct cred *cred = current_cred();
3935 if ((file->f_flags & O_APPEND) && !(arg & O_APPEND)) {
3936 err = file_has_perm(cred, file, FILE__WRITE);
3945 case F_GETOWNER_UIDS:
3946 /* Just check FD__USE permission */
3947 err = file_has_perm(cred, file, 0);
3955 #if BITS_PER_LONG == 32
3960 err = file_has_perm(cred, file, FILE__LOCK);
3967 static void selinux_file_set_fowner(struct file *file)
3969 struct file_security_struct *fsec;
3971 fsec = selinux_file(file);
3972 fsec->fown_sid = current_sid();
3975 static int selinux_file_send_sigiotask(struct task_struct *tsk,
3976 struct fown_struct *fown, int signum)
3979 u32 sid = task_sid(tsk);
3981 struct file_security_struct *fsec;
3983 /* struct fown_struct is never outside the context of a struct file */
3984 file = container_of(fown, struct file, f_owner);
3986 fsec = selinux_file(file);
3989 perm = signal_to_av(SIGIO); /* as per send_sigio_to_task */
3991 perm = signal_to_av(signum);
3993 return avc_has_perm(&selinux_state,
3994 fsec->fown_sid, sid,
3995 SECCLASS_PROCESS, perm, NULL);
3998 static int selinux_file_receive(struct file *file)
4000 const struct cred *cred = current_cred();
4002 return file_has_perm(cred, file, file_to_av(file));
4005 static int selinux_file_open(struct file *file)
4007 struct file_security_struct *fsec;
4008 struct inode_security_struct *isec;
4010 fsec = selinux_file(file);
4011 isec = inode_security(file_inode(file));
4013 * Save inode label and policy sequence number
4014 * at open-time so that selinux_file_permission
4015 * can determine whether revalidation is necessary.
4016 * Task label is already saved in the file security
4017 * struct as its SID.
4019 fsec->isid = isec->sid;
4020 fsec->pseqno = avc_policy_seqno(&selinux_state);
4022 * Since the inode label or policy seqno may have changed
4023 * between the selinux_inode_permission check and the saving
4024 * of state above, recheck that access is still permitted.
4025 * Otherwise, access might never be revalidated against the
4026 * new inode label or new policy.
4027 * This check is not redundant - do not remove.
4029 return file_path_has_perm(file->f_cred, file, open_file_to_av(file));
4032 /* task security operations */
4034 static int selinux_task_alloc(struct task_struct *task,
4035 unsigned long clone_flags)
4037 u32 sid = current_sid();
4039 return avc_has_perm(&selinux_state,
4040 sid, sid, SECCLASS_PROCESS, PROCESS__FORK, NULL);
4044 * prepare a new set of credentials for modification
4046 static int selinux_cred_prepare(struct cred *new, const struct cred *old,
4049 const struct task_security_struct *old_tsec = selinux_cred(old);
4050 struct task_security_struct *tsec = selinux_cred(new);
4057 * transfer the SELinux data to a blank set of creds
4059 static void selinux_cred_transfer(struct cred *new, const struct cred *old)
4061 const struct task_security_struct *old_tsec = selinux_cred(old);
4062 struct task_security_struct *tsec = selinux_cred(new);
4067 static void selinux_cred_getsecid(const struct cred *c, u32 *secid)
4069 *secid = cred_sid(c);
4073 * set the security data for a kernel service
4074 * - all the creation contexts are set to unlabelled
4076 static int selinux_kernel_act_as(struct cred *new, u32 secid)
4078 struct task_security_struct *tsec = selinux_cred(new);
4079 u32 sid = current_sid();
4082 ret = avc_has_perm(&selinux_state,
4084 SECCLASS_KERNEL_SERVICE,
4085 KERNEL_SERVICE__USE_AS_OVERRIDE,
4089 tsec->create_sid = 0;
4090 tsec->keycreate_sid = 0;
4091 tsec->sockcreate_sid = 0;
4097 * set the file creation context in a security record to the same as the
4098 * objective context of the specified inode
4100 static int selinux_kernel_create_files_as(struct cred *new, struct inode *inode)
4102 struct inode_security_struct *isec = inode_security(inode);
4103 struct task_security_struct *tsec = selinux_cred(new);
4104 u32 sid = current_sid();
4107 ret = avc_has_perm(&selinux_state,
4109 SECCLASS_KERNEL_SERVICE,
4110 KERNEL_SERVICE__CREATE_FILES_AS,
4114 tsec->create_sid = isec->sid;
4118 static int selinux_kernel_module_request(char *kmod_name)
4120 struct common_audit_data ad;
4122 ad.type = LSM_AUDIT_DATA_KMOD;
4123 ad.u.kmod_name = kmod_name;
4125 return avc_has_perm(&selinux_state,
4126 current_sid(), SECINITSID_KERNEL, SECCLASS_SYSTEM,
4127 SYSTEM__MODULE_REQUEST, &ad);
4130 static int selinux_kernel_module_from_file(struct file *file)
4132 struct common_audit_data ad;
4133 struct inode_security_struct *isec;
4134 struct file_security_struct *fsec;
4135 u32 sid = current_sid();
4140 return avc_has_perm(&selinux_state,
4141 sid, sid, SECCLASS_SYSTEM,
4142 SYSTEM__MODULE_LOAD, NULL);
4146 ad.type = LSM_AUDIT_DATA_FILE;
4149 fsec = selinux_file(file);
4150 if (sid != fsec->sid) {
4151 rc = avc_has_perm(&selinux_state,
4152 sid, fsec->sid, SECCLASS_FD, FD__USE, &ad);
4157 isec = inode_security(file_inode(file));
4158 return avc_has_perm(&selinux_state,
4159 sid, isec->sid, SECCLASS_SYSTEM,
4160 SYSTEM__MODULE_LOAD, &ad);
4163 static int selinux_kernel_read_file(struct file *file,
4164 enum kernel_read_file_id id,
4170 case READING_MODULE:
4171 rc = selinux_kernel_module_from_file(contents ? file : NULL);
4180 static int selinux_kernel_load_data(enum kernel_load_data_id id, bool contents)
4185 case LOADING_MODULE:
4186 rc = selinux_kernel_module_from_file(NULL);
4195 static int selinux_task_setpgid(struct task_struct *p, pid_t pgid)
4197 return avc_has_perm(&selinux_state,
4198 current_sid(), task_sid(p), SECCLASS_PROCESS,
4199 PROCESS__SETPGID, NULL);
4202 static int selinux_task_getpgid(struct task_struct *p)
4204 return avc_has_perm(&selinux_state,
4205 current_sid(), task_sid(p), SECCLASS_PROCESS,
4206 PROCESS__GETPGID, NULL);
4209 static int selinux_task_getsid(struct task_struct *p)
4211 return avc_has_perm(&selinux_state,
4212 current_sid(), task_sid(p), SECCLASS_PROCESS,
4213 PROCESS__GETSESSION, NULL);
4216 static void selinux_task_getsecid(struct task_struct *p, u32 *secid)
4218 *secid = task_sid(p);
4221 static int selinux_task_setnice(struct task_struct *p, int nice)
4223 return avc_has_perm(&selinux_state,
4224 current_sid(), task_sid(p), SECCLASS_PROCESS,
4225 PROCESS__SETSCHED, NULL);
4228 static int selinux_task_setioprio(struct task_struct *p, int ioprio)
4230 return avc_has_perm(&selinux_state,
4231 current_sid(), task_sid(p), SECCLASS_PROCESS,
4232 PROCESS__SETSCHED, NULL);
4235 static int selinux_task_getioprio(struct task_struct *p)
4237 return avc_has_perm(&selinux_state,
4238 current_sid(), task_sid(p), SECCLASS_PROCESS,
4239 PROCESS__GETSCHED, NULL);
4242 static int selinux_task_prlimit(const struct cred *cred, const struct cred *tcred,
4249 if (flags & LSM_PRLIMIT_WRITE)
4250 av |= PROCESS__SETRLIMIT;
4251 if (flags & LSM_PRLIMIT_READ)
4252 av |= PROCESS__GETRLIMIT;
4253 return avc_has_perm(&selinux_state,
4254 cred_sid(cred), cred_sid(tcred),
4255 SECCLASS_PROCESS, av, NULL);
4258 static int selinux_task_setrlimit(struct task_struct *p, unsigned int resource,
4259 struct rlimit *new_rlim)
4261 struct rlimit *old_rlim = p->signal->rlim + resource;
4263 /* Control the ability to change the hard limit (whether
4264 lowering or raising it), so that the hard limit can
4265 later be used as a safe reset point for the soft limit
4266 upon context transitions. See selinux_bprm_committing_creds. */
4267 if (old_rlim->rlim_max != new_rlim->rlim_max)
4268 return avc_has_perm(&selinux_state,
4269 current_sid(), task_sid(p),
4270 SECCLASS_PROCESS, PROCESS__SETRLIMIT, NULL);
4275 static int selinux_task_setscheduler(struct task_struct *p)
4277 return avc_has_perm(&selinux_state,
4278 current_sid(), task_sid(p), SECCLASS_PROCESS,
4279 PROCESS__SETSCHED, NULL);
4282 static int selinux_task_getscheduler(struct task_struct *p)
4284 return avc_has_perm(&selinux_state,
4285 current_sid(), task_sid(p), SECCLASS_PROCESS,
4286 PROCESS__GETSCHED, NULL);
4289 static int selinux_task_movememory(struct task_struct *p)
4291 return avc_has_perm(&selinux_state,
4292 current_sid(), task_sid(p), SECCLASS_PROCESS,
4293 PROCESS__SETSCHED, NULL);
4296 static int selinux_task_kill(struct task_struct *p, struct kernel_siginfo *info,
4297 int sig, const struct cred *cred)
4303 perm = PROCESS__SIGNULL; /* null signal; existence test */
4305 perm = signal_to_av(sig);
4307 secid = current_sid();
4309 secid = cred_sid(cred);
4310 return avc_has_perm(&selinux_state,
4311 secid, task_sid(p), SECCLASS_PROCESS, perm, NULL);
4314 static void selinux_task_to_inode(struct task_struct *p,
4315 struct inode *inode)
4317 struct inode_security_struct *isec = selinux_inode(inode);
4318 u32 sid = task_sid(p);
4320 spin_lock(&isec->lock);
4321 isec->sclass = inode_mode_to_security_class(inode->i_mode);
4323 isec->initialized = LABEL_INITIALIZED;
4324 spin_unlock(&isec->lock);
4327 /* Returns error only if unable to parse addresses */
4328 static int selinux_parse_skb_ipv4(struct sk_buff *skb,
4329 struct common_audit_data *ad, u8 *proto)
4331 int offset, ihlen, ret = -EINVAL;
4332 struct iphdr _iph, *ih;
4334 offset = skb_network_offset(skb);
4335 ih = skb_header_pointer(skb, offset, sizeof(_iph), &_iph);
4339 ihlen = ih->ihl * 4;
4340 if (ihlen < sizeof(_iph))
4343 ad->u.net->v4info.saddr = ih->saddr;
4344 ad->u.net->v4info.daddr = ih->daddr;
4348 *proto = ih->protocol;
4350 switch (ih->protocol) {
4352 struct tcphdr _tcph, *th;
4354 if (ntohs(ih->frag_off) & IP_OFFSET)
4358 th = skb_header_pointer(skb, offset, sizeof(_tcph), &_tcph);
4362 ad->u.net->sport = th->source;
4363 ad->u.net->dport = th->dest;
4368 struct udphdr _udph, *uh;
4370 if (ntohs(ih->frag_off) & IP_OFFSET)
4374 uh = skb_header_pointer(skb, offset, sizeof(_udph), &_udph);
4378 ad->u.net->sport = uh->source;
4379 ad->u.net->dport = uh->dest;
4383 case IPPROTO_DCCP: {
4384 struct dccp_hdr _dccph, *dh;
4386 if (ntohs(ih->frag_off) & IP_OFFSET)
4390 dh = skb_header_pointer(skb, offset, sizeof(_dccph), &_dccph);
4394 ad->u.net->sport = dh->dccph_sport;
4395 ad->u.net->dport = dh->dccph_dport;
4399 #if IS_ENABLED(CONFIG_IP_SCTP)
4400 case IPPROTO_SCTP: {
4401 struct sctphdr _sctph, *sh;
4403 if (ntohs(ih->frag_off) & IP_OFFSET)
4407 sh = skb_header_pointer(skb, offset, sizeof(_sctph), &_sctph);
4411 ad->u.net->sport = sh->source;
4412 ad->u.net->dport = sh->dest;
4423 #if IS_ENABLED(CONFIG_IPV6)
4425 /* Returns error only if unable to parse addresses */
4426 static int selinux_parse_skb_ipv6(struct sk_buff *skb,
4427 struct common_audit_data *ad, u8 *proto)
4430 int ret = -EINVAL, offset;
4431 struct ipv6hdr _ipv6h, *ip6;
4434 offset = skb_network_offset(skb);
4435 ip6 = skb_header_pointer(skb, offset, sizeof(_ipv6h), &_ipv6h);
4439 ad->u.net->v6info.saddr = ip6->saddr;
4440 ad->u.net->v6info.daddr = ip6->daddr;
4443 nexthdr = ip6->nexthdr;
4444 offset += sizeof(_ipv6h);
4445 offset = ipv6_skip_exthdr(skb, offset, &nexthdr, &frag_off);
4454 struct tcphdr _tcph, *th;
4456 th = skb_header_pointer(skb, offset, sizeof(_tcph), &_tcph);
4460 ad->u.net->sport = th->source;
4461 ad->u.net->dport = th->dest;
4466 struct udphdr _udph, *uh;
4468 uh = skb_header_pointer(skb, offset, sizeof(_udph), &_udph);
4472 ad->u.net->sport = uh->source;
4473 ad->u.net->dport = uh->dest;
4477 case IPPROTO_DCCP: {
4478 struct dccp_hdr _dccph, *dh;
4480 dh = skb_header_pointer(skb, offset, sizeof(_dccph), &_dccph);
4484 ad->u.net->sport = dh->dccph_sport;
4485 ad->u.net->dport = dh->dccph_dport;
4489 #if IS_ENABLED(CONFIG_IP_SCTP)
4490 case IPPROTO_SCTP: {
4491 struct sctphdr _sctph, *sh;
4493 sh = skb_header_pointer(skb, offset, sizeof(_sctph), &_sctph);
4497 ad->u.net->sport = sh->source;
4498 ad->u.net->dport = sh->dest;
4502 /* includes fragments */
4512 static int selinux_parse_skb(struct sk_buff *skb, struct common_audit_data *ad,
4513 char **_addrp, int src, u8 *proto)
4518 switch (ad->u.net->family) {
4520 ret = selinux_parse_skb_ipv4(skb, ad, proto);
4523 addrp = (char *)(src ? &ad->u.net->v4info.saddr :
4524 &ad->u.net->v4info.daddr);
4527 #if IS_ENABLED(CONFIG_IPV6)
4529 ret = selinux_parse_skb_ipv6(skb, ad, proto);
4532 addrp = (char *)(src ? &ad->u.net->v6info.saddr :
4533 &ad->u.net->v6info.daddr);
4543 "SELinux: failure in selinux_parse_skb(),"
4544 " unable to parse packet\n");
4554 * selinux_skb_peerlbl_sid - Determine the peer label of a packet
4556 * @family: protocol family
4557 * @sid: the packet's peer label SID
4560 * Check the various different forms of network peer labeling and determine
4561 * the peer label/SID for the packet; most of the magic actually occurs in
4562 * the security server function security_net_peersid_cmp(). The function
4563 * returns zero if the value in @sid is valid (although it may be SECSID_NULL)
4564 * or -EACCES if @sid is invalid due to inconsistencies with the different
4568 static int selinux_skb_peerlbl_sid(struct sk_buff *skb, u16 family, u32 *sid)
4575 err = selinux_xfrm_skb_sid(skb, &xfrm_sid);
4578 err = selinux_netlbl_skbuff_getsid(skb, family, &nlbl_type, &nlbl_sid);
4582 err = security_net_peersid_resolve(&selinux_state, nlbl_sid,
4583 nlbl_type, xfrm_sid, sid);
4584 if (unlikely(err)) {
4586 "SELinux: failure in selinux_skb_peerlbl_sid(),"
4587 " unable to determine packet's peer label\n");
4595 * selinux_conn_sid - Determine the child socket label for a connection
4596 * @sk_sid: the parent socket's SID
4597 * @skb_sid: the packet's SID
4598 * @conn_sid: the resulting connection SID
4600 * If @skb_sid is valid then the user:role:type information from @sk_sid is
4601 * combined with the MLS information from @skb_sid in order to create
4602 * @conn_sid. If @skb_sid is not valid then @conn_sid is simply a copy
4603 * of @sk_sid. Returns zero on success, negative values on failure.
4606 static int selinux_conn_sid(u32 sk_sid, u32 skb_sid, u32 *conn_sid)
4610 if (skb_sid != SECSID_NULL)
4611 err = security_sid_mls_copy(&selinux_state, sk_sid, skb_sid,
4619 /* socket security operations */
4621 static int socket_sockcreate_sid(const struct task_security_struct *tsec,
4622 u16 secclass, u32 *socksid)
4624 if (tsec->sockcreate_sid > SECSID_NULL) {
4625 *socksid = tsec->sockcreate_sid;
4629 return security_transition_sid(&selinux_state, tsec->sid, tsec->sid,
4630 secclass, NULL, socksid);
4633 static int sock_has_perm(struct sock *sk, u32 perms)
4635 struct sk_security_struct *sksec = sk->sk_security;
4636 struct common_audit_data ad;
4637 struct lsm_network_audit net = {0,};
4639 if (sksec->sid == SECINITSID_KERNEL)
4642 ad.type = LSM_AUDIT_DATA_NET;
4646 return avc_has_perm(&selinux_state,
4647 current_sid(), sksec->sid, sksec->sclass, perms,
4651 static int selinux_socket_create(int family, int type,
4652 int protocol, int kern)
4654 const struct task_security_struct *tsec = selinux_cred(current_cred());
4662 secclass = socket_type_to_security_class(family, type, protocol);
4663 rc = socket_sockcreate_sid(tsec, secclass, &newsid);
4667 return avc_has_perm(&selinux_state,
4668 tsec->sid, newsid, secclass, SOCKET__CREATE, NULL);
4671 static int selinux_socket_post_create(struct socket *sock, int family,
4672 int type, int protocol, int kern)
4674 const struct task_security_struct *tsec = selinux_cred(current_cred());
4675 struct inode_security_struct *isec = inode_security_novalidate(SOCK_INODE(sock));
4676 struct sk_security_struct *sksec;
4677 u16 sclass = socket_type_to_security_class(family, type, protocol);
4678 u32 sid = SECINITSID_KERNEL;
4682 err = socket_sockcreate_sid(tsec, sclass, &sid);
4687 isec->sclass = sclass;
4689 isec->initialized = LABEL_INITIALIZED;
4692 sksec = sock->sk->sk_security;
4693 sksec->sclass = sclass;
4695 /* Allows detection of the first association on this socket */
4696 if (sksec->sclass == SECCLASS_SCTP_SOCKET)
4697 sksec->sctp_assoc_state = SCTP_ASSOC_UNSET;
4699 err = selinux_netlbl_socket_post_create(sock->sk, family);
4705 static int selinux_socket_socketpair(struct socket *socka,
4706 struct socket *sockb)
4708 struct sk_security_struct *sksec_a = socka->sk->sk_security;
4709 struct sk_security_struct *sksec_b = sockb->sk->sk_security;
4711 sksec_a->peer_sid = sksec_b->sid;
4712 sksec_b->peer_sid = sksec_a->sid;
4717 /* Range of port numbers used to automatically bind.
4718 Need to determine whether we should perform a name_bind
4719 permission check between the socket and the port number. */
4721 static int selinux_socket_bind(struct socket *sock, struct sockaddr *address, int addrlen)
4723 struct sock *sk = sock->sk;
4724 struct sk_security_struct *sksec = sk->sk_security;
4728 err = sock_has_perm(sk, SOCKET__BIND);
4732 /* If PF_INET or PF_INET6, check name_bind permission for the port. */
4733 family = sk->sk_family;
4734 if (family == PF_INET || family == PF_INET6) {
4736 struct common_audit_data ad;
4737 struct lsm_network_audit net = {0,};
4738 struct sockaddr_in *addr4 = NULL;
4739 struct sockaddr_in6 *addr6 = NULL;
4741 unsigned short snum;
4745 * sctp_bindx(3) calls via selinux_sctp_bind_connect()
4746 * that validates multiple binding addresses. Because of this
4747 * need to check address->sa_family as it is possible to have
4748 * sk->sk_family = PF_INET6 with addr->sa_family = AF_INET.
4750 if (addrlen < offsetofend(struct sockaddr, sa_family))
4752 family_sa = address->sa_family;
4753 switch (family_sa) {
4756 if (addrlen < sizeof(struct sockaddr_in))
4758 addr4 = (struct sockaddr_in *)address;
4759 if (family_sa == AF_UNSPEC) {
4760 /* see __inet_bind(), we only want to allow
4761 * AF_UNSPEC if the address is INADDR_ANY
4763 if (addr4->sin_addr.s_addr != htonl(INADDR_ANY))
4765 family_sa = AF_INET;
4767 snum = ntohs(addr4->sin_port);
4768 addrp = (char *)&addr4->sin_addr.s_addr;
4771 if (addrlen < SIN6_LEN_RFC2133)
4773 addr6 = (struct sockaddr_in6 *)address;
4774 snum = ntohs(addr6->sin6_port);
4775 addrp = (char *)&addr6->sin6_addr.s6_addr;
4781 ad.type = LSM_AUDIT_DATA_NET;
4783 ad.u.net->sport = htons(snum);
4784 ad.u.net->family = family_sa;
4789 inet_get_local_port_range(sock_net(sk), &low, &high);
4791 if (inet_port_requires_bind_service(sock_net(sk), snum) ||
4792 snum < low || snum > high) {
4793 err = sel_netport_sid(sk->sk_protocol,
4797 err = avc_has_perm(&selinux_state,
4800 SOCKET__NAME_BIND, &ad);
4806 switch (sksec->sclass) {
4807 case SECCLASS_TCP_SOCKET:
4808 node_perm = TCP_SOCKET__NODE_BIND;
4811 case SECCLASS_UDP_SOCKET:
4812 node_perm = UDP_SOCKET__NODE_BIND;
4815 case SECCLASS_DCCP_SOCKET:
4816 node_perm = DCCP_SOCKET__NODE_BIND;
4819 case SECCLASS_SCTP_SOCKET:
4820 node_perm = SCTP_SOCKET__NODE_BIND;
4824 node_perm = RAWIP_SOCKET__NODE_BIND;
4828 err = sel_netnode_sid(addrp, family_sa, &sid);
4832 if (family_sa == AF_INET)
4833 ad.u.net->v4info.saddr = addr4->sin_addr.s_addr;
4835 ad.u.net->v6info.saddr = addr6->sin6_addr;
4837 err = avc_has_perm(&selinux_state,
4839 sksec->sclass, node_perm, &ad);
4846 /* Note that SCTP services expect -EINVAL, others -EAFNOSUPPORT. */
4847 if (sksec->sclass == SECCLASS_SCTP_SOCKET)
4849 return -EAFNOSUPPORT;
4852 /* This supports connect(2) and SCTP connect services such as sctp_connectx(3)
4853 * and sctp_sendmsg(3) as described in Documentation/security/SCTP.rst
4855 static int selinux_socket_connect_helper(struct socket *sock,
4856 struct sockaddr *address, int addrlen)
4858 struct sock *sk = sock->sk;
4859 struct sk_security_struct *sksec = sk->sk_security;
4862 err = sock_has_perm(sk, SOCKET__CONNECT);
4865 if (addrlen < offsetofend(struct sockaddr, sa_family))
4868 /* connect(AF_UNSPEC) has special handling, as it is a documented
4869 * way to disconnect the socket
4871 if (address->sa_family == AF_UNSPEC)
4875 * If a TCP, DCCP or SCTP socket, check name_connect permission
4878 if (sksec->sclass == SECCLASS_TCP_SOCKET ||
4879 sksec->sclass == SECCLASS_DCCP_SOCKET ||
4880 sksec->sclass == SECCLASS_SCTP_SOCKET) {
4881 struct common_audit_data ad;
4882 struct lsm_network_audit net = {0,};
4883 struct sockaddr_in *addr4 = NULL;
4884 struct sockaddr_in6 *addr6 = NULL;
4885 unsigned short snum;
4888 /* sctp_connectx(3) calls via selinux_sctp_bind_connect()
4889 * that validates multiple connect addresses. Because of this
4890 * need to check address->sa_family as it is possible to have
4891 * sk->sk_family = PF_INET6 with addr->sa_family = AF_INET.
4893 switch (address->sa_family) {
4895 addr4 = (struct sockaddr_in *)address;
4896 if (addrlen < sizeof(struct sockaddr_in))
4898 snum = ntohs(addr4->sin_port);
4901 addr6 = (struct sockaddr_in6 *)address;
4902 if (addrlen < SIN6_LEN_RFC2133)
4904 snum = ntohs(addr6->sin6_port);
4907 /* Note that SCTP services expect -EINVAL, whereas
4908 * others expect -EAFNOSUPPORT.
4910 if (sksec->sclass == SECCLASS_SCTP_SOCKET)
4913 return -EAFNOSUPPORT;
4916 err = sel_netport_sid(sk->sk_protocol, snum, &sid);
4920 switch (sksec->sclass) {
4921 case SECCLASS_TCP_SOCKET:
4922 perm = TCP_SOCKET__NAME_CONNECT;
4924 case SECCLASS_DCCP_SOCKET:
4925 perm = DCCP_SOCKET__NAME_CONNECT;
4927 case SECCLASS_SCTP_SOCKET:
4928 perm = SCTP_SOCKET__NAME_CONNECT;
4932 ad.type = LSM_AUDIT_DATA_NET;
4934 ad.u.net->dport = htons(snum);
4935 ad.u.net->family = address->sa_family;
4936 err = avc_has_perm(&selinux_state,
4937 sksec->sid, sid, sksec->sclass, perm, &ad);
4945 /* Supports connect(2), see comments in selinux_socket_connect_helper() */
4946 static int selinux_socket_connect(struct socket *sock,
4947 struct sockaddr *address, int addrlen)
4950 struct sock *sk = sock->sk;
4952 err = selinux_socket_connect_helper(sock, address, addrlen);
4956 return selinux_netlbl_socket_connect(sk, address);
4959 static int selinux_socket_listen(struct socket *sock, int backlog)
4961 return sock_has_perm(sock->sk, SOCKET__LISTEN);
4964 static int selinux_socket_accept(struct socket *sock, struct socket *newsock)
4967 struct inode_security_struct *isec;
4968 struct inode_security_struct *newisec;
4972 err = sock_has_perm(sock->sk, SOCKET__ACCEPT);
4976 isec = inode_security_novalidate(SOCK_INODE(sock));
4977 spin_lock(&isec->lock);
4978 sclass = isec->sclass;
4980 spin_unlock(&isec->lock);
4982 newisec = inode_security_novalidate(SOCK_INODE(newsock));
4983 newisec->sclass = sclass;
4985 newisec->initialized = LABEL_INITIALIZED;
4990 static int selinux_socket_sendmsg(struct socket *sock, struct msghdr *msg,
4993 return sock_has_perm(sock->sk, SOCKET__WRITE);
4996 static int selinux_socket_recvmsg(struct socket *sock, struct msghdr *msg,
4997 int size, int flags)
4999 return sock_has_perm(sock->sk, SOCKET__READ);
5002 static int selinux_socket_getsockname(struct socket *sock)
5004 return sock_has_perm(sock->sk, SOCKET__GETATTR);
5007 static int selinux_socket_getpeername(struct socket *sock)
5009 return sock_has_perm(sock->sk, SOCKET__GETATTR);
5012 static int selinux_socket_setsockopt(struct socket *sock, int level, int optname)
5016 err = sock_has_perm(sock->sk, SOCKET__SETOPT);
5020 return selinux_netlbl_socket_setsockopt(sock, level, optname);
5023 static int selinux_socket_getsockopt(struct socket *sock, int level,
5026 return sock_has_perm(sock->sk, SOCKET__GETOPT);
5029 static int selinux_socket_shutdown(struct socket *sock, int how)
5031 return sock_has_perm(sock->sk, SOCKET__SHUTDOWN);
5034 static int selinux_socket_unix_stream_connect(struct sock *sock,
5038 struct sk_security_struct *sksec_sock = sock->sk_security;
5039 struct sk_security_struct *sksec_other = other->sk_security;
5040 struct sk_security_struct *sksec_new = newsk->sk_security;
5041 struct common_audit_data ad;
5042 struct lsm_network_audit net = {0,};
5045 ad.type = LSM_AUDIT_DATA_NET;
5047 ad.u.net->sk = other;
5049 err = avc_has_perm(&selinux_state,
5050 sksec_sock->sid, sksec_other->sid,
5051 sksec_other->sclass,
5052 UNIX_STREAM_SOCKET__CONNECTTO, &ad);
5056 /* server child socket */
5057 sksec_new->peer_sid = sksec_sock->sid;
5058 err = security_sid_mls_copy(&selinux_state, sksec_other->sid,
5059 sksec_sock->sid, &sksec_new->sid);
5063 /* connecting socket */
5064 sksec_sock->peer_sid = sksec_new->sid;
5069 static int selinux_socket_unix_may_send(struct socket *sock,
5070 struct socket *other)
5072 struct sk_security_struct *ssec = sock->sk->sk_security;
5073 struct sk_security_struct *osec = other->sk->sk_security;
5074 struct common_audit_data ad;
5075 struct lsm_network_audit net = {0,};
5077 ad.type = LSM_AUDIT_DATA_NET;
5079 ad.u.net->sk = other->sk;
5081 return avc_has_perm(&selinux_state,
5082 ssec->sid, osec->sid, osec->sclass, SOCKET__SENDTO,
5086 static int selinux_inet_sys_rcv_skb(struct net *ns, int ifindex,
5087 char *addrp, u16 family, u32 peer_sid,
5088 struct common_audit_data *ad)
5094 err = sel_netif_sid(ns, ifindex, &if_sid);
5097 err = avc_has_perm(&selinux_state,
5099 SECCLASS_NETIF, NETIF__INGRESS, ad);
5103 err = sel_netnode_sid(addrp, family, &node_sid);
5106 return avc_has_perm(&selinux_state,
5108 SECCLASS_NODE, NODE__RECVFROM, ad);
5111 static int selinux_sock_rcv_skb_compat(struct sock *sk, struct sk_buff *skb,
5115 struct sk_security_struct *sksec = sk->sk_security;
5116 u32 sk_sid = sksec->sid;
5117 struct common_audit_data ad;
5118 struct lsm_network_audit net = {0,};
5121 ad.type = LSM_AUDIT_DATA_NET;
5123 ad.u.net->netif = skb->skb_iif;
5124 ad.u.net->family = family;
5125 err = selinux_parse_skb(skb, &ad, &addrp, 1, NULL);
5129 if (selinux_secmark_enabled()) {
5130 err = avc_has_perm(&selinux_state,
5131 sk_sid, skb->secmark, SECCLASS_PACKET,
5137 err = selinux_netlbl_sock_rcv_skb(sksec, skb, family, &ad);
5140 err = selinux_xfrm_sock_rcv_skb(sksec->sid, skb, &ad);
5145 static int selinux_socket_sock_rcv_skb(struct sock *sk, struct sk_buff *skb)
5148 struct sk_security_struct *sksec = sk->sk_security;
5149 u16 family = sk->sk_family;
5150 u32 sk_sid = sksec->sid;
5151 struct common_audit_data ad;
5152 struct lsm_network_audit net = {0,};
5157 if (family != PF_INET && family != PF_INET6)
5160 /* Handle mapped IPv4 packets arriving via IPv6 sockets */
5161 if (family == PF_INET6 && skb->protocol == htons(ETH_P_IP))
5164 /* If any sort of compatibility mode is enabled then handoff processing
5165 * to the selinux_sock_rcv_skb_compat() function to deal with the
5166 * special handling. We do this in an attempt to keep this function
5167 * as fast and as clean as possible. */
5168 if (!selinux_policycap_netpeer())
5169 return selinux_sock_rcv_skb_compat(sk, skb, family);
5171 secmark_active = selinux_secmark_enabled();
5172 peerlbl_active = selinux_peerlbl_enabled();
5173 if (!secmark_active && !peerlbl_active)
5176 ad.type = LSM_AUDIT_DATA_NET;
5178 ad.u.net->netif = skb->skb_iif;
5179 ad.u.net->family = family;
5180 err = selinux_parse_skb(skb, &ad, &addrp, 1, NULL);
5184 if (peerlbl_active) {
5187 err = selinux_skb_peerlbl_sid(skb, family, &peer_sid);
5190 err = selinux_inet_sys_rcv_skb(sock_net(sk), skb->skb_iif,
5191 addrp, family, peer_sid, &ad);
5193 selinux_netlbl_err(skb, family, err, 0);
5196 err = avc_has_perm(&selinux_state,
5197 sk_sid, peer_sid, SECCLASS_PEER,
5200 selinux_netlbl_err(skb, family, err, 0);
5205 if (secmark_active) {
5206 err = avc_has_perm(&selinux_state,
5207 sk_sid, skb->secmark, SECCLASS_PACKET,
5216 static int selinux_socket_getpeersec_stream(struct socket *sock, char __user *optval,
5217 int __user *optlen, unsigned len)
5222 struct sk_security_struct *sksec = sock->sk->sk_security;
5223 u32 peer_sid = SECSID_NULL;
5225 if (sksec->sclass == SECCLASS_UNIX_STREAM_SOCKET ||
5226 sksec->sclass == SECCLASS_TCP_SOCKET ||
5227 sksec->sclass == SECCLASS_SCTP_SOCKET)
5228 peer_sid = sksec->peer_sid;
5229 if (peer_sid == SECSID_NULL)
5230 return -ENOPROTOOPT;
5232 err = security_sid_to_context(&selinux_state, peer_sid, &scontext,
5237 if (scontext_len > len) {
5242 if (copy_to_user(optval, scontext, scontext_len))
5246 if (put_user(scontext_len, optlen))
5252 static int selinux_socket_getpeersec_dgram(struct socket *sock, struct sk_buff *skb, u32 *secid)
5254 u32 peer_secid = SECSID_NULL;
5256 struct inode_security_struct *isec;
5258 if (skb && skb->protocol == htons(ETH_P_IP))
5260 else if (skb && skb->protocol == htons(ETH_P_IPV6))
5263 family = sock->sk->sk_family;
5267 if (sock && family == PF_UNIX) {
5268 isec = inode_security_novalidate(SOCK_INODE(sock));
5269 peer_secid = isec->sid;
5271 selinux_skb_peerlbl_sid(skb, family, &peer_secid);
5274 *secid = peer_secid;
5275 if (peer_secid == SECSID_NULL)
5280 static int selinux_sk_alloc_security(struct sock *sk, int family, gfp_t priority)
5282 struct sk_security_struct *sksec;
5284 sksec = kzalloc(sizeof(*sksec), priority);
5288 sksec->peer_sid = SECINITSID_UNLABELED;
5289 sksec->sid = SECINITSID_UNLABELED;
5290 sksec->sclass = SECCLASS_SOCKET;
5291 selinux_netlbl_sk_security_reset(sksec);
5292 sk->sk_security = sksec;
5297 static void selinux_sk_free_security(struct sock *sk)
5299 struct sk_security_struct *sksec = sk->sk_security;
5301 sk->sk_security = NULL;
5302 selinux_netlbl_sk_security_free(sksec);
5306 static void selinux_sk_clone_security(const struct sock *sk, struct sock *newsk)
5308 struct sk_security_struct *sksec = sk->sk_security;
5309 struct sk_security_struct *newsksec = newsk->sk_security;
5311 newsksec->sid = sksec->sid;
5312 newsksec->peer_sid = sksec->peer_sid;
5313 newsksec->sclass = sksec->sclass;
5315 selinux_netlbl_sk_security_reset(newsksec);
5318 static void selinux_sk_getsecid(struct sock *sk, u32 *secid)
5321 *secid = SECINITSID_ANY_SOCKET;
5323 struct sk_security_struct *sksec = sk->sk_security;
5325 *secid = sksec->sid;
5329 static void selinux_sock_graft(struct sock *sk, struct socket *parent)
5331 struct inode_security_struct *isec =
5332 inode_security_novalidate(SOCK_INODE(parent));
5333 struct sk_security_struct *sksec = sk->sk_security;
5335 if (sk->sk_family == PF_INET || sk->sk_family == PF_INET6 ||
5336 sk->sk_family == PF_UNIX)
5337 isec->sid = sksec->sid;
5338 sksec->sclass = isec->sclass;
5341 /* Called whenever SCTP receives an INIT chunk. This happens when an incoming
5342 * connect(2), sctp_connectx(3) or sctp_sendmsg(3) (with no association
5345 static int selinux_sctp_assoc_request(struct sctp_endpoint *ep,
5346 struct sk_buff *skb)
5348 struct sk_security_struct *sksec = ep->base.sk->sk_security;
5349 struct common_audit_data ad;
5350 struct lsm_network_audit net = {0,};
5352 u32 peer_sid = SECINITSID_UNLABELED;
5356 if (!selinux_policycap_extsockclass())
5359 peerlbl_active = selinux_peerlbl_enabled();
5361 if (peerlbl_active) {
5362 /* This will return peer_sid = SECSID_NULL if there are
5363 * no peer labels, see security_net_peersid_resolve().
5365 err = selinux_skb_peerlbl_sid(skb, ep->base.sk->sk_family,
5370 if (peer_sid == SECSID_NULL)
5371 peer_sid = SECINITSID_UNLABELED;
5374 if (sksec->sctp_assoc_state == SCTP_ASSOC_UNSET) {
5375 sksec->sctp_assoc_state = SCTP_ASSOC_SET;
5377 /* Here as first association on socket. As the peer SID
5378 * was allowed by peer recv (and the netif/node checks),
5379 * then it is approved by policy and used as the primary
5380 * peer SID for getpeercon(3).
5382 sksec->peer_sid = peer_sid;
5383 } else if (sksec->peer_sid != peer_sid) {
5384 /* Other association peer SIDs are checked to enforce
5385 * consistency among the peer SIDs.
5387 ad.type = LSM_AUDIT_DATA_NET;
5389 ad.u.net->sk = ep->base.sk;
5390 err = avc_has_perm(&selinux_state,
5391 sksec->peer_sid, peer_sid, sksec->sclass,
5392 SCTP_SOCKET__ASSOCIATION, &ad);
5397 /* Compute the MLS component for the connection and store
5398 * the information in ep. This will be used by SCTP TCP type
5399 * sockets and peeled off connections as they cause a new
5400 * socket to be generated. selinux_sctp_sk_clone() will then
5401 * plug this into the new socket.
5403 err = selinux_conn_sid(sksec->sid, peer_sid, &conn_sid);
5407 ep->secid = conn_sid;
5408 ep->peer_secid = peer_sid;
5410 /* Set any NetLabel labels including CIPSO/CALIPSO options. */
5411 return selinux_netlbl_sctp_assoc_request(ep, skb);
5414 /* Check if sctp IPv4/IPv6 addresses are valid for binding or connecting
5415 * based on their @optname.
5417 static int selinux_sctp_bind_connect(struct sock *sk, int optname,
5418 struct sockaddr *address,
5421 int len, err = 0, walk_size = 0;
5423 struct sockaddr *addr;
5424 struct socket *sock;
5426 if (!selinux_policycap_extsockclass())
5429 /* Process one or more addresses that may be IPv4 or IPv6 */
5430 sock = sk->sk_socket;
5433 while (walk_size < addrlen) {
5434 if (walk_size + sizeof(sa_family_t) > addrlen)
5438 switch (addr->sa_family) {
5441 len = sizeof(struct sockaddr_in);
5444 len = sizeof(struct sockaddr_in6);
5450 if (walk_size + len > addrlen)
5456 case SCTP_PRIMARY_ADDR:
5457 case SCTP_SET_PEER_PRIMARY_ADDR:
5458 case SCTP_SOCKOPT_BINDX_ADD:
5459 err = selinux_socket_bind(sock, addr, len);
5461 /* Connect checks */
5462 case SCTP_SOCKOPT_CONNECTX:
5463 case SCTP_PARAM_SET_PRIMARY:
5464 case SCTP_PARAM_ADD_IP:
5465 case SCTP_SENDMSG_CONNECT:
5466 err = selinux_socket_connect_helper(sock, addr, len);
5470 /* As selinux_sctp_bind_connect() is called by the
5471 * SCTP protocol layer, the socket is already locked,
5472 * therefore selinux_netlbl_socket_connect_locked()
5473 * is called here. The situations handled are:
5474 * sctp_connectx(3), sctp_sendmsg(3), sendmsg(2),
5475 * whenever a new IP address is added or when a new
5476 * primary address is selected.
5477 * Note that an SCTP connect(2) call happens before
5478 * the SCTP protocol layer and is handled via
5479 * selinux_socket_connect().
5481 err = selinux_netlbl_socket_connect_locked(sk, addr);
5495 /* Called whenever a new socket is created by accept(2) or sctp_peeloff(3). */
5496 static void selinux_sctp_sk_clone(struct sctp_endpoint *ep, struct sock *sk,
5499 struct sk_security_struct *sksec = sk->sk_security;
5500 struct sk_security_struct *newsksec = newsk->sk_security;
5502 /* If policy does not support SECCLASS_SCTP_SOCKET then call
5503 * the non-sctp clone version.
5505 if (!selinux_policycap_extsockclass())
5506 return selinux_sk_clone_security(sk, newsk);
5508 newsksec->sid = ep->secid;
5509 newsksec->peer_sid = ep->peer_secid;
5510 newsksec->sclass = sksec->sclass;
5511 selinux_netlbl_sctp_sk_clone(sk, newsk);
5514 static int selinux_inet_conn_request(const struct sock *sk, struct sk_buff *skb,
5515 struct request_sock *req)
5517 struct sk_security_struct *sksec = sk->sk_security;
5519 u16 family = req->rsk_ops->family;
5523 err = selinux_skb_peerlbl_sid(skb, family, &peersid);
5526 err = selinux_conn_sid(sksec->sid, peersid, &connsid);
5529 req->secid = connsid;
5530 req->peer_secid = peersid;
5532 return selinux_netlbl_inet_conn_request(req, family);
5535 static void selinux_inet_csk_clone(struct sock *newsk,
5536 const struct request_sock *req)
5538 struct sk_security_struct *newsksec = newsk->sk_security;
5540 newsksec->sid = req->secid;
5541 newsksec->peer_sid = req->peer_secid;
5542 /* NOTE: Ideally, we should also get the isec->sid for the
5543 new socket in sync, but we don't have the isec available yet.
5544 So we will wait until sock_graft to do it, by which
5545 time it will have been created and available. */
5547 /* We don't need to take any sort of lock here as we are the only
5548 * thread with access to newsksec */
5549 selinux_netlbl_inet_csk_clone(newsk, req->rsk_ops->family);
5552 static void selinux_inet_conn_established(struct sock *sk, struct sk_buff *skb)
5554 u16 family = sk->sk_family;
5555 struct sk_security_struct *sksec = sk->sk_security;
5557 /* handle mapped IPv4 packets arriving via IPv6 sockets */
5558 if (family == PF_INET6 && skb->protocol == htons(ETH_P_IP))
5561 selinux_skb_peerlbl_sid(skb, family, &sksec->peer_sid);
5564 static int selinux_secmark_relabel_packet(u32 sid)
5566 const struct task_security_struct *__tsec;
5569 __tsec = selinux_cred(current_cred());
5572 return avc_has_perm(&selinux_state,
5573 tsid, sid, SECCLASS_PACKET, PACKET__RELABELTO,
5577 static void selinux_secmark_refcount_inc(void)
5579 atomic_inc(&selinux_secmark_refcount);
5582 static void selinux_secmark_refcount_dec(void)
5584 atomic_dec(&selinux_secmark_refcount);
5587 static void selinux_req_classify_flow(const struct request_sock *req,
5588 struct flowi_common *flic)
5590 flic->flowic_secid = req->secid;
5593 static int selinux_tun_dev_alloc_security(void **security)
5595 struct tun_security_struct *tunsec;
5597 tunsec = kzalloc(sizeof(*tunsec), GFP_KERNEL);
5600 tunsec->sid = current_sid();
5606 static void selinux_tun_dev_free_security(void *security)
5611 static int selinux_tun_dev_create(void)
5613 u32 sid = current_sid();
5615 /* we aren't taking into account the "sockcreate" SID since the socket
5616 * that is being created here is not a socket in the traditional sense,
5617 * instead it is a private sock, accessible only to the kernel, and
5618 * representing a wide range of network traffic spanning multiple
5619 * connections unlike traditional sockets - check the TUN driver to
5620 * get a better understanding of why this socket is special */
5622 return avc_has_perm(&selinux_state,
5623 sid, sid, SECCLASS_TUN_SOCKET, TUN_SOCKET__CREATE,
5627 static int selinux_tun_dev_attach_queue(void *security)
5629 struct tun_security_struct *tunsec = security;
5631 return avc_has_perm(&selinux_state,
5632 current_sid(), tunsec->sid, SECCLASS_TUN_SOCKET,
5633 TUN_SOCKET__ATTACH_QUEUE, NULL);
5636 static int selinux_tun_dev_attach(struct sock *sk, void *security)
5638 struct tun_security_struct *tunsec = security;
5639 struct sk_security_struct *sksec = sk->sk_security;
5641 /* we don't currently perform any NetLabel based labeling here and it
5642 * isn't clear that we would want to do so anyway; while we could apply
5643 * labeling without the support of the TUN user the resulting labeled
5644 * traffic from the other end of the connection would almost certainly
5645 * cause confusion to the TUN user that had no idea network labeling
5646 * protocols were being used */
5648 sksec->sid = tunsec->sid;
5649 sksec->sclass = SECCLASS_TUN_SOCKET;
5654 static int selinux_tun_dev_open(void *security)
5656 struct tun_security_struct *tunsec = security;
5657 u32 sid = current_sid();
5660 err = avc_has_perm(&selinux_state,
5661 sid, tunsec->sid, SECCLASS_TUN_SOCKET,
5662 TUN_SOCKET__RELABELFROM, NULL);
5665 err = avc_has_perm(&selinux_state,
5666 sid, sid, SECCLASS_TUN_SOCKET,
5667 TUN_SOCKET__RELABELTO, NULL);
5675 #ifdef CONFIG_NETFILTER
5677 static unsigned int selinux_ip_forward(struct sk_buff *skb,
5678 const struct net_device *indev,
5684 struct common_audit_data ad;
5685 struct lsm_network_audit net = {0,};
5690 if (!selinux_policycap_netpeer())
5693 secmark_active = selinux_secmark_enabled();
5694 netlbl_active = netlbl_enabled();
5695 peerlbl_active = selinux_peerlbl_enabled();
5696 if (!secmark_active && !peerlbl_active)
5699 if (selinux_skb_peerlbl_sid(skb, family, &peer_sid) != 0)
5702 ad.type = LSM_AUDIT_DATA_NET;
5704 ad.u.net->netif = indev->ifindex;
5705 ad.u.net->family = family;
5706 if (selinux_parse_skb(skb, &ad, &addrp, 1, NULL) != 0)
5709 if (peerlbl_active) {
5710 err = selinux_inet_sys_rcv_skb(dev_net(indev), indev->ifindex,
5711 addrp, family, peer_sid, &ad);
5713 selinux_netlbl_err(skb, family, err, 1);
5719 if (avc_has_perm(&selinux_state,
5720 peer_sid, skb->secmark,
5721 SECCLASS_PACKET, PACKET__FORWARD_IN, &ad))
5725 /* we do this in the FORWARD path and not the POST_ROUTING
5726 * path because we want to make sure we apply the necessary
5727 * labeling before IPsec is applied so we can leverage AH
5729 if (selinux_netlbl_skbuff_setsid(skb, family, peer_sid) != 0)
5735 static unsigned int selinux_ipv4_forward(void *priv,
5736 struct sk_buff *skb,
5737 const struct nf_hook_state *state)
5739 return selinux_ip_forward(skb, state->in, PF_INET);
5742 #if IS_ENABLED(CONFIG_IPV6)
5743 static unsigned int selinux_ipv6_forward(void *priv,
5744 struct sk_buff *skb,
5745 const struct nf_hook_state *state)
5747 return selinux_ip_forward(skb, state->in, PF_INET6);
5751 static unsigned int selinux_ip_output(struct sk_buff *skb,
5757 if (!netlbl_enabled())
5760 /* we do this in the LOCAL_OUT path and not the POST_ROUTING path
5761 * because we want to make sure we apply the necessary labeling
5762 * before IPsec is applied so we can leverage AH protection */
5765 struct sk_security_struct *sksec;
5767 if (sk_listener(sk))
5768 /* if the socket is the listening state then this
5769 * packet is a SYN-ACK packet which means it needs to
5770 * be labeled based on the connection/request_sock and
5771 * not the parent socket. unfortunately, we can't
5772 * lookup the request_sock yet as it isn't queued on
5773 * the parent socket until after the SYN-ACK is sent.
5774 * the "solution" is to simply pass the packet as-is
5775 * as any IP option based labeling should be copied
5776 * from the initial connection request (in the IP
5777 * layer). it is far from ideal, but until we get a
5778 * security label in the packet itself this is the
5779 * best we can do. */
5782 /* standard practice, label using the parent socket */
5783 sksec = sk->sk_security;
5786 sid = SECINITSID_KERNEL;
5787 if (selinux_netlbl_skbuff_setsid(skb, family, sid) != 0)
5793 static unsigned int selinux_ipv4_output(void *priv,
5794 struct sk_buff *skb,
5795 const struct nf_hook_state *state)
5797 return selinux_ip_output(skb, PF_INET);
5800 #if IS_ENABLED(CONFIG_IPV6)
5801 static unsigned int selinux_ipv6_output(void *priv,
5802 struct sk_buff *skb,
5803 const struct nf_hook_state *state)
5805 return selinux_ip_output(skb, PF_INET6);
5809 static unsigned int selinux_ip_postroute_compat(struct sk_buff *skb,
5813 struct sock *sk = skb_to_full_sk(skb);
5814 struct sk_security_struct *sksec;
5815 struct common_audit_data ad;
5816 struct lsm_network_audit net = {0,};
5822 sksec = sk->sk_security;
5824 ad.type = LSM_AUDIT_DATA_NET;
5826 ad.u.net->netif = ifindex;
5827 ad.u.net->family = family;
5828 if (selinux_parse_skb(skb, &ad, &addrp, 0, &proto))
5831 if (selinux_secmark_enabled())
5832 if (avc_has_perm(&selinux_state,
5833 sksec->sid, skb->secmark,
5834 SECCLASS_PACKET, PACKET__SEND, &ad))
5835 return NF_DROP_ERR(-ECONNREFUSED);
5837 if (selinux_xfrm_postroute_last(sksec->sid, skb, &ad, proto))
5838 return NF_DROP_ERR(-ECONNREFUSED);
5843 static unsigned int selinux_ip_postroute(struct sk_buff *skb,
5844 const struct net_device *outdev,
5849 int ifindex = outdev->ifindex;
5851 struct common_audit_data ad;
5852 struct lsm_network_audit net = {0,};
5857 /* If any sort of compatibility mode is enabled then handoff processing
5858 * to the selinux_ip_postroute_compat() function to deal with the
5859 * special handling. We do this in an attempt to keep this function
5860 * as fast and as clean as possible. */
5861 if (!selinux_policycap_netpeer())
5862 return selinux_ip_postroute_compat(skb, ifindex, family);
5864 secmark_active = selinux_secmark_enabled();
5865 peerlbl_active = selinux_peerlbl_enabled();
5866 if (!secmark_active && !peerlbl_active)
5869 sk = skb_to_full_sk(skb);
5872 /* If skb->dst->xfrm is non-NULL then the packet is undergoing an IPsec
5873 * packet transformation so allow the packet to pass without any checks
5874 * since we'll have another chance to perform access control checks
5875 * when the packet is on it's final way out.
5876 * NOTE: there appear to be some IPv6 multicast cases where skb->dst
5877 * is NULL, in this case go ahead and apply access control.
5878 * NOTE: if this is a local socket (skb->sk != NULL) that is in the
5879 * TCP listening state we cannot wait until the XFRM processing
5880 * is done as we will miss out on the SA label if we do;
5881 * unfortunately, this means more work, but it is only once per
5883 if (skb_dst(skb) != NULL && skb_dst(skb)->xfrm != NULL &&
5884 !(sk && sk_listener(sk)))
5889 /* Without an associated socket the packet is either coming
5890 * from the kernel or it is being forwarded; check the packet
5891 * to determine which and if the packet is being forwarded
5892 * query the packet directly to determine the security label. */
5894 secmark_perm = PACKET__FORWARD_OUT;
5895 if (selinux_skb_peerlbl_sid(skb, family, &peer_sid))
5898 secmark_perm = PACKET__SEND;
5899 peer_sid = SECINITSID_KERNEL;
5901 } else if (sk_listener(sk)) {
5902 /* Locally generated packet but the associated socket is in the
5903 * listening state which means this is a SYN-ACK packet. In
5904 * this particular case the correct security label is assigned
5905 * to the connection/request_sock but unfortunately we can't
5906 * query the request_sock as it isn't queued on the parent
5907 * socket until after the SYN-ACK packet is sent; the only
5908 * viable choice is to regenerate the label like we do in
5909 * selinux_inet_conn_request(). See also selinux_ip_output()
5910 * for similar problems. */
5912 struct sk_security_struct *sksec;
5914 sksec = sk->sk_security;
5915 if (selinux_skb_peerlbl_sid(skb, family, &skb_sid))
5917 /* At this point, if the returned skb peerlbl is SECSID_NULL
5918 * and the packet has been through at least one XFRM
5919 * transformation then we must be dealing with the "final"
5920 * form of labeled IPsec packet; since we've already applied
5921 * all of our access controls on this packet we can safely
5922 * pass the packet. */
5923 if (skb_sid == SECSID_NULL) {
5926 if (IPCB(skb)->flags & IPSKB_XFRM_TRANSFORMED)
5930 if (IP6CB(skb)->flags & IP6SKB_XFRM_TRANSFORMED)
5934 return NF_DROP_ERR(-ECONNREFUSED);
5937 if (selinux_conn_sid(sksec->sid, skb_sid, &peer_sid))
5939 secmark_perm = PACKET__SEND;
5941 /* Locally generated packet, fetch the security label from the
5942 * associated socket. */
5943 struct sk_security_struct *sksec = sk->sk_security;
5944 peer_sid = sksec->sid;
5945 secmark_perm = PACKET__SEND;
5948 ad.type = LSM_AUDIT_DATA_NET;
5950 ad.u.net->netif = ifindex;
5951 ad.u.net->family = family;
5952 if (selinux_parse_skb(skb, &ad, &addrp, 0, NULL))
5956 if (avc_has_perm(&selinux_state,
5957 peer_sid, skb->secmark,
5958 SECCLASS_PACKET, secmark_perm, &ad))
5959 return NF_DROP_ERR(-ECONNREFUSED);
5961 if (peerlbl_active) {
5965 if (sel_netif_sid(dev_net(outdev), ifindex, &if_sid))
5967 if (avc_has_perm(&selinux_state,
5969 SECCLASS_NETIF, NETIF__EGRESS, &ad))
5970 return NF_DROP_ERR(-ECONNREFUSED);
5972 if (sel_netnode_sid(addrp, family, &node_sid))
5974 if (avc_has_perm(&selinux_state,
5976 SECCLASS_NODE, NODE__SENDTO, &ad))
5977 return NF_DROP_ERR(-ECONNREFUSED);
5983 static unsigned int selinux_ipv4_postroute(void *priv,
5984 struct sk_buff *skb,
5985 const struct nf_hook_state *state)
5987 return selinux_ip_postroute(skb, state->out, PF_INET);
5990 #if IS_ENABLED(CONFIG_IPV6)
5991 static unsigned int selinux_ipv6_postroute(void *priv,
5992 struct sk_buff *skb,
5993 const struct nf_hook_state *state)
5995 return selinux_ip_postroute(skb, state->out, PF_INET6);
5999 #endif /* CONFIG_NETFILTER */
6001 static int selinux_netlink_send(struct sock *sk, struct sk_buff *skb)
6004 unsigned int msg_len;
6005 unsigned int data_len = skb->len;
6006 unsigned char *data = skb->data;
6007 struct nlmsghdr *nlh;
6008 struct sk_security_struct *sksec = sk->sk_security;
6009 u16 sclass = sksec->sclass;
6012 while (data_len >= nlmsg_total_size(0)) {
6013 nlh = (struct nlmsghdr *)data;
6015 /* NOTE: the nlmsg_len field isn't reliably set by some netlink
6016 * users which means we can't reject skb's with bogus
6017 * length fields; our solution is to follow what
6018 * netlink_rcv_skb() does and simply skip processing at
6019 * messages with length fields that are clearly junk
6021 if (nlh->nlmsg_len < NLMSG_HDRLEN || nlh->nlmsg_len > data_len)
6024 rc = selinux_nlmsg_lookup(sclass, nlh->nlmsg_type, &perm);
6026 rc = sock_has_perm(sk, perm);
6029 } else if (rc == -EINVAL) {
6030 /* -EINVAL is a missing msg/perm mapping */
6031 pr_warn_ratelimited("SELinux: unrecognized netlink"
6032 " message: protocol=%hu nlmsg_type=%hu sclass=%s"
6033 " pid=%d comm=%s\n",
6034 sk->sk_protocol, nlh->nlmsg_type,
6035 secclass_map[sclass - 1].name,
6036 task_pid_nr(current), current->comm);
6037 if (enforcing_enabled(&selinux_state) &&
6038 !security_get_allow_unknown(&selinux_state))
6041 } else if (rc == -ENOENT) {
6042 /* -ENOENT is a missing socket/class mapping, ignore */
6048 /* move to the next message after applying netlink padding */
6049 msg_len = NLMSG_ALIGN(nlh->nlmsg_len);
6050 if (msg_len >= data_len)
6052 data_len -= msg_len;
6059 static void ipc_init_security(struct ipc_security_struct *isec, u16 sclass)
6061 isec->sclass = sclass;
6062 isec->sid = current_sid();
6065 static int ipc_has_perm(struct kern_ipc_perm *ipc_perms,
6068 struct ipc_security_struct *isec;
6069 struct common_audit_data ad;
6070 u32 sid = current_sid();
6072 isec = selinux_ipc(ipc_perms);
6074 ad.type = LSM_AUDIT_DATA_IPC;
6075 ad.u.ipc_id = ipc_perms->key;
6077 return avc_has_perm(&selinux_state,
6078 sid, isec->sid, isec->sclass, perms, &ad);
6081 static int selinux_msg_msg_alloc_security(struct msg_msg *msg)
6083 struct msg_security_struct *msec;
6085 msec = selinux_msg_msg(msg);
6086 msec->sid = SECINITSID_UNLABELED;
6091 /* message queue security operations */
6092 static int selinux_msg_queue_alloc_security(struct kern_ipc_perm *msq)
6094 struct ipc_security_struct *isec;
6095 struct common_audit_data ad;
6096 u32 sid = current_sid();
6099 isec = selinux_ipc(msq);
6100 ipc_init_security(isec, SECCLASS_MSGQ);
6102 ad.type = LSM_AUDIT_DATA_IPC;
6103 ad.u.ipc_id = msq->key;
6105 rc = avc_has_perm(&selinux_state,
6106 sid, isec->sid, SECCLASS_MSGQ,
6111 static int selinux_msg_queue_associate(struct kern_ipc_perm *msq, int msqflg)
6113 struct ipc_security_struct *isec;
6114 struct common_audit_data ad;
6115 u32 sid = current_sid();
6117 isec = selinux_ipc(msq);
6119 ad.type = LSM_AUDIT_DATA_IPC;
6120 ad.u.ipc_id = msq->key;
6122 return avc_has_perm(&selinux_state,
6123 sid, isec->sid, SECCLASS_MSGQ,
6124 MSGQ__ASSOCIATE, &ad);
6127 static int selinux_msg_queue_msgctl(struct kern_ipc_perm *msq, int cmd)
6135 /* No specific object, just general system-wide information. */
6136 return avc_has_perm(&selinux_state,
6137 current_sid(), SECINITSID_KERNEL,
6138 SECCLASS_SYSTEM, SYSTEM__IPC_INFO, NULL);
6142 perms = MSGQ__GETATTR | MSGQ__ASSOCIATE;
6145 perms = MSGQ__SETATTR;
6148 perms = MSGQ__DESTROY;
6154 err = ipc_has_perm(msq, perms);
6158 static int selinux_msg_queue_msgsnd(struct kern_ipc_perm *msq, struct msg_msg *msg, int msqflg)
6160 struct ipc_security_struct *isec;
6161 struct msg_security_struct *msec;
6162 struct common_audit_data ad;
6163 u32 sid = current_sid();
6166 isec = selinux_ipc(msq);
6167 msec = selinux_msg_msg(msg);
6170 * First time through, need to assign label to the message
6172 if (msec->sid == SECINITSID_UNLABELED) {
6174 * Compute new sid based on current process and
6175 * message queue this message will be stored in
6177 rc = security_transition_sid(&selinux_state, sid, isec->sid,
6178 SECCLASS_MSG, NULL, &msec->sid);
6183 ad.type = LSM_AUDIT_DATA_IPC;
6184 ad.u.ipc_id = msq->key;
6186 /* Can this process write to the queue? */
6187 rc = avc_has_perm(&selinux_state,
6188 sid, isec->sid, SECCLASS_MSGQ,
6191 /* Can this process send the message */
6192 rc = avc_has_perm(&selinux_state,
6193 sid, msec->sid, SECCLASS_MSG,
6196 /* Can the message be put in the queue? */
6197 rc = avc_has_perm(&selinux_state,
6198 msec->sid, isec->sid, SECCLASS_MSGQ,
6199 MSGQ__ENQUEUE, &ad);
6204 static int selinux_msg_queue_msgrcv(struct kern_ipc_perm *msq, struct msg_msg *msg,
6205 struct task_struct *target,
6206 long type, int mode)
6208 struct ipc_security_struct *isec;
6209 struct msg_security_struct *msec;
6210 struct common_audit_data ad;
6211 u32 sid = task_sid(target);
6214 isec = selinux_ipc(msq);
6215 msec = selinux_msg_msg(msg);
6217 ad.type = LSM_AUDIT_DATA_IPC;
6218 ad.u.ipc_id = msq->key;
6220 rc = avc_has_perm(&selinux_state,
6222 SECCLASS_MSGQ, MSGQ__READ, &ad);
6224 rc = avc_has_perm(&selinux_state,
6226 SECCLASS_MSG, MSG__RECEIVE, &ad);
6230 /* Shared Memory security operations */
6231 static int selinux_shm_alloc_security(struct kern_ipc_perm *shp)
6233 struct ipc_security_struct *isec;
6234 struct common_audit_data ad;
6235 u32 sid = current_sid();
6238 isec = selinux_ipc(shp);
6239 ipc_init_security(isec, SECCLASS_SHM);
6241 ad.type = LSM_AUDIT_DATA_IPC;
6242 ad.u.ipc_id = shp->key;
6244 rc = avc_has_perm(&selinux_state,
6245 sid, isec->sid, SECCLASS_SHM,
6250 static int selinux_shm_associate(struct kern_ipc_perm *shp, int shmflg)
6252 struct ipc_security_struct *isec;
6253 struct common_audit_data ad;
6254 u32 sid = current_sid();
6256 isec = selinux_ipc(shp);
6258 ad.type = LSM_AUDIT_DATA_IPC;
6259 ad.u.ipc_id = shp->key;
6261 return avc_has_perm(&selinux_state,
6262 sid, isec->sid, SECCLASS_SHM,
6263 SHM__ASSOCIATE, &ad);
6266 /* Note, at this point, shp is locked down */
6267 static int selinux_shm_shmctl(struct kern_ipc_perm *shp, int cmd)
6275 /* No specific object, just general system-wide information. */
6276 return avc_has_perm(&selinux_state,
6277 current_sid(), SECINITSID_KERNEL,
6278 SECCLASS_SYSTEM, SYSTEM__IPC_INFO, NULL);
6282 perms = SHM__GETATTR | SHM__ASSOCIATE;
6285 perms = SHM__SETATTR;
6292 perms = SHM__DESTROY;
6298 err = ipc_has_perm(shp, perms);
6302 static int selinux_shm_shmat(struct kern_ipc_perm *shp,
6303 char __user *shmaddr, int shmflg)
6307 if (shmflg & SHM_RDONLY)
6310 perms = SHM__READ | SHM__WRITE;
6312 return ipc_has_perm(shp, perms);
6315 /* Semaphore security operations */
6316 static int selinux_sem_alloc_security(struct kern_ipc_perm *sma)
6318 struct ipc_security_struct *isec;
6319 struct common_audit_data ad;
6320 u32 sid = current_sid();
6323 isec = selinux_ipc(sma);
6324 ipc_init_security(isec, SECCLASS_SEM);
6326 ad.type = LSM_AUDIT_DATA_IPC;
6327 ad.u.ipc_id = sma->key;
6329 rc = avc_has_perm(&selinux_state,
6330 sid, isec->sid, SECCLASS_SEM,
6335 static int selinux_sem_associate(struct kern_ipc_perm *sma, int semflg)
6337 struct ipc_security_struct *isec;
6338 struct common_audit_data ad;
6339 u32 sid = current_sid();
6341 isec = selinux_ipc(sma);
6343 ad.type = LSM_AUDIT_DATA_IPC;
6344 ad.u.ipc_id = sma->key;
6346 return avc_has_perm(&selinux_state,
6347 sid, isec->sid, SECCLASS_SEM,
6348 SEM__ASSOCIATE, &ad);
6351 /* Note, at this point, sma is locked down */
6352 static int selinux_sem_semctl(struct kern_ipc_perm *sma, int cmd)
6360 /* No specific object, just general system-wide information. */
6361 return avc_has_perm(&selinux_state,
6362 current_sid(), SECINITSID_KERNEL,
6363 SECCLASS_SYSTEM, SYSTEM__IPC_INFO, NULL);
6367 perms = SEM__GETATTR;
6378 perms = SEM__DESTROY;
6381 perms = SEM__SETATTR;
6386 perms = SEM__GETATTR | SEM__ASSOCIATE;
6392 err = ipc_has_perm(sma, perms);
6396 static int selinux_sem_semop(struct kern_ipc_perm *sma,
6397 struct sembuf *sops, unsigned nsops, int alter)
6402 perms = SEM__READ | SEM__WRITE;
6406 return ipc_has_perm(sma, perms);
6409 static int selinux_ipc_permission(struct kern_ipc_perm *ipcp, short flag)
6415 av |= IPC__UNIX_READ;
6417 av |= IPC__UNIX_WRITE;
6422 return ipc_has_perm(ipcp, av);
6425 static void selinux_ipc_getsecid(struct kern_ipc_perm *ipcp, u32 *secid)
6427 struct ipc_security_struct *isec = selinux_ipc(ipcp);
6431 static void selinux_d_instantiate(struct dentry *dentry, struct inode *inode)
6434 inode_doinit_with_dentry(inode, dentry);
6437 static int selinux_getprocattr(struct task_struct *p,
6438 char *name, char **value)
6440 const struct task_security_struct *__tsec;
6446 __tsec = selinux_cred(__task_cred(p));
6449 error = avc_has_perm(&selinux_state,
6450 current_sid(), __tsec->sid,
6451 SECCLASS_PROCESS, PROCESS__GETATTR, NULL);
6456 if (!strcmp(name, "current"))
6458 else if (!strcmp(name, "prev"))
6460 else if (!strcmp(name, "exec"))
6461 sid = __tsec->exec_sid;
6462 else if (!strcmp(name, "fscreate"))
6463 sid = __tsec->create_sid;
6464 else if (!strcmp(name, "keycreate"))
6465 sid = __tsec->keycreate_sid;
6466 else if (!strcmp(name, "sockcreate"))
6467 sid = __tsec->sockcreate_sid;
6477 error = security_sid_to_context(&selinux_state, sid, value, &len);
6487 static int selinux_setprocattr(const char *name, void *value, size_t size)
6489 struct task_security_struct *tsec;
6491 u32 mysid = current_sid(), sid = 0, ptsid;
6496 * Basic control over ability to set these attributes at all.
6498 if (!strcmp(name, "exec"))
6499 error = avc_has_perm(&selinux_state,
6500 mysid, mysid, SECCLASS_PROCESS,
6501 PROCESS__SETEXEC, NULL);
6502 else if (!strcmp(name, "fscreate"))
6503 error = avc_has_perm(&selinux_state,
6504 mysid, mysid, SECCLASS_PROCESS,
6505 PROCESS__SETFSCREATE, NULL);
6506 else if (!strcmp(name, "keycreate"))
6507 error = avc_has_perm(&selinux_state,
6508 mysid, mysid, SECCLASS_PROCESS,
6509 PROCESS__SETKEYCREATE, NULL);
6510 else if (!strcmp(name, "sockcreate"))
6511 error = avc_has_perm(&selinux_state,
6512 mysid, mysid, SECCLASS_PROCESS,
6513 PROCESS__SETSOCKCREATE, NULL);
6514 else if (!strcmp(name, "current"))
6515 error = avc_has_perm(&selinux_state,
6516 mysid, mysid, SECCLASS_PROCESS,
6517 PROCESS__SETCURRENT, NULL);
6523 /* Obtain a SID for the context, if one was specified. */
6524 if (size && str[0] && str[0] != '\n') {
6525 if (str[size-1] == '\n') {
6529 error = security_context_to_sid(&selinux_state, value, size,
6531 if (error == -EINVAL && !strcmp(name, "fscreate")) {
6532 if (!has_cap_mac_admin(true)) {
6533 struct audit_buffer *ab;
6536 /* We strip a nul only if it is at the end, otherwise the
6537 * context contains a nul and we should audit that */
6538 if (str[size - 1] == '\0')
6539 audit_size = size - 1;
6542 ab = audit_log_start(audit_context(),
6545 audit_log_format(ab, "op=fscreate invalid_context=");
6546 audit_log_n_untrustedstring(ab, value, audit_size);
6551 error = security_context_to_sid_force(
6559 new = prepare_creds();
6563 /* Permission checking based on the specified context is
6564 performed during the actual operation (execve,
6565 open/mkdir/...), when we know the full context of the
6566 operation. See selinux_bprm_creds_for_exec for the execve
6567 checks and may_create for the file creation checks. The
6568 operation will then fail if the context is not permitted. */
6569 tsec = selinux_cred(new);
6570 if (!strcmp(name, "exec")) {
6571 tsec->exec_sid = sid;
6572 } else if (!strcmp(name, "fscreate")) {
6573 tsec->create_sid = sid;
6574 } else if (!strcmp(name, "keycreate")) {
6576 error = avc_has_perm(&selinux_state, mysid, sid,
6577 SECCLASS_KEY, KEY__CREATE, NULL);
6581 tsec->keycreate_sid = sid;
6582 } else if (!strcmp(name, "sockcreate")) {
6583 tsec->sockcreate_sid = sid;
6584 } else if (!strcmp(name, "current")) {
6589 /* Only allow single threaded processes to change context */
6591 if (!current_is_single_threaded()) {
6592 error = security_bounded_transition(&selinux_state,
6598 /* Check permissions for the transition. */
6599 error = avc_has_perm(&selinux_state,
6600 tsec->sid, sid, SECCLASS_PROCESS,
6601 PROCESS__DYNTRANSITION, NULL);
6605 /* Check for ptracing, and update the task SID if ok.
6606 Otherwise, leave SID unchanged and fail. */
6607 ptsid = ptrace_parent_sid();
6609 error = avc_has_perm(&selinux_state,
6610 ptsid, sid, SECCLASS_PROCESS,
6611 PROCESS__PTRACE, NULL);
6630 static int selinux_ismaclabel(const char *name)
6632 return (strcmp(name, XATTR_SELINUX_SUFFIX) == 0);
6635 static int selinux_secid_to_secctx(u32 secid, char **secdata, u32 *seclen)
6637 return security_sid_to_context(&selinux_state, secid,
6641 static int selinux_secctx_to_secid(const char *secdata, u32 seclen, u32 *secid)
6643 return security_context_to_sid(&selinux_state, secdata, seclen,
6647 static void selinux_release_secctx(char *secdata, u32 seclen)
6652 static void selinux_inode_invalidate_secctx(struct inode *inode)
6654 struct inode_security_struct *isec = selinux_inode(inode);
6656 spin_lock(&isec->lock);
6657 isec->initialized = LABEL_INVALID;
6658 spin_unlock(&isec->lock);
6662 * called with inode->i_mutex locked
6664 static int selinux_inode_notifysecctx(struct inode *inode, void *ctx, u32 ctxlen)
6666 int rc = selinux_inode_setsecurity(inode, XATTR_SELINUX_SUFFIX,
6668 /* Do not return error when suppressing label (SBLABEL_MNT not set). */
6669 return rc == -EOPNOTSUPP ? 0 : rc;
6673 * called with inode->i_mutex locked
6675 static int selinux_inode_setsecctx(struct dentry *dentry, void *ctx, u32 ctxlen)
6677 return __vfs_setxattr_noperm(&init_user_ns, dentry, XATTR_NAME_SELINUX,
6681 static int selinux_inode_getsecctx(struct inode *inode, void **ctx, u32 *ctxlen)
6684 len = selinux_inode_getsecurity(&init_user_ns, inode,
6685 XATTR_SELINUX_SUFFIX, ctx, true);
6693 static int selinux_key_alloc(struct key *k, const struct cred *cred,
6694 unsigned long flags)
6696 const struct task_security_struct *tsec;
6697 struct key_security_struct *ksec;
6699 ksec = kzalloc(sizeof(struct key_security_struct), GFP_KERNEL);
6703 tsec = selinux_cred(cred);
6704 if (tsec->keycreate_sid)
6705 ksec->sid = tsec->keycreate_sid;
6707 ksec->sid = tsec->sid;
6713 static void selinux_key_free(struct key *k)
6715 struct key_security_struct *ksec = k->security;
6721 static int selinux_key_permission(key_ref_t key_ref,
6722 const struct cred *cred,
6723 enum key_need_perm need_perm)
6726 struct key_security_struct *ksec;
6729 switch (need_perm) {
6736 case KEY_NEED_WRITE:
6739 case KEY_NEED_SEARCH:
6745 case KEY_NEED_SETATTR:
6746 perm = KEY__SETATTR;
6748 case KEY_NEED_UNLINK:
6749 case KEY_SYSADMIN_OVERRIDE:
6750 case KEY_AUTHTOKEN_OVERRIDE:
6751 case KEY_DEFER_PERM_CHECK:
6759 sid = cred_sid(cred);
6760 key = key_ref_to_ptr(key_ref);
6761 ksec = key->security;
6763 return avc_has_perm(&selinux_state,
6764 sid, ksec->sid, SECCLASS_KEY, perm, NULL);
6767 static int selinux_key_getsecurity(struct key *key, char **_buffer)
6769 struct key_security_struct *ksec = key->security;
6770 char *context = NULL;
6774 rc = security_sid_to_context(&selinux_state, ksec->sid,
6782 #ifdef CONFIG_KEY_NOTIFICATIONS
6783 static int selinux_watch_key(struct key *key)
6785 struct key_security_struct *ksec = key->security;
6786 u32 sid = current_sid();
6788 return avc_has_perm(&selinux_state,
6789 sid, ksec->sid, SECCLASS_KEY, KEY__VIEW, NULL);
6794 #ifdef CONFIG_SECURITY_INFINIBAND
6795 static int selinux_ib_pkey_access(void *ib_sec, u64 subnet_prefix, u16 pkey_val)
6797 struct common_audit_data ad;
6800 struct ib_security_struct *sec = ib_sec;
6801 struct lsm_ibpkey_audit ibpkey;
6803 err = sel_ib_pkey_sid(subnet_prefix, pkey_val, &sid);
6807 ad.type = LSM_AUDIT_DATA_IBPKEY;
6808 ibpkey.subnet_prefix = subnet_prefix;
6809 ibpkey.pkey = pkey_val;
6810 ad.u.ibpkey = &ibpkey;
6811 return avc_has_perm(&selinux_state,
6813 SECCLASS_INFINIBAND_PKEY,
6814 INFINIBAND_PKEY__ACCESS, &ad);
6817 static int selinux_ib_endport_manage_subnet(void *ib_sec, const char *dev_name,
6820 struct common_audit_data ad;
6823 struct ib_security_struct *sec = ib_sec;
6824 struct lsm_ibendport_audit ibendport;
6826 err = security_ib_endport_sid(&selinux_state, dev_name, port_num,
6832 ad.type = LSM_AUDIT_DATA_IBENDPORT;
6833 strncpy(ibendport.dev_name, dev_name, sizeof(ibendport.dev_name));
6834 ibendport.port = port_num;
6835 ad.u.ibendport = &ibendport;
6836 return avc_has_perm(&selinux_state,
6838 SECCLASS_INFINIBAND_ENDPORT,
6839 INFINIBAND_ENDPORT__MANAGE_SUBNET, &ad);
6842 static int selinux_ib_alloc_security(void **ib_sec)
6844 struct ib_security_struct *sec;
6846 sec = kzalloc(sizeof(*sec), GFP_KERNEL);
6849 sec->sid = current_sid();
6855 static void selinux_ib_free_security(void *ib_sec)
6861 #ifdef CONFIG_BPF_SYSCALL
6862 static int selinux_bpf(int cmd, union bpf_attr *attr,
6865 u32 sid = current_sid();
6869 case BPF_MAP_CREATE:
6870 ret = avc_has_perm(&selinux_state,
6871 sid, sid, SECCLASS_BPF, BPF__MAP_CREATE,
6875 ret = avc_has_perm(&selinux_state,
6876 sid, sid, SECCLASS_BPF, BPF__PROG_LOAD,
6887 static u32 bpf_map_fmode_to_av(fmode_t fmode)
6891 if (fmode & FMODE_READ)
6892 av |= BPF__MAP_READ;
6893 if (fmode & FMODE_WRITE)
6894 av |= BPF__MAP_WRITE;
6898 /* This function will check the file pass through unix socket or binder to see
6899 * if it is a bpf related object. And apply correspinding checks on the bpf
6900 * object based on the type. The bpf maps and programs, not like other files and
6901 * socket, are using a shared anonymous inode inside the kernel as their inode.
6902 * So checking that inode cannot identify if the process have privilege to
6903 * access the bpf object and that's why we have to add this additional check in
6904 * selinux_file_receive and selinux_binder_transfer_files.
6906 static int bpf_fd_pass(struct file *file, u32 sid)
6908 struct bpf_security_struct *bpfsec;
6909 struct bpf_prog *prog;
6910 struct bpf_map *map;
6913 if (file->f_op == &bpf_map_fops) {
6914 map = file->private_data;
6915 bpfsec = map->security;
6916 ret = avc_has_perm(&selinux_state,
6917 sid, bpfsec->sid, SECCLASS_BPF,
6918 bpf_map_fmode_to_av(file->f_mode), NULL);
6921 } else if (file->f_op == &bpf_prog_fops) {
6922 prog = file->private_data;
6923 bpfsec = prog->aux->security;
6924 ret = avc_has_perm(&selinux_state,
6925 sid, bpfsec->sid, SECCLASS_BPF,
6926 BPF__PROG_RUN, NULL);
6933 static int selinux_bpf_map(struct bpf_map *map, fmode_t fmode)
6935 u32 sid = current_sid();
6936 struct bpf_security_struct *bpfsec;
6938 bpfsec = map->security;
6939 return avc_has_perm(&selinux_state,
6940 sid, bpfsec->sid, SECCLASS_BPF,
6941 bpf_map_fmode_to_av(fmode), NULL);
6944 static int selinux_bpf_prog(struct bpf_prog *prog)
6946 u32 sid = current_sid();
6947 struct bpf_security_struct *bpfsec;
6949 bpfsec = prog->aux->security;
6950 return avc_has_perm(&selinux_state,
6951 sid, bpfsec->sid, SECCLASS_BPF,
6952 BPF__PROG_RUN, NULL);
6955 static int selinux_bpf_map_alloc(struct bpf_map *map)
6957 struct bpf_security_struct *bpfsec;
6959 bpfsec = kzalloc(sizeof(*bpfsec), GFP_KERNEL);
6963 bpfsec->sid = current_sid();
6964 map->security = bpfsec;
6969 static void selinux_bpf_map_free(struct bpf_map *map)
6971 struct bpf_security_struct *bpfsec = map->security;
6973 map->security = NULL;
6977 static int selinux_bpf_prog_alloc(struct bpf_prog_aux *aux)
6979 struct bpf_security_struct *bpfsec;
6981 bpfsec = kzalloc(sizeof(*bpfsec), GFP_KERNEL);
6985 bpfsec->sid = current_sid();
6986 aux->security = bpfsec;
6991 static void selinux_bpf_prog_free(struct bpf_prog_aux *aux)
6993 struct bpf_security_struct *bpfsec = aux->security;
6995 aux->security = NULL;
7000 static int selinux_lockdown(enum lockdown_reason what)
7002 struct common_audit_data ad;
7003 u32 sid = current_sid();
7004 int invalid_reason = (what <= LOCKDOWN_NONE) ||
7005 (what == LOCKDOWN_INTEGRITY_MAX) ||
7006 (what >= LOCKDOWN_CONFIDENTIALITY_MAX);
7008 if (WARN(invalid_reason, "Invalid lockdown reason")) {
7009 audit_log(audit_context(),
7010 GFP_ATOMIC, AUDIT_SELINUX_ERR,
7011 "lockdown_reason=invalid");
7015 ad.type = LSM_AUDIT_DATA_LOCKDOWN;
7018 if (what <= LOCKDOWN_INTEGRITY_MAX)
7019 return avc_has_perm(&selinux_state,
7020 sid, sid, SECCLASS_LOCKDOWN,
7021 LOCKDOWN__INTEGRITY, &ad);
7023 return avc_has_perm(&selinux_state,
7024 sid, sid, SECCLASS_LOCKDOWN,
7025 LOCKDOWN__CONFIDENTIALITY, &ad);
7028 struct lsm_blob_sizes selinux_blob_sizes __lsm_ro_after_init = {
7029 .lbs_cred = sizeof(struct task_security_struct),
7030 .lbs_file = sizeof(struct file_security_struct),
7031 .lbs_inode = sizeof(struct inode_security_struct),
7032 .lbs_ipc = sizeof(struct ipc_security_struct),
7033 .lbs_msg_msg = sizeof(struct msg_security_struct),
7036 #ifdef CONFIG_PERF_EVENTS
7037 static int selinux_perf_event_open(struct perf_event_attr *attr, int type)
7039 u32 requested, sid = current_sid();
7041 if (type == PERF_SECURITY_OPEN)
7042 requested = PERF_EVENT__OPEN;
7043 else if (type == PERF_SECURITY_CPU)
7044 requested = PERF_EVENT__CPU;
7045 else if (type == PERF_SECURITY_KERNEL)
7046 requested = PERF_EVENT__KERNEL;
7047 else if (type == PERF_SECURITY_TRACEPOINT)
7048 requested = PERF_EVENT__TRACEPOINT;
7052 return avc_has_perm(&selinux_state, sid, sid, SECCLASS_PERF_EVENT,
7056 static int selinux_perf_event_alloc(struct perf_event *event)
7058 struct perf_event_security_struct *perfsec;
7060 perfsec = kzalloc(sizeof(*perfsec), GFP_KERNEL);
7064 perfsec->sid = current_sid();
7065 event->security = perfsec;
7070 static void selinux_perf_event_free(struct perf_event *event)
7072 struct perf_event_security_struct *perfsec = event->security;
7074 event->security = NULL;
7078 static int selinux_perf_event_read(struct perf_event *event)
7080 struct perf_event_security_struct *perfsec = event->security;
7081 u32 sid = current_sid();
7083 return avc_has_perm(&selinux_state, sid, perfsec->sid,
7084 SECCLASS_PERF_EVENT, PERF_EVENT__READ, NULL);
7087 static int selinux_perf_event_write(struct perf_event *event)
7089 struct perf_event_security_struct *perfsec = event->security;
7090 u32 sid = current_sid();
7092 return avc_has_perm(&selinux_state, sid, perfsec->sid,
7093 SECCLASS_PERF_EVENT, PERF_EVENT__WRITE, NULL);
7098 * IMPORTANT NOTE: When adding new hooks, please be careful to keep this order:
7099 * 1. any hooks that don't belong to (2.) or (3.) below,
7100 * 2. hooks that both access structures allocated by other hooks, and allocate
7101 * structures that can be later accessed by other hooks (mostly "cloning"
7103 * 3. hooks that only allocate structures that can be later accessed by other
7104 * hooks ("allocating" hooks).
7106 * Please follow block comment delimiters in the list to keep this order.
7108 * This ordering is needed for SELinux runtime disable to work at least somewhat
7109 * safely. Breaking the ordering rules above might lead to NULL pointer derefs
7110 * when disabling SELinux at runtime.
7112 static struct security_hook_list selinux_hooks[] __lsm_ro_after_init = {
7113 LSM_HOOK_INIT(binder_set_context_mgr, selinux_binder_set_context_mgr),
7114 LSM_HOOK_INIT(binder_transaction, selinux_binder_transaction),
7115 LSM_HOOK_INIT(binder_transfer_binder, selinux_binder_transfer_binder),
7116 LSM_HOOK_INIT(binder_transfer_file, selinux_binder_transfer_file),
7118 LSM_HOOK_INIT(ptrace_access_check, selinux_ptrace_access_check),
7119 LSM_HOOK_INIT(ptrace_traceme, selinux_ptrace_traceme),
7120 LSM_HOOK_INIT(capget, selinux_capget),
7121 LSM_HOOK_INIT(capset, selinux_capset),
7122 LSM_HOOK_INIT(capable, selinux_capable),
7123 LSM_HOOK_INIT(quotactl, selinux_quotactl),
7124 LSM_HOOK_INIT(quota_on, selinux_quota_on),
7125 LSM_HOOK_INIT(syslog, selinux_syslog),
7126 LSM_HOOK_INIT(vm_enough_memory, selinux_vm_enough_memory),
7128 LSM_HOOK_INIT(netlink_send, selinux_netlink_send),
7130 LSM_HOOK_INIT(bprm_creds_for_exec, selinux_bprm_creds_for_exec),
7131 LSM_HOOK_INIT(bprm_committing_creds, selinux_bprm_committing_creds),
7132 LSM_HOOK_INIT(bprm_committed_creds, selinux_bprm_committed_creds),
7134 LSM_HOOK_INIT(sb_free_security, selinux_sb_free_security),
7135 LSM_HOOK_INIT(sb_free_mnt_opts, selinux_free_mnt_opts),
7136 LSM_HOOK_INIT(sb_mnt_opts_compat, selinux_sb_mnt_opts_compat),
7137 LSM_HOOK_INIT(sb_remount, selinux_sb_remount),
7138 LSM_HOOK_INIT(sb_kern_mount, selinux_sb_kern_mount),
7139 LSM_HOOK_INIT(sb_show_options, selinux_sb_show_options),
7140 LSM_HOOK_INIT(sb_statfs, selinux_sb_statfs),
7141 LSM_HOOK_INIT(sb_mount, selinux_mount),
7142 LSM_HOOK_INIT(sb_umount, selinux_umount),
7143 LSM_HOOK_INIT(sb_set_mnt_opts, selinux_set_mnt_opts),
7144 LSM_HOOK_INIT(sb_clone_mnt_opts, selinux_sb_clone_mnt_opts),
7146 LSM_HOOK_INIT(move_mount, selinux_move_mount),
7148 LSM_HOOK_INIT(dentry_init_security, selinux_dentry_init_security),
7149 LSM_HOOK_INIT(dentry_create_files_as, selinux_dentry_create_files_as),
7151 LSM_HOOK_INIT(inode_free_security, selinux_inode_free_security),
7152 LSM_HOOK_INIT(inode_init_security, selinux_inode_init_security),
7153 LSM_HOOK_INIT(inode_init_security_anon, selinux_inode_init_security_anon),
7154 LSM_HOOK_INIT(inode_create, selinux_inode_create),
7155 LSM_HOOK_INIT(inode_link, selinux_inode_link),
7156 LSM_HOOK_INIT(inode_unlink, selinux_inode_unlink),
7157 LSM_HOOK_INIT(inode_symlink, selinux_inode_symlink),
7158 LSM_HOOK_INIT(inode_mkdir, selinux_inode_mkdir),
7159 LSM_HOOK_INIT(inode_rmdir, selinux_inode_rmdir),
7160 LSM_HOOK_INIT(inode_mknod, selinux_inode_mknod),
7161 LSM_HOOK_INIT(inode_rename, selinux_inode_rename),
7162 LSM_HOOK_INIT(inode_readlink, selinux_inode_readlink),
7163 LSM_HOOK_INIT(inode_follow_link, selinux_inode_follow_link),
7164 LSM_HOOK_INIT(inode_permission, selinux_inode_permission),
7165 LSM_HOOK_INIT(inode_setattr, selinux_inode_setattr),
7166 LSM_HOOK_INIT(inode_getattr, selinux_inode_getattr),
7167 LSM_HOOK_INIT(inode_setxattr, selinux_inode_setxattr),
7168 LSM_HOOK_INIT(inode_post_setxattr, selinux_inode_post_setxattr),
7169 LSM_HOOK_INIT(inode_getxattr, selinux_inode_getxattr),
7170 LSM_HOOK_INIT(inode_listxattr, selinux_inode_listxattr),
7171 LSM_HOOK_INIT(inode_removexattr, selinux_inode_removexattr),
7172 LSM_HOOK_INIT(inode_getsecurity, selinux_inode_getsecurity),
7173 LSM_HOOK_INIT(inode_setsecurity, selinux_inode_setsecurity),
7174 LSM_HOOK_INIT(inode_listsecurity, selinux_inode_listsecurity),
7175 LSM_HOOK_INIT(inode_getsecid, selinux_inode_getsecid),
7176 LSM_HOOK_INIT(inode_copy_up, selinux_inode_copy_up),
7177 LSM_HOOK_INIT(inode_copy_up_xattr, selinux_inode_copy_up_xattr),
7178 LSM_HOOK_INIT(path_notify, selinux_path_notify),
7180 LSM_HOOK_INIT(kernfs_init_security, selinux_kernfs_init_security),
7182 LSM_HOOK_INIT(file_permission, selinux_file_permission),
7183 LSM_HOOK_INIT(file_alloc_security, selinux_file_alloc_security),
7184 LSM_HOOK_INIT(file_ioctl, selinux_file_ioctl),
7185 LSM_HOOK_INIT(mmap_file, selinux_mmap_file),
7186 LSM_HOOK_INIT(mmap_addr, selinux_mmap_addr),
7187 LSM_HOOK_INIT(file_mprotect, selinux_file_mprotect),
7188 LSM_HOOK_INIT(file_lock, selinux_file_lock),
7189 LSM_HOOK_INIT(file_fcntl, selinux_file_fcntl),
7190 LSM_HOOK_INIT(file_set_fowner, selinux_file_set_fowner),
7191 LSM_HOOK_INIT(file_send_sigiotask, selinux_file_send_sigiotask),
7192 LSM_HOOK_INIT(file_receive, selinux_file_receive),
7194 LSM_HOOK_INIT(file_open, selinux_file_open),
7196 LSM_HOOK_INIT(task_alloc, selinux_task_alloc),
7197 LSM_HOOK_INIT(cred_prepare, selinux_cred_prepare),
7198 LSM_HOOK_INIT(cred_transfer, selinux_cred_transfer),
7199 LSM_HOOK_INIT(cred_getsecid, selinux_cred_getsecid),
7200 LSM_HOOK_INIT(kernel_act_as, selinux_kernel_act_as),
7201 LSM_HOOK_INIT(kernel_create_files_as, selinux_kernel_create_files_as),
7202 LSM_HOOK_INIT(kernel_module_request, selinux_kernel_module_request),
7203 LSM_HOOK_INIT(kernel_load_data, selinux_kernel_load_data),
7204 LSM_HOOK_INIT(kernel_read_file, selinux_kernel_read_file),
7205 LSM_HOOK_INIT(task_setpgid, selinux_task_setpgid),
7206 LSM_HOOK_INIT(task_getpgid, selinux_task_getpgid),
7207 LSM_HOOK_INIT(task_getsid, selinux_task_getsid),
7208 LSM_HOOK_INIT(task_getsecid_subj, selinux_task_getsecid),
7209 LSM_HOOK_INIT(task_getsecid_obj, selinux_task_getsecid),
7210 LSM_HOOK_INIT(task_setnice, selinux_task_setnice),
7211 LSM_HOOK_INIT(task_setioprio, selinux_task_setioprio),
7212 LSM_HOOK_INIT(task_getioprio, selinux_task_getioprio),
7213 LSM_HOOK_INIT(task_prlimit, selinux_task_prlimit),
7214 LSM_HOOK_INIT(task_setrlimit, selinux_task_setrlimit),
7215 LSM_HOOK_INIT(task_setscheduler, selinux_task_setscheduler),
7216 LSM_HOOK_INIT(task_getscheduler, selinux_task_getscheduler),
7217 LSM_HOOK_INIT(task_movememory, selinux_task_movememory),
7218 LSM_HOOK_INIT(task_kill, selinux_task_kill),
7219 LSM_HOOK_INIT(task_to_inode, selinux_task_to_inode),
7221 LSM_HOOK_INIT(ipc_permission, selinux_ipc_permission),
7222 LSM_HOOK_INIT(ipc_getsecid, selinux_ipc_getsecid),
7224 LSM_HOOK_INIT(msg_queue_associate, selinux_msg_queue_associate),
7225 LSM_HOOK_INIT(msg_queue_msgctl, selinux_msg_queue_msgctl),
7226 LSM_HOOK_INIT(msg_queue_msgsnd, selinux_msg_queue_msgsnd),
7227 LSM_HOOK_INIT(msg_queue_msgrcv, selinux_msg_queue_msgrcv),
7229 LSM_HOOK_INIT(shm_associate, selinux_shm_associate),
7230 LSM_HOOK_INIT(shm_shmctl, selinux_shm_shmctl),
7231 LSM_HOOK_INIT(shm_shmat, selinux_shm_shmat),
7233 LSM_HOOK_INIT(sem_associate, selinux_sem_associate),
7234 LSM_HOOK_INIT(sem_semctl, selinux_sem_semctl),
7235 LSM_HOOK_INIT(sem_semop, selinux_sem_semop),
7237 LSM_HOOK_INIT(d_instantiate, selinux_d_instantiate),
7239 LSM_HOOK_INIT(getprocattr, selinux_getprocattr),
7240 LSM_HOOK_INIT(setprocattr, selinux_setprocattr),
7242 LSM_HOOK_INIT(ismaclabel, selinux_ismaclabel),
7243 LSM_HOOK_INIT(secctx_to_secid, selinux_secctx_to_secid),
7244 LSM_HOOK_INIT(release_secctx, selinux_release_secctx),
7245 LSM_HOOK_INIT(inode_invalidate_secctx, selinux_inode_invalidate_secctx),
7246 LSM_HOOK_INIT(inode_notifysecctx, selinux_inode_notifysecctx),
7247 LSM_HOOK_INIT(inode_setsecctx, selinux_inode_setsecctx),
7249 LSM_HOOK_INIT(unix_stream_connect, selinux_socket_unix_stream_connect),
7250 LSM_HOOK_INIT(unix_may_send, selinux_socket_unix_may_send),
7252 LSM_HOOK_INIT(socket_create, selinux_socket_create),
7253 LSM_HOOK_INIT(socket_post_create, selinux_socket_post_create),
7254 LSM_HOOK_INIT(socket_socketpair, selinux_socket_socketpair),
7255 LSM_HOOK_INIT(socket_bind, selinux_socket_bind),
7256 LSM_HOOK_INIT(socket_connect, selinux_socket_connect),
7257 LSM_HOOK_INIT(socket_listen, selinux_socket_listen),
7258 LSM_HOOK_INIT(socket_accept, selinux_socket_accept),
7259 LSM_HOOK_INIT(socket_sendmsg, selinux_socket_sendmsg),
7260 LSM_HOOK_INIT(socket_recvmsg, selinux_socket_recvmsg),
7261 LSM_HOOK_INIT(socket_getsockname, selinux_socket_getsockname),
7262 LSM_HOOK_INIT(socket_getpeername, selinux_socket_getpeername),
7263 LSM_HOOK_INIT(socket_getsockopt, selinux_socket_getsockopt),
7264 LSM_HOOK_INIT(socket_setsockopt, selinux_socket_setsockopt),
7265 LSM_HOOK_INIT(socket_shutdown, selinux_socket_shutdown),
7266 LSM_HOOK_INIT(socket_sock_rcv_skb, selinux_socket_sock_rcv_skb),
7267 LSM_HOOK_INIT(socket_getpeersec_stream,
7268 selinux_socket_getpeersec_stream),
7269 LSM_HOOK_INIT(socket_getpeersec_dgram, selinux_socket_getpeersec_dgram),
7270 LSM_HOOK_INIT(sk_free_security, selinux_sk_free_security),
7271 LSM_HOOK_INIT(sk_clone_security, selinux_sk_clone_security),
7272 LSM_HOOK_INIT(sk_getsecid, selinux_sk_getsecid),
7273 LSM_HOOK_INIT(sock_graft, selinux_sock_graft),
7274 LSM_HOOK_INIT(sctp_assoc_request, selinux_sctp_assoc_request),
7275 LSM_HOOK_INIT(sctp_sk_clone, selinux_sctp_sk_clone),
7276 LSM_HOOK_INIT(sctp_bind_connect, selinux_sctp_bind_connect),
7277 LSM_HOOK_INIT(inet_conn_request, selinux_inet_conn_request),
7278 LSM_HOOK_INIT(inet_csk_clone, selinux_inet_csk_clone),
7279 LSM_HOOK_INIT(inet_conn_established, selinux_inet_conn_established),
7280 LSM_HOOK_INIT(secmark_relabel_packet, selinux_secmark_relabel_packet),
7281 LSM_HOOK_INIT(secmark_refcount_inc, selinux_secmark_refcount_inc),
7282 LSM_HOOK_INIT(secmark_refcount_dec, selinux_secmark_refcount_dec),
7283 LSM_HOOK_INIT(req_classify_flow, selinux_req_classify_flow),
7284 LSM_HOOK_INIT(tun_dev_free_security, selinux_tun_dev_free_security),
7285 LSM_HOOK_INIT(tun_dev_create, selinux_tun_dev_create),
7286 LSM_HOOK_INIT(tun_dev_attach_queue, selinux_tun_dev_attach_queue),
7287 LSM_HOOK_INIT(tun_dev_attach, selinux_tun_dev_attach),
7288 LSM_HOOK_INIT(tun_dev_open, selinux_tun_dev_open),
7289 #ifdef CONFIG_SECURITY_INFINIBAND
7290 LSM_HOOK_INIT(ib_pkey_access, selinux_ib_pkey_access),
7291 LSM_HOOK_INIT(ib_endport_manage_subnet,
7292 selinux_ib_endport_manage_subnet),
7293 LSM_HOOK_INIT(ib_free_security, selinux_ib_free_security),
7295 #ifdef CONFIG_SECURITY_NETWORK_XFRM
7296 LSM_HOOK_INIT(xfrm_policy_free_security, selinux_xfrm_policy_free),
7297 LSM_HOOK_INIT(xfrm_policy_delete_security, selinux_xfrm_policy_delete),
7298 LSM_HOOK_INIT(xfrm_state_free_security, selinux_xfrm_state_free),
7299 LSM_HOOK_INIT(xfrm_state_delete_security, selinux_xfrm_state_delete),
7300 LSM_HOOK_INIT(xfrm_policy_lookup, selinux_xfrm_policy_lookup),
7301 LSM_HOOK_INIT(xfrm_state_pol_flow_match,
7302 selinux_xfrm_state_pol_flow_match),
7303 LSM_HOOK_INIT(xfrm_decode_session, selinux_xfrm_decode_session),
7307 LSM_HOOK_INIT(key_free, selinux_key_free),
7308 LSM_HOOK_INIT(key_permission, selinux_key_permission),
7309 LSM_HOOK_INIT(key_getsecurity, selinux_key_getsecurity),
7310 #ifdef CONFIG_KEY_NOTIFICATIONS
7311 LSM_HOOK_INIT(watch_key, selinux_watch_key),
7316 LSM_HOOK_INIT(audit_rule_known, selinux_audit_rule_known),
7317 LSM_HOOK_INIT(audit_rule_match, selinux_audit_rule_match),
7318 LSM_HOOK_INIT(audit_rule_free, selinux_audit_rule_free),
7321 #ifdef CONFIG_BPF_SYSCALL
7322 LSM_HOOK_INIT(bpf, selinux_bpf),
7323 LSM_HOOK_INIT(bpf_map, selinux_bpf_map),
7324 LSM_HOOK_INIT(bpf_prog, selinux_bpf_prog),
7325 LSM_HOOK_INIT(bpf_map_free_security, selinux_bpf_map_free),
7326 LSM_HOOK_INIT(bpf_prog_free_security, selinux_bpf_prog_free),
7329 #ifdef CONFIG_PERF_EVENTS
7330 LSM_HOOK_INIT(perf_event_open, selinux_perf_event_open),
7331 LSM_HOOK_INIT(perf_event_free, selinux_perf_event_free),
7332 LSM_HOOK_INIT(perf_event_read, selinux_perf_event_read),
7333 LSM_HOOK_INIT(perf_event_write, selinux_perf_event_write),
7336 LSM_HOOK_INIT(locked_down, selinux_lockdown),
7339 * PUT "CLONING" (ACCESSING + ALLOCATING) HOOKS HERE
7341 LSM_HOOK_INIT(fs_context_dup, selinux_fs_context_dup),
7342 LSM_HOOK_INIT(fs_context_parse_param, selinux_fs_context_parse_param),
7343 LSM_HOOK_INIT(sb_eat_lsm_opts, selinux_sb_eat_lsm_opts),
7344 LSM_HOOK_INIT(sb_add_mnt_opt, selinux_add_mnt_opt),
7345 #ifdef CONFIG_SECURITY_NETWORK_XFRM
7346 LSM_HOOK_INIT(xfrm_policy_clone_security, selinux_xfrm_policy_clone),
7350 * PUT "ALLOCATING" HOOKS HERE
7352 LSM_HOOK_INIT(msg_msg_alloc_security, selinux_msg_msg_alloc_security),
7353 LSM_HOOK_INIT(msg_queue_alloc_security,
7354 selinux_msg_queue_alloc_security),
7355 LSM_HOOK_INIT(shm_alloc_security, selinux_shm_alloc_security),
7356 LSM_HOOK_INIT(sb_alloc_security, selinux_sb_alloc_security),
7357 LSM_HOOK_INIT(inode_alloc_security, selinux_inode_alloc_security),
7358 LSM_HOOK_INIT(sem_alloc_security, selinux_sem_alloc_security),
7359 LSM_HOOK_INIT(secid_to_secctx, selinux_secid_to_secctx),
7360 LSM_HOOK_INIT(inode_getsecctx, selinux_inode_getsecctx),
7361 LSM_HOOK_INIT(sk_alloc_security, selinux_sk_alloc_security),
7362 LSM_HOOK_INIT(tun_dev_alloc_security, selinux_tun_dev_alloc_security),
7363 #ifdef CONFIG_SECURITY_INFINIBAND
7364 LSM_HOOK_INIT(ib_alloc_security, selinux_ib_alloc_security),
7366 #ifdef CONFIG_SECURITY_NETWORK_XFRM
7367 LSM_HOOK_INIT(xfrm_policy_alloc_security, selinux_xfrm_policy_alloc),
7368 LSM_HOOK_INIT(xfrm_state_alloc, selinux_xfrm_state_alloc),
7369 LSM_HOOK_INIT(xfrm_state_alloc_acquire,
7370 selinux_xfrm_state_alloc_acquire),
7373 LSM_HOOK_INIT(key_alloc, selinux_key_alloc),
7376 LSM_HOOK_INIT(audit_rule_init, selinux_audit_rule_init),
7378 #ifdef CONFIG_BPF_SYSCALL
7379 LSM_HOOK_INIT(bpf_map_alloc_security, selinux_bpf_map_alloc),
7380 LSM_HOOK_INIT(bpf_prog_alloc_security, selinux_bpf_prog_alloc),
7382 #ifdef CONFIG_PERF_EVENTS
7383 LSM_HOOK_INIT(perf_event_alloc, selinux_perf_event_alloc),
7387 static __init int selinux_init(void)
7389 pr_info("SELinux: Initializing.\n");
7391 memset(&selinux_state, 0, sizeof(selinux_state));
7392 enforcing_set(&selinux_state, selinux_enforcing_boot);
7393 checkreqprot_set(&selinux_state, selinux_checkreqprot_boot);
7394 selinux_avc_init(&selinux_state.avc);
7395 mutex_init(&selinux_state.status_lock);
7396 mutex_init(&selinux_state.policy_mutex);
7398 /* Set the security state for the initial task. */
7399 cred_init_security();
7401 default_noexec = !(VM_DATA_DEFAULT_FLAGS & VM_EXEC);
7407 ebitmap_cache_init();
7409 hashtab_cache_init();
7411 security_add_hooks(selinux_hooks, ARRAY_SIZE(selinux_hooks), "selinux");
7413 if (avc_add_callback(selinux_netcache_avc_callback, AVC_CALLBACK_RESET))
7414 panic("SELinux: Unable to register AVC netcache callback\n");
7416 if (avc_add_callback(selinux_lsm_notifier_avc_callback, AVC_CALLBACK_RESET))
7417 panic("SELinux: Unable to register AVC LSM notifier callback\n");
7419 if (selinux_enforcing_boot)
7420 pr_debug("SELinux: Starting in enforcing mode\n");
7422 pr_debug("SELinux: Starting in permissive mode\n");
7424 fs_validate_description("selinux", selinux_fs_parameters);
7429 static void delayed_superblock_init(struct super_block *sb, void *unused)
7431 selinux_set_mnt_opts(sb, NULL, 0, NULL);
7434 void selinux_complete_init(void)
7436 pr_debug("SELinux: Completing initialization.\n");
7438 /* Set up any superblocks initialized prior to the policy load. */
7439 pr_debug("SELinux: Setting up existing superblocks.\n");
7440 iterate_supers(delayed_superblock_init, NULL);
7443 /* SELinux requires early initialization in order to label
7444 all processes and objects when they are created. */
7445 DEFINE_LSM(selinux) = {
7447 .flags = LSM_FLAG_LEGACY_MAJOR | LSM_FLAG_EXCLUSIVE,
7448 .enabled = &selinux_enabled_boot,
7449 .blobs = &selinux_blob_sizes,
7450 .init = selinux_init,
7453 #if defined(CONFIG_NETFILTER)
7455 static const struct nf_hook_ops selinux_nf_ops[] = {
7457 .hook = selinux_ipv4_postroute,
7459 .hooknum = NF_INET_POST_ROUTING,
7460 .priority = NF_IP_PRI_SELINUX_LAST,
7463 .hook = selinux_ipv4_forward,
7465 .hooknum = NF_INET_FORWARD,
7466 .priority = NF_IP_PRI_SELINUX_FIRST,
7469 .hook = selinux_ipv4_output,
7471 .hooknum = NF_INET_LOCAL_OUT,
7472 .priority = NF_IP_PRI_SELINUX_FIRST,
7474 #if IS_ENABLED(CONFIG_IPV6)
7476 .hook = selinux_ipv6_postroute,
7478 .hooknum = NF_INET_POST_ROUTING,
7479 .priority = NF_IP6_PRI_SELINUX_LAST,
7482 .hook = selinux_ipv6_forward,
7484 .hooknum = NF_INET_FORWARD,
7485 .priority = NF_IP6_PRI_SELINUX_FIRST,
7488 .hook = selinux_ipv6_output,
7490 .hooknum = NF_INET_LOCAL_OUT,
7491 .priority = NF_IP6_PRI_SELINUX_FIRST,
7496 static int __net_init selinux_nf_register(struct net *net)
7498 return nf_register_net_hooks(net, selinux_nf_ops,
7499 ARRAY_SIZE(selinux_nf_ops));
7502 static void __net_exit selinux_nf_unregister(struct net *net)
7504 nf_unregister_net_hooks(net, selinux_nf_ops,
7505 ARRAY_SIZE(selinux_nf_ops));
7508 static struct pernet_operations selinux_net_ops = {
7509 .init = selinux_nf_register,
7510 .exit = selinux_nf_unregister,
7513 static int __init selinux_nf_ip_init(void)
7517 if (!selinux_enabled_boot)
7520 pr_debug("SELinux: Registering netfilter hooks\n");
7522 err = register_pernet_subsys(&selinux_net_ops);
7524 panic("SELinux: register_pernet_subsys: error %d\n", err);
7528 __initcall(selinux_nf_ip_init);
7530 #ifdef CONFIG_SECURITY_SELINUX_DISABLE
7531 static void selinux_nf_ip_exit(void)
7533 pr_debug("SELinux: Unregistering netfilter hooks\n");
7535 unregister_pernet_subsys(&selinux_net_ops);
7539 #else /* CONFIG_NETFILTER */
7541 #ifdef CONFIG_SECURITY_SELINUX_DISABLE
7542 #define selinux_nf_ip_exit()
7545 #endif /* CONFIG_NETFILTER */
7547 #ifdef CONFIG_SECURITY_SELINUX_DISABLE
7548 int selinux_disable(struct selinux_state *state)
7550 if (selinux_initialized(state)) {
7551 /* Not permitted after initial policy load. */
7555 if (selinux_disabled(state)) {
7556 /* Only do this once. */
7560 selinux_mark_disabled(state);
7562 pr_info("SELinux: Disabled at runtime.\n");
7565 * Unregister netfilter hooks.
7566 * Must be done before security_delete_hooks() to avoid breaking
7569 selinux_nf_ip_exit();
7571 security_delete_hooks(selinux_hooks, ARRAY_SIZE(selinux_hooks));
7573 /* Try to destroy the avc node cache */
7576 /* Unregister selinuxfs. */