2 * NSA Security-Enhanced Linux (SELinux) security module
4 * This file contains the SELinux hook function implementations.
6 * Authors: Stephen Smalley, <sds@tycho.nsa.gov>
7 * Chris Vance, <cvance@nai.com>
8 * Wayne Salamon, <wsalamon@nai.com>
9 * James Morris <jmorris@redhat.com>
11 * Copyright (C) 2001,2002 Networks Associates Technology, Inc.
12 * Copyright (C) 2003-2008 Red Hat, Inc., James Morris <jmorris@redhat.com>
13 * Eric Paris <eparis@redhat.com>
14 * Copyright (C) 2004-2005 Trusted Computer Solutions, Inc.
15 * <dgoeddel@trustedcs.com>
16 * Copyright (C) 2006, 2007, 2009 Hewlett-Packard Development Company, L.P.
17 * Paul Moore <paul@paul-moore.com>
18 * Copyright (C) 2007 Hitachi Software Engineering Co., Ltd.
19 * Yuichi Nakamura <ynakam@hitachisoft.jp>
20 * Copyright (C) 2016 Mellanox Technologies
22 * This program is free software; you can redistribute it and/or modify
23 * it under the terms of the GNU General Public License version 2,
24 * as published by the Free Software Foundation.
27 #include <linux/init.h>
29 #include <linux/kernel.h>
30 #include <linux/tracehook.h>
31 #include <linux/errno.h>
32 #include <linux/sched/signal.h>
33 #include <linux/sched/task.h>
34 #include <linux/lsm_hooks.h>
35 #include <linux/xattr.h>
36 #include <linux/capability.h>
37 #include <linux/unistd.h>
39 #include <linux/mman.h>
40 #include <linux/slab.h>
41 #include <linux/pagemap.h>
42 #include <linux/proc_fs.h>
43 #include <linux/swap.h>
44 #include <linux/spinlock.h>
45 #include <linux/syscalls.h>
46 #include <linux/dcache.h>
47 #include <linux/file.h>
48 #include <linux/fdtable.h>
49 #include <linux/namei.h>
50 #include <linux/mount.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 <uapi/linux/mount.h>
103 struct selinux_state selinux_state;
105 /* SECMARK reference count */
106 static atomic_t selinux_secmark_refcount = ATOMIC_INIT(0);
108 #ifdef CONFIG_SECURITY_SELINUX_DEVELOP
109 static int selinux_enforcing_boot;
111 static int __init enforcing_setup(char *str)
113 unsigned long enforcing;
114 if (!kstrtoul(str, 0, &enforcing))
115 selinux_enforcing_boot = enforcing ? 1 : 0;
118 __setup("enforcing=", enforcing_setup);
120 #define selinux_enforcing_boot 1
123 int selinux_enabled __lsm_ro_after_init = 1;
124 #ifdef CONFIG_SECURITY_SELINUX_BOOTPARAM
125 static int __init selinux_enabled_setup(char *str)
127 unsigned long enabled;
128 if (!kstrtoul(str, 0, &enabled))
129 selinux_enabled = enabled ? 1 : 0;
132 __setup("selinux=", selinux_enabled_setup);
135 static unsigned int selinux_checkreqprot_boot =
136 CONFIG_SECURITY_SELINUX_CHECKREQPROT_VALUE;
138 static int __init checkreqprot_setup(char *str)
140 unsigned long checkreqprot;
142 if (!kstrtoul(str, 0, &checkreqprot))
143 selinux_checkreqprot_boot = checkreqprot ? 1 : 0;
146 __setup("checkreqprot=", checkreqprot_setup);
149 * selinux_secmark_enabled - Check to see if SECMARK is currently enabled
152 * This function checks the SECMARK reference counter to see if any SECMARK
153 * targets are currently configured, if the reference counter is greater than
154 * zero SECMARK is considered to be enabled. Returns true (1) if SECMARK is
155 * enabled, false (0) if SECMARK is disabled. If the always_check_network
156 * policy capability is enabled, SECMARK is always considered enabled.
159 static int selinux_secmark_enabled(void)
161 return (selinux_policycap_alwaysnetwork() ||
162 atomic_read(&selinux_secmark_refcount));
166 * selinux_peerlbl_enabled - Check to see if peer labeling is currently enabled
169 * This function checks if NetLabel or labeled IPSEC is enabled. Returns true
170 * (1) if any are enabled or false (0) if neither are enabled. If the
171 * always_check_network policy capability is enabled, peer labeling
172 * is always considered enabled.
175 static int selinux_peerlbl_enabled(void)
177 return (selinux_policycap_alwaysnetwork() ||
178 netlbl_enabled() || selinux_xfrm_enabled());
181 static int selinux_netcache_avc_callback(u32 event)
183 if (event == AVC_CALLBACK_RESET) {
192 static int selinux_lsm_notifier_avc_callback(u32 event)
194 if (event == AVC_CALLBACK_RESET) {
196 call_lsm_notifier(LSM_POLICY_CHANGE, NULL);
203 * initialise the security for the init task
205 static void cred_init_security(void)
207 struct cred *cred = (struct cred *) current->real_cred;
208 struct task_security_struct *tsec;
210 tsec = selinux_cred(cred);
211 tsec->osid = tsec->sid = SECINITSID_KERNEL;
215 * get the security ID of a set of credentials
217 static inline u32 cred_sid(const struct cred *cred)
219 const struct task_security_struct *tsec;
221 tsec = selinux_cred(cred);
226 * get the objective security ID of a task
228 static inline u32 task_sid(const struct task_struct *task)
233 sid = cred_sid(__task_cred(task));
238 /* Allocate and free functions for each kind of security blob. */
240 static int inode_alloc_security(struct inode *inode)
242 struct inode_security_struct *isec = selinux_inode(inode);
243 u32 sid = current_sid();
245 spin_lock_init(&isec->lock);
246 INIT_LIST_HEAD(&isec->list);
248 isec->sid = SECINITSID_UNLABELED;
249 isec->sclass = SECCLASS_FILE;
250 isec->task_sid = sid;
251 isec->initialized = LABEL_INVALID;
256 static int inode_doinit_with_dentry(struct inode *inode, struct dentry *opt_dentry);
259 * Try reloading inode security labels that have been marked as invalid. The
260 * @may_sleep parameter indicates when sleeping and thus reloading labels is
261 * allowed; when set to false, returns -ECHILD when the label is
262 * invalid. The @dentry parameter should be set to a dentry of the inode.
264 static int __inode_security_revalidate(struct inode *inode,
265 struct dentry *dentry,
268 struct inode_security_struct *isec = selinux_inode(inode);
270 might_sleep_if(may_sleep);
272 if (selinux_state.initialized &&
273 isec->initialized != LABEL_INITIALIZED) {
278 * Try reloading the inode security label. This will fail if
279 * @opt_dentry is NULL and no dentry for this inode can be
280 * found; in that case, continue using the old label.
282 inode_doinit_with_dentry(inode, dentry);
287 static struct inode_security_struct *inode_security_novalidate(struct inode *inode)
289 return selinux_inode(inode);
292 static struct inode_security_struct *inode_security_rcu(struct inode *inode, bool rcu)
296 error = __inode_security_revalidate(inode, NULL, !rcu);
298 return ERR_PTR(error);
299 return selinux_inode(inode);
303 * Get the security label of an inode.
305 static struct inode_security_struct *inode_security(struct inode *inode)
307 __inode_security_revalidate(inode, NULL, true);
308 return selinux_inode(inode);
311 static struct inode_security_struct *backing_inode_security_novalidate(struct dentry *dentry)
313 struct inode *inode = d_backing_inode(dentry);
315 return selinux_inode(inode);
319 * Get the security label of a dentry's backing inode.
321 static struct inode_security_struct *backing_inode_security(struct dentry *dentry)
323 struct inode *inode = d_backing_inode(dentry);
325 __inode_security_revalidate(inode, dentry, true);
326 return selinux_inode(inode);
329 static void inode_free_security(struct inode *inode)
331 struct inode_security_struct *isec = selinux_inode(inode);
332 struct superblock_security_struct *sbsec;
336 sbsec = inode->i_sb->s_security;
338 * As not all inode security structures are in a list, we check for
339 * empty list outside of the lock to make sure that we won't waste
340 * time taking a lock doing nothing.
342 * The list_del_init() function can be safely called more than once.
343 * It should not be possible for this function to be called with
344 * concurrent list_add(), but for better safety against future changes
345 * in the code, we use list_empty_careful() here.
347 if (!list_empty_careful(&isec->list)) {
348 spin_lock(&sbsec->isec_lock);
349 list_del_init(&isec->list);
350 spin_unlock(&sbsec->isec_lock);
354 static int file_alloc_security(struct file *file)
356 struct file_security_struct *fsec = selinux_file(file);
357 u32 sid = current_sid();
360 fsec->fown_sid = sid;
365 static int superblock_alloc_security(struct super_block *sb)
367 struct superblock_security_struct *sbsec;
369 sbsec = kzalloc(sizeof(struct superblock_security_struct), GFP_KERNEL);
373 mutex_init(&sbsec->lock);
374 INIT_LIST_HEAD(&sbsec->isec_head);
375 spin_lock_init(&sbsec->isec_lock);
377 sbsec->sid = SECINITSID_UNLABELED;
378 sbsec->def_sid = SECINITSID_FILE;
379 sbsec->mntpoint_sid = SECINITSID_UNLABELED;
380 sb->s_security = sbsec;
385 static void superblock_free_security(struct super_block *sb)
387 struct superblock_security_struct *sbsec = sb->s_security;
388 sb->s_security = NULL;
392 struct selinux_mnt_opts {
393 const char *fscontext, *context, *rootcontext, *defcontext;
396 static void selinux_free_mnt_opts(void *mnt_opts)
398 struct selinux_mnt_opts *opts = mnt_opts;
399 kfree(opts->fscontext);
400 kfree(opts->context);
401 kfree(opts->rootcontext);
402 kfree(opts->defcontext);
406 static inline int inode_doinit(struct inode *inode)
408 return inode_doinit_with_dentry(inode, NULL);
420 #define A(s, has_arg) {#s, sizeof(#s) - 1, Opt_##s, has_arg}
430 A(rootcontext, true),
435 static int match_opt_prefix(char *s, int l, char **arg)
439 for (i = 0; i < ARRAY_SIZE(tokens); i++) {
440 size_t len = tokens[i].len;
441 if (len > l || memcmp(s, tokens[i].name, len))
443 if (tokens[i].has_arg) {
444 if (len == l || s[len] != '=')
449 return tokens[i].opt;
454 #define SEL_MOUNT_FAIL_MSG "SELinux: duplicate or incompatible mount options\n"
456 static int may_context_mount_sb_relabel(u32 sid,
457 struct superblock_security_struct *sbsec,
458 const struct cred *cred)
460 const struct task_security_struct *tsec = selinux_cred(cred);
463 rc = avc_has_perm(&selinux_state,
464 tsec->sid, sbsec->sid, SECCLASS_FILESYSTEM,
465 FILESYSTEM__RELABELFROM, NULL);
469 rc = avc_has_perm(&selinux_state,
470 tsec->sid, sid, SECCLASS_FILESYSTEM,
471 FILESYSTEM__RELABELTO, NULL);
475 static int may_context_mount_inode_relabel(u32 sid,
476 struct superblock_security_struct *sbsec,
477 const struct cred *cred)
479 const struct task_security_struct *tsec = selinux_cred(cred);
481 rc = avc_has_perm(&selinux_state,
482 tsec->sid, sbsec->sid, SECCLASS_FILESYSTEM,
483 FILESYSTEM__RELABELFROM, NULL);
487 rc = avc_has_perm(&selinux_state,
488 sid, sbsec->sid, SECCLASS_FILESYSTEM,
489 FILESYSTEM__ASSOCIATE, NULL);
493 static int selinux_is_sblabel_mnt(struct super_block *sb)
495 struct superblock_security_struct *sbsec = sb->s_security;
497 return sbsec->behavior == SECURITY_FS_USE_XATTR ||
498 sbsec->behavior == SECURITY_FS_USE_TRANS ||
499 sbsec->behavior == SECURITY_FS_USE_TASK ||
500 sbsec->behavior == SECURITY_FS_USE_NATIVE ||
501 /* Special handling. Genfs but also in-core setxattr handler */
502 !strcmp(sb->s_type->name, "sysfs") ||
503 !strcmp(sb->s_type->name, "pstore") ||
504 !strcmp(sb->s_type->name, "debugfs") ||
505 !strcmp(sb->s_type->name, "tracefs") ||
506 !strcmp(sb->s_type->name, "rootfs") ||
507 (selinux_policycap_cgroupseclabel() &&
508 (!strcmp(sb->s_type->name, "cgroup") ||
509 !strcmp(sb->s_type->name, "cgroup2")));
512 static int sb_finish_set_opts(struct super_block *sb)
514 struct superblock_security_struct *sbsec = sb->s_security;
515 struct dentry *root = sb->s_root;
516 struct inode *root_inode = d_backing_inode(root);
519 if (sbsec->behavior == SECURITY_FS_USE_XATTR) {
520 /* Make sure that the xattr handler exists and that no
521 error other than -ENODATA is returned by getxattr on
522 the root directory. -ENODATA is ok, as this may be
523 the first boot of the SELinux kernel before we have
524 assigned xattr values to the filesystem. */
525 if (!(root_inode->i_opflags & IOP_XATTR)) {
526 pr_warn("SELinux: (dev %s, type %s) has no "
527 "xattr support\n", sb->s_id, sb->s_type->name);
532 rc = __vfs_getxattr(root, root_inode, XATTR_NAME_SELINUX, NULL, 0);
533 if (rc < 0 && rc != -ENODATA) {
534 if (rc == -EOPNOTSUPP)
535 pr_warn("SELinux: (dev %s, type "
536 "%s) has no security xattr handler\n",
537 sb->s_id, sb->s_type->name);
539 pr_warn("SELinux: (dev %s, type "
540 "%s) getxattr errno %d\n", sb->s_id,
541 sb->s_type->name, -rc);
546 sbsec->flags |= SE_SBINITIALIZED;
549 * Explicitly set or clear SBLABEL_MNT. It's not sufficient to simply
550 * leave the flag untouched because sb_clone_mnt_opts might be handing
551 * us a superblock that needs the flag to be cleared.
553 if (selinux_is_sblabel_mnt(sb))
554 sbsec->flags |= SBLABEL_MNT;
556 sbsec->flags &= ~SBLABEL_MNT;
558 /* Initialize the root inode. */
559 rc = inode_doinit_with_dentry(root_inode, root);
561 /* Initialize any other inodes associated with the superblock, e.g.
562 inodes created prior to initial policy load or inodes created
563 during get_sb by a pseudo filesystem that directly
565 spin_lock(&sbsec->isec_lock);
566 while (!list_empty(&sbsec->isec_head)) {
567 struct inode_security_struct *isec =
568 list_first_entry(&sbsec->isec_head,
569 struct inode_security_struct, list);
570 struct inode *inode = isec->inode;
571 list_del_init(&isec->list);
572 spin_unlock(&sbsec->isec_lock);
573 inode = igrab(inode);
575 if (!IS_PRIVATE(inode))
579 spin_lock(&sbsec->isec_lock);
581 spin_unlock(&sbsec->isec_lock);
586 static int bad_option(struct superblock_security_struct *sbsec, char flag,
587 u32 old_sid, u32 new_sid)
589 char mnt_flags = sbsec->flags & SE_MNTMASK;
591 /* check if the old mount command had the same options */
592 if (sbsec->flags & SE_SBINITIALIZED)
593 if (!(sbsec->flags & flag) ||
594 (old_sid != new_sid))
597 /* check if we were passed the same options twice,
598 * aka someone passed context=a,context=b
600 if (!(sbsec->flags & SE_SBINITIALIZED))
601 if (mnt_flags & flag)
606 static int parse_sid(struct super_block *sb, const char *s, u32 *sid)
608 int rc = security_context_str_to_sid(&selinux_state, s,
611 pr_warn("SELinux: security_context_str_to_sid"
612 "(%s) failed for (dev %s, type %s) errno=%d\n",
613 s, sb->s_id, sb->s_type->name, rc);
618 * Allow filesystems with binary mount data to explicitly set mount point
619 * labeling information.
621 static int selinux_set_mnt_opts(struct super_block *sb,
623 unsigned long kern_flags,
624 unsigned long *set_kern_flags)
626 const struct cred *cred = current_cred();
627 struct superblock_security_struct *sbsec = sb->s_security;
628 struct dentry *root = sbsec->sb->s_root;
629 struct selinux_mnt_opts *opts = mnt_opts;
630 struct inode_security_struct *root_isec;
631 u32 fscontext_sid = 0, context_sid = 0, rootcontext_sid = 0;
632 u32 defcontext_sid = 0;
635 mutex_lock(&sbsec->lock);
637 if (!selinux_state.initialized) {
639 /* Defer initialization until selinux_complete_init,
640 after the initial policy is loaded and the security
641 server is ready to handle calls. */
645 pr_warn("SELinux: Unable to set superblock options "
646 "before the security server is initialized\n");
649 if (kern_flags && !set_kern_flags) {
650 /* Specifying internal flags without providing a place to
651 * place the results is not allowed */
657 * Binary mount data FS will come through this function twice. Once
658 * from an explicit call and once from the generic calls from the vfs.
659 * Since the generic VFS calls will not contain any security mount data
660 * we need to skip the double mount verification.
662 * This does open a hole in which we will not notice if the first
663 * mount using this sb set explict options and a second mount using
664 * this sb does not set any security options. (The first options
665 * will be used for both mounts)
667 if ((sbsec->flags & SE_SBINITIALIZED) && (sb->s_type->fs_flags & FS_BINARY_MOUNTDATA)
671 root_isec = backing_inode_security_novalidate(root);
674 * parse the mount options, check if they are valid sids.
675 * also check if someone is trying to mount the same sb more
676 * than once with different security options.
679 if (opts->fscontext) {
680 rc = parse_sid(sb, opts->fscontext, &fscontext_sid);
683 if (bad_option(sbsec, FSCONTEXT_MNT, sbsec->sid,
685 goto out_double_mount;
686 sbsec->flags |= FSCONTEXT_MNT;
689 rc = parse_sid(sb, opts->context, &context_sid);
692 if (bad_option(sbsec, CONTEXT_MNT, sbsec->mntpoint_sid,
694 goto out_double_mount;
695 sbsec->flags |= CONTEXT_MNT;
697 if (opts->rootcontext) {
698 rc = parse_sid(sb, opts->rootcontext, &rootcontext_sid);
701 if (bad_option(sbsec, ROOTCONTEXT_MNT, root_isec->sid,
703 goto out_double_mount;
704 sbsec->flags |= ROOTCONTEXT_MNT;
706 if (opts->defcontext) {
707 rc = parse_sid(sb, opts->defcontext, &defcontext_sid);
710 if (bad_option(sbsec, DEFCONTEXT_MNT, sbsec->def_sid,
712 goto out_double_mount;
713 sbsec->flags |= DEFCONTEXT_MNT;
717 if (sbsec->flags & SE_SBINITIALIZED) {
718 /* previously mounted with options, but not on this attempt? */
719 if ((sbsec->flags & SE_MNTMASK) && !opts)
720 goto out_double_mount;
725 if (strcmp(sb->s_type->name, "proc") == 0)
726 sbsec->flags |= SE_SBPROC | SE_SBGENFS;
728 if (!strcmp(sb->s_type->name, "debugfs") ||
729 !strcmp(sb->s_type->name, "tracefs") ||
730 !strcmp(sb->s_type->name, "sysfs") ||
731 !strcmp(sb->s_type->name, "pstore") ||
732 !strcmp(sb->s_type->name, "cgroup") ||
733 !strcmp(sb->s_type->name, "cgroup2"))
734 sbsec->flags |= SE_SBGENFS;
736 if (!sbsec->behavior) {
738 * Determine the labeling behavior to use for this
741 rc = security_fs_use(&selinux_state, sb);
743 pr_warn("%s: security_fs_use(%s) returned %d\n",
744 __func__, sb->s_type->name, rc);
750 * If this is a user namespace mount and the filesystem type is not
751 * explicitly whitelisted, then no contexts are allowed on the command
752 * line and security labels must be ignored.
754 if (sb->s_user_ns != &init_user_ns &&
755 strcmp(sb->s_type->name, "tmpfs") &&
756 strcmp(sb->s_type->name, "ramfs") &&
757 strcmp(sb->s_type->name, "devpts")) {
758 if (context_sid || fscontext_sid || rootcontext_sid ||
763 if (sbsec->behavior == SECURITY_FS_USE_XATTR) {
764 sbsec->behavior = SECURITY_FS_USE_MNTPOINT;
765 rc = security_transition_sid(&selinux_state,
769 &sbsec->mntpoint_sid);
776 /* sets the context of the superblock for the fs being mounted. */
778 rc = may_context_mount_sb_relabel(fscontext_sid, sbsec, cred);
782 sbsec->sid = fscontext_sid;
786 * Switch to using mount point labeling behavior.
787 * sets the label used on all file below the mountpoint, and will set
788 * the superblock context if not already set.
790 if (kern_flags & SECURITY_LSM_NATIVE_LABELS && !context_sid) {
791 sbsec->behavior = SECURITY_FS_USE_NATIVE;
792 *set_kern_flags |= SECURITY_LSM_NATIVE_LABELS;
796 if (!fscontext_sid) {
797 rc = may_context_mount_sb_relabel(context_sid, sbsec,
801 sbsec->sid = context_sid;
803 rc = may_context_mount_inode_relabel(context_sid, sbsec,
808 if (!rootcontext_sid)
809 rootcontext_sid = context_sid;
811 sbsec->mntpoint_sid = context_sid;
812 sbsec->behavior = SECURITY_FS_USE_MNTPOINT;
815 if (rootcontext_sid) {
816 rc = may_context_mount_inode_relabel(rootcontext_sid, sbsec,
821 root_isec->sid = rootcontext_sid;
822 root_isec->initialized = LABEL_INITIALIZED;
825 if (defcontext_sid) {
826 if (sbsec->behavior != SECURITY_FS_USE_XATTR &&
827 sbsec->behavior != SECURITY_FS_USE_NATIVE) {
829 pr_warn("SELinux: defcontext option is "
830 "invalid for this filesystem type\n");
834 if (defcontext_sid != sbsec->def_sid) {
835 rc = may_context_mount_inode_relabel(defcontext_sid,
841 sbsec->def_sid = defcontext_sid;
845 rc = sb_finish_set_opts(sb);
847 mutex_unlock(&sbsec->lock);
851 pr_warn("SELinux: mount invalid. Same superblock, different "
852 "security settings for (dev %s, type %s)\n", sb->s_id,
857 static int selinux_cmp_sb_context(const struct super_block *oldsb,
858 const struct super_block *newsb)
860 struct superblock_security_struct *old = oldsb->s_security;
861 struct superblock_security_struct *new = newsb->s_security;
862 char oldflags = old->flags & SE_MNTMASK;
863 char newflags = new->flags & SE_MNTMASK;
865 if (oldflags != newflags)
867 if ((oldflags & FSCONTEXT_MNT) && old->sid != new->sid)
869 if ((oldflags & CONTEXT_MNT) && old->mntpoint_sid != new->mntpoint_sid)
871 if ((oldflags & DEFCONTEXT_MNT) && old->def_sid != new->def_sid)
873 if (oldflags & ROOTCONTEXT_MNT) {
874 struct inode_security_struct *oldroot = backing_inode_security(oldsb->s_root);
875 struct inode_security_struct *newroot = backing_inode_security(newsb->s_root);
876 if (oldroot->sid != newroot->sid)
881 pr_warn("SELinux: mount invalid. Same superblock, "
882 "different security settings for (dev %s, "
883 "type %s)\n", newsb->s_id, newsb->s_type->name);
887 static int selinux_sb_clone_mnt_opts(const struct super_block *oldsb,
888 struct super_block *newsb,
889 unsigned long kern_flags,
890 unsigned long *set_kern_flags)
893 const struct superblock_security_struct *oldsbsec = oldsb->s_security;
894 struct superblock_security_struct *newsbsec = newsb->s_security;
896 int set_fscontext = (oldsbsec->flags & FSCONTEXT_MNT);
897 int set_context = (oldsbsec->flags & CONTEXT_MNT);
898 int set_rootcontext = (oldsbsec->flags & ROOTCONTEXT_MNT);
901 * if the parent was able to be mounted it clearly had no special lsm
902 * mount options. thus we can safely deal with this superblock later
904 if (!selinux_state.initialized)
908 * Specifying internal flags without providing a place to
909 * place the results is not allowed.
911 if (kern_flags && !set_kern_flags)
914 /* how can we clone if the old one wasn't set up?? */
915 BUG_ON(!(oldsbsec->flags & SE_SBINITIALIZED));
917 /* if fs is reusing a sb, make sure that the contexts match */
918 if (newsbsec->flags & SE_SBINITIALIZED)
919 return selinux_cmp_sb_context(oldsb, newsb);
921 mutex_lock(&newsbsec->lock);
923 newsbsec->flags = oldsbsec->flags;
925 newsbsec->sid = oldsbsec->sid;
926 newsbsec->def_sid = oldsbsec->def_sid;
927 newsbsec->behavior = oldsbsec->behavior;
929 if (newsbsec->behavior == SECURITY_FS_USE_NATIVE &&
930 !(kern_flags & SECURITY_LSM_NATIVE_LABELS) && !set_context) {
931 rc = security_fs_use(&selinux_state, newsb);
936 if (kern_flags & SECURITY_LSM_NATIVE_LABELS && !set_context) {
937 newsbsec->behavior = SECURITY_FS_USE_NATIVE;
938 *set_kern_flags |= SECURITY_LSM_NATIVE_LABELS;
942 u32 sid = oldsbsec->mntpoint_sid;
946 if (!set_rootcontext) {
947 struct inode_security_struct *newisec = backing_inode_security(newsb->s_root);
950 newsbsec->mntpoint_sid = sid;
952 if (set_rootcontext) {
953 const struct inode_security_struct *oldisec = backing_inode_security(oldsb->s_root);
954 struct inode_security_struct *newisec = backing_inode_security(newsb->s_root);
956 newisec->sid = oldisec->sid;
959 sb_finish_set_opts(newsb);
961 mutex_unlock(&newsbsec->lock);
965 static int selinux_add_opt(int token, const char *s, void **mnt_opts)
967 struct selinux_mnt_opts *opts = *mnt_opts;
969 if (token == Opt_seclabel) /* eaten and completely ignored */
973 opts = kzalloc(sizeof(struct selinux_mnt_opts), GFP_KERNEL);
982 if (opts->context || opts->defcontext)
991 case Opt_rootcontext:
992 if (opts->rootcontext)
994 opts->rootcontext = s;
997 if (opts->context || opts->defcontext)
999 opts->defcontext = s;
1004 pr_warn(SEL_MOUNT_FAIL_MSG);
1008 static int selinux_add_mnt_opt(const char *option, const char *val, int len,
1011 int token = Opt_error;
1014 for (i = 0; i < ARRAY_SIZE(tokens); i++) {
1015 if (strcmp(option, tokens[i].name) == 0) {
1016 token = tokens[i].opt;
1021 if (token == Opt_error)
1024 if (token != Opt_seclabel)
1025 val = kmemdup_nul(val, len, GFP_KERNEL);
1026 rc = selinux_add_opt(token, val, mnt_opts);
1030 selinux_free_mnt_opts(*mnt_opts);
1037 static int show_sid(struct seq_file *m, u32 sid)
1039 char *context = NULL;
1043 rc = security_sid_to_context(&selinux_state, sid,
1046 bool has_comma = context && strchr(context, ',');
1050 seq_escape(m, context, "\"\n\\");
1058 static int selinux_sb_show_options(struct seq_file *m, struct super_block *sb)
1060 struct superblock_security_struct *sbsec = sb->s_security;
1063 if (!(sbsec->flags & SE_SBINITIALIZED))
1066 if (!selinux_state.initialized)
1069 if (sbsec->flags & FSCONTEXT_MNT) {
1071 seq_puts(m, FSCONTEXT_STR);
1072 rc = show_sid(m, sbsec->sid);
1076 if (sbsec->flags & CONTEXT_MNT) {
1078 seq_puts(m, CONTEXT_STR);
1079 rc = show_sid(m, sbsec->mntpoint_sid);
1083 if (sbsec->flags & DEFCONTEXT_MNT) {
1085 seq_puts(m, DEFCONTEXT_STR);
1086 rc = show_sid(m, sbsec->def_sid);
1090 if (sbsec->flags & ROOTCONTEXT_MNT) {
1091 struct dentry *root = sbsec->sb->s_root;
1092 struct inode_security_struct *isec = backing_inode_security(root);
1094 seq_puts(m, ROOTCONTEXT_STR);
1095 rc = show_sid(m, isec->sid);
1099 if (sbsec->flags & SBLABEL_MNT) {
1101 seq_puts(m, LABELSUPP_STR);
1106 static inline u16 inode_mode_to_security_class(umode_t mode)
1108 switch (mode & S_IFMT) {
1110 return SECCLASS_SOCK_FILE;
1112 return SECCLASS_LNK_FILE;
1114 return SECCLASS_FILE;
1116 return SECCLASS_BLK_FILE;
1118 return SECCLASS_DIR;
1120 return SECCLASS_CHR_FILE;
1122 return SECCLASS_FIFO_FILE;
1126 return SECCLASS_FILE;
1129 static inline int default_protocol_stream(int protocol)
1131 return (protocol == IPPROTO_IP || protocol == IPPROTO_TCP);
1134 static inline int default_protocol_dgram(int protocol)
1136 return (protocol == IPPROTO_IP || protocol == IPPROTO_UDP);
1139 static inline u16 socket_type_to_security_class(int family, int type, int protocol)
1141 int extsockclass = selinux_policycap_extsockclass();
1147 case SOCK_SEQPACKET:
1148 return SECCLASS_UNIX_STREAM_SOCKET;
1151 return SECCLASS_UNIX_DGRAM_SOCKET;
1158 case SOCK_SEQPACKET:
1159 if (default_protocol_stream(protocol))
1160 return SECCLASS_TCP_SOCKET;
1161 else if (extsockclass && protocol == IPPROTO_SCTP)
1162 return SECCLASS_SCTP_SOCKET;
1164 return SECCLASS_RAWIP_SOCKET;
1166 if (default_protocol_dgram(protocol))
1167 return SECCLASS_UDP_SOCKET;
1168 else if (extsockclass && (protocol == IPPROTO_ICMP ||
1169 protocol == IPPROTO_ICMPV6))
1170 return SECCLASS_ICMP_SOCKET;
1172 return SECCLASS_RAWIP_SOCKET;
1174 return SECCLASS_DCCP_SOCKET;
1176 return SECCLASS_RAWIP_SOCKET;
1182 return SECCLASS_NETLINK_ROUTE_SOCKET;
1183 case NETLINK_SOCK_DIAG:
1184 return SECCLASS_NETLINK_TCPDIAG_SOCKET;
1186 return SECCLASS_NETLINK_NFLOG_SOCKET;
1188 return SECCLASS_NETLINK_XFRM_SOCKET;
1189 case NETLINK_SELINUX:
1190 return SECCLASS_NETLINK_SELINUX_SOCKET;
1192 return SECCLASS_NETLINK_ISCSI_SOCKET;
1194 return SECCLASS_NETLINK_AUDIT_SOCKET;
1195 case NETLINK_FIB_LOOKUP:
1196 return SECCLASS_NETLINK_FIB_LOOKUP_SOCKET;
1197 case NETLINK_CONNECTOR:
1198 return SECCLASS_NETLINK_CONNECTOR_SOCKET;
1199 case NETLINK_NETFILTER:
1200 return SECCLASS_NETLINK_NETFILTER_SOCKET;
1201 case NETLINK_DNRTMSG:
1202 return SECCLASS_NETLINK_DNRT_SOCKET;
1203 case NETLINK_KOBJECT_UEVENT:
1204 return SECCLASS_NETLINK_KOBJECT_UEVENT_SOCKET;
1205 case NETLINK_GENERIC:
1206 return SECCLASS_NETLINK_GENERIC_SOCKET;
1207 case NETLINK_SCSITRANSPORT:
1208 return SECCLASS_NETLINK_SCSITRANSPORT_SOCKET;
1210 return SECCLASS_NETLINK_RDMA_SOCKET;
1211 case NETLINK_CRYPTO:
1212 return SECCLASS_NETLINK_CRYPTO_SOCKET;
1214 return SECCLASS_NETLINK_SOCKET;
1217 return SECCLASS_PACKET_SOCKET;
1219 return SECCLASS_KEY_SOCKET;
1221 return SECCLASS_APPLETALK_SOCKET;
1227 return SECCLASS_AX25_SOCKET;
1229 return SECCLASS_IPX_SOCKET;
1231 return SECCLASS_NETROM_SOCKET;
1233 return SECCLASS_ATMPVC_SOCKET;
1235 return SECCLASS_X25_SOCKET;
1237 return SECCLASS_ROSE_SOCKET;
1239 return SECCLASS_DECNET_SOCKET;
1241 return SECCLASS_ATMSVC_SOCKET;
1243 return SECCLASS_RDS_SOCKET;
1245 return SECCLASS_IRDA_SOCKET;
1247 return SECCLASS_PPPOX_SOCKET;
1249 return SECCLASS_LLC_SOCKET;
1251 return SECCLASS_CAN_SOCKET;
1253 return SECCLASS_TIPC_SOCKET;
1255 return SECCLASS_BLUETOOTH_SOCKET;
1257 return SECCLASS_IUCV_SOCKET;
1259 return SECCLASS_RXRPC_SOCKET;
1261 return SECCLASS_ISDN_SOCKET;
1263 return SECCLASS_PHONET_SOCKET;
1265 return SECCLASS_IEEE802154_SOCKET;
1267 return SECCLASS_CAIF_SOCKET;
1269 return SECCLASS_ALG_SOCKET;
1271 return SECCLASS_NFC_SOCKET;
1273 return SECCLASS_VSOCK_SOCKET;
1275 return SECCLASS_KCM_SOCKET;
1277 return SECCLASS_QIPCRTR_SOCKET;
1279 return SECCLASS_SMC_SOCKET;
1281 return SECCLASS_XDP_SOCKET;
1283 #error New address family defined, please update this function.
1288 return SECCLASS_SOCKET;
1291 static int selinux_genfs_get_sid(struct dentry *dentry,
1297 struct super_block *sb = dentry->d_sb;
1298 char *buffer, *path;
1300 buffer = (char *)__get_free_page(GFP_KERNEL);
1304 path = dentry_path_raw(dentry, buffer, PAGE_SIZE);
1308 if (flags & SE_SBPROC) {
1309 /* each process gets a /proc/PID/ entry. Strip off the
1310 * PID part to get a valid selinux labeling.
1311 * e.g. /proc/1/net/rpc/nfs -> /net/rpc/nfs */
1312 while (path[1] >= '0' && path[1] <= '9') {
1317 rc = security_genfs_sid(&selinux_state, sb->s_type->name,
1319 if (rc == -ENOENT) {
1320 /* No match in policy, mark as unlabeled. */
1321 *sid = SECINITSID_UNLABELED;
1325 free_page((unsigned long)buffer);
1329 /* The inode's security attributes must be initialized before first use. */
1330 static int inode_doinit_with_dentry(struct inode *inode, struct dentry *opt_dentry)
1332 struct superblock_security_struct *sbsec = NULL;
1333 struct inode_security_struct *isec = selinux_inode(inode);
1334 u32 task_sid, sid = 0;
1336 struct dentry *dentry;
1337 #define INITCONTEXTLEN 255
1338 char *context = NULL;
1342 if (isec->initialized == LABEL_INITIALIZED)
1345 spin_lock(&isec->lock);
1346 if (isec->initialized == LABEL_INITIALIZED)
1349 if (isec->sclass == SECCLASS_FILE)
1350 isec->sclass = inode_mode_to_security_class(inode->i_mode);
1352 sbsec = inode->i_sb->s_security;
1353 if (!(sbsec->flags & SE_SBINITIALIZED)) {
1354 /* Defer initialization until selinux_complete_init,
1355 after the initial policy is loaded and the security
1356 server is ready to handle calls. */
1357 spin_lock(&sbsec->isec_lock);
1358 if (list_empty(&isec->list))
1359 list_add(&isec->list, &sbsec->isec_head);
1360 spin_unlock(&sbsec->isec_lock);
1364 sclass = isec->sclass;
1365 task_sid = isec->task_sid;
1367 isec->initialized = LABEL_PENDING;
1368 spin_unlock(&isec->lock);
1370 switch (sbsec->behavior) {
1371 case SECURITY_FS_USE_NATIVE:
1373 case SECURITY_FS_USE_XATTR:
1374 if (!(inode->i_opflags & IOP_XATTR)) {
1375 sid = sbsec->def_sid;
1378 /* Need a dentry, since the xattr API requires one.
1379 Life would be simpler if we could just pass the inode. */
1381 /* Called from d_instantiate or d_splice_alias. */
1382 dentry = dget(opt_dentry);
1385 * Called from selinux_complete_init, try to find a dentry.
1386 * Some filesystems really want a connected one, so try
1387 * that first. We could split SECURITY_FS_USE_XATTR in
1388 * two, depending upon that...
1390 dentry = d_find_alias(inode);
1392 dentry = d_find_any_alias(inode);
1396 * this is can be hit on boot when a file is accessed
1397 * before the policy is loaded. When we load policy we
1398 * may find inodes that have no dentry on the
1399 * sbsec->isec_head list. No reason to complain as these
1400 * will get fixed up the next time we go through
1401 * inode_doinit with a dentry, before these inodes could
1402 * be used again by userspace.
1407 len = INITCONTEXTLEN;
1408 context = kmalloc(len+1, GFP_NOFS);
1414 context[len] = '\0';
1415 rc = __vfs_getxattr(dentry, inode, XATTR_NAME_SELINUX, context, len);
1416 if (rc == -ERANGE) {
1419 /* Need a larger buffer. Query for the right size. */
1420 rc = __vfs_getxattr(dentry, inode, XATTR_NAME_SELINUX, NULL, 0);
1426 context = kmalloc(len+1, GFP_NOFS);
1432 context[len] = '\0';
1433 rc = __vfs_getxattr(dentry, inode, XATTR_NAME_SELINUX, context, len);
1437 if (rc != -ENODATA) {
1438 pr_warn("SELinux: %s: getxattr returned "
1439 "%d for dev=%s ino=%ld\n", __func__,
1440 -rc, inode->i_sb->s_id, inode->i_ino);
1444 /* Map ENODATA to the default file SID */
1445 sid = sbsec->def_sid;
1448 rc = security_context_to_sid_default(&selinux_state,
1453 char *dev = inode->i_sb->s_id;
1454 unsigned long ino = inode->i_ino;
1456 if (rc == -EINVAL) {
1457 if (printk_ratelimit())
1458 pr_notice("SELinux: inode=%lu on dev=%s was found to have an invalid "
1459 "context=%s. This indicates you may need to relabel the inode or the "
1460 "filesystem in question.\n", ino, dev, context);
1462 pr_warn("SELinux: %s: context_to_sid(%s) "
1463 "returned %d for dev=%s ino=%ld\n",
1464 __func__, context, -rc, dev, ino);
1467 /* Leave with the unlabeled SID */
1474 case SECURITY_FS_USE_TASK:
1477 case SECURITY_FS_USE_TRANS:
1478 /* Default to the fs SID. */
1481 /* Try to obtain a transition SID. */
1482 rc = security_transition_sid(&selinux_state, task_sid, sid,
1483 sclass, NULL, &sid);
1487 case SECURITY_FS_USE_MNTPOINT:
1488 sid = sbsec->mntpoint_sid;
1491 /* Default to the fs superblock SID. */
1494 if ((sbsec->flags & SE_SBGENFS) && !S_ISLNK(inode->i_mode)) {
1495 /* We must have a dentry to determine the label on
1498 /* Called from d_instantiate or
1499 * d_splice_alias. */
1500 dentry = dget(opt_dentry);
1502 /* Called from selinux_complete_init, try to
1503 * find a dentry. Some filesystems really want
1504 * a connected one, so try that first.
1506 dentry = d_find_alias(inode);
1508 dentry = d_find_any_alias(inode);
1511 * This 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
1515 * these will get fixed up the next time we go through
1516 * inode_doinit() with a dentry, before these inodes
1517 * could be used again by userspace.
1521 rc = selinux_genfs_get_sid(dentry, sclass,
1522 sbsec->flags, &sid);
1531 spin_lock(&isec->lock);
1532 if (isec->initialized == LABEL_PENDING) {
1534 isec->initialized = LABEL_INVALID;
1538 isec->initialized = LABEL_INITIALIZED;
1543 spin_unlock(&isec->lock);
1547 /* Convert a Linux signal to an access vector. */
1548 static inline u32 signal_to_av(int sig)
1554 /* Commonly granted from child to parent. */
1555 perm = PROCESS__SIGCHLD;
1558 /* Cannot be caught or ignored */
1559 perm = PROCESS__SIGKILL;
1562 /* Cannot be caught or ignored */
1563 perm = PROCESS__SIGSTOP;
1566 /* All other signals. */
1567 perm = PROCESS__SIGNAL;
1574 #if CAP_LAST_CAP > 63
1575 #error Fix SELinux to handle capabilities > 63.
1578 /* Check whether a task is allowed to use a capability. */
1579 static int cred_has_capability(const struct cred *cred,
1580 int cap, unsigned int opts, bool initns)
1582 struct common_audit_data ad;
1583 struct av_decision avd;
1585 u32 sid = cred_sid(cred);
1586 u32 av = CAP_TO_MASK(cap);
1589 ad.type = LSM_AUDIT_DATA_CAP;
1592 switch (CAP_TO_INDEX(cap)) {
1594 sclass = initns ? SECCLASS_CAPABILITY : SECCLASS_CAP_USERNS;
1597 sclass = initns ? SECCLASS_CAPABILITY2 : SECCLASS_CAP2_USERNS;
1600 pr_err("SELinux: out of range capability %d\n", cap);
1605 rc = avc_has_perm_noaudit(&selinux_state,
1606 sid, sid, sclass, av, 0, &avd);
1607 if (!(opts & CAP_OPT_NOAUDIT)) {
1608 int rc2 = avc_audit(&selinux_state,
1609 sid, sid, sclass, av, &avd, rc, &ad, 0);
1616 /* Check whether a task has a particular permission to an inode.
1617 The 'adp' parameter is optional and allows other audit
1618 data to be passed (e.g. the dentry). */
1619 static int inode_has_perm(const struct cred *cred,
1620 struct inode *inode,
1622 struct common_audit_data *adp)
1624 struct inode_security_struct *isec;
1627 validate_creds(cred);
1629 if (unlikely(IS_PRIVATE(inode)))
1632 sid = cred_sid(cred);
1633 isec = selinux_inode(inode);
1635 return avc_has_perm(&selinux_state,
1636 sid, isec->sid, isec->sclass, perms, adp);
1639 /* Same as inode_has_perm, but pass explicit audit data containing
1640 the dentry to help the auditing code to more easily generate the
1641 pathname if needed. */
1642 static inline int dentry_has_perm(const struct cred *cred,
1643 struct dentry *dentry,
1646 struct inode *inode = d_backing_inode(dentry);
1647 struct common_audit_data ad;
1649 ad.type = LSM_AUDIT_DATA_DENTRY;
1650 ad.u.dentry = dentry;
1651 __inode_security_revalidate(inode, dentry, true);
1652 return inode_has_perm(cred, inode, av, &ad);
1655 /* Same as inode_has_perm, but pass explicit audit data containing
1656 the path to help the auditing code to more easily generate the
1657 pathname if needed. */
1658 static inline int path_has_perm(const struct cred *cred,
1659 const struct path *path,
1662 struct inode *inode = d_backing_inode(path->dentry);
1663 struct common_audit_data ad;
1665 ad.type = LSM_AUDIT_DATA_PATH;
1667 __inode_security_revalidate(inode, path->dentry, true);
1668 return inode_has_perm(cred, inode, av, &ad);
1671 /* Same as path_has_perm, but uses the inode from the file struct. */
1672 static inline int file_path_has_perm(const struct cred *cred,
1676 struct common_audit_data ad;
1678 ad.type = LSM_AUDIT_DATA_FILE;
1680 return inode_has_perm(cred, file_inode(file), av, &ad);
1683 #ifdef CONFIG_BPF_SYSCALL
1684 static int bpf_fd_pass(struct file *file, u32 sid);
1687 /* Check whether a task can use an open file descriptor to
1688 access an inode in a given way. Check access to the
1689 descriptor itself, and then use dentry_has_perm to
1690 check a particular permission to the file.
1691 Access to the descriptor is implicitly granted if it
1692 has the same SID as the process. If av is zero, then
1693 access to the file is not checked, e.g. for cases
1694 where only the descriptor is affected like seek. */
1695 static int file_has_perm(const struct cred *cred,
1699 struct file_security_struct *fsec = selinux_file(file);
1700 struct inode *inode = file_inode(file);
1701 struct common_audit_data ad;
1702 u32 sid = cred_sid(cred);
1705 ad.type = LSM_AUDIT_DATA_FILE;
1708 if (sid != fsec->sid) {
1709 rc = avc_has_perm(&selinux_state,
1718 #ifdef CONFIG_BPF_SYSCALL
1719 rc = bpf_fd_pass(file, cred_sid(cred));
1724 /* av is zero if only checking access to the descriptor. */
1727 rc = inode_has_perm(cred, inode, av, &ad);
1734 * Determine the label for an inode that might be unioned.
1737 selinux_determine_inode_label(const struct task_security_struct *tsec,
1739 const struct qstr *name, u16 tclass,
1742 const struct superblock_security_struct *sbsec = dir->i_sb->s_security;
1744 if ((sbsec->flags & SE_SBINITIALIZED) &&
1745 (sbsec->behavior == SECURITY_FS_USE_MNTPOINT)) {
1746 *_new_isid = sbsec->mntpoint_sid;
1747 } else if ((sbsec->flags & SBLABEL_MNT) &&
1749 *_new_isid = tsec->create_sid;
1751 const struct inode_security_struct *dsec = inode_security(dir);
1752 return security_transition_sid(&selinux_state, tsec->sid,
1760 /* Check whether a task can create a file. */
1761 static int may_create(struct inode *dir,
1762 struct dentry *dentry,
1765 const struct task_security_struct *tsec = selinux_cred(current_cred());
1766 struct inode_security_struct *dsec;
1767 struct superblock_security_struct *sbsec;
1769 struct common_audit_data ad;
1772 dsec = inode_security(dir);
1773 sbsec = dir->i_sb->s_security;
1777 ad.type = LSM_AUDIT_DATA_DENTRY;
1778 ad.u.dentry = dentry;
1780 rc = avc_has_perm(&selinux_state,
1781 sid, dsec->sid, SECCLASS_DIR,
1782 DIR__ADD_NAME | DIR__SEARCH,
1787 rc = selinux_determine_inode_label(selinux_cred(current_cred()), dir,
1788 &dentry->d_name, tclass, &newsid);
1792 rc = avc_has_perm(&selinux_state,
1793 sid, newsid, tclass, FILE__CREATE, &ad);
1797 return avc_has_perm(&selinux_state,
1799 SECCLASS_FILESYSTEM,
1800 FILESYSTEM__ASSOCIATE, &ad);
1804 #define MAY_UNLINK 1
1807 /* Check whether a task can link, unlink, or rmdir a file/directory. */
1808 static int may_link(struct inode *dir,
1809 struct dentry *dentry,
1813 struct inode_security_struct *dsec, *isec;
1814 struct common_audit_data ad;
1815 u32 sid = current_sid();
1819 dsec = inode_security(dir);
1820 isec = backing_inode_security(dentry);
1822 ad.type = LSM_AUDIT_DATA_DENTRY;
1823 ad.u.dentry = dentry;
1826 av |= (kind ? DIR__REMOVE_NAME : DIR__ADD_NAME);
1827 rc = avc_has_perm(&selinux_state,
1828 sid, dsec->sid, SECCLASS_DIR, av, &ad);
1843 pr_warn("SELinux: %s: unrecognized kind %d\n",
1848 rc = avc_has_perm(&selinux_state,
1849 sid, isec->sid, isec->sclass, av, &ad);
1853 static inline int may_rename(struct inode *old_dir,
1854 struct dentry *old_dentry,
1855 struct inode *new_dir,
1856 struct dentry *new_dentry)
1858 struct inode_security_struct *old_dsec, *new_dsec, *old_isec, *new_isec;
1859 struct common_audit_data ad;
1860 u32 sid = current_sid();
1862 int old_is_dir, new_is_dir;
1865 old_dsec = inode_security(old_dir);
1866 old_isec = backing_inode_security(old_dentry);
1867 old_is_dir = d_is_dir(old_dentry);
1868 new_dsec = inode_security(new_dir);
1870 ad.type = LSM_AUDIT_DATA_DENTRY;
1872 ad.u.dentry = old_dentry;
1873 rc = avc_has_perm(&selinux_state,
1874 sid, old_dsec->sid, SECCLASS_DIR,
1875 DIR__REMOVE_NAME | DIR__SEARCH, &ad);
1878 rc = avc_has_perm(&selinux_state,
1880 old_isec->sclass, FILE__RENAME, &ad);
1883 if (old_is_dir && new_dir != old_dir) {
1884 rc = avc_has_perm(&selinux_state,
1886 old_isec->sclass, DIR__REPARENT, &ad);
1891 ad.u.dentry = new_dentry;
1892 av = DIR__ADD_NAME | DIR__SEARCH;
1893 if (d_is_positive(new_dentry))
1894 av |= DIR__REMOVE_NAME;
1895 rc = avc_has_perm(&selinux_state,
1896 sid, new_dsec->sid, SECCLASS_DIR, av, &ad);
1899 if (d_is_positive(new_dentry)) {
1900 new_isec = backing_inode_security(new_dentry);
1901 new_is_dir = d_is_dir(new_dentry);
1902 rc = avc_has_perm(&selinux_state,
1905 (new_is_dir ? DIR__RMDIR : FILE__UNLINK), &ad);
1913 /* Check whether a task can perform a filesystem operation. */
1914 static int superblock_has_perm(const struct cred *cred,
1915 struct super_block *sb,
1917 struct common_audit_data *ad)
1919 struct superblock_security_struct *sbsec;
1920 u32 sid = cred_sid(cred);
1922 sbsec = sb->s_security;
1923 return avc_has_perm(&selinux_state,
1924 sid, sbsec->sid, SECCLASS_FILESYSTEM, perms, ad);
1927 /* Convert a Linux mode and permission mask to an access vector. */
1928 static inline u32 file_mask_to_av(int mode, int mask)
1932 if (!S_ISDIR(mode)) {
1933 if (mask & MAY_EXEC)
1934 av |= FILE__EXECUTE;
1935 if (mask & MAY_READ)
1938 if (mask & MAY_APPEND)
1940 else if (mask & MAY_WRITE)
1944 if (mask & MAY_EXEC)
1946 if (mask & MAY_WRITE)
1948 if (mask & MAY_READ)
1955 /* Convert a Linux file to an access vector. */
1956 static inline u32 file_to_av(struct file *file)
1960 if (file->f_mode & FMODE_READ)
1962 if (file->f_mode & FMODE_WRITE) {
1963 if (file->f_flags & O_APPEND)
1970 * Special file opened with flags 3 for ioctl-only use.
1979 * Convert a file to an access vector and include the correct open
1982 static inline u32 open_file_to_av(struct file *file)
1984 u32 av = file_to_av(file);
1985 struct inode *inode = file_inode(file);
1987 if (selinux_policycap_openperm() &&
1988 inode->i_sb->s_magic != SOCKFS_MAGIC)
1994 /* Hook functions begin here. */
1996 static int selinux_binder_set_context_mgr(struct task_struct *mgr)
1998 u32 mysid = current_sid();
1999 u32 mgrsid = task_sid(mgr);
2001 return avc_has_perm(&selinux_state,
2002 mysid, mgrsid, SECCLASS_BINDER,
2003 BINDER__SET_CONTEXT_MGR, NULL);
2006 static int selinux_binder_transaction(struct task_struct *from,
2007 struct task_struct *to)
2009 u32 mysid = current_sid();
2010 u32 fromsid = task_sid(from);
2011 u32 tosid = task_sid(to);
2014 if (mysid != fromsid) {
2015 rc = avc_has_perm(&selinux_state,
2016 mysid, fromsid, SECCLASS_BINDER,
2017 BINDER__IMPERSONATE, NULL);
2022 return avc_has_perm(&selinux_state,
2023 fromsid, tosid, SECCLASS_BINDER, BINDER__CALL,
2027 static int selinux_binder_transfer_binder(struct task_struct *from,
2028 struct task_struct *to)
2030 u32 fromsid = task_sid(from);
2031 u32 tosid = task_sid(to);
2033 return avc_has_perm(&selinux_state,
2034 fromsid, tosid, SECCLASS_BINDER, BINDER__TRANSFER,
2038 static int selinux_binder_transfer_file(struct task_struct *from,
2039 struct task_struct *to,
2042 u32 sid = task_sid(to);
2043 struct file_security_struct *fsec = selinux_file(file);
2044 struct dentry *dentry = file->f_path.dentry;
2045 struct inode_security_struct *isec;
2046 struct common_audit_data ad;
2049 ad.type = LSM_AUDIT_DATA_PATH;
2050 ad.u.path = file->f_path;
2052 if (sid != fsec->sid) {
2053 rc = avc_has_perm(&selinux_state,
2062 #ifdef CONFIG_BPF_SYSCALL
2063 rc = bpf_fd_pass(file, sid);
2068 if (unlikely(IS_PRIVATE(d_backing_inode(dentry))))
2071 isec = backing_inode_security(dentry);
2072 return avc_has_perm(&selinux_state,
2073 sid, isec->sid, isec->sclass, file_to_av(file),
2077 static int selinux_ptrace_access_check(struct task_struct *child,
2080 u32 sid = current_sid();
2081 u32 csid = task_sid(child);
2083 if (mode & PTRACE_MODE_READ)
2084 return avc_has_perm(&selinux_state,
2085 sid, csid, SECCLASS_FILE, FILE__READ, NULL);
2087 return avc_has_perm(&selinux_state,
2088 sid, csid, SECCLASS_PROCESS, PROCESS__PTRACE, NULL);
2091 static int selinux_ptrace_traceme(struct task_struct *parent)
2093 return avc_has_perm(&selinux_state,
2094 task_sid(parent), current_sid(), SECCLASS_PROCESS,
2095 PROCESS__PTRACE, NULL);
2098 static int selinux_capget(struct task_struct *target, kernel_cap_t *effective,
2099 kernel_cap_t *inheritable, kernel_cap_t *permitted)
2101 return avc_has_perm(&selinux_state,
2102 current_sid(), task_sid(target), SECCLASS_PROCESS,
2103 PROCESS__GETCAP, NULL);
2106 static int selinux_capset(struct cred *new, const struct cred *old,
2107 const kernel_cap_t *effective,
2108 const kernel_cap_t *inheritable,
2109 const kernel_cap_t *permitted)
2111 return avc_has_perm(&selinux_state,
2112 cred_sid(old), cred_sid(new), SECCLASS_PROCESS,
2113 PROCESS__SETCAP, NULL);
2117 * (This comment used to live with the selinux_task_setuid hook,
2118 * which was removed).
2120 * Since setuid only affects the current process, and since the SELinux
2121 * controls are not based on the Linux identity attributes, SELinux does not
2122 * need to control this operation. However, SELinux does control the use of
2123 * the CAP_SETUID and CAP_SETGID capabilities using the capable hook.
2126 static int selinux_capable(const struct cred *cred, struct user_namespace *ns,
2127 int cap, unsigned int opts)
2129 return cred_has_capability(cred, cap, opts, ns == &init_user_ns);
2132 static int selinux_quotactl(int cmds, int type, int id, struct super_block *sb)
2134 const struct cred *cred = current_cred();
2146 rc = superblock_has_perm(cred, sb, FILESYSTEM__QUOTAMOD, NULL);
2151 rc = superblock_has_perm(cred, sb, FILESYSTEM__QUOTAGET, NULL);
2154 rc = 0; /* let the kernel handle invalid cmds */
2160 static int selinux_quota_on(struct dentry *dentry)
2162 const struct cred *cred = current_cred();
2164 return dentry_has_perm(cred, dentry, FILE__QUOTAON);
2167 static int selinux_syslog(int type)
2170 case SYSLOG_ACTION_READ_ALL: /* Read last kernel messages */
2171 case SYSLOG_ACTION_SIZE_BUFFER: /* Return size of the log buffer */
2172 return avc_has_perm(&selinux_state,
2173 current_sid(), SECINITSID_KERNEL,
2174 SECCLASS_SYSTEM, SYSTEM__SYSLOG_READ, NULL);
2175 case SYSLOG_ACTION_CONSOLE_OFF: /* Disable logging to console */
2176 case SYSLOG_ACTION_CONSOLE_ON: /* Enable logging to console */
2177 /* Set level of messages printed to console */
2178 case SYSLOG_ACTION_CONSOLE_LEVEL:
2179 return avc_has_perm(&selinux_state,
2180 current_sid(), SECINITSID_KERNEL,
2181 SECCLASS_SYSTEM, SYSTEM__SYSLOG_CONSOLE,
2184 /* All other syslog types */
2185 return avc_has_perm(&selinux_state,
2186 current_sid(), SECINITSID_KERNEL,
2187 SECCLASS_SYSTEM, SYSTEM__SYSLOG_MOD, NULL);
2191 * Check that a process has enough memory to allocate a new virtual
2192 * mapping. 0 means there is enough memory for the allocation to
2193 * succeed and -ENOMEM implies there is not.
2195 * Do not audit the selinux permission check, as this is applied to all
2196 * processes that allocate mappings.
2198 static int selinux_vm_enough_memory(struct mm_struct *mm, long pages)
2200 int rc, cap_sys_admin = 0;
2202 rc = cred_has_capability(current_cred(), CAP_SYS_ADMIN,
2203 CAP_OPT_NOAUDIT, true);
2207 return cap_sys_admin;
2210 /* binprm security operations */
2212 static u32 ptrace_parent_sid(void)
2215 struct task_struct *tracer;
2218 tracer = ptrace_parent(current);
2220 sid = task_sid(tracer);
2226 static int check_nnp_nosuid(const struct linux_binprm *bprm,
2227 const struct task_security_struct *old_tsec,
2228 const struct task_security_struct *new_tsec)
2230 int nnp = (bprm->unsafe & LSM_UNSAFE_NO_NEW_PRIVS);
2231 int nosuid = !mnt_may_suid(bprm->file->f_path.mnt);
2235 if (!nnp && !nosuid)
2236 return 0; /* neither NNP nor nosuid */
2238 if (new_tsec->sid == old_tsec->sid)
2239 return 0; /* No change in credentials */
2242 * If the policy enables the nnp_nosuid_transition policy capability,
2243 * then we permit transitions under NNP or nosuid if the
2244 * policy allows the corresponding permission between
2245 * the old and new contexts.
2247 if (selinux_policycap_nnp_nosuid_transition()) {
2250 av |= PROCESS2__NNP_TRANSITION;
2252 av |= PROCESS2__NOSUID_TRANSITION;
2253 rc = avc_has_perm(&selinux_state,
2254 old_tsec->sid, new_tsec->sid,
2255 SECCLASS_PROCESS2, av, NULL);
2261 * We also permit NNP or nosuid transitions to bounded SIDs,
2262 * i.e. SIDs that are guaranteed to only be allowed a subset
2263 * of the permissions of the current SID.
2265 rc = security_bounded_transition(&selinux_state, old_tsec->sid,
2271 * On failure, preserve the errno values for NNP vs nosuid.
2272 * NNP: Operation not permitted for caller.
2273 * nosuid: Permission denied to file.
2280 static int selinux_bprm_set_creds(struct linux_binprm *bprm)
2282 const struct task_security_struct *old_tsec;
2283 struct task_security_struct *new_tsec;
2284 struct inode_security_struct *isec;
2285 struct common_audit_data ad;
2286 struct inode *inode = file_inode(bprm->file);
2289 /* SELinux context only depends on initial program or script and not
2290 * the script interpreter */
2291 if (bprm->called_set_creds)
2294 old_tsec = selinux_cred(current_cred());
2295 new_tsec = selinux_cred(bprm->cred);
2296 isec = inode_security(inode);
2298 /* Default to the current task SID. */
2299 new_tsec->sid = old_tsec->sid;
2300 new_tsec->osid = old_tsec->sid;
2302 /* Reset fs, key, and sock SIDs on execve. */
2303 new_tsec->create_sid = 0;
2304 new_tsec->keycreate_sid = 0;
2305 new_tsec->sockcreate_sid = 0;
2307 if (old_tsec->exec_sid) {
2308 new_tsec->sid = old_tsec->exec_sid;
2309 /* Reset exec SID on execve. */
2310 new_tsec->exec_sid = 0;
2312 /* Fail on NNP or nosuid if not an allowed transition. */
2313 rc = check_nnp_nosuid(bprm, old_tsec, new_tsec);
2317 /* Check for a default transition on this program. */
2318 rc = security_transition_sid(&selinux_state, old_tsec->sid,
2319 isec->sid, SECCLASS_PROCESS, NULL,
2325 * Fallback to old SID on NNP or nosuid if not an allowed
2328 rc = check_nnp_nosuid(bprm, old_tsec, new_tsec);
2330 new_tsec->sid = old_tsec->sid;
2333 ad.type = LSM_AUDIT_DATA_FILE;
2334 ad.u.file = bprm->file;
2336 if (new_tsec->sid == old_tsec->sid) {
2337 rc = avc_has_perm(&selinux_state,
2338 old_tsec->sid, isec->sid,
2339 SECCLASS_FILE, FILE__EXECUTE_NO_TRANS, &ad);
2343 /* Check permissions for the transition. */
2344 rc = avc_has_perm(&selinux_state,
2345 old_tsec->sid, new_tsec->sid,
2346 SECCLASS_PROCESS, PROCESS__TRANSITION, &ad);
2350 rc = avc_has_perm(&selinux_state,
2351 new_tsec->sid, isec->sid,
2352 SECCLASS_FILE, FILE__ENTRYPOINT, &ad);
2356 /* Check for shared state */
2357 if (bprm->unsafe & LSM_UNSAFE_SHARE) {
2358 rc = avc_has_perm(&selinux_state,
2359 old_tsec->sid, new_tsec->sid,
2360 SECCLASS_PROCESS, PROCESS__SHARE,
2366 /* Make sure that anyone attempting to ptrace over a task that
2367 * changes its SID has the appropriate permit */
2368 if (bprm->unsafe & LSM_UNSAFE_PTRACE) {
2369 u32 ptsid = ptrace_parent_sid();
2371 rc = avc_has_perm(&selinux_state,
2372 ptsid, new_tsec->sid,
2374 PROCESS__PTRACE, NULL);
2380 /* Clear any possibly unsafe personality bits on exec: */
2381 bprm->per_clear |= PER_CLEAR_ON_SETID;
2383 /* Enable secure mode for SIDs transitions unless
2384 the noatsecure permission is granted between
2385 the two SIDs, i.e. ahp returns 0. */
2386 rc = avc_has_perm(&selinux_state,
2387 old_tsec->sid, new_tsec->sid,
2388 SECCLASS_PROCESS, PROCESS__NOATSECURE,
2390 bprm->secureexec |= !!rc;
2396 static int match_file(const void *p, struct file *file, unsigned fd)
2398 return file_has_perm(p, file, file_to_av(file)) ? fd + 1 : 0;
2401 /* Derived from fs/exec.c:flush_old_files. */
2402 static inline void flush_unauthorized_files(const struct cred *cred,
2403 struct files_struct *files)
2405 struct file *file, *devnull = NULL;
2406 struct tty_struct *tty;
2410 tty = get_current_tty();
2412 spin_lock(&tty->files_lock);
2413 if (!list_empty(&tty->tty_files)) {
2414 struct tty_file_private *file_priv;
2416 /* Revalidate access to controlling tty.
2417 Use file_path_has_perm on the tty path directly
2418 rather than using file_has_perm, as this particular
2419 open file may belong to another process and we are
2420 only interested in the inode-based check here. */
2421 file_priv = list_first_entry(&tty->tty_files,
2422 struct tty_file_private, list);
2423 file = file_priv->file;
2424 if (file_path_has_perm(cred, file, FILE__READ | FILE__WRITE))
2427 spin_unlock(&tty->files_lock);
2430 /* Reset controlling tty. */
2434 /* Revalidate access to inherited open files. */
2435 n = iterate_fd(files, 0, match_file, cred);
2436 if (!n) /* none found? */
2439 devnull = dentry_open(&selinux_null, O_RDWR, cred);
2440 if (IS_ERR(devnull))
2442 /* replace all the matching ones with this */
2444 replace_fd(n - 1, devnull, 0);
2445 } while ((n = iterate_fd(files, n, match_file, cred)) != 0);
2451 * Prepare a process for imminent new credential changes due to exec
2453 static void selinux_bprm_committing_creds(struct linux_binprm *bprm)
2455 struct task_security_struct *new_tsec;
2456 struct rlimit *rlim, *initrlim;
2459 new_tsec = selinux_cred(bprm->cred);
2460 if (new_tsec->sid == new_tsec->osid)
2463 /* Close files for which the new task SID is not authorized. */
2464 flush_unauthorized_files(bprm->cred, current->files);
2466 /* Always clear parent death signal on SID transitions. */
2467 current->pdeath_signal = 0;
2469 /* Check whether the new SID can inherit resource limits from the old
2470 * SID. If not, reset all soft limits to the lower of the current
2471 * task's hard limit and the init task's soft limit.
2473 * Note that the setting of hard limits (even to lower them) can be
2474 * controlled by the setrlimit check. The inclusion of the init task's
2475 * soft limit into the computation is to avoid resetting soft limits
2476 * higher than the default soft limit for cases where the default is
2477 * lower than the hard limit, e.g. RLIMIT_CORE or RLIMIT_STACK.
2479 rc = avc_has_perm(&selinux_state,
2480 new_tsec->osid, new_tsec->sid, SECCLASS_PROCESS,
2481 PROCESS__RLIMITINH, NULL);
2483 /* protect against do_prlimit() */
2485 for (i = 0; i < RLIM_NLIMITS; i++) {
2486 rlim = current->signal->rlim + i;
2487 initrlim = init_task.signal->rlim + i;
2488 rlim->rlim_cur = min(rlim->rlim_max, initrlim->rlim_cur);
2490 task_unlock(current);
2491 if (IS_ENABLED(CONFIG_POSIX_TIMERS))
2492 update_rlimit_cpu(current, rlimit(RLIMIT_CPU));
2497 * Clean up the process immediately after the installation of new credentials
2500 static void selinux_bprm_committed_creds(struct linux_binprm *bprm)
2502 const struct task_security_struct *tsec = selinux_cred(current_cred());
2503 struct itimerval itimer;
2513 /* Check whether the new SID can inherit signal state from the old SID.
2514 * If not, clear itimers to avoid subsequent signal generation and
2515 * flush and unblock signals.
2517 * This must occur _after_ the task SID has been updated so that any
2518 * kill done after the flush will be checked against the new SID.
2520 rc = avc_has_perm(&selinux_state,
2521 osid, sid, SECCLASS_PROCESS, PROCESS__SIGINH, NULL);
2523 if (IS_ENABLED(CONFIG_POSIX_TIMERS)) {
2524 memset(&itimer, 0, sizeof itimer);
2525 for (i = 0; i < 3; i++)
2526 do_setitimer(i, &itimer, NULL);
2528 spin_lock_irq(¤t->sighand->siglock);
2529 if (!fatal_signal_pending(current)) {
2530 flush_sigqueue(¤t->pending);
2531 flush_sigqueue(¤t->signal->shared_pending);
2532 flush_signal_handlers(current, 1);
2533 sigemptyset(¤t->blocked);
2534 recalc_sigpending();
2536 spin_unlock_irq(¤t->sighand->siglock);
2539 /* Wake up the parent if it is waiting so that it can recheck
2540 * wait permission to the new task SID. */
2541 read_lock(&tasklist_lock);
2542 __wake_up_parent(current, current->real_parent);
2543 read_unlock(&tasklist_lock);
2546 /* superblock security operations */
2548 static int selinux_sb_alloc_security(struct super_block *sb)
2550 return superblock_alloc_security(sb);
2553 static void selinux_sb_free_security(struct super_block *sb)
2555 superblock_free_security(sb);
2558 static inline int opt_len(const char *s)
2560 bool open_quote = false;
2564 for (len = 0; (c = s[len]) != '\0'; len++) {
2566 open_quote = !open_quote;
2567 if (c == ',' && !open_quote)
2573 static int selinux_sb_eat_lsm_opts(char *options, void **mnt_opts)
2575 char *from = options;
2580 int len = opt_len(from);
2584 token = match_opt_prefix(from, len, &arg);
2586 if (token != Opt_error) {
2591 for (p = q = arg; p < from + len; p++) {
2596 arg = kmemdup_nul(arg, q - arg, GFP_KERNEL);
2598 rc = selinux_add_opt(token, arg, mnt_opts);
2602 selinux_free_mnt_opts(*mnt_opts);
2608 if (!first) { // copy with preceding comma
2613 memmove(to, from, len);
2625 static int selinux_sb_remount(struct super_block *sb, void *mnt_opts)
2627 struct selinux_mnt_opts *opts = mnt_opts;
2628 struct superblock_security_struct *sbsec = sb->s_security;
2632 if (!(sbsec->flags & SE_SBINITIALIZED))
2638 if (opts->fscontext) {
2639 rc = parse_sid(sb, opts->fscontext, &sid);
2642 if (bad_option(sbsec, FSCONTEXT_MNT, sbsec->sid, sid))
2643 goto out_bad_option;
2645 if (opts->context) {
2646 rc = parse_sid(sb, opts->context, &sid);
2649 if (bad_option(sbsec, CONTEXT_MNT, sbsec->mntpoint_sid, sid))
2650 goto out_bad_option;
2652 if (opts->rootcontext) {
2653 struct inode_security_struct *root_isec;
2654 root_isec = backing_inode_security(sb->s_root);
2655 rc = parse_sid(sb, opts->rootcontext, &sid);
2658 if (bad_option(sbsec, ROOTCONTEXT_MNT, root_isec->sid, sid))
2659 goto out_bad_option;
2661 if (opts->defcontext) {
2662 rc = parse_sid(sb, opts->defcontext, &sid);
2665 if (bad_option(sbsec, DEFCONTEXT_MNT, sbsec->def_sid, sid))
2666 goto out_bad_option;
2671 pr_warn("SELinux: unable to change security options "
2672 "during remount (dev %s, type=%s)\n", sb->s_id,
2677 static int selinux_sb_kern_mount(struct super_block *sb)
2679 const struct cred *cred = current_cred();
2680 struct common_audit_data ad;
2682 ad.type = LSM_AUDIT_DATA_DENTRY;
2683 ad.u.dentry = sb->s_root;
2684 return superblock_has_perm(cred, sb, FILESYSTEM__MOUNT, &ad);
2687 static int selinux_sb_statfs(struct dentry *dentry)
2689 const struct cred *cred = current_cred();
2690 struct common_audit_data ad;
2692 ad.type = LSM_AUDIT_DATA_DENTRY;
2693 ad.u.dentry = dentry->d_sb->s_root;
2694 return superblock_has_perm(cred, dentry->d_sb, FILESYSTEM__GETATTR, &ad);
2697 static int selinux_mount(const char *dev_name,
2698 const struct path *path,
2700 unsigned long flags,
2703 const struct cred *cred = current_cred();
2705 if (flags & MS_REMOUNT)
2706 return superblock_has_perm(cred, path->dentry->d_sb,
2707 FILESYSTEM__REMOUNT, NULL);
2709 return path_has_perm(cred, path, FILE__MOUNTON);
2712 static int selinux_umount(struct vfsmount *mnt, int flags)
2714 const struct cred *cred = current_cred();
2716 return superblock_has_perm(cred, mnt->mnt_sb,
2717 FILESYSTEM__UNMOUNT, NULL);
2720 /* inode security operations */
2722 static int selinux_inode_alloc_security(struct inode *inode)
2724 return inode_alloc_security(inode);
2727 static void selinux_inode_free_security(struct inode *inode)
2729 inode_free_security(inode);
2732 static int selinux_dentry_init_security(struct dentry *dentry, int mode,
2733 const struct qstr *name, void **ctx,
2739 rc = selinux_determine_inode_label(selinux_cred(current_cred()),
2740 d_inode(dentry->d_parent), name,
2741 inode_mode_to_security_class(mode),
2746 return security_sid_to_context(&selinux_state, newsid, (char **)ctx,
2750 static int selinux_dentry_create_files_as(struct dentry *dentry, int mode,
2752 const struct cred *old,
2757 struct task_security_struct *tsec;
2759 rc = selinux_determine_inode_label(selinux_cred(old),
2760 d_inode(dentry->d_parent), name,
2761 inode_mode_to_security_class(mode),
2766 tsec = selinux_cred(new);
2767 tsec->create_sid = newsid;
2771 static int selinux_inode_init_security(struct inode *inode, struct inode *dir,
2772 const struct qstr *qstr,
2774 void **value, size_t *len)
2776 const struct task_security_struct *tsec = selinux_cred(current_cred());
2777 struct superblock_security_struct *sbsec;
2782 sbsec = dir->i_sb->s_security;
2784 newsid = tsec->create_sid;
2786 rc = selinux_determine_inode_label(selinux_cred(current_cred()),
2788 inode_mode_to_security_class(inode->i_mode),
2793 /* Possibly defer initialization to selinux_complete_init. */
2794 if (sbsec->flags & SE_SBINITIALIZED) {
2795 struct inode_security_struct *isec = selinux_inode(inode);
2796 isec->sclass = inode_mode_to_security_class(inode->i_mode);
2798 isec->initialized = LABEL_INITIALIZED;
2801 if (!selinux_state.initialized || !(sbsec->flags & SBLABEL_MNT))
2805 *name = XATTR_SELINUX_SUFFIX;
2808 rc = security_sid_to_context_force(&selinux_state, newsid,
2819 static int selinux_inode_create(struct inode *dir, struct dentry *dentry, umode_t mode)
2821 return may_create(dir, dentry, SECCLASS_FILE);
2824 static int selinux_inode_link(struct dentry *old_dentry, struct inode *dir, struct dentry *new_dentry)
2826 return may_link(dir, old_dentry, MAY_LINK);
2829 static int selinux_inode_unlink(struct inode *dir, struct dentry *dentry)
2831 return may_link(dir, dentry, MAY_UNLINK);
2834 static int selinux_inode_symlink(struct inode *dir, struct dentry *dentry, const char *name)
2836 return may_create(dir, dentry, SECCLASS_LNK_FILE);
2839 static int selinux_inode_mkdir(struct inode *dir, struct dentry *dentry, umode_t mask)
2841 return may_create(dir, dentry, SECCLASS_DIR);
2844 static int selinux_inode_rmdir(struct inode *dir, struct dentry *dentry)
2846 return may_link(dir, dentry, MAY_RMDIR);
2849 static int selinux_inode_mknod(struct inode *dir, struct dentry *dentry, umode_t mode, dev_t dev)
2851 return may_create(dir, dentry, inode_mode_to_security_class(mode));
2854 static int selinux_inode_rename(struct inode *old_inode, struct dentry *old_dentry,
2855 struct inode *new_inode, struct dentry *new_dentry)
2857 return may_rename(old_inode, old_dentry, new_inode, new_dentry);
2860 static int selinux_inode_readlink(struct dentry *dentry)
2862 const struct cred *cred = current_cred();
2864 return dentry_has_perm(cred, dentry, FILE__READ);
2867 static int selinux_inode_follow_link(struct dentry *dentry, struct inode *inode,
2870 const struct cred *cred = current_cred();
2871 struct common_audit_data ad;
2872 struct inode_security_struct *isec;
2875 validate_creds(cred);
2877 ad.type = LSM_AUDIT_DATA_DENTRY;
2878 ad.u.dentry = dentry;
2879 sid = cred_sid(cred);
2880 isec = inode_security_rcu(inode, rcu);
2882 return PTR_ERR(isec);
2884 return avc_has_perm_flags(&selinux_state,
2885 sid, isec->sid, isec->sclass, FILE__READ, &ad,
2886 rcu ? MAY_NOT_BLOCK : 0);
2889 static noinline int audit_inode_permission(struct inode *inode,
2890 u32 perms, u32 audited, u32 denied,
2894 struct common_audit_data ad;
2895 struct inode_security_struct *isec = selinux_inode(inode);
2898 ad.type = LSM_AUDIT_DATA_INODE;
2901 rc = slow_avc_audit(&selinux_state,
2902 current_sid(), isec->sid, isec->sclass, perms,
2903 audited, denied, result, &ad, flags);
2909 static int selinux_inode_permission(struct inode *inode, int mask)
2911 const struct cred *cred = current_cred();
2914 unsigned flags = mask & MAY_NOT_BLOCK;
2915 struct inode_security_struct *isec;
2917 struct av_decision avd;
2919 u32 audited, denied;
2921 from_access = mask & MAY_ACCESS;
2922 mask &= (MAY_READ|MAY_WRITE|MAY_EXEC|MAY_APPEND);
2924 /* No permission to check. Existence test. */
2928 validate_creds(cred);
2930 if (unlikely(IS_PRIVATE(inode)))
2933 perms = file_mask_to_av(inode->i_mode, mask);
2935 sid = cred_sid(cred);
2936 isec = inode_security_rcu(inode, flags & MAY_NOT_BLOCK);
2938 return PTR_ERR(isec);
2940 rc = avc_has_perm_noaudit(&selinux_state,
2941 sid, isec->sid, isec->sclass, perms, 0, &avd);
2942 audited = avc_audit_required(perms, &avd, rc,
2943 from_access ? FILE__AUDIT_ACCESS : 0,
2945 if (likely(!audited))
2948 rc2 = audit_inode_permission(inode, perms, audited, denied, rc, flags);
2954 static int selinux_inode_setattr(struct dentry *dentry, struct iattr *iattr)
2956 const struct cred *cred = current_cred();
2957 struct inode *inode = d_backing_inode(dentry);
2958 unsigned int ia_valid = iattr->ia_valid;
2959 __u32 av = FILE__WRITE;
2961 /* ATTR_FORCE is just used for ATTR_KILL_S[UG]ID. */
2962 if (ia_valid & ATTR_FORCE) {
2963 ia_valid &= ~(ATTR_KILL_SUID | ATTR_KILL_SGID | ATTR_MODE |
2969 if (ia_valid & (ATTR_MODE | ATTR_UID | ATTR_GID |
2970 ATTR_ATIME_SET | ATTR_MTIME_SET | ATTR_TIMES_SET))
2971 return dentry_has_perm(cred, dentry, FILE__SETATTR);
2973 if (selinux_policycap_openperm() &&
2974 inode->i_sb->s_magic != SOCKFS_MAGIC &&
2975 (ia_valid & ATTR_SIZE) &&
2976 !(ia_valid & ATTR_FILE))
2979 return dentry_has_perm(cred, dentry, av);
2982 static int selinux_inode_getattr(const struct path *path)
2984 return path_has_perm(current_cred(), path, FILE__GETATTR);
2987 static bool has_cap_mac_admin(bool audit)
2989 const struct cred *cred = current_cred();
2990 unsigned int opts = audit ? CAP_OPT_NONE : CAP_OPT_NOAUDIT;
2992 if (cap_capable(cred, &init_user_ns, CAP_MAC_ADMIN, opts))
2994 if (cred_has_capability(cred, CAP_MAC_ADMIN, opts, true))
2999 static int selinux_inode_setxattr(struct dentry *dentry, const char *name,
3000 const void *value, size_t size, int flags)
3002 struct inode *inode = d_backing_inode(dentry);
3003 struct inode_security_struct *isec;
3004 struct superblock_security_struct *sbsec;
3005 struct common_audit_data ad;
3006 u32 newsid, sid = current_sid();
3009 if (strcmp(name, XATTR_NAME_SELINUX)) {
3010 rc = cap_inode_setxattr(dentry, name, value, size, flags);
3014 /* Not an attribute we recognize, so just check the
3015 ordinary setattr permission. */
3016 return dentry_has_perm(current_cred(), dentry, FILE__SETATTR);
3019 sbsec = inode->i_sb->s_security;
3020 if (!(sbsec->flags & SBLABEL_MNT))
3023 if (!inode_owner_or_capable(inode))
3026 ad.type = LSM_AUDIT_DATA_DENTRY;
3027 ad.u.dentry = dentry;
3029 isec = backing_inode_security(dentry);
3030 rc = avc_has_perm(&selinux_state,
3031 sid, isec->sid, isec->sclass,
3032 FILE__RELABELFROM, &ad);
3036 rc = security_context_to_sid(&selinux_state, value, size, &newsid,
3038 if (rc == -EINVAL) {
3039 if (!has_cap_mac_admin(true)) {
3040 struct audit_buffer *ab;
3043 /* We strip a nul only if it is at the end, otherwise the
3044 * context contains a nul and we should audit that */
3046 const char *str = value;
3048 if (str[size - 1] == '\0')
3049 audit_size = size - 1;
3055 ab = audit_log_start(audit_context(),
3056 GFP_ATOMIC, AUDIT_SELINUX_ERR);
3057 audit_log_format(ab, "op=setxattr invalid_context=");
3058 audit_log_n_untrustedstring(ab, value, audit_size);
3063 rc = security_context_to_sid_force(&selinux_state, value,
3069 rc = avc_has_perm(&selinux_state,
3070 sid, newsid, isec->sclass,
3071 FILE__RELABELTO, &ad);
3075 rc = security_validate_transition(&selinux_state, isec->sid, newsid,
3080 return avc_has_perm(&selinux_state,
3083 SECCLASS_FILESYSTEM,
3084 FILESYSTEM__ASSOCIATE,
3088 static void selinux_inode_post_setxattr(struct dentry *dentry, const char *name,
3089 const void *value, size_t size,
3092 struct inode *inode = d_backing_inode(dentry);
3093 struct inode_security_struct *isec;
3097 if (strcmp(name, XATTR_NAME_SELINUX)) {
3098 /* Not an attribute we recognize, so nothing to do. */
3102 rc = security_context_to_sid_force(&selinux_state, value, size,
3105 pr_err("SELinux: unable to map context to SID"
3106 "for (%s, %lu), rc=%d\n",
3107 inode->i_sb->s_id, inode->i_ino, -rc);
3111 isec = backing_inode_security(dentry);
3112 spin_lock(&isec->lock);
3113 isec->sclass = inode_mode_to_security_class(inode->i_mode);
3115 isec->initialized = LABEL_INITIALIZED;
3116 spin_unlock(&isec->lock);
3121 static int selinux_inode_getxattr(struct dentry *dentry, const char *name)
3123 const struct cred *cred = current_cred();
3125 return dentry_has_perm(cred, dentry, FILE__GETATTR);
3128 static int selinux_inode_listxattr(struct dentry *dentry)
3130 const struct cred *cred = current_cred();
3132 return dentry_has_perm(cred, dentry, FILE__GETATTR);
3135 static int selinux_inode_removexattr(struct dentry *dentry, const char *name)
3137 if (strcmp(name, XATTR_NAME_SELINUX)) {
3138 int rc = cap_inode_removexattr(dentry, name);
3142 /* Not an attribute we recognize, so just check the
3143 ordinary setattr permission. */
3144 return dentry_has_perm(current_cred(), dentry, FILE__SETATTR);
3147 /* No one is allowed to remove a SELinux security label.
3148 You can change the label, but all data must be labeled. */
3153 * Copy the inode security context value to the user.
3155 * Permission check is handled by selinux_inode_getxattr hook.
3157 static int selinux_inode_getsecurity(struct inode *inode, const char *name, void **buffer, bool alloc)
3161 char *context = NULL;
3162 struct inode_security_struct *isec;
3164 if (strcmp(name, XATTR_SELINUX_SUFFIX))
3168 * If the caller has CAP_MAC_ADMIN, then get the raw context
3169 * value even if it is not defined by current policy; otherwise,
3170 * use the in-core value under current policy.
3171 * Use the non-auditing forms of the permission checks since
3172 * getxattr may be called by unprivileged processes commonly
3173 * and lack of permission just means that we fall back to the
3174 * in-core context value, not a denial.
3176 isec = inode_security(inode);
3177 if (has_cap_mac_admin(false))
3178 error = security_sid_to_context_force(&selinux_state,
3179 isec->sid, &context,
3182 error = security_sid_to_context(&selinux_state, isec->sid,
3196 static int selinux_inode_setsecurity(struct inode *inode, const char *name,
3197 const void *value, size_t size, int flags)
3199 struct inode_security_struct *isec = inode_security_novalidate(inode);
3203 if (strcmp(name, XATTR_SELINUX_SUFFIX))
3206 if (!value || !size)
3209 rc = security_context_to_sid(&selinux_state, value, size, &newsid,
3214 spin_lock(&isec->lock);
3215 isec->sclass = inode_mode_to_security_class(inode->i_mode);
3217 isec->initialized = LABEL_INITIALIZED;
3218 spin_unlock(&isec->lock);
3222 static int selinux_inode_listsecurity(struct inode *inode, char *buffer, size_t buffer_size)
3224 const int len = sizeof(XATTR_NAME_SELINUX);
3225 if (buffer && len <= buffer_size)
3226 memcpy(buffer, XATTR_NAME_SELINUX, len);
3230 static void selinux_inode_getsecid(struct inode *inode, u32 *secid)
3232 struct inode_security_struct *isec = inode_security_novalidate(inode);
3236 static int selinux_inode_copy_up(struct dentry *src, struct cred **new)
3239 struct task_security_struct *tsec;
3240 struct cred *new_creds = *new;
3242 if (new_creds == NULL) {
3243 new_creds = prepare_creds();
3248 tsec = selinux_cred(new_creds);
3249 /* Get label from overlay inode and set it in create_sid */
3250 selinux_inode_getsecid(d_inode(src), &sid);
3251 tsec->create_sid = sid;
3256 static int selinux_inode_copy_up_xattr(const char *name)
3258 /* The copy_up hook above sets the initial context on an inode, but we
3259 * don't then want to overwrite it by blindly copying all the lower
3260 * xattrs up. Instead, we have to filter out SELinux-related xattrs.
3262 if (strcmp(name, XATTR_NAME_SELINUX) == 0)
3263 return 1; /* Discard */
3265 * Any other attribute apart from SELINUX is not claimed, supported
3271 /* file security operations */
3273 static int selinux_revalidate_file_permission(struct file *file, int mask)
3275 const struct cred *cred = current_cred();
3276 struct inode *inode = file_inode(file);
3278 /* file_mask_to_av won't add FILE__WRITE if MAY_APPEND is set */
3279 if ((file->f_flags & O_APPEND) && (mask & MAY_WRITE))
3282 return file_has_perm(cred, file,
3283 file_mask_to_av(inode->i_mode, mask));
3286 static int selinux_file_permission(struct file *file, int mask)
3288 struct inode *inode = file_inode(file);
3289 struct file_security_struct *fsec = selinux_file(file);
3290 struct inode_security_struct *isec;
3291 u32 sid = current_sid();
3294 /* No permission to check. Existence test. */
3297 isec = inode_security(inode);
3298 if (sid == fsec->sid && fsec->isid == isec->sid &&
3299 fsec->pseqno == avc_policy_seqno(&selinux_state))
3300 /* No change since file_open check. */
3303 return selinux_revalidate_file_permission(file, mask);
3306 static int selinux_file_alloc_security(struct file *file)
3308 return file_alloc_security(file);
3312 * Check whether a task has the ioctl permission and cmd
3313 * operation to an inode.
3315 static int ioctl_has_perm(const struct cred *cred, struct file *file,
3316 u32 requested, u16 cmd)
3318 struct common_audit_data ad;
3319 struct file_security_struct *fsec = selinux_file(file);
3320 struct inode *inode = file_inode(file);
3321 struct inode_security_struct *isec;
3322 struct lsm_ioctlop_audit ioctl;
3323 u32 ssid = cred_sid(cred);
3325 u8 driver = cmd >> 8;
3326 u8 xperm = cmd & 0xff;
3328 ad.type = LSM_AUDIT_DATA_IOCTL_OP;
3331 ad.u.op->path = file->f_path;
3333 if (ssid != fsec->sid) {
3334 rc = avc_has_perm(&selinux_state,
3343 if (unlikely(IS_PRIVATE(inode)))
3346 isec = inode_security(inode);
3347 rc = avc_has_extended_perms(&selinux_state,
3348 ssid, isec->sid, isec->sclass,
3349 requested, driver, xperm, &ad);
3354 static int selinux_file_ioctl(struct file *file, unsigned int cmd,
3357 const struct cred *cred = current_cred();
3367 case FS_IOC_GETFLAGS:
3369 case FS_IOC_GETVERSION:
3370 error = file_has_perm(cred, file, FILE__GETATTR);
3373 case FS_IOC_SETFLAGS:
3375 case FS_IOC_SETVERSION:
3376 error = file_has_perm(cred, file, FILE__SETATTR);
3379 /* sys_ioctl() checks */
3383 error = file_has_perm(cred, file, 0);
3388 error = cred_has_capability(cred, CAP_SYS_TTY_CONFIG,
3389 CAP_OPT_NONE, true);
3392 /* default case assumes that the command will go
3393 * to the file's ioctl() function.
3396 error = ioctl_has_perm(cred, file, FILE__IOCTL, (u16) cmd);
3401 static int default_noexec;
3403 static int file_map_prot_check(struct file *file, unsigned long prot, int shared)
3405 const struct cred *cred = current_cred();
3406 u32 sid = cred_sid(cred);
3409 if (default_noexec &&
3410 (prot & PROT_EXEC) && (!file || IS_PRIVATE(file_inode(file)) ||
3411 (!shared && (prot & PROT_WRITE)))) {
3413 * We are making executable an anonymous mapping or a
3414 * private file mapping that will also be writable.
3415 * This has an additional check.
3417 rc = avc_has_perm(&selinux_state,
3418 sid, sid, SECCLASS_PROCESS,
3419 PROCESS__EXECMEM, NULL);
3425 /* read access is always possible with a mapping */
3426 u32 av = FILE__READ;
3428 /* write access only matters if the mapping is shared */
3429 if (shared && (prot & PROT_WRITE))
3432 if (prot & PROT_EXEC)
3433 av |= FILE__EXECUTE;
3435 return file_has_perm(cred, file, av);
3442 static int selinux_mmap_addr(unsigned long addr)
3446 if (addr < CONFIG_LSM_MMAP_MIN_ADDR) {
3447 u32 sid = current_sid();
3448 rc = avc_has_perm(&selinux_state,
3449 sid, sid, SECCLASS_MEMPROTECT,
3450 MEMPROTECT__MMAP_ZERO, NULL);
3456 static int selinux_mmap_file(struct file *file, unsigned long reqprot,
3457 unsigned long prot, unsigned long flags)
3459 struct common_audit_data ad;
3463 ad.type = LSM_AUDIT_DATA_FILE;
3465 rc = inode_has_perm(current_cred(), file_inode(file),
3471 if (selinux_state.checkreqprot)
3474 return file_map_prot_check(file, prot,
3475 (flags & MAP_TYPE) == MAP_SHARED);
3478 static int selinux_file_mprotect(struct vm_area_struct *vma,
3479 unsigned long reqprot,
3482 const struct cred *cred = current_cred();
3483 u32 sid = cred_sid(cred);
3485 if (selinux_state.checkreqprot)
3488 if (default_noexec &&
3489 (prot & PROT_EXEC) && !(vma->vm_flags & VM_EXEC)) {
3491 if (vma->vm_start >= vma->vm_mm->start_brk &&
3492 vma->vm_end <= vma->vm_mm->brk) {
3493 rc = avc_has_perm(&selinux_state,
3494 sid, sid, SECCLASS_PROCESS,
3495 PROCESS__EXECHEAP, NULL);
3496 } else if (!vma->vm_file &&
3497 ((vma->vm_start <= vma->vm_mm->start_stack &&
3498 vma->vm_end >= vma->vm_mm->start_stack) ||
3499 vma_is_stack_for_current(vma))) {
3500 rc = avc_has_perm(&selinux_state,
3501 sid, sid, SECCLASS_PROCESS,
3502 PROCESS__EXECSTACK, NULL);
3503 } else if (vma->vm_file && vma->anon_vma) {
3505 * We are making executable a file mapping that has
3506 * had some COW done. Since pages might have been
3507 * written, check ability to execute the possibly
3508 * modified content. This typically should only
3509 * occur for text relocations.
3511 rc = file_has_perm(cred, vma->vm_file, FILE__EXECMOD);
3517 return file_map_prot_check(vma->vm_file, prot, vma->vm_flags&VM_SHARED);
3520 static int selinux_file_lock(struct file *file, unsigned int cmd)
3522 const struct cred *cred = current_cred();
3524 return file_has_perm(cred, file, FILE__LOCK);
3527 static int selinux_file_fcntl(struct file *file, unsigned int cmd,
3530 const struct cred *cred = current_cred();
3535 if ((file->f_flags & O_APPEND) && !(arg & O_APPEND)) {
3536 err = file_has_perm(cred, file, FILE__WRITE);
3545 case F_GETOWNER_UIDS:
3546 /* Just check FD__USE permission */
3547 err = file_has_perm(cred, file, 0);
3555 #if BITS_PER_LONG == 32
3560 err = file_has_perm(cred, file, FILE__LOCK);
3567 static void selinux_file_set_fowner(struct file *file)
3569 struct file_security_struct *fsec;
3571 fsec = selinux_file(file);
3572 fsec->fown_sid = current_sid();
3575 static int selinux_file_send_sigiotask(struct task_struct *tsk,
3576 struct fown_struct *fown, int signum)
3579 u32 sid = task_sid(tsk);
3581 struct file_security_struct *fsec;
3583 /* struct fown_struct is never outside the context of a struct file */
3584 file = container_of(fown, struct file, f_owner);
3586 fsec = selinux_file(file);
3589 perm = signal_to_av(SIGIO); /* as per send_sigio_to_task */
3591 perm = signal_to_av(signum);
3593 return avc_has_perm(&selinux_state,
3594 fsec->fown_sid, sid,
3595 SECCLASS_PROCESS, perm, NULL);
3598 static int selinux_file_receive(struct file *file)
3600 const struct cred *cred = current_cred();
3602 return file_has_perm(cred, file, file_to_av(file));
3605 static int selinux_file_open(struct file *file)
3607 struct file_security_struct *fsec;
3608 struct inode_security_struct *isec;
3610 fsec = selinux_file(file);
3611 isec = inode_security(file_inode(file));
3613 * Save inode label and policy sequence number
3614 * at open-time so that selinux_file_permission
3615 * can determine whether revalidation is necessary.
3616 * Task label is already saved in the file security
3617 * struct as its SID.
3619 fsec->isid = isec->sid;
3620 fsec->pseqno = avc_policy_seqno(&selinux_state);
3622 * Since the inode label or policy seqno may have changed
3623 * between the selinux_inode_permission check and the saving
3624 * of state above, recheck that access is still permitted.
3625 * Otherwise, access might never be revalidated against the
3626 * new inode label or new policy.
3627 * This check is not redundant - do not remove.
3629 return file_path_has_perm(file->f_cred, file, open_file_to_av(file));
3632 /* task security operations */
3634 static int selinux_task_alloc(struct task_struct *task,
3635 unsigned long clone_flags)
3637 u32 sid = current_sid();
3639 return avc_has_perm(&selinux_state,
3640 sid, sid, SECCLASS_PROCESS, PROCESS__FORK, NULL);
3644 * prepare a new set of credentials for modification
3646 static int selinux_cred_prepare(struct cred *new, const struct cred *old,
3649 const struct task_security_struct *old_tsec = selinux_cred(old);
3650 struct task_security_struct *tsec = selinux_cred(new);
3657 * transfer the SELinux data to a blank set of creds
3659 static void selinux_cred_transfer(struct cred *new, const struct cred *old)
3661 const struct task_security_struct *old_tsec = selinux_cred(old);
3662 struct task_security_struct *tsec = selinux_cred(new);
3667 static void selinux_cred_getsecid(const struct cred *c, u32 *secid)
3669 *secid = cred_sid(c);
3673 * set the security data for a kernel service
3674 * - all the creation contexts are set to unlabelled
3676 static int selinux_kernel_act_as(struct cred *new, u32 secid)
3678 struct task_security_struct *tsec = selinux_cred(new);
3679 u32 sid = current_sid();
3682 ret = avc_has_perm(&selinux_state,
3684 SECCLASS_KERNEL_SERVICE,
3685 KERNEL_SERVICE__USE_AS_OVERRIDE,
3689 tsec->create_sid = 0;
3690 tsec->keycreate_sid = 0;
3691 tsec->sockcreate_sid = 0;
3697 * set the file creation context in a security record to the same as the
3698 * objective context of the specified inode
3700 static int selinux_kernel_create_files_as(struct cred *new, struct inode *inode)
3702 struct inode_security_struct *isec = inode_security(inode);
3703 struct task_security_struct *tsec = selinux_cred(new);
3704 u32 sid = current_sid();
3707 ret = avc_has_perm(&selinux_state,
3709 SECCLASS_KERNEL_SERVICE,
3710 KERNEL_SERVICE__CREATE_FILES_AS,
3714 tsec->create_sid = isec->sid;
3718 static int selinux_kernel_module_request(char *kmod_name)
3720 struct common_audit_data ad;
3722 ad.type = LSM_AUDIT_DATA_KMOD;
3723 ad.u.kmod_name = kmod_name;
3725 return avc_has_perm(&selinux_state,
3726 current_sid(), SECINITSID_KERNEL, SECCLASS_SYSTEM,
3727 SYSTEM__MODULE_REQUEST, &ad);
3730 static int selinux_kernel_module_from_file(struct file *file)
3732 struct common_audit_data ad;
3733 struct inode_security_struct *isec;
3734 struct file_security_struct *fsec;
3735 u32 sid = current_sid();
3740 return avc_has_perm(&selinux_state,
3741 sid, sid, SECCLASS_SYSTEM,
3742 SYSTEM__MODULE_LOAD, NULL);
3746 ad.type = LSM_AUDIT_DATA_FILE;
3749 fsec = selinux_file(file);
3750 if (sid != fsec->sid) {
3751 rc = avc_has_perm(&selinux_state,
3752 sid, fsec->sid, SECCLASS_FD, FD__USE, &ad);
3757 isec = inode_security(file_inode(file));
3758 return avc_has_perm(&selinux_state,
3759 sid, isec->sid, SECCLASS_SYSTEM,
3760 SYSTEM__MODULE_LOAD, &ad);
3763 static int selinux_kernel_read_file(struct file *file,
3764 enum kernel_read_file_id id)
3769 case READING_MODULE:
3770 rc = selinux_kernel_module_from_file(file);
3779 static int selinux_kernel_load_data(enum kernel_load_data_id id)
3784 case LOADING_MODULE:
3785 rc = selinux_kernel_module_from_file(NULL);
3793 static int selinux_task_setpgid(struct task_struct *p, pid_t pgid)
3795 return avc_has_perm(&selinux_state,
3796 current_sid(), task_sid(p), SECCLASS_PROCESS,
3797 PROCESS__SETPGID, NULL);
3800 static int selinux_task_getpgid(struct task_struct *p)
3802 return avc_has_perm(&selinux_state,
3803 current_sid(), task_sid(p), SECCLASS_PROCESS,
3804 PROCESS__GETPGID, NULL);
3807 static int selinux_task_getsid(struct task_struct *p)
3809 return avc_has_perm(&selinux_state,
3810 current_sid(), task_sid(p), SECCLASS_PROCESS,
3811 PROCESS__GETSESSION, NULL);
3814 static void selinux_task_getsecid(struct task_struct *p, u32 *secid)
3816 *secid = task_sid(p);
3819 static int selinux_task_setnice(struct task_struct *p, int nice)
3821 return avc_has_perm(&selinux_state,
3822 current_sid(), task_sid(p), SECCLASS_PROCESS,
3823 PROCESS__SETSCHED, NULL);
3826 static int selinux_task_setioprio(struct task_struct *p, int ioprio)
3828 return avc_has_perm(&selinux_state,
3829 current_sid(), task_sid(p), SECCLASS_PROCESS,
3830 PROCESS__SETSCHED, NULL);
3833 static int selinux_task_getioprio(struct task_struct *p)
3835 return avc_has_perm(&selinux_state,
3836 current_sid(), task_sid(p), SECCLASS_PROCESS,
3837 PROCESS__GETSCHED, NULL);
3840 static int selinux_task_prlimit(const struct cred *cred, const struct cred *tcred,
3847 if (flags & LSM_PRLIMIT_WRITE)
3848 av |= PROCESS__SETRLIMIT;
3849 if (flags & LSM_PRLIMIT_READ)
3850 av |= PROCESS__GETRLIMIT;
3851 return avc_has_perm(&selinux_state,
3852 cred_sid(cred), cred_sid(tcred),
3853 SECCLASS_PROCESS, av, NULL);
3856 static int selinux_task_setrlimit(struct task_struct *p, unsigned int resource,
3857 struct rlimit *new_rlim)
3859 struct rlimit *old_rlim = p->signal->rlim + resource;
3861 /* Control the ability to change the hard limit (whether
3862 lowering or raising it), so that the hard limit can
3863 later be used as a safe reset point for the soft limit
3864 upon context transitions. See selinux_bprm_committing_creds. */
3865 if (old_rlim->rlim_max != new_rlim->rlim_max)
3866 return avc_has_perm(&selinux_state,
3867 current_sid(), task_sid(p),
3868 SECCLASS_PROCESS, PROCESS__SETRLIMIT, NULL);
3873 static int selinux_task_setscheduler(struct task_struct *p)
3875 return avc_has_perm(&selinux_state,
3876 current_sid(), task_sid(p), SECCLASS_PROCESS,
3877 PROCESS__SETSCHED, NULL);
3880 static int selinux_task_getscheduler(struct task_struct *p)
3882 return avc_has_perm(&selinux_state,
3883 current_sid(), task_sid(p), SECCLASS_PROCESS,
3884 PROCESS__GETSCHED, NULL);
3887 static int selinux_task_movememory(struct task_struct *p)
3889 return avc_has_perm(&selinux_state,
3890 current_sid(), task_sid(p), SECCLASS_PROCESS,
3891 PROCESS__SETSCHED, NULL);
3894 static int selinux_task_kill(struct task_struct *p, struct kernel_siginfo *info,
3895 int sig, const struct cred *cred)
3901 perm = PROCESS__SIGNULL; /* null signal; existence test */
3903 perm = signal_to_av(sig);
3905 secid = current_sid();
3907 secid = cred_sid(cred);
3908 return avc_has_perm(&selinux_state,
3909 secid, task_sid(p), SECCLASS_PROCESS, perm, NULL);
3912 static void selinux_task_to_inode(struct task_struct *p,
3913 struct inode *inode)
3915 struct inode_security_struct *isec = selinux_inode(inode);
3916 u32 sid = task_sid(p);
3918 spin_lock(&isec->lock);
3919 isec->sclass = inode_mode_to_security_class(inode->i_mode);
3921 isec->initialized = LABEL_INITIALIZED;
3922 spin_unlock(&isec->lock);
3925 /* Returns error only if unable to parse addresses */
3926 static int selinux_parse_skb_ipv4(struct sk_buff *skb,
3927 struct common_audit_data *ad, u8 *proto)
3929 int offset, ihlen, ret = -EINVAL;
3930 struct iphdr _iph, *ih;
3932 offset = skb_network_offset(skb);
3933 ih = skb_header_pointer(skb, offset, sizeof(_iph), &_iph);
3937 ihlen = ih->ihl * 4;
3938 if (ihlen < sizeof(_iph))
3941 ad->u.net->v4info.saddr = ih->saddr;
3942 ad->u.net->v4info.daddr = ih->daddr;
3946 *proto = ih->protocol;
3948 switch (ih->protocol) {
3950 struct tcphdr _tcph, *th;
3952 if (ntohs(ih->frag_off) & IP_OFFSET)
3956 th = skb_header_pointer(skb, offset, sizeof(_tcph), &_tcph);
3960 ad->u.net->sport = th->source;
3961 ad->u.net->dport = th->dest;
3966 struct udphdr _udph, *uh;
3968 if (ntohs(ih->frag_off) & IP_OFFSET)
3972 uh = skb_header_pointer(skb, offset, sizeof(_udph), &_udph);
3976 ad->u.net->sport = uh->source;
3977 ad->u.net->dport = uh->dest;
3981 case IPPROTO_DCCP: {
3982 struct dccp_hdr _dccph, *dh;
3984 if (ntohs(ih->frag_off) & IP_OFFSET)
3988 dh = skb_header_pointer(skb, offset, sizeof(_dccph), &_dccph);
3992 ad->u.net->sport = dh->dccph_sport;
3993 ad->u.net->dport = dh->dccph_dport;
3997 #if IS_ENABLED(CONFIG_IP_SCTP)
3998 case IPPROTO_SCTP: {
3999 struct sctphdr _sctph, *sh;
4001 if (ntohs(ih->frag_off) & IP_OFFSET)
4005 sh = skb_header_pointer(skb, offset, sizeof(_sctph), &_sctph);
4009 ad->u.net->sport = sh->source;
4010 ad->u.net->dport = sh->dest;
4021 #if IS_ENABLED(CONFIG_IPV6)
4023 /* Returns error only if unable to parse addresses */
4024 static int selinux_parse_skb_ipv6(struct sk_buff *skb,
4025 struct common_audit_data *ad, u8 *proto)
4028 int ret = -EINVAL, offset;
4029 struct ipv6hdr _ipv6h, *ip6;
4032 offset = skb_network_offset(skb);
4033 ip6 = skb_header_pointer(skb, offset, sizeof(_ipv6h), &_ipv6h);
4037 ad->u.net->v6info.saddr = ip6->saddr;
4038 ad->u.net->v6info.daddr = ip6->daddr;
4041 nexthdr = ip6->nexthdr;
4042 offset += sizeof(_ipv6h);
4043 offset = ipv6_skip_exthdr(skb, offset, &nexthdr, &frag_off);
4052 struct tcphdr _tcph, *th;
4054 th = skb_header_pointer(skb, offset, sizeof(_tcph), &_tcph);
4058 ad->u.net->sport = th->source;
4059 ad->u.net->dport = th->dest;
4064 struct udphdr _udph, *uh;
4066 uh = skb_header_pointer(skb, offset, sizeof(_udph), &_udph);
4070 ad->u.net->sport = uh->source;
4071 ad->u.net->dport = uh->dest;
4075 case IPPROTO_DCCP: {
4076 struct dccp_hdr _dccph, *dh;
4078 dh = skb_header_pointer(skb, offset, sizeof(_dccph), &_dccph);
4082 ad->u.net->sport = dh->dccph_sport;
4083 ad->u.net->dport = dh->dccph_dport;
4087 #if IS_ENABLED(CONFIG_IP_SCTP)
4088 case IPPROTO_SCTP: {
4089 struct sctphdr _sctph, *sh;
4091 sh = skb_header_pointer(skb, offset, sizeof(_sctph), &_sctph);
4095 ad->u.net->sport = sh->source;
4096 ad->u.net->dport = sh->dest;
4100 /* includes fragments */
4110 static int selinux_parse_skb(struct sk_buff *skb, struct common_audit_data *ad,
4111 char **_addrp, int src, u8 *proto)
4116 switch (ad->u.net->family) {
4118 ret = selinux_parse_skb_ipv4(skb, ad, proto);
4121 addrp = (char *)(src ? &ad->u.net->v4info.saddr :
4122 &ad->u.net->v4info.daddr);
4125 #if IS_ENABLED(CONFIG_IPV6)
4127 ret = selinux_parse_skb_ipv6(skb, ad, proto);
4130 addrp = (char *)(src ? &ad->u.net->v6info.saddr :
4131 &ad->u.net->v6info.daddr);
4141 "SELinux: failure in selinux_parse_skb(),"
4142 " unable to parse packet\n");
4152 * selinux_skb_peerlbl_sid - Determine the peer label of a packet
4154 * @family: protocol family
4155 * @sid: the packet's peer label SID
4158 * Check the various different forms of network peer labeling and determine
4159 * the peer label/SID for the packet; most of the magic actually occurs in
4160 * the security server function security_net_peersid_cmp(). The function
4161 * returns zero if the value in @sid is valid (although it may be SECSID_NULL)
4162 * or -EACCES if @sid is invalid due to inconsistencies with the different
4166 static int selinux_skb_peerlbl_sid(struct sk_buff *skb, u16 family, u32 *sid)
4173 err = selinux_xfrm_skb_sid(skb, &xfrm_sid);
4176 err = selinux_netlbl_skbuff_getsid(skb, family, &nlbl_type, &nlbl_sid);
4180 err = security_net_peersid_resolve(&selinux_state, nlbl_sid,
4181 nlbl_type, xfrm_sid, sid);
4182 if (unlikely(err)) {
4184 "SELinux: failure in selinux_skb_peerlbl_sid(),"
4185 " unable to determine packet's peer label\n");
4193 * selinux_conn_sid - Determine the child socket label for a connection
4194 * @sk_sid: the parent socket's SID
4195 * @skb_sid: the packet's SID
4196 * @conn_sid: the resulting connection SID
4198 * If @skb_sid is valid then the user:role:type information from @sk_sid is
4199 * combined with the MLS information from @skb_sid in order to create
4200 * @conn_sid. If @skb_sid is not valid then then @conn_sid is simply a copy
4201 * of @sk_sid. Returns zero on success, negative values on failure.
4204 static int selinux_conn_sid(u32 sk_sid, u32 skb_sid, u32 *conn_sid)
4208 if (skb_sid != SECSID_NULL)
4209 err = security_sid_mls_copy(&selinux_state, sk_sid, skb_sid,
4217 /* socket security operations */
4219 static int socket_sockcreate_sid(const struct task_security_struct *tsec,
4220 u16 secclass, u32 *socksid)
4222 if (tsec->sockcreate_sid > SECSID_NULL) {
4223 *socksid = tsec->sockcreate_sid;
4227 return security_transition_sid(&selinux_state, tsec->sid, tsec->sid,
4228 secclass, NULL, socksid);
4231 static int sock_has_perm(struct sock *sk, u32 perms)
4233 struct sk_security_struct *sksec = sk->sk_security;
4234 struct common_audit_data ad;
4235 struct lsm_network_audit net = {0,};
4237 if (sksec->sid == SECINITSID_KERNEL)
4240 ad.type = LSM_AUDIT_DATA_NET;
4244 return avc_has_perm(&selinux_state,
4245 current_sid(), sksec->sid, sksec->sclass, perms,
4249 static int selinux_socket_create(int family, int type,
4250 int protocol, int kern)
4252 const struct task_security_struct *tsec = selinux_cred(current_cred());
4260 secclass = socket_type_to_security_class(family, type, protocol);
4261 rc = socket_sockcreate_sid(tsec, secclass, &newsid);
4265 return avc_has_perm(&selinux_state,
4266 tsec->sid, newsid, secclass, SOCKET__CREATE, NULL);
4269 static int selinux_socket_post_create(struct socket *sock, int family,
4270 int type, int protocol, int kern)
4272 const struct task_security_struct *tsec = selinux_cred(current_cred());
4273 struct inode_security_struct *isec = inode_security_novalidate(SOCK_INODE(sock));
4274 struct sk_security_struct *sksec;
4275 u16 sclass = socket_type_to_security_class(family, type, protocol);
4276 u32 sid = SECINITSID_KERNEL;
4280 err = socket_sockcreate_sid(tsec, sclass, &sid);
4285 isec->sclass = sclass;
4287 isec->initialized = LABEL_INITIALIZED;
4290 sksec = sock->sk->sk_security;
4291 sksec->sclass = sclass;
4293 /* Allows detection of the first association on this socket */
4294 if (sksec->sclass == SECCLASS_SCTP_SOCKET)
4295 sksec->sctp_assoc_state = SCTP_ASSOC_UNSET;
4297 err = selinux_netlbl_socket_post_create(sock->sk, family);
4303 static int selinux_socket_socketpair(struct socket *socka,
4304 struct socket *sockb)
4306 struct sk_security_struct *sksec_a = socka->sk->sk_security;
4307 struct sk_security_struct *sksec_b = sockb->sk->sk_security;
4309 sksec_a->peer_sid = sksec_b->sid;
4310 sksec_b->peer_sid = sksec_a->sid;
4315 /* Range of port numbers used to automatically bind.
4316 Need to determine whether we should perform a name_bind
4317 permission check between the socket and the port number. */
4319 static int selinux_socket_bind(struct socket *sock, struct sockaddr *address, int addrlen)
4321 struct sock *sk = sock->sk;
4322 struct sk_security_struct *sksec = sk->sk_security;
4326 err = sock_has_perm(sk, SOCKET__BIND);
4330 /* If PF_INET or PF_INET6, check name_bind permission for the port. */
4331 family = sk->sk_family;
4332 if (family == PF_INET || family == PF_INET6) {
4334 struct common_audit_data ad;
4335 struct lsm_network_audit net = {0,};
4336 struct sockaddr_in *addr4 = NULL;
4337 struct sockaddr_in6 *addr6 = NULL;
4338 u16 family_sa = address->sa_family;
4339 unsigned short snum;
4343 * sctp_bindx(3) calls via selinux_sctp_bind_connect()
4344 * that validates multiple binding addresses. Because of this
4345 * need to check address->sa_family as it is possible to have
4346 * sk->sk_family = PF_INET6 with addr->sa_family = AF_INET.
4348 switch (family_sa) {
4351 if (addrlen < sizeof(struct sockaddr_in))
4353 addr4 = (struct sockaddr_in *)address;
4354 if (family_sa == AF_UNSPEC) {
4355 /* see __inet_bind(), we only want to allow
4356 * AF_UNSPEC if the address is INADDR_ANY
4358 if (addr4->sin_addr.s_addr != htonl(INADDR_ANY))
4360 family_sa = AF_INET;
4362 snum = ntohs(addr4->sin_port);
4363 addrp = (char *)&addr4->sin_addr.s_addr;
4366 if (addrlen < SIN6_LEN_RFC2133)
4368 addr6 = (struct sockaddr_in6 *)address;
4369 snum = ntohs(addr6->sin6_port);
4370 addrp = (char *)&addr6->sin6_addr.s6_addr;
4376 ad.type = LSM_AUDIT_DATA_NET;
4378 ad.u.net->sport = htons(snum);
4379 ad.u.net->family = family_sa;
4384 inet_get_local_port_range(sock_net(sk), &low, &high);
4386 if (snum < max(inet_prot_sock(sock_net(sk)), low) ||
4388 err = sel_netport_sid(sk->sk_protocol,
4392 err = avc_has_perm(&selinux_state,
4395 SOCKET__NAME_BIND, &ad);
4401 switch (sksec->sclass) {
4402 case SECCLASS_TCP_SOCKET:
4403 node_perm = TCP_SOCKET__NODE_BIND;
4406 case SECCLASS_UDP_SOCKET:
4407 node_perm = UDP_SOCKET__NODE_BIND;
4410 case SECCLASS_DCCP_SOCKET:
4411 node_perm = DCCP_SOCKET__NODE_BIND;
4414 case SECCLASS_SCTP_SOCKET:
4415 node_perm = SCTP_SOCKET__NODE_BIND;
4419 node_perm = RAWIP_SOCKET__NODE_BIND;
4423 err = sel_netnode_sid(addrp, family_sa, &sid);
4427 if (family_sa == AF_INET)
4428 ad.u.net->v4info.saddr = addr4->sin_addr.s_addr;
4430 ad.u.net->v6info.saddr = addr6->sin6_addr;
4432 err = avc_has_perm(&selinux_state,
4434 sksec->sclass, node_perm, &ad);
4441 /* Note that SCTP services expect -EINVAL, others -EAFNOSUPPORT. */
4442 if (sksec->sclass == SECCLASS_SCTP_SOCKET)
4444 return -EAFNOSUPPORT;
4447 /* This supports connect(2) and SCTP connect services such as sctp_connectx(3)
4448 * and sctp_sendmsg(3) as described in Documentation/security/LSM-sctp.rst
4450 static int selinux_socket_connect_helper(struct socket *sock,
4451 struct sockaddr *address, int addrlen)
4453 struct sock *sk = sock->sk;
4454 struct sk_security_struct *sksec = sk->sk_security;
4457 err = sock_has_perm(sk, SOCKET__CONNECT);
4462 * If a TCP, DCCP or SCTP socket, check name_connect permission
4465 if (sksec->sclass == SECCLASS_TCP_SOCKET ||
4466 sksec->sclass == SECCLASS_DCCP_SOCKET ||
4467 sksec->sclass == SECCLASS_SCTP_SOCKET) {
4468 struct common_audit_data ad;
4469 struct lsm_network_audit net = {0,};
4470 struct sockaddr_in *addr4 = NULL;
4471 struct sockaddr_in6 *addr6 = NULL;
4472 unsigned short snum;
4475 /* sctp_connectx(3) calls via selinux_sctp_bind_connect()
4476 * that validates multiple connect addresses. Because of this
4477 * need to check address->sa_family as it is possible to have
4478 * sk->sk_family = PF_INET6 with addr->sa_family = AF_INET.
4480 switch (address->sa_family) {
4482 addr4 = (struct sockaddr_in *)address;
4483 if (addrlen < sizeof(struct sockaddr_in))
4485 snum = ntohs(addr4->sin_port);
4488 addr6 = (struct sockaddr_in6 *)address;
4489 if (addrlen < SIN6_LEN_RFC2133)
4491 snum = ntohs(addr6->sin6_port);
4494 /* Note that SCTP services expect -EINVAL, whereas
4495 * others expect -EAFNOSUPPORT.
4497 if (sksec->sclass == SECCLASS_SCTP_SOCKET)
4500 return -EAFNOSUPPORT;
4503 err = sel_netport_sid(sk->sk_protocol, snum, &sid);
4507 switch (sksec->sclass) {
4508 case SECCLASS_TCP_SOCKET:
4509 perm = TCP_SOCKET__NAME_CONNECT;
4511 case SECCLASS_DCCP_SOCKET:
4512 perm = DCCP_SOCKET__NAME_CONNECT;
4514 case SECCLASS_SCTP_SOCKET:
4515 perm = SCTP_SOCKET__NAME_CONNECT;
4519 ad.type = LSM_AUDIT_DATA_NET;
4521 ad.u.net->dport = htons(snum);
4522 ad.u.net->family = address->sa_family;
4523 err = avc_has_perm(&selinux_state,
4524 sksec->sid, sid, sksec->sclass, perm, &ad);
4532 /* Supports connect(2), see comments in selinux_socket_connect_helper() */
4533 static int selinux_socket_connect(struct socket *sock,
4534 struct sockaddr *address, int addrlen)
4537 struct sock *sk = sock->sk;
4539 err = selinux_socket_connect_helper(sock, address, addrlen);
4543 return selinux_netlbl_socket_connect(sk, address);
4546 static int selinux_socket_listen(struct socket *sock, int backlog)
4548 return sock_has_perm(sock->sk, SOCKET__LISTEN);
4551 static int selinux_socket_accept(struct socket *sock, struct socket *newsock)
4554 struct inode_security_struct *isec;
4555 struct inode_security_struct *newisec;
4559 err = sock_has_perm(sock->sk, SOCKET__ACCEPT);
4563 isec = inode_security_novalidate(SOCK_INODE(sock));
4564 spin_lock(&isec->lock);
4565 sclass = isec->sclass;
4567 spin_unlock(&isec->lock);
4569 newisec = inode_security_novalidate(SOCK_INODE(newsock));
4570 newisec->sclass = sclass;
4572 newisec->initialized = LABEL_INITIALIZED;
4577 static int selinux_socket_sendmsg(struct socket *sock, struct msghdr *msg,
4580 return sock_has_perm(sock->sk, SOCKET__WRITE);
4583 static int selinux_socket_recvmsg(struct socket *sock, struct msghdr *msg,
4584 int size, int flags)
4586 return sock_has_perm(sock->sk, SOCKET__READ);
4589 static int selinux_socket_getsockname(struct socket *sock)
4591 return sock_has_perm(sock->sk, SOCKET__GETATTR);
4594 static int selinux_socket_getpeername(struct socket *sock)
4596 return sock_has_perm(sock->sk, SOCKET__GETATTR);
4599 static int selinux_socket_setsockopt(struct socket *sock, int level, int optname)
4603 err = sock_has_perm(sock->sk, SOCKET__SETOPT);
4607 return selinux_netlbl_socket_setsockopt(sock, level, optname);
4610 static int selinux_socket_getsockopt(struct socket *sock, int level,
4613 return sock_has_perm(sock->sk, SOCKET__GETOPT);
4616 static int selinux_socket_shutdown(struct socket *sock, int how)
4618 return sock_has_perm(sock->sk, SOCKET__SHUTDOWN);
4621 static int selinux_socket_unix_stream_connect(struct sock *sock,
4625 struct sk_security_struct *sksec_sock = sock->sk_security;
4626 struct sk_security_struct *sksec_other = other->sk_security;
4627 struct sk_security_struct *sksec_new = newsk->sk_security;
4628 struct common_audit_data ad;
4629 struct lsm_network_audit net = {0,};
4632 ad.type = LSM_AUDIT_DATA_NET;
4634 ad.u.net->sk = other;
4636 err = avc_has_perm(&selinux_state,
4637 sksec_sock->sid, sksec_other->sid,
4638 sksec_other->sclass,
4639 UNIX_STREAM_SOCKET__CONNECTTO, &ad);
4643 /* server child socket */
4644 sksec_new->peer_sid = sksec_sock->sid;
4645 err = security_sid_mls_copy(&selinux_state, sksec_other->sid,
4646 sksec_sock->sid, &sksec_new->sid);
4650 /* connecting socket */
4651 sksec_sock->peer_sid = sksec_new->sid;
4656 static int selinux_socket_unix_may_send(struct socket *sock,
4657 struct socket *other)
4659 struct sk_security_struct *ssec = sock->sk->sk_security;
4660 struct sk_security_struct *osec = other->sk->sk_security;
4661 struct common_audit_data ad;
4662 struct lsm_network_audit net = {0,};
4664 ad.type = LSM_AUDIT_DATA_NET;
4666 ad.u.net->sk = other->sk;
4668 return avc_has_perm(&selinux_state,
4669 ssec->sid, osec->sid, osec->sclass, SOCKET__SENDTO,
4673 static int selinux_inet_sys_rcv_skb(struct net *ns, int ifindex,
4674 char *addrp, u16 family, u32 peer_sid,
4675 struct common_audit_data *ad)
4681 err = sel_netif_sid(ns, ifindex, &if_sid);
4684 err = avc_has_perm(&selinux_state,
4686 SECCLASS_NETIF, NETIF__INGRESS, ad);
4690 err = sel_netnode_sid(addrp, family, &node_sid);
4693 return avc_has_perm(&selinux_state,
4695 SECCLASS_NODE, NODE__RECVFROM, ad);
4698 static int selinux_sock_rcv_skb_compat(struct sock *sk, struct sk_buff *skb,
4702 struct sk_security_struct *sksec = sk->sk_security;
4703 u32 sk_sid = sksec->sid;
4704 struct common_audit_data ad;
4705 struct lsm_network_audit net = {0,};
4708 ad.type = LSM_AUDIT_DATA_NET;
4710 ad.u.net->netif = skb->skb_iif;
4711 ad.u.net->family = family;
4712 err = selinux_parse_skb(skb, &ad, &addrp, 1, NULL);
4716 if (selinux_secmark_enabled()) {
4717 err = avc_has_perm(&selinux_state,
4718 sk_sid, skb->secmark, SECCLASS_PACKET,
4724 err = selinux_netlbl_sock_rcv_skb(sksec, skb, family, &ad);
4727 err = selinux_xfrm_sock_rcv_skb(sksec->sid, skb, &ad);
4732 static int selinux_socket_sock_rcv_skb(struct sock *sk, struct sk_buff *skb)
4735 struct sk_security_struct *sksec = sk->sk_security;
4736 u16 family = sk->sk_family;
4737 u32 sk_sid = sksec->sid;
4738 struct common_audit_data ad;
4739 struct lsm_network_audit net = {0,};
4744 if (family != PF_INET && family != PF_INET6)
4747 /* Handle mapped IPv4 packets arriving via IPv6 sockets */
4748 if (family == PF_INET6 && skb->protocol == htons(ETH_P_IP))
4751 /* If any sort of compatibility mode is enabled then handoff processing
4752 * to the selinux_sock_rcv_skb_compat() function to deal with the
4753 * special handling. We do this in an attempt to keep this function
4754 * as fast and as clean as possible. */
4755 if (!selinux_policycap_netpeer())
4756 return selinux_sock_rcv_skb_compat(sk, skb, family);
4758 secmark_active = selinux_secmark_enabled();
4759 peerlbl_active = selinux_peerlbl_enabled();
4760 if (!secmark_active && !peerlbl_active)
4763 ad.type = LSM_AUDIT_DATA_NET;
4765 ad.u.net->netif = skb->skb_iif;
4766 ad.u.net->family = family;
4767 err = selinux_parse_skb(skb, &ad, &addrp, 1, NULL);
4771 if (peerlbl_active) {
4774 err = selinux_skb_peerlbl_sid(skb, family, &peer_sid);
4777 err = selinux_inet_sys_rcv_skb(sock_net(sk), skb->skb_iif,
4778 addrp, family, peer_sid, &ad);
4780 selinux_netlbl_err(skb, family, err, 0);
4783 err = avc_has_perm(&selinux_state,
4784 sk_sid, peer_sid, SECCLASS_PEER,
4787 selinux_netlbl_err(skb, family, err, 0);
4792 if (secmark_active) {
4793 err = avc_has_perm(&selinux_state,
4794 sk_sid, skb->secmark, SECCLASS_PACKET,
4803 static int selinux_socket_getpeersec_stream(struct socket *sock, char __user *optval,
4804 int __user *optlen, unsigned len)
4809 struct sk_security_struct *sksec = sock->sk->sk_security;
4810 u32 peer_sid = SECSID_NULL;
4812 if (sksec->sclass == SECCLASS_UNIX_STREAM_SOCKET ||
4813 sksec->sclass == SECCLASS_TCP_SOCKET ||
4814 sksec->sclass == SECCLASS_SCTP_SOCKET)
4815 peer_sid = sksec->peer_sid;
4816 if (peer_sid == SECSID_NULL)
4817 return -ENOPROTOOPT;
4819 err = security_sid_to_context(&selinux_state, peer_sid, &scontext,
4824 if (scontext_len > len) {
4829 if (copy_to_user(optval, scontext, scontext_len))
4833 if (put_user(scontext_len, optlen))
4839 static int selinux_socket_getpeersec_dgram(struct socket *sock, struct sk_buff *skb, u32 *secid)
4841 u32 peer_secid = SECSID_NULL;
4843 struct inode_security_struct *isec;
4845 if (skb && skb->protocol == htons(ETH_P_IP))
4847 else if (skb && skb->protocol == htons(ETH_P_IPV6))
4850 family = sock->sk->sk_family;
4854 if (sock && family == PF_UNIX) {
4855 isec = inode_security_novalidate(SOCK_INODE(sock));
4856 peer_secid = isec->sid;
4858 selinux_skb_peerlbl_sid(skb, family, &peer_secid);
4861 *secid = peer_secid;
4862 if (peer_secid == SECSID_NULL)
4867 static int selinux_sk_alloc_security(struct sock *sk, int family, gfp_t priority)
4869 struct sk_security_struct *sksec;
4871 sksec = kzalloc(sizeof(*sksec), priority);
4875 sksec->peer_sid = SECINITSID_UNLABELED;
4876 sksec->sid = SECINITSID_UNLABELED;
4877 sksec->sclass = SECCLASS_SOCKET;
4878 selinux_netlbl_sk_security_reset(sksec);
4879 sk->sk_security = sksec;
4884 static void selinux_sk_free_security(struct sock *sk)
4886 struct sk_security_struct *sksec = sk->sk_security;
4888 sk->sk_security = NULL;
4889 selinux_netlbl_sk_security_free(sksec);
4893 static void selinux_sk_clone_security(const struct sock *sk, struct sock *newsk)
4895 struct sk_security_struct *sksec = sk->sk_security;
4896 struct sk_security_struct *newsksec = newsk->sk_security;
4898 newsksec->sid = sksec->sid;
4899 newsksec->peer_sid = sksec->peer_sid;
4900 newsksec->sclass = sksec->sclass;
4902 selinux_netlbl_sk_security_reset(newsksec);
4905 static void selinux_sk_getsecid(struct sock *sk, u32 *secid)
4908 *secid = SECINITSID_ANY_SOCKET;
4910 struct sk_security_struct *sksec = sk->sk_security;
4912 *secid = sksec->sid;
4916 static void selinux_sock_graft(struct sock *sk, struct socket *parent)
4918 struct inode_security_struct *isec =
4919 inode_security_novalidate(SOCK_INODE(parent));
4920 struct sk_security_struct *sksec = sk->sk_security;
4922 if (sk->sk_family == PF_INET || sk->sk_family == PF_INET6 ||
4923 sk->sk_family == PF_UNIX)
4924 isec->sid = sksec->sid;
4925 sksec->sclass = isec->sclass;
4928 /* Called whenever SCTP receives an INIT chunk. This happens when an incoming
4929 * connect(2), sctp_connectx(3) or sctp_sendmsg(3) (with no association
4932 static int selinux_sctp_assoc_request(struct sctp_endpoint *ep,
4933 struct sk_buff *skb)
4935 struct sk_security_struct *sksec = ep->base.sk->sk_security;
4936 struct common_audit_data ad;
4937 struct lsm_network_audit net = {0,};
4939 u32 peer_sid = SECINITSID_UNLABELED;
4943 if (!selinux_policycap_extsockclass())
4946 peerlbl_active = selinux_peerlbl_enabled();
4948 if (peerlbl_active) {
4949 /* This will return peer_sid = SECSID_NULL if there are
4950 * no peer labels, see security_net_peersid_resolve().
4952 err = selinux_skb_peerlbl_sid(skb, ep->base.sk->sk_family,
4957 if (peer_sid == SECSID_NULL)
4958 peer_sid = SECINITSID_UNLABELED;
4961 if (sksec->sctp_assoc_state == SCTP_ASSOC_UNSET) {
4962 sksec->sctp_assoc_state = SCTP_ASSOC_SET;
4964 /* Here as first association on socket. As the peer SID
4965 * was allowed by peer recv (and the netif/node checks),
4966 * then it is approved by policy and used as the primary
4967 * peer SID for getpeercon(3).
4969 sksec->peer_sid = peer_sid;
4970 } else if (sksec->peer_sid != peer_sid) {
4971 /* Other association peer SIDs are checked to enforce
4972 * consistency among the peer SIDs.
4974 ad.type = LSM_AUDIT_DATA_NET;
4976 ad.u.net->sk = ep->base.sk;
4977 err = avc_has_perm(&selinux_state,
4978 sksec->peer_sid, peer_sid, sksec->sclass,
4979 SCTP_SOCKET__ASSOCIATION, &ad);
4984 /* Compute the MLS component for the connection and store
4985 * the information in ep. This will be used by SCTP TCP type
4986 * sockets and peeled off connections as they cause a new
4987 * socket to be generated. selinux_sctp_sk_clone() will then
4988 * plug this into the new socket.
4990 err = selinux_conn_sid(sksec->sid, peer_sid, &conn_sid);
4994 ep->secid = conn_sid;
4995 ep->peer_secid = peer_sid;
4997 /* Set any NetLabel labels including CIPSO/CALIPSO options. */
4998 return selinux_netlbl_sctp_assoc_request(ep, skb);
5001 /* Check if sctp IPv4/IPv6 addresses are valid for binding or connecting
5002 * based on their @optname.
5004 static int selinux_sctp_bind_connect(struct sock *sk, int optname,
5005 struct sockaddr *address,
5008 int len, err = 0, walk_size = 0;
5010 struct sockaddr *addr;
5011 struct socket *sock;
5013 if (!selinux_policycap_extsockclass())
5016 /* Process one or more addresses that may be IPv4 or IPv6 */
5017 sock = sk->sk_socket;
5020 while (walk_size < addrlen) {
5021 if (walk_size + sizeof(sa_family_t) > addrlen)
5025 switch (addr->sa_family) {
5028 len = sizeof(struct sockaddr_in);
5031 len = sizeof(struct sockaddr_in6);
5040 case SCTP_PRIMARY_ADDR:
5041 case SCTP_SET_PEER_PRIMARY_ADDR:
5042 case SCTP_SOCKOPT_BINDX_ADD:
5043 err = selinux_socket_bind(sock, addr, len);
5045 /* Connect checks */
5046 case SCTP_SOCKOPT_CONNECTX:
5047 case SCTP_PARAM_SET_PRIMARY:
5048 case SCTP_PARAM_ADD_IP:
5049 case SCTP_SENDMSG_CONNECT:
5050 err = selinux_socket_connect_helper(sock, addr, len);
5054 /* As selinux_sctp_bind_connect() is called by the
5055 * SCTP protocol layer, the socket is already locked,
5056 * therefore selinux_netlbl_socket_connect_locked() is
5057 * is called here. The situations handled are:
5058 * sctp_connectx(3), sctp_sendmsg(3), sendmsg(2),
5059 * whenever a new IP address is added or when a new
5060 * primary address is selected.
5061 * Note that an SCTP connect(2) call happens before
5062 * the SCTP protocol layer and is handled via
5063 * selinux_socket_connect().
5065 err = selinux_netlbl_socket_connect_locked(sk, addr);
5079 /* Called whenever a new socket is created by accept(2) or sctp_peeloff(3). */
5080 static void selinux_sctp_sk_clone(struct sctp_endpoint *ep, struct sock *sk,
5083 struct sk_security_struct *sksec = sk->sk_security;
5084 struct sk_security_struct *newsksec = newsk->sk_security;
5086 /* If policy does not support SECCLASS_SCTP_SOCKET then call
5087 * the non-sctp clone version.
5089 if (!selinux_policycap_extsockclass())
5090 return selinux_sk_clone_security(sk, newsk);
5092 newsksec->sid = ep->secid;
5093 newsksec->peer_sid = ep->peer_secid;
5094 newsksec->sclass = sksec->sclass;
5095 selinux_netlbl_sctp_sk_clone(sk, newsk);
5098 static int selinux_inet_conn_request(struct sock *sk, struct sk_buff *skb,
5099 struct request_sock *req)
5101 struct sk_security_struct *sksec = sk->sk_security;
5103 u16 family = req->rsk_ops->family;
5107 err = selinux_skb_peerlbl_sid(skb, family, &peersid);
5110 err = selinux_conn_sid(sksec->sid, peersid, &connsid);
5113 req->secid = connsid;
5114 req->peer_secid = peersid;
5116 return selinux_netlbl_inet_conn_request(req, family);
5119 static void selinux_inet_csk_clone(struct sock *newsk,
5120 const struct request_sock *req)
5122 struct sk_security_struct *newsksec = newsk->sk_security;
5124 newsksec->sid = req->secid;
5125 newsksec->peer_sid = req->peer_secid;
5126 /* NOTE: Ideally, we should also get the isec->sid for the
5127 new socket in sync, but we don't have the isec available yet.
5128 So we will wait until sock_graft to do it, by which
5129 time it will have been created and available. */
5131 /* We don't need to take any sort of lock here as we are the only
5132 * thread with access to newsksec */
5133 selinux_netlbl_inet_csk_clone(newsk, req->rsk_ops->family);
5136 static void selinux_inet_conn_established(struct sock *sk, struct sk_buff *skb)
5138 u16 family = sk->sk_family;
5139 struct sk_security_struct *sksec = sk->sk_security;
5141 /* handle mapped IPv4 packets arriving via IPv6 sockets */
5142 if (family == PF_INET6 && skb->protocol == htons(ETH_P_IP))
5145 selinux_skb_peerlbl_sid(skb, family, &sksec->peer_sid);
5148 static int selinux_secmark_relabel_packet(u32 sid)
5150 const struct task_security_struct *__tsec;
5153 __tsec = selinux_cred(current_cred());
5156 return avc_has_perm(&selinux_state,
5157 tsid, sid, SECCLASS_PACKET, PACKET__RELABELTO,
5161 static void selinux_secmark_refcount_inc(void)
5163 atomic_inc(&selinux_secmark_refcount);
5166 static void selinux_secmark_refcount_dec(void)
5168 atomic_dec(&selinux_secmark_refcount);
5171 static void selinux_req_classify_flow(const struct request_sock *req,
5174 fl->flowi_secid = req->secid;
5177 static int selinux_tun_dev_alloc_security(void **security)
5179 struct tun_security_struct *tunsec;
5181 tunsec = kzalloc(sizeof(*tunsec), GFP_KERNEL);
5184 tunsec->sid = current_sid();
5190 static void selinux_tun_dev_free_security(void *security)
5195 static int selinux_tun_dev_create(void)
5197 u32 sid = current_sid();
5199 /* we aren't taking into account the "sockcreate" SID since the socket
5200 * that is being created here is not a socket in the traditional sense,
5201 * instead it is a private sock, accessible only to the kernel, and
5202 * representing a wide range of network traffic spanning multiple
5203 * connections unlike traditional sockets - check the TUN driver to
5204 * get a better understanding of why this socket is special */
5206 return avc_has_perm(&selinux_state,
5207 sid, sid, SECCLASS_TUN_SOCKET, TUN_SOCKET__CREATE,
5211 static int selinux_tun_dev_attach_queue(void *security)
5213 struct tun_security_struct *tunsec = security;
5215 return avc_has_perm(&selinux_state,
5216 current_sid(), tunsec->sid, SECCLASS_TUN_SOCKET,
5217 TUN_SOCKET__ATTACH_QUEUE, NULL);
5220 static int selinux_tun_dev_attach(struct sock *sk, void *security)
5222 struct tun_security_struct *tunsec = security;
5223 struct sk_security_struct *sksec = sk->sk_security;
5225 /* we don't currently perform any NetLabel based labeling here and it
5226 * isn't clear that we would want to do so anyway; while we could apply
5227 * labeling without the support of the TUN user the resulting labeled
5228 * traffic from the other end of the connection would almost certainly
5229 * cause confusion to the TUN user that had no idea network labeling
5230 * protocols were being used */
5232 sksec->sid = tunsec->sid;
5233 sksec->sclass = SECCLASS_TUN_SOCKET;
5238 static int selinux_tun_dev_open(void *security)
5240 struct tun_security_struct *tunsec = security;
5241 u32 sid = current_sid();
5244 err = avc_has_perm(&selinux_state,
5245 sid, tunsec->sid, SECCLASS_TUN_SOCKET,
5246 TUN_SOCKET__RELABELFROM, NULL);
5249 err = avc_has_perm(&selinux_state,
5250 sid, sid, SECCLASS_TUN_SOCKET,
5251 TUN_SOCKET__RELABELTO, NULL);
5259 static int selinux_nlmsg_perm(struct sock *sk, struct sk_buff *skb)
5263 struct nlmsghdr *nlh;
5264 struct sk_security_struct *sksec = sk->sk_security;
5266 if (skb->len < NLMSG_HDRLEN) {
5270 nlh = nlmsg_hdr(skb);
5272 err = selinux_nlmsg_lookup(sksec->sclass, nlh->nlmsg_type, &perm);
5274 if (err == -EINVAL) {
5275 pr_warn_ratelimited("SELinux: unrecognized netlink"
5276 " message: protocol=%hu nlmsg_type=%hu sclass=%s"
5277 " pig=%d comm=%s\n",
5278 sk->sk_protocol, nlh->nlmsg_type,
5279 secclass_map[sksec->sclass - 1].name,
5280 task_pid_nr(current), current->comm);
5281 if (!enforcing_enabled(&selinux_state) ||
5282 security_get_allow_unknown(&selinux_state))
5292 err = sock_has_perm(sk, perm);
5297 #ifdef CONFIG_NETFILTER
5299 static unsigned int selinux_ip_forward(struct sk_buff *skb,
5300 const struct net_device *indev,
5306 struct common_audit_data ad;
5307 struct lsm_network_audit net = {0,};
5312 if (!selinux_policycap_netpeer())
5315 secmark_active = selinux_secmark_enabled();
5316 netlbl_active = netlbl_enabled();
5317 peerlbl_active = selinux_peerlbl_enabled();
5318 if (!secmark_active && !peerlbl_active)
5321 if (selinux_skb_peerlbl_sid(skb, family, &peer_sid) != 0)
5324 ad.type = LSM_AUDIT_DATA_NET;
5326 ad.u.net->netif = indev->ifindex;
5327 ad.u.net->family = family;
5328 if (selinux_parse_skb(skb, &ad, &addrp, 1, NULL) != 0)
5331 if (peerlbl_active) {
5332 err = selinux_inet_sys_rcv_skb(dev_net(indev), indev->ifindex,
5333 addrp, family, peer_sid, &ad);
5335 selinux_netlbl_err(skb, family, err, 1);
5341 if (avc_has_perm(&selinux_state,
5342 peer_sid, skb->secmark,
5343 SECCLASS_PACKET, PACKET__FORWARD_IN, &ad))
5347 /* we do this in the FORWARD path and not the POST_ROUTING
5348 * path because we want to make sure we apply the necessary
5349 * labeling before IPsec is applied so we can leverage AH
5351 if (selinux_netlbl_skbuff_setsid(skb, family, peer_sid) != 0)
5357 static unsigned int selinux_ipv4_forward(void *priv,
5358 struct sk_buff *skb,
5359 const struct nf_hook_state *state)
5361 return selinux_ip_forward(skb, state->in, PF_INET);
5364 #if IS_ENABLED(CONFIG_IPV6)
5365 static unsigned int selinux_ipv6_forward(void *priv,
5366 struct sk_buff *skb,
5367 const struct nf_hook_state *state)
5369 return selinux_ip_forward(skb, state->in, PF_INET6);
5373 static unsigned int selinux_ip_output(struct sk_buff *skb,
5379 if (!netlbl_enabled())
5382 /* we do this in the LOCAL_OUT path and not the POST_ROUTING path
5383 * because we want to make sure we apply the necessary labeling
5384 * before IPsec is applied so we can leverage AH protection */
5387 struct sk_security_struct *sksec;
5389 if (sk_listener(sk))
5390 /* if the socket is the listening state then this
5391 * packet is a SYN-ACK packet which means it needs to
5392 * be labeled based on the connection/request_sock and
5393 * not the parent socket. unfortunately, we can't
5394 * lookup the request_sock yet as it isn't queued on
5395 * the parent socket until after the SYN-ACK is sent.
5396 * the "solution" is to simply pass the packet as-is
5397 * as any IP option based labeling should be copied
5398 * from the initial connection request (in the IP
5399 * layer). it is far from ideal, but until we get a
5400 * security label in the packet itself this is the
5401 * best we can do. */
5404 /* standard practice, label using the parent socket */
5405 sksec = sk->sk_security;
5408 sid = SECINITSID_KERNEL;
5409 if (selinux_netlbl_skbuff_setsid(skb, family, sid) != 0)
5415 static unsigned int selinux_ipv4_output(void *priv,
5416 struct sk_buff *skb,
5417 const struct nf_hook_state *state)
5419 return selinux_ip_output(skb, PF_INET);
5422 #if IS_ENABLED(CONFIG_IPV6)
5423 static unsigned int selinux_ipv6_output(void *priv,
5424 struct sk_buff *skb,
5425 const struct nf_hook_state *state)
5427 return selinux_ip_output(skb, PF_INET6);
5431 static unsigned int selinux_ip_postroute_compat(struct sk_buff *skb,
5435 struct sock *sk = skb_to_full_sk(skb);
5436 struct sk_security_struct *sksec;
5437 struct common_audit_data ad;
5438 struct lsm_network_audit net = {0,};
5444 sksec = sk->sk_security;
5446 ad.type = LSM_AUDIT_DATA_NET;
5448 ad.u.net->netif = ifindex;
5449 ad.u.net->family = family;
5450 if (selinux_parse_skb(skb, &ad, &addrp, 0, &proto))
5453 if (selinux_secmark_enabled())
5454 if (avc_has_perm(&selinux_state,
5455 sksec->sid, skb->secmark,
5456 SECCLASS_PACKET, PACKET__SEND, &ad))
5457 return NF_DROP_ERR(-ECONNREFUSED);
5459 if (selinux_xfrm_postroute_last(sksec->sid, skb, &ad, proto))
5460 return NF_DROP_ERR(-ECONNREFUSED);
5465 static unsigned int selinux_ip_postroute(struct sk_buff *skb,
5466 const struct net_device *outdev,
5471 int ifindex = outdev->ifindex;
5473 struct common_audit_data ad;
5474 struct lsm_network_audit net = {0,};
5479 /* If any sort of compatibility mode is enabled then handoff processing
5480 * to the selinux_ip_postroute_compat() function to deal with the
5481 * special handling. We do this in an attempt to keep this function
5482 * as fast and as clean as possible. */
5483 if (!selinux_policycap_netpeer())
5484 return selinux_ip_postroute_compat(skb, ifindex, family);
5486 secmark_active = selinux_secmark_enabled();
5487 peerlbl_active = selinux_peerlbl_enabled();
5488 if (!secmark_active && !peerlbl_active)
5491 sk = skb_to_full_sk(skb);
5494 /* If skb->dst->xfrm is non-NULL then the packet is undergoing an IPsec
5495 * packet transformation so allow the packet to pass without any checks
5496 * since we'll have another chance to perform access control checks
5497 * when the packet is on it's final way out.
5498 * NOTE: there appear to be some IPv6 multicast cases where skb->dst
5499 * is NULL, in this case go ahead and apply access control.
5500 * NOTE: if this is a local socket (skb->sk != NULL) that is in the
5501 * TCP listening state we cannot wait until the XFRM processing
5502 * is done as we will miss out on the SA label if we do;
5503 * unfortunately, this means more work, but it is only once per
5505 if (skb_dst(skb) != NULL && skb_dst(skb)->xfrm != NULL &&
5506 !(sk && sk_listener(sk)))
5511 /* Without an associated socket the packet is either coming
5512 * from the kernel or it is being forwarded; check the packet
5513 * to determine which and if the packet is being forwarded
5514 * query the packet directly to determine the security label. */
5516 secmark_perm = PACKET__FORWARD_OUT;
5517 if (selinux_skb_peerlbl_sid(skb, family, &peer_sid))
5520 secmark_perm = PACKET__SEND;
5521 peer_sid = SECINITSID_KERNEL;
5523 } else if (sk_listener(sk)) {
5524 /* Locally generated packet but the associated socket is in the
5525 * listening state which means this is a SYN-ACK packet. In
5526 * this particular case the correct security label is assigned
5527 * to the connection/request_sock but unfortunately we can't
5528 * query the request_sock as it isn't queued on the parent
5529 * socket until after the SYN-ACK packet is sent; the only
5530 * viable choice is to regenerate the label like we do in
5531 * selinux_inet_conn_request(). See also selinux_ip_output()
5532 * for similar problems. */
5534 struct sk_security_struct *sksec;
5536 sksec = sk->sk_security;
5537 if (selinux_skb_peerlbl_sid(skb, family, &skb_sid))
5539 /* At this point, if the returned skb peerlbl is SECSID_NULL
5540 * and the packet has been through at least one XFRM
5541 * transformation then we must be dealing with the "final"
5542 * form of labeled IPsec packet; since we've already applied
5543 * all of our access controls on this packet we can safely
5544 * pass the packet. */
5545 if (skb_sid == SECSID_NULL) {
5548 if (IPCB(skb)->flags & IPSKB_XFRM_TRANSFORMED)
5552 if (IP6CB(skb)->flags & IP6SKB_XFRM_TRANSFORMED)
5556 return NF_DROP_ERR(-ECONNREFUSED);
5559 if (selinux_conn_sid(sksec->sid, skb_sid, &peer_sid))
5561 secmark_perm = PACKET__SEND;
5563 /* Locally generated packet, fetch the security label from the
5564 * associated socket. */
5565 struct sk_security_struct *sksec = sk->sk_security;
5566 peer_sid = sksec->sid;
5567 secmark_perm = PACKET__SEND;
5570 ad.type = LSM_AUDIT_DATA_NET;
5572 ad.u.net->netif = ifindex;
5573 ad.u.net->family = family;
5574 if (selinux_parse_skb(skb, &ad, &addrp, 0, NULL))
5578 if (avc_has_perm(&selinux_state,
5579 peer_sid, skb->secmark,
5580 SECCLASS_PACKET, secmark_perm, &ad))
5581 return NF_DROP_ERR(-ECONNREFUSED);
5583 if (peerlbl_active) {
5587 if (sel_netif_sid(dev_net(outdev), ifindex, &if_sid))
5589 if (avc_has_perm(&selinux_state,
5591 SECCLASS_NETIF, NETIF__EGRESS, &ad))
5592 return NF_DROP_ERR(-ECONNREFUSED);
5594 if (sel_netnode_sid(addrp, family, &node_sid))
5596 if (avc_has_perm(&selinux_state,
5598 SECCLASS_NODE, NODE__SENDTO, &ad))
5599 return NF_DROP_ERR(-ECONNREFUSED);
5605 static unsigned int selinux_ipv4_postroute(void *priv,
5606 struct sk_buff *skb,
5607 const struct nf_hook_state *state)
5609 return selinux_ip_postroute(skb, state->out, PF_INET);
5612 #if IS_ENABLED(CONFIG_IPV6)
5613 static unsigned int selinux_ipv6_postroute(void *priv,
5614 struct sk_buff *skb,
5615 const struct nf_hook_state *state)
5617 return selinux_ip_postroute(skb, state->out, PF_INET6);
5621 #endif /* CONFIG_NETFILTER */
5623 static int selinux_netlink_send(struct sock *sk, struct sk_buff *skb)
5625 return selinux_nlmsg_perm(sk, skb);
5628 static void ipc_init_security(struct ipc_security_struct *isec, u16 sclass)
5630 isec->sclass = sclass;
5631 isec->sid = current_sid();
5634 static int msg_msg_alloc_security(struct msg_msg *msg)
5636 struct msg_security_struct *msec;
5638 msec = selinux_msg_msg(msg);
5639 msec->sid = SECINITSID_UNLABELED;
5644 static int ipc_has_perm(struct kern_ipc_perm *ipc_perms,
5647 struct ipc_security_struct *isec;
5648 struct common_audit_data ad;
5649 u32 sid = current_sid();
5651 isec = selinux_ipc(ipc_perms);
5653 ad.type = LSM_AUDIT_DATA_IPC;
5654 ad.u.ipc_id = ipc_perms->key;
5656 return avc_has_perm(&selinux_state,
5657 sid, isec->sid, isec->sclass, perms, &ad);
5660 static int selinux_msg_msg_alloc_security(struct msg_msg *msg)
5662 return msg_msg_alloc_security(msg);
5665 /* message queue security operations */
5666 static int selinux_msg_queue_alloc_security(struct kern_ipc_perm *msq)
5668 struct ipc_security_struct *isec;
5669 struct common_audit_data ad;
5670 u32 sid = current_sid();
5673 isec = selinux_ipc(msq);
5674 ipc_init_security(isec, SECCLASS_MSGQ);
5676 ad.type = LSM_AUDIT_DATA_IPC;
5677 ad.u.ipc_id = msq->key;
5679 rc = avc_has_perm(&selinux_state,
5680 sid, isec->sid, SECCLASS_MSGQ,
5685 static int selinux_msg_queue_associate(struct kern_ipc_perm *msq, int msqflg)
5687 struct ipc_security_struct *isec;
5688 struct common_audit_data ad;
5689 u32 sid = current_sid();
5691 isec = selinux_ipc(msq);
5693 ad.type = LSM_AUDIT_DATA_IPC;
5694 ad.u.ipc_id = msq->key;
5696 return avc_has_perm(&selinux_state,
5697 sid, isec->sid, SECCLASS_MSGQ,
5698 MSGQ__ASSOCIATE, &ad);
5701 static int selinux_msg_queue_msgctl(struct kern_ipc_perm *msq, int cmd)
5709 /* No specific object, just general system-wide information. */
5710 return avc_has_perm(&selinux_state,
5711 current_sid(), SECINITSID_KERNEL,
5712 SECCLASS_SYSTEM, SYSTEM__IPC_INFO, NULL);
5716 perms = MSGQ__GETATTR | MSGQ__ASSOCIATE;
5719 perms = MSGQ__SETATTR;
5722 perms = MSGQ__DESTROY;
5728 err = ipc_has_perm(msq, perms);
5732 static int selinux_msg_queue_msgsnd(struct kern_ipc_perm *msq, struct msg_msg *msg, int msqflg)
5734 struct ipc_security_struct *isec;
5735 struct msg_security_struct *msec;
5736 struct common_audit_data ad;
5737 u32 sid = current_sid();
5740 isec = selinux_ipc(msq);
5741 msec = selinux_msg_msg(msg);
5744 * First time through, need to assign label to the message
5746 if (msec->sid == SECINITSID_UNLABELED) {
5748 * Compute new sid based on current process and
5749 * message queue this message will be stored in
5751 rc = security_transition_sid(&selinux_state, sid, isec->sid,
5752 SECCLASS_MSG, NULL, &msec->sid);
5757 ad.type = LSM_AUDIT_DATA_IPC;
5758 ad.u.ipc_id = msq->key;
5760 /* Can this process write to the queue? */
5761 rc = avc_has_perm(&selinux_state,
5762 sid, isec->sid, SECCLASS_MSGQ,
5765 /* Can this process send the message */
5766 rc = avc_has_perm(&selinux_state,
5767 sid, msec->sid, SECCLASS_MSG,
5770 /* Can the message be put in the queue? */
5771 rc = avc_has_perm(&selinux_state,
5772 msec->sid, isec->sid, SECCLASS_MSGQ,
5773 MSGQ__ENQUEUE, &ad);
5778 static int selinux_msg_queue_msgrcv(struct kern_ipc_perm *msq, struct msg_msg *msg,
5779 struct task_struct *target,
5780 long type, int mode)
5782 struct ipc_security_struct *isec;
5783 struct msg_security_struct *msec;
5784 struct common_audit_data ad;
5785 u32 sid = task_sid(target);
5788 isec = selinux_ipc(msq);
5789 msec = selinux_msg_msg(msg);
5791 ad.type = LSM_AUDIT_DATA_IPC;
5792 ad.u.ipc_id = msq->key;
5794 rc = avc_has_perm(&selinux_state,
5796 SECCLASS_MSGQ, MSGQ__READ, &ad);
5798 rc = avc_has_perm(&selinux_state,
5800 SECCLASS_MSG, MSG__RECEIVE, &ad);
5804 /* Shared Memory security operations */
5805 static int selinux_shm_alloc_security(struct kern_ipc_perm *shp)
5807 struct ipc_security_struct *isec;
5808 struct common_audit_data ad;
5809 u32 sid = current_sid();
5812 isec = selinux_ipc(shp);
5813 ipc_init_security(isec, SECCLASS_SHM);
5815 ad.type = LSM_AUDIT_DATA_IPC;
5816 ad.u.ipc_id = shp->key;
5818 rc = avc_has_perm(&selinux_state,
5819 sid, isec->sid, SECCLASS_SHM,
5824 static int selinux_shm_associate(struct kern_ipc_perm *shp, int shmflg)
5826 struct ipc_security_struct *isec;
5827 struct common_audit_data ad;
5828 u32 sid = current_sid();
5830 isec = selinux_ipc(shp);
5832 ad.type = LSM_AUDIT_DATA_IPC;
5833 ad.u.ipc_id = shp->key;
5835 return avc_has_perm(&selinux_state,
5836 sid, isec->sid, SECCLASS_SHM,
5837 SHM__ASSOCIATE, &ad);
5840 /* Note, at this point, shp is locked down */
5841 static int selinux_shm_shmctl(struct kern_ipc_perm *shp, int cmd)
5849 /* No specific object, just general system-wide information. */
5850 return avc_has_perm(&selinux_state,
5851 current_sid(), SECINITSID_KERNEL,
5852 SECCLASS_SYSTEM, SYSTEM__IPC_INFO, NULL);
5856 perms = SHM__GETATTR | SHM__ASSOCIATE;
5859 perms = SHM__SETATTR;
5866 perms = SHM__DESTROY;
5872 err = ipc_has_perm(shp, perms);
5876 static int selinux_shm_shmat(struct kern_ipc_perm *shp,
5877 char __user *shmaddr, int shmflg)
5881 if (shmflg & SHM_RDONLY)
5884 perms = SHM__READ | SHM__WRITE;
5886 return ipc_has_perm(shp, perms);
5889 /* Semaphore security operations */
5890 static int selinux_sem_alloc_security(struct kern_ipc_perm *sma)
5892 struct ipc_security_struct *isec;
5893 struct common_audit_data ad;
5894 u32 sid = current_sid();
5897 isec = selinux_ipc(sma);
5898 ipc_init_security(isec, SECCLASS_SEM);
5900 ad.type = LSM_AUDIT_DATA_IPC;
5901 ad.u.ipc_id = sma->key;
5903 rc = avc_has_perm(&selinux_state,
5904 sid, isec->sid, SECCLASS_SEM,
5909 static int selinux_sem_associate(struct kern_ipc_perm *sma, int semflg)
5911 struct ipc_security_struct *isec;
5912 struct common_audit_data ad;
5913 u32 sid = current_sid();
5915 isec = selinux_ipc(sma);
5917 ad.type = LSM_AUDIT_DATA_IPC;
5918 ad.u.ipc_id = sma->key;
5920 return avc_has_perm(&selinux_state,
5921 sid, isec->sid, SECCLASS_SEM,
5922 SEM__ASSOCIATE, &ad);
5925 /* Note, at this point, sma is locked down */
5926 static int selinux_sem_semctl(struct kern_ipc_perm *sma, int cmd)
5934 /* No specific object, just general system-wide information. */
5935 return avc_has_perm(&selinux_state,
5936 current_sid(), SECINITSID_KERNEL,
5937 SECCLASS_SYSTEM, SYSTEM__IPC_INFO, NULL);
5941 perms = SEM__GETATTR;
5952 perms = SEM__DESTROY;
5955 perms = SEM__SETATTR;
5960 perms = SEM__GETATTR | SEM__ASSOCIATE;
5966 err = ipc_has_perm(sma, perms);
5970 static int selinux_sem_semop(struct kern_ipc_perm *sma,
5971 struct sembuf *sops, unsigned nsops, int alter)
5976 perms = SEM__READ | SEM__WRITE;
5980 return ipc_has_perm(sma, perms);
5983 static int selinux_ipc_permission(struct kern_ipc_perm *ipcp, short flag)
5989 av |= IPC__UNIX_READ;
5991 av |= IPC__UNIX_WRITE;
5996 return ipc_has_perm(ipcp, av);
5999 static void selinux_ipc_getsecid(struct kern_ipc_perm *ipcp, u32 *secid)
6001 struct ipc_security_struct *isec = selinux_ipc(ipcp);
6005 static void selinux_d_instantiate(struct dentry *dentry, struct inode *inode)
6008 inode_doinit_with_dentry(inode, dentry);
6011 static int selinux_getprocattr(struct task_struct *p,
6012 char *name, char **value)
6014 const struct task_security_struct *__tsec;
6020 __tsec = selinux_cred(__task_cred(p));
6023 error = avc_has_perm(&selinux_state,
6024 current_sid(), __tsec->sid,
6025 SECCLASS_PROCESS, PROCESS__GETATTR, NULL);
6030 if (!strcmp(name, "current"))
6032 else if (!strcmp(name, "prev"))
6034 else if (!strcmp(name, "exec"))
6035 sid = __tsec->exec_sid;
6036 else if (!strcmp(name, "fscreate"))
6037 sid = __tsec->create_sid;
6038 else if (!strcmp(name, "keycreate"))
6039 sid = __tsec->keycreate_sid;
6040 else if (!strcmp(name, "sockcreate"))
6041 sid = __tsec->sockcreate_sid;
6051 error = security_sid_to_context(&selinux_state, sid, value, &len);
6061 static int selinux_setprocattr(const char *name, void *value, size_t size)
6063 struct task_security_struct *tsec;
6065 u32 mysid = current_sid(), sid = 0, ptsid;
6070 * Basic control over ability to set these attributes at all.
6072 if (!strcmp(name, "exec"))
6073 error = avc_has_perm(&selinux_state,
6074 mysid, mysid, SECCLASS_PROCESS,
6075 PROCESS__SETEXEC, NULL);
6076 else if (!strcmp(name, "fscreate"))
6077 error = avc_has_perm(&selinux_state,
6078 mysid, mysid, SECCLASS_PROCESS,
6079 PROCESS__SETFSCREATE, NULL);
6080 else if (!strcmp(name, "keycreate"))
6081 error = avc_has_perm(&selinux_state,
6082 mysid, mysid, SECCLASS_PROCESS,
6083 PROCESS__SETKEYCREATE, NULL);
6084 else if (!strcmp(name, "sockcreate"))
6085 error = avc_has_perm(&selinux_state,
6086 mysid, mysid, SECCLASS_PROCESS,
6087 PROCESS__SETSOCKCREATE, NULL);
6088 else if (!strcmp(name, "current"))
6089 error = avc_has_perm(&selinux_state,
6090 mysid, mysid, SECCLASS_PROCESS,
6091 PROCESS__SETCURRENT, NULL);
6097 /* Obtain a SID for the context, if one was specified. */
6098 if (size && str[0] && str[0] != '\n') {
6099 if (str[size-1] == '\n') {
6103 error = security_context_to_sid(&selinux_state, value, size,
6105 if (error == -EINVAL && !strcmp(name, "fscreate")) {
6106 if (!has_cap_mac_admin(true)) {
6107 struct audit_buffer *ab;
6110 /* We strip a nul only if it is at the end, otherwise the
6111 * context contains a nul and we should audit that */
6112 if (str[size - 1] == '\0')
6113 audit_size = size - 1;
6116 ab = audit_log_start(audit_context(),
6119 audit_log_format(ab, "op=fscreate invalid_context=");
6120 audit_log_n_untrustedstring(ab, value, audit_size);
6125 error = security_context_to_sid_force(
6133 new = prepare_creds();
6137 /* Permission checking based on the specified context is
6138 performed during the actual operation (execve,
6139 open/mkdir/...), when we know the full context of the
6140 operation. See selinux_bprm_set_creds for the execve
6141 checks and may_create for the file creation checks. The
6142 operation will then fail if the context is not permitted. */
6143 tsec = selinux_cred(new);
6144 if (!strcmp(name, "exec")) {
6145 tsec->exec_sid = sid;
6146 } else if (!strcmp(name, "fscreate")) {
6147 tsec->create_sid = sid;
6148 } else if (!strcmp(name, "keycreate")) {
6149 error = avc_has_perm(&selinux_state,
6150 mysid, sid, SECCLASS_KEY, KEY__CREATE,
6154 tsec->keycreate_sid = sid;
6155 } else if (!strcmp(name, "sockcreate")) {
6156 tsec->sockcreate_sid = sid;
6157 } else if (!strcmp(name, "current")) {
6162 /* Only allow single threaded processes to change context */
6164 if (!current_is_single_threaded()) {
6165 error = security_bounded_transition(&selinux_state,
6171 /* Check permissions for the transition. */
6172 error = avc_has_perm(&selinux_state,
6173 tsec->sid, sid, SECCLASS_PROCESS,
6174 PROCESS__DYNTRANSITION, NULL);
6178 /* Check for ptracing, and update the task SID if ok.
6179 Otherwise, leave SID unchanged and fail. */
6180 ptsid = ptrace_parent_sid();
6182 error = avc_has_perm(&selinux_state,
6183 ptsid, sid, SECCLASS_PROCESS,
6184 PROCESS__PTRACE, NULL);
6203 static int selinux_ismaclabel(const char *name)
6205 return (strcmp(name, XATTR_SELINUX_SUFFIX) == 0);
6208 static int selinux_secid_to_secctx(u32 secid, char **secdata, u32 *seclen)
6210 return security_sid_to_context(&selinux_state, secid,
6214 static int selinux_secctx_to_secid(const char *secdata, u32 seclen, u32 *secid)
6216 return security_context_to_sid(&selinux_state, secdata, seclen,
6220 static void selinux_release_secctx(char *secdata, u32 seclen)
6225 static void selinux_inode_invalidate_secctx(struct inode *inode)
6227 struct inode_security_struct *isec = selinux_inode(inode);
6229 spin_lock(&isec->lock);
6230 isec->initialized = LABEL_INVALID;
6231 spin_unlock(&isec->lock);
6235 * called with inode->i_mutex locked
6237 static int selinux_inode_notifysecctx(struct inode *inode, void *ctx, u32 ctxlen)
6239 return selinux_inode_setsecurity(inode, XATTR_SELINUX_SUFFIX, ctx, ctxlen, 0);
6243 * called with inode->i_mutex locked
6245 static int selinux_inode_setsecctx(struct dentry *dentry, void *ctx, u32 ctxlen)
6247 return __vfs_setxattr_noperm(dentry, XATTR_NAME_SELINUX, ctx, ctxlen, 0);
6250 static int selinux_inode_getsecctx(struct inode *inode, void **ctx, u32 *ctxlen)
6253 len = selinux_inode_getsecurity(inode, XATTR_SELINUX_SUFFIX,
6262 static int selinux_key_alloc(struct key *k, const struct cred *cred,
6263 unsigned long flags)
6265 const struct task_security_struct *tsec;
6266 struct key_security_struct *ksec;
6268 ksec = kzalloc(sizeof(struct key_security_struct), GFP_KERNEL);
6272 tsec = selinux_cred(cred);
6273 if (tsec->keycreate_sid)
6274 ksec->sid = tsec->keycreate_sid;
6276 ksec->sid = tsec->sid;
6282 static void selinux_key_free(struct key *k)
6284 struct key_security_struct *ksec = k->security;
6290 static int selinux_key_permission(key_ref_t key_ref,
6291 const struct cred *cred,
6295 struct key_security_struct *ksec;
6298 /* if no specific permissions are requested, we skip the
6299 permission check. No serious, additional covert channels
6300 appear to be created. */
6304 sid = cred_sid(cred);
6306 key = key_ref_to_ptr(key_ref);
6307 ksec = key->security;
6309 return avc_has_perm(&selinux_state,
6310 sid, ksec->sid, SECCLASS_KEY, perm, NULL);
6313 static int selinux_key_getsecurity(struct key *key, char **_buffer)
6315 struct key_security_struct *ksec = key->security;
6316 char *context = NULL;
6320 rc = security_sid_to_context(&selinux_state, ksec->sid,
6329 #ifdef CONFIG_SECURITY_INFINIBAND
6330 static int selinux_ib_pkey_access(void *ib_sec, u64 subnet_prefix, u16 pkey_val)
6332 struct common_audit_data ad;
6335 struct ib_security_struct *sec = ib_sec;
6336 struct lsm_ibpkey_audit ibpkey;
6338 err = sel_ib_pkey_sid(subnet_prefix, pkey_val, &sid);
6342 ad.type = LSM_AUDIT_DATA_IBPKEY;
6343 ibpkey.subnet_prefix = subnet_prefix;
6344 ibpkey.pkey = pkey_val;
6345 ad.u.ibpkey = &ibpkey;
6346 return avc_has_perm(&selinux_state,
6348 SECCLASS_INFINIBAND_PKEY,
6349 INFINIBAND_PKEY__ACCESS, &ad);
6352 static int selinux_ib_endport_manage_subnet(void *ib_sec, const char *dev_name,
6355 struct common_audit_data ad;
6358 struct ib_security_struct *sec = ib_sec;
6359 struct lsm_ibendport_audit ibendport;
6361 err = security_ib_endport_sid(&selinux_state, dev_name, port_num,
6367 ad.type = LSM_AUDIT_DATA_IBENDPORT;
6368 strncpy(ibendport.dev_name, dev_name, sizeof(ibendport.dev_name));
6369 ibendport.port = port_num;
6370 ad.u.ibendport = &ibendport;
6371 return avc_has_perm(&selinux_state,
6373 SECCLASS_INFINIBAND_ENDPORT,
6374 INFINIBAND_ENDPORT__MANAGE_SUBNET, &ad);
6377 static int selinux_ib_alloc_security(void **ib_sec)
6379 struct ib_security_struct *sec;
6381 sec = kzalloc(sizeof(*sec), GFP_KERNEL);
6384 sec->sid = current_sid();
6390 static void selinux_ib_free_security(void *ib_sec)
6396 #ifdef CONFIG_BPF_SYSCALL
6397 static int selinux_bpf(int cmd, union bpf_attr *attr,
6400 u32 sid = current_sid();
6404 case BPF_MAP_CREATE:
6405 ret = avc_has_perm(&selinux_state,
6406 sid, sid, SECCLASS_BPF, BPF__MAP_CREATE,
6410 ret = avc_has_perm(&selinux_state,
6411 sid, sid, SECCLASS_BPF, BPF__PROG_LOAD,
6422 static u32 bpf_map_fmode_to_av(fmode_t fmode)
6426 if (fmode & FMODE_READ)
6427 av |= BPF__MAP_READ;
6428 if (fmode & FMODE_WRITE)
6429 av |= BPF__MAP_WRITE;
6433 /* This function will check the file pass through unix socket or binder to see
6434 * if it is a bpf related object. And apply correspinding checks on the bpf
6435 * object based on the type. The bpf maps and programs, not like other files and
6436 * socket, are using a shared anonymous inode inside the kernel as their inode.
6437 * So checking that inode cannot identify if the process have privilege to
6438 * access the bpf object and that's why we have to add this additional check in
6439 * selinux_file_receive and selinux_binder_transfer_files.
6441 static int bpf_fd_pass(struct file *file, u32 sid)
6443 struct bpf_security_struct *bpfsec;
6444 struct bpf_prog *prog;
6445 struct bpf_map *map;
6448 if (file->f_op == &bpf_map_fops) {
6449 map = file->private_data;
6450 bpfsec = map->security;
6451 ret = avc_has_perm(&selinux_state,
6452 sid, bpfsec->sid, SECCLASS_BPF,
6453 bpf_map_fmode_to_av(file->f_mode), NULL);
6456 } else if (file->f_op == &bpf_prog_fops) {
6457 prog = file->private_data;
6458 bpfsec = prog->aux->security;
6459 ret = avc_has_perm(&selinux_state,
6460 sid, bpfsec->sid, SECCLASS_BPF,
6461 BPF__PROG_RUN, NULL);
6468 static int selinux_bpf_map(struct bpf_map *map, fmode_t fmode)
6470 u32 sid = current_sid();
6471 struct bpf_security_struct *bpfsec;
6473 bpfsec = map->security;
6474 return avc_has_perm(&selinux_state,
6475 sid, bpfsec->sid, SECCLASS_BPF,
6476 bpf_map_fmode_to_av(fmode), NULL);
6479 static int selinux_bpf_prog(struct bpf_prog *prog)
6481 u32 sid = current_sid();
6482 struct bpf_security_struct *bpfsec;
6484 bpfsec = prog->aux->security;
6485 return avc_has_perm(&selinux_state,
6486 sid, bpfsec->sid, SECCLASS_BPF,
6487 BPF__PROG_RUN, NULL);
6490 static int selinux_bpf_map_alloc(struct bpf_map *map)
6492 struct bpf_security_struct *bpfsec;
6494 bpfsec = kzalloc(sizeof(*bpfsec), GFP_KERNEL);
6498 bpfsec->sid = current_sid();
6499 map->security = bpfsec;
6504 static void selinux_bpf_map_free(struct bpf_map *map)
6506 struct bpf_security_struct *bpfsec = map->security;
6508 map->security = NULL;
6512 static int selinux_bpf_prog_alloc(struct bpf_prog_aux *aux)
6514 struct bpf_security_struct *bpfsec;
6516 bpfsec = kzalloc(sizeof(*bpfsec), GFP_KERNEL);
6520 bpfsec->sid = current_sid();
6521 aux->security = bpfsec;
6526 static void selinux_bpf_prog_free(struct bpf_prog_aux *aux)
6528 struct bpf_security_struct *bpfsec = aux->security;
6530 aux->security = NULL;
6535 struct lsm_blob_sizes selinux_blob_sizes __lsm_ro_after_init = {
6536 .lbs_cred = sizeof(struct task_security_struct),
6537 .lbs_file = sizeof(struct file_security_struct),
6538 .lbs_inode = sizeof(struct inode_security_struct),
6539 .lbs_ipc = sizeof(struct ipc_security_struct),
6540 .lbs_msg_msg = sizeof(struct msg_security_struct),
6543 static struct security_hook_list selinux_hooks[] __lsm_ro_after_init = {
6544 LSM_HOOK_INIT(binder_set_context_mgr, selinux_binder_set_context_mgr),
6545 LSM_HOOK_INIT(binder_transaction, selinux_binder_transaction),
6546 LSM_HOOK_INIT(binder_transfer_binder, selinux_binder_transfer_binder),
6547 LSM_HOOK_INIT(binder_transfer_file, selinux_binder_transfer_file),
6549 LSM_HOOK_INIT(ptrace_access_check, selinux_ptrace_access_check),
6550 LSM_HOOK_INIT(ptrace_traceme, selinux_ptrace_traceme),
6551 LSM_HOOK_INIT(capget, selinux_capget),
6552 LSM_HOOK_INIT(capset, selinux_capset),
6553 LSM_HOOK_INIT(capable, selinux_capable),
6554 LSM_HOOK_INIT(quotactl, selinux_quotactl),
6555 LSM_HOOK_INIT(quota_on, selinux_quota_on),
6556 LSM_HOOK_INIT(syslog, selinux_syslog),
6557 LSM_HOOK_INIT(vm_enough_memory, selinux_vm_enough_memory),
6559 LSM_HOOK_INIT(netlink_send, selinux_netlink_send),
6561 LSM_HOOK_INIT(bprm_set_creds, selinux_bprm_set_creds),
6562 LSM_HOOK_INIT(bprm_committing_creds, selinux_bprm_committing_creds),
6563 LSM_HOOK_INIT(bprm_committed_creds, selinux_bprm_committed_creds),
6565 LSM_HOOK_INIT(sb_alloc_security, selinux_sb_alloc_security),
6566 LSM_HOOK_INIT(sb_free_security, selinux_sb_free_security),
6567 LSM_HOOK_INIT(sb_eat_lsm_opts, selinux_sb_eat_lsm_opts),
6568 LSM_HOOK_INIT(sb_free_mnt_opts, selinux_free_mnt_opts),
6569 LSM_HOOK_INIT(sb_remount, selinux_sb_remount),
6570 LSM_HOOK_INIT(sb_kern_mount, selinux_sb_kern_mount),
6571 LSM_HOOK_INIT(sb_show_options, selinux_sb_show_options),
6572 LSM_HOOK_INIT(sb_statfs, selinux_sb_statfs),
6573 LSM_HOOK_INIT(sb_mount, selinux_mount),
6574 LSM_HOOK_INIT(sb_umount, selinux_umount),
6575 LSM_HOOK_INIT(sb_set_mnt_opts, selinux_set_mnt_opts),
6576 LSM_HOOK_INIT(sb_clone_mnt_opts, selinux_sb_clone_mnt_opts),
6577 LSM_HOOK_INIT(sb_add_mnt_opt, selinux_add_mnt_opt),
6579 LSM_HOOK_INIT(dentry_init_security, selinux_dentry_init_security),
6580 LSM_HOOK_INIT(dentry_create_files_as, selinux_dentry_create_files_as),
6582 LSM_HOOK_INIT(inode_alloc_security, selinux_inode_alloc_security),
6583 LSM_HOOK_INIT(inode_free_security, selinux_inode_free_security),
6584 LSM_HOOK_INIT(inode_init_security, selinux_inode_init_security),
6585 LSM_HOOK_INIT(inode_create, selinux_inode_create),
6586 LSM_HOOK_INIT(inode_link, selinux_inode_link),
6587 LSM_HOOK_INIT(inode_unlink, selinux_inode_unlink),
6588 LSM_HOOK_INIT(inode_symlink, selinux_inode_symlink),
6589 LSM_HOOK_INIT(inode_mkdir, selinux_inode_mkdir),
6590 LSM_HOOK_INIT(inode_rmdir, selinux_inode_rmdir),
6591 LSM_HOOK_INIT(inode_mknod, selinux_inode_mknod),
6592 LSM_HOOK_INIT(inode_rename, selinux_inode_rename),
6593 LSM_HOOK_INIT(inode_readlink, selinux_inode_readlink),
6594 LSM_HOOK_INIT(inode_follow_link, selinux_inode_follow_link),
6595 LSM_HOOK_INIT(inode_permission, selinux_inode_permission),
6596 LSM_HOOK_INIT(inode_setattr, selinux_inode_setattr),
6597 LSM_HOOK_INIT(inode_getattr, selinux_inode_getattr),
6598 LSM_HOOK_INIT(inode_setxattr, selinux_inode_setxattr),
6599 LSM_HOOK_INIT(inode_post_setxattr, selinux_inode_post_setxattr),
6600 LSM_HOOK_INIT(inode_getxattr, selinux_inode_getxattr),
6601 LSM_HOOK_INIT(inode_listxattr, selinux_inode_listxattr),
6602 LSM_HOOK_INIT(inode_removexattr, selinux_inode_removexattr),
6603 LSM_HOOK_INIT(inode_getsecurity, selinux_inode_getsecurity),
6604 LSM_HOOK_INIT(inode_setsecurity, selinux_inode_setsecurity),
6605 LSM_HOOK_INIT(inode_listsecurity, selinux_inode_listsecurity),
6606 LSM_HOOK_INIT(inode_getsecid, selinux_inode_getsecid),
6607 LSM_HOOK_INIT(inode_copy_up, selinux_inode_copy_up),
6608 LSM_HOOK_INIT(inode_copy_up_xattr, selinux_inode_copy_up_xattr),
6610 LSM_HOOK_INIT(file_permission, selinux_file_permission),
6611 LSM_HOOK_INIT(file_alloc_security, selinux_file_alloc_security),
6612 LSM_HOOK_INIT(file_ioctl, selinux_file_ioctl),
6613 LSM_HOOK_INIT(mmap_file, selinux_mmap_file),
6614 LSM_HOOK_INIT(mmap_addr, selinux_mmap_addr),
6615 LSM_HOOK_INIT(file_mprotect, selinux_file_mprotect),
6616 LSM_HOOK_INIT(file_lock, selinux_file_lock),
6617 LSM_HOOK_INIT(file_fcntl, selinux_file_fcntl),
6618 LSM_HOOK_INIT(file_set_fowner, selinux_file_set_fowner),
6619 LSM_HOOK_INIT(file_send_sigiotask, selinux_file_send_sigiotask),
6620 LSM_HOOK_INIT(file_receive, selinux_file_receive),
6622 LSM_HOOK_INIT(file_open, selinux_file_open),
6624 LSM_HOOK_INIT(task_alloc, selinux_task_alloc),
6625 LSM_HOOK_INIT(cred_prepare, selinux_cred_prepare),
6626 LSM_HOOK_INIT(cred_transfer, selinux_cred_transfer),
6627 LSM_HOOK_INIT(cred_getsecid, selinux_cred_getsecid),
6628 LSM_HOOK_INIT(kernel_act_as, selinux_kernel_act_as),
6629 LSM_HOOK_INIT(kernel_create_files_as, selinux_kernel_create_files_as),
6630 LSM_HOOK_INIT(kernel_module_request, selinux_kernel_module_request),
6631 LSM_HOOK_INIT(kernel_load_data, selinux_kernel_load_data),
6632 LSM_HOOK_INIT(kernel_read_file, selinux_kernel_read_file),
6633 LSM_HOOK_INIT(task_setpgid, selinux_task_setpgid),
6634 LSM_HOOK_INIT(task_getpgid, selinux_task_getpgid),
6635 LSM_HOOK_INIT(task_getsid, selinux_task_getsid),
6636 LSM_HOOK_INIT(task_getsecid, selinux_task_getsecid),
6637 LSM_HOOK_INIT(task_setnice, selinux_task_setnice),
6638 LSM_HOOK_INIT(task_setioprio, selinux_task_setioprio),
6639 LSM_HOOK_INIT(task_getioprio, selinux_task_getioprio),
6640 LSM_HOOK_INIT(task_prlimit, selinux_task_prlimit),
6641 LSM_HOOK_INIT(task_setrlimit, selinux_task_setrlimit),
6642 LSM_HOOK_INIT(task_setscheduler, selinux_task_setscheduler),
6643 LSM_HOOK_INIT(task_getscheduler, selinux_task_getscheduler),
6644 LSM_HOOK_INIT(task_movememory, selinux_task_movememory),
6645 LSM_HOOK_INIT(task_kill, selinux_task_kill),
6646 LSM_HOOK_INIT(task_to_inode, selinux_task_to_inode),
6648 LSM_HOOK_INIT(ipc_permission, selinux_ipc_permission),
6649 LSM_HOOK_INIT(ipc_getsecid, selinux_ipc_getsecid),
6651 LSM_HOOK_INIT(msg_msg_alloc_security, selinux_msg_msg_alloc_security),
6653 LSM_HOOK_INIT(msg_queue_alloc_security,
6654 selinux_msg_queue_alloc_security),
6655 LSM_HOOK_INIT(msg_queue_associate, selinux_msg_queue_associate),
6656 LSM_HOOK_INIT(msg_queue_msgctl, selinux_msg_queue_msgctl),
6657 LSM_HOOK_INIT(msg_queue_msgsnd, selinux_msg_queue_msgsnd),
6658 LSM_HOOK_INIT(msg_queue_msgrcv, selinux_msg_queue_msgrcv),
6660 LSM_HOOK_INIT(shm_alloc_security, selinux_shm_alloc_security),
6661 LSM_HOOK_INIT(shm_associate, selinux_shm_associate),
6662 LSM_HOOK_INIT(shm_shmctl, selinux_shm_shmctl),
6663 LSM_HOOK_INIT(shm_shmat, selinux_shm_shmat),
6665 LSM_HOOK_INIT(sem_alloc_security, selinux_sem_alloc_security),
6666 LSM_HOOK_INIT(sem_associate, selinux_sem_associate),
6667 LSM_HOOK_INIT(sem_semctl, selinux_sem_semctl),
6668 LSM_HOOK_INIT(sem_semop, selinux_sem_semop),
6670 LSM_HOOK_INIT(d_instantiate, selinux_d_instantiate),
6672 LSM_HOOK_INIT(getprocattr, selinux_getprocattr),
6673 LSM_HOOK_INIT(setprocattr, selinux_setprocattr),
6675 LSM_HOOK_INIT(ismaclabel, selinux_ismaclabel),
6676 LSM_HOOK_INIT(secid_to_secctx, selinux_secid_to_secctx),
6677 LSM_HOOK_INIT(secctx_to_secid, selinux_secctx_to_secid),
6678 LSM_HOOK_INIT(release_secctx, selinux_release_secctx),
6679 LSM_HOOK_INIT(inode_invalidate_secctx, selinux_inode_invalidate_secctx),
6680 LSM_HOOK_INIT(inode_notifysecctx, selinux_inode_notifysecctx),
6681 LSM_HOOK_INIT(inode_setsecctx, selinux_inode_setsecctx),
6682 LSM_HOOK_INIT(inode_getsecctx, selinux_inode_getsecctx),
6684 LSM_HOOK_INIT(unix_stream_connect, selinux_socket_unix_stream_connect),
6685 LSM_HOOK_INIT(unix_may_send, selinux_socket_unix_may_send),
6687 LSM_HOOK_INIT(socket_create, selinux_socket_create),
6688 LSM_HOOK_INIT(socket_post_create, selinux_socket_post_create),
6689 LSM_HOOK_INIT(socket_socketpair, selinux_socket_socketpair),
6690 LSM_HOOK_INIT(socket_bind, selinux_socket_bind),
6691 LSM_HOOK_INIT(socket_connect, selinux_socket_connect),
6692 LSM_HOOK_INIT(socket_listen, selinux_socket_listen),
6693 LSM_HOOK_INIT(socket_accept, selinux_socket_accept),
6694 LSM_HOOK_INIT(socket_sendmsg, selinux_socket_sendmsg),
6695 LSM_HOOK_INIT(socket_recvmsg, selinux_socket_recvmsg),
6696 LSM_HOOK_INIT(socket_getsockname, selinux_socket_getsockname),
6697 LSM_HOOK_INIT(socket_getpeername, selinux_socket_getpeername),
6698 LSM_HOOK_INIT(socket_getsockopt, selinux_socket_getsockopt),
6699 LSM_HOOK_INIT(socket_setsockopt, selinux_socket_setsockopt),
6700 LSM_HOOK_INIT(socket_shutdown, selinux_socket_shutdown),
6701 LSM_HOOK_INIT(socket_sock_rcv_skb, selinux_socket_sock_rcv_skb),
6702 LSM_HOOK_INIT(socket_getpeersec_stream,
6703 selinux_socket_getpeersec_stream),
6704 LSM_HOOK_INIT(socket_getpeersec_dgram, selinux_socket_getpeersec_dgram),
6705 LSM_HOOK_INIT(sk_alloc_security, selinux_sk_alloc_security),
6706 LSM_HOOK_INIT(sk_free_security, selinux_sk_free_security),
6707 LSM_HOOK_INIT(sk_clone_security, selinux_sk_clone_security),
6708 LSM_HOOK_INIT(sk_getsecid, selinux_sk_getsecid),
6709 LSM_HOOK_INIT(sock_graft, selinux_sock_graft),
6710 LSM_HOOK_INIT(sctp_assoc_request, selinux_sctp_assoc_request),
6711 LSM_HOOK_INIT(sctp_sk_clone, selinux_sctp_sk_clone),
6712 LSM_HOOK_INIT(sctp_bind_connect, selinux_sctp_bind_connect),
6713 LSM_HOOK_INIT(inet_conn_request, selinux_inet_conn_request),
6714 LSM_HOOK_INIT(inet_csk_clone, selinux_inet_csk_clone),
6715 LSM_HOOK_INIT(inet_conn_established, selinux_inet_conn_established),
6716 LSM_HOOK_INIT(secmark_relabel_packet, selinux_secmark_relabel_packet),
6717 LSM_HOOK_INIT(secmark_refcount_inc, selinux_secmark_refcount_inc),
6718 LSM_HOOK_INIT(secmark_refcount_dec, selinux_secmark_refcount_dec),
6719 LSM_HOOK_INIT(req_classify_flow, selinux_req_classify_flow),
6720 LSM_HOOK_INIT(tun_dev_alloc_security, selinux_tun_dev_alloc_security),
6721 LSM_HOOK_INIT(tun_dev_free_security, selinux_tun_dev_free_security),
6722 LSM_HOOK_INIT(tun_dev_create, selinux_tun_dev_create),
6723 LSM_HOOK_INIT(tun_dev_attach_queue, selinux_tun_dev_attach_queue),
6724 LSM_HOOK_INIT(tun_dev_attach, selinux_tun_dev_attach),
6725 LSM_HOOK_INIT(tun_dev_open, selinux_tun_dev_open),
6726 #ifdef CONFIG_SECURITY_INFINIBAND
6727 LSM_HOOK_INIT(ib_pkey_access, selinux_ib_pkey_access),
6728 LSM_HOOK_INIT(ib_endport_manage_subnet,
6729 selinux_ib_endport_manage_subnet),
6730 LSM_HOOK_INIT(ib_alloc_security, selinux_ib_alloc_security),
6731 LSM_HOOK_INIT(ib_free_security, selinux_ib_free_security),
6733 #ifdef CONFIG_SECURITY_NETWORK_XFRM
6734 LSM_HOOK_INIT(xfrm_policy_alloc_security, selinux_xfrm_policy_alloc),
6735 LSM_HOOK_INIT(xfrm_policy_clone_security, selinux_xfrm_policy_clone),
6736 LSM_HOOK_INIT(xfrm_policy_free_security, selinux_xfrm_policy_free),
6737 LSM_HOOK_INIT(xfrm_policy_delete_security, selinux_xfrm_policy_delete),
6738 LSM_HOOK_INIT(xfrm_state_alloc, selinux_xfrm_state_alloc),
6739 LSM_HOOK_INIT(xfrm_state_alloc_acquire,
6740 selinux_xfrm_state_alloc_acquire),
6741 LSM_HOOK_INIT(xfrm_state_free_security, selinux_xfrm_state_free),
6742 LSM_HOOK_INIT(xfrm_state_delete_security, selinux_xfrm_state_delete),
6743 LSM_HOOK_INIT(xfrm_policy_lookup, selinux_xfrm_policy_lookup),
6744 LSM_HOOK_INIT(xfrm_state_pol_flow_match,
6745 selinux_xfrm_state_pol_flow_match),
6746 LSM_HOOK_INIT(xfrm_decode_session, selinux_xfrm_decode_session),
6750 LSM_HOOK_INIT(key_alloc, selinux_key_alloc),
6751 LSM_HOOK_INIT(key_free, selinux_key_free),
6752 LSM_HOOK_INIT(key_permission, selinux_key_permission),
6753 LSM_HOOK_INIT(key_getsecurity, selinux_key_getsecurity),
6757 LSM_HOOK_INIT(audit_rule_init, selinux_audit_rule_init),
6758 LSM_HOOK_INIT(audit_rule_known, selinux_audit_rule_known),
6759 LSM_HOOK_INIT(audit_rule_match, selinux_audit_rule_match),
6760 LSM_HOOK_INIT(audit_rule_free, selinux_audit_rule_free),
6763 #ifdef CONFIG_BPF_SYSCALL
6764 LSM_HOOK_INIT(bpf, selinux_bpf),
6765 LSM_HOOK_INIT(bpf_map, selinux_bpf_map),
6766 LSM_HOOK_INIT(bpf_prog, selinux_bpf_prog),
6767 LSM_HOOK_INIT(bpf_map_alloc_security, selinux_bpf_map_alloc),
6768 LSM_HOOK_INIT(bpf_prog_alloc_security, selinux_bpf_prog_alloc),
6769 LSM_HOOK_INIT(bpf_map_free_security, selinux_bpf_map_free),
6770 LSM_HOOK_INIT(bpf_prog_free_security, selinux_bpf_prog_free),
6774 static __init int selinux_init(void)
6776 pr_info("SELinux: Initializing.\n");
6778 memset(&selinux_state, 0, sizeof(selinux_state));
6779 enforcing_set(&selinux_state, selinux_enforcing_boot);
6780 selinux_state.checkreqprot = selinux_checkreqprot_boot;
6781 selinux_ss_init(&selinux_state.ss);
6782 selinux_avc_init(&selinux_state.avc);
6784 /* Set the security state for the initial task. */
6785 cred_init_security();
6787 default_noexec = !(VM_DATA_DEFAULT_FLAGS & VM_EXEC);
6793 ebitmap_cache_init();
6795 hashtab_cache_init();
6797 security_add_hooks(selinux_hooks, ARRAY_SIZE(selinux_hooks), "selinux");
6799 if (avc_add_callback(selinux_netcache_avc_callback, AVC_CALLBACK_RESET))
6800 panic("SELinux: Unable to register AVC netcache callback\n");
6802 if (avc_add_callback(selinux_lsm_notifier_avc_callback, AVC_CALLBACK_RESET))
6803 panic("SELinux: Unable to register AVC LSM notifier callback\n");
6805 if (selinux_enforcing_boot)
6806 pr_debug("SELinux: Starting in enforcing mode\n");
6808 pr_debug("SELinux: Starting in permissive mode\n");
6813 static void delayed_superblock_init(struct super_block *sb, void *unused)
6815 selinux_set_mnt_opts(sb, NULL, 0, NULL);
6818 void selinux_complete_init(void)
6820 pr_debug("SELinux: Completing initialization.\n");
6822 /* Set up any superblocks initialized prior to the policy load. */
6823 pr_debug("SELinux: Setting up existing superblocks.\n");
6824 iterate_supers(delayed_superblock_init, NULL);
6827 /* SELinux requires early initialization in order to label
6828 all processes and objects when they are created. */
6829 DEFINE_LSM(selinux) = {
6831 .flags = LSM_FLAG_LEGACY_MAJOR | LSM_FLAG_EXCLUSIVE,
6832 .enabled = &selinux_enabled,
6833 .blobs = &selinux_blob_sizes,
6834 .init = selinux_init,
6837 #if defined(CONFIG_NETFILTER)
6839 static const struct nf_hook_ops selinux_nf_ops[] = {
6841 .hook = selinux_ipv4_postroute,
6843 .hooknum = NF_INET_POST_ROUTING,
6844 .priority = NF_IP_PRI_SELINUX_LAST,
6847 .hook = selinux_ipv4_forward,
6849 .hooknum = NF_INET_FORWARD,
6850 .priority = NF_IP_PRI_SELINUX_FIRST,
6853 .hook = selinux_ipv4_output,
6855 .hooknum = NF_INET_LOCAL_OUT,
6856 .priority = NF_IP_PRI_SELINUX_FIRST,
6858 #if IS_ENABLED(CONFIG_IPV6)
6860 .hook = selinux_ipv6_postroute,
6862 .hooknum = NF_INET_POST_ROUTING,
6863 .priority = NF_IP6_PRI_SELINUX_LAST,
6866 .hook = selinux_ipv6_forward,
6868 .hooknum = NF_INET_FORWARD,
6869 .priority = NF_IP6_PRI_SELINUX_FIRST,
6872 .hook = selinux_ipv6_output,
6874 .hooknum = NF_INET_LOCAL_OUT,
6875 .priority = NF_IP6_PRI_SELINUX_FIRST,
6880 static int __net_init selinux_nf_register(struct net *net)
6882 return nf_register_net_hooks(net, selinux_nf_ops,
6883 ARRAY_SIZE(selinux_nf_ops));
6886 static void __net_exit selinux_nf_unregister(struct net *net)
6888 nf_unregister_net_hooks(net, selinux_nf_ops,
6889 ARRAY_SIZE(selinux_nf_ops));
6892 static struct pernet_operations selinux_net_ops = {
6893 .init = selinux_nf_register,
6894 .exit = selinux_nf_unregister,
6897 static int __init selinux_nf_ip_init(void)
6901 if (!selinux_enabled)
6904 pr_debug("SELinux: Registering netfilter hooks\n");
6906 err = register_pernet_subsys(&selinux_net_ops);
6908 panic("SELinux: register_pernet_subsys: error %d\n", err);
6912 __initcall(selinux_nf_ip_init);
6914 #ifdef CONFIG_SECURITY_SELINUX_DISABLE
6915 static void selinux_nf_ip_exit(void)
6917 pr_debug("SELinux: Unregistering netfilter hooks\n");
6919 unregister_pernet_subsys(&selinux_net_ops);
6923 #else /* CONFIG_NETFILTER */
6925 #ifdef CONFIG_SECURITY_SELINUX_DISABLE
6926 #define selinux_nf_ip_exit()
6929 #endif /* CONFIG_NETFILTER */
6931 #ifdef CONFIG_SECURITY_SELINUX_DISABLE
6932 int selinux_disable(struct selinux_state *state)
6934 if (state->initialized) {
6935 /* Not permitted after initial policy load. */
6939 if (state->disabled) {
6940 /* Only do this once. */
6944 state->disabled = 1;
6946 pr_info("SELinux: Disabled at runtime.\n");
6948 selinux_enabled = 0;
6950 security_delete_hooks(selinux_hooks, ARRAY_SIZE(selinux_hooks));
6952 /* Try to destroy the avc node cache */
6955 /* Unregister netfilter hooks. */
6956 selinux_nf_ip_exit();
6958 /* Unregister selinuxfs. */