1 // SPDX-License-Identifier: GPL-2.0-only
3 * NSA Security-Enhanced Linux (SELinux) security module
5 * This file contains the SELinux hook function implementations.
7 * Authors: Stephen Smalley, <sds@tycho.nsa.gov>
8 * Chris Vance, <cvance@nai.com>
9 * Wayne Salamon, <wsalamon@nai.com>
10 * James Morris <jmorris@redhat.com>
12 * Copyright (C) 2001,2002 Networks Associates Technology, Inc.
13 * Copyright (C) 2003-2008 Red Hat, Inc., James Morris <jmorris@redhat.com>
14 * Eric Paris <eparis@redhat.com>
15 * Copyright (C) 2004-2005 Trusted Computer Solutions, Inc.
16 * <dgoeddel@trustedcs.com>
17 * Copyright (C) 2006, 2007, 2009 Hewlett-Packard Development Company, L.P.
18 * Paul Moore <paul@paul-moore.com>
19 * Copyright (C) 2007 Hitachi Software Engineering Co., Ltd.
20 * Yuichi Nakamura <ynakam@hitachisoft.jp>
21 * Copyright (C) 2016 Mellanox Technologies
24 #include <linux/init.h>
26 #include <linux/kernel.h>
27 #include <linux/kernel_read_file.h>
28 #include <linux/tracehook.h>
29 #include <linux/errno.h>
30 #include <linux/sched/signal.h>
31 #include <linux/sched/task.h>
32 #include <linux/lsm_hooks.h>
33 #include <linux/xattr.h>
34 #include <linux/capability.h>
35 #include <linux/unistd.h>
37 #include <linux/mman.h>
38 #include <linux/slab.h>
39 #include <linux/pagemap.h>
40 #include <linux/proc_fs.h>
41 #include <linux/swap.h>
42 #include <linux/spinlock.h>
43 #include <linux/syscalls.h>
44 #include <linux/dcache.h>
45 #include <linux/file.h>
46 #include <linux/fdtable.h>
47 #include <linux/namei.h>
48 #include <linux/mount.h>
49 #include <linux/fs_context.h>
50 #include <linux/fs_parser.h>
51 #include <linux/netfilter_ipv4.h>
52 #include <linux/netfilter_ipv6.h>
53 #include <linux/tty.h>
55 #include <net/ip.h> /* for local_port_range[] */
56 #include <net/tcp.h> /* struct or_callable used in sock_rcv_skb */
57 #include <net/inet_connection_sock.h>
58 #include <net/net_namespace.h>
59 #include <net/netlabel.h>
60 #include <linux/uaccess.h>
61 #include <asm/ioctls.h>
62 #include <linux/atomic.h>
63 #include <linux/bitops.h>
64 #include <linux/interrupt.h>
65 #include <linux/netdevice.h> /* for network interface checks */
66 #include <net/netlink.h>
67 #include <linux/tcp.h>
68 #include <linux/udp.h>
69 #include <linux/dccp.h>
70 #include <linux/sctp.h>
71 #include <net/sctp/structs.h>
72 #include <linux/quota.h>
73 #include <linux/un.h> /* for Unix socket types */
74 #include <net/af_unix.h> /* for Unix socket types */
75 #include <linux/parser.h>
76 #include <linux/nfs_mount.h>
78 #include <linux/hugetlb.h>
79 #include <linux/personality.h>
80 #include <linux/audit.h>
81 #include <linux/string.h>
82 #include <linux/mutex.h>
83 #include <linux/posix-timers.h>
84 #include <linux/syslog.h>
85 #include <linux/user_namespace.h>
86 #include <linux/export.h>
87 #include <linux/msg.h>
88 #include <linux/shm.h>
89 #include <linux/bpf.h>
90 #include <linux/kernfs.h>
91 #include <linux/stringhash.h> /* for hashlen_string() */
92 #include <uapi/linux/mount.h>
93 #include <linux/fsnotify.h>
94 #include <linux/fanotify.h>
103 #include "netlabel.h"
107 struct selinux_state selinux_state;
109 /* SECMARK reference count */
110 static atomic_t selinux_secmark_refcount = ATOMIC_INIT(0);
112 #ifdef CONFIG_SECURITY_SELINUX_DEVELOP
113 static int selinux_enforcing_boot __initdata;
115 static int __init enforcing_setup(char *str)
117 unsigned long enforcing;
118 if (!kstrtoul(str, 0, &enforcing))
119 selinux_enforcing_boot = enforcing ? 1 : 0;
122 __setup("enforcing=", enforcing_setup);
124 #define selinux_enforcing_boot 1
127 int selinux_enabled_boot __initdata = 1;
128 #ifdef CONFIG_SECURITY_SELINUX_BOOTPARAM
129 static int __init selinux_enabled_setup(char *str)
131 unsigned long enabled;
132 if (!kstrtoul(str, 0, &enabled))
133 selinux_enabled_boot = enabled ? 1 : 0;
136 __setup("selinux=", selinux_enabled_setup);
139 static unsigned int selinux_checkreqprot_boot =
140 CONFIG_SECURITY_SELINUX_CHECKREQPROT_VALUE;
142 static int __init checkreqprot_setup(char *str)
144 unsigned long checkreqprot;
146 if (!kstrtoul(str, 0, &checkreqprot)) {
147 selinux_checkreqprot_boot = checkreqprot ? 1 : 0;
149 pr_warn("SELinux: checkreqprot set to 1 via kernel parameter. This is deprecated and will be rejected in a future kernel release.\n");
153 __setup("checkreqprot=", checkreqprot_setup);
156 * selinux_secmark_enabled - Check to see if SECMARK is currently enabled
159 * This function checks the SECMARK reference counter to see if any SECMARK
160 * targets are currently configured, if the reference counter is greater than
161 * zero SECMARK is considered to be enabled. Returns true (1) if SECMARK is
162 * enabled, false (0) if SECMARK is disabled. If the always_check_network
163 * policy capability is enabled, SECMARK is always considered enabled.
166 static int selinux_secmark_enabled(void)
168 return (selinux_policycap_alwaysnetwork() ||
169 atomic_read(&selinux_secmark_refcount));
173 * selinux_peerlbl_enabled - Check to see if peer labeling is currently enabled
176 * This function checks if NetLabel or labeled IPSEC is enabled. Returns true
177 * (1) if any are enabled or false (0) if neither are enabled. If the
178 * always_check_network policy capability is enabled, peer labeling
179 * is always considered enabled.
182 static int selinux_peerlbl_enabled(void)
184 return (selinux_policycap_alwaysnetwork() ||
185 netlbl_enabled() || selinux_xfrm_enabled());
188 static int selinux_netcache_avc_callback(u32 event)
190 if (event == AVC_CALLBACK_RESET) {
199 static int selinux_lsm_notifier_avc_callback(u32 event)
201 if (event == AVC_CALLBACK_RESET) {
203 call_blocking_lsm_notifier(LSM_POLICY_CHANGE, NULL);
210 * initialise the security for the init task
212 static void cred_init_security(void)
214 struct cred *cred = (struct cred *) current->real_cred;
215 struct task_security_struct *tsec;
217 tsec = selinux_cred(cred);
218 tsec->osid = tsec->sid = SECINITSID_KERNEL;
222 * get the security ID of a set of credentials
224 static inline u32 cred_sid(const struct cred *cred)
226 const struct task_security_struct *tsec;
228 tsec = selinux_cred(cred);
233 * get the subjective security ID of a task
235 static inline u32 task_sid_subj(const struct task_struct *task)
240 sid = cred_sid(rcu_dereference(task->cred));
246 * get the objective security ID of a task
248 static inline u32 task_sid_obj(const struct task_struct *task)
253 sid = cred_sid(__task_cred(task));
259 * get the security ID of a task for use with binder
261 static inline u32 task_sid_binder(const struct task_struct *task)
264 * In many case where this function is used we should be using the
265 * task's subjective SID, but we can't reliably access the subjective
266 * creds of a task other than our own so we must use the objective
267 * creds/SID, which are safe to access. The downside is that if a task
268 * is temporarily overriding it's creds it will not be reflected here;
269 * however, it isn't clear that binder would handle that case well
272 * If this ever changes and we can safely reference the subjective
273 * creds/SID of another task, this function will make it easier to
274 * identify the various places where we make use of the task SIDs in
275 * the binder code. It is also likely that we will need to adjust
276 * the main drivers/android binder code as well.
278 return task_sid_obj(task);
281 static int inode_doinit_with_dentry(struct inode *inode, struct dentry *opt_dentry);
284 * Try reloading inode security labels that have been marked as invalid. The
285 * @may_sleep parameter indicates when sleeping and thus reloading labels is
286 * allowed; when set to false, returns -ECHILD when the label is
287 * invalid. The @dentry parameter should be set to a dentry of the inode.
289 static int __inode_security_revalidate(struct inode *inode,
290 struct dentry *dentry,
293 struct inode_security_struct *isec = selinux_inode(inode);
295 might_sleep_if(may_sleep);
297 if (selinux_initialized(&selinux_state) &&
298 isec->initialized != LABEL_INITIALIZED) {
303 * Try reloading the inode security label. This will fail if
304 * @opt_dentry is NULL and no dentry for this inode can be
305 * found; in that case, continue using the old label.
307 inode_doinit_with_dentry(inode, dentry);
312 static struct inode_security_struct *inode_security_novalidate(struct inode *inode)
314 return selinux_inode(inode);
317 static struct inode_security_struct *inode_security_rcu(struct inode *inode, bool rcu)
321 error = __inode_security_revalidate(inode, NULL, !rcu);
323 return ERR_PTR(error);
324 return selinux_inode(inode);
328 * Get the security label of an inode.
330 static struct inode_security_struct *inode_security(struct inode *inode)
332 __inode_security_revalidate(inode, NULL, true);
333 return selinux_inode(inode);
336 static struct inode_security_struct *backing_inode_security_novalidate(struct dentry *dentry)
338 struct inode *inode = d_backing_inode(dentry);
340 return selinux_inode(inode);
344 * Get the security label of a dentry's backing inode.
346 static struct inode_security_struct *backing_inode_security(struct dentry *dentry)
348 struct inode *inode = d_backing_inode(dentry);
350 __inode_security_revalidate(inode, dentry, true);
351 return selinux_inode(inode);
354 static void inode_free_security(struct inode *inode)
356 struct inode_security_struct *isec = selinux_inode(inode);
357 struct superblock_security_struct *sbsec;
361 sbsec = inode->i_sb->s_security;
363 * As not all inode security structures are in a list, we check for
364 * empty list outside of the lock to make sure that we won't waste
365 * time taking a lock doing nothing.
367 * The list_del_init() function can be safely called more than once.
368 * It should not be possible for this function to be called with
369 * concurrent list_add(), but for better safety against future changes
370 * in the code, we use list_empty_careful() here.
372 if (!list_empty_careful(&isec->list)) {
373 spin_lock(&sbsec->isec_lock);
374 list_del_init(&isec->list);
375 spin_unlock(&sbsec->isec_lock);
379 static void superblock_free_security(struct super_block *sb)
381 struct superblock_security_struct *sbsec = sb->s_security;
382 sb->s_security = NULL;
386 struct selinux_mnt_opts {
387 const char *fscontext, *context, *rootcontext, *defcontext;
390 static void selinux_free_mnt_opts(void *mnt_opts)
392 struct selinux_mnt_opts *opts = mnt_opts;
393 kfree(opts->fscontext);
394 kfree(opts->context);
395 kfree(opts->rootcontext);
396 kfree(opts->defcontext);
409 #define A(s, has_arg) {#s, sizeof(#s) - 1, Opt_##s, has_arg}
419 A(rootcontext, true),
424 static int match_opt_prefix(char *s, int l, char **arg)
428 for (i = 0; i < ARRAY_SIZE(tokens); i++) {
429 size_t len = tokens[i].len;
430 if (len > l || memcmp(s, tokens[i].name, len))
432 if (tokens[i].has_arg) {
433 if (len == l || s[len] != '=')
438 return tokens[i].opt;
443 #define SEL_MOUNT_FAIL_MSG "SELinux: duplicate or incompatible mount options\n"
445 static int may_context_mount_sb_relabel(u32 sid,
446 struct superblock_security_struct *sbsec,
447 const struct cred *cred)
449 const struct task_security_struct *tsec = selinux_cred(cred);
452 rc = avc_has_perm(&selinux_state,
453 tsec->sid, sbsec->sid, SECCLASS_FILESYSTEM,
454 FILESYSTEM__RELABELFROM, NULL);
458 rc = avc_has_perm(&selinux_state,
459 tsec->sid, sid, SECCLASS_FILESYSTEM,
460 FILESYSTEM__RELABELTO, NULL);
464 static int may_context_mount_inode_relabel(u32 sid,
465 struct superblock_security_struct *sbsec,
466 const struct cred *cred)
468 const struct task_security_struct *tsec = selinux_cred(cred);
470 rc = avc_has_perm(&selinux_state,
471 tsec->sid, sbsec->sid, SECCLASS_FILESYSTEM,
472 FILESYSTEM__RELABELFROM, NULL);
476 rc = avc_has_perm(&selinux_state,
477 sid, sbsec->sid, SECCLASS_FILESYSTEM,
478 FILESYSTEM__ASSOCIATE, NULL);
482 static int selinux_is_genfs_special_handling(struct super_block *sb)
484 /* Special handling. Genfs but also in-core setxattr handler */
485 return !strcmp(sb->s_type->name, "sysfs") ||
486 !strcmp(sb->s_type->name, "pstore") ||
487 !strcmp(sb->s_type->name, "debugfs") ||
488 !strcmp(sb->s_type->name, "tracefs") ||
489 !strcmp(sb->s_type->name, "rootfs") ||
490 (selinux_policycap_cgroupseclabel() &&
491 (!strcmp(sb->s_type->name, "cgroup") ||
492 !strcmp(sb->s_type->name, "cgroup2")));
495 static int selinux_is_sblabel_mnt(struct super_block *sb)
497 struct superblock_security_struct *sbsec = sb->s_security;
500 * IMPORTANT: Double-check logic in this function when adding a new
501 * SECURITY_FS_USE_* definition!
503 BUILD_BUG_ON(SECURITY_FS_USE_MAX != 7);
505 switch (sbsec->behavior) {
506 case SECURITY_FS_USE_XATTR:
507 case SECURITY_FS_USE_TRANS:
508 case SECURITY_FS_USE_TASK:
509 case SECURITY_FS_USE_NATIVE:
512 case SECURITY_FS_USE_GENFS:
513 return selinux_is_genfs_special_handling(sb);
515 /* Never allow relabeling on context mounts */
516 case SECURITY_FS_USE_MNTPOINT:
517 case SECURITY_FS_USE_NONE:
523 static int sb_check_xattr_support(struct super_block *sb)
525 struct superblock_security_struct *sbsec = sb->s_security;
526 struct dentry *root = sb->s_root;
527 struct inode *root_inode = d_backing_inode(root);
532 * Make sure that the xattr handler exists and that no
533 * error other than -ENODATA is returned by getxattr on
534 * the root directory. -ENODATA is ok, as this may be
535 * the first boot of the SELinux kernel before we have
536 * assigned xattr values to the filesystem.
538 if (!(root_inode->i_opflags & IOP_XATTR)) {
539 pr_warn("SELinux: (dev %s, type %s) has no xattr support\n",
540 sb->s_id, sb->s_type->name);
544 rc = __vfs_getxattr(root, root_inode, XATTR_NAME_SELINUX, NULL, 0);
545 if (rc < 0 && rc != -ENODATA) {
546 if (rc == -EOPNOTSUPP) {
547 pr_warn("SELinux: (dev %s, type %s) has no security xattr handler\n",
548 sb->s_id, sb->s_type->name);
551 pr_warn("SELinux: (dev %s, type %s) getxattr errno %d\n",
552 sb->s_id, sb->s_type->name, -rc);
559 /* No xattr support - try to fallback to genfs if possible. */
560 rc = security_genfs_sid(&selinux_state, sb->s_type->name, "/",
565 pr_warn("SELinux: (dev %s, type %s) falling back to genfs\n",
566 sb->s_id, sb->s_type->name);
567 sbsec->behavior = SECURITY_FS_USE_GENFS;
572 static int sb_finish_set_opts(struct super_block *sb)
574 struct superblock_security_struct *sbsec = sb->s_security;
575 struct dentry *root = sb->s_root;
576 struct inode *root_inode = d_backing_inode(root);
579 if (sbsec->behavior == SECURITY_FS_USE_XATTR) {
580 rc = sb_check_xattr_support(sb);
585 sbsec->flags |= SE_SBINITIALIZED;
588 * Explicitly set or clear SBLABEL_MNT. It's not sufficient to simply
589 * leave the flag untouched because sb_clone_mnt_opts might be handing
590 * us a superblock that needs the flag to be cleared.
592 if (selinux_is_sblabel_mnt(sb))
593 sbsec->flags |= SBLABEL_MNT;
595 sbsec->flags &= ~SBLABEL_MNT;
597 /* Initialize the root inode. */
598 rc = inode_doinit_with_dentry(root_inode, root);
600 /* Initialize any other inodes associated with the superblock, e.g.
601 inodes created prior to initial policy load or inodes created
602 during get_sb by a pseudo filesystem that directly
604 spin_lock(&sbsec->isec_lock);
605 while (!list_empty(&sbsec->isec_head)) {
606 struct inode_security_struct *isec =
607 list_first_entry(&sbsec->isec_head,
608 struct inode_security_struct, list);
609 struct inode *inode = isec->inode;
610 list_del_init(&isec->list);
611 spin_unlock(&sbsec->isec_lock);
612 inode = igrab(inode);
614 if (!IS_PRIVATE(inode))
615 inode_doinit_with_dentry(inode, NULL);
618 spin_lock(&sbsec->isec_lock);
620 spin_unlock(&sbsec->isec_lock);
624 static int bad_option(struct superblock_security_struct *sbsec, char flag,
625 u32 old_sid, u32 new_sid)
627 char mnt_flags = sbsec->flags & SE_MNTMASK;
629 /* check if the old mount command had the same options */
630 if (sbsec->flags & SE_SBINITIALIZED)
631 if (!(sbsec->flags & flag) ||
632 (old_sid != new_sid))
635 /* check if we were passed the same options twice,
636 * aka someone passed context=a,context=b
638 if (!(sbsec->flags & SE_SBINITIALIZED))
639 if (mnt_flags & flag)
644 static int parse_sid(struct super_block *sb, const char *s, u32 *sid)
646 int rc = security_context_str_to_sid(&selinux_state, s,
649 pr_warn("SELinux: security_context_str_to_sid"
650 "(%s) failed for (dev %s, type %s) errno=%d\n",
651 s, sb->s_id, sb->s_type->name, rc);
656 * Allow filesystems with binary mount data to explicitly set mount point
657 * labeling information.
659 static int selinux_set_mnt_opts(struct super_block *sb,
661 unsigned long kern_flags,
662 unsigned long *set_kern_flags)
664 const struct cred *cred = current_cred();
665 struct superblock_security_struct *sbsec = sb->s_security;
666 struct dentry *root = sb->s_root;
667 struct selinux_mnt_opts *opts = mnt_opts;
668 struct inode_security_struct *root_isec;
669 u32 fscontext_sid = 0, context_sid = 0, rootcontext_sid = 0;
670 u32 defcontext_sid = 0;
673 mutex_lock(&sbsec->lock);
675 if (!selinux_initialized(&selinux_state)) {
677 /* Defer initialization until selinux_complete_init,
678 after the initial policy is loaded and the security
679 server is ready to handle calls. */
683 pr_warn("SELinux: Unable to set superblock options "
684 "before the security server is initialized\n");
687 if (kern_flags && !set_kern_flags) {
688 /* Specifying internal flags without providing a place to
689 * place the results is not allowed */
695 * Binary mount data FS will come through this function twice. Once
696 * from an explicit call and once from the generic calls from the vfs.
697 * Since the generic VFS calls will not contain any security mount data
698 * we need to skip the double mount verification.
700 * This does open a hole in which we will not notice if the first
701 * mount using this sb set explict options and a second mount using
702 * this sb does not set any security options. (The first options
703 * will be used for both mounts)
705 if ((sbsec->flags & SE_SBINITIALIZED) && (sb->s_type->fs_flags & FS_BINARY_MOUNTDATA)
709 root_isec = backing_inode_security_novalidate(root);
712 * parse the mount options, check if they are valid sids.
713 * also check if someone is trying to mount the same sb more
714 * than once with different security options.
717 if (opts->fscontext) {
718 rc = parse_sid(sb, opts->fscontext, &fscontext_sid);
721 if (bad_option(sbsec, FSCONTEXT_MNT, sbsec->sid,
723 goto out_double_mount;
724 sbsec->flags |= FSCONTEXT_MNT;
727 rc = parse_sid(sb, opts->context, &context_sid);
730 if (bad_option(sbsec, CONTEXT_MNT, sbsec->mntpoint_sid,
732 goto out_double_mount;
733 sbsec->flags |= CONTEXT_MNT;
735 if (opts->rootcontext) {
736 rc = parse_sid(sb, opts->rootcontext, &rootcontext_sid);
739 if (bad_option(sbsec, ROOTCONTEXT_MNT, root_isec->sid,
741 goto out_double_mount;
742 sbsec->flags |= ROOTCONTEXT_MNT;
744 if (opts->defcontext) {
745 rc = parse_sid(sb, opts->defcontext, &defcontext_sid);
748 if (bad_option(sbsec, DEFCONTEXT_MNT, sbsec->def_sid,
750 goto out_double_mount;
751 sbsec->flags |= DEFCONTEXT_MNT;
755 if (sbsec->flags & SE_SBINITIALIZED) {
756 /* previously mounted with options, but not on this attempt? */
757 if ((sbsec->flags & SE_MNTMASK) && !opts)
758 goto out_double_mount;
763 if (strcmp(sb->s_type->name, "proc") == 0)
764 sbsec->flags |= SE_SBPROC | SE_SBGENFS;
766 if (!strcmp(sb->s_type->name, "debugfs") ||
767 !strcmp(sb->s_type->name, "tracefs") ||
768 !strcmp(sb->s_type->name, "binder") ||
769 !strcmp(sb->s_type->name, "bpf") ||
770 !strcmp(sb->s_type->name, "pstore"))
771 sbsec->flags |= SE_SBGENFS;
773 if (!strcmp(sb->s_type->name, "sysfs") ||
774 !strcmp(sb->s_type->name, "cgroup") ||
775 !strcmp(sb->s_type->name, "cgroup2"))
776 sbsec->flags |= SE_SBGENFS | SE_SBGENFS_XATTR;
778 if (!sbsec->behavior) {
780 * Determine the labeling behavior to use for this
783 rc = security_fs_use(&selinux_state, sb);
785 pr_warn("%s: security_fs_use(%s) returned %d\n",
786 __func__, sb->s_type->name, rc);
792 * If this is a user namespace mount and the filesystem type is not
793 * explicitly whitelisted, then no contexts are allowed on the command
794 * line and security labels must be ignored.
796 if (sb->s_user_ns != &init_user_ns &&
797 strcmp(sb->s_type->name, "tmpfs") &&
798 strcmp(sb->s_type->name, "ramfs") &&
799 strcmp(sb->s_type->name, "devpts") &&
800 strcmp(sb->s_type->name, "overlay")) {
801 if (context_sid || fscontext_sid || rootcontext_sid ||
806 if (sbsec->behavior == SECURITY_FS_USE_XATTR) {
807 sbsec->behavior = SECURITY_FS_USE_MNTPOINT;
808 rc = security_transition_sid(&selinux_state,
812 &sbsec->mntpoint_sid);
819 /* sets the context of the superblock for the fs being mounted. */
821 rc = may_context_mount_sb_relabel(fscontext_sid, sbsec, cred);
825 sbsec->sid = fscontext_sid;
829 * Switch to using mount point labeling behavior.
830 * sets the label used on all file below the mountpoint, and will set
831 * the superblock context if not already set.
833 if (kern_flags & SECURITY_LSM_NATIVE_LABELS && !context_sid) {
834 sbsec->behavior = SECURITY_FS_USE_NATIVE;
835 *set_kern_flags |= SECURITY_LSM_NATIVE_LABELS;
839 if (!fscontext_sid) {
840 rc = may_context_mount_sb_relabel(context_sid, sbsec,
844 sbsec->sid = context_sid;
846 rc = may_context_mount_inode_relabel(context_sid, sbsec,
851 if (!rootcontext_sid)
852 rootcontext_sid = context_sid;
854 sbsec->mntpoint_sid = context_sid;
855 sbsec->behavior = SECURITY_FS_USE_MNTPOINT;
858 if (rootcontext_sid) {
859 rc = may_context_mount_inode_relabel(rootcontext_sid, sbsec,
864 root_isec->sid = rootcontext_sid;
865 root_isec->initialized = LABEL_INITIALIZED;
868 if (defcontext_sid) {
869 if (sbsec->behavior != SECURITY_FS_USE_XATTR &&
870 sbsec->behavior != SECURITY_FS_USE_NATIVE) {
872 pr_warn("SELinux: defcontext option is "
873 "invalid for this filesystem type\n");
877 if (defcontext_sid != sbsec->def_sid) {
878 rc = may_context_mount_inode_relabel(defcontext_sid,
884 sbsec->def_sid = defcontext_sid;
888 rc = sb_finish_set_opts(sb);
890 mutex_unlock(&sbsec->lock);
894 pr_warn("SELinux: mount invalid. Same superblock, different "
895 "security settings for (dev %s, type %s)\n", sb->s_id,
900 static int selinux_cmp_sb_context(const struct super_block *oldsb,
901 const struct super_block *newsb)
903 struct superblock_security_struct *old = oldsb->s_security;
904 struct superblock_security_struct *new = newsb->s_security;
905 char oldflags = old->flags & SE_MNTMASK;
906 char newflags = new->flags & SE_MNTMASK;
908 if (oldflags != newflags)
910 if ((oldflags & FSCONTEXT_MNT) && old->sid != new->sid)
912 if ((oldflags & CONTEXT_MNT) && old->mntpoint_sid != new->mntpoint_sid)
914 if ((oldflags & DEFCONTEXT_MNT) && old->def_sid != new->def_sid)
916 if (oldflags & ROOTCONTEXT_MNT) {
917 struct inode_security_struct *oldroot = backing_inode_security(oldsb->s_root);
918 struct inode_security_struct *newroot = backing_inode_security(newsb->s_root);
919 if (oldroot->sid != newroot->sid)
924 pr_warn("SELinux: mount invalid. Same superblock, "
925 "different security settings for (dev %s, "
926 "type %s)\n", newsb->s_id, newsb->s_type->name);
930 static int selinux_sb_clone_mnt_opts(const struct super_block *oldsb,
931 struct super_block *newsb,
932 unsigned long kern_flags,
933 unsigned long *set_kern_flags)
936 const struct superblock_security_struct *oldsbsec = oldsb->s_security;
937 struct superblock_security_struct *newsbsec = newsb->s_security;
939 int set_fscontext = (oldsbsec->flags & FSCONTEXT_MNT);
940 int set_context = (oldsbsec->flags & CONTEXT_MNT);
941 int set_rootcontext = (oldsbsec->flags & ROOTCONTEXT_MNT);
944 * if the parent was able to be mounted it clearly had no special lsm
945 * mount options. thus we can safely deal with this superblock later
947 if (!selinux_initialized(&selinux_state))
951 * Specifying internal flags without providing a place to
952 * place the results is not allowed.
954 if (kern_flags && !set_kern_flags)
957 /* how can we clone if the old one wasn't set up?? */
958 BUG_ON(!(oldsbsec->flags & SE_SBINITIALIZED));
960 /* if fs is reusing a sb, make sure that the contexts match */
961 if (newsbsec->flags & SE_SBINITIALIZED) {
962 if ((kern_flags & SECURITY_LSM_NATIVE_LABELS) && !set_context)
963 *set_kern_flags |= SECURITY_LSM_NATIVE_LABELS;
964 return selinux_cmp_sb_context(oldsb, newsb);
967 mutex_lock(&newsbsec->lock);
969 newsbsec->flags = oldsbsec->flags;
971 newsbsec->sid = oldsbsec->sid;
972 newsbsec->def_sid = oldsbsec->def_sid;
973 newsbsec->behavior = oldsbsec->behavior;
975 if (newsbsec->behavior == SECURITY_FS_USE_NATIVE &&
976 !(kern_flags & SECURITY_LSM_NATIVE_LABELS) && !set_context) {
977 rc = security_fs_use(&selinux_state, newsb);
982 if (kern_flags & SECURITY_LSM_NATIVE_LABELS && !set_context) {
983 newsbsec->behavior = SECURITY_FS_USE_NATIVE;
984 *set_kern_flags |= SECURITY_LSM_NATIVE_LABELS;
988 u32 sid = oldsbsec->mntpoint_sid;
992 if (!set_rootcontext) {
993 struct inode_security_struct *newisec = backing_inode_security(newsb->s_root);
996 newsbsec->mntpoint_sid = sid;
998 if (set_rootcontext) {
999 const struct inode_security_struct *oldisec = backing_inode_security(oldsb->s_root);
1000 struct inode_security_struct *newisec = backing_inode_security(newsb->s_root);
1002 newisec->sid = oldisec->sid;
1005 sb_finish_set_opts(newsb);
1007 mutex_unlock(&newsbsec->lock);
1011 static int selinux_add_opt(int token, const char *s, void **mnt_opts)
1013 struct selinux_mnt_opts *opts = *mnt_opts;
1015 if (token == Opt_seclabel) /* eaten and completely ignored */
1019 opts = kzalloc(sizeof(struct selinux_mnt_opts), GFP_KERNEL);
1028 if (opts->context || opts->defcontext)
1033 if (opts->fscontext)
1035 opts->fscontext = s;
1037 case Opt_rootcontext:
1038 if (opts->rootcontext)
1040 opts->rootcontext = s;
1042 case Opt_defcontext:
1043 if (opts->context || opts->defcontext)
1045 opts->defcontext = s;
1050 pr_warn(SEL_MOUNT_FAIL_MSG);
1054 static int selinux_add_mnt_opt(const char *option, const char *val, int len,
1057 int token = Opt_error;
1060 for (i = 0; i < ARRAY_SIZE(tokens); i++) {
1061 if (strcmp(option, tokens[i].name) == 0) {
1062 token = tokens[i].opt;
1067 if (token == Opt_error)
1070 if (token != Opt_seclabel) {
1071 val = kmemdup_nul(val, len, GFP_KERNEL);
1077 rc = selinux_add_opt(token, val, mnt_opts);
1086 selinux_free_mnt_opts(*mnt_opts);
1092 static int show_sid(struct seq_file *m, u32 sid)
1094 char *context = NULL;
1098 rc = security_sid_to_context(&selinux_state, sid,
1101 bool has_comma = context && strchr(context, ',');
1106 seq_escape(m, context, "\"\n\\");
1114 static int selinux_sb_show_options(struct seq_file *m, struct super_block *sb)
1116 struct superblock_security_struct *sbsec = sb->s_security;
1119 if (!(sbsec->flags & SE_SBINITIALIZED))
1122 if (!selinux_initialized(&selinux_state))
1125 if (sbsec->flags & FSCONTEXT_MNT) {
1127 seq_puts(m, FSCONTEXT_STR);
1128 rc = show_sid(m, sbsec->sid);
1132 if (sbsec->flags & CONTEXT_MNT) {
1134 seq_puts(m, CONTEXT_STR);
1135 rc = show_sid(m, sbsec->mntpoint_sid);
1139 if (sbsec->flags & DEFCONTEXT_MNT) {
1141 seq_puts(m, DEFCONTEXT_STR);
1142 rc = show_sid(m, sbsec->def_sid);
1146 if (sbsec->flags & ROOTCONTEXT_MNT) {
1147 struct dentry *root = sb->s_root;
1148 struct inode_security_struct *isec = backing_inode_security(root);
1150 seq_puts(m, ROOTCONTEXT_STR);
1151 rc = show_sid(m, isec->sid);
1155 if (sbsec->flags & SBLABEL_MNT) {
1157 seq_puts(m, SECLABEL_STR);
1162 static inline u16 inode_mode_to_security_class(umode_t mode)
1164 switch (mode & S_IFMT) {
1166 return SECCLASS_SOCK_FILE;
1168 return SECCLASS_LNK_FILE;
1170 return SECCLASS_FILE;
1172 return SECCLASS_BLK_FILE;
1174 return SECCLASS_DIR;
1176 return SECCLASS_CHR_FILE;
1178 return SECCLASS_FIFO_FILE;
1182 return SECCLASS_FILE;
1185 static inline int default_protocol_stream(int protocol)
1187 return (protocol == IPPROTO_IP || protocol == IPPROTO_TCP ||
1188 protocol == IPPROTO_MPTCP);
1191 static inline int default_protocol_dgram(int protocol)
1193 return (protocol == IPPROTO_IP || protocol == IPPROTO_UDP);
1196 static inline u16 socket_type_to_security_class(int family, int type, int protocol)
1198 int extsockclass = selinux_policycap_extsockclass();
1204 case SOCK_SEQPACKET:
1205 return SECCLASS_UNIX_STREAM_SOCKET;
1208 return SECCLASS_UNIX_DGRAM_SOCKET;
1215 case SOCK_SEQPACKET:
1216 if (default_protocol_stream(protocol))
1217 return SECCLASS_TCP_SOCKET;
1218 else if (extsockclass && protocol == IPPROTO_SCTP)
1219 return SECCLASS_SCTP_SOCKET;
1221 return SECCLASS_RAWIP_SOCKET;
1223 if (default_protocol_dgram(protocol))
1224 return SECCLASS_UDP_SOCKET;
1225 else if (extsockclass && (protocol == IPPROTO_ICMP ||
1226 protocol == IPPROTO_ICMPV6))
1227 return SECCLASS_ICMP_SOCKET;
1229 return SECCLASS_RAWIP_SOCKET;
1231 return SECCLASS_DCCP_SOCKET;
1233 return SECCLASS_RAWIP_SOCKET;
1239 return SECCLASS_NETLINK_ROUTE_SOCKET;
1240 case NETLINK_SOCK_DIAG:
1241 return SECCLASS_NETLINK_TCPDIAG_SOCKET;
1243 return SECCLASS_NETLINK_NFLOG_SOCKET;
1245 return SECCLASS_NETLINK_XFRM_SOCKET;
1246 case NETLINK_SELINUX:
1247 return SECCLASS_NETLINK_SELINUX_SOCKET;
1249 return SECCLASS_NETLINK_ISCSI_SOCKET;
1251 return SECCLASS_NETLINK_AUDIT_SOCKET;
1252 case NETLINK_FIB_LOOKUP:
1253 return SECCLASS_NETLINK_FIB_LOOKUP_SOCKET;
1254 case NETLINK_CONNECTOR:
1255 return SECCLASS_NETLINK_CONNECTOR_SOCKET;
1256 case NETLINK_NETFILTER:
1257 return SECCLASS_NETLINK_NETFILTER_SOCKET;
1258 case NETLINK_DNRTMSG:
1259 return SECCLASS_NETLINK_DNRT_SOCKET;
1260 case NETLINK_KOBJECT_UEVENT:
1261 return SECCLASS_NETLINK_KOBJECT_UEVENT_SOCKET;
1262 case NETLINK_GENERIC:
1263 return SECCLASS_NETLINK_GENERIC_SOCKET;
1264 case NETLINK_SCSITRANSPORT:
1265 return SECCLASS_NETLINK_SCSITRANSPORT_SOCKET;
1267 return SECCLASS_NETLINK_RDMA_SOCKET;
1268 case NETLINK_CRYPTO:
1269 return SECCLASS_NETLINK_CRYPTO_SOCKET;
1271 return SECCLASS_NETLINK_SOCKET;
1274 return SECCLASS_PACKET_SOCKET;
1276 return SECCLASS_KEY_SOCKET;
1278 return SECCLASS_APPLETALK_SOCKET;
1284 return SECCLASS_AX25_SOCKET;
1286 return SECCLASS_IPX_SOCKET;
1288 return SECCLASS_NETROM_SOCKET;
1290 return SECCLASS_ATMPVC_SOCKET;
1292 return SECCLASS_X25_SOCKET;
1294 return SECCLASS_ROSE_SOCKET;
1296 return SECCLASS_DECNET_SOCKET;
1298 return SECCLASS_ATMSVC_SOCKET;
1300 return SECCLASS_RDS_SOCKET;
1302 return SECCLASS_IRDA_SOCKET;
1304 return SECCLASS_PPPOX_SOCKET;
1306 return SECCLASS_LLC_SOCKET;
1308 return SECCLASS_CAN_SOCKET;
1310 return SECCLASS_TIPC_SOCKET;
1312 return SECCLASS_BLUETOOTH_SOCKET;
1314 return SECCLASS_IUCV_SOCKET;
1316 return SECCLASS_RXRPC_SOCKET;
1318 return SECCLASS_ISDN_SOCKET;
1320 return SECCLASS_PHONET_SOCKET;
1322 return SECCLASS_IEEE802154_SOCKET;
1324 return SECCLASS_CAIF_SOCKET;
1326 return SECCLASS_ALG_SOCKET;
1328 return SECCLASS_NFC_SOCKET;
1330 return SECCLASS_VSOCK_SOCKET;
1332 return SECCLASS_KCM_SOCKET;
1334 return SECCLASS_QIPCRTR_SOCKET;
1336 return SECCLASS_SMC_SOCKET;
1338 return SECCLASS_XDP_SOCKET;
1340 #error New address family defined, please update this function.
1345 return SECCLASS_SOCKET;
1348 static int selinux_genfs_get_sid(struct dentry *dentry,
1354 struct super_block *sb = dentry->d_sb;
1355 char *buffer, *path;
1357 buffer = (char *)__get_free_page(GFP_KERNEL);
1361 path = dentry_path_raw(dentry, buffer, PAGE_SIZE);
1365 if (flags & SE_SBPROC) {
1366 /* each process gets a /proc/PID/ entry. Strip off the
1367 * PID part to get a valid selinux labeling.
1368 * e.g. /proc/1/net/rpc/nfs -> /net/rpc/nfs */
1369 while (path[1] >= '0' && path[1] <= '9') {
1374 rc = security_genfs_sid(&selinux_state, sb->s_type->name,
1376 if (rc == -ENOENT) {
1377 /* No match in policy, mark as unlabeled. */
1378 *sid = SECINITSID_UNLABELED;
1382 free_page((unsigned long)buffer);
1386 static int inode_doinit_use_xattr(struct inode *inode, struct dentry *dentry,
1387 u32 def_sid, u32 *sid)
1389 #define INITCONTEXTLEN 255
1394 len = INITCONTEXTLEN;
1395 context = kmalloc(len + 1, GFP_NOFS);
1399 context[len] = '\0';
1400 rc = __vfs_getxattr(dentry, inode, XATTR_NAME_SELINUX, context, len);
1401 if (rc == -ERANGE) {
1404 /* Need a larger buffer. Query for the right size. */
1405 rc = __vfs_getxattr(dentry, inode, XATTR_NAME_SELINUX, NULL, 0);
1410 context = kmalloc(len + 1, GFP_NOFS);
1414 context[len] = '\0';
1415 rc = __vfs_getxattr(dentry, inode, XATTR_NAME_SELINUX,
1420 if (rc != -ENODATA) {
1421 pr_warn("SELinux: %s: getxattr returned %d for dev=%s ino=%ld\n",
1422 __func__, -rc, inode->i_sb->s_id, inode->i_ino);
1429 rc = security_context_to_sid_default(&selinux_state, context, rc, sid,
1432 char *dev = inode->i_sb->s_id;
1433 unsigned long ino = inode->i_ino;
1435 if (rc == -EINVAL) {
1436 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",
1439 pr_warn("SELinux: %s: context_to_sid(%s) returned %d for dev=%s ino=%ld\n",
1440 __func__, context, -rc, dev, ino);
1447 /* The inode's security attributes must be initialized before first use. */
1448 static int inode_doinit_with_dentry(struct inode *inode, struct dentry *opt_dentry)
1450 struct superblock_security_struct *sbsec = NULL;
1451 struct inode_security_struct *isec = selinux_inode(inode);
1452 u32 task_sid, sid = 0;
1454 struct dentry *dentry;
1457 if (isec->initialized == LABEL_INITIALIZED)
1460 spin_lock(&isec->lock);
1461 if (isec->initialized == LABEL_INITIALIZED)
1464 if (isec->sclass == SECCLASS_FILE)
1465 isec->sclass = inode_mode_to_security_class(inode->i_mode);
1467 sbsec = inode->i_sb->s_security;
1468 if (!(sbsec->flags & SE_SBINITIALIZED)) {
1469 /* Defer initialization until selinux_complete_init,
1470 after the initial policy is loaded and the security
1471 server is ready to handle calls. */
1472 spin_lock(&sbsec->isec_lock);
1473 if (list_empty(&isec->list))
1474 list_add(&isec->list, &sbsec->isec_head);
1475 spin_unlock(&sbsec->isec_lock);
1479 sclass = isec->sclass;
1480 task_sid = isec->task_sid;
1482 isec->initialized = LABEL_PENDING;
1483 spin_unlock(&isec->lock);
1485 switch (sbsec->behavior) {
1486 case SECURITY_FS_USE_NATIVE:
1488 case SECURITY_FS_USE_XATTR:
1489 if (!(inode->i_opflags & IOP_XATTR)) {
1490 sid = sbsec->def_sid;
1493 /* Need a dentry, since the xattr API requires one.
1494 Life would be simpler if we could just pass the inode. */
1496 /* Called from d_instantiate or d_splice_alias. */
1497 dentry = dget(opt_dentry);
1500 * Called from selinux_complete_init, try to find a dentry.
1501 * Some filesystems really want a connected one, so try
1502 * that first. We could split SECURITY_FS_USE_XATTR in
1503 * two, depending upon that...
1505 dentry = d_find_alias(inode);
1507 dentry = d_find_any_alias(inode);
1511 * this is can be hit on boot when a file is accessed
1512 * before the policy is loaded. When we load policy we
1513 * may find inodes that have no dentry on the
1514 * sbsec->isec_head list. No reason to complain as these
1515 * will get fixed up the next time we go through
1516 * inode_doinit with a dentry, before these inodes could
1517 * be used again by userspace.
1522 rc = inode_doinit_use_xattr(inode, dentry, sbsec->def_sid,
1528 case SECURITY_FS_USE_TASK:
1531 case SECURITY_FS_USE_TRANS:
1532 /* Default to the fs SID. */
1535 /* Try to obtain a transition SID. */
1536 rc = security_transition_sid(&selinux_state, task_sid, sid,
1537 sclass, NULL, &sid);
1541 case SECURITY_FS_USE_MNTPOINT:
1542 sid = sbsec->mntpoint_sid;
1545 /* Default to the fs superblock SID. */
1548 if ((sbsec->flags & SE_SBGENFS) &&
1549 (!S_ISLNK(inode->i_mode) ||
1550 selinux_policycap_genfs_seclabel_symlinks())) {
1551 /* We must have a dentry to determine the label on
1554 /* Called from d_instantiate or
1555 * d_splice_alias. */
1556 dentry = dget(opt_dentry);
1558 /* Called from selinux_complete_init, try to
1559 * find a dentry. Some filesystems really want
1560 * a connected one, so try that first.
1562 dentry = d_find_alias(inode);
1564 dentry = d_find_any_alias(inode);
1567 * This can be hit on boot when a file is accessed
1568 * before the policy is loaded. When we load policy we
1569 * may find inodes that have no dentry on the
1570 * sbsec->isec_head list. No reason to complain as
1571 * these will get fixed up the next time we go through
1572 * inode_doinit() with a dentry, before these inodes
1573 * could be used again by userspace.
1577 rc = selinux_genfs_get_sid(dentry, sclass,
1578 sbsec->flags, &sid);
1584 if ((sbsec->flags & SE_SBGENFS_XATTR) &&
1585 (inode->i_opflags & IOP_XATTR)) {
1586 rc = inode_doinit_use_xattr(inode, dentry,
1599 spin_lock(&isec->lock);
1600 if (isec->initialized == LABEL_PENDING) {
1602 isec->initialized = LABEL_INVALID;
1605 isec->initialized = LABEL_INITIALIZED;
1610 spin_unlock(&isec->lock);
1614 spin_lock(&isec->lock);
1615 if (isec->initialized == LABEL_PENDING) {
1616 isec->initialized = LABEL_INVALID;
1619 spin_unlock(&isec->lock);
1623 /* Convert a Linux signal to an access vector. */
1624 static inline u32 signal_to_av(int sig)
1630 /* Commonly granted from child to parent. */
1631 perm = PROCESS__SIGCHLD;
1634 /* Cannot be caught or ignored */
1635 perm = PROCESS__SIGKILL;
1638 /* Cannot be caught or ignored */
1639 perm = PROCESS__SIGSTOP;
1642 /* All other signals. */
1643 perm = PROCESS__SIGNAL;
1650 #if CAP_LAST_CAP > 63
1651 #error Fix SELinux to handle capabilities > 63.
1654 /* Check whether a task is allowed to use a capability. */
1655 static int cred_has_capability(const struct cred *cred,
1656 int cap, unsigned int opts, bool initns)
1658 struct common_audit_data ad;
1659 struct av_decision avd;
1661 u32 sid = cred_sid(cred);
1662 u32 av = CAP_TO_MASK(cap);
1665 ad.type = LSM_AUDIT_DATA_CAP;
1668 switch (CAP_TO_INDEX(cap)) {
1670 sclass = initns ? SECCLASS_CAPABILITY : SECCLASS_CAP_USERNS;
1673 sclass = initns ? SECCLASS_CAPABILITY2 : SECCLASS_CAP2_USERNS;
1676 pr_err("SELinux: out of range capability %d\n", cap);
1681 rc = avc_has_perm_noaudit(&selinux_state,
1682 sid, sid, sclass, av, 0, &avd);
1683 if (!(opts & CAP_OPT_NOAUDIT)) {
1684 int rc2 = avc_audit(&selinux_state,
1685 sid, sid, sclass, av, &avd, rc, &ad, 0);
1692 /* Check whether a task has a particular permission to an inode.
1693 The 'adp' parameter is optional and allows other audit
1694 data to be passed (e.g. the dentry). */
1695 static int inode_has_perm(const struct cred *cred,
1696 struct inode *inode,
1698 struct common_audit_data *adp)
1700 struct inode_security_struct *isec;
1703 validate_creds(cred);
1705 if (unlikely(IS_PRIVATE(inode)))
1708 sid = cred_sid(cred);
1709 isec = selinux_inode(inode);
1711 return avc_has_perm(&selinux_state,
1712 sid, isec->sid, isec->sclass, perms, adp);
1715 /* Same as inode_has_perm, but pass explicit audit data containing
1716 the dentry to help the auditing code to more easily generate the
1717 pathname if needed. */
1718 static inline int dentry_has_perm(const struct cred *cred,
1719 struct dentry *dentry,
1722 struct inode *inode = d_backing_inode(dentry);
1723 struct common_audit_data ad;
1725 ad.type = LSM_AUDIT_DATA_DENTRY;
1726 ad.u.dentry = dentry;
1727 __inode_security_revalidate(inode, dentry, true);
1728 return inode_has_perm(cred, inode, av, &ad);
1731 /* Same as inode_has_perm, but pass explicit audit data containing
1732 the path to help the auditing code to more easily generate the
1733 pathname if needed. */
1734 static inline int path_has_perm(const struct cred *cred,
1735 const struct path *path,
1738 struct inode *inode = d_backing_inode(path->dentry);
1739 struct common_audit_data ad;
1741 ad.type = LSM_AUDIT_DATA_PATH;
1743 __inode_security_revalidate(inode, path->dentry, true);
1744 return inode_has_perm(cred, inode, av, &ad);
1747 /* Same as path_has_perm, but uses the inode from the file struct. */
1748 static inline int file_path_has_perm(const struct cred *cred,
1752 struct common_audit_data ad;
1754 ad.type = LSM_AUDIT_DATA_FILE;
1756 return inode_has_perm(cred, file_inode(file), av, &ad);
1759 #ifdef CONFIG_BPF_SYSCALL
1760 static int bpf_fd_pass(struct file *file, u32 sid);
1763 /* Check whether a task can use an open file descriptor to
1764 access an inode in a given way. Check access to the
1765 descriptor itself, and then use dentry_has_perm to
1766 check a particular permission to the file.
1767 Access to the descriptor is implicitly granted if it
1768 has the same SID as the process. If av is zero, then
1769 access to the file is not checked, e.g. for cases
1770 where only the descriptor is affected like seek. */
1771 static int file_has_perm(const struct cred *cred,
1775 struct file_security_struct *fsec = selinux_file(file);
1776 struct inode *inode = file_inode(file);
1777 struct common_audit_data ad;
1778 u32 sid = cred_sid(cred);
1781 ad.type = LSM_AUDIT_DATA_FILE;
1784 if (sid != fsec->sid) {
1785 rc = avc_has_perm(&selinux_state,
1794 #ifdef CONFIG_BPF_SYSCALL
1795 rc = bpf_fd_pass(file, cred_sid(cred));
1800 /* av is zero if only checking access to the descriptor. */
1803 rc = inode_has_perm(cred, inode, av, &ad);
1810 * Determine the label for an inode that might be unioned.
1813 selinux_determine_inode_label(const struct task_security_struct *tsec,
1815 const struct qstr *name, u16 tclass,
1818 const struct superblock_security_struct *sbsec = dir->i_sb->s_security;
1820 if ((sbsec->flags & SE_SBINITIALIZED) &&
1821 (sbsec->behavior == SECURITY_FS_USE_MNTPOINT)) {
1822 *_new_isid = sbsec->mntpoint_sid;
1823 } else if ((sbsec->flags & SBLABEL_MNT) &&
1825 *_new_isid = tsec->create_sid;
1827 const struct inode_security_struct *dsec = inode_security(dir);
1828 return security_transition_sid(&selinux_state, tsec->sid,
1836 /* Check whether a task can create a file. */
1837 static int may_create(struct inode *dir,
1838 struct dentry *dentry,
1841 const struct task_security_struct *tsec = selinux_cred(current_cred());
1842 struct inode_security_struct *dsec;
1843 struct superblock_security_struct *sbsec;
1845 struct common_audit_data ad;
1848 dsec = inode_security(dir);
1849 sbsec = dir->i_sb->s_security;
1853 ad.type = LSM_AUDIT_DATA_DENTRY;
1854 ad.u.dentry = dentry;
1856 rc = avc_has_perm(&selinux_state,
1857 sid, dsec->sid, SECCLASS_DIR,
1858 DIR__ADD_NAME | DIR__SEARCH,
1863 rc = selinux_determine_inode_label(tsec, dir, &dentry->d_name, tclass,
1868 rc = avc_has_perm(&selinux_state,
1869 sid, newsid, tclass, FILE__CREATE, &ad);
1873 return avc_has_perm(&selinux_state,
1875 SECCLASS_FILESYSTEM,
1876 FILESYSTEM__ASSOCIATE, &ad);
1880 #define MAY_UNLINK 1
1883 /* Check whether a task can link, unlink, or rmdir a file/directory. */
1884 static int may_link(struct inode *dir,
1885 struct dentry *dentry,
1889 struct inode_security_struct *dsec, *isec;
1890 struct common_audit_data ad;
1891 u32 sid = current_sid();
1895 dsec = inode_security(dir);
1896 isec = backing_inode_security(dentry);
1898 ad.type = LSM_AUDIT_DATA_DENTRY;
1899 ad.u.dentry = dentry;
1902 av |= (kind ? DIR__REMOVE_NAME : DIR__ADD_NAME);
1903 rc = avc_has_perm(&selinux_state,
1904 sid, dsec->sid, SECCLASS_DIR, av, &ad);
1919 pr_warn("SELinux: %s: unrecognized kind %d\n",
1924 rc = avc_has_perm(&selinux_state,
1925 sid, isec->sid, isec->sclass, av, &ad);
1929 static inline int may_rename(struct inode *old_dir,
1930 struct dentry *old_dentry,
1931 struct inode *new_dir,
1932 struct dentry *new_dentry)
1934 struct inode_security_struct *old_dsec, *new_dsec, *old_isec, *new_isec;
1935 struct common_audit_data ad;
1936 u32 sid = current_sid();
1938 int old_is_dir, new_is_dir;
1941 old_dsec = inode_security(old_dir);
1942 old_isec = backing_inode_security(old_dentry);
1943 old_is_dir = d_is_dir(old_dentry);
1944 new_dsec = inode_security(new_dir);
1946 ad.type = LSM_AUDIT_DATA_DENTRY;
1948 ad.u.dentry = old_dentry;
1949 rc = avc_has_perm(&selinux_state,
1950 sid, old_dsec->sid, SECCLASS_DIR,
1951 DIR__REMOVE_NAME | DIR__SEARCH, &ad);
1954 rc = avc_has_perm(&selinux_state,
1956 old_isec->sclass, FILE__RENAME, &ad);
1959 if (old_is_dir && new_dir != old_dir) {
1960 rc = avc_has_perm(&selinux_state,
1962 old_isec->sclass, DIR__REPARENT, &ad);
1967 ad.u.dentry = new_dentry;
1968 av = DIR__ADD_NAME | DIR__SEARCH;
1969 if (d_is_positive(new_dentry))
1970 av |= DIR__REMOVE_NAME;
1971 rc = avc_has_perm(&selinux_state,
1972 sid, new_dsec->sid, SECCLASS_DIR, av, &ad);
1975 if (d_is_positive(new_dentry)) {
1976 new_isec = backing_inode_security(new_dentry);
1977 new_is_dir = d_is_dir(new_dentry);
1978 rc = avc_has_perm(&selinux_state,
1981 (new_is_dir ? DIR__RMDIR : FILE__UNLINK), &ad);
1989 /* Check whether a task can perform a filesystem operation. */
1990 static int superblock_has_perm(const struct cred *cred,
1991 struct super_block *sb,
1993 struct common_audit_data *ad)
1995 struct superblock_security_struct *sbsec;
1996 u32 sid = cred_sid(cred);
1998 sbsec = sb->s_security;
1999 return avc_has_perm(&selinux_state,
2000 sid, sbsec->sid, SECCLASS_FILESYSTEM, perms, ad);
2003 /* Convert a Linux mode and permission mask to an access vector. */
2004 static inline u32 file_mask_to_av(int mode, int mask)
2008 if (!S_ISDIR(mode)) {
2009 if (mask & MAY_EXEC)
2010 av |= FILE__EXECUTE;
2011 if (mask & MAY_READ)
2014 if (mask & MAY_APPEND)
2016 else if (mask & MAY_WRITE)
2020 if (mask & MAY_EXEC)
2022 if (mask & MAY_WRITE)
2024 if (mask & MAY_READ)
2031 /* Convert a Linux file to an access vector. */
2032 static inline u32 file_to_av(struct file *file)
2036 if (file->f_mode & FMODE_READ)
2038 if (file->f_mode & FMODE_WRITE) {
2039 if (file->f_flags & O_APPEND)
2046 * Special file opened with flags 3 for ioctl-only use.
2055 * Convert a file to an access vector and include the correct
2058 static inline u32 open_file_to_av(struct file *file)
2060 u32 av = file_to_av(file);
2061 struct inode *inode = file_inode(file);
2063 if (selinux_policycap_openperm() &&
2064 inode->i_sb->s_magic != SOCKFS_MAGIC)
2070 /* Hook functions begin here. */
2072 static int selinux_binder_set_context_mgr(struct task_struct *mgr)
2074 return avc_has_perm(&selinux_state,
2075 current_sid(), task_sid_binder(mgr), SECCLASS_BINDER,
2076 BINDER__SET_CONTEXT_MGR, NULL);
2079 static int selinux_binder_transaction(struct task_struct *from,
2080 struct task_struct *to)
2082 u32 mysid = current_sid();
2083 u32 fromsid = task_sid_binder(from);
2086 if (mysid != fromsid) {
2087 rc = avc_has_perm(&selinux_state,
2088 mysid, fromsid, SECCLASS_BINDER,
2089 BINDER__IMPERSONATE, NULL);
2094 return avc_has_perm(&selinux_state, fromsid, task_sid_binder(to),
2095 SECCLASS_BINDER, BINDER__CALL, NULL);
2098 static int selinux_binder_transfer_binder(struct task_struct *from,
2099 struct task_struct *to)
2101 return avc_has_perm(&selinux_state,
2102 task_sid_binder(from), task_sid_binder(to),
2103 SECCLASS_BINDER, BINDER__TRANSFER,
2107 static int selinux_binder_transfer_file(struct task_struct *from,
2108 struct task_struct *to,
2111 u32 sid = task_sid_binder(to);
2112 struct file_security_struct *fsec = selinux_file(file);
2113 struct dentry *dentry = file->f_path.dentry;
2114 struct inode_security_struct *isec;
2115 struct common_audit_data ad;
2118 ad.type = LSM_AUDIT_DATA_PATH;
2119 ad.u.path = file->f_path;
2121 if (sid != fsec->sid) {
2122 rc = avc_has_perm(&selinux_state,
2131 #ifdef CONFIG_BPF_SYSCALL
2132 rc = bpf_fd_pass(file, sid);
2137 if (unlikely(IS_PRIVATE(d_backing_inode(dentry))))
2140 isec = backing_inode_security(dentry);
2141 return avc_has_perm(&selinux_state,
2142 sid, isec->sid, isec->sclass, file_to_av(file),
2146 static int selinux_ptrace_access_check(struct task_struct *child,
2149 u32 sid = current_sid();
2150 u32 csid = task_sid_obj(child);
2152 if (mode & PTRACE_MODE_READ)
2153 return avc_has_perm(&selinux_state,
2154 sid, csid, SECCLASS_FILE, FILE__READ, NULL);
2156 return avc_has_perm(&selinux_state,
2157 sid, csid, SECCLASS_PROCESS, PROCESS__PTRACE, NULL);
2160 static int selinux_ptrace_traceme(struct task_struct *parent)
2162 return avc_has_perm(&selinux_state,
2163 task_sid_subj(parent), task_sid_obj(current),
2164 SECCLASS_PROCESS, PROCESS__PTRACE, NULL);
2167 static int selinux_capget(struct task_struct *target, kernel_cap_t *effective,
2168 kernel_cap_t *inheritable, kernel_cap_t *permitted)
2170 return avc_has_perm(&selinux_state,
2171 current_sid(), task_sid_obj(target), SECCLASS_PROCESS,
2172 PROCESS__GETCAP, NULL);
2175 static int selinux_capset(struct cred *new, const struct cred *old,
2176 const kernel_cap_t *effective,
2177 const kernel_cap_t *inheritable,
2178 const kernel_cap_t *permitted)
2180 return avc_has_perm(&selinux_state,
2181 cred_sid(old), cred_sid(new), SECCLASS_PROCESS,
2182 PROCESS__SETCAP, NULL);
2186 * (This comment used to live with the selinux_task_setuid hook,
2187 * which was removed).
2189 * Since setuid only affects the current process, and since the SELinux
2190 * controls are not based on the Linux identity attributes, SELinux does not
2191 * need to control this operation. However, SELinux does control the use of
2192 * the CAP_SETUID and CAP_SETGID capabilities using the capable hook.
2195 static int selinux_capable(const struct cred *cred, struct user_namespace *ns,
2196 int cap, unsigned int opts)
2198 return cred_has_capability(cred, cap, opts, ns == &init_user_ns);
2201 static int selinux_quotactl(int cmds, int type, int id, struct super_block *sb)
2203 const struct cred *cred = current_cred();
2218 rc = superblock_has_perm(cred, sb, FILESYSTEM__QUOTAMOD, NULL);
2226 case Q_XGETNEXTQUOTA:
2227 rc = superblock_has_perm(cred, sb, FILESYSTEM__QUOTAGET, NULL);
2230 rc = 0; /* let the kernel handle invalid cmds */
2236 static int selinux_quota_on(struct dentry *dentry)
2238 const struct cred *cred = current_cred();
2240 return dentry_has_perm(cred, dentry, FILE__QUOTAON);
2243 static int selinux_syslog(int type)
2246 case SYSLOG_ACTION_READ_ALL: /* Read last kernel messages */
2247 case SYSLOG_ACTION_SIZE_BUFFER: /* Return size of the log buffer */
2248 return avc_has_perm(&selinux_state,
2249 current_sid(), SECINITSID_KERNEL,
2250 SECCLASS_SYSTEM, SYSTEM__SYSLOG_READ, NULL);
2251 case SYSLOG_ACTION_CONSOLE_OFF: /* Disable logging to console */
2252 case SYSLOG_ACTION_CONSOLE_ON: /* Enable logging to console */
2253 /* Set level of messages printed to console */
2254 case SYSLOG_ACTION_CONSOLE_LEVEL:
2255 return avc_has_perm(&selinux_state,
2256 current_sid(), SECINITSID_KERNEL,
2257 SECCLASS_SYSTEM, SYSTEM__SYSLOG_CONSOLE,
2260 /* All other syslog types */
2261 return avc_has_perm(&selinux_state,
2262 current_sid(), SECINITSID_KERNEL,
2263 SECCLASS_SYSTEM, SYSTEM__SYSLOG_MOD, NULL);
2267 * Check that a process has enough memory to allocate a new virtual
2268 * mapping. 0 means there is enough memory for the allocation to
2269 * succeed and -ENOMEM implies there is not.
2271 * Do not audit the selinux permission check, as this is applied to all
2272 * processes that allocate mappings.
2274 static int selinux_vm_enough_memory(struct mm_struct *mm, long pages)
2276 int rc, cap_sys_admin = 0;
2278 rc = cred_has_capability(current_cred(), CAP_SYS_ADMIN,
2279 CAP_OPT_NOAUDIT, true);
2283 return cap_sys_admin;
2286 /* binprm security operations */
2288 static u32 ptrace_parent_sid(void)
2291 struct task_struct *tracer;
2294 tracer = ptrace_parent(current);
2296 sid = task_sid_obj(tracer);
2302 static int check_nnp_nosuid(const struct linux_binprm *bprm,
2303 const struct task_security_struct *old_tsec,
2304 const struct task_security_struct *new_tsec)
2306 int nnp = (bprm->unsafe & LSM_UNSAFE_NO_NEW_PRIVS);
2307 int nosuid = !mnt_may_suid(bprm->file->f_path.mnt);
2311 if (!nnp && !nosuid)
2312 return 0; /* neither NNP nor nosuid */
2314 if (new_tsec->sid == old_tsec->sid)
2315 return 0; /* No change in credentials */
2318 * If the policy enables the nnp_nosuid_transition policy capability,
2319 * then we permit transitions under NNP or nosuid if the
2320 * policy allows the corresponding permission between
2321 * the old and new contexts.
2323 if (selinux_policycap_nnp_nosuid_transition()) {
2326 av |= PROCESS2__NNP_TRANSITION;
2328 av |= PROCESS2__NOSUID_TRANSITION;
2329 rc = avc_has_perm(&selinux_state,
2330 old_tsec->sid, new_tsec->sid,
2331 SECCLASS_PROCESS2, av, NULL);
2337 * We also permit NNP or nosuid transitions to bounded SIDs,
2338 * i.e. SIDs that are guaranteed to only be allowed a subset
2339 * of the permissions of the current SID.
2341 rc = security_bounded_transition(&selinux_state, old_tsec->sid,
2347 * On failure, preserve the errno values for NNP vs nosuid.
2348 * NNP: Operation not permitted for caller.
2349 * nosuid: Permission denied to file.
2356 static int selinux_bprm_creds_for_exec(struct linux_binprm *bprm)
2358 const struct task_security_struct *old_tsec;
2359 struct task_security_struct *new_tsec;
2360 struct inode_security_struct *isec;
2361 struct common_audit_data ad;
2362 struct inode *inode = file_inode(bprm->file);
2365 /* SELinux context only depends on initial program or script and not
2366 * the script interpreter */
2368 old_tsec = selinux_cred(current_cred());
2369 new_tsec = selinux_cred(bprm->cred);
2370 isec = inode_security(inode);
2372 /* Default to the current task SID. */
2373 new_tsec->sid = old_tsec->sid;
2374 new_tsec->osid = old_tsec->sid;
2376 /* Reset fs, key, and sock SIDs on execve. */
2377 new_tsec->create_sid = 0;
2378 new_tsec->keycreate_sid = 0;
2379 new_tsec->sockcreate_sid = 0;
2381 if (old_tsec->exec_sid) {
2382 new_tsec->sid = old_tsec->exec_sid;
2383 /* Reset exec SID on execve. */
2384 new_tsec->exec_sid = 0;
2386 /* Fail on NNP or nosuid if not an allowed transition. */
2387 rc = check_nnp_nosuid(bprm, old_tsec, new_tsec);
2391 /* Check for a default transition on this program. */
2392 rc = security_transition_sid(&selinux_state, old_tsec->sid,
2393 isec->sid, SECCLASS_PROCESS, NULL,
2399 * Fallback to old SID on NNP or nosuid if not an allowed
2402 rc = check_nnp_nosuid(bprm, old_tsec, new_tsec);
2404 new_tsec->sid = old_tsec->sid;
2407 ad.type = LSM_AUDIT_DATA_FILE;
2408 ad.u.file = bprm->file;
2410 if (new_tsec->sid == old_tsec->sid) {
2411 rc = avc_has_perm(&selinux_state,
2412 old_tsec->sid, isec->sid,
2413 SECCLASS_FILE, FILE__EXECUTE_NO_TRANS, &ad);
2417 /* Check permissions for the transition. */
2418 rc = avc_has_perm(&selinux_state,
2419 old_tsec->sid, new_tsec->sid,
2420 SECCLASS_PROCESS, PROCESS__TRANSITION, &ad);
2424 rc = avc_has_perm(&selinux_state,
2425 new_tsec->sid, isec->sid,
2426 SECCLASS_FILE, FILE__ENTRYPOINT, &ad);
2430 /* Check for shared state */
2431 if (bprm->unsafe & LSM_UNSAFE_SHARE) {
2432 rc = avc_has_perm(&selinux_state,
2433 old_tsec->sid, new_tsec->sid,
2434 SECCLASS_PROCESS, PROCESS__SHARE,
2440 /* Make sure that anyone attempting to ptrace over a task that
2441 * changes its SID has the appropriate permit */
2442 if (bprm->unsafe & LSM_UNSAFE_PTRACE) {
2443 u32 ptsid = ptrace_parent_sid();
2445 rc = avc_has_perm(&selinux_state,
2446 ptsid, new_tsec->sid,
2448 PROCESS__PTRACE, NULL);
2454 /* Clear any possibly unsafe personality bits on exec: */
2455 bprm->per_clear |= PER_CLEAR_ON_SETID;
2457 /* Enable secure mode for SIDs transitions unless
2458 the noatsecure permission is granted between
2459 the two SIDs, i.e. ahp returns 0. */
2460 rc = avc_has_perm(&selinux_state,
2461 old_tsec->sid, new_tsec->sid,
2462 SECCLASS_PROCESS, PROCESS__NOATSECURE,
2464 bprm->secureexec |= !!rc;
2470 static int match_file(const void *p, struct file *file, unsigned fd)
2472 return file_has_perm(p, file, file_to_av(file)) ? fd + 1 : 0;
2475 /* Derived from fs/exec.c:flush_old_files. */
2476 static inline void flush_unauthorized_files(const struct cred *cred,
2477 struct files_struct *files)
2479 struct file *file, *devnull = NULL;
2480 struct tty_struct *tty;
2484 tty = get_current_tty();
2486 spin_lock(&tty->files_lock);
2487 if (!list_empty(&tty->tty_files)) {
2488 struct tty_file_private *file_priv;
2490 /* Revalidate access to controlling tty.
2491 Use file_path_has_perm on the tty path directly
2492 rather than using file_has_perm, as this particular
2493 open file may belong to another process and we are
2494 only interested in the inode-based check here. */
2495 file_priv = list_first_entry(&tty->tty_files,
2496 struct tty_file_private, list);
2497 file = file_priv->file;
2498 if (file_path_has_perm(cred, file, FILE__READ | FILE__WRITE))
2501 spin_unlock(&tty->files_lock);
2504 /* Reset controlling tty. */
2508 /* Revalidate access to inherited open files. */
2509 n = iterate_fd(files, 0, match_file, cred);
2510 if (!n) /* none found? */
2513 devnull = dentry_open(&selinux_null, O_RDWR, cred);
2514 if (IS_ERR(devnull))
2516 /* replace all the matching ones with this */
2518 replace_fd(n - 1, devnull, 0);
2519 } while ((n = iterate_fd(files, n, match_file, cred)) != 0);
2525 * Prepare a process for imminent new credential changes due to exec
2527 static void selinux_bprm_committing_creds(struct linux_binprm *bprm)
2529 struct task_security_struct *new_tsec;
2530 struct rlimit *rlim, *initrlim;
2533 new_tsec = selinux_cred(bprm->cred);
2534 if (new_tsec->sid == new_tsec->osid)
2537 /* Close files for which the new task SID is not authorized. */
2538 flush_unauthorized_files(bprm->cred, current->files);
2540 /* Always clear parent death signal on SID transitions. */
2541 current->pdeath_signal = 0;
2543 /* Check whether the new SID can inherit resource limits from the old
2544 * SID. If not, reset all soft limits to the lower of the current
2545 * task's hard limit and the init task's soft limit.
2547 * Note that the setting of hard limits (even to lower them) can be
2548 * controlled by the setrlimit check. The inclusion of the init task's
2549 * soft limit into the computation is to avoid resetting soft limits
2550 * higher than the default soft limit for cases where the default is
2551 * lower than the hard limit, e.g. RLIMIT_CORE or RLIMIT_STACK.
2553 rc = avc_has_perm(&selinux_state,
2554 new_tsec->osid, new_tsec->sid, SECCLASS_PROCESS,
2555 PROCESS__RLIMITINH, NULL);
2557 /* protect against do_prlimit() */
2559 for (i = 0; i < RLIM_NLIMITS; i++) {
2560 rlim = current->signal->rlim + i;
2561 initrlim = init_task.signal->rlim + i;
2562 rlim->rlim_cur = min(rlim->rlim_max, initrlim->rlim_cur);
2564 task_unlock(current);
2565 if (IS_ENABLED(CONFIG_POSIX_TIMERS))
2566 update_rlimit_cpu(current, rlimit(RLIMIT_CPU));
2571 * Clean up the process immediately after the installation of new credentials
2574 static void selinux_bprm_committed_creds(struct linux_binprm *bprm)
2576 const struct task_security_struct *tsec = selinux_cred(current_cred());
2586 /* Check whether the new SID can inherit signal state from the old SID.
2587 * If not, clear itimers to avoid subsequent signal generation and
2588 * flush and unblock signals.
2590 * This must occur _after_ the task SID has been updated so that any
2591 * kill done after the flush will be checked against the new SID.
2593 rc = avc_has_perm(&selinux_state,
2594 osid, sid, SECCLASS_PROCESS, PROCESS__SIGINH, NULL);
2598 spin_lock_irq(¤t->sighand->siglock);
2599 if (!fatal_signal_pending(current)) {
2600 flush_sigqueue(¤t->pending);
2601 flush_sigqueue(¤t->signal->shared_pending);
2602 flush_signal_handlers(current, 1);
2603 sigemptyset(¤t->blocked);
2604 recalc_sigpending();
2606 spin_unlock_irq(¤t->sighand->siglock);
2609 /* Wake up the parent if it is waiting so that it can recheck
2610 * wait permission to the new task SID. */
2611 read_lock(&tasklist_lock);
2612 __wake_up_parent(current, current->real_parent);
2613 read_unlock(&tasklist_lock);
2616 /* superblock security operations */
2618 static int selinux_sb_alloc_security(struct super_block *sb)
2620 struct superblock_security_struct *sbsec;
2622 sbsec = kzalloc(sizeof(struct superblock_security_struct), GFP_KERNEL);
2626 mutex_init(&sbsec->lock);
2627 INIT_LIST_HEAD(&sbsec->isec_head);
2628 spin_lock_init(&sbsec->isec_lock);
2629 sbsec->sid = SECINITSID_UNLABELED;
2630 sbsec->def_sid = SECINITSID_FILE;
2631 sbsec->mntpoint_sid = SECINITSID_UNLABELED;
2632 sb->s_security = sbsec;
2637 static void selinux_sb_free_security(struct super_block *sb)
2639 superblock_free_security(sb);
2642 static inline int opt_len(const char *s)
2644 bool open_quote = false;
2648 for (len = 0; (c = s[len]) != '\0'; len++) {
2650 open_quote = !open_quote;
2651 if (c == ',' && !open_quote)
2657 static int selinux_sb_eat_lsm_opts(char *options, void **mnt_opts)
2659 char *from = options;
2665 int len = opt_len(from);
2669 token = match_opt_prefix(from, len, &arg);
2671 if (token != Opt_error) {
2676 for (p = q = arg; p < from + len; p++) {
2681 arg = kmemdup_nul(arg, q - arg, GFP_KERNEL);
2687 rc = selinux_add_opt(token, arg, mnt_opts);
2693 if (!first) { // copy with preceding comma
2698 memmove(to, from, len);
2711 selinux_free_mnt_opts(*mnt_opts);
2717 static int selinux_sb_mnt_opts_compat(struct super_block *sb, void *mnt_opts)
2719 struct selinux_mnt_opts *opts = mnt_opts;
2720 struct superblock_security_struct *sbsec = sb->s_security;
2725 * Superblock not initialized (i.e. no options) - reject if any
2726 * options specified, otherwise accept.
2728 if (!(sbsec->flags & SE_SBINITIALIZED))
2729 return opts ? 1 : 0;
2732 * Superblock initialized and no options specified - reject if
2733 * superblock has any options set, otherwise accept.
2736 return (sbsec->flags & SE_MNTMASK) ? 1 : 0;
2738 if (opts->fscontext) {
2739 rc = parse_sid(sb, opts->fscontext, &sid);
2742 if (bad_option(sbsec, FSCONTEXT_MNT, sbsec->sid, sid))
2745 if (opts->context) {
2746 rc = parse_sid(sb, opts->context, &sid);
2749 if (bad_option(sbsec, CONTEXT_MNT, sbsec->mntpoint_sid, sid))
2752 if (opts->rootcontext) {
2753 struct inode_security_struct *root_isec;
2755 root_isec = backing_inode_security(sb->s_root);
2756 rc = parse_sid(sb, opts->rootcontext, &sid);
2759 if (bad_option(sbsec, ROOTCONTEXT_MNT, root_isec->sid, sid))
2762 if (opts->defcontext) {
2763 rc = parse_sid(sb, opts->defcontext, &sid);
2766 if (bad_option(sbsec, DEFCONTEXT_MNT, sbsec->def_sid, sid))
2772 static int selinux_sb_remount(struct super_block *sb, void *mnt_opts)
2774 struct selinux_mnt_opts *opts = mnt_opts;
2775 struct superblock_security_struct *sbsec = sb->s_security;
2779 if (!(sbsec->flags & SE_SBINITIALIZED))
2785 if (opts->fscontext) {
2786 rc = parse_sid(sb, opts->fscontext, &sid);
2789 if (bad_option(sbsec, FSCONTEXT_MNT, sbsec->sid, sid))
2790 goto out_bad_option;
2792 if (opts->context) {
2793 rc = parse_sid(sb, opts->context, &sid);
2796 if (bad_option(sbsec, CONTEXT_MNT, sbsec->mntpoint_sid, sid))
2797 goto out_bad_option;
2799 if (opts->rootcontext) {
2800 struct inode_security_struct *root_isec;
2801 root_isec = backing_inode_security(sb->s_root);
2802 rc = parse_sid(sb, opts->rootcontext, &sid);
2805 if (bad_option(sbsec, ROOTCONTEXT_MNT, root_isec->sid, sid))
2806 goto out_bad_option;
2808 if (opts->defcontext) {
2809 rc = parse_sid(sb, opts->defcontext, &sid);
2812 if (bad_option(sbsec, DEFCONTEXT_MNT, sbsec->def_sid, sid))
2813 goto out_bad_option;
2818 pr_warn("SELinux: unable to change security options "
2819 "during remount (dev %s, type=%s)\n", sb->s_id,
2824 static int selinux_sb_kern_mount(struct super_block *sb)
2826 const struct cred *cred = current_cred();
2827 struct common_audit_data ad;
2829 ad.type = LSM_AUDIT_DATA_DENTRY;
2830 ad.u.dentry = sb->s_root;
2831 return superblock_has_perm(cred, sb, FILESYSTEM__MOUNT, &ad);
2834 static int selinux_sb_statfs(struct dentry *dentry)
2836 const struct cred *cred = current_cred();
2837 struct common_audit_data ad;
2839 ad.type = LSM_AUDIT_DATA_DENTRY;
2840 ad.u.dentry = dentry->d_sb->s_root;
2841 return superblock_has_perm(cred, dentry->d_sb, FILESYSTEM__GETATTR, &ad);
2844 static int selinux_mount(const char *dev_name,
2845 const struct path *path,
2847 unsigned long flags,
2850 const struct cred *cred = current_cred();
2852 if (flags & MS_REMOUNT)
2853 return superblock_has_perm(cred, path->dentry->d_sb,
2854 FILESYSTEM__REMOUNT, NULL);
2856 return path_has_perm(cred, path, FILE__MOUNTON);
2859 static int selinux_move_mount(const struct path *from_path,
2860 const struct path *to_path)
2862 const struct cred *cred = current_cred();
2864 return path_has_perm(cred, to_path, FILE__MOUNTON);
2867 static int selinux_umount(struct vfsmount *mnt, int flags)
2869 const struct cred *cred = current_cred();
2871 return superblock_has_perm(cred, mnt->mnt_sb,
2872 FILESYSTEM__UNMOUNT, NULL);
2875 static int selinux_fs_context_dup(struct fs_context *fc,
2876 struct fs_context *src_fc)
2878 const struct selinux_mnt_opts *src = src_fc->security;
2879 struct selinux_mnt_opts *opts;
2884 fc->security = kzalloc(sizeof(struct selinux_mnt_opts), GFP_KERNEL);
2888 opts = fc->security;
2890 if (src->fscontext) {
2891 opts->fscontext = kstrdup(src->fscontext, GFP_KERNEL);
2892 if (!opts->fscontext)
2896 opts->context = kstrdup(src->context, GFP_KERNEL);
2900 if (src->rootcontext) {
2901 opts->rootcontext = kstrdup(src->rootcontext, GFP_KERNEL);
2902 if (!opts->rootcontext)
2905 if (src->defcontext) {
2906 opts->defcontext = kstrdup(src->defcontext, GFP_KERNEL);
2907 if (!opts->defcontext)
2913 static const struct fs_parameter_spec selinux_fs_parameters[] = {
2914 fsparam_string(CONTEXT_STR, Opt_context),
2915 fsparam_string(DEFCONTEXT_STR, Opt_defcontext),
2916 fsparam_string(FSCONTEXT_STR, Opt_fscontext),
2917 fsparam_string(ROOTCONTEXT_STR, Opt_rootcontext),
2918 fsparam_flag (SECLABEL_STR, Opt_seclabel),
2922 static int selinux_fs_context_parse_param(struct fs_context *fc,
2923 struct fs_parameter *param)
2925 struct fs_parse_result result;
2928 opt = fs_parse(fc, selinux_fs_parameters, param, &result);
2932 rc = selinux_add_opt(opt, param->string, &fc->security);
2934 param->string = NULL;
2940 /* inode security operations */
2942 static int selinux_inode_alloc_security(struct inode *inode)
2944 struct inode_security_struct *isec = selinux_inode(inode);
2945 u32 sid = current_sid();
2947 spin_lock_init(&isec->lock);
2948 INIT_LIST_HEAD(&isec->list);
2949 isec->inode = inode;
2950 isec->sid = SECINITSID_UNLABELED;
2951 isec->sclass = SECCLASS_FILE;
2952 isec->task_sid = sid;
2953 isec->initialized = LABEL_INVALID;
2958 static void selinux_inode_free_security(struct inode *inode)
2960 inode_free_security(inode);
2963 static int selinux_dentry_init_security(struct dentry *dentry, int mode,
2964 const struct qstr *name, void **ctx,
2970 rc = selinux_determine_inode_label(selinux_cred(current_cred()),
2971 d_inode(dentry->d_parent), name,
2972 inode_mode_to_security_class(mode),
2977 return security_sid_to_context(&selinux_state, newsid, (char **)ctx,
2981 static int selinux_dentry_create_files_as(struct dentry *dentry, int mode,
2983 const struct cred *old,
2988 struct task_security_struct *tsec;
2990 rc = selinux_determine_inode_label(selinux_cred(old),
2991 d_inode(dentry->d_parent), name,
2992 inode_mode_to_security_class(mode),
2997 tsec = selinux_cred(new);
2998 tsec->create_sid = newsid;
3002 static int selinux_inode_init_security(struct inode *inode, struct inode *dir,
3003 const struct qstr *qstr,
3005 void **value, size_t *len)
3007 const struct task_security_struct *tsec = selinux_cred(current_cred());
3008 struct superblock_security_struct *sbsec;
3013 sbsec = dir->i_sb->s_security;
3015 newsid = tsec->create_sid;
3017 rc = selinux_determine_inode_label(tsec, dir, qstr,
3018 inode_mode_to_security_class(inode->i_mode),
3023 /* Possibly defer initialization to selinux_complete_init. */
3024 if (sbsec->flags & SE_SBINITIALIZED) {
3025 struct inode_security_struct *isec = selinux_inode(inode);
3026 isec->sclass = inode_mode_to_security_class(inode->i_mode);
3028 isec->initialized = LABEL_INITIALIZED;
3031 if (!selinux_initialized(&selinux_state) ||
3032 !(sbsec->flags & SBLABEL_MNT))
3036 *name = XATTR_SELINUX_SUFFIX;
3039 rc = security_sid_to_context_force(&selinux_state, newsid,
3050 static int selinux_inode_init_security_anon(struct inode *inode,
3051 const struct qstr *name,
3052 const struct inode *context_inode)
3054 const struct task_security_struct *tsec = selinux_cred(current_cred());
3055 struct common_audit_data ad;
3056 struct inode_security_struct *isec;
3059 if (unlikely(!selinux_initialized(&selinux_state)))
3062 isec = selinux_inode(inode);
3065 * We only get here once per ephemeral inode. The inode has
3066 * been initialized via inode_alloc_security but is otherwise
3070 if (context_inode) {
3071 struct inode_security_struct *context_isec =
3072 selinux_inode(context_inode);
3073 if (context_isec->initialized != LABEL_INITIALIZED) {
3074 pr_err("SELinux: context_inode is not initialized");
3078 isec->sclass = context_isec->sclass;
3079 isec->sid = context_isec->sid;
3081 isec->sclass = SECCLASS_ANON_INODE;
3082 rc = security_transition_sid(
3083 &selinux_state, tsec->sid, tsec->sid,
3084 isec->sclass, name, &isec->sid);
3089 isec->initialized = LABEL_INITIALIZED;
3091 * Now that we've initialized security, check whether we're
3092 * allowed to actually create this type of anonymous inode.
3095 ad.type = LSM_AUDIT_DATA_INODE;
3098 return avc_has_perm(&selinux_state,
3106 static int selinux_inode_create(struct inode *dir, struct dentry *dentry, umode_t mode)
3108 return may_create(dir, dentry, SECCLASS_FILE);
3111 static int selinux_inode_link(struct dentry *old_dentry, struct inode *dir, struct dentry *new_dentry)
3113 return may_link(dir, old_dentry, MAY_LINK);
3116 static int selinux_inode_unlink(struct inode *dir, struct dentry *dentry)
3118 return may_link(dir, dentry, MAY_UNLINK);
3121 static int selinux_inode_symlink(struct inode *dir, struct dentry *dentry, const char *name)
3123 return may_create(dir, dentry, SECCLASS_LNK_FILE);
3126 static int selinux_inode_mkdir(struct inode *dir, struct dentry *dentry, umode_t mask)
3128 return may_create(dir, dentry, SECCLASS_DIR);
3131 static int selinux_inode_rmdir(struct inode *dir, struct dentry *dentry)
3133 return may_link(dir, dentry, MAY_RMDIR);
3136 static int selinux_inode_mknod(struct inode *dir, struct dentry *dentry, umode_t mode, dev_t dev)
3138 return may_create(dir, dentry, inode_mode_to_security_class(mode));
3141 static int selinux_inode_rename(struct inode *old_inode, struct dentry *old_dentry,
3142 struct inode *new_inode, struct dentry *new_dentry)
3144 return may_rename(old_inode, old_dentry, new_inode, new_dentry);
3147 static int selinux_inode_readlink(struct dentry *dentry)
3149 const struct cred *cred = current_cred();
3151 return dentry_has_perm(cred, dentry, FILE__READ);
3154 static int selinux_inode_follow_link(struct dentry *dentry, struct inode *inode,
3157 const struct cred *cred = current_cred();
3158 struct common_audit_data ad;
3159 struct inode_security_struct *isec;
3162 validate_creds(cred);
3164 ad.type = LSM_AUDIT_DATA_DENTRY;
3165 ad.u.dentry = dentry;
3166 sid = cred_sid(cred);
3167 isec = inode_security_rcu(inode, rcu);
3169 return PTR_ERR(isec);
3171 return avc_has_perm_flags(&selinux_state,
3172 sid, isec->sid, isec->sclass, FILE__READ, &ad,
3173 rcu ? MAY_NOT_BLOCK : 0);
3176 static noinline int audit_inode_permission(struct inode *inode,
3177 u32 perms, u32 audited, u32 denied,
3180 struct common_audit_data ad;
3181 struct inode_security_struct *isec = selinux_inode(inode);
3184 ad.type = LSM_AUDIT_DATA_INODE;
3187 rc = slow_avc_audit(&selinux_state,
3188 current_sid(), isec->sid, isec->sclass, perms,
3189 audited, denied, result, &ad);
3195 static int selinux_inode_permission(struct inode *inode, int mask)
3197 const struct cred *cred = current_cred();
3200 bool no_block = mask & MAY_NOT_BLOCK;
3201 struct inode_security_struct *isec;
3203 struct av_decision avd;
3205 u32 audited, denied;
3207 from_access = mask & MAY_ACCESS;
3208 mask &= (MAY_READ|MAY_WRITE|MAY_EXEC|MAY_APPEND);
3210 /* No permission to check. Existence test. */
3214 validate_creds(cred);
3216 if (unlikely(IS_PRIVATE(inode)))
3219 perms = file_mask_to_av(inode->i_mode, mask);
3221 sid = cred_sid(cred);
3222 isec = inode_security_rcu(inode, no_block);
3224 return PTR_ERR(isec);
3226 rc = avc_has_perm_noaudit(&selinux_state,
3227 sid, isec->sid, isec->sclass, perms,
3228 no_block ? AVC_NONBLOCKING : 0,
3230 audited = avc_audit_required(perms, &avd, rc,
3231 from_access ? FILE__AUDIT_ACCESS : 0,
3233 if (likely(!audited))
3236 /* fall back to ref-walk if we have to generate audit */
3240 rc2 = audit_inode_permission(inode, perms, audited, denied, rc);
3246 static int selinux_inode_setattr(struct dentry *dentry, struct iattr *iattr)
3248 const struct cred *cred = current_cred();
3249 struct inode *inode = d_backing_inode(dentry);
3250 unsigned int ia_valid = iattr->ia_valid;
3251 __u32 av = FILE__WRITE;
3253 /* ATTR_FORCE is just used for ATTR_KILL_S[UG]ID. */
3254 if (ia_valid & ATTR_FORCE) {
3255 ia_valid &= ~(ATTR_KILL_SUID | ATTR_KILL_SGID | ATTR_MODE |
3261 if (ia_valid & (ATTR_MODE | ATTR_UID | ATTR_GID |
3262 ATTR_ATIME_SET | ATTR_MTIME_SET | ATTR_TIMES_SET))
3263 return dentry_has_perm(cred, dentry, FILE__SETATTR);
3265 if (selinux_policycap_openperm() &&
3266 inode->i_sb->s_magic != SOCKFS_MAGIC &&
3267 (ia_valid & ATTR_SIZE) &&
3268 !(ia_valid & ATTR_FILE))
3271 return dentry_has_perm(cred, dentry, av);
3274 static int selinux_inode_getattr(const struct path *path)
3276 return path_has_perm(current_cred(), path, FILE__GETATTR);
3279 static bool has_cap_mac_admin(bool audit)
3281 const struct cred *cred = current_cred();
3282 unsigned int opts = audit ? CAP_OPT_NONE : CAP_OPT_NOAUDIT;
3284 if (cap_capable(cred, &init_user_ns, CAP_MAC_ADMIN, opts))
3286 if (cred_has_capability(cred, CAP_MAC_ADMIN, opts, true))
3291 static int selinux_inode_setxattr(struct user_namespace *mnt_userns,
3292 struct dentry *dentry, const char *name,
3293 const void *value, size_t size, int flags)
3295 struct inode *inode = d_backing_inode(dentry);
3296 struct inode_security_struct *isec;
3297 struct superblock_security_struct *sbsec;
3298 struct common_audit_data ad;
3299 u32 newsid, sid = current_sid();
3302 if (strcmp(name, XATTR_NAME_SELINUX)) {
3303 rc = cap_inode_setxattr(dentry, name, value, size, flags);
3307 /* Not an attribute we recognize, so just check the
3308 ordinary setattr permission. */
3309 return dentry_has_perm(current_cred(), dentry, FILE__SETATTR);
3312 if (!selinux_initialized(&selinux_state))
3313 return (inode_owner_or_capable(mnt_userns, inode) ? 0 : -EPERM);
3315 sbsec = inode->i_sb->s_security;
3316 if (!(sbsec->flags & SBLABEL_MNT))
3319 if (!inode_owner_or_capable(mnt_userns, inode))
3322 ad.type = LSM_AUDIT_DATA_DENTRY;
3323 ad.u.dentry = dentry;
3325 isec = backing_inode_security(dentry);
3326 rc = avc_has_perm(&selinux_state,
3327 sid, isec->sid, isec->sclass,
3328 FILE__RELABELFROM, &ad);
3332 rc = security_context_to_sid(&selinux_state, value, size, &newsid,
3334 if (rc == -EINVAL) {
3335 if (!has_cap_mac_admin(true)) {
3336 struct audit_buffer *ab;
3339 /* We strip a nul only if it is at the end, otherwise the
3340 * context contains a nul and we should audit that */
3342 const char *str = value;
3344 if (str[size - 1] == '\0')
3345 audit_size = size - 1;
3351 ab = audit_log_start(audit_context(),
3352 GFP_ATOMIC, AUDIT_SELINUX_ERR);
3353 audit_log_format(ab, "op=setxattr invalid_context=");
3354 audit_log_n_untrustedstring(ab, value, audit_size);
3359 rc = security_context_to_sid_force(&selinux_state, value,
3365 rc = avc_has_perm(&selinux_state,
3366 sid, newsid, isec->sclass,
3367 FILE__RELABELTO, &ad);
3371 rc = security_validate_transition(&selinux_state, isec->sid, newsid,
3376 return avc_has_perm(&selinux_state,
3379 SECCLASS_FILESYSTEM,
3380 FILESYSTEM__ASSOCIATE,
3384 static void selinux_inode_post_setxattr(struct dentry *dentry, const char *name,
3385 const void *value, size_t size,
3388 struct inode *inode = d_backing_inode(dentry);
3389 struct inode_security_struct *isec;
3393 if (strcmp(name, XATTR_NAME_SELINUX)) {
3394 /* Not an attribute we recognize, so nothing to do. */
3398 if (!selinux_initialized(&selinux_state)) {
3399 /* If we haven't even been initialized, then we can't validate
3400 * against a policy, so leave the label as invalid. It may
3401 * resolve to a valid label on the next revalidation try if
3402 * we've since initialized.
3407 rc = security_context_to_sid_force(&selinux_state, value, size,
3410 pr_err("SELinux: unable to map context to SID"
3411 "for (%s, %lu), rc=%d\n",
3412 inode->i_sb->s_id, inode->i_ino, -rc);
3416 isec = backing_inode_security(dentry);
3417 spin_lock(&isec->lock);
3418 isec->sclass = inode_mode_to_security_class(inode->i_mode);
3420 isec->initialized = LABEL_INITIALIZED;
3421 spin_unlock(&isec->lock);
3426 static int selinux_inode_getxattr(struct dentry *dentry, const char *name)
3428 const struct cred *cred = current_cred();
3430 return dentry_has_perm(cred, dentry, FILE__GETATTR);
3433 static int selinux_inode_listxattr(struct dentry *dentry)
3435 const struct cred *cred = current_cred();
3437 return dentry_has_perm(cred, dentry, FILE__GETATTR);
3440 static int selinux_inode_removexattr(struct user_namespace *mnt_userns,
3441 struct dentry *dentry, const char *name)
3443 if (strcmp(name, XATTR_NAME_SELINUX)) {
3444 int rc = cap_inode_removexattr(mnt_userns, dentry, name);
3448 /* Not an attribute we recognize, so just check the
3449 ordinary setattr permission. */
3450 return dentry_has_perm(current_cred(), dentry, FILE__SETATTR);
3453 if (!selinux_initialized(&selinux_state))
3456 /* No one is allowed to remove a SELinux security label.
3457 You can change the label, but all data must be labeled. */
3461 static int selinux_path_notify(const struct path *path, u64 mask,
3462 unsigned int obj_type)
3467 struct common_audit_data ad;
3469 ad.type = LSM_AUDIT_DATA_PATH;
3473 * Set permission needed based on the type of mark being set.
3474 * Performs an additional check for sb watches.
3477 case FSNOTIFY_OBJ_TYPE_VFSMOUNT:
3478 perm = FILE__WATCH_MOUNT;
3480 case FSNOTIFY_OBJ_TYPE_SB:
3481 perm = FILE__WATCH_SB;
3482 ret = superblock_has_perm(current_cred(), path->dentry->d_sb,
3483 FILESYSTEM__WATCH, &ad);
3487 case FSNOTIFY_OBJ_TYPE_INODE:
3494 /* blocking watches require the file:watch_with_perm permission */
3495 if (mask & (ALL_FSNOTIFY_PERM_EVENTS))
3496 perm |= FILE__WATCH_WITH_PERM;
3498 /* watches on read-like events need the file:watch_reads permission */
3499 if (mask & (FS_ACCESS | FS_ACCESS_PERM | FS_CLOSE_NOWRITE))
3500 perm |= FILE__WATCH_READS;
3502 return path_has_perm(current_cred(), path, perm);
3506 * Copy the inode security context value to the user.
3508 * Permission check is handled by selinux_inode_getxattr hook.
3510 static int selinux_inode_getsecurity(struct user_namespace *mnt_userns,
3511 struct inode *inode, const char *name,
3512 void **buffer, bool alloc)
3516 char *context = NULL;
3517 struct inode_security_struct *isec;
3520 * If we're not initialized yet, then we can't validate contexts, so
3521 * just let vfs_getxattr fall back to using the on-disk xattr.
3523 if (!selinux_initialized(&selinux_state) ||
3524 strcmp(name, XATTR_SELINUX_SUFFIX))
3528 * If the caller has CAP_MAC_ADMIN, then get the raw context
3529 * value even if it is not defined by current policy; otherwise,
3530 * use the in-core value under current policy.
3531 * Use the non-auditing forms of the permission checks since
3532 * getxattr may be called by unprivileged processes commonly
3533 * and lack of permission just means that we fall back to the
3534 * in-core context value, not a denial.
3536 isec = inode_security(inode);
3537 if (has_cap_mac_admin(false))
3538 error = security_sid_to_context_force(&selinux_state,
3539 isec->sid, &context,
3542 error = security_sid_to_context(&selinux_state, isec->sid,
3556 static int selinux_inode_setsecurity(struct inode *inode, const char *name,
3557 const void *value, size_t size, int flags)
3559 struct inode_security_struct *isec = inode_security_novalidate(inode);
3560 struct superblock_security_struct *sbsec = inode->i_sb->s_security;
3564 if (strcmp(name, XATTR_SELINUX_SUFFIX))
3567 if (!(sbsec->flags & SBLABEL_MNT))
3570 if (!value || !size)
3573 rc = security_context_to_sid(&selinux_state, value, size, &newsid,
3578 spin_lock(&isec->lock);
3579 isec->sclass = inode_mode_to_security_class(inode->i_mode);
3581 isec->initialized = LABEL_INITIALIZED;
3582 spin_unlock(&isec->lock);
3586 static int selinux_inode_listsecurity(struct inode *inode, char *buffer, size_t buffer_size)
3588 const int len = sizeof(XATTR_NAME_SELINUX);
3590 if (!selinux_initialized(&selinux_state))
3593 if (buffer && len <= buffer_size)
3594 memcpy(buffer, XATTR_NAME_SELINUX, len);
3598 static void selinux_inode_getsecid(struct inode *inode, u32 *secid)
3600 struct inode_security_struct *isec = inode_security_novalidate(inode);
3604 static int selinux_inode_copy_up(struct dentry *src, struct cred **new)
3607 struct task_security_struct *tsec;
3608 struct cred *new_creds = *new;
3610 if (new_creds == NULL) {
3611 new_creds = prepare_creds();
3616 tsec = selinux_cred(new_creds);
3617 /* Get label from overlay inode and set it in create_sid */
3618 selinux_inode_getsecid(d_inode(src), &sid);
3619 tsec->create_sid = sid;
3624 static int selinux_inode_copy_up_xattr(const char *name)
3626 /* The copy_up hook above sets the initial context on an inode, but we
3627 * don't then want to overwrite it by blindly copying all the lower
3628 * xattrs up. Instead, we have to filter out SELinux-related xattrs.
3630 if (strcmp(name, XATTR_NAME_SELINUX) == 0)
3631 return 1; /* Discard */
3633 * Any other attribute apart from SELINUX is not claimed, supported
3639 /* kernfs node operations */
3641 static int selinux_kernfs_init_security(struct kernfs_node *kn_dir,
3642 struct kernfs_node *kn)
3644 const struct task_security_struct *tsec = selinux_cred(current_cred());
3645 u32 parent_sid, newsid, clen;
3649 rc = kernfs_xattr_get(kn_dir, XATTR_NAME_SELINUX, NULL, 0);
3656 context = kmalloc(clen, GFP_KERNEL);
3660 rc = kernfs_xattr_get(kn_dir, XATTR_NAME_SELINUX, context, clen);
3666 rc = security_context_to_sid(&selinux_state, context, clen, &parent_sid,
3672 if (tsec->create_sid) {
3673 newsid = tsec->create_sid;
3675 u16 secclass = inode_mode_to_security_class(kn->mode);
3679 q.hash_len = hashlen_string(kn_dir, kn->name);
3681 rc = security_transition_sid(&selinux_state, tsec->sid,
3682 parent_sid, secclass, &q,
3688 rc = security_sid_to_context_force(&selinux_state, newsid,
3693 rc = kernfs_xattr_set(kn, XATTR_NAME_SELINUX, context, clen,
3700 /* file security operations */
3702 static int selinux_revalidate_file_permission(struct file *file, int mask)
3704 const struct cred *cred = current_cred();
3705 struct inode *inode = file_inode(file);
3707 /* file_mask_to_av won't add FILE__WRITE if MAY_APPEND is set */
3708 if ((file->f_flags & O_APPEND) && (mask & MAY_WRITE))
3711 return file_has_perm(cred, file,
3712 file_mask_to_av(inode->i_mode, mask));
3715 static int selinux_file_permission(struct file *file, int mask)
3717 struct inode *inode = file_inode(file);
3718 struct file_security_struct *fsec = selinux_file(file);
3719 struct inode_security_struct *isec;
3720 u32 sid = current_sid();
3723 /* No permission to check. Existence test. */
3726 isec = inode_security(inode);
3727 if (sid == fsec->sid && fsec->isid == isec->sid &&
3728 fsec->pseqno == avc_policy_seqno(&selinux_state))
3729 /* No change since file_open check. */
3732 return selinux_revalidate_file_permission(file, mask);
3735 static int selinux_file_alloc_security(struct file *file)
3737 struct file_security_struct *fsec = selinux_file(file);
3738 u32 sid = current_sid();
3741 fsec->fown_sid = sid;
3747 * Check whether a task has the ioctl permission and cmd
3748 * operation to an inode.
3750 static int ioctl_has_perm(const struct cred *cred, struct file *file,
3751 u32 requested, u16 cmd)
3753 struct common_audit_data ad;
3754 struct file_security_struct *fsec = selinux_file(file);
3755 struct inode *inode = file_inode(file);
3756 struct inode_security_struct *isec;
3757 struct lsm_ioctlop_audit ioctl;
3758 u32 ssid = cred_sid(cred);
3760 u8 driver = cmd >> 8;
3761 u8 xperm = cmd & 0xff;
3763 ad.type = LSM_AUDIT_DATA_IOCTL_OP;
3766 ad.u.op->path = file->f_path;
3768 if (ssid != fsec->sid) {
3769 rc = avc_has_perm(&selinux_state,
3778 if (unlikely(IS_PRIVATE(inode)))
3781 isec = inode_security(inode);
3782 rc = avc_has_extended_perms(&selinux_state,
3783 ssid, isec->sid, isec->sclass,
3784 requested, driver, xperm, &ad);
3789 static int selinux_file_ioctl(struct file *file, unsigned int cmd,
3792 const struct cred *cred = current_cred();
3799 case FS_IOC_GETFLAGS:
3800 case FS_IOC_GETVERSION:
3801 error = file_has_perm(cred, file, FILE__GETATTR);
3804 case FS_IOC_SETFLAGS:
3805 case FS_IOC_SETVERSION:
3806 error = file_has_perm(cred, file, FILE__SETATTR);
3809 /* sys_ioctl() checks */
3812 error = file_has_perm(cred, file, 0);
3817 error = cred_has_capability(cred, CAP_SYS_TTY_CONFIG,
3818 CAP_OPT_NONE, true);
3821 /* default case assumes that the command will go
3822 * to the file's ioctl() function.
3825 error = ioctl_has_perm(cred, file, FILE__IOCTL, (u16) cmd);
3830 static int default_noexec __ro_after_init;
3832 static int file_map_prot_check(struct file *file, unsigned long prot, int shared)
3834 const struct cred *cred = current_cred();
3835 u32 sid = cred_sid(cred);
3838 if (default_noexec &&
3839 (prot & PROT_EXEC) && (!file || IS_PRIVATE(file_inode(file)) ||
3840 (!shared && (prot & PROT_WRITE)))) {
3842 * We are making executable an anonymous mapping or a
3843 * private file mapping that will also be writable.
3844 * This has an additional check.
3846 rc = avc_has_perm(&selinux_state,
3847 sid, sid, SECCLASS_PROCESS,
3848 PROCESS__EXECMEM, NULL);
3854 /* read access is always possible with a mapping */
3855 u32 av = FILE__READ;
3857 /* write access only matters if the mapping is shared */
3858 if (shared && (prot & PROT_WRITE))
3861 if (prot & PROT_EXEC)
3862 av |= FILE__EXECUTE;
3864 return file_has_perm(cred, file, av);
3871 static int selinux_mmap_addr(unsigned long addr)
3875 if (addr < CONFIG_LSM_MMAP_MIN_ADDR) {
3876 u32 sid = current_sid();
3877 rc = avc_has_perm(&selinux_state,
3878 sid, sid, SECCLASS_MEMPROTECT,
3879 MEMPROTECT__MMAP_ZERO, NULL);
3885 static int selinux_mmap_file(struct file *file, unsigned long reqprot,
3886 unsigned long prot, unsigned long flags)
3888 struct common_audit_data ad;
3892 ad.type = LSM_AUDIT_DATA_FILE;
3894 rc = inode_has_perm(current_cred(), file_inode(file),
3900 if (checkreqprot_get(&selinux_state))
3903 return file_map_prot_check(file, prot,
3904 (flags & MAP_TYPE) == MAP_SHARED);
3907 static int selinux_file_mprotect(struct vm_area_struct *vma,
3908 unsigned long reqprot,
3911 const struct cred *cred = current_cred();
3912 u32 sid = cred_sid(cred);
3914 if (checkreqprot_get(&selinux_state))
3917 if (default_noexec &&
3918 (prot & PROT_EXEC) && !(vma->vm_flags & VM_EXEC)) {
3920 if (vma->vm_start >= vma->vm_mm->start_brk &&
3921 vma->vm_end <= vma->vm_mm->brk) {
3922 rc = avc_has_perm(&selinux_state,
3923 sid, sid, SECCLASS_PROCESS,
3924 PROCESS__EXECHEAP, NULL);
3925 } else if (!vma->vm_file &&
3926 ((vma->vm_start <= vma->vm_mm->start_stack &&
3927 vma->vm_end >= vma->vm_mm->start_stack) ||
3928 vma_is_stack_for_current(vma))) {
3929 rc = avc_has_perm(&selinux_state,
3930 sid, sid, SECCLASS_PROCESS,
3931 PROCESS__EXECSTACK, NULL);
3932 } else if (vma->vm_file && vma->anon_vma) {
3934 * We are making executable a file mapping that has
3935 * had some COW done. Since pages might have been
3936 * written, check ability to execute the possibly
3937 * modified content. This typically should only
3938 * occur for text relocations.
3940 rc = file_has_perm(cred, vma->vm_file, FILE__EXECMOD);
3946 return file_map_prot_check(vma->vm_file, prot, vma->vm_flags&VM_SHARED);
3949 static int selinux_file_lock(struct file *file, unsigned int cmd)
3951 const struct cred *cred = current_cred();
3953 return file_has_perm(cred, file, FILE__LOCK);
3956 static int selinux_file_fcntl(struct file *file, unsigned int cmd,
3959 const struct cred *cred = current_cred();
3964 if ((file->f_flags & O_APPEND) && !(arg & O_APPEND)) {
3965 err = file_has_perm(cred, file, FILE__WRITE);
3974 case F_GETOWNER_UIDS:
3975 /* Just check FD__USE permission */
3976 err = file_has_perm(cred, file, 0);
3984 #if BITS_PER_LONG == 32
3989 err = file_has_perm(cred, file, FILE__LOCK);
3996 static void selinux_file_set_fowner(struct file *file)
3998 struct file_security_struct *fsec;
4000 fsec = selinux_file(file);
4001 fsec->fown_sid = current_sid();
4004 static int selinux_file_send_sigiotask(struct task_struct *tsk,
4005 struct fown_struct *fown, int signum)
4008 u32 sid = task_sid_obj(tsk);
4010 struct file_security_struct *fsec;
4012 /* struct fown_struct is never outside the context of a struct file */
4013 file = container_of(fown, struct file, f_owner);
4015 fsec = selinux_file(file);
4018 perm = signal_to_av(SIGIO); /* as per send_sigio_to_task */
4020 perm = signal_to_av(signum);
4022 return avc_has_perm(&selinux_state,
4023 fsec->fown_sid, sid,
4024 SECCLASS_PROCESS, perm, NULL);
4027 static int selinux_file_receive(struct file *file)
4029 const struct cred *cred = current_cred();
4031 return file_has_perm(cred, file, file_to_av(file));
4034 static int selinux_file_open(struct file *file)
4036 struct file_security_struct *fsec;
4037 struct inode_security_struct *isec;
4039 fsec = selinux_file(file);
4040 isec = inode_security(file_inode(file));
4042 * Save inode label and policy sequence number
4043 * at open-time so that selinux_file_permission
4044 * can determine whether revalidation is necessary.
4045 * Task label is already saved in the file security
4046 * struct as its SID.
4048 fsec->isid = isec->sid;
4049 fsec->pseqno = avc_policy_seqno(&selinux_state);
4051 * Since the inode label or policy seqno may have changed
4052 * between the selinux_inode_permission check and the saving
4053 * of state above, recheck that access is still permitted.
4054 * Otherwise, access might never be revalidated against the
4055 * new inode label or new policy.
4056 * This check is not redundant - do not remove.
4058 return file_path_has_perm(file->f_cred, file, open_file_to_av(file));
4061 /* task security operations */
4063 static int selinux_task_alloc(struct task_struct *task,
4064 unsigned long clone_flags)
4066 u32 sid = current_sid();
4068 return avc_has_perm(&selinux_state,
4069 sid, sid, SECCLASS_PROCESS, PROCESS__FORK, NULL);
4073 * prepare a new set of credentials for modification
4075 static int selinux_cred_prepare(struct cred *new, const struct cred *old,
4078 const struct task_security_struct *old_tsec = selinux_cred(old);
4079 struct task_security_struct *tsec = selinux_cred(new);
4086 * transfer the SELinux data to a blank set of creds
4088 static void selinux_cred_transfer(struct cred *new, const struct cred *old)
4090 const struct task_security_struct *old_tsec = selinux_cred(old);
4091 struct task_security_struct *tsec = selinux_cred(new);
4096 static void selinux_cred_getsecid(const struct cred *c, u32 *secid)
4098 *secid = cred_sid(c);
4102 * set the security data for a kernel service
4103 * - all the creation contexts are set to unlabelled
4105 static int selinux_kernel_act_as(struct cred *new, u32 secid)
4107 struct task_security_struct *tsec = selinux_cred(new);
4108 u32 sid = current_sid();
4111 ret = avc_has_perm(&selinux_state,
4113 SECCLASS_KERNEL_SERVICE,
4114 KERNEL_SERVICE__USE_AS_OVERRIDE,
4118 tsec->create_sid = 0;
4119 tsec->keycreate_sid = 0;
4120 tsec->sockcreate_sid = 0;
4126 * set the file creation context in a security record to the same as the
4127 * objective context of the specified inode
4129 static int selinux_kernel_create_files_as(struct cred *new, struct inode *inode)
4131 struct inode_security_struct *isec = inode_security(inode);
4132 struct task_security_struct *tsec = selinux_cred(new);
4133 u32 sid = current_sid();
4136 ret = avc_has_perm(&selinux_state,
4138 SECCLASS_KERNEL_SERVICE,
4139 KERNEL_SERVICE__CREATE_FILES_AS,
4143 tsec->create_sid = isec->sid;
4147 static int selinux_kernel_module_request(char *kmod_name)
4149 struct common_audit_data ad;
4151 ad.type = LSM_AUDIT_DATA_KMOD;
4152 ad.u.kmod_name = kmod_name;
4154 return avc_has_perm(&selinux_state,
4155 current_sid(), SECINITSID_KERNEL, SECCLASS_SYSTEM,
4156 SYSTEM__MODULE_REQUEST, &ad);
4159 static int selinux_kernel_module_from_file(struct file *file)
4161 struct common_audit_data ad;
4162 struct inode_security_struct *isec;
4163 struct file_security_struct *fsec;
4164 u32 sid = current_sid();
4169 return avc_has_perm(&selinux_state,
4170 sid, sid, SECCLASS_SYSTEM,
4171 SYSTEM__MODULE_LOAD, NULL);
4175 ad.type = LSM_AUDIT_DATA_FILE;
4178 fsec = selinux_file(file);
4179 if (sid != fsec->sid) {
4180 rc = avc_has_perm(&selinux_state,
4181 sid, fsec->sid, SECCLASS_FD, FD__USE, &ad);
4186 isec = inode_security(file_inode(file));
4187 return avc_has_perm(&selinux_state,
4188 sid, isec->sid, SECCLASS_SYSTEM,
4189 SYSTEM__MODULE_LOAD, &ad);
4192 static int selinux_kernel_read_file(struct file *file,
4193 enum kernel_read_file_id id,
4199 case READING_MODULE:
4200 rc = selinux_kernel_module_from_file(contents ? file : NULL);
4209 static int selinux_kernel_load_data(enum kernel_load_data_id id, bool contents)
4214 case LOADING_MODULE:
4215 rc = selinux_kernel_module_from_file(NULL);
4224 static int selinux_task_setpgid(struct task_struct *p, pid_t pgid)
4226 return avc_has_perm(&selinux_state,
4227 current_sid(), task_sid_obj(p), SECCLASS_PROCESS,
4228 PROCESS__SETPGID, NULL);
4231 static int selinux_task_getpgid(struct task_struct *p)
4233 return avc_has_perm(&selinux_state,
4234 current_sid(), task_sid_obj(p), SECCLASS_PROCESS,
4235 PROCESS__GETPGID, NULL);
4238 static int selinux_task_getsid(struct task_struct *p)
4240 return avc_has_perm(&selinux_state,
4241 current_sid(), task_sid_obj(p), SECCLASS_PROCESS,
4242 PROCESS__GETSESSION, NULL);
4245 static void selinux_task_getsecid_subj(struct task_struct *p, u32 *secid)
4247 *secid = task_sid_subj(p);
4250 static void selinux_task_getsecid_obj(struct task_struct *p, u32 *secid)
4252 *secid = task_sid_obj(p);
4255 static int selinux_task_setnice(struct task_struct *p, int nice)
4257 return avc_has_perm(&selinux_state,
4258 current_sid(), task_sid_obj(p), SECCLASS_PROCESS,
4259 PROCESS__SETSCHED, NULL);
4262 static int selinux_task_setioprio(struct task_struct *p, int ioprio)
4264 return avc_has_perm(&selinux_state,
4265 current_sid(), task_sid_obj(p), SECCLASS_PROCESS,
4266 PROCESS__SETSCHED, NULL);
4269 static int selinux_task_getioprio(struct task_struct *p)
4271 return avc_has_perm(&selinux_state,
4272 current_sid(), task_sid_obj(p), SECCLASS_PROCESS,
4273 PROCESS__GETSCHED, NULL);
4276 static int selinux_task_prlimit(const struct cred *cred, const struct cred *tcred,
4283 if (flags & LSM_PRLIMIT_WRITE)
4284 av |= PROCESS__SETRLIMIT;
4285 if (flags & LSM_PRLIMIT_READ)
4286 av |= PROCESS__GETRLIMIT;
4287 return avc_has_perm(&selinux_state,
4288 cred_sid(cred), cred_sid(tcred),
4289 SECCLASS_PROCESS, av, NULL);
4292 static int selinux_task_setrlimit(struct task_struct *p, unsigned int resource,
4293 struct rlimit *new_rlim)
4295 struct rlimit *old_rlim = p->signal->rlim + resource;
4297 /* Control the ability to change the hard limit (whether
4298 lowering or raising it), so that the hard limit can
4299 later be used as a safe reset point for the soft limit
4300 upon context transitions. See selinux_bprm_committing_creds. */
4301 if (old_rlim->rlim_max != new_rlim->rlim_max)
4302 return avc_has_perm(&selinux_state,
4303 current_sid(), task_sid_obj(p),
4304 SECCLASS_PROCESS, PROCESS__SETRLIMIT, NULL);
4309 static int selinux_task_setscheduler(struct task_struct *p)
4311 return avc_has_perm(&selinux_state,
4312 current_sid(), task_sid_obj(p), SECCLASS_PROCESS,
4313 PROCESS__SETSCHED, NULL);
4316 static int selinux_task_getscheduler(struct task_struct *p)
4318 return avc_has_perm(&selinux_state,
4319 current_sid(), task_sid_obj(p), SECCLASS_PROCESS,
4320 PROCESS__GETSCHED, NULL);
4323 static int selinux_task_movememory(struct task_struct *p)
4325 return avc_has_perm(&selinux_state,
4326 current_sid(), task_sid_obj(p), SECCLASS_PROCESS,
4327 PROCESS__SETSCHED, NULL);
4330 static int selinux_task_kill(struct task_struct *p, struct kernel_siginfo *info,
4331 int sig, const struct cred *cred)
4337 perm = PROCESS__SIGNULL; /* null signal; existence test */
4339 perm = signal_to_av(sig);
4341 secid = current_sid();
4343 secid = cred_sid(cred);
4344 return avc_has_perm(&selinux_state,
4345 secid, task_sid_obj(p), SECCLASS_PROCESS, perm, NULL);
4348 static void selinux_task_to_inode(struct task_struct *p,
4349 struct inode *inode)
4351 struct inode_security_struct *isec = selinux_inode(inode);
4352 u32 sid = task_sid_obj(p);
4354 spin_lock(&isec->lock);
4355 isec->sclass = inode_mode_to_security_class(inode->i_mode);
4357 isec->initialized = LABEL_INITIALIZED;
4358 spin_unlock(&isec->lock);
4361 /* Returns error only if unable to parse addresses */
4362 static int selinux_parse_skb_ipv4(struct sk_buff *skb,
4363 struct common_audit_data *ad, u8 *proto)
4365 int offset, ihlen, ret = -EINVAL;
4366 struct iphdr _iph, *ih;
4368 offset = skb_network_offset(skb);
4369 ih = skb_header_pointer(skb, offset, sizeof(_iph), &_iph);
4373 ihlen = ih->ihl * 4;
4374 if (ihlen < sizeof(_iph))
4377 ad->u.net->v4info.saddr = ih->saddr;
4378 ad->u.net->v4info.daddr = ih->daddr;
4382 *proto = ih->protocol;
4384 switch (ih->protocol) {
4386 struct tcphdr _tcph, *th;
4388 if (ntohs(ih->frag_off) & IP_OFFSET)
4392 th = skb_header_pointer(skb, offset, sizeof(_tcph), &_tcph);
4396 ad->u.net->sport = th->source;
4397 ad->u.net->dport = th->dest;
4402 struct udphdr _udph, *uh;
4404 if (ntohs(ih->frag_off) & IP_OFFSET)
4408 uh = skb_header_pointer(skb, offset, sizeof(_udph), &_udph);
4412 ad->u.net->sport = uh->source;
4413 ad->u.net->dport = uh->dest;
4417 case IPPROTO_DCCP: {
4418 struct dccp_hdr _dccph, *dh;
4420 if (ntohs(ih->frag_off) & IP_OFFSET)
4424 dh = skb_header_pointer(skb, offset, sizeof(_dccph), &_dccph);
4428 ad->u.net->sport = dh->dccph_sport;
4429 ad->u.net->dport = dh->dccph_dport;
4433 #if IS_ENABLED(CONFIG_IP_SCTP)
4434 case IPPROTO_SCTP: {
4435 struct sctphdr _sctph, *sh;
4437 if (ntohs(ih->frag_off) & IP_OFFSET)
4441 sh = skb_header_pointer(skb, offset, sizeof(_sctph), &_sctph);
4445 ad->u.net->sport = sh->source;
4446 ad->u.net->dport = sh->dest;
4457 #if IS_ENABLED(CONFIG_IPV6)
4459 /* Returns error only if unable to parse addresses */
4460 static int selinux_parse_skb_ipv6(struct sk_buff *skb,
4461 struct common_audit_data *ad, u8 *proto)
4464 int ret = -EINVAL, offset;
4465 struct ipv6hdr _ipv6h, *ip6;
4468 offset = skb_network_offset(skb);
4469 ip6 = skb_header_pointer(skb, offset, sizeof(_ipv6h), &_ipv6h);
4473 ad->u.net->v6info.saddr = ip6->saddr;
4474 ad->u.net->v6info.daddr = ip6->daddr;
4477 nexthdr = ip6->nexthdr;
4478 offset += sizeof(_ipv6h);
4479 offset = ipv6_skip_exthdr(skb, offset, &nexthdr, &frag_off);
4488 struct tcphdr _tcph, *th;
4490 th = skb_header_pointer(skb, offset, sizeof(_tcph), &_tcph);
4494 ad->u.net->sport = th->source;
4495 ad->u.net->dport = th->dest;
4500 struct udphdr _udph, *uh;
4502 uh = skb_header_pointer(skb, offset, sizeof(_udph), &_udph);
4506 ad->u.net->sport = uh->source;
4507 ad->u.net->dport = uh->dest;
4511 case IPPROTO_DCCP: {
4512 struct dccp_hdr _dccph, *dh;
4514 dh = skb_header_pointer(skb, offset, sizeof(_dccph), &_dccph);
4518 ad->u.net->sport = dh->dccph_sport;
4519 ad->u.net->dport = dh->dccph_dport;
4523 #if IS_ENABLED(CONFIG_IP_SCTP)
4524 case IPPROTO_SCTP: {
4525 struct sctphdr _sctph, *sh;
4527 sh = skb_header_pointer(skb, offset, sizeof(_sctph), &_sctph);
4531 ad->u.net->sport = sh->source;
4532 ad->u.net->dport = sh->dest;
4536 /* includes fragments */
4546 static int selinux_parse_skb(struct sk_buff *skb, struct common_audit_data *ad,
4547 char **_addrp, int src, u8 *proto)
4552 switch (ad->u.net->family) {
4554 ret = selinux_parse_skb_ipv4(skb, ad, proto);
4557 addrp = (char *)(src ? &ad->u.net->v4info.saddr :
4558 &ad->u.net->v4info.daddr);
4561 #if IS_ENABLED(CONFIG_IPV6)
4563 ret = selinux_parse_skb_ipv6(skb, ad, proto);
4566 addrp = (char *)(src ? &ad->u.net->v6info.saddr :
4567 &ad->u.net->v6info.daddr);
4577 "SELinux: failure in selinux_parse_skb(),"
4578 " unable to parse packet\n");
4588 * selinux_skb_peerlbl_sid - Determine the peer label of a packet
4590 * @family: protocol family
4591 * @sid: the packet's peer label SID
4594 * Check the various different forms of network peer labeling and determine
4595 * the peer label/SID for the packet; most of the magic actually occurs in
4596 * the security server function security_net_peersid_cmp(). The function
4597 * returns zero if the value in @sid is valid (although it may be SECSID_NULL)
4598 * or -EACCES if @sid is invalid due to inconsistencies with the different
4602 static int selinux_skb_peerlbl_sid(struct sk_buff *skb, u16 family, u32 *sid)
4609 err = selinux_xfrm_skb_sid(skb, &xfrm_sid);
4612 err = selinux_netlbl_skbuff_getsid(skb, family, &nlbl_type, &nlbl_sid);
4616 err = security_net_peersid_resolve(&selinux_state, nlbl_sid,
4617 nlbl_type, xfrm_sid, sid);
4618 if (unlikely(err)) {
4620 "SELinux: failure in selinux_skb_peerlbl_sid(),"
4621 " unable to determine packet's peer label\n");
4629 * selinux_conn_sid - Determine the child socket label for a connection
4630 * @sk_sid: the parent socket's SID
4631 * @skb_sid: the packet's SID
4632 * @conn_sid: the resulting connection SID
4634 * If @skb_sid is valid then the user:role:type information from @sk_sid is
4635 * combined with the MLS information from @skb_sid in order to create
4636 * @conn_sid. If @skb_sid is not valid then @conn_sid is simply a copy
4637 * of @sk_sid. Returns zero on success, negative values on failure.
4640 static int selinux_conn_sid(u32 sk_sid, u32 skb_sid, u32 *conn_sid)
4644 if (skb_sid != SECSID_NULL)
4645 err = security_sid_mls_copy(&selinux_state, sk_sid, skb_sid,
4653 /* socket security operations */
4655 static int socket_sockcreate_sid(const struct task_security_struct *tsec,
4656 u16 secclass, u32 *socksid)
4658 if (tsec->sockcreate_sid > SECSID_NULL) {
4659 *socksid = tsec->sockcreate_sid;
4663 return security_transition_sid(&selinux_state, tsec->sid, tsec->sid,
4664 secclass, NULL, socksid);
4667 static int sock_has_perm(struct sock *sk, u32 perms)
4669 struct sk_security_struct *sksec = sk->sk_security;
4670 struct common_audit_data ad;
4671 struct lsm_network_audit net = {0,};
4673 if (sksec->sid == SECINITSID_KERNEL)
4676 ad.type = LSM_AUDIT_DATA_NET;
4680 return avc_has_perm(&selinux_state,
4681 current_sid(), sksec->sid, sksec->sclass, perms,
4685 static int selinux_socket_create(int family, int type,
4686 int protocol, int kern)
4688 const struct task_security_struct *tsec = selinux_cred(current_cred());
4696 secclass = socket_type_to_security_class(family, type, protocol);
4697 rc = socket_sockcreate_sid(tsec, secclass, &newsid);
4701 return avc_has_perm(&selinux_state,
4702 tsec->sid, newsid, secclass, SOCKET__CREATE, NULL);
4705 static int selinux_socket_post_create(struct socket *sock, int family,
4706 int type, int protocol, int kern)
4708 const struct task_security_struct *tsec = selinux_cred(current_cred());
4709 struct inode_security_struct *isec = inode_security_novalidate(SOCK_INODE(sock));
4710 struct sk_security_struct *sksec;
4711 u16 sclass = socket_type_to_security_class(family, type, protocol);
4712 u32 sid = SECINITSID_KERNEL;
4716 err = socket_sockcreate_sid(tsec, sclass, &sid);
4721 isec->sclass = sclass;
4723 isec->initialized = LABEL_INITIALIZED;
4726 sksec = sock->sk->sk_security;
4727 sksec->sclass = sclass;
4729 /* Allows detection of the first association on this socket */
4730 if (sksec->sclass == SECCLASS_SCTP_SOCKET)
4731 sksec->sctp_assoc_state = SCTP_ASSOC_UNSET;
4733 err = selinux_netlbl_socket_post_create(sock->sk, family);
4739 static int selinux_socket_socketpair(struct socket *socka,
4740 struct socket *sockb)
4742 struct sk_security_struct *sksec_a = socka->sk->sk_security;
4743 struct sk_security_struct *sksec_b = sockb->sk->sk_security;
4745 sksec_a->peer_sid = sksec_b->sid;
4746 sksec_b->peer_sid = sksec_a->sid;
4751 /* Range of port numbers used to automatically bind.
4752 Need to determine whether we should perform a name_bind
4753 permission check between the socket and the port number. */
4755 static int selinux_socket_bind(struct socket *sock, struct sockaddr *address, int addrlen)
4757 struct sock *sk = sock->sk;
4758 struct sk_security_struct *sksec = sk->sk_security;
4762 err = sock_has_perm(sk, SOCKET__BIND);
4766 /* If PF_INET or PF_INET6, check name_bind permission for the port. */
4767 family = sk->sk_family;
4768 if (family == PF_INET || family == PF_INET6) {
4770 struct common_audit_data ad;
4771 struct lsm_network_audit net = {0,};
4772 struct sockaddr_in *addr4 = NULL;
4773 struct sockaddr_in6 *addr6 = NULL;
4775 unsigned short snum;
4779 * sctp_bindx(3) calls via selinux_sctp_bind_connect()
4780 * that validates multiple binding addresses. Because of this
4781 * need to check address->sa_family as it is possible to have
4782 * sk->sk_family = PF_INET6 with addr->sa_family = AF_INET.
4784 if (addrlen < offsetofend(struct sockaddr, sa_family))
4786 family_sa = address->sa_family;
4787 switch (family_sa) {
4790 if (addrlen < sizeof(struct sockaddr_in))
4792 addr4 = (struct sockaddr_in *)address;
4793 if (family_sa == AF_UNSPEC) {
4794 /* see __inet_bind(), we only want to allow
4795 * AF_UNSPEC if the address is INADDR_ANY
4797 if (addr4->sin_addr.s_addr != htonl(INADDR_ANY))
4799 family_sa = AF_INET;
4801 snum = ntohs(addr4->sin_port);
4802 addrp = (char *)&addr4->sin_addr.s_addr;
4805 if (addrlen < SIN6_LEN_RFC2133)
4807 addr6 = (struct sockaddr_in6 *)address;
4808 snum = ntohs(addr6->sin6_port);
4809 addrp = (char *)&addr6->sin6_addr.s6_addr;
4815 ad.type = LSM_AUDIT_DATA_NET;
4817 ad.u.net->sport = htons(snum);
4818 ad.u.net->family = family_sa;
4823 inet_get_local_port_range(sock_net(sk), &low, &high);
4825 if (inet_port_requires_bind_service(sock_net(sk), snum) ||
4826 snum < low || snum > high) {
4827 err = sel_netport_sid(sk->sk_protocol,
4831 err = avc_has_perm(&selinux_state,
4834 SOCKET__NAME_BIND, &ad);
4840 switch (sksec->sclass) {
4841 case SECCLASS_TCP_SOCKET:
4842 node_perm = TCP_SOCKET__NODE_BIND;
4845 case SECCLASS_UDP_SOCKET:
4846 node_perm = UDP_SOCKET__NODE_BIND;
4849 case SECCLASS_DCCP_SOCKET:
4850 node_perm = DCCP_SOCKET__NODE_BIND;
4853 case SECCLASS_SCTP_SOCKET:
4854 node_perm = SCTP_SOCKET__NODE_BIND;
4858 node_perm = RAWIP_SOCKET__NODE_BIND;
4862 err = sel_netnode_sid(addrp, family_sa, &sid);
4866 if (family_sa == AF_INET)
4867 ad.u.net->v4info.saddr = addr4->sin_addr.s_addr;
4869 ad.u.net->v6info.saddr = addr6->sin6_addr;
4871 err = avc_has_perm(&selinux_state,
4873 sksec->sclass, node_perm, &ad);
4880 /* Note that SCTP services expect -EINVAL, others -EAFNOSUPPORT. */
4881 if (sksec->sclass == SECCLASS_SCTP_SOCKET)
4883 return -EAFNOSUPPORT;
4886 /* This supports connect(2) and SCTP connect services such as sctp_connectx(3)
4887 * and sctp_sendmsg(3) as described in Documentation/security/SCTP.rst
4889 static int selinux_socket_connect_helper(struct socket *sock,
4890 struct sockaddr *address, int addrlen)
4892 struct sock *sk = sock->sk;
4893 struct sk_security_struct *sksec = sk->sk_security;
4896 err = sock_has_perm(sk, SOCKET__CONNECT);
4899 if (addrlen < offsetofend(struct sockaddr, sa_family))
4902 /* connect(AF_UNSPEC) has special handling, as it is a documented
4903 * way to disconnect the socket
4905 if (address->sa_family == AF_UNSPEC)
4909 * If a TCP, DCCP or SCTP socket, check name_connect permission
4912 if (sksec->sclass == SECCLASS_TCP_SOCKET ||
4913 sksec->sclass == SECCLASS_DCCP_SOCKET ||
4914 sksec->sclass == SECCLASS_SCTP_SOCKET) {
4915 struct common_audit_data ad;
4916 struct lsm_network_audit net = {0,};
4917 struct sockaddr_in *addr4 = NULL;
4918 struct sockaddr_in6 *addr6 = NULL;
4919 unsigned short snum;
4922 /* sctp_connectx(3) calls via selinux_sctp_bind_connect()
4923 * that validates multiple connect addresses. Because of this
4924 * need to check address->sa_family as it is possible to have
4925 * sk->sk_family = PF_INET6 with addr->sa_family = AF_INET.
4927 switch (address->sa_family) {
4929 addr4 = (struct sockaddr_in *)address;
4930 if (addrlen < sizeof(struct sockaddr_in))
4932 snum = ntohs(addr4->sin_port);
4935 addr6 = (struct sockaddr_in6 *)address;
4936 if (addrlen < SIN6_LEN_RFC2133)
4938 snum = ntohs(addr6->sin6_port);
4941 /* Note that SCTP services expect -EINVAL, whereas
4942 * others expect -EAFNOSUPPORT.
4944 if (sksec->sclass == SECCLASS_SCTP_SOCKET)
4947 return -EAFNOSUPPORT;
4950 err = sel_netport_sid(sk->sk_protocol, snum, &sid);
4954 switch (sksec->sclass) {
4955 case SECCLASS_TCP_SOCKET:
4956 perm = TCP_SOCKET__NAME_CONNECT;
4958 case SECCLASS_DCCP_SOCKET:
4959 perm = DCCP_SOCKET__NAME_CONNECT;
4961 case SECCLASS_SCTP_SOCKET:
4962 perm = SCTP_SOCKET__NAME_CONNECT;
4966 ad.type = LSM_AUDIT_DATA_NET;
4968 ad.u.net->dport = htons(snum);
4969 ad.u.net->family = address->sa_family;
4970 err = avc_has_perm(&selinux_state,
4971 sksec->sid, sid, sksec->sclass, perm, &ad);
4979 /* Supports connect(2), see comments in selinux_socket_connect_helper() */
4980 static int selinux_socket_connect(struct socket *sock,
4981 struct sockaddr *address, int addrlen)
4984 struct sock *sk = sock->sk;
4986 err = selinux_socket_connect_helper(sock, address, addrlen);
4990 return selinux_netlbl_socket_connect(sk, address);
4993 static int selinux_socket_listen(struct socket *sock, int backlog)
4995 return sock_has_perm(sock->sk, SOCKET__LISTEN);
4998 static int selinux_socket_accept(struct socket *sock, struct socket *newsock)
5001 struct inode_security_struct *isec;
5002 struct inode_security_struct *newisec;
5006 err = sock_has_perm(sock->sk, SOCKET__ACCEPT);
5010 isec = inode_security_novalidate(SOCK_INODE(sock));
5011 spin_lock(&isec->lock);
5012 sclass = isec->sclass;
5014 spin_unlock(&isec->lock);
5016 newisec = inode_security_novalidate(SOCK_INODE(newsock));
5017 newisec->sclass = sclass;
5019 newisec->initialized = LABEL_INITIALIZED;
5024 static int selinux_socket_sendmsg(struct socket *sock, struct msghdr *msg,
5027 return sock_has_perm(sock->sk, SOCKET__WRITE);
5030 static int selinux_socket_recvmsg(struct socket *sock, struct msghdr *msg,
5031 int size, int flags)
5033 return sock_has_perm(sock->sk, SOCKET__READ);
5036 static int selinux_socket_getsockname(struct socket *sock)
5038 return sock_has_perm(sock->sk, SOCKET__GETATTR);
5041 static int selinux_socket_getpeername(struct socket *sock)
5043 return sock_has_perm(sock->sk, SOCKET__GETATTR);
5046 static int selinux_socket_setsockopt(struct socket *sock, int level, int optname)
5050 err = sock_has_perm(sock->sk, SOCKET__SETOPT);
5054 return selinux_netlbl_socket_setsockopt(sock, level, optname);
5057 static int selinux_socket_getsockopt(struct socket *sock, int level,
5060 return sock_has_perm(sock->sk, SOCKET__GETOPT);
5063 static int selinux_socket_shutdown(struct socket *sock, int how)
5065 return sock_has_perm(sock->sk, SOCKET__SHUTDOWN);
5068 static int selinux_socket_unix_stream_connect(struct sock *sock,
5072 struct sk_security_struct *sksec_sock = sock->sk_security;
5073 struct sk_security_struct *sksec_other = other->sk_security;
5074 struct sk_security_struct *sksec_new = newsk->sk_security;
5075 struct common_audit_data ad;
5076 struct lsm_network_audit net = {0,};
5079 ad.type = LSM_AUDIT_DATA_NET;
5081 ad.u.net->sk = other;
5083 err = avc_has_perm(&selinux_state,
5084 sksec_sock->sid, sksec_other->sid,
5085 sksec_other->sclass,
5086 UNIX_STREAM_SOCKET__CONNECTTO, &ad);
5090 /* server child socket */
5091 sksec_new->peer_sid = sksec_sock->sid;
5092 err = security_sid_mls_copy(&selinux_state, sksec_other->sid,
5093 sksec_sock->sid, &sksec_new->sid);
5097 /* connecting socket */
5098 sksec_sock->peer_sid = sksec_new->sid;
5103 static int selinux_socket_unix_may_send(struct socket *sock,
5104 struct socket *other)
5106 struct sk_security_struct *ssec = sock->sk->sk_security;
5107 struct sk_security_struct *osec = other->sk->sk_security;
5108 struct common_audit_data ad;
5109 struct lsm_network_audit net = {0,};
5111 ad.type = LSM_AUDIT_DATA_NET;
5113 ad.u.net->sk = other->sk;
5115 return avc_has_perm(&selinux_state,
5116 ssec->sid, osec->sid, osec->sclass, SOCKET__SENDTO,
5120 static int selinux_inet_sys_rcv_skb(struct net *ns, int ifindex,
5121 char *addrp, u16 family, u32 peer_sid,
5122 struct common_audit_data *ad)
5128 err = sel_netif_sid(ns, ifindex, &if_sid);
5131 err = avc_has_perm(&selinux_state,
5133 SECCLASS_NETIF, NETIF__INGRESS, ad);
5137 err = sel_netnode_sid(addrp, family, &node_sid);
5140 return avc_has_perm(&selinux_state,
5142 SECCLASS_NODE, NODE__RECVFROM, ad);
5145 static int selinux_sock_rcv_skb_compat(struct sock *sk, struct sk_buff *skb,
5149 struct sk_security_struct *sksec = sk->sk_security;
5150 u32 sk_sid = sksec->sid;
5151 struct common_audit_data ad;
5152 struct lsm_network_audit net = {0,};
5155 ad.type = LSM_AUDIT_DATA_NET;
5157 ad.u.net->netif = skb->skb_iif;
5158 ad.u.net->family = family;
5159 err = selinux_parse_skb(skb, &ad, &addrp, 1, NULL);
5163 if (selinux_secmark_enabled()) {
5164 err = avc_has_perm(&selinux_state,
5165 sk_sid, skb->secmark, SECCLASS_PACKET,
5171 err = selinux_netlbl_sock_rcv_skb(sksec, skb, family, &ad);
5174 err = selinux_xfrm_sock_rcv_skb(sksec->sid, skb, &ad);
5179 static int selinux_socket_sock_rcv_skb(struct sock *sk, struct sk_buff *skb)
5182 struct sk_security_struct *sksec = sk->sk_security;
5183 u16 family = sk->sk_family;
5184 u32 sk_sid = sksec->sid;
5185 struct common_audit_data ad;
5186 struct lsm_network_audit net = {0,};
5191 if (family != PF_INET && family != PF_INET6)
5194 /* Handle mapped IPv4 packets arriving via IPv6 sockets */
5195 if (family == PF_INET6 && skb->protocol == htons(ETH_P_IP))
5198 /* If any sort of compatibility mode is enabled then handoff processing
5199 * to the selinux_sock_rcv_skb_compat() function to deal with the
5200 * special handling. We do this in an attempt to keep this function
5201 * as fast and as clean as possible. */
5202 if (!selinux_policycap_netpeer())
5203 return selinux_sock_rcv_skb_compat(sk, skb, family);
5205 secmark_active = selinux_secmark_enabled();
5206 peerlbl_active = selinux_peerlbl_enabled();
5207 if (!secmark_active && !peerlbl_active)
5210 ad.type = LSM_AUDIT_DATA_NET;
5212 ad.u.net->netif = skb->skb_iif;
5213 ad.u.net->family = family;
5214 err = selinux_parse_skb(skb, &ad, &addrp, 1, NULL);
5218 if (peerlbl_active) {
5221 err = selinux_skb_peerlbl_sid(skb, family, &peer_sid);
5224 err = selinux_inet_sys_rcv_skb(sock_net(sk), skb->skb_iif,
5225 addrp, family, peer_sid, &ad);
5227 selinux_netlbl_err(skb, family, err, 0);
5230 err = avc_has_perm(&selinux_state,
5231 sk_sid, peer_sid, SECCLASS_PEER,
5234 selinux_netlbl_err(skb, family, err, 0);
5239 if (secmark_active) {
5240 err = avc_has_perm(&selinux_state,
5241 sk_sid, skb->secmark, SECCLASS_PACKET,
5250 static int selinux_socket_getpeersec_stream(struct socket *sock, char __user *optval,
5251 int __user *optlen, unsigned len)
5256 struct sk_security_struct *sksec = sock->sk->sk_security;
5257 u32 peer_sid = SECSID_NULL;
5259 if (sksec->sclass == SECCLASS_UNIX_STREAM_SOCKET ||
5260 sksec->sclass == SECCLASS_TCP_SOCKET ||
5261 sksec->sclass == SECCLASS_SCTP_SOCKET)
5262 peer_sid = sksec->peer_sid;
5263 if (peer_sid == SECSID_NULL)
5264 return -ENOPROTOOPT;
5266 err = security_sid_to_context(&selinux_state, peer_sid, &scontext,
5271 if (scontext_len > len) {
5276 if (copy_to_user(optval, scontext, scontext_len))
5280 if (put_user(scontext_len, optlen))
5286 static int selinux_socket_getpeersec_dgram(struct socket *sock, struct sk_buff *skb, u32 *secid)
5288 u32 peer_secid = SECSID_NULL;
5290 struct inode_security_struct *isec;
5292 if (skb && skb->protocol == htons(ETH_P_IP))
5294 else if (skb && skb->protocol == htons(ETH_P_IPV6))
5297 family = sock->sk->sk_family;
5301 if (sock && family == PF_UNIX) {
5302 isec = inode_security_novalidate(SOCK_INODE(sock));
5303 peer_secid = isec->sid;
5305 selinux_skb_peerlbl_sid(skb, family, &peer_secid);
5308 *secid = peer_secid;
5309 if (peer_secid == SECSID_NULL)
5314 static int selinux_sk_alloc_security(struct sock *sk, int family, gfp_t priority)
5316 struct sk_security_struct *sksec;
5318 sksec = kzalloc(sizeof(*sksec), priority);
5322 sksec->peer_sid = SECINITSID_UNLABELED;
5323 sksec->sid = SECINITSID_UNLABELED;
5324 sksec->sclass = SECCLASS_SOCKET;
5325 selinux_netlbl_sk_security_reset(sksec);
5326 sk->sk_security = sksec;
5331 static void selinux_sk_free_security(struct sock *sk)
5333 struct sk_security_struct *sksec = sk->sk_security;
5335 sk->sk_security = NULL;
5336 selinux_netlbl_sk_security_free(sksec);
5340 static void selinux_sk_clone_security(const struct sock *sk, struct sock *newsk)
5342 struct sk_security_struct *sksec = sk->sk_security;
5343 struct sk_security_struct *newsksec = newsk->sk_security;
5345 newsksec->sid = sksec->sid;
5346 newsksec->peer_sid = sksec->peer_sid;
5347 newsksec->sclass = sksec->sclass;
5349 selinux_netlbl_sk_security_reset(newsksec);
5352 static void selinux_sk_getsecid(struct sock *sk, u32 *secid)
5355 *secid = SECINITSID_ANY_SOCKET;
5357 struct sk_security_struct *sksec = sk->sk_security;
5359 *secid = sksec->sid;
5363 static void selinux_sock_graft(struct sock *sk, struct socket *parent)
5365 struct inode_security_struct *isec =
5366 inode_security_novalidate(SOCK_INODE(parent));
5367 struct sk_security_struct *sksec = sk->sk_security;
5369 if (sk->sk_family == PF_INET || sk->sk_family == PF_INET6 ||
5370 sk->sk_family == PF_UNIX)
5371 isec->sid = sksec->sid;
5372 sksec->sclass = isec->sclass;
5375 /* Called whenever SCTP receives an INIT chunk. This happens when an incoming
5376 * connect(2), sctp_connectx(3) or sctp_sendmsg(3) (with no association
5379 static int selinux_sctp_assoc_request(struct sctp_endpoint *ep,
5380 struct sk_buff *skb)
5382 struct sk_security_struct *sksec = ep->base.sk->sk_security;
5383 struct common_audit_data ad;
5384 struct lsm_network_audit net = {0,};
5386 u32 peer_sid = SECINITSID_UNLABELED;
5390 if (!selinux_policycap_extsockclass())
5393 peerlbl_active = selinux_peerlbl_enabled();
5395 if (peerlbl_active) {
5396 /* This will return peer_sid = SECSID_NULL if there are
5397 * no peer labels, see security_net_peersid_resolve().
5399 err = selinux_skb_peerlbl_sid(skb, ep->base.sk->sk_family,
5404 if (peer_sid == SECSID_NULL)
5405 peer_sid = SECINITSID_UNLABELED;
5408 if (sksec->sctp_assoc_state == SCTP_ASSOC_UNSET) {
5409 sksec->sctp_assoc_state = SCTP_ASSOC_SET;
5411 /* Here as first association on socket. As the peer SID
5412 * was allowed by peer recv (and the netif/node checks),
5413 * then it is approved by policy and used as the primary
5414 * peer SID for getpeercon(3).
5416 sksec->peer_sid = peer_sid;
5417 } else if (sksec->peer_sid != peer_sid) {
5418 /* Other association peer SIDs are checked to enforce
5419 * consistency among the peer SIDs.
5421 ad.type = LSM_AUDIT_DATA_NET;
5423 ad.u.net->sk = ep->base.sk;
5424 err = avc_has_perm(&selinux_state,
5425 sksec->peer_sid, peer_sid, sksec->sclass,
5426 SCTP_SOCKET__ASSOCIATION, &ad);
5431 /* Compute the MLS component for the connection and store
5432 * the information in ep. This will be used by SCTP TCP type
5433 * sockets and peeled off connections as they cause a new
5434 * socket to be generated. selinux_sctp_sk_clone() will then
5435 * plug this into the new socket.
5437 err = selinux_conn_sid(sksec->sid, peer_sid, &conn_sid);
5441 ep->secid = conn_sid;
5442 ep->peer_secid = peer_sid;
5444 /* Set any NetLabel labels including CIPSO/CALIPSO options. */
5445 return selinux_netlbl_sctp_assoc_request(ep, skb);
5448 /* Check if sctp IPv4/IPv6 addresses are valid for binding or connecting
5449 * based on their @optname.
5451 static int selinux_sctp_bind_connect(struct sock *sk, int optname,
5452 struct sockaddr *address,
5455 int len, err = 0, walk_size = 0;
5457 struct sockaddr *addr;
5458 struct socket *sock;
5460 if (!selinux_policycap_extsockclass())
5463 /* Process one or more addresses that may be IPv4 or IPv6 */
5464 sock = sk->sk_socket;
5467 while (walk_size < addrlen) {
5468 if (walk_size + sizeof(sa_family_t) > addrlen)
5472 switch (addr->sa_family) {
5475 len = sizeof(struct sockaddr_in);
5478 len = sizeof(struct sockaddr_in6);
5484 if (walk_size + len > addrlen)
5490 case SCTP_PRIMARY_ADDR:
5491 case SCTP_SET_PEER_PRIMARY_ADDR:
5492 case SCTP_SOCKOPT_BINDX_ADD:
5493 err = selinux_socket_bind(sock, addr, len);
5495 /* Connect checks */
5496 case SCTP_SOCKOPT_CONNECTX:
5497 case SCTP_PARAM_SET_PRIMARY:
5498 case SCTP_PARAM_ADD_IP:
5499 case SCTP_SENDMSG_CONNECT:
5500 err = selinux_socket_connect_helper(sock, addr, len);
5504 /* As selinux_sctp_bind_connect() is called by the
5505 * SCTP protocol layer, the socket is already locked,
5506 * therefore selinux_netlbl_socket_connect_locked()
5507 * is called here. The situations handled are:
5508 * sctp_connectx(3), sctp_sendmsg(3), sendmsg(2),
5509 * whenever a new IP address is added or when a new
5510 * primary address is selected.
5511 * Note that an SCTP connect(2) call happens before
5512 * the SCTP protocol layer and is handled via
5513 * selinux_socket_connect().
5515 err = selinux_netlbl_socket_connect_locked(sk, addr);
5529 /* Called whenever a new socket is created by accept(2) or sctp_peeloff(3). */
5530 static void selinux_sctp_sk_clone(struct sctp_endpoint *ep, struct sock *sk,
5533 struct sk_security_struct *sksec = sk->sk_security;
5534 struct sk_security_struct *newsksec = newsk->sk_security;
5536 /* If policy does not support SECCLASS_SCTP_SOCKET then call
5537 * the non-sctp clone version.
5539 if (!selinux_policycap_extsockclass())
5540 return selinux_sk_clone_security(sk, newsk);
5542 newsksec->sid = ep->secid;
5543 newsksec->peer_sid = ep->peer_secid;
5544 newsksec->sclass = sksec->sclass;
5545 selinux_netlbl_sctp_sk_clone(sk, newsk);
5548 static int selinux_inet_conn_request(const struct sock *sk, struct sk_buff *skb,
5549 struct request_sock *req)
5551 struct sk_security_struct *sksec = sk->sk_security;
5553 u16 family = req->rsk_ops->family;
5557 err = selinux_skb_peerlbl_sid(skb, family, &peersid);
5560 err = selinux_conn_sid(sksec->sid, peersid, &connsid);
5563 req->secid = connsid;
5564 req->peer_secid = peersid;
5566 return selinux_netlbl_inet_conn_request(req, family);
5569 static void selinux_inet_csk_clone(struct sock *newsk,
5570 const struct request_sock *req)
5572 struct sk_security_struct *newsksec = newsk->sk_security;
5574 newsksec->sid = req->secid;
5575 newsksec->peer_sid = req->peer_secid;
5576 /* NOTE: Ideally, we should also get the isec->sid for the
5577 new socket in sync, but we don't have the isec available yet.
5578 So we will wait until sock_graft to do it, by which
5579 time it will have been created and available. */
5581 /* We don't need to take any sort of lock here as we are the only
5582 * thread with access to newsksec */
5583 selinux_netlbl_inet_csk_clone(newsk, req->rsk_ops->family);
5586 static void selinux_inet_conn_established(struct sock *sk, struct sk_buff *skb)
5588 u16 family = sk->sk_family;
5589 struct sk_security_struct *sksec = sk->sk_security;
5591 /* handle mapped IPv4 packets arriving via IPv6 sockets */
5592 if (family == PF_INET6 && skb->protocol == htons(ETH_P_IP))
5595 selinux_skb_peerlbl_sid(skb, family, &sksec->peer_sid);
5598 static int selinux_secmark_relabel_packet(u32 sid)
5600 const struct task_security_struct *__tsec;
5603 __tsec = selinux_cred(current_cred());
5606 return avc_has_perm(&selinux_state,
5607 tsid, sid, SECCLASS_PACKET, PACKET__RELABELTO,
5611 static void selinux_secmark_refcount_inc(void)
5613 atomic_inc(&selinux_secmark_refcount);
5616 static void selinux_secmark_refcount_dec(void)
5618 atomic_dec(&selinux_secmark_refcount);
5621 static void selinux_req_classify_flow(const struct request_sock *req,
5622 struct flowi_common *flic)
5624 flic->flowic_secid = req->secid;
5627 static int selinux_tun_dev_alloc_security(void **security)
5629 struct tun_security_struct *tunsec;
5631 tunsec = kzalloc(sizeof(*tunsec), GFP_KERNEL);
5634 tunsec->sid = current_sid();
5640 static void selinux_tun_dev_free_security(void *security)
5645 static int selinux_tun_dev_create(void)
5647 u32 sid = current_sid();
5649 /* we aren't taking into account the "sockcreate" SID since the socket
5650 * that is being created here is not a socket in the traditional sense,
5651 * instead it is a private sock, accessible only to the kernel, and
5652 * representing a wide range of network traffic spanning multiple
5653 * connections unlike traditional sockets - check the TUN driver to
5654 * get a better understanding of why this socket is special */
5656 return avc_has_perm(&selinux_state,
5657 sid, sid, SECCLASS_TUN_SOCKET, TUN_SOCKET__CREATE,
5661 static int selinux_tun_dev_attach_queue(void *security)
5663 struct tun_security_struct *tunsec = security;
5665 return avc_has_perm(&selinux_state,
5666 current_sid(), tunsec->sid, SECCLASS_TUN_SOCKET,
5667 TUN_SOCKET__ATTACH_QUEUE, NULL);
5670 static int selinux_tun_dev_attach(struct sock *sk, void *security)
5672 struct tun_security_struct *tunsec = security;
5673 struct sk_security_struct *sksec = sk->sk_security;
5675 /* we don't currently perform any NetLabel based labeling here and it
5676 * isn't clear that we would want to do so anyway; while we could apply
5677 * labeling without the support of the TUN user the resulting labeled
5678 * traffic from the other end of the connection would almost certainly
5679 * cause confusion to the TUN user that had no idea network labeling
5680 * protocols were being used */
5682 sksec->sid = tunsec->sid;
5683 sksec->sclass = SECCLASS_TUN_SOCKET;
5688 static int selinux_tun_dev_open(void *security)
5690 struct tun_security_struct *tunsec = security;
5691 u32 sid = current_sid();
5694 err = avc_has_perm(&selinux_state,
5695 sid, tunsec->sid, SECCLASS_TUN_SOCKET,
5696 TUN_SOCKET__RELABELFROM, NULL);
5699 err = avc_has_perm(&selinux_state,
5700 sid, sid, SECCLASS_TUN_SOCKET,
5701 TUN_SOCKET__RELABELTO, NULL);
5709 #ifdef CONFIG_NETFILTER
5711 static unsigned int selinux_ip_forward(struct sk_buff *skb,
5712 const struct net_device *indev,
5718 struct common_audit_data ad;
5719 struct lsm_network_audit net = {0,};
5724 if (!selinux_policycap_netpeer())
5727 secmark_active = selinux_secmark_enabled();
5728 netlbl_active = netlbl_enabled();
5729 peerlbl_active = selinux_peerlbl_enabled();
5730 if (!secmark_active && !peerlbl_active)
5733 if (selinux_skb_peerlbl_sid(skb, family, &peer_sid) != 0)
5736 ad.type = LSM_AUDIT_DATA_NET;
5738 ad.u.net->netif = indev->ifindex;
5739 ad.u.net->family = family;
5740 if (selinux_parse_skb(skb, &ad, &addrp, 1, NULL) != 0)
5743 if (peerlbl_active) {
5744 err = selinux_inet_sys_rcv_skb(dev_net(indev), indev->ifindex,
5745 addrp, family, peer_sid, &ad);
5747 selinux_netlbl_err(skb, family, err, 1);
5753 if (avc_has_perm(&selinux_state,
5754 peer_sid, skb->secmark,
5755 SECCLASS_PACKET, PACKET__FORWARD_IN, &ad))
5759 /* we do this in the FORWARD path and not the POST_ROUTING
5760 * path because we want to make sure we apply the necessary
5761 * labeling before IPsec is applied so we can leverage AH
5763 if (selinux_netlbl_skbuff_setsid(skb, family, peer_sid) != 0)
5769 static unsigned int selinux_ipv4_forward(void *priv,
5770 struct sk_buff *skb,
5771 const struct nf_hook_state *state)
5773 return selinux_ip_forward(skb, state->in, PF_INET);
5776 #if IS_ENABLED(CONFIG_IPV6)
5777 static unsigned int selinux_ipv6_forward(void *priv,
5778 struct sk_buff *skb,
5779 const struct nf_hook_state *state)
5781 return selinux_ip_forward(skb, state->in, PF_INET6);
5785 static unsigned int selinux_ip_output(struct sk_buff *skb,
5791 if (!netlbl_enabled())
5794 /* we do this in the LOCAL_OUT path and not the POST_ROUTING path
5795 * because we want to make sure we apply the necessary labeling
5796 * before IPsec is applied so we can leverage AH protection */
5799 struct sk_security_struct *sksec;
5801 if (sk_listener(sk))
5802 /* if the socket is the listening state then this
5803 * packet is a SYN-ACK packet which means it needs to
5804 * be labeled based on the connection/request_sock and
5805 * not the parent socket. unfortunately, we can't
5806 * lookup the request_sock yet as it isn't queued on
5807 * the parent socket until after the SYN-ACK is sent.
5808 * the "solution" is to simply pass the packet as-is
5809 * as any IP option based labeling should be copied
5810 * from the initial connection request (in the IP
5811 * layer). it is far from ideal, but until we get a
5812 * security label in the packet itself this is the
5813 * best we can do. */
5816 /* standard practice, label using the parent socket */
5817 sksec = sk->sk_security;
5820 sid = SECINITSID_KERNEL;
5821 if (selinux_netlbl_skbuff_setsid(skb, family, sid) != 0)
5827 static unsigned int selinux_ipv4_output(void *priv,
5828 struct sk_buff *skb,
5829 const struct nf_hook_state *state)
5831 return selinux_ip_output(skb, PF_INET);
5834 #if IS_ENABLED(CONFIG_IPV6)
5835 static unsigned int selinux_ipv6_output(void *priv,
5836 struct sk_buff *skb,
5837 const struct nf_hook_state *state)
5839 return selinux_ip_output(skb, PF_INET6);
5843 static unsigned int selinux_ip_postroute_compat(struct sk_buff *skb,
5847 struct sock *sk = skb_to_full_sk(skb);
5848 struct sk_security_struct *sksec;
5849 struct common_audit_data ad;
5850 struct lsm_network_audit net = {0,};
5856 sksec = sk->sk_security;
5858 ad.type = LSM_AUDIT_DATA_NET;
5860 ad.u.net->netif = ifindex;
5861 ad.u.net->family = family;
5862 if (selinux_parse_skb(skb, &ad, &addrp, 0, &proto))
5865 if (selinux_secmark_enabled())
5866 if (avc_has_perm(&selinux_state,
5867 sksec->sid, skb->secmark,
5868 SECCLASS_PACKET, PACKET__SEND, &ad))
5869 return NF_DROP_ERR(-ECONNREFUSED);
5871 if (selinux_xfrm_postroute_last(sksec->sid, skb, &ad, proto))
5872 return NF_DROP_ERR(-ECONNREFUSED);
5877 static unsigned int selinux_ip_postroute(struct sk_buff *skb,
5878 const struct net_device *outdev,
5883 int ifindex = outdev->ifindex;
5885 struct common_audit_data ad;
5886 struct lsm_network_audit net = {0,};
5891 /* If any sort of compatibility mode is enabled then handoff processing
5892 * to the selinux_ip_postroute_compat() function to deal with the
5893 * special handling. We do this in an attempt to keep this function
5894 * as fast and as clean as possible. */
5895 if (!selinux_policycap_netpeer())
5896 return selinux_ip_postroute_compat(skb, ifindex, family);
5898 secmark_active = selinux_secmark_enabled();
5899 peerlbl_active = selinux_peerlbl_enabled();
5900 if (!secmark_active && !peerlbl_active)
5903 sk = skb_to_full_sk(skb);
5906 /* If skb->dst->xfrm is non-NULL then the packet is undergoing an IPsec
5907 * packet transformation so allow the packet to pass without any checks
5908 * since we'll have another chance to perform access control checks
5909 * when the packet is on it's final way out.
5910 * NOTE: there appear to be some IPv6 multicast cases where skb->dst
5911 * is NULL, in this case go ahead and apply access control.
5912 * NOTE: if this is a local socket (skb->sk != NULL) that is in the
5913 * TCP listening state we cannot wait until the XFRM processing
5914 * is done as we will miss out on the SA label if we do;
5915 * unfortunately, this means more work, but it is only once per
5917 if (skb_dst(skb) != NULL && skb_dst(skb)->xfrm != NULL &&
5918 !(sk && sk_listener(sk)))
5923 /* Without an associated socket the packet is either coming
5924 * from the kernel or it is being forwarded; check the packet
5925 * to determine which and if the packet is being forwarded
5926 * query the packet directly to determine the security label. */
5928 secmark_perm = PACKET__FORWARD_OUT;
5929 if (selinux_skb_peerlbl_sid(skb, family, &peer_sid))
5932 secmark_perm = PACKET__SEND;
5933 peer_sid = SECINITSID_KERNEL;
5935 } else if (sk_listener(sk)) {
5936 /* Locally generated packet but the associated socket is in the
5937 * listening state which means this is a SYN-ACK packet. In
5938 * this particular case the correct security label is assigned
5939 * to the connection/request_sock but unfortunately we can't
5940 * query the request_sock as it isn't queued on the parent
5941 * socket until after the SYN-ACK packet is sent; the only
5942 * viable choice is to regenerate the label like we do in
5943 * selinux_inet_conn_request(). See also selinux_ip_output()
5944 * for similar problems. */
5946 struct sk_security_struct *sksec;
5948 sksec = sk->sk_security;
5949 if (selinux_skb_peerlbl_sid(skb, family, &skb_sid))
5951 /* At this point, if the returned skb peerlbl is SECSID_NULL
5952 * and the packet has been through at least one XFRM
5953 * transformation then we must be dealing with the "final"
5954 * form of labeled IPsec packet; since we've already applied
5955 * all of our access controls on this packet we can safely
5956 * pass the packet. */
5957 if (skb_sid == SECSID_NULL) {
5960 if (IPCB(skb)->flags & IPSKB_XFRM_TRANSFORMED)
5964 if (IP6CB(skb)->flags & IP6SKB_XFRM_TRANSFORMED)
5968 return NF_DROP_ERR(-ECONNREFUSED);
5971 if (selinux_conn_sid(sksec->sid, skb_sid, &peer_sid))
5973 secmark_perm = PACKET__SEND;
5975 /* Locally generated packet, fetch the security label from the
5976 * associated socket. */
5977 struct sk_security_struct *sksec = sk->sk_security;
5978 peer_sid = sksec->sid;
5979 secmark_perm = PACKET__SEND;
5982 ad.type = LSM_AUDIT_DATA_NET;
5984 ad.u.net->netif = ifindex;
5985 ad.u.net->family = family;
5986 if (selinux_parse_skb(skb, &ad, &addrp, 0, NULL))
5990 if (avc_has_perm(&selinux_state,
5991 peer_sid, skb->secmark,
5992 SECCLASS_PACKET, secmark_perm, &ad))
5993 return NF_DROP_ERR(-ECONNREFUSED);
5995 if (peerlbl_active) {
5999 if (sel_netif_sid(dev_net(outdev), ifindex, &if_sid))
6001 if (avc_has_perm(&selinux_state,
6003 SECCLASS_NETIF, NETIF__EGRESS, &ad))
6004 return NF_DROP_ERR(-ECONNREFUSED);
6006 if (sel_netnode_sid(addrp, family, &node_sid))
6008 if (avc_has_perm(&selinux_state,
6010 SECCLASS_NODE, NODE__SENDTO, &ad))
6011 return NF_DROP_ERR(-ECONNREFUSED);
6017 static unsigned int selinux_ipv4_postroute(void *priv,
6018 struct sk_buff *skb,
6019 const struct nf_hook_state *state)
6021 return selinux_ip_postroute(skb, state->out, PF_INET);
6024 #if IS_ENABLED(CONFIG_IPV6)
6025 static unsigned int selinux_ipv6_postroute(void *priv,
6026 struct sk_buff *skb,
6027 const struct nf_hook_state *state)
6029 return selinux_ip_postroute(skb, state->out, PF_INET6);
6033 #endif /* CONFIG_NETFILTER */
6035 static int selinux_netlink_send(struct sock *sk, struct sk_buff *skb)
6038 unsigned int msg_len;
6039 unsigned int data_len = skb->len;
6040 unsigned char *data = skb->data;
6041 struct nlmsghdr *nlh;
6042 struct sk_security_struct *sksec = sk->sk_security;
6043 u16 sclass = sksec->sclass;
6046 while (data_len >= nlmsg_total_size(0)) {
6047 nlh = (struct nlmsghdr *)data;
6049 /* NOTE: the nlmsg_len field isn't reliably set by some netlink
6050 * users which means we can't reject skb's with bogus
6051 * length fields; our solution is to follow what
6052 * netlink_rcv_skb() does and simply skip processing at
6053 * messages with length fields that are clearly junk
6055 if (nlh->nlmsg_len < NLMSG_HDRLEN || nlh->nlmsg_len > data_len)
6058 rc = selinux_nlmsg_lookup(sclass, nlh->nlmsg_type, &perm);
6060 rc = sock_has_perm(sk, perm);
6063 } else if (rc == -EINVAL) {
6064 /* -EINVAL is a missing msg/perm mapping */
6065 pr_warn_ratelimited("SELinux: unrecognized netlink"
6066 " message: protocol=%hu nlmsg_type=%hu sclass=%s"
6067 " pid=%d comm=%s\n",
6068 sk->sk_protocol, nlh->nlmsg_type,
6069 secclass_map[sclass - 1].name,
6070 task_pid_nr(current), current->comm);
6071 if (enforcing_enabled(&selinux_state) &&
6072 !security_get_allow_unknown(&selinux_state))
6075 } else if (rc == -ENOENT) {
6076 /* -ENOENT is a missing socket/class mapping, ignore */
6082 /* move to the next message after applying netlink padding */
6083 msg_len = NLMSG_ALIGN(nlh->nlmsg_len);
6084 if (msg_len >= data_len)
6086 data_len -= msg_len;
6093 static void ipc_init_security(struct ipc_security_struct *isec, u16 sclass)
6095 isec->sclass = sclass;
6096 isec->sid = current_sid();
6099 static int ipc_has_perm(struct kern_ipc_perm *ipc_perms,
6102 struct ipc_security_struct *isec;
6103 struct common_audit_data ad;
6104 u32 sid = current_sid();
6106 isec = selinux_ipc(ipc_perms);
6108 ad.type = LSM_AUDIT_DATA_IPC;
6109 ad.u.ipc_id = ipc_perms->key;
6111 return avc_has_perm(&selinux_state,
6112 sid, isec->sid, isec->sclass, perms, &ad);
6115 static int selinux_msg_msg_alloc_security(struct msg_msg *msg)
6117 struct msg_security_struct *msec;
6119 msec = selinux_msg_msg(msg);
6120 msec->sid = SECINITSID_UNLABELED;
6125 /* message queue security operations */
6126 static int selinux_msg_queue_alloc_security(struct kern_ipc_perm *msq)
6128 struct ipc_security_struct *isec;
6129 struct common_audit_data ad;
6130 u32 sid = current_sid();
6133 isec = selinux_ipc(msq);
6134 ipc_init_security(isec, SECCLASS_MSGQ);
6136 ad.type = LSM_AUDIT_DATA_IPC;
6137 ad.u.ipc_id = msq->key;
6139 rc = avc_has_perm(&selinux_state,
6140 sid, isec->sid, SECCLASS_MSGQ,
6145 static int selinux_msg_queue_associate(struct kern_ipc_perm *msq, int msqflg)
6147 struct ipc_security_struct *isec;
6148 struct common_audit_data ad;
6149 u32 sid = current_sid();
6151 isec = selinux_ipc(msq);
6153 ad.type = LSM_AUDIT_DATA_IPC;
6154 ad.u.ipc_id = msq->key;
6156 return avc_has_perm(&selinux_state,
6157 sid, isec->sid, SECCLASS_MSGQ,
6158 MSGQ__ASSOCIATE, &ad);
6161 static int selinux_msg_queue_msgctl(struct kern_ipc_perm *msq, int cmd)
6169 /* No specific object, just general system-wide information. */
6170 return avc_has_perm(&selinux_state,
6171 current_sid(), SECINITSID_KERNEL,
6172 SECCLASS_SYSTEM, SYSTEM__IPC_INFO, NULL);
6176 perms = MSGQ__GETATTR | MSGQ__ASSOCIATE;
6179 perms = MSGQ__SETATTR;
6182 perms = MSGQ__DESTROY;
6188 err = ipc_has_perm(msq, perms);
6192 static int selinux_msg_queue_msgsnd(struct kern_ipc_perm *msq, struct msg_msg *msg, int msqflg)
6194 struct ipc_security_struct *isec;
6195 struct msg_security_struct *msec;
6196 struct common_audit_data ad;
6197 u32 sid = current_sid();
6200 isec = selinux_ipc(msq);
6201 msec = selinux_msg_msg(msg);
6204 * First time through, need to assign label to the message
6206 if (msec->sid == SECINITSID_UNLABELED) {
6208 * Compute new sid based on current process and
6209 * message queue this message will be stored in
6211 rc = security_transition_sid(&selinux_state, sid, isec->sid,
6212 SECCLASS_MSG, NULL, &msec->sid);
6217 ad.type = LSM_AUDIT_DATA_IPC;
6218 ad.u.ipc_id = msq->key;
6220 /* Can this process write to the queue? */
6221 rc = avc_has_perm(&selinux_state,
6222 sid, isec->sid, SECCLASS_MSGQ,
6225 /* Can this process send the message */
6226 rc = avc_has_perm(&selinux_state,
6227 sid, msec->sid, SECCLASS_MSG,
6230 /* Can the message be put in the queue? */
6231 rc = avc_has_perm(&selinux_state,
6232 msec->sid, isec->sid, SECCLASS_MSGQ,
6233 MSGQ__ENQUEUE, &ad);
6238 static int selinux_msg_queue_msgrcv(struct kern_ipc_perm *msq, struct msg_msg *msg,
6239 struct task_struct *target,
6240 long type, int mode)
6242 struct ipc_security_struct *isec;
6243 struct msg_security_struct *msec;
6244 struct common_audit_data ad;
6245 u32 sid = task_sid_subj(target);
6248 isec = selinux_ipc(msq);
6249 msec = selinux_msg_msg(msg);
6251 ad.type = LSM_AUDIT_DATA_IPC;
6252 ad.u.ipc_id = msq->key;
6254 rc = avc_has_perm(&selinux_state,
6256 SECCLASS_MSGQ, MSGQ__READ, &ad);
6258 rc = avc_has_perm(&selinux_state,
6260 SECCLASS_MSG, MSG__RECEIVE, &ad);
6264 /* Shared Memory security operations */
6265 static int selinux_shm_alloc_security(struct kern_ipc_perm *shp)
6267 struct ipc_security_struct *isec;
6268 struct common_audit_data ad;
6269 u32 sid = current_sid();
6272 isec = selinux_ipc(shp);
6273 ipc_init_security(isec, SECCLASS_SHM);
6275 ad.type = LSM_AUDIT_DATA_IPC;
6276 ad.u.ipc_id = shp->key;
6278 rc = avc_has_perm(&selinux_state,
6279 sid, isec->sid, SECCLASS_SHM,
6284 static int selinux_shm_associate(struct kern_ipc_perm *shp, int shmflg)
6286 struct ipc_security_struct *isec;
6287 struct common_audit_data ad;
6288 u32 sid = current_sid();
6290 isec = selinux_ipc(shp);
6292 ad.type = LSM_AUDIT_DATA_IPC;
6293 ad.u.ipc_id = shp->key;
6295 return avc_has_perm(&selinux_state,
6296 sid, isec->sid, SECCLASS_SHM,
6297 SHM__ASSOCIATE, &ad);
6300 /* Note, at this point, shp is locked down */
6301 static int selinux_shm_shmctl(struct kern_ipc_perm *shp, int cmd)
6309 /* No specific object, just general system-wide information. */
6310 return avc_has_perm(&selinux_state,
6311 current_sid(), SECINITSID_KERNEL,
6312 SECCLASS_SYSTEM, SYSTEM__IPC_INFO, NULL);
6316 perms = SHM__GETATTR | SHM__ASSOCIATE;
6319 perms = SHM__SETATTR;
6326 perms = SHM__DESTROY;
6332 err = ipc_has_perm(shp, perms);
6336 static int selinux_shm_shmat(struct kern_ipc_perm *shp,
6337 char __user *shmaddr, int shmflg)
6341 if (shmflg & SHM_RDONLY)
6344 perms = SHM__READ | SHM__WRITE;
6346 return ipc_has_perm(shp, perms);
6349 /* Semaphore security operations */
6350 static int selinux_sem_alloc_security(struct kern_ipc_perm *sma)
6352 struct ipc_security_struct *isec;
6353 struct common_audit_data ad;
6354 u32 sid = current_sid();
6357 isec = selinux_ipc(sma);
6358 ipc_init_security(isec, SECCLASS_SEM);
6360 ad.type = LSM_AUDIT_DATA_IPC;
6361 ad.u.ipc_id = sma->key;
6363 rc = avc_has_perm(&selinux_state,
6364 sid, isec->sid, SECCLASS_SEM,
6369 static int selinux_sem_associate(struct kern_ipc_perm *sma, int semflg)
6371 struct ipc_security_struct *isec;
6372 struct common_audit_data ad;
6373 u32 sid = current_sid();
6375 isec = selinux_ipc(sma);
6377 ad.type = LSM_AUDIT_DATA_IPC;
6378 ad.u.ipc_id = sma->key;
6380 return avc_has_perm(&selinux_state,
6381 sid, isec->sid, SECCLASS_SEM,
6382 SEM__ASSOCIATE, &ad);
6385 /* Note, at this point, sma is locked down */
6386 static int selinux_sem_semctl(struct kern_ipc_perm *sma, int cmd)
6394 /* No specific object, just general system-wide information. */
6395 return avc_has_perm(&selinux_state,
6396 current_sid(), SECINITSID_KERNEL,
6397 SECCLASS_SYSTEM, SYSTEM__IPC_INFO, NULL);
6401 perms = SEM__GETATTR;
6412 perms = SEM__DESTROY;
6415 perms = SEM__SETATTR;
6420 perms = SEM__GETATTR | SEM__ASSOCIATE;
6426 err = ipc_has_perm(sma, perms);
6430 static int selinux_sem_semop(struct kern_ipc_perm *sma,
6431 struct sembuf *sops, unsigned nsops, int alter)
6436 perms = SEM__READ | SEM__WRITE;
6440 return ipc_has_perm(sma, perms);
6443 static int selinux_ipc_permission(struct kern_ipc_perm *ipcp, short flag)
6449 av |= IPC__UNIX_READ;
6451 av |= IPC__UNIX_WRITE;
6456 return ipc_has_perm(ipcp, av);
6459 static void selinux_ipc_getsecid(struct kern_ipc_perm *ipcp, u32 *secid)
6461 struct ipc_security_struct *isec = selinux_ipc(ipcp);
6465 static void selinux_d_instantiate(struct dentry *dentry, struct inode *inode)
6468 inode_doinit_with_dentry(inode, dentry);
6471 static int selinux_getprocattr(struct task_struct *p,
6472 char *name, char **value)
6474 const struct task_security_struct *__tsec;
6480 __tsec = selinux_cred(__task_cred(p));
6483 error = avc_has_perm(&selinux_state,
6484 current_sid(), __tsec->sid,
6485 SECCLASS_PROCESS, PROCESS__GETATTR, NULL);
6490 if (!strcmp(name, "current"))
6492 else if (!strcmp(name, "prev"))
6494 else if (!strcmp(name, "exec"))
6495 sid = __tsec->exec_sid;
6496 else if (!strcmp(name, "fscreate"))
6497 sid = __tsec->create_sid;
6498 else if (!strcmp(name, "keycreate"))
6499 sid = __tsec->keycreate_sid;
6500 else if (!strcmp(name, "sockcreate"))
6501 sid = __tsec->sockcreate_sid;
6511 error = security_sid_to_context(&selinux_state, sid, value, &len);
6521 static int selinux_setprocattr(const char *name, void *value, size_t size)
6523 struct task_security_struct *tsec;
6525 u32 mysid = current_sid(), sid = 0, ptsid;
6530 * Basic control over ability to set these attributes at all.
6532 if (!strcmp(name, "exec"))
6533 error = avc_has_perm(&selinux_state,
6534 mysid, mysid, SECCLASS_PROCESS,
6535 PROCESS__SETEXEC, NULL);
6536 else if (!strcmp(name, "fscreate"))
6537 error = avc_has_perm(&selinux_state,
6538 mysid, mysid, SECCLASS_PROCESS,
6539 PROCESS__SETFSCREATE, NULL);
6540 else if (!strcmp(name, "keycreate"))
6541 error = avc_has_perm(&selinux_state,
6542 mysid, mysid, SECCLASS_PROCESS,
6543 PROCESS__SETKEYCREATE, NULL);
6544 else if (!strcmp(name, "sockcreate"))
6545 error = avc_has_perm(&selinux_state,
6546 mysid, mysid, SECCLASS_PROCESS,
6547 PROCESS__SETSOCKCREATE, NULL);
6548 else if (!strcmp(name, "current"))
6549 error = avc_has_perm(&selinux_state,
6550 mysid, mysid, SECCLASS_PROCESS,
6551 PROCESS__SETCURRENT, NULL);
6557 /* Obtain a SID for the context, if one was specified. */
6558 if (size && str[0] && str[0] != '\n') {
6559 if (str[size-1] == '\n') {
6563 error = security_context_to_sid(&selinux_state, value, size,
6565 if (error == -EINVAL && !strcmp(name, "fscreate")) {
6566 if (!has_cap_mac_admin(true)) {
6567 struct audit_buffer *ab;
6570 /* We strip a nul only if it is at the end, otherwise the
6571 * context contains a nul and we should audit that */
6572 if (str[size - 1] == '\0')
6573 audit_size = size - 1;
6576 ab = audit_log_start(audit_context(),
6579 audit_log_format(ab, "op=fscreate invalid_context=");
6580 audit_log_n_untrustedstring(ab, value, audit_size);
6585 error = security_context_to_sid_force(
6593 new = prepare_creds();
6597 /* Permission checking based on the specified context is
6598 performed during the actual operation (execve,
6599 open/mkdir/...), when we know the full context of the
6600 operation. See selinux_bprm_creds_for_exec for the execve
6601 checks and may_create for the file creation checks. The
6602 operation will then fail if the context is not permitted. */
6603 tsec = selinux_cred(new);
6604 if (!strcmp(name, "exec")) {
6605 tsec->exec_sid = sid;
6606 } else if (!strcmp(name, "fscreate")) {
6607 tsec->create_sid = sid;
6608 } else if (!strcmp(name, "keycreate")) {
6610 error = avc_has_perm(&selinux_state, mysid, sid,
6611 SECCLASS_KEY, KEY__CREATE, NULL);
6615 tsec->keycreate_sid = sid;
6616 } else if (!strcmp(name, "sockcreate")) {
6617 tsec->sockcreate_sid = sid;
6618 } else if (!strcmp(name, "current")) {
6623 /* Only allow single threaded processes to change context */
6625 if (!current_is_single_threaded()) {
6626 error = security_bounded_transition(&selinux_state,
6632 /* Check permissions for the transition. */
6633 error = avc_has_perm(&selinux_state,
6634 tsec->sid, sid, SECCLASS_PROCESS,
6635 PROCESS__DYNTRANSITION, NULL);
6639 /* Check for ptracing, and update the task SID if ok.
6640 Otherwise, leave SID unchanged and fail. */
6641 ptsid = ptrace_parent_sid();
6643 error = avc_has_perm(&selinux_state,
6644 ptsid, sid, SECCLASS_PROCESS,
6645 PROCESS__PTRACE, NULL);
6664 static int selinux_ismaclabel(const char *name)
6666 return (strcmp(name, XATTR_SELINUX_SUFFIX) == 0);
6669 static int selinux_secid_to_secctx(u32 secid, char **secdata, u32 *seclen)
6671 return security_sid_to_context(&selinux_state, secid,
6675 static int selinux_secctx_to_secid(const char *secdata, u32 seclen, u32 *secid)
6677 return security_context_to_sid(&selinux_state, secdata, seclen,
6681 static void selinux_release_secctx(char *secdata, u32 seclen)
6686 static void selinux_inode_invalidate_secctx(struct inode *inode)
6688 struct inode_security_struct *isec = selinux_inode(inode);
6690 spin_lock(&isec->lock);
6691 isec->initialized = LABEL_INVALID;
6692 spin_unlock(&isec->lock);
6696 * called with inode->i_mutex locked
6698 static int selinux_inode_notifysecctx(struct inode *inode, void *ctx, u32 ctxlen)
6700 int rc = selinux_inode_setsecurity(inode, XATTR_SELINUX_SUFFIX,
6702 /* Do not return error when suppressing label (SBLABEL_MNT not set). */
6703 return rc == -EOPNOTSUPP ? 0 : rc;
6707 * called with inode->i_mutex locked
6709 static int selinux_inode_setsecctx(struct dentry *dentry, void *ctx, u32 ctxlen)
6711 return __vfs_setxattr_noperm(&init_user_ns, dentry, XATTR_NAME_SELINUX,
6715 static int selinux_inode_getsecctx(struct inode *inode, void **ctx, u32 *ctxlen)
6718 len = selinux_inode_getsecurity(&init_user_ns, inode,
6719 XATTR_SELINUX_SUFFIX, ctx, true);
6727 static int selinux_key_alloc(struct key *k, const struct cred *cred,
6728 unsigned long flags)
6730 const struct task_security_struct *tsec;
6731 struct key_security_struct *ksec;
6733 ksec = kzalloc(sizeof(struct key_security_struct), GFP_KERNEL);
6737 tsec = selinux_cred(cred);
6738 if (tsec->keycreate_sid)
6739 ksec->sid = tsec->keycreate_sid;
6741 ksec->sid = tsec->sid;
6747 static void selinux_key_free(struct key *k)
6749 struct key_security_struct *ksec = k->security;
6755 static int selinux_key_permission(key_ref_t key_ref,
6756 const struct cred *cred,
6757 enum key_need_perm need_perm)
6760 struct key_security_struct *ksec;
6763 switch (need_perm) {
6770 case KEY_NEED_WRITE:
6773 case KEY_NEED_SEARCH:
6779 case KEY_NEED_SETATTR:
6780 perm = KEY__SETATTR;
6782 case KEY_NEED_UNLINK:
6783 case KEY_SYSADMIN_OVERRIDE:
6784 case KEY_AUTHTOKEN_OVERRIDE:
6785 case KEY_DEFER_PERM_CHECK:
6793 sid = cred_sid(cred);
6794 key = key_ref_to_ptr(key_ref);
6795 ksec = key->security;
6797 return avc_has_perm(&selinux_state,
6798 sid, ksec->sid, SECCLASS_KEY, perm, NULL);
6801 static int selinux_key_getsecurity(struct key *key, char **_buffer)
6803 struct key_security_struct *ksec = key->security;
6804 char *context = NULL;
6808 rc = security_sid_to_context(&selinux_state, ksec->sid,
6816 #ifdef CONFIG_KEY_NOTIFICATIONS
6817 static int selinux_watch_key(struct key *key)
6819 struct key_security_struct *ksec = key->security;
6820 u32 sid = current_sid();
6822 return avc_has_perm(&selinux_state,
6823 sid, ksec->sid, SECCLASS_KEY, KEY__VIEW, NULL);
6828 #ifdef CONFIG_SECURITY_INFINIBAND
6829 static int selinux_ib_pkey_access(void *ib_sec, u64 subnet_prefix, u16 pkey_val)
6831 struct common_audit_data ad;
6834 struct ib_security_struct *sec = ib_sec;
6835 struct lsm_ibpkey_audit ibpkey;
6837 err = sel_ib_pkey_sid(subnet_prefix, pkey_val, &sid);
6841 ad.type = LSM_AUDIT_DATA_IBPKEY;
6842 ibpkey.subnet_prefix = subnet_prefix;
6843 ibpkey.pkey = pkey_val;
6844 ad.u.ibpkey = &ibpkey;
6845 return avc_has_perm(&selinux_state,
6847 SECCLASS_INFINIBAND_PKEY,
6848 INFINIBAND_PKEY__ACCESS, &ad);
6851 static int selinux_ib_endport_manage_subnet(void *ib_sec, const char *dev_name,
6854 struct common_audit_data ad;
6857 struct ib_security_struct *sec = ib_sec;
6858 struct lsm_ibendport_audit ibendport;
6860 err = security_ib_endport_sid(&selinux_state, dev_name, port_num,
6866 ad.type = LSM_AUDIT_DATA_IBENDPORT;
6867 strncpy(ibendport.dev_name, dev_name, sizeof(ibendport.dev_name));
6868 ibendport.port = port_num;
6869 ad.u.ibendport = &ibendport;
6870 return avc_has_perm(&selinux_state,
6872 SECCLASS_INFINIBAND_ENDPORT,
6873 INFINIBAND_ENDPORT__MANAGE_SUBNET, &ad);
6876 static int selinux_ib_alloc_security(void **ib_sec)
6878 struct ib_security_struct *sec;
6880 sec = kzalloc(sizeof(*sec), GFP_KERNEL);
6883 sec->sid = current_sid();
6889 static void selinux_ib_free_security(void *ib_sec)
6895 #ifdef CONFIG_BPF_SYSCALL
6896 static int selinux_bpf(int cmd, union bpf_attr *attr,
6899 u32 sid = current_sid();
6903 case BPF_MAP_CREATE:
6904 ret = avc_has_perm(&selinux_state,
6905 sid, sid, SECCLASS_BPF, BPF__MAP_CREATE,
6909 ret = avc_has_perm(&selinux_state,
6910 sid, sid, SECCLASS_BPF, BPF__PROG_LOAD,
6921 static u32 bpf_map_fmode_to_av(fmode_t fmode)
6925 if (fmode & FMODE_READ)
6926 av |= BPF__MAP_READ;
6927 if (fmode & FMODE_WRITE)
6928 av |= BPF__MAP_WRITE;
6932 /* This function will check the file pass through unix socket or binder to see
6933 * if it is a bpf related object. And apply correspinding checks on the bpf
6934 * object based on the type. The bpf maps and programs, not like other files and
6935 * socket, are using a shared anonymous inode inside the kernel as their inode.
6936 * So checking that inode cannot identify if the process have privilege to
6937 * access the bpf object and that's why we have to add this additional check in
6938 * selinux_file_receive and selinux_binder_transfer_files.
6940 static int bpf_fd_pass(struct file *file, u32 sid)
6942 struct bpf_security_struct *bpfsec;
6943 struct bpf_prog *prog;
6944 struct bpf_map *map;
6947 if (file->f_op == &bpf_map_fops) {
6948 map = file->private_data;
6949 bpfsec = map->security;
6950 ret = avc_has_perm(&selinux_state,
6951 sid, bpfsec->sid, SECCLASS_BPF,
6952 bpf_map_fmode_to_av(file->f_mode), NULL);
6955 } else if (file->f_op == &bpf_prog_fops) {
6956 prog = file->private_data;
6957 bpfsec = prog->aux->security;
6958 ret = avc_has_perm(&selinux_state,
6959 sid, bpfsec->sid, SECCLASS_BPF,
6960 BPF__PROG_RUN, NULL);
6967 static int selinux_bpf_map(struct bpf_map *map, fmode_t fmode)
6969 u32 sid = current_sid();
6970 struct bpf_security_struct *bpfsec;
6972 bpfsec = map->security;
6973 return avc_has_perm(&selinux_state,
6974 sid, bpfsec->sid, SECCLASS_BPF,
6975 bpf_map_fmode_to_av(fmode), NULL);
6978 static int selinux_bpf_prog(struct bpf_prog *prog)
6980 u32 sid = current_sid();
6981 struct bpf_security_struct *bpfsec;
6983 bpfsec = prog->aux->security;
6984 return avc_has_perm(&selinux_state,
6985 sid, bpfsec->sid, SECCLASS_BPF,
6986 BPF__PROG_RUN, NULL);
6989 static int selinux_bpf_map_alloc(struct bpf_map *map)
6991 struct bpf_security_struct *bpfsec;
6993 bpfsec = kzalloc(sizeof(*bpfsec), GFP_KERNEL);
6997 bpfsec->sid = current_sid();
6998 map->security = bpfsec;
7003 static void selinux_bpf_map_free(struct bpf_map *map)
7005 struct bpf_security_struct *bpfsec = map->security;
7007 map->security = NULL;
7011 static int selinux_bpf_prog_alloc(struct bpf_prog_aux *aux)
7013 struct bpf_security_struct *bpfsec;
7015 bpfsec = kzalloc(sizeof(*bpfsec), GFP_KERNEL);
7019 bpfsec->sid = current_sid();
7020 aux->security = bpfsec;
7025 static void selinux_bpf_prog_free(struct bpf_prog_aux *aux)
7027 struct bpf_security_struct *bpfsec = aux->security;
7029 aux->security = NULL;
7034 static int selinux_lockdown(enum lockdown_reason what)
7036 struct common_audit_data ad;
7037 u32 sid = current_sid();
7038 int invalid_reason = (what <= LOCKDOWN_NONE) ||
7039 (what == LOCKDOWN_INTEGRITY_MAX) ||
7040 (what >= LOCKDOWN_CONFIDENTIALITY_MAX);
7042 if (WARN(invalid_reason, "Invalid lockdown reason")) {
7043 audit_log(audit_context(),
7044 GFP_ATOMIC, AUDIT_SELINUX_ERR,
7045 "lockdown_reason=invalid");
7049 ad.type = LSM_AUDIT_DATA_LOCKDOWN;
7052 if (what <= LOCKDOWN_INTEGRITY_MAX)
7053 return avc_has_perm(&selinux_state,
7054 sid, sid, SECCLASS_LOCKDOWN,
7055 LOCKDOWN__INTEGRITY, &ad);
7057 return avc_has_perm(&selinux_state,
7058 sid, sid, SECCLASS_LOCKDOWN,
7059 LOCKDOWN__CONFIDENTIALITY, &ad);
7062 struct lsm_blob_sizes selinux_blob_sizes __lsm_ro_after_init = {
7063 .lbs_cred = sizeof(struct task_security_struct),
7064 .lbs_file = sizeof(struct file_security_struct),
7065 .lbs_inode = sizeof(struct inode_security_struct),
7066 .lbs_ipc = sizeof(struct ipc_security_struct),
7067 .lbs_msg_msg = sizeof(struct msg_security_struct),
7070 #ifdef CONFIG_PERF_EVENTS
7071 static int selinux_perf_event_open(struct perf_event_attr *attr, int type)
7073 u32 requested, sid = current_sid();
7075 if (type == PERF_SECURITY_OPEN)
7076 requested = PERF_EVENT__OPEN;
7077 else if (type == PERF_SECURITY_CPU)
7078 requested = PERF_EVENT__CPU;
7079 else if (type == PERF_SECURITY_KERNEL)
7080 requested = PERF_EVENT__KERNEL;
7081 else if (type == PERF_SECURITY_TRACEPOINT)
7082 requested = PERF_EVENT__TRACEPOINT;
7086 return avc_has_perm(&selinux_state, sid, sid, SECCLASS_PERF_EVENT,
7090 static int selinux_perf_event_alloc(struct perf_event *event)
7092 struct perf_event_security_struct *perfsec;
7094 perfsec = kzalloc(sizeof(*perfsec), GFP_KERNEL);
7098 perfsec->sid = current_sid();
7099 event->security = perfsec;
7104 static void selinux_perf_event_free(struct perf_event *event)
7106 struct perf_event_security_struct *perfsec = event->security;
7108 event->security = NULL;
7112 static int selinux_perf_event_read(struct perf_event *event)
7114 struct perf_event_security_struct *perfsec = event->security;
7115 u32 sid = current_sid();
7117 return avc_has_perm(&selinux_state, sid, perfsec->sid,
7118 SECCLASS_PERF_EVENT, PERF_EVENT__READ, NULL);
7121 static int selinux_perf_event_write(struct perf_event *event)
7123 struct perf_event_security_struct *perfsec = event->security;
7124 u32 sid = current_sid();
7126 return avc_has_perm(&selinux_state, sid, perfsec->sid,
7127 SECCLASS_PERF_EVENT, PERF_EVENT__WRITE, NULL);
7132 * IMPORTANT NOTE: When adding new hooks, please be careful to keep this order:
7133 * 1. any hooks that don't belong to (2.) or (3.) below,
7134 * 2. hooks that both access structures allocated by other hooks, and allocate
7135 * structures that can be later accessed by other hooks (mostly "cloning"
7137 * 3. hooks that only allocate structures that can be later accessed by other
7138 * hooks ("allocating" hooks).
7140 * Please follow block comment delimiters in the list to keep this order.
7142 * This ordering is needed for SELinux runtime disable to work at least somewhat
7143 * safely. Breaking the ordering rules above might lead to NULL pointer derefs
7144 * when disabling SELinux at runtime.
7146 static struct security_hook_list selinux_hooks[] __lsm_ro_after_init = {
7147 LSM_HOOK_INIT(binder_set_context_mgr, selinux_binder_set_context_mgr),
7148 LSM_HOOK_INIT(binder_transaction, selinux_binder_transaction),
7149 LSM_HOOK_INIT(binder_transfer_binder, selinux_binder_transfer_binder),
7150 LSM_HOOK_INIT(binder_transfer_file, selinux_binder_transfer_file),
7152 LSM_HOOK_INIT(ptrace_access_check, selinux_ptrace_access_check),
7153 LSM_HOOK_INIT(ptrace_traceme, selinux_ptrace_traceme),
7154 LSM_HOOK_INIT(capget, selinux_capget),
7155 LSM_HOOK_INIT(capset, selinux_capset),
7156 LSM_HOOK_INIT(capable, selinux_capable),
7157 LSM_HOOK_INIT(quotactl, selinux_quotactl),
7158 LSM_HOOK_INIT(quota_on, selinux_quota_on),
7159 LSM_HOOK_INIT(syslog, selinux_syslog),
7160 LSM_HOOK_INIT(vm_enough_memory, selinux_vm_enough_memory),
7162 LSM_HOOK_INIT(netlink_send, selinux_netlink_send),
7164 LSM_HOOK_INIT(bprm_creds_for_exec, selinux_bprm_creds_for_exec),
7165 LSM_HOOK_INIT(bprm_committing_creds, selinux_bprm_committing_creds),
7166 LSM_HOOK_INIT(bprm_committed_creds, selinux_bprm_committed_creds),
7168 LSM_HOOK_INIT(sb_free_security, selinux_sb_free_security),
7169 LSM_HOOK_INIT(sb_free_mnt_opts, selinux_free_mnt_opts),
7170 LSM_HOOK_INIT(sb_mnt_opts_compat, selinux_sb_mnt_opts_compat),
7171 LSM_HOOK_INIT(sb_remount, selinux_sb_remount),
7172 LSM_HOOK_INIT(sb_kern_mount, selinux_sb_kern_mount),
7173 LSM_HOOK_INIT(sb_show_options, selinux_sb_show_options),
7174 LSM_HOOK_INIT(sb_statfs, selinux_sb_statfs),
7175 LSM_HOOK_INIT(sb_mount, selinux_mount),
7176 LSM_HOOK_INIT(sb_umount, selinux_umount),
7177 LSM_HOOK_INIT(sb_set_mnt_opts, selinux_set_mnt_opts),
7178 LSM_HOOK_INIT(sb_clone_mnt_opts, selinux_sb_clone_mnt_opts),
7180 LSM_HOOK_INIT(move_mount, selinux_move_mount),
7182 LSM_HOOK_INIT(dentry_init_security, selinux_dentry_init_security),
7183 LSM_HOOK_INIT(dentry_create_files_as, selinux_dentry_create_files_as),
7185 LSM_HOOK_INIT(inode_free_security, selinux_inode_free_security),
7186 LSM_HOOK_INIT(inode_init_security, selinux_inode_init_security),
7187 LSM_HOOK_INIT(inode_init_security_anon, selinux_inode_init_security_anon),
7188 LSM_HOOK_INIT(inode_create, selinux_inode_create),
7189 LSM_HOOK_INIT(inode_link, selinux_inode_link),
7190 LSM_HOOK_INIT(inode_unlink, selinux_inode_unlink),
7191 LSM_HOOK_INIT(inode_symlink, selinux_inode_symlink),
7192 LSM_HOOK_INIT(inode_mkdir, selinux_inode_mkdir),
7193 LSM_HOOK_INIT(inode_rmdir, selinux_inode_rmdir),
7194 LSM_HOOK_INIT(inode_mknod, selinux_inode_mknod),
7195 LSM_HOOK_INIT(inode_rename, selinux_inode_rename),
7196 LSM_HOOK_INIT(inode_readlink, selinux_inode_readlink),
7197 LSM_HOOK_INIT(inode_follow_link, selinux_inode_follow_link),
7198 LSM_HOOK_INIT(inode_permission, selinux_inode_permission),
7199 LSM_HOOK_INIT(inode_setattr, selinux_inode_setattr),
7200 LSM_HOOK_INIT(inode_getattr, selinux_inode_getattr),
7201 LSM_HOOK_INIT(inode_setxattr, selinux_inode_setxattr),
7202 LSM_HOOK_INIT(inode_post_setxattr, selinux_inode_post_setxattr),
7203 LSM_HOOK_INIT(inode_getxattr, selinux_inode_getxattr),
7204 LSM_HOOK_INIT(inode_listxattr, selinux_inode_listxattr),
7205 LSM_HOOK_INIT(inode_removexattr, selinux_inode_removexattr),
7206 LSM_HOOK_INIT(inode_getsecurity, selinux_inode_getsecurity),
7207 LSM_HOOK_INIT(inode_setsecurity, selinux_inode_setsecurity),
7208 LSM_HOOK_INIT(inode_listsecurity, selinux_inode_listsecurity),
7209 LSM_HOOK_INIT(inode_getsecid, selinux_inode_getsecid),
7210 LSM_HOOK_INIT(inode_copy_up, selinux_inode_copy_up),
7211 LSM_HOOK_INIT(inode_copy_up_xattr, selinux_inode_copy_up_xattr),
7212 LSM_HOOK_INIT(path_notify, selinux_path_notify),
7214 LSM_HOOK_INIT(kernfs_init_security, selinux_kernfs_init_security),
7216 LSM_HOOK_INIT(file_permission, selinux_file_permission),
7217 LSM_HOOK_INIT(file_alloc_security, selinux_file_alloc_security),
7218 LSM_HOOK_INIT(file_ioctl, selinux_file_ioctl),
7219 LSM_HOOK_INIT(mmap_file, selinux_mmap_file),
7220 LSM_HOOK_INIT(mmap_addr, selinux_mmap_addr),
7221 LSM_HOOK_INIT(file_mprotect, selinux_file_mprotect),
7222 LSM_HOOK_INIT(file_lock, selinux_file_lock),
7223 LSM_HOOK_INIT(file_fcntl, selinux_file_fcntl),
7224 LSM_HOOK_INIT(file_set_fowner, selinux_file_set_fowner),
7225 LSM_HOOK_INIT(file_send_sigiotask, selinux_file_send_sigiotask),
7226 LSM_HOOK_INIT(file_receive, selinux_file_receive),
7228 LSM_HOOK_INIT(file_open, selinux_file_open),
7230 LSM_HOOK_INIT(task_alloc, selinux_task_alloc),
7231 LSM_HOOK_INIT(cred_prepare, selinux_cred_prepare),
7232 LSM_HOOK_INIT(cred_transfer, selinux_cred_transfer),
7233 LSM_HOOK_INIT(cred_getsecid, selinux_cred_getsecid),
7234 LSM_HOOK_INIT(kernel_act_as, selinux_kernel_act_as),
7235 LSM_HOOK_INIT(kernel_create_files_as, selinux_kernel_create_files_as),
7236 LSM_HOOK_INIT(kernel_module_request, selinux_kernel_module_request),
7237 LSM_HOOK_INIT(kernel_load_data, selinux_kernel_load_data),
7238 LSM_HOOK_INIT(kernel_read_file, selinux_kernel_read_file),
7239 LSM_HOOK_INIT(task_setpgid, selinux_task_setpgid),
7240 LSM_HOOK_INIT(task_getpgid, selinux_task_getpgid),
7241 LSM_HOOK_INIT(task_getsid, selinux_task_getsid),
7242 LSM_HOOK_INIT(task_getsecid_subj, selinux_task_getsecid_subj),
7243 LSM_HOOK_INIT(task_getsecid_obj, selinux_task_getsecid_obj),
7244 LSM_HOOK_INIT(task_setnice, selinux_task_setnice),
7245 LSM_HOOK_INIT(task_setioprio, selinux_task_setioprio),
7246 LSM_HOOK_INIT(task_getioprio, selinux_task_getioprio),
7247 LSM_HOOK_INIT(task_prlimit, selinux_task_prlimit),
7248 LSM_HOOK_INIT(task_setrlimit, selinux_task_setrlimit),
7249 LSM_HOOK_INIT(task_setscheduler, selinux_task_setscheduler),
7250 LSM_HOOK_INIT(task_getscheduler, selinux_task_getscheduler),
7251 LSM_HOOK_INIT(task_movememory, selinux_task_movememory),
7252 LSM_HOOK_INIT(task_kill, selinux_task_kill),
7253 LSM_HOOK_INIT(task_to_inode, selinux_task_to_inode),
7255 LSM_HOOK_INIT(ipc_permission, selinux_ipc_permission),
7256 LSM_HOOK_INIT(ipc_getsecid, selinux_ipc_getsecid),
7258 LSM_HOOK_INIT(msg_queue_associate, selinux_msg_queue_associate),
7259 LSM_HOOK_INIT(msg_queue_msgctl, selinux_msg_queue_msgctl),
7260 LSM_HOOK_INIT(msg_queue_msgsnd, selinux_msg_queue_msgsnd),
7261 LSM_HOOK_INIT(msg_queue_msgrcv, selinux_msg_queue_msgrcv),
7263 LSM_HOOK_INIT(shm_associate, selinux_shm_associate),
7264 LSM_HOOK_INIT(shm_shmctl, selinux_shm_shmctl),
7265 LSM_HOOK_INIT(shm_shmat, selinux_shm_shmat),
7267 LSM_HOOK_INIT(sem_associate, selinux_sem_associate),
7268 LSM_HOOK_INIT(sem_semctl, selinux_sem_semctl),
7269 LSM_HOOK_INIT(sem_semop, selinux_sem_semop),
7271 LSM_HOOK_INIT(d_instantiate, selinux_d_instantiate),
7273 LSM_HOOK_INIT(getprocattr, selinux_getprocattr),
7274 LSM_HOOK_INIT(setprocattr, selinux_setprocattr),
7276 LSM_HOOK_INIT(ismaclabel, selinux_ismaclabel),
7277 LSM_HOOK_INIT(secctx_to_secid, selinux_secctx_to_secid),
7278 LSM_HOOK_INIT(release_secctx, selinux_release_secctx),
7279 LSM_HOOK_INIT(inode_invalidate_secctx, selinux_inode_invalidate_secctx),
7280 LSM_HOOK_INIT(inode_notifysecctx, selinux_inode_notifysecctx),
7281 LSM_HOOK_INIT(inode_setsecctx, selinux_inode_setsecctx),
7283 LSM_HOOK_INIT(unix_stream_connect, selinux_socket_unix_stream_connect),
7284 LSM_HOOK_INIT(unix_may_send, selinux_socket_unix_may_send),
7286 LSM_HOOK_INIT(socket_create, selinux_socket_create),
7287 LSM_HOOK_INIT(socket_post_create, selinux_socket_post_create),
7288 LSM_HOOK_INIT(socket_socketpair, selinux_socket_socketpair),
7289 LSM_HOOK_INIT(socket_bind, selinux_socket_bind),
7290 LSM_HOOK_INIT(socket_connect, selinux_socket_connect),
7291 LSM_HOOK_INIT(socket_listen, selinux_socket_listen),
7292 LSM_HOOK_INIT(socket_accept, selinux_socket_accept),
7293 LSM_HOOK_INIT(socket_sendmsg, selinux_socket_sendmsg),
7294 LSM_HOOK_INIT(socket_recvmsg, selinux_socket_recvmsg),
7295 LSM_HOOK_INIT(socket_getsockname, selinux_socket_getsockname),
7296 LSM_HOOK_INIT(socket_getpeername, selinux_socket_getpeername),
7297 LSM_HOOK_INIT(socket_getsockopt, selinux_socket_getsockopt),
7298 LSM_HOOK_INIT(socket_setsockopt, selinux_socket_setsockopt),
7299 LSM_HOOK_INIT(socket_shutdown, selinux_socket_shutdown),
7300 LSM_HOOK_INIT(socket_sock_rcv_skb, selinux_socket_sock_rcv_skb),
7301 LSM_HOOK_INIT(socket_getpeersec_stream,
7302 selinux_socket_getpeersec_stream),
7303 LSM_HOOK_INIT(socket_getpeersec_dgram, selinux_socket_getpeersec_dgram),
7304 LSM_HOOK_INIT(sk_free_security, selinux_sk_free_security),
7305 LSM_HOOK_INIT(sk_clone_security, selinux_sk_clone_security),
7306 LSM_HOOK_INIT(sk_getsecid, selinux_sk_getsecid),
7307 LSM_HOOK_INIT(sock_graft, selinux_sock_graft),
7308 LSM_HOOK_INIT(sctp_assoc_request, selinux_sctp_assoc_request),
7309 LSM_HOOK_INIT(sctp_sk_clone, selinux_sctp_sk_clone),
7310 LSM_HOOK_INIT(sctp_bind_connect, selinux_sctp_bind_connect),
7311 LSM_HOOK_INIT(inet_conn_request, selinux_inet_conn_request),
7312 LSM_HOOK_INIT(inet_csk_clone, selinux_inet_csk_clone),
7313 LSM_HOOK_INIT(inet_conn_established, selinux_inet_conn_established),
7314 LSM_HOOK_INIT(secmark_relabel_packet, selinux_secmark_relabel_packet),
7315 LSM_HOOK_INIT(secmark_refcount_inc, selinux_secmark_refcount_inc),
7316 LSM_HOOK_INIT(secmark_refcount_dec, selinux_secmark_refcount_dec),
7317 LSM_HOOK_INIT(req_classify_flow, selinux_req_classify_flow),
7318 LSM_HOOK_INIT(tun_dev_free_security, selinux_tun_dev_free_security),
7319 LSM_HOOK_INIT(tun_dev_create, selinux_tun_dev_create),
7320 LSM_HOOK_INIT(tun_dev_attach_queue, selinux_tun_dev_attach_queue),
7321 LSM_HOOK_INIT(tun_dev_attach, selinux_tun_dev_attach),
7322 LSM_HOOK_INIT(tun_dev_open, selinux_tun_dev_open),
7323 #ifdef CONFIG_SECURITY_INFINIBAND
7324 LSM_HOOK_INIT(ib_pkey_access, selinux_ib_pkey_access),
7325 LSM_HOOK_INIT(ib_endport_manage_subnet,
7326 selinux_ib_endport_manage_subnet),
7327 LSM_HOOK_INIT(ib_free_security, selinux_ib_free_security),
7329 #ifdef CONFIG_SECURITY_NETWORK_XFRM
7330 LSM_HOOK_INIT(xfrm_policy_free_security, selinux_xfrm_policy_free),
7331 LSM_HOOK_INIT(xfrm_policy_delete_security, selinux_xfrm_policy_delete),
7332 LSM_HOOK_INIT(xfrm_state_free_security, selinux_xfrm_state_free),
7333 LSM_HOOK_INIT(xfrm_state_delete_security, selinux_xfrm_state_delete),
7334 LSM_HOOK_INIT(xfrm_policy_lookup, selinux_xfrm_policy_lookup),
7335 LSM_HOOK_INIT(xfrm_state_pol_flow_match,
7336 selinux_xfrm_state_pol_flow_match),
7337 LSM_HOOK_INIT(xfrm_decode_session, selinux_xfrm_decode_session),
7341 LSM_HOOK_INIT(key_free, selinux_key_free),
7342 LSM_HOOK_INIT(key_permission, selinux_key_permission),
7343 LSM_HOOK_INIT(key_getsecurity, selinux_key_getsecurity),
7344 #ifdef CONFIG_KEY_NOTIFICATIONS
7345 LSM_HOOK_INIT(watch_key, selinux_watch_key),
7350 LSM_HOOK_INIT(audit_rule_known, selinux_audit_rule_known),
7351 LSM_HOOK_INIT(audit_rule_match, selinux_audit_rule_match),
7352 LSM_HOOK_INIT(audit_rule_free, selinux_audit_rule_free),
7355 #ifdef CONFIG_BPF_SYSCALL
7356 LSM_HOOK_INIT(bpf, selinux_bpf),
7357 LSM_HOOK_INIT(bpf_map, selinux_bpf_map),
7358 LSM_HOOK_INIT(bpf_prog, selinux_bpf_prog),
7359 LSM_HOOK_INIT(bpf_map_free_security, selinux_bpf_map_free),
7360 LSM_HOOK_INIT(bpf_prog_free_security, selinux_bpf_prog_free),
7363 #ifdef CONFIG_PERF_EVENTS
7364 LSM_HOOK_INIT(perf_event_open, selinux_perf_event_open),
7365 LSM_HOOK_INIT(perf_event_free, selinux_perf_event_free),
7366 LSM_HOOK_INIT(perf_event_read, selinux_perf_event_read),
7367 LSM_HOOK_INIT(perf_event_write, selinux_perf_event_write),
7370 LSM_HOOK_INIT(locked_down, selinux_lockdown),
7373 * PUT "CLONING" (ACCESSING + ALLOCATING) HOOKS HERE
7375 LSM_HOOK_INIT(fs_context_dup, selinux_fs_context_dup),
7376 LSM_HOOK_INIT(fs_context_parse_param, selinux_fs_context_parse_param),
7377 LSM_HOOK_INIT(sb_eat_lsm_opts, selinux_sb_eat_lsm_opts),
7378 LSM_HOOK_INIT(sb_add_mnt_opt, selinux_add_mnt_opt),
7379 #ifdef CONFIG_SECURITY_NETWORK_XFRM
7380 LSM_HOOK_INIT(xfrm_policy_clone_security, selinux_xfrm_policy_clone),
7384 * PUT "ALLOCATING" HOOKS HERE
7386 LSM_HOOK_INIT(msg_msg_alloc_security, selinux_msg_msg_alloc_security),
7387 LSM_HOOK_INIT(msg_queue_alloc_security,
7388 selinux_msg_queue_alloc_security),
7389 LSM_HOOK_INIT(shm_alloc_security, selinux_shm_alloc_security),
7390 LSM_HOOK_INIT(sb_alloc_security, selinux_sb_alloc_security),
7391 LSM_HOOK_INIT(inode_alloc_security, selinux_inode_alloc_security),
7392 LSM_HOOK_INIT(sem_alloc_security, selinux_sem_alloc_security),
7393 LSM_HOOK_INIT(secid_to_secctx, selinux_secid_to_secctx),
7394 LSM_HOOK_INIT(inode_getsecctx, selinux_inode_getsecctx),
7395 LSM_HOOK_INIT(sk_alloc_security, selinux_sk_alloc_security),
7396 LSM_HOOK_INIT(tun_dev_alloc_security, selinux_tun_dev_alloc_security),
7397 #ifdef CONFIG_SECURITY_INFINIBAND
7398 LSM_HOOK_INIT(ib_alloc_security, selinux_ib_alloc_security),
7400 #ifdef CONFIG_SECURITY_NETWORK_XFRM
7401 LSM_HOOK_INIT(xfrm_policy_alloc_security, selinux_xfrm_policy_alloc),
7402 LSM_HOOK_INIT(xfrm_state_alloc, selinux_xfrm_state_alloc),
7403 LSM_HOOK_INIT(xfrm_state_alloc_acquire,
7404 selinux_xfrm_state_alloc_acquire),
7407 LSM_HOOK_INIT(key_alloc, selinux_key_alloc),
7410 LSM_HOOK_INIT(audit_rule_init, selinux_audit_rule_init),
7412 #ifdef CONFIG_BPF_SYSCALL
7413 LSM_HOOK_INIT(bpf_map_alloc_security, selinux_bpf_map_alloc),
7414 LSM_HOOK_INIT(bpf_prog_alloc_security, selinux_bpf_prog_alloc),
7416 #ifdef CONFIG_PERF_EVENTS
7417 LSM_HOOK_INIT(perf_event_alloc, selinux_perf_event_alloc),
7421 static __init int selinux_init(void)
7423 pr_info("SELinux: Initializing.\n");
7425 memset(&selinux_state, 0, sizeof(selinux_state));
7426 enforcing_set(&selinux_state, selinux_enforcing_boot);
7427 checkreqprot_set(&selinux_state, selinux_checkreqprot_boot);
7428 selinux_avc_init(&selinux_state.avc);
7429 mutex_init(&selinux_state.status_lock);
7430 mutex_init(&selinux_state.policy_mutex);
7432 /* Set the security state for the initial task. */
7433 cred_init_security();
7435 default_noexec = !(VM_DATA_DEFAULT_FLAGS & VM_EXEC);
7441 ebitmap_cache_init();
7443 hashtab_cache_init();
7445 security_add_hooks(selinux_hooks, ARRAY_SIZE(selinux_hooks), "selinux");
7447 if (avc_add_callback(selinux_netcache_avc_callback, AVC_CALLBACK_RESET))
7448 panic("SELinux: Unable to register AVC netcache callback\n");
7450 if (avc_add_callback(selinux_lsm_notifier_avc_callback, AVC_CALLBACK_RESET))
7451 panic("SELinux: Unable to register AVC LSM notifier callback\n");
7453 if (selinux_enforcing_boot)
7454 pr_debug("SELinux: Starting in enforcing mode\n");
7456 pr_debug("SELinux: Starting in permissive mode\n");
7458 fs_validate_description("selinux", selinux_fs_parameters);
7463 static void delayed_superblock_init(struct super_block *sb, void *unused)
7465 selinux_set_mnt_opts(sb, NULL, 0, NULL);
7468 void selinux_complete_init(void)
7470 pr_debug("SELinux: Completing initialization.\n");
7472 /* Set up any superblocks initialized prior to the policy load. */
7473 pr_debug("SELinux: Setting up existing superblocks.\n");
7474 iterate_supers(delayed_superblock_init, NULL);
7477 /* SELinux requires early initialization in order to label
7478 all processes and objects when they are created. */
7479 DEFINE_LSM(selinux) = {
7481 .flags = LSM_FLAG_LEGACY_MAJOR | LSM_FLAG_EXCLUSIVE,
7482 .enabled = &selinux_enabled_boot,
7483 .blobs = &selinux_blob_sizes,
7484 .init = selinux_init,
7487 #if defined(CONFIG_NETFILTER)
7489 static const struct nf_hook_ops selinux_nf_ops[] = {
7491 .hook = selinux_ipv4_postroute,
7493 .hooknum = NF_INET_POST_ROUTING,
7494 .priority = NF_IP_PRI_SELINUX_LAST,
7497 .hook = selinux_ipv4_forward,
7499 .hooknum = NF_INET_FORWARD,
7500 .priority = NF_IP_PRI_SELINUX_FIRST,
7503 .hook = selinux_ipv4_output,
7505 .hooknum = NF_INET_LOCAL_OUT,
7506 .priority = NF_IP_PRI_SELINUX_FIRST,
7508 #if IS_ENABLED(CONFIG_IPV6)
7510 .hook = selinux_ipv6_postroute,
7512 .hooknum = NF_INET_POST_ROUTING,
7513 .priority = NF_IP6_PRI_SELINUX_LAST,
7516 .hook = selinux_ipv6_forward,
7518 .hooknum = NF_INET_FORWARD,
7519 .priority = NF_IP6_PRI_SELINUX_FIRST,
7522 .hook = selinux_ipv6_output,
7524 .hooknum = NF_INET_LOCAL_OUT,
7525 .priority = NF_IP6_PRI_SELINUX_FIRST,
7530 static int __net_init selinux_nf_register(struct net *net)
7532 return nf_register_net_hooks(net, selinux_nf_ops,
7533 ARRAY_SIZE(selinux_nf_ops));
7536 static void __net_exit selinux_nf_unregister(struct net *net)
7538 nf_unregister_net_hooks(net, selinux_nf_ops,
7539 ARRAY_SIZE(selinux_nf_ops));
7542 static struct pernet_operations selinux_net_ops = {
7543 .init = selinux_nf_register,
7544 .exit = selinux_nf_unregister,
7547 static int __init selinux_nf_ip_init(void)
7551 if (!selinux_enabled_boot)
7554 pr_debug("SELinux: Registering netfilter hooks\n");
7556 err = register_pernet_subsys(&selinux_net_ops);
7558 panic("SELinux: register_pernet_subsys: error %d\n", err);
7562 __initcall(selinux_nf_ip_init);
7564 #ifdef CONFIG_SECURITY_SELINUX_DISABLE
7565 static void selinux_nf_ip_exit(void)
7567 pr_debug("SELinux: Unregistering netfilter hooks\n");
7569 unregister_pernet_subsys(&selinux_net_ops);
7573 #else /* CONFIG_NETFILTER */
7575 #ifdef CONFIG_SECURITY_SELINUX_DISABLE
7576 #define selinux_nf_ip_exit()
7579 #endif /* CONFIG_NETFILTER */
7581 #ifdef CONFIG_SECURITY_SELINUX_DISABLE
7582 int selinux_disable(struct selinux_state *state)
7584 if (selinux_initialized(state)) {
7585 /* Not permitted after initial policy load. */
7589 if (selinux_disabled(state)) {
7590 /* Only do this once. */
7594 selinux_mark_disabled(state);
7596 pr_info("SELinux: Disabled at runtime.\n");
7599 * Unregister netfilter hooks.
7600 * Must be done before security_delete_hooks() to avoid breaking
7603 selinux_nf_ip_exit();
7605 security_delete_hooks(selinux_hooks, ARRAY_SIZE(selinux_hooks));
7607 /* Try to destroy the avc node cache */
7610 /* Unregister selinuxfs. */