1 // SPDX-License-Identifier: GPL-2.0-only
3 * Security-Enhanced Linux (SELinux) security module
5 * This file contains the SELinux hook function implementations.
12 * Copyright (C) 2001,2002 Networks Associates Technology, Inc.
15 * Copyright (C) 2004-2005 Trusted Computer Solutions, Inc.
17 * Copyright (C) 2006, 2007, 2009 Hewlett-Packard Development Company, L.P.
19 * Copyright (C) 2007 Hitachi Software Engineering Co., Ltd.
21 * Copyright (C) 2016 Mellanox Technologies
24 #include <linux/init.h>
26 #include <linux/kernel.h>
27 #include <linux/kernel_read_file.h>
28 #include <linux/errno.h>
29 #include <linux/sched/signal.h>
30 #include <linux/sched/task.h>
31 #include <linux/lsm_hooks.h>
32 #include <linux/xattr.h>
33 #include <linux/capability.h>
34 #include <linux/unistd.h>
36 #include <linux/mman.h>
37 #include <linux/slab.h>
38 #include <linux/pagemap.h>
39 #include <linux/proc_fs.h>
40 #include <linux/swap.h>
41 #include <linux/spinlock.h>
42 #include <linux/syscalls.h>
43 #include <linux/dcache.h>
44 #include <linux/file.h>
45 #include <linux/fdtable.h>
46 #include <linux/namei.h>
47 #include <linux/mount.h>
48 #include <linux/fs_context.h>
49 #include <linux/fs_parser.h>
50 #include <linux/netfilter_ipv4.h>
51 #include <linux/netfilter_ipv6.h>
52 #include <linux/tty.h>
54 #include <net/ip.h> /* for local_port_range[] */
55 #include <net/tcp.h> /* struct or_callable used in sock_rcv_skb */
56 #include <net/inet_connection_sock.h>
57 #include <net/net_namespace.h>
58 #include <net/netlabel.h>
59 #include <linux/uaccess.h>
60 #include <asm/ioctls.h>
61 #include <linux/atomic.h>
62 #include <linux/bitops.h>
63 #include <linux/interrupt.h>
64 #include <linux/netdevice.h> /* for network interface checks */
65 #include <net/netlink.h>
66 #include <linux/tcp.h>
67 #include <linux/udp.h>
68 #include <linux/dccp.h>
69 #include <linux/sctp.h>
70 #include <net/sctp/structs.h>
71 #include <linux/quota.h>
72 #include <linux/un.h> /* for Unix socket types */
73 #include <net/af_unix.h> /* for Unix socket types */
74 #include <linux/parser.h>
75 #include <linux/nfs_mount.h>
77 #include <linux/hugetlb.h>
78 #include <linux/personality.h>
79 #include <linux/audit.h>
80 #include <linux/string.h>
81 #include <linux/mutex.h>
82 #include <linux/posix-timers.h>
83 #include <linux/syslog.h>
84 #include <linux/user_namespace.h>
85 #include <linux/export.h>
86 #include <linux/msg.h>
87 #include <linux/shm.h>
88 #include <linux/bpf.h>
89 #include <linux/kernfs.h>
90 #include <linux/stringhash.h> /* for hashlen_string() */
91 #include <uapi/linux/mount.h>
92 #include <linux/fsnotify.h>
93 #include <linux/fanotify.h>
94 #include <linux/io_uring.h>
103 #include "netlabel.h"
107 struct selinux_state selinux_state;
109 /* SECMARK reference count */
110 static atomic_t selinux_secmark_refcount = ATOMIC_INIT(0);
112 #ifdef CONFIG_SECURITY_SELINUX_DEVELOP
113 static int selinux_enforcing_boot __initdata;
115 static int __init enforcing_setup(char *str)
117 unsigned long enforcing;
118 if (!kstrtoul(str, 0, &enforcing))
119 selinux_enforcing_boot = enforcing ? 1 : 0;
122 __setup("enforcing=", enforcing_setup);
124 #define selinux_enforcing_boot 1
127 int selinux_enabled_boot __initdata = 1;
128 #ifdef CONFIG_SECURITY_SELINUX_BOOTPARAM
129 static int __init selinux_enabled_setup(char *str)
131 unsigned long enabled;
132 if (!kstrtoul(str, 0, &enabled))
133 selinux_enabled_boot = enabled ? 1 : 0;
136 __setup("selinux=", selinux_enabled_setup);
139 static int __init checkreqprot_setup(char *str)
141 unsigned long checkreqprot;
143 if (!kstrtoul(str, 0, &checkreqprot)) {
145 pr_err("SELinux: checkreqprot set to 1 via kernel parameter. This is no longer supported.\n");
149 __setup("checkreqprot=", checkreqprot_setup);
152 * selinux_secmark_enabled - Check to see if SECMARK is currently enabled
155 * This function checks the SECMARK reference counter to see if any SECMARK
156 * targets are currently configured, if the reference counter is greater than
157 * zero SECMARK is considered to be enabled. Returns true (1) if SECMARK is
158 * enabled, false (0) if SECMARK is disabled. If the always_check_network
159 * policy capability is enabled, SECMARK is always considered enabled.
162 static int selinux_secmark_enabled(void)
164 return (selinux_policycap_alwaysnetwork() ||
165 atomic_read(&selinux_secmark_refcount));
169 * selinux_peerlbl_enabled - Check to see if peer labeling is currently enabled
172 * This function checks if NetLabel or labeled IPSEC is enabled. Returns true
173 * (1) if any are enabled or false (0) if neither are enabled. If the
174 * always_check_network policy capability is enabled, peer labeling
175 * is always considered enabled.
178 static int selinux_peerlbl_enabled(void)
180 return (selinux_policycap_alwaysnetwork() ||
181 netlbl_enabled() || selinux_xfrm_enabled());
184 static int selinux_netcache_avc_callback(u32 event)
186 if (event == AVC_CALLBACK_RESET) {
195 static int selinux_lsm_notifier_avc_callback(u32 event)
197 if (event == AVC_CALLBACK_RESET) {
199 call_blocking_lsm_notifier(LSM_POLICY_CHANGE, NULL);
206 * initialise the security for the init task
208 static void cred_init_security(void)
210 struct task_security_struct *tsec;
212 tsec = selinux_cred(unrcu_pointer(current->real_cred));
213 tsec->osid = tsec->sid = SECINITSID_KERNEL;
217 * get the security ID of a set of credentials
219 static inline u32 cred_sid(const struct cred *cred)
221 const struct task_security_struct *tsec;
223 tsec = selinux_cred(cred);
227 static void __ad_net_init(struct common_audit_data *ad,
228 struct lsm_network_audit *net,
229 int ifindex, struct sock *sk, u16 family)
231 ad->type = LSM_AUDIT_DATA_NET;
233 net->netif = ifindex;
235 net->family = family;
238 static void ad_net_init_from_sk(struct common_audit_data *ad,
239 struct lsm_network_audit *net,
242 __ad_net_init(ad, net, 0, sk, 0);
245 static void ad_net_init_from_iif(struct common_audit_data *ad,
246 struct lsm_network_audit *net,
247 int ifindex, u16 family)
249 __ad_net_init(ad, net, ifindex, NULL, family);
253 * get the objective security ID of a task
255 static inline u32 task_sid_obj(const struct task_struct *task)
260 sid = cred_sid(__task_cred(task));
265 static int inode_doinit_with_dentry(struct inode *inode, struct dentry *opt_dentry);
268 * Try reloading inode security labels that have been marked as invalid. The
269 * @may_sleep parameter indicates when sleeping and thus reloading labels is
270 * allowed; when set to false, returns -ECHILD when the label is
271 * invalid. The @dentry parameter should be set to a dentry of the inode.
273 static int __inode_security_revalidate(struct inode *inode,
274 struct dentry *dentry,
277 struct inode_security_struct *isec = selinux_inode(inode);
279 might_sleep_if(may_sleep);
281 if (selinux_initialized() &&
282 isec->initialized != LABEL_INITIALIZED) {
287 * Try reloading the inode security label. This will fail if
288 * @opt_dentry is NULL and no dentry for this inode can be
289 * found; in that case, continue using the old label.
291 inode_doinit_with_dentry(inode, dentry);
296 static struct inode_security_struct *inode_security_novalidate(struct inode *inode)
298 return selinux_inode(inode);
301 static struct inode_security_struct *inode_security_rcu(struct inode *inode, bool rcu)
305 error = __inode_security_revalidate(inode, NULL, !rcu);
307 return ERR_PTR(error);
308 return selinux_inode(inode);
312 * Get the security label of an inode.
314 static struct inode_security_struct *inode_security(struct inode *inode)
316 __inode_security_revalidate(inode, NULL, true);
317 return selinux_inode(inode);
320 static struct inode_security_struct *backing_inode_security_novalidate(struct dentry *dentry)
322 struct inode *inode = d_backing_inode(dentry);
324 return selinux_inode(inode);
328 * Get the security label of a dentry's backing inode.
330 static struct inode_security_struct *backing_inode_security(struct dentry *dentry)
332 struct inode *inode = d_backing_inode(dentry);
334 __inode_security_revalidate(inode, dentry, true);
335 return selinux_inode(inode);
338 static void inode_free_security(struct inode *inode)
340 struct inode_security_struct *isec = selinux_inode(inode);
341 struct superblock_security_struct *sbsec;
345 sbsec = selinux_superblock(inode->i_sb);
347 * As not all inode security structures are in a list, we check for
348 * empty list outside of the lock to make sure that we won't waste
349 * time taking a lock doing nothing.
351 * The list_del_init() function can be safely called more than once.
352 * It should not be possible for this function to be called with
353 * concurrent list_add(), but for better safety against future changes
354 * in the code, we use list_empty_careful() here.
356 if (!list_empty_careful(&isec->list)) {
357 spin_lock(&sbsec->isec_lock);
358 list_del_init(&isec->list);
359 spin_unlock(&sbsec->isec_lock);
363 struct selinux_mnt_opts {
370 static void selinux_free_mnt_opts(void *mnt_opts)
384 #define A(s, has_arg) {#s, sizeof(#s) - 1, Opt_##s, has_arg}
385 static const struct {
394 A(rootcontext, true),
399 static int match_opt_prefix(char *s, int l, char **arg)
403 for (i = 0; i < ARRAY_SIZE(tokens); i++) {
404 size_t len = tokens[i].len;
405 if (len > l || memcmp(s, tokens[i].name, len))
407 if (tokens[i].has_arg) {
408 if (len == l || s[len] != '=')
413 return tokens[i].opt;
418 #define SEL_MOUNT_FAIL_MSG "SELinux: duplicate or incompatible mount options\n"
420 static int may_context_mount_sb_relabel(u32 sid,
421 struct superblock_security_struct *sbsec,
422 const struct cred *cred)
424 const struct task_security_struct *tsec = selinux_cred(cred);
427 rc = avc_has_perm(tsec->sid, sbsec->sid, SECCLASS_FILESYSTEM,
428 FILESYSTEM__RELABELFROM, NULL);
432 rc = avc_has_perm(tsec->sid, sid, SECCLASS_FILESYSTEM,
433 FILESYSTEM__RELABELTO, NULL);
437 static int may_context_mount_inode_relabel(u32 sid,
438 struct superblock_security_struct *sbsec,
439 const struct cred *cred)
441 const struct task_security_struct *tsec = selinux_cred(cred);
443 rc = avc_has_perm(tsec->sid, sbsec->sid, SECCLASS_FILESYSTEM,
444 FILESYSTEM__RELABELFROM, NULL);
448 rc = avc_has_perm(sid, sbsec->sid, SECCLASS_FILESYSTEM,
449 FILESYSTEM__ASSOCIATE, NULL);
453 static int selinux_is_genfs_special_handling(struct super_block *sb)
455 /* Special handling. Genfs but also in-core setxattr handler */
456 return !strcmp(sb->s_type->name, "sysfs") ||
457 !strcmp(sb->s_type->name, "pstore") ||
458 !strcmp(sb->s_type->name, "debugfs") ||
459 !strcmp(sb->s_type->name, "tracefs") ||
460 !strcmp(sb->s_type->name, "rootfs") ||
461 (selinux_policycap_cgroupseclabel() &&
462 (!strcmp(sb->s_type->name, "cgroup") ||
463 !strcmp(sb->s_type->name, "cgroup2")));
466 static int selinux_is_sblabel_mnt(struct super_block *sb)
468 struct superblock_security_struct *sbsec = selinux_superblock(sb);
471 * IMPORTANT: Double-check logic in this function when adding a new
472 * SECURITY_FS_USE_* definition!
474 BUILD_BUG_ON(SECURITY_FS_USE_MAX != 7);
476 switch (sbsec->behavior) {
477 case SECURITY_FS_USE_XATTR:
478 case SECURITY_FS_USE_TRANS:
479 case SECURITY_FS_USE_TASK:
480 case SECURITY_FS_USE_NATIVE:
483 case SECURITY_FS_USE_GENFS:
484 return selinux_is_genfs_special_handling(sb);
486 /* Never allow relabeling on context mounts */
487 case SECURITY_FS_USE_MNTPOINT:
488 case SECURITY_FS_USE_NONE:
494 static int sb_check_xattr_support(struct super_block *sb)
496 struct superblock_security_struct *sbsec = selinux_superblock(sb);
497 struct dentry *root = sb->s_root;
498 struct inode *root_inode = d_backing_inode(root);
503 * Make sure that the xattr handler exists and that no
504 * error other than -ENODATA is returned by getxattr on
505 * the root directory. -ENODATA is ok, as this may be
506 * the first boot of the SELinux kernel before we have
507 * assigned xattr values to the filesystem.
509 if (!(root_inode->i_opflags & IOP_XATTR)) {
510 pr_warn("SELinux: (dev %s, type %s) has no xattr support\n",
511 sb->s_id, sb->s_type->name);
515 rc = __vfs_getxattr(root, root_inode, XATTR_NAME_SELINUX, NULL, 0);
516 if (rc < 0 && rc != -ENODATA) {
517 if (rc == -EOPNOTSUPP) {
518 pr_warn("SELinux: (dev %s, type %s) has no security xattr handler\n",
519 sb->s_id, sb->s_type->name);
522 pr_warn("SELinux: (dev %s, type %s) getxattr errno %d\n",
523 sb->s_id, sb->s_type->name, -rc);
530 /* No xattr support - try to fallback to genfs if possible. */
531 rc = security_genfs_sid(sb->s_type->name, "/",
536 pr_warn("SELinux: (dev %s, type %s) falling back to genfs\n",
537 sb->s_id, sb->s_type->name);
538 sbsec->behavior = SECURITY_FS_USE_GENFS;
543 static int sb_finish_set_opts(struct super_block *sb)
545 struct superblock_security_struct *sbsec = selinux_superblock(sb);
546 struct dentry *root = sb->s_root;
547 struct inode *root_inode = d_backing_inode(root);
550 if (sbsec->behavior == SECURITY_FS_USE_XATTR) {
551 rc = sb_check_xattr_support(sb);
556 sbsec->flags |= SE_SBINITIALIZED;
559 * Explicitly set or clear SBLABEL_MNT. It's not sufficient to simply
560 * leave the flag untouched because sb_clone_mnt_opts might be handing
561 * us a superblock that needs the flag to be cleared.
563 if (selinux_is_sblabel_mnt(sb))
564 sbsec->flags |= SBLABEL_MNT;
566 sbsec->flags &= ~SBLABEL_MNT;
568 /* Initialize the root inode. */
569 rc = inode_doinit_with_dentry(root_inode, root);
571 /* Initialize any other inodes associated with the superblock, e.g.
572 inodes created prior to initial policy load or inodes created
573 during get_sb by a pseudo filesystem that directly
575 spin_lock(&sbsec->isec_lock);
576 while (!list_empty(&sbsec->isec_head)) {
577 struct inode_security_struct *isec =
578 list_first_entry(&sbsec->isec_head,
579 struct inode_security_struct, list);
580 struct inode *inode = isec->inode;
581 list_del_init(&isec->list);
582 spin_unlock(&sbsec->isec_lock);
583 inode = igrab(inode);
585 if (!IS_PRIVATE(inode))
586 inode_doinit_with_dentry(inode, NULL);
589 spin_lock(&sbsec->isec_lock);
591 spin_unlock(&sbsec->isec_lock);
595 static int bad_option(struct superblock_security_struct *sbsec, char flag,
596 u32 old_sid, u32 new_sid)
598 char mnt_flags = sbsec->flags & SE_MNTMASK;
600 /* check if the old mount command had the same options */
601 if (sbsec->flags & SE_SBINITIALIZED)
602 if (!(sbsec->flags & flag) ||
603 (old_sid != new_sid))
606 /* check if we were passed the same options twice,
607 * aka someone passed context=a,context=b
609 if (!(sbsec->flags & SE_SBINITIALIZED))
610 if (mnt_flags & flag)
616 * Allow filesystems with binary mount data to explicitly set mount point
617 * labeling information.
619 static int selinux_set_mnt_opts(struct super_block *sb,
621 unsigned long kern_flags,
622 unsigned long *set_kern_flags)
624 const struct cred *cred = current_cred();
625 struct superblock_security_struct *sbsec = selinux_superblock(sb);
626 struct dentry *root = sb->s_root;
627 struct selinux_mnt_opts *opts = mnt_opts;
628 struct inode_security_struct *root_isec;
629 u32 fscontext_sid = 0, context_sid = 0, rootcontext_sid = 0;
630 u32 defcontext_sid = 0;
634 * Specifying internal flags without providing a place to
635 * place the results is not allowed
637 if (kern_flags && !set_kern_flags)
640 mutex_lock(&sbsec->lock);
642 if (!selinux_initialized()) {
644 /* Defer initialization until selinux_complete_init,
645 after the initial policy is loaded and the security
646 server is ready to handle calls. */
647 if (kern_flags & SECURITY_LSM_NATIVE_LABELS) {
648 sbsec->flags |= SE_SBNATIVE;
649 *set_kern_flags |= SECURITY_LSM_NATIVE_LABELS;
654 pr_warn("SELinux: Unable to set superblock options "
655 "before the security server is initialized\n");
660 * Binary mount data FS will come through this function twice. Once
661 * from an explicit call and once from the generic calls from the vfs.
662 * Since the generic VFS calls will not contain any security mount data
663 * we need to skip the double mount verification.
665 * This does open a hole in which we will not notice if the first
666 * mount using this sb set explicit options and a second mount using
667 * this sb does not set any security options. (The first options
668 * will be used for both mounts)
670 if ((sbsec->flags & SE_SBINITIALIZED) && (sb->s_type->fs_flags & FS_BINARY_MOUNTDATA)
674 root_isec = backing_inode_security_novalidate(root);
677 * parse the mount options, check if they are valid sids.
678 * also check if someone is trying to mount the same sb more
679 * than once with different security options.
682 if (opts->fscontext_sid) {
683 fscontext_sid = opts->fscontext_sid;
684 if (bad_option(sbsec, FSCONTEXT_MNT, sbsec->sid,
686 goto out_double_mount;
687 sbsec->flags |= FSCONTEXT_MNT;
689 if (opts->context_sid) {
690 context_sid = opts->context_sid;
691 if (bad_option(sbsec, CONTEXT_MNT, sbsec->mntpoint_sid,
693 goto out_double_mount;
694 sbsec->flags |= CONTEXT_MNT;
696 if (opts->rootcontext_sid) {
697 rootcontext_sid = opts->rootcontext_sid;
698 if (bad_option(sbsec, ROOTCONTEXT_MNT, root_isec->sid,
700 goto out_double_mount;
701 sbsec->flags |= ROOTCONTEXT_MNT;
703 if (opts->defcontext_sid) {
704 defcontext_sid = opts->defcontext_sid;
705 if (bad_option(sbsec, DEFCONTEXT_MNT, sbsec->def_sid,
707 goto out_double_mount;
708 sbsec->flags |= DEFCONTEXT_MNT;
712 if (sbsec->flags & SE_SBINITIALIZED) {
713 /* previously mounted with options, but not on this attempt? */
714 if ((sbsec->flags & SE_MNTMASK) && !opts)
715 goto out_double_mount;
720 if (strcmp(sb->s_type->name, "proc") == 0)
721 sbsec->flags |= SE_SBPROC | SE_SBGENFS;
723 if (!strcmp(sb->s_type->name, "debugfs") ||
724 !strcmp(sb->s_type->name, "tracefs") ||
725 !strcmp(sb->s_type->name, "binder") ||
726 !strcmp(sb->s_type->name, "bpf") ||
727 !strcmp(sb->s_type->name, "pstore") ||
728 !strcmp(sb->s_type->name, "securityfs"))
729 sbsec->flags |= SE_SBGENFS;
731 if (!strcmp(sb->s_type->name, "sysfs") ||
732 !strcmp(sb->s_type->name, "cgroup") ||
733 !strcmp(sb->s_type->name, "cgroup2"))
734 sbsec->flags |= SE_SBGENFS | SE_SBGENFS_XATTR;
736 if (!sbsec->behavior) {
738 * Determine the labeling behavior to use for this
741 rc = security_fs_use(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 strcmp(sb->s_type->name, "overlay")) {
759 if (context_sid || fscontext_sid || rootcontext_sid ||
764 if (sbsec->behavior == SECURITY_FS_USE_XATTR) {
765 sbsec->behavior = SECURITY_FS_USE_MNTPOINT;
766 rc = security_transition_sid(current_sid(),
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 (sbsec->flags & SE_SBNATIVE) {
792 * This means we are initializing a superblock that has been
793 * mounted before the SELinux was initialized and the
794 * filesystem requested native labeling. We had already
795 * returned SECURITY_LSM_NATIVE_LABELS in *set_kern_flags
796 * in the original mount attempt, so now we just need to set
797 * the SECURITY_FS_USE_NATIVE behavior.
799 sbsec->behavior = SECURITY_FS_USE_NATIVE;
800 } else if (kern_flags & SECURITY_LSM_NATIVE_LABELS && !context_sid) {
801 sbsec->behavior = SECURITY_FS_USE_NATIVE;
802 *set_kern_flags |= SECURITY_LSM_NATIVE_LABELS;
806 if (!fscontext_sid) {
807 rc = may_context_mount_sb_relabel(context_sid, sbsec,
811 sbsec->sid = context_sid;
813 rc = may_context_mount_inode_relabel(context_sid, sbsec,
818 if (!rootcontext_sid)
819 rootcontext_sid = context_sid;
821 sbsec->mntpoint_sid = context_sid;
822 sbsec->behavior = SECURITY_FS_USE_MNTPOINT;
825 if (rootcontext_sid) {
826 rc = may_context_mount_inode_relabel(rootcontext_sid, sbsec,
831 root_isec->sid = rootcontext_sid;
832 root_isec->initialized = LABEL_INITIALIZED;
835 if (defcontext_sid) {
836 if (sbsec->behavior != SECURITY_FS_USE_XATTR &&
837 sbsec->behavior != SECURITY_FS_USE_NATIVE) {
839 pr_warn("SELinux: defcontext option is "
840 "invalid for this filesystem type\n");
844 if (defcontext_sid != sbsec->def_sid) {
845 rc = may_context_mount_inode_relabel(defcontext_sid,
851 sbsec->def_sid = defcontext_sid;
855 rc = sb_finish_set_opts(sb);
857 mutex_unlock(&sbsec->lock);
861 pr_warn("SELinux: mount invalid. Same superblock, different "
862 "security settings for (dev %s, type %s)\n", sb->s_id,
867 static int selinux_cmp_sb_context(const struct super_block *oldsb,
868 const struct super_block *newsb)
870 struct superblock_security_struct *old = selinux_superblock(oldsb);
871 struct superblock_security_struct *new = selinux_superblock(newsb);
872 char oldflags = old->flags & SE_MNTMASK;
873 char newflags = new->flags & SE_MNTMASK;
875 if (oldflags != newflags)
877 if ((oldflags & FSCONTEXT_MNT) && old->sid != new->sid)
879 if ((oldflags & CONTEXT_MNT) && old->mntpoint_sid != new->mntpoint_sid)
881 if ((oldflags & DEFCONTEXT_MNT) && old->def_sid != new->def_sid)
883 if (oldflags & ROOTCONTEXT_MNT) {
884 struct inode_security_struct *oldroot = backing_inode_security(oldsb->s_root);
885 struct inode_security_struct *newroot = backing_inode_security(newsb->s_root);
886 if (oldroot->sid != newroot->sid)
891 pr_warn("SELinux: mount invalid. Same superblock, "
892 "different security settings for (dev %s, "
893 "type %s)\n", newsb->s_id, newsb->s_type->name);
897 static int selinux_sb_clone_mnt_opts(const struct super_block *oldsb,
898 struct super_block *newsb,
899 unsigned long kern_flags,
900 unsigned long *set_kern_flags)
903 const struct superblock_security_struct *oldsbsec =
904 selinux_superblock(oldsb);
905 struct superblock_security_struct *newsbsec = selinux_superblock(newsb);
907 int set_fscontext = (oldsbsec->flags & FSCONTEXT_MNT);
908 int set_context = (oldsbsec->flags & CONTEXT_MNT);
909 int set_rootcontext = (oldsbsec->flags & ROOTCONTEXT_MNT);
912 * Specifying internal flags without providing a place to
913 * place the results is not allowed.
915 if (kern_flags && !set_kern_flags)
918 mutex_lock(&newsbsec->lock);
921 * if the parent was able to be mounted it clearly had no special lsm
922 * mount options. thus we can safely deal with this superblock later
924 if (!selinux_initialized()) {
925 if (kern_flags & SECURITY_LSM_NATIVE_LABELS) {
926 newsbsec->flags |= SE_SBNATIVE;
927 *set_kern_flags |= SECURITY_LSM_NATIVE_LABELS;
932 /* how can we clone if the old one wasn't set up?? */
933 BUG_ON(!(oldsbsec->flags & SE_SBINITIALIZED));
935 /* if fs is reusing a sb, make sure that the contexts match */
936 if (newsbsec->flags & SE_SBINITIALIZED) {
937 mutex_unlock(&newsbsec->lock);
938 if ((kern_flags & SECURITY_LSM_NATIVE_LABELS) && !set_context)
939 *set_kern_flags |= SECURITY_LSM_NATIVE_LABELS;
940 return selinux_cmp_sb_context(oldsb, newsb);
943 newsbsec->flags = oldsbsec->flags;
945 newsbsec->sid = oldsbsec->sid;
946 newsbsec->def_sid = oldsbsec->def_sid;
947 newsbsec->behavior = oldsbsec->behavior;
949 if (newsbsec->behavior == SECURITY_FS_USE_NATIVE &&
950 !(kern_flags & SECURITY_LSM_NATIVE_LABELS) && !set_context) {
951 rc = security_fs_use(newsb);
956 if (kern_flags & SECURITY_LSM_NATIVE_LABELS && !set_context) {
957 newsbsec->behavior = SECURITY_FS_USE_NATIVE;
958 *set_kern_flags |= SECURITY_LSM_NATIVE_LABELS;
962 u32 sid = oldsbsec->mntpoint_sid;
966 if (!set_rootcontext) {
967 struct inode_security_struct *newisec = backing_inode_security(newsb->s_root);
970 newsbsec->mntpoint_sid = sid;
972 if (set_rootcontext) {
973 const struct inode_security_struct *oldisec = backing_inode_security(oldsb->s_root);
974 struct inode_security_struct *newisec = backing_inode_security(newsb->s_root);
976 newisec->sid = oldisec->sid;
979 sb_finish_set_opts(newsb);
981 mutex_unlock(&newsbsec->lock);
986 * NOTE: the caller is responsible for freeing the memory even if on error.
988 static int selinux_add_opt(int token, const char *s, void **mnt_opts)
990 struct selinux_mnt_opts *opts = *mnt_opts;
994 if (token == Opt_seclabel)
995 /* eaten and completely ignored */
1000 if (!selinux_initialized()) {
1001 pr_warn("SELinux: Unable to set superblock options before the security server is initialized\n");
1006 opts = kzalloc(sizeof(*opts), GFP_KERNEL);
1014 if (opts->context_sid || opts->defcontext_sid)
1016 dst_sid = &opts->context_sid;
1019 if (opts->fscontext_sid)
1021 dst_sid = &opts->fscontext_sid;
1023 case Opt_rootcontext:
1024 if (opts->rootcontext_sid)
1026 dst_sid = &opts->rootcontext_sid;
1028 case Opt_defcontext:
1029 if (opts->context_sid || opts->defcontext_sid)
1031 dst_sid = &opts->defcontext_sid;
1037 rc = security_context_str_to_sid(s, dst_sid, GFP_KERNEL);
1039 pr_warn("SELinux: security_context_str_to_sid (%s) failed with errno=%d\n",
1044 pr_warn(SEL_MOUNT_FAIL_MSG);
1048 static int show_sid(struct seq_file *m, u32 sid)
1050 char *context = NULL;
1054 rc = security_sid_to_context(sid, &context, &len);
1056 bool has_comma = strchr(context, ',');
1061 seq_escape(m, context, "\"\n\\");
1069 static int selinux_sb_show_options(struct seq_file *m, struct super_block *sb)
1071 struct superblock_security_struct *sbsec = selinux_superblock(sb);
1074 if (!(sbsec->flags & SE_SBINITIALIZED))
1077 if (!selinux_initialized())
1080 if (sbsec->flags & FSCONTEXT_MNT) {
1082 seq_puts(m, FSCONTEXT_STR);
1083 rc = show_sid(m, sbsec->sid);
1087 if (sbsec->flags & CONTEXT_MNT) {
1089 seq_puts(m, CONTEXT_STR);
1090 rc = show_sid(m, sbsec->mntpoint_sid);
1094 if (sbsec->flags & DEFCONTEXT_MNT) {
1096 seq_puts(m, DEFCONTEXT_STR);
1097 rc = show_sid(m, sbsec->def_sid);
1101 if (sbsec->flags & ROOTCONTEXT_MNT) {
1102 struct dentry *root = sb->s_root;
1103 struct inode_security_struct *isec = backing_inode_security(root);
1105 seq_puts(m, ROOTCONTEXT_STR);
1106 rc = show_sid(m, isec->sid);
1110 if (sbsec->flags & SBLABEL_MNT) {
1112 seq_puts(m, SECLABEL_STR);
1117 static inline u16 inode_mode_to_security_class(umode_t mode)
1119 switch (mode & S_IFMT) {
1121 return SECCLASS_SOCK_FILE;
1123 return SECCLASS_LNK_FILE;
1125 return SECCLASS_FILE;
1127 return SECCLASS_BLK_FILE;
1129 return SECCLASS_DIR;
1131 return SECCLASS_CHR_FILE;
1133 return SECCLASS_FIFO_FILE;
1137 return SECCLASS_FILE;
1140 static inline int default_protocol_stream(int protocol)
1142 return (protocol == IPPROTO_IP || protocol == IPPROTO_TCP ||
1143 protocol == IPPROTO_MPTCP);
1146 static inline int default_protocol_dgram(int protocol)
1148 return (protocol == IPPROTO_IP || protocol == IPPROTO_UDP);
1151 static inline u16 socket_type_to_security_class(int family, int type, int protocol)
1153 bool extsockclass = selinux_policycap_extsockclass();
1159 case SOCK_SEQPACKET:
1160 return SECCLASS_UNIX_STREAM_SOCKET;
1163 return SECCLASS_UNIX_DGRAM_SOCKET;
1170 case SOCK_SEQPACKET:
1171 if (default_protocol_stream(protocol))
1172 return SECCLASS_TCP_SOCKET;
1173 else if (extsockclass && protocol == IPPROTO_SCTP)
1174 return SECCLASS_SCTP_SOCKET;
1176 return SECCLASS_RAWIP_SOCKET;
1178 if (default_protocol_dgram(protocol))
1179 return SECCLASS_UDP_SOCKET;
1180 else if (extsockclass && (protocol == IPPROTO_ICMP ||
1181 protocol == IPPROTO_ICMPV6))
1182 return SECCLASS_ICMP_SOCKET;
1184 return SECCLASS_RAWIP_SOCKET;
1186 return SECCLASS_DCCP_SOCKET;
1188 return SECCLASS_RAWIP_SOCKET;
1194 return SECCLASS_NETLINK_ROUTE_SOCKET;
1195 case NETLINK_SOCK_DIAG:
1196 return SECCLASS_NETLINK_TCPDIAG_SOCKET;
1198 return SECCLASS_NETLINK_NFLOG_SOCKET;
1200 return SECCLASS_NETLINK_XFRM_SOCKET;
1201 case NETLINK_SELINUX:
1202 return SECCLASS_NETLINK_SELINUX_SOCKET;
1204 return SECCLASS_NETLINK_ISCSI_SOCKET;
1206 return SECCLASS_NETLINK_AUDIT_SOCKET;
1207 case NETLINK_FIB_LOOKUP:
1208 return SECCLASS_NETLINK_FIB_LOOKUP_SOCKET;
1209 case NETLINK_CONNECTOR:
1210 return SECCLASS_NETLINK_CONNECTOR_SOCKET;
1211 case NETLINK_NETFILTER:
1212 return SECCLASS_NETLINK_NETFILTER_SOCKET;
1213 case NETLINK_DNRTMSG:
1214 return SECCLASS_NETLINK_DNRT_SOCKET;
1215 case NETLINK_KOBJECT_UEVENT:
1216 return SECCLASS_NETLINK_KOBJECT_UEVENT_SOCKET;
1217 case NETLINK_GENERIC:
1218 return SECCLASS_NETLINK_GENERIC_SOCKET;
1219 case NETLINK_SCSITRANSPORT:
1220 return SECCLASS_NETLINK_SCSITRANSPORT_SOCKET;
1222 return SECCLASS_NETLINK_RDMA_SOCKET;
1223 case NETLINK_CRYPTO:
1224 return SECCLASS_NETLINK_CRYPTO_SOCKET;
1226 return SECCLASS_NETLINK_SOCKET;
1229 return SECCLASS_PACKET_SOCKET;
1231 return SECCLASS_KEY_SOCKET;
1233 return SECCLASS_APPLETALK_SOCKET;
1239 return SECCLASS_AX25_SOCKET;
1241 return SECCLASS_IPX_SOCKET;
1243 return SECCLASS_NETROM_SOCKET;
1245 return SECCLASS_ATMPVC_SOCKET;
1247 return SECCLASS_X25_SOCKET;
1249 return SECCLASS_ROSE_SOCKET;
1251 return SECCLASS_DECNET_SOCKET;
1253 return SECCLASS_ATMSVC_SOCKET;
1255 return SECCLASS_RDS_SOCKET;
1257 return SECCLASS_IRDA_SOCKET;
1259 return SECCLASS_PPPOX_SOCKET;
1261 return SECCLASS_LLC_SOCKET;
1263 return SECCLASS_CAN_SOCKET;
1265 return SECCLASS_TIPC_SOCKET;
1267 return SECCLASS_BLUETOOTH_SOCKET;
1269 return SECCLASS_IUCV_SOCKET;
1271 return SECCLASS_RXRPC_SOCKET;
1273 return SECCLASS_ISDN_SOCKET;
1275 return SECCLASS_PHONET_SOCKET;
1277 return SECCLASS_IEEE802154_SOCKET;
1279 return SECCLASS_CAIF_SOCKET;
1281 return SECCLASS_ALG_SOCKET;
1283 return SECCLASS_NFC_SOCKET;
1285 return SECCLASS_VSOCK_SOCKET;
1287 return SECCLASS_KCM_SOCKET;
1289 return SECCLASS_QIPCRTR_SOCKET;
1291 return SECCLASS_SMC_SOCKET;
1293 return SECCLASS_XDP_SOCKET;
1295 return SECCLASS_MCTP_SOCKET;
1297 #error New address family defined, please update this function.
1302 return SECCLASS_SOCKET;
1305 static int selinux_genfs_get_sid(struct dentry *dentry,
1311 struct super_block *sb = dentry->d_sb;
1312 char *buffer, *path;
1314 buffer = (char *)__get_free_page(GFP_KERNEL);
1318 path = dentry_path_raw(dentry, buffer, PAGE_SIZE);
1322 if (flags & SE_SBPROC) {
1323 /* each process gets a /proc/PID/ entry. Strip off the
1324 * PID part to get a valid selinux labeling.
1325 * e.g. /proc/1/net/rpc/nfs -> /net/rpc/nfs */
1326 while (path[1] >= '0' && path[1] <= '9') {
1331 rc = security_genfs_sid(sb->s_type->name,
1333 if (rc == -ENOENT) {
1334 /* No match in policy, mark as unlabeled. */
1335 *sid = SECINITSID_UNLABELED;
1339 free_page((unsigned long)buffer);
1343 static int inode_doinit_use_xattr(struct inode *inode, struct dentry *dentry,
1344 u32 def_sid, u32 *sid)
1346 #define INITCONTEXTLEN 255
1351 len = INITCONTEXTLEN;
1352 context = kmalloc(len + 1, GFP_NOFS);
1356 context[len] = '\0';
1357 rc = __vfs_getxattr(dentry, inode, XATTR_NAME_SELINUX, context, len);
1358 if (rc == -ERANGE) {
1361 /* Need a larger buffer. Query for the right size. */
1362 rc = __vfs_getxattr(dentry, inode, XATTR_NAME_SELINUX, NULL, 0);
1367 context = kmalloc(len + 1, GFP_NOFS);
1371 context[len] = '\0';
1372 rc = __vfs_getxattr(dentry, inode, XATTR_NAME_SELINUX,
1377 if (rc != -ENODATA) {
1378 pr_warn("SELinux: %s: getxattr returned %d for dev=%s ino=%ld\n",
1379 __func__, -rc, inode->i_sb->s_id, inode->i_ino);
1386 rc = security_context_to_sid_default(context, rc, sid,
1389 char *dev = inode->i_sb->s_id;
1390 unsigned long ino = inode->i_ino;
1392 if (rc == -EINVAL) {
1393 pr_notice_ratelimited("SELinux: inode=%lu on dev=%s was found to have an invalid context=%s. This indicates you may need to relabel the inode or the filesystem in question.\n",
1396 pr_warn("SELinux: %s: context_to_sid(%s) returned %d for dev=%s ino=%ld\n",
1397 __func__, context, -rc, dev, ino);
1404 /* The inode's security attributes must be initialized before first use. */
1405 static int inode_doinit_with_dentry(struct inode *inode, struct dentry *opt_dentry)
1407 struct superblock_security_struct *sbsec = NULL;
1408 struct inode_security_struct *isec = selinux_inode(inode);
1409 u32 task_sid, sid = 0;
1411 struct dentry *dentry;
1414 if (isec->initialized == LABEL_INITIALIZED)
1417 spin_lock(&isec->lock);
1418 if (isec->initialized == LABEL_INITIALIZED)
1421 if (isec->sclass == SECCLASS_FILE)
1422 isec->sclass = inode_mode_to_security_class(inode->i_mode);
1424 sbsec = selinux_superblock(inode->i_sb);
1425 if (!(sbsec->flags & SE_SBINITIALIZED)) {
1426 /* Defer initialization until selinux_complete_init,
1427 after the initial policy is loaded and the security
1428 server is ready to handle calls. */
1429 spin_lock(&sbsec->isec_lock);
1430 if (list_empty(&isec->list))
1431 list_add(&isec->list, &sbsec->isec_head);
1432 spin_unlock(&sbsec->isec_lock);
1436 sclass = isec->sclass;
1437 task_sid = isec->task_sid;
1439 isec->initialized = LABEL_PENDING;
1440 spin_unlock(&isec->lock);
1442 switch (sbsec->behavior) {
1444 * In case of SECURITY_FS_USE_NATIVE we need to re-fetch the labels
1445 * via xattr when called from delayed_superblock_init().
1447 case SECURITY_FS_USE_NATIVE:
1448 case SECURITY_FS_USE_XATTR:
1449 if (!(inode->i_opflags & IOP_XATTR)) {
1450 sid = sbsec->def_sid;
1453 /* Need a dentry, since the xattr API requires one.
1454 Life would be simpler if we could just pass the inode. */
1456 /* Called from d_instantiate or d_splice_alias. */
1457 dentry = dget(opt_dentry);
1460 * Called from selinux_complete_init, try to find a dentry.
1461 * Some filesystems really want a connected one, so try
1462 * that first. We could split SECURITY_FS_USE_XATTR in
1463 * two, depending upon that...
1465 dentry = d_find_alias(inode);
1467 dentry = d_find_any_alias(inode);
1471 * this is can be hit on boot when a file is accessed
1472 * before the policy is loaded. When we load policy we
1473 * may find inodes that have no dentry on the
1474 * sbsec->isec_head list. No reason to complain as these
1475 * will get fixed up the next time we go through
1476 * inode_doinit with a dentry, before these inodes could
1477 * be used again by userspace.
1482 rc = inode_doinit_use_xattr(inode, dentry, sbsec->def_sid,
1488 case SECURITY_FS_USE_TASK:
1491 case SECURITY_FS_USE_TRANS:
1492 /* Default to the fs SID. */
1495 /* Try to obtain a transition SID. */
1496 rc = security_transition_sid(task_sid, sid,
1497 sclass, NULL, &sid);
1501 case SECURITY_FS_USE_MNTPOINT:
1502 sid = sbsec->mntpoint_sid;
1505 /* Default to the fs superblock SID. */
1508 if ((sbsec->flags & SE_SBGENFS) &&
1509 (!S_ISLNK(inode->i_mode) ||
1510 selinux_policycap_genfs_seclabel_symlinks())) {
1511 /* We must have a dentry to determine the label on
1514 /* Called from d_instantiate or
1515 * d_splice_alias. */
1516 dentry = dget(opt_dentry);
1518 /* Called from selinux_complete_init, try to
1519 * find a dentry. Some filesystems really want
1520 * a connected one, so try that first.
1522 dentry = d_find_alias(inode);
1524 dentry = d_find_any_alias(inode);
1527 * This can be hit on boot when a file is accessed
1528 * before the policy is loaded. When we load policy we
1529 * may find inodes that have no dentry on the
1530 * sbsec->isec_head list. No reason to complain as
1531 * these will get fixed up the next time we go through
1532 * inode_doinit() with a dentry, before these inodes
1533 * could be used again by userspace.
1537 rc = selinux_genfs_get_sid(dentry, sclass,
1538 sbsec->flags, &sid);
1544 if ((sbsec->flags & SE_SBGENFS_XATTR) &&
1545 (inode->i_opflags & IOP_XATTR)) {
1546 rc = inode_doinit_use_xattr(inode, dentry,
1559 spin_lock(&isec->lock);
1560 if (isec->initialized == LABEL_PENDING) {
1562 isec->initialized = LABEL_INVALID;
1565 isec->initialized = LABEL_INITIALIZED;
1570 spin_unlock(&isec->lock);
1574 spin_lock(&isec->lock);
1575 if (isec->initialized == LABEL_PENDING) {
1576 isec->initialized = LABEL_INVALID;
1579 spin_unlock(&isec->lock);
1583 /* Convert a Linux signal to an access vector. */
1584 static inline u32 signal_to_av(int sig)
1590 /* Commonly granted from child to parent. */
1591 perm = PROCESS__SIGCHLD;
1594 /* Cannot be caught or ignored */
1595 perm = PROCESS__SIGKILL;
1598 /* Cannot be caught or ignored */
1599 perm = PROCESS__SIGSTOP;
1602 /* All other signals. */
1603 perm = PROCESS__SIGNAL;
1610 #if CAP_LAST_CAP > 63
1611 #error Fix SELinux to handle capabilities > 63.
1614 /* Check whether a task is allowed to use a capability. */
1615 static int cred_has_capability(const struct cred *cred,
1616 int cap, unsigned int opts, bool initns)
1618 struct common_audit_data ad;
1619 struct av_decision avd;
1621 u32 sid = cred_sid(cred);
1622 u32 av = CAP_TO_MASK(cap);
1625 ad.type = LSM_AUDIT_DATA_CAP;
1628 switch (CAP_TO_INDEX(cap)) {
1630 sclass = initns ? SECCLASS_CAPABILITY : SECCLASS_CAP_USERNS;
1633 sclass = initns ? SECCLASS_CAPABILITY2 : SECCLASS_CAP2_USERNS;
1636 pr_err("SELinux: out of range capability %d\n", cap);
1641 rc = avc_has_perm_noaudit(sid, sid, sclass, av, 0, &avd);
1642 if (!(opts & CAP_OPT_NOAUDIT)) {
1643 int rc2 = avc_audit(sid, sid, sclass, av, &avd, rc, &ad);
1650 /* Check whether a task has a particular permission to an inode.
1651 The 'adp' parameter is optional and allows other audit
1652 data to be passed (e.g. the dentry). */
1653 static int inode_has_perm(const struct cred *cred,
1654 struct inode *inode,
1656 struct common_audit_data *adp)
1658 struct inode_security_struct *isec;
1661 validate_creds(cred);
1663 if (unlikely(IS_PRIVATE(inode)))
1666 sid = cred_sid(cred);
1667 isec = selinux_inode(inode);
1669 return avc_has_perm(sid, isec->sid, isec->sclass, perms, adp);
1672 /* Same as inode_has_perm, but pass explicit audit data containing
1673 the dentry to help the auditing code to more easily generate the
1674 pathname if needed. */
1675 static inline int dentry_has_perm(const struct cred *cred,
1676 struct dentry *dentry,
1679 struct inode *inode = d_backing_inode(dentry);
1680 struct common_audit_data ad;
1682 ad.type = LSM_AUDIT_DATA_DENTRY;
1683 ad.u.dentry = dentry;
1684 __inode_security_revalidate(inode, dentry, true);
1685 return inode_has_perm(cred, inode, av, &ad);
1688 /* Same as inode_has_perm, but pass explicit audit data containing
1689 the path to help the auditing code to more easily generate the
1690 pathname if needed. */
1691 static inline int path_has_perm(const struct cred *cred,
1692 const struct path *path,
1695 struct inode *inode = d_backing_inode(path->dentry);
1696 struct common_audit_data ad;
1698 ad.type = LSM_AUDIT_DATA_PATH;
1700 __inode_security_revalidate(inode, path->dentry, true);
1701 return inode_has_perm(cred, inode, av, &ad);
1704 /* Same as path_has_perm, but uses the inode from the file struct. */
1705 static inline int file_path_has_perm(const struct cred *cred,
1709 struct common_audit_data ad;
1711 ad.type = LSM_AUDIT_DATA_FILE;
1713 return inode_has_perm(cred, file_inode(file), av, &ad);
1716 #ifdef CONFIG_BPF_SYSCALL
1717 static int bpf_fd_pass(struct file *file, u32 sid);
1720 /* Check whether a task can use an open file descriptor to
1721 access an inode in a given way. Check access to the
1722 descriptor itself, and then use dentry_has_perm to
1723 check a particular permission to the file.
1724 Access to the descriptor is implicitly granted if it
1725 has the same SID as the process. If av is zero, then
1726 access to the file is not checked, e.g. for cases
1727 where only the descriptor is affected like seek. */
1728 static int file_has_perm(const struct cred *cred,
1732 struct file_security_struct *fsec = selinux_file(file);
1733 struct inode *inode = file_inode(file);
1734 struct common_audit_data ad;
1735 u32 sid = cred_sid(cred);
1738 ad.type = LSM_AUDIT_DATA_FILE;
1741 if (sid != fsec->sid) {
1742 rc = avc_has_perm(sid, fsec->sid,
1750 #ifdef CONFIG_BPF_SYSCALL
1751 rc = bpf_fd_pass(file, cred_sid(cred));
1756 /* av is zero if only checking access to the descriptor. */
1759 rc = inode_has_perm(cred, inode, av, &ad);
1766 * Determine the label for an inode that might be unioned.
1769 selinux_determine_inode_label(const struct task_security_struct *tsec,
1771 const struct qstr *name, u16 tclass,
1774 const struct superblock_security_struct *sbsec =
1775 selinux_superblock(dir->i_sb);
1777 if ((sbsec->flags & SE_SBINITIALIZED) &&
1778 (sbsec->behavior == SECURITY_FS_USE_MNTPOINT)) {
1779 *_new_isid = sbsec->mntpoint_sid;
1780 } else if ((sbsec->flags & SBLABEL_MNT) &&
1782 *_new_isid = tsec->create_sid;
1784 const struct inode_security_struct *dsec = inode_security(dir);
1785 return security_transition_sid(tsec->sid,
1793 /* Check whether a task can create a file. */
1794 static int may_create(struct inode *dir,
1795 struct dentry *dentry,
1798 const struct task_security_struct *tsec = selinux_cred(current_cred());
1799 struct inode_security_struct *dsec;
1800 struct superblock_security_struct *sbsec;
1802 struct common_audit_data ad;
1805 dsec = inode_security(dir);
1806 sbsec = selinux_superblock(dir->i_sb);
1810 ad.type = LSM_AUDIT_DATA_DENTRY;
1811 ad.u.dentry = dentry;
1813 rc = avc_has_perm(sid, dsec->sid, SECCLASS_DIR,
1814 DIR__ADD_NAME | DIR__SEARCH,
1819 rc = selinux_determine_inode_label(tsec, dir, &dentry->d_name, tclass,
1824 rc = avc_has_perm(sid, newsid, tclass, FILE__CREATE, &ad);
1828 return avc_has_perm(newsid, sbsec->sid,
1829 SECCLASS_FILESYSTEM,
1830 FILESYSTEM__ASSOCIATE, &ad);
1834 #define MAY_UNLINK 1
1837 /* Check whether a task can link, unlink, or rmdir a file/directory. */
1838 static int may_link(struct inode *dir,
1839 struct dentry *dentry,
1843 struct inode_security_struct *dsec, *isec;
1844 struct common_audit_data ad;
1845 u32 sid = current_sid();
1849 dsec = inode_security(dir);
1850 isec = backing_inode_security(dentry);
1852 ad.type = LSM_AUDIT_DATA_DENTRY;
1853 ad.u.dentry = dentry;
1856 av |= (kind ? DIR__REMOVE_NAME : DIR__ADD_NAME);
1857 rc = avc_has_perm(sid, dsec->sid, SECCLASS_DIR, av, &ad);
1872 pr_warn("SELinux: %s: unrecognized kind %d\n",
1877 rc = avc_has_perm(sid, isec->sid, isec->sclass, av, &ad);
1881 static inline int may_rename(struct inode *old_dir,
1882 struct dentry *old_dentry,
1883 struct inode *new_dir,
1884 struct dentry *new_dentry)
1886 struct inode_security_struct *old_dsec, *new_dsec, *old_isec, *new_isec;
1887 struct common_audit_data ad;
1888 u32 sid = current_sid();
1890 int old_is_dir, new_is_dir;
1893 old_dsec = inode_security(old_dir);
1894 old_isec = backing_inode_security(old_dentry);
1895 old_is_dir = d_is_dir(old_dentry);
1896 new_dsec = inode_security(new_dir);
1898 ad.type = LSM_AUDIT_DATA_DENTRY;
1900 ad.u.dentry = old_dentry;
1901 rc = avc_has_perm(sid, old_dsec->sid, SECCLASS_DIR,
1902 DIR__REMOVE_NAME | DIR__SEARCH, &ad);
1905 rc = avc_has_perm(sid, old_isec->sid,
1906 old_isec->sclass, FILE__RENAME, &ad);
1909 if (old_is_dir && new_dir != old_dir) {
1910 rc = avc_has_perm(sid, old_isec->sid,
1911 old_isec->sclass, DIR__REPARENT, &ad);
1916 ad.u.dentry = new_dentry;
1917 av = DIR__ADD_NAME | DIR__SEARCH;
1918 if (d_is_positive(new_dentry))
1919 av |= DIR__REMOVE_NAME;
1920 rc = avc_has_perm(sid, new_dsec->sid, SECCLASS_DIR, av, &ad);
1923 if (d_is_positive(new_dentry)) {
1924 new_isec = backing_inode_security(new_dentry);
1925 new_is_dir = d_is_dir(new_dentry);
1926 rc = avc_has_perm(sid, new_isec->sid,
1928 (new_is_dir ? DIR__RMDIR : FILE__UNLINK), &ad);
1936 /* Check whether a task can perform a filesystem operation. */
1937 static int superblock_has_perm(const struct cred *cred,
1938 struct super_block *sb,
1940 struct common_audit_data *ad)
1942 struct superblock_security_struct *sbsec;
1943 u32 sid = cred_sid(cred);
1945 sbsec = selinux_superblock(sb);
1946 return avc_has_perm(sid, sbsec->sid, SECCLASS_FILESYSTEM, perms, ad);
1949 /* Convert a Linux mode and permission mask to an access vector. */
1950 static inline u32 file_mask_to_av(int mode, int mask)
1954 if (!S_ISDIR(mode)) {
1955 if (mask & MAY_EXEC)
1956 av |= FILE__EXECUTE;
1957 if (mask & MAY_READ)
1960 if (mask & MAY_APPEND)
1962 else if (mask & MAY_WRITE)
1966 if (mask & MAY_EXEC)
1968 if (mask & MAY_WRITE)
1970 if (mask & MAY_READ)
1977 /* Convert a Linux file to an access vector. */
1978 static inline u32 file_to_av(struct file *file)
1982 if (file->f_mode & FMODE_READ)
1984 if (file->f_mode & FMODE_WRITE) {
1985 if (file->f_flags & O_APPEND)
1992 * Special file opened with flags 3 for ioctl-only use.
2001 * Convert a file to an access vector and include the correct
2004 static inline u32 open_file_to_av(struct file *file)
2006 u32 av = file_to_av(file);
2007 struct inode *inode = file_inode(file);
2009 if (selinux_policycap_openperm() &&
2010 inode->i_sb->s_magic != SOCKFS_MAGIC)
2016 /* Hook functions begin here. */
2018 static int selinux_binder_set_context_mgr(const struct cred *mgr)
2020 return avc_has_perm(current_sid(), cred_sid(mgr), SECCLASS_BINDER,
2021 BINDER__SET_CONTEXT_MGR, NULL);
2024 static int selinux_binder_transaction(const struct cred *from,
2025 const struct cred *to)
2027 u32 mysid = current_sid();
2028 u32 fromsid = cred_sid(from);
2029 u32 tosid = cred_sid(to);
2032 if (mysid != fromsid) {
2033 rc = avc_has_perm(mysid, fromsid, SECCLASS_BINDER,
2034 BINDER__IMPERSONATE, NULL);
2039 return avc_has_perm(fromsid, tosid,
2040 SECCLASS_BINDER, BINDER__CALL, NULL);
2043 static int selinux_binder_transfer_binder(const struct cred *from,
2044 const struct cred *to)
2046 return avc_has_perm(cred_sid(from), cred_sid(to),
2047 SECCLASS_BINDER, BINDER__TRANSFER,
2051 static int selinux_binder_transfer_file(const struct cred *from,
2052 const struct cred *to,
2055 u32 sid = cred_sid(to);
2056 struct file_security_struct *fsec = selinux_file(file);
2057 struct dentry *dentry = file->f_path.dentry;
2058 struct inode_security_struct *isec;
2059 struct common_audit_data ad;
2062 ad.type = LSM_AUDIT_DATA_PATH;
2063 ad.u.path = file->f_path;
2065 if (sid != fsec->sid) {
2066 rc = avc_has_perm(sid, fsec->sid,
2074 #ifdef CONFIG_BPF_SYSCALL
2075 rc = bpf_fd_pass(file, sid);
2080 if (unlikely(IS_PRIVATE(d_backing_inode(dentry))))
2083 isec = backing_inode_security(dentry);
2084 return avc_has_perm(sid, isec->sid, isec->sclass, file_to_av(file),
2088 static int selinux_ptrace_access_check(struct task_struct *child,
2091 u32 sid = current_sid();
2092 u32 csid = task_sid_obj(child);
2094 if (mode & PTRACE_MODE_READ)
2095 return avc_has_perm(sid, csid, SECCLASS_FILE, FILE__READ,
2098 return avc_has_perm(sid, csid, SECCLASS_PROCESS, PROCESS__PTRACE,
2102 static int selinux_ptrace_traceme(struct task_struct *parent)
2104 return avc_has_perm(task_sid_obj(parent), task_sid_obj(current),
2105 SECCLASS_PROCESS, PROCESS__PTRACE, NULL);
2108 static int selinux_capget(struct task_struct *target, kernel_cap_t *effective,
2109 kernel_cap_t *inheritable, kernel_cap_t *permitted)
2111 return avc_has_perm(current_sid(), task_sid_obj(target),
2112 SECCLASS_PROCESS, PROCESS__GETCAP, NULL);
2115 static int selinux_capset(struct cred *new, const struct cred *old,
2116 const kernel_cap_t *effective,
2117 const kernel_cap_t *inheritable,
2118 const kernel_cap_t *permitted)
2120 return avc_has_perm(cred_sid(old), cred_sid(new), SECCLASS_PROCESS,
2121 PROCESS__SETCAP, NULL);
2125 * (This comment used to live with the selinux_task_setuid hook,
2126 * which was removed).
2128 * Since setuid only affects the current process, and since the SELinux
2129 * controls are not based on the Linux identity attributes, SELinux does not
2130 * need to control this operation. However, SELinux does control the use of
2131 * the CAP_SETUID and CAP_SETGID capabilities using the capable hook.
2134 static int selinux_capable(const struct cred *cred, struct user_namespace *ns,
2135 int cap, unsigned int opts)
2137 return cred_has_capability(cred, cap, opts, ns == &init_user_ns);
2140 static int selinux_quotactl(int cmds, int type, int id, struct super_block *sb)
2142 const struct cred *cred = current_cred();
2157 rc = superblock_has_perm(cred, sb, FILESYSTEM__QUOTAMOD, NULL);
2165 case Q_XGETNEXTQUOTA:
2166 rc = superblock_has_perm(cred, sb, FILESYSTEM__QUOTAGET, NULL);
2169 rc = 0; /* let the kernel handle invalid cmds */
2175 static int selinux_quota_on(struct dentry *dentry)
2177 const struct cred *cred = current_cred();
2179 return dentry_has_perm(cred, dentry, FILE__QUOTAON);
2182 static int selinux_syslog(int type)
2185 case SYSLOG_ACTION_READ_ALL: /* Read last kernel messages */
2186 case SYSLOG_ACTION_SIZE_BUFFER: /* Return size of the log buffer */
2187 return avc_has_perm(current_sid(), SECINITSID_KERNEL,
2188 SECCLASS_SYSTEM, SYSTEM__SYSLOG_READ, NULL);
2189 case SYSLOG_ACTION_CONSOLE_OFF: /* Disable logging to console */
2190 case SYSLOG_ACTION_CONSOLE_ON: /* Enable logging to console */
2191 /* Set level of messages printed to console */
2192 case SYSLOG_ACTION_CONSOLE_LEVEL:
2193 return avc_has_perm(current_sid(), SECINITSID_KERNEL,
2194 SECCLASS_SYSTEM, SYSTEM__SYSLOG_CONSOLE,
2197 /* All other syslog types */
2198 return avc_has_perm(current_sid(), SECINITSID_KERNEL,
2199 SECCLASS_SYSTEM, SYSTEM__SYSLOG_MOD, NULL);
2203 * Check that a process has enough memory to allocate a new virtual
2204 * mapping. 0 means there is enough memory for the allocation to
2205 * succeed and -ENOMEM implies there is not.
2207 * Do not audit the selinux permission check, as this is applied to all
2208 * processes that allocate mappings.
2210 static int selinux_vm_enough_memory(struct mm_struct *mm, long pages)
2212 int rc, cap_sys_admin = 0;
2214 rc = cred_has_capability(current_cred(), CAP_SYS_ADMIN,
2215 CAP_OPT_NOAUDIT, true);
2219 return cap_sys_admin;
2222 /* binprm security operations */
2224 static u32 ptrace_parent_sid(void)
2227 struct task_struct *tracer;
2230 tracer = ptrace_parent(current);
2232 sid = task_sid_obj(tracer);
2238 static int check_nnp_nosuid(const struct linux_binprm *bprm,
2239 const struct task_security_struct *old_tsec,
2240 const struct task_security_struct *new_tsec)
2242 int nnp = (bprm->unsafe & LSM_UNSAFE_NO_NEW_PRIVS);
2243 int nosuid = !mnt_may_suid(bprm->file->f_path.mnt);
2247 if (!nnp && !nosuid)
2248 return 0; /* neither NNP nor nosuid */
2250 if (new_tsec->sid == old_tsec->sid)
2251 return 0; /* No change in credentials */
2254 * If the policy enables the nnp_nosuid_transition policy capability,
2255 * then we permit transitions under NNP or nosuid if the
2256 * policy allows the corresponding permission between
2257 * the old and new contexts.
2259 if (selinux_policycap_nnp_nosuid_transition()) {
2262 av |= PROCESS2__NNP_TRANSITION;
2264 av |= PROCESS2__NOSUID_TRANSITION;
2265 rc = avc_has_perm(old_tsec->sid, new_tsec->sid,
2266 SECCLASS_PROCESS2, av, NULL);
2272 * We also permit NNP or nosuid transitions to bounded SIDs,
2273 * i.e. SIDs that are guaranteed to only be allowed a subset
2274 * of the permissions of the current SID.
2276 rc = security_bounded_transition(old_tsec->sid,
2282 * On failure, preserve the errno values for NNP vs nosuid.
2283 * NNP: Operation not permitted for caller.
2284 * nosuid: Permission denied to file.
2291 static int selinux_bprm_creds_for_exec(struct linux_binprm *bprm)
2293 const struct task_security_struct *old_tsec;
2294 struct task_security_struct *new_tsec;
2295 struct inode_security_struct *isec;
2296 struct common_audit_data ad;
2297 struct inode *inode = file_inode(bprm->file);
2300 /* SELinux context only depends on initial program or script and not
2301 * the script interpreter */
2303 old_tsec = selinux_cred(current_cred());
2304 new_tsec = selinux_cred(bprm->cred);
2305 isec = inode_security(inode);
2307 /* Default to the current task SID. */
2308 new_tsec->sid = old_tsec->sid;
2309 new_tsec->osid = old_tsec->sid;
2311 /* Reset fs, key, and sock SIDs on execve. */
2312 new_tsec->create_sid = 0;
2313 new_tsec->keycreate_sid = 0;
2314 new_tsec->sockcreate_sid = 0;
2316 if (old_tsec->exec_sid) {
2317 new_tsec->sid = old_tsec->exec_sid;
2318 /* Reset exec SID on execve. */
2319 new_tsec->exec_sid = 0;
2321 /* Fail on NNP or nosuid if not an allowed transition. */
2322 rc = check_nnp_nosuid(bprm, old_tsec, new_tsec);
2326 /* Check for a default transition on this program. */
2327 rc = security_transition_sid(old_tsec->sid,
2328 isec->sid, SECCLASS_PROCESS, NULL,
2334 * Fallback to old SID on NNP or nosuid if not an allowed
2337 rc = check_nnp_nosuid(bprm, old_tsec, new_tsec);
2339 new_tsec->sid = old_tsec->sid;
2342 ad.type = LSM_AUDIT_DATA_FILE;
2343 ad.u.file = bprm->file;
2345 if (new_tsec->sid == old_tsec->sid) {
2346 rc = avc_has_perm(old_tsec->sid, isec->sid,
2347 SECCLASS_FILE, FILE__EXECUTE_NO_TRANS, &ad);
2351 /* Check permissions for the transition. */
2352 rc = avc_has_perm(old_tsec->sid, new_tsec->sid,
2353 SECCLASS_PROCESS, PROCESS__TRANSITION, &ad);
2357 rc = avc_has_perm(new_tsec->sid, isec->sid,
2358 SECCLASS_FILE, FILE__ENTRYPOINT, &ad);
2362 /* Check for shared state */
2363 if (bprm->unsafe & LSM_UNSAFE_SHARE) {
2364 rc = avc_has_perm(old_tsec->sid, new_tsec->sid,
2365 SECCLASS_PROCESS, PROCESS__SHARE,
2371 /* Make sure that anyone attempting to ptrace over a task that
2372 * changes its SID has the appropriate permit */
2373 if (bprm->unsafe & LSM_UNSAFE_PTRACE) {
2374 u32 ptsid = ptrace_parent_sid();
2376 rc = avc_has_perm(ptsid, new_tsec->sid,
2378 PROCESS__PTRACE, NULL);
2384 /* Clear any possibly unsafe personality bits on exec: */
2385 bprm->per_clear |= PER_CLEAR_ON_SETID;
2387 /* Enable secure mode for SIDs transitions unless
2388 the noatsecure permission is granted between
2389 the two SIDs, i.e. ahp returns 0. */
2390 rc = avc_has_perm(old_tsec->sid, new_tsec->sid,
2391 SECCLASS_PROCESS, PROCESS__NOATSECURE,
2393 bprm->secureexec |= !!rc;
2399 static int match_file(const void *p, struct file *file, unsigned fd)
2401 return file_has_perm(p, file, file_to_av(file)) ? fd + 1 : 0;
2404 /* Derived from fs/exec.c:flush_old_files. */
2405 static inline void flush_unauthorized_files(const struct cred *cred,
2406 struct files_struct *files)
2408 struct file *file, *devnull = NULL;
2409 struct tty_struct *tty;
2413 tty = get_current_tty();
2415 spin_lock(&tty->files_lock);
2416 if (!list_empty(&tty->tty_files)) {
2417 struct tty_file_private *file_priv;
2419 /* Revalidate access to controlling tty.
2420 Use file_path_has_perm on the tty path directly
2421 rather than using file_has_perm, as this particular
2422 open file may belong to another process and we are
2423 only interested in the inode-based check here. */
2424 file_priv = list_first_entry(&tty->tty_files,
2425 struct tty_file_private, list);
2426 file = file_priv->file;
2427 if (file_path_has_perm(cred, file, FILE__READ | FILE__WRITE))
2430 spin_unlock(&tty->files_lock);
2433 /* Reset controlling tty. */
2437 /* Revalidate access to inherited open files. */
2438 n = iterate_fd(files, 0, match_file, cred);
2439 if (!n) /* none found? */
2442 devnull = dentry_open(&selinux_null, O_RDWR, cred);
2443 if (IS_ERR(devnull))
2445 /* replace all the matching ones with this */
2447 replace_fd(n - 1, devnull, 0);
2448 } while ((n = iterate_fd(files, n, match_file, cred)) != 0);
2454 * Prepare a process for imminent new credential changes due to exec
2456 static void selinux_bprm_committing_creds(struct linux_binprm *bprm)
2458 struct task_security_struct *new_tsec;
2459 struct rlimit *rlim, *initrlim;
2462 new_tsec = selinux_cred(bprm->cred);
2463 if (new_tsec->sid == new_tsec->osid)
2466 /* Close files for which the new task SID is not authorized. */
2467 flush_unauthorized_files(bprm->cred, current->files);
2469 /* Always clear parent death signal on SID transitions. */
2470 current->pdeath_signal = 0;
2472 /* Check whether the new SID can inherit resource limits from the old
2473 * SID. If not, reset all soft limits to the lower of the current
2474 * task's hard limit and the init task's soft limit.
2476 * Note that the setting of hard limits (even to lower them) can be
2477 * controlled by the setrlimit check. The inclusion of the init task's
2478 * soft limit into the computation is to avoid resetting soft limits
2479 * higher than the default soft limit for cases where the default is
2480 * lower than the hard limit, e.g. RLIMIT_CORE or RLIMIT_STACK.
2482 rc = avc_has_perm(new_tsec->osid, new_tsec->sid, SECCLASS_PROCESS,
2483 PROCESS__RLIMITINH, NULL);
2485 /* protect against do_prlimit() */
2487 for (i = 0; i < RLIM_NLIMITS; i++) {
2488 rlim = current->signal->rlim + i;
2489 initrlim = init_task.signal->rlim + i;
2490 rlim->rlim_cur = min(rlim->rlim_max, initrlim->rlim_cur);
2492 task_unlock(current);
2493 if (IS_ENABLED(CONFIG_POSIX_TIMERS))
2494 update_rlimit_cpu(current, rlimit(RLIMIT_CPU));
2499 * Clean up the process immediately after the installation of new credentials
2502 static void selinux_bprm_committed_creds(struct linux_binprm *bprm)
2504 const struct task_security_struct *tsec = selinux_cred(current_cred());
2514 /* Check whether the new SID can inherit signal state from the old SID.
2515 * If not, clear itimers to avoid subsequent signal generation and
2516 * flush and unblock signals.
2518 * This must occur _after_ the task SID has been updated so that any
2519 * kill done after the flush will be checked against the new SID.
2521 rc = avc_has_perm(osid, sid, SECCLASS_PROCESS, PROCESS__SIGINH, NULL);
2525 spin_lock_irq(&unrcu_pointer(current->sighand)->siglock);
2526 if (!fatal_signal_pending(current)) {
2527 flush_sigqueue(¤t->pending);
2528 flush_sigqueue(¤t->signal->shared_pending);
2529 flush_signal_handlers(current, 1);
2530 sigemptyset(¤t->blocked);
2531 recalc_sigpending();
2533 spin_unlock_irq(&unrcu_pointer(current->sighand)->siglock);
2536 /* Wake up the parent if it is waiting so that it can recheck
2537 * wait permission to the new task SID. */
2538 read_lock(&tasklist_lock);
2539 __wake_up_parent(current, unrcu_pointer(current->real_parent));
2540 read_unlock(&tasklist_lock);
2543 /* superblock security operations */
2545 static int selinux_sb_alloc_security(struct super_block *sb)
2547 struct superblock_security_struct *sbsec = selinux_superblock(sb);
2549 mutex_init(&sbsec->lock);
2550 INIT_LIST_HEAD(&sbsec->isec_head);
2551 spin_lock_init(&sbsec->isec_lock);
2552 sbsec->sid = SECINITSID_UNLABELED;
2553 sbsec->def_sid = SECINITSID_FILE;
2554 sbsec->mntpoint_sid = SECINITSID_UNLABELED;
2559 static inline int opt_len(const char *s)
2561 bool open_quote = false;
2565 for (len = 0; (c = s[len]) != '\0'; len++) {
2567 open_quote = !open_quote;
2568 if (c == ',' && !open_quote)
2574 static int selinux_sb_eat_lsm_opts(char *options, void **mnt_opts)
2576 char *from = options;
2582 int len = opt_len(from);
2586 token = match_opt_prefix(from, len, &arg);
2588 if (token != Opt_error) {
2593 for (p = q = arg; p < from + len; p++) {
2598 arg = kmemdup_nul(arg, q - arg, GFP_KERNEL);
2604 rc = selinux_add_opt(token, arg, mnt_opts);
2611 if (!first) { // copy with preceding comma
2616 memmove(to, from, len);
2629 selinux_free_mnt_opts(*mnt_opts);
2635 static int selinux_sb_mnt_opts_compat(struct super_block *sb, void *mnt_opts)
2637 struct selinux_mnt_opts *opts = mnt_opts;
2638 struct superblock_security_struct *sbsec = selinux_superblock(sb);
2641 * Superblock not initialized (i.e. no options) - reject if any
2642 * options specified, otherwise accept.
2644 if (!(sbsec->flags & SE_SBINITIALIZED))
2645 return opts ? 1 : 0;
2648 * Superblock initialized and no options specified - reject if
2649 * superblock has any options set, otherwise accept.
2652 return (sbsec->flags & SE_MNTMASK) ? 1 : 0;
2654 if (opts->fscontext_sid) {
2655 if (bad_option(sbsec, FSCONTEXT_MNT, sbsec->sid,
2656 opts->fscontext_sid))
2659 if (opts->context_sid) {
2660 if (bad_option(sbsec, CONTEXT_MNT, sbsec->mntpoint_sid,
2664 if (opts->rootcontext_sid) {
2665 struct inode_security_struct *root_isec;
2667 root_isec = backing_inode_security(sb->s_root);
2668 if (bad_option(sbsec, ROOTCONTEXT_MNT, root_isec->sid,
2669 opts->rootcontext_sid))
2672 if (opts->defcontext_sid) {
2673 if (bad_option(sbsec, DEFCONTEXT_MNT, sbsec->def_sid,
2674 opts->defcontext_sid))
2680 static int selinux_sb_remount(struct super_block *sb, void *mnt_opts)
2682 struct selinux_mnt_opts *opts = mnt_opts;
2683 struct superblock_security_struct *sbsec = selinux_superblock(sb);
2685 if (!(sbsec->flags & SE_SBINITIALIZED))
2691 if (opts->fscontext_sid) {
2692 if (bad_option(sbsec, FSCONTEXT_MNT, sbsec->sid,
2693 opts->fscontext_sid))
2694 goto out_bad_option;
2696 if (opts->context_sid) {
2697 if (bad_option(sbsec, CONTEXT_MNT, sbsec->mntpoint_sid,
2699 goto out_bad_option;
2701 if (opts->rootcontext_sid) {
2702 struct inode_security_struct *root_isec;
2703 root_isec = backing_inode_security(sb->s_root);
2704 if (bad_option(sbsec, ROOTCONTEXT_MNT, root_isec->sid,
2705 opts->rootcontext_sid))
2706 goto out_bad_option;
2708 if (opts->defcontext_sid) {
2709 if (bad_option(sbsec, DEFCONTEXT_MNT, sbsec->def_sid,
2710 opts->defcontext_sid))
2711 goto out_bad_option;
2716 pr_warn("SELinux: unable to change security options "
2717 "during remount (dev %s, type=%s)\n", sb->s_id,
2722 static int selinux_sb_kern_mount(struct super_block *sb)
2724 const struct cred *cred = current_cred();
2725 struct common_audit_data ad;
2727 ad.type = LSM_AUDIT_DATA_DENTRY;
2728 ad.u.dentry = sb->s_root;
2729 return superblock_has_perm(cred, sb, FILESYSTEM__MOUNT, &ad);
2732 static int selinux_sb_statfs(struct dentry *dentry)
2734 const struct cred *cred = current_cred();
2735 struct common_audit_data ad;
2737 ad.type = LSM_AUDIT_DATA_DENTRY;
2738 ad.u.dentry = dentry->d_sb->s_root;
2739 return superblock_has_perm(cred, dentry->d_sb, FILESYSTEM__GETATTR, &ad);
2742 static int selinux_mount(const char *dev_name,
2743 const struct path *path,
2745 unsigned long flags,
2748 const struct cred *cred = current_cred();
2750 if (flags & MS_REMOUNT)
2751 return superblock_has_perm(cred, path->dentry->d_sb,
2752 FILESYSTEM__REMOUNT, NULL);
2754 return path_has_perm(cred, path, FILE__MOUNTON);
2757 static int selinux_move_mount(const struct path *from_path,
2758 const struct path *to_path)
2760 const struct cred *cred = current_cred();
2762 return path_has_perm(cred, to_path, FILE__MOUNTON);
2765 static int selinux_umount(struct vfsmount *mnt, int flags)
2767 const struct cred *cred = current_cred();
2769 return superblock_has_perm(cred, mnt->mnt_sb,
2770 FILESYSTEM__UNMOUNT, NULL);
2773 static int selinux_fs_context_dup(struct fs_context *fc,
2774 struct fs_context *src_fc)
2776 const struct selinux_mnt_opts *src = src_fc->security;
2781 fc->security = kmemdup(src, sizeof(*src), GFP_KERNEL);
2782 return fc->security ? 0 : -ENOMEM;
2785 static const struct fs_parameter_spec selinux_fs_parameters[] = {
2786 fsparam_string(CONTEXT_STR, Opt_context),
2787 fsparam_string(DEFCONTEXT_STR, Opt_defcontext),
2788 fsparam_string(FSCONTEXT_STR, Opt_fscontext),
2789 fsparam_string(ROOTCONTEXT_STR, Opt_rootcontext),
2790 fsparam_flag (SECLABEL_STR, Opt_seclabel),
2794 static int selinux_fs_context_parse_param(struct fs_context *fc,
2795 struct fs_parameter *param)
2797 struct fs_parse_result result;
2800 opt = fs_parse(fc, selinux_fs_parameters, param, &result);
2804 return selinux_add_opt(opt, param->string, &fc->security);
2807 /* inode security operations */
2809 static int selinux_inode_alloc_security(struct inode *inode)
2811 struct inode_security_struct *isec = selinux_inode(inode);
2812 u32 sid = current_sid();
2814 spin_lock_init(&isec->lock);
2815 INIT_LIST_HEAD(&isec->list);
2816 isec->inode = inode;
2817 isec->sid = SECINITSID_UNLABELED;
2818 isec->sclass = SECCLASS_FILE;
2819 isec->task_sid = sid;
2820 isec->initialized = LABEL_INVALID;
2825 static void selinux_inode_free_security(struct inode *inode)
2827 inode_free_security(inode);
2830 static int selinux_dentry_init_security(struct dentry *dentry, int mode,
2831 const struct qstr *name,
2832 const char **xattr_name, void **ctx,
2838 rc = selinux_determine_inode_label(selinux_cred(current_cred()),
2839 d_inode(dentry->d_parent), name,
2840 inode_mode_to_security_class(mode),
2846 *xattr_name = XATTR_NAME_SELINUX;
2848 return security_sid_to_context(newsid, (char **)ctx,
2852 static int selinux_dentry_create_files_as(struct dentry *dentry, int mode,
2854 const struct cred *old,
2859 struct task_security_struct *tsec;
2861 rc = selinux_determine_inode_label(selinux_cred(old),
2862 d_inode(dentry->d_parent), name,
2863 inode_mode_to_security_class(mode),
2868 tsec = selinux_cred(new);
2869 tsec->create_sid = newsid;
2873 static int selinux_inode_init_security(struct inode *inode, struct inode *dir,
2874 const struct qstr *qstr,
2876 void **value, size_t *len)
2878 const struct task_security_struct *tsec = selinux_cred(current_cred());
2879 struct superblock_security_struct *sbsec;
2884 sbsec = selinux_superblock(dir->i_sb);
2886 newsid = tsec->create_sid;
2888 rc = selinux_determine_inode_label(tsec, dir, qstr,
2889 inode_mode_to_security_class(inode->i_mode),
2894 /* Possibly defer initialization to selinux_complete_init. */
2895 if (sbsec->flags & SE_SBINITIALIZED) {
2896 struct inode_security_struct *isec = selinux_inode(inode);
2897 isec->sclass = inode_mode_to_security_class(inode->i_mode);
2899 isec->initialized = LABEL_INITIALIZED;
2902 if (!selinux_initialized() ||
2903 !(sbsec->flags & SBLABEL_MNT))
2907 *name = XATTR_SELINUX_SUFFIX;
2910 rc = security_sid_to_context_force(newsid,
2921 static int selinux_inode_init_security_anon(struct inode *inode,
2922 const struct qstr *name,
2923 const struct inode *context_inode)
2925 const struct task_security_struct *tsec = selinux_cred(current_cred());
2926 struct common_audit_data ad;
2927 struct inode_security_struct *isec;
2930 if (unlikely(!selinux_initialized()))
2933 isec = selinux_inode(inode);
2936 * We only get here once per ephemeral inode. The inode has
2937 * been initialized via inode_alloc_security but is otherwise
2941 if (context_inode) {
2942 struct inode_security_struct *context_isec =
2943 selinux_inode(context_inode);
2944 if (context_isec->initialized != LABEL_INITIALIZED) {
2945 pr_err("SELinux: context_inode is not initialized\n");
2949 isec->sclass = context_isec->sclass;
2950 isec->sid = context_isec->sid;
2952 isec->sclass = SECCLASS_ANON_INODE;
2953 rc = security_transition_sid(
2954 tsec->sid, tsec->sid,
2955 isec->sclass, name, &isec->sid);
2960 isec->initialized = LABEL_INITIALIZED;
2962 * Now that we've initialized security, check whether we're
2963 * allowed to actually create this type of anonymous inode.
2966 ad.type = LSM_AUDIT_DATA_ANONINODE;
2967 ad.u.anonclass = name ? (const char *)name->name : "?";
2969 return avc_has_perm(tsec->sid,
2976 static int selinux_inode_create(struct inode *dir, struct dentry *dentry, umode_t mode)
2978 return may_create(dir, dentry, SECCLASS_FILE);
2981 static int selinux_inode_link(struct dentry *old_dentry, struct inode *dir, struct dentry *new_dentry)
2983 return may_link(dir, old_dentry, MAY_LINK);
2986 static int selinux_inode_unlink(struct inode *dir, struct dentry *dentry)
2988 return may_link(dir, dentry, MAY_UNLINK);
2991 static int selinux_inode_symlink(struct inode *dir, struct dentry *dentry, const char *name)
2993 return may_create(dir, dentry, SECCLASS_LNK_FILE);
2996 static int selinux_inode_mkdir(struct inode *dir, struct dentry *dentry, umode_t mask)
2998 return may_create(dir, dentry, SECCLASS_DIR);
3001 static int selinux_inode_rmdir(struct inode *dir, struct dentry *dentry)
3003 return may_link(dir, dentry, MAY_RMDIR);
3006 static int selinux_inode_mknod(struct inode *dir, struct dentry *dentry, umode_t mode, dev_t dev)
3008 return may_create(dir, dentry, inode_mode_to_security_class(mode));
3011 static int selinux_inode_rename(struct inode *old_inode, struct dentry *old_dentry,
3012 struct inode *new_inode, struct dentry *new_dentry)
3014 return may_rename(old_inode, old_dentry, new_inode, new_dentry);
3017 static int selinux_inode_readlink(struct dentry *dentry)
3019 const struct cred *cred = current_cred();
3021 return dentry_has_perm(cred, dentry, FILE__READ);
3024 static int selinux_inode_follow_link(struct dentry *dentry, struct inode *inode,
3027 const struct cred *cred = current_cred();
3028 struct common_audit_data ad;
3029 struct inode_security_struct *isec;
3032 validate_creds(cred);
3034 ad.type = LSM_AUDIT_DATA_DENTRY;
3035 ad.u.dentry = dentry;
3036 sid = cred_sid(cred);
3037 isec = inode_security_rcu(inode, rcu);
3039 return PTR_ERR(isec);
3041 return avc_has_perm(sid, isec->sid, isec->sclass, FILE__READ, &ad);
3044 static noinline int audit_inode_permission(struct inode *inode,
3045 u32 perms, u32 audited, u32 denied,
3048 struct common_audit_data ad;
3049 struct inode_security_struct *isec = selinux_inode(inode);
3051 ad.type = LSM_AUDIT_DATA_INODE;
3054 return slow_avc_audit(current_sid(), isec->sid, isec->sclass, perms,
3055 audited, denied, result, &ad);
3058 static int selinux_inode_permission(struct inode *inode, int mask)
3060 const struct cred *cred = current_cred();
3063 bool no_block = mask & MAY_NOT_BLOCK;
3064 struct inode_security_struct *isec;
3066 struct av_decision avd;
3068 u32 audited, denied;
3070 from_access = mask & MAY_ACCESS;
3071 mask &= (MAY_READ|MAY_WRITE|MAY_EXEC|MAY_APPEND);
3073 /* No permission to check. Existence test. */
3077 validate_creds(cred);
3079 if (unlikely(IS_PRIVATE(inode)))
3082 perms = file_mask_to_av(inode->i_mode, mask);
3084 sid = cred_sid(cred);
3085 isec = inode_security_rcu(inode, no_block);
3087 return PTR_ERR(isec);
3089 rc = avc_has_perm_noaudit(sid, isec->sid, isec->sclass, perms, 0,
3091 audited = avc_audit_required(perms, &avd, rc,
3092 from_access ? FILE__AUDIT_ACCESS : 0,
3094 if (likely(!audited))
3097 rc2 = audit_inode_permission(inode, perms, audited, denied, rc);
3103 static int selinux_inode_setattr(struct dentry *dentry, struct iattr *iattr)
3105 const struct cred *cred = current_cred();
3106 struct inode *inode = d_backing_inode(dentry);
3107 unsigned int ia_valid = iattr->ia_valid;
3108 __u32 av = FILE__WRITE;
3110 /* ATTR_FORCE is just used for ATTR_KILL_S[UG]ID. */
3111 if (ia_valid & ATTR_FORCE) {
3112 ia_valid &= ~(ATTR_KILL_SUID | ATTR_KILL_SGID | ATTR_MODE |
3118 if (ia_valid & (ATTR_MODE | ATTR_UID | ATTR_GID |
3119 ATTR_ATIME_SET | ATTR_MTIME_SET | ATTR_TIMES_SET))
3120 return dentry_has_perm(cred, dentry, FILE__SETATTR);
3122 if (selinux_policycap_openperm() &&
3123 inode->i_sb->s_magic != SOCKFS_MAGIC &&
3124 (ia_valid & ATTR_SIZE) &&
3125 !(ia_valid & ATTR_FILE))
3128 return dentry_has_perm(cred, dentry, av);
3131 static int selinux_inode_getattr(const struct path *path)
3133 return path_has_perm(current_cred(), path, FILE__GETATTR);
3136 static bool has_cap_mac_admin(bool audit)
3138 const struct cred *cred = current_cred();
3139 unsigned int opts = audit ? CAP_OPT_NONE : CAP_OPT_NOAUDIT;
3141 if (cap_capable(cred, &init_user_ns, CAP_MAC_ADMIN, opts))
3143 if (cred_has_capability(cred, CAP_MAC_ADMIN, opts, true))
3148 static int selinux_inode_setxattr(struct mnt_idmap *idmap,
3149 struct dentry *dentry, const char *name,
3150 const void *value, size_t size, int flags)
3152 struct inode *inode = d_backing_inode(dentry);
3153 struct inode_security_struct *isec;
3154 struct superblock_security_struct *sbsec;
3155 struct common_audit_data ad;
3156 u32 newsid, sid = current_sid();
3159 if (strcmp(name, XATTR_NAME_SELINUX)) {
3160 rc = cap_inode_setxattr(dentry, name, value, size, flags);
3164 /* Not an attribute we recognize, so just check the
3165 ordinary setattr permission. */
3166 return dentry_has_perm(current_cred(), dentry, FILE__SETATTR);
3169 if (!selinux_initialized())
3170 return (inode_owner_or_capable(idmap, inode) ? 0 : -EPERM);
3172 sbsec = selinux_superblock(inode->i_sb);
3173 if (!(sbsec->flags & SBLABEL_MNT))
3176 if (!inode_owner_or_capable(idmap, inode))
3179 ad.type = LSM_AUDIT_DATA_DENTRY;
3180 ad.u.dentry = dentry;
3182 isec = backing_inode_security(dentry);
3183 rc = avc_has_perm(sid, isec->sid, isec->sclass,
3184 FILE__RELABELFROM, &ad);
3188 rc = security_context_to_sid(value, size, &newsid,
3190 if (rc == -EINVAL) {
3191 if (!has_cap_mac_admin(true)) {
3192 struct audit_buffer *ab;
3195 /* We strip a nul only if it is at the end, otherwise the
3196 * context contains a nul and we should audit that */
3198 const char *str = value;
3200 if (str[size - 1] == '\0')
3201 audit_size = size - 1;
3207 ab = audit_log_start(audit_context(),
3208 GFP_ATOMIC, AUDIT_SELINUX_ERR);
3211 audit_log_format(ab, "op=setxattr invalid_context=");
3212 audit_log_n_untrustedstring(ab, value, audit_size);
3217 rc = security_context_to_sid_force(value,
3223 rc = avc_has_perm(sid, newsid, isec->sclass,
3224 FILE__RELABELTO, &ad);
3228 rc = security_validate_transition(isec->sid, newsid,
3233 return avc_has_perm(newsid,
3235 SECCLASS_FILESYSTEM,
3236 FILESYSTEM__ASSOCIATE,
3240 static int selinux_inode_set_acl(struct mnt_idmap *idmap,
3241 struct dentry *dentry, const char *acl_name,
3242 struct posix_acl *kacl)
3244 return dentry_has_perm(current_cred(), dentry, FILE__SETATTR);
3247 static int selinux_inode_get_acl(struct mnt_idmap *idmap,
3248 struct dentry *dentry, const char *acl_name)
3250 return dentry_has_perm(current_cred(), dentry, FILE__GETATTR);
3253 static int selinux_inode_remove_acl(struct mnt_idmap *idmap,
3254 struct dentry *dentry, const char *acl_name)
3256 return dentry_has_perm(current_cred(), dentry, FILE__SETATTR);
3259 static void selinux_inode_post_setxattr(struct dentry *dentry, const char *name,
3260 const void *value, size_t size,
3263 struct inode *inode = d_backing_inode(dentry);
3264 struct inode_security_struct *isec;
3268 if (strcmp(name, XATTR_NAME_SELINUX)) {
3269 /* Not an attribute we recognize, so nothing to do. */
3273 if (!selinux_initialized()) {
3274 /* If we haven't even been initialized, then we can't validate
3275 * against a policy, so leave the label as invalid. It may
3276 * resolve to a valid label on the next revalidation try if
3277 * we've since initialized.
3282 rc = security_context_to_sid_force(value, size,
3285 pr_err("SELinux: unable to map context to SID"
3286 "for (%s, %lu), rc=%d\n",
3287 inode->i_sb->s_id, inode->i_ino, -rc);
3291 isec = backing_inode_security(dentry);
3292 spin_lock(&isec->lock);
3293 isec->sclass = inode_mode_to_security_class(inode->i_mode);
3295 isec->initialized = LABEL_INITIALIZED;
3296 spin_unlock(&isec->lock);
3299 static int selinux_inode_getxattr(struct dentry *dentry, const char *name)
3301 const struct cred *cred = current_cred();
3303 return dentry_has_perm(cred, dentry, FILE__GETATTR);
3306 static int selinux_inode_listxattr(struct dentry *dentry)
3308 const struct cred *cred = current_cred();
3310 return dentry_has_perm(cred, dentry, FILE__GETATTR);
3313 static int selinux_inode_removexattr(struct mnt_idmap *idmap,
3314 struct dentry *dentry, const char *name)
3316 if (strcmp(name, XATTR_NAME_SELINUX)) {
3317 int rc = cap_inode_removexattr(idmap, dentry, name);
3321 /* Not an attribute we recognize, so just check the
3322 ordinary setattr permission. */
3323 return dentry_has_perm(current_cred(), dentry, FILE__SETATTR);
3326 if (!selinux_initialized())
3329 /* No one is allowed to remove a SELinux security label.
3330 You can change the label, but all data must be labeled. */
3334 static int selinux_path_notify(const struct path *path, u64 mask,
3335 unsigned int obj_type)
3340 struct common_audit_data ad;
3342 ad.type = LSM_AUDIT_DATA_PATH;
3346 * Set permission needed based on the type of mark being set.
3347 * Performs an additional check for sb watches.
3350 case FSNOTIFY_OBJ_TYPE_VFSMOUNT:
3351 perm = FILE__WATCH_MOUNT;
3353 case FSNOTIFY_OBJ_TYPE_SB:
3354 perm = FILE__WATCH_SB;
3355 ret = superblock_has_perm(current_cred(), path->dentry->d_sb,
3356 FILESYSTEM__WATCH, &ad);
3360 case FSNOTIFY_OBJ_TYPE_INODE:
3367 /* blocking watches require the file:watch_with_perm permission */
3368 if (mask & (ALL_FSNOTIFY_PERM_EVENTS))
3369 perm |= FILE__WATCH_WITH_PERM;
3371 /* watches on read-like events need the file:watch_reads permission */
3372 if (mask & (FS_ACCESS | FS_ACCESS_PERM | FS_CLOSE_NOWRITE))
3373 perm |= FILE__WATCH_READS;
3375 return path_has_perm(current_cred(), path, perm);
3379 * Copy the inode security context value to the user.
3381 * Permission check is handled by selinux_inode_getxattr hook.
3383 static int selinux_inode_getsecurity(struct mnt_idmap *idmap,
3384 struct inode *inode, const char *name,
3385 void **buffer, bool alloc)
3389 char *context = NULL;
3390 struct inode_security_struct *isec;
3393 * If we're not initialized yet, then we can't validate contexts, so
3394 * just let vfs_getxattr fall back to using the on-disk xattr.
3396 if (!selinux_initialized() ||
3397 strcmp(name, XATTR_SELINUX_SUFFIX))
3401 * If the caller has CAP_MAC_ADMIN, then get the raw context
3402 * value even if it is not defined by current policy; otherwise,
3403 * use the in-core value under current policy.
3404 * Use the non-auditing forms of the permission checks since
3405 * getxattr may be called by unprivileged processes commonly
3406 * and lack of permission just means that we fall back to the
3407 * in-core context value, not a denial.
3409 isec = inode_security(inode);
3410 if (has_cap_mac_admin(false))
3411 error = security_sid_to_context_force(isec->sid, &context,
3414 error = security_sid_to_context(isec->sid,
3428 static int selinux_inode_setsecurity(struct inode *inode, const char *name,
3429 const void *value, size_t size, int flags)
3431 struct inode_security_struct *isec = inode_security_novalidate(inode);
3432 struct superblock_security_struct *sbsec;
3436 if (strcmp(name, XATTR_SELINUX_SUFFIX))
3439 sbsec = selinux_superblock(inode->i_sb);
3440 if (!(sbsec->flags & SBLABEL_MNT))
3443 if (!value || !size)
3446 rc = security_context_to_sid(value, size, &newsid,
3451 spin_lock(&isec->lock);
3452 isec->sclass = inode_mode_to_security_class(inode->i_mode);
3454 isec->initialized = LABEL_INITIALIZED;
3455 spin_unlock(&isec->lock);
3459 static int selinux_inode_listsecurity(struct inode *inode, char *buffer, size_t buffer_size)
3461 const int len = sizeof(XATTR_NAME_SELINUX);
3463 if (!selinux_initialized())
3466 if (buffer && len <= buffer_size)
3467 memcpy(buffer, XATTR_NAME_SELINUX, len);
3471 static void selinux_inode_getsecid(struct inode *inode, u32 *secid)
3473 struct inode_security_struct *isec = inode_security_novalidate(inode);
3477 static int selinux_inode_copy_up(struct dentry *src, struct cred **new)
3480 struct task_security_struct *tsec;
3481 struct cred *new_creds = *new;
3483 if (new_creds == NULL) {
3484 new_creds = prepare_creds();
3489 tsec = selinux_cred(new_creds);
3490 /* Get label from overlay inode and set it in create_sid */
3491 selinux_inode_getsecid(d_inode(src), &sid);
3492 tsec->create_sid = sid;
3497 static int selinux_inode_copy_up_xattr(const char *name)
3499 /* The copy_up hook above sets the initial context on an inode, but we
3500 * don't then want to overwrite it by blindly copying all the lower
3501 * xattrs up. Instead, we have to filter out SELinux-related xattrs.
3503 if (strcmp(name, XATTR_NAME_SELINUX) == 0)
3504 return 1; /* Discard */
3506 * Any other attribute apart from SELINUX is not claimed, supported
3512 /* kernfs node operations */
3514 static int selinux_kernfs_init_security(struct kernfs_node *kn_dir,
3515 struct kernfs_node *kn)
3517 const struct task_security_struct *tsec = selinux_cred(current_cred());
3518 u32 parent_sid, newsid, clen;
3522 rc = kernfs_xattr_get(kn_dir, XATTR_NAME_SELINUX, NULL, 0);
3529 context = kmalloc(clen, GFP_KERNEL);
3533 rc = kernfs_xattr_get(kn_dir, XATTR_NAME_SELINUX, context, clen);
3539 rc = security_context_to_sid(context, clen, &parent_sid,
3545 if (tsec->create_sid) {
3546 newsid = tsec->create_sid;
3548 u16 secclass = inode_mode_to_security_class(kn->mode);
3552 q.hash_len = hashlen_string(kn_dir, kn->name);
3554 rc = security_transition_sid(tsec->sid,
3555 parent_sid, secclass, &q,
3561 rc = security_sid_to_context_force(newsid,
3566 rc = kernfs_xattr_set(kn, XATTR_NAME_SELINUX, context, clen,
3573 /* file security operations */
3575 static int selinux_revalidate_file_permission(struct file *file, int mask)
3577 const struct cred *cred = current_cred();
3578 struct inode *inode = file_inode(file);
3580 /* file_mask_to_av won't add FILE__WRITE if MAY_APPEND is set */
3581 if ((file->f_flags & O_APPEND) && (mask & MAY_WRITE))
3584 return file_has_perm(cred, file,
3585 file_mask_to_av(inode->i_mode, mask));
3588 static int selinux_file_permission(struct file *file, int mask)
3590 struct inode *inode = file_inode(file);
3591 struct file_security_struct *fsec = selinux_file(file);
3592 struct inode_security_struct *isec;
3593 u32 sid = current_sid();
3596 /* No permission to check. Existence test. */
3599 isec = inode_security(inode);
3600 if (sid == fsec->sid && fsec->isid == isec->sid &&
3601 fsec->pseqno == avc_policy_seqno())
3602 /* No change since file_open check. */
3605 return selinux_revalidate_file_permission(file, mask);
3608 static int selinux_file_alloc_security(struct file *file)
3610 struct file_security_struct *fsec = selinux_file(file);
3611 u32 sid = current_sid();
3614 fsec->fown_sid = sid;
3620 * Check whether a task has the ioctl permission and cmd
3621 * operation to an inode.
3623 static int ioctl_has_perm(const struct cred *cred, struct file *file,
3624 u32 requested, u16 cmd)
3626 struct common_audit_data ad;
3627 struct file_security_struct *fsec = selinux_file(file);
3628 struct inode *inode = file_inode(file);
3629 struct inode_security_struct *isec;
3630 struct lsm_ioctlop_audit ioctl;
3631 u32 ssid = cred_sid(cred);
3633 u8 driver = cmd >> 8;
3634 u8 xperm = cmd & 0xff;
3636 ad.type = LSM_AUDIT_DATA_IOCTL_OP;
3639 ad.u.op->path = file->f_path;
3641 if (ssid != fsec->sid) {
3642 rc = avc_has_perm(ssid, fsec->sid,
3650 if (unlikely(IS_PRIVATE(inode)))
3653 isec = inode_security(inode);
3654 rc = avc_has_extended_perms(ssid, isec->sid, isec->sclass,
3655 requested, driver, xperm, &ad);
3660 static int selinux_file_ioctl(struct file *file, unsigned int cmd,
3663 const struct cred *cred = current_cred();
3670 case FS_IOC_GETFLAGS:
3671 case FS_IOC_GETVERSION:
3672 error = file_has_perm(cred, file, FILE__GETATTR);
3675 case FS_IOC_SETFLAGS:
3676 case FS_IOC_SETVERSION:
3677 error = file_has_perm(cred, file, FILE__SETATTR);
3680 /* sys_ioctl() checks */
3683 error = file_has_perm(cred, file, 0);
3688 error = cred_has_capability(cred, CAP_SYS_TTY_CONFIG,
3689 CAP_OPT_NONE, true);
3694 if (!selinux_policycap_ioctl_skip_cloexec())
3695 error = ioctl_has_perm(cred, file, FILE__IOCTL, (u16) cmd);
3698 /* default case assumes that the command will go
3699 * to the file's ioctl() function.
3702 error = ioctl_has_perm(cred, file, FILE__IOCTL, (u16) cmd);
3707 static int default_noexec __ro_after_init;
3709 static int file_map_prot_check(struct file *file, unsigned long prot, int shared)
3711 const struct cred *cred = current_cred();
3712 u32 sid = cred_sid(cred);
3715 if (default_noexec &&
3716 (prot & PROT_EXEC) && (!file || IS_PRIVATE(file_inode(file)) ||
3717 (!shared && (prot & PROT_WRITE)))) {
3719 * We are making executable an anonymous mapping or a
3720 * private file mapping that will also be writable.
3721 * This has an additional check.
3723 rc = avc_has_perm(sid, sid, SECCLASS_PROCESS,
3724 PROCESS__EXECMEM, NULL);
3730 /* read access is always possible with a mapping */
3731 u32 av = FILE__READ;
3733 /* write access only matters if the mapping is shared */
3734 if (shared && (prot & PROT_WRITE))
3737 if (prot & PROT_EXEC)
3738 av |= FILE__EXECUTE;
3740 return file_has_perm(cred, file, av);
3747 static int selinux_mmap_addr(unsigned long addr)
3751 if (addr < CONFIG_LSM_MMAP_MIN_ADDR) {
3752 u32 sid = current_sid();
3753 rc = avc_has_perm(sid, sid, SECCLASS_MEMPROTECT,
3754 MEMPROTECT__MMAP_ZERO, NULL);
3760 static int selinux_mmap_file(struct file *file,
3761 unsigned long reqprot __always_unused,
3762 unsigned long prot, unsigned long flags)
3764 struct common_audit_data ad;
3768 ad.type = LSM_AUDIT_DATA_FILE;
3770 rc = inode_has_perm(current_cred(), file_inode(file),
3776 return file_map_prot_check(file, prot,
3777 (flags & MAP_TYPE) == MAP_SHARED);
3780 static int selinux_file_mprotect(struct vm_area_struct *vma,
3781 unsigned long reqprot __always_unused,
3784 const struct cred *cred = current_cred();
3785 u32 sid = cred_sid(cred);
3787 if (default_noexec &&
3788 (prot & PROT_EXEC) && !(vma->vm_flags & VM_EXEC)) {
3790 if (vma->vm_start >= vma->vm_mm->start_brk &&
3791 vma->vm_end <= vma->vm_mm->brk) {
3792 rc = avc_has_perm(sid, sid, SECCLASS_PROCESS,
3793 PROCESS__EXECHEAP, NULL);
3794 } else if (!vma->vm_file &&
3795 ((vma->vm_start <= vma->vm_mm->start_stack &&
3796 vma->vm_end >= vma->vm_mm->start_stack) ||
3797 vma_is_stack_for_current(vma))) {
3798 rc = avc_has_perm(sid, sid, SECCLASS_PROCESS,
3799 PROCESS__EXECSTACK, NULL);
3800 } else if (vma->vm_file && vma->anon_vma) {
3802 * We are making executable a file mapping that has
3803 * had some COW done. Since pages might have been
3804 * written, check ability to execute the possibly
3805 * modified content. This typically should only
3806 * occur for text relocations.
3808 rc = file_has_perm(cred, vma->vm_file, FILE__EXECMOD);
3814 return file_map_prot_check(vma->vm_file, prot, vma->vm_flags&VM_SHARED);
3817 static int selinux_file_lock(struct file *file, unsigned int cmd)
3819 const struct cred *cred = current_cred();
3821 return file_has_perm(cred, file, FILE__LOCK);
3824 static int selinux_file_fcntl(struct file *file, unsigned int cmd,
3827 const struct cred *cred = current_cred();
3832 if ((file->f_flags & O_APPEND) && !(arg & O_APPEND)) {
3833 err = file_has_perm(cred, file, FILE__WRITE);
3842 case F_GETOWNER_UIDS:
3843 /* Just check FD__USE permission */
3844 err = file_has_perm(cred, file, 0);
3852 #if BITS_PER_LONG == 32
3857 err = file_has_perm(cred, file, FILE__LOCK);
3864 static void selinux_file_set_fowner(struct file *file)
3866 struct file_security_struct *fsec;
3868 fsec = selinux_file(file);
3869 fsec->fown_sid = current_sid();
3872 static int selinux_file_send_sigiotask(struct task_struct *tsk,
3873 struct fown_struct *fown, int signum)
3876 u32 sid = task_sid_obj(tsk);
3878 struct file_security_struct *fsec;
3880 /* struct fown_struct is never outside the context of a struct file */
3881 file = container_of(fown, struct file, f_owner);
3883 fsec = selinux_file(file);
3886 perm = signal_to_av(SIGIO); /* as per send_sigio_to_task */
3888 perm = signal_to_av(signum);
3890 return avc_has_perm(fsec->fown_sid, sid,
3891 SECCLASS_PROCESS, perm, NULL);
3894 static int selinux_file_receive(struct file *file)
3896 const struct cred *cred = current_cred();
3898 return file_has_perm(cred, file, file_to_av(file));
3901 static int selinux_file_open(struct file *file)
3903 struct file_security_struct *fsec;
3904 struct inode_security_struct *isec;
3906 fsec = selinux_file(file);
3907 isec = inode_security(file_inode(file));
3909 * Save inode label and policy sequence number
3910 * at open-time so that selinux_file_permission
3911 * can determine whether revalidation is necessary.
3912 * Task label is already saved in the file security
3913 * struct as its SID.
3915 fsec->isid = isec->sid;
3916 fsec->pseqno = avc_policy_seqno();
3918 * Since the inode label or policy seqno may have changed
3919 * between the selinux_inode_permission check and the saving
3920 * of state above, recheck that access is still permitted.
3921 * Otherwise, access might never be revalidated against the
3922 * new inode label or new policy.
3923 * This check is not redundant - do not remove.
3925 return file_path_has_perm(file->f_cred, file, open_file_to_av(file));
3928 /* task security operations */
3930 static int selinux_task_alloc(struct task_struct *task,
3931 unsigned long clone_flags)
3933 u32 sid = current_sid();
3935 return avc_has_perm(sid, sid, SECCLASS_PROCESS, PROCESS__FORK, NULL);
3939 * prepare a new set of credentials for modification
3941 static int selinux_cred_prepare(struct cred *new, const struct cred *old,
3944 const struct task_security_struct *old_tsec = selinux_cred(old);
3945 struct task_security_struct *tsec = selinux_cred(new);
3952 * transfer the SELinux data to a blank set of creds
3954 static void selinux_cred_transfer(struct cred *new, const struct cred *old)
3956 const struct task_security_struct *old_tsec = selinux_cred(old);
3957 struct task_security_struct *tsec = selinux_cred(new);
3962 static void selinux_cred_getsecid(const struct cred *c, u32 *secid)
3964 *secid = cred_sid(c);
3968 * set the security data for a kernel service
3969 * - all the creation contexts are set to unlabelled
3971 static int selinux_kernel_act_as(struct cred *new, u32 secid)
3973 struct task_security_struct *tsec = selinux_cred(new);
3974 u32 sid = current_sid();
3977 ret = avc_has_perm(sid, secid,
3978 SECCLASS_KERNEL_SERVICE,
3979 KERNEL_SERVICE__USE_AS_OVERRIDE,
3983 tsec->create_sid = 0;
3984 tsec->keycreate_sid = 0;
3985 tsec->sockcreate_sid = 0;
3991 * set the file creation context in a security record to the same as the
3992 * objective context of the specified inode
3994 static int selinux_kernel_create_files_as(struct cred *new, struct inode *inode)
3996 struct inode_security_struct *isec = inode_security(inode);
3997 struct task_security_struct *tsec = selinux_cred(new);
3998 u32 sid = current_sid();
4001 ret = avc_has_perm(sid, isec->sid,
4002 SECCLASS_KERNEL_SERVICE,
4003 KERNEL_SERVICE__CREATE_FILES_AS,
4007 tsec->create_sid = isec->sid;
4011 static int selinux_kernel_module_request(char *kmod_name)
4013 struct common_audit_data ad;
4015 ad.type = LSM_AUDIT_DATA_KMOD;
4016 ad.u.kmod_name = kmod_name;
4018 return avc_has_perm(current_sid(), SECINITSID_KERNEL, SECCLASS_SYSTEM,
4019 SYSTEM__MODULE_REQUEST, &ad);
4022 static int selinux_kernel_module_from_file(struct file *file)
4024 struct common_audit_data ad;
4025 struct inode_security_struct *isec;
4026 struct file_security_struct *fsec;
4027 u32 sid = current_sid();
4032 return avc_has_perm(sid, sid, SECCLASS_SYSTEM,
4033 SYSTEM__MODULE_LOAD, NULL);
4037 ad.type = LSM_AUDIT_DATA_FILE;
4040 fsec = selinux_file(file);
4041 if (sid != fsec->sid) {
4042 rc = avc_has_perm(sid, fsec->sid, SECCLASS_FD, FD__USE, &ad);
4047 isec = inode_security(file_inode(file));
4048 return avc_has_perm(sid, isec->sid, SECCLASS_SYSTEM,
4049 SYSTEM__MODULE_LOAD, &ad);
4052 static int selinux_kernel_read_file(struct file *file,
4053 enum kernel_read_file_id id,
4059 case READING_MODULE:
4060 rc = selinux_kernel_module_from_file(contents ? file : NULL);
4069 static int selinux_kernel_load_data(enum kernel_load_data_id id, bool contents)
4074 case LOADING_MODULE:
4075 rc = selinux_kernel_module_from_file(NULL);
4084 static int selinux_task_setpgid(struct task_struct *p, pid_t pgid)
4086 return avc_has_perm(current_sid(), task_sid_obj(p), SECCLASS_PROCESS,
4087 PROCESS__SETPGID, NULL);
4090 static int selinux_task_getpgid(struct task_struct *p)
4092 return avc_has_perm(current_sid(), task_sid_obj(p), SECCLASS_PROCESS,
4093 PROCESS__GETPGID, NULL);
4096 static int selinux_task_getsid(struct task_struct *p)
4098 return avc_has_perm(current_sid(), task_sid_obj(p), SECCLASS_PROCESS,
4099 PROCESS__GETSESSION, NULL);
4102 static void selinux_current_getsecid_subj(u32 *secid)
4104 *secid = current_sid();
4107 static void selinux_task_getsecid_obj(struct task_struct *p, u32 *secid)
4109 *secid = task_sid_obj(p);
4112 static int selinux_task_setnice(struct task_struct *p, int nice)
4114 return avc_has_perm(current_sid(), task_sid_obj(p), SECCLASS_PROCESS,
4115 PROCESS__SETSCHED, NULL);
4118 static int selinux_task_setioprio(struct task_struct *p, int ioprio)
4120 return avc_has_perm(current_sid(), task_sid_obj(p), SECCLASS_PROCESS,
4121 PROCESS__SETSCHED, NULL);
4124 static int selinux_task_getioprio(struct task_struct *p)
4126 return avc_has_perm(current_sid(), task_sid_obj(p), SECCLASS_PROCESS,
4127 PROCESS__GETSCHED, NULL);
4130 static int selinux_task_prlimit(const struct cred *cred, const struct cred *tcred,
4137 if (flags & LSM_PRLIMIT_WRITE)
4138 av |= PROCESS__SETRLIMIT;
4139 if (flags & LSM_PRLIMIT_READ)
4140 av |= PROCESS__GETRLIMIT;
4141 return avc_has_perm(cred_sid(cred), cred_sid(tcred),
4142 SECCLASS_PROCESS, av, NULL);
4145 static int selinux_task_setrlimit(struct task_struct *p, unsigned int resource,
4146 struct rlimit *new_rlim)
4148 struct rlimit *old_rlim = p->signal->rlim + resource;
4150 /* Control the ability to change the hard limit (whether
4151 lowering or raising it), so that the hard limit can
4152 later be used as a safe reset point for the soft limit
4153 upon context transitions. See selinux_bprm_committing_creds. */
4154 if (old_rlim->rlim_max != new_rlim->rlim_max)
4155 return avc_has_perm(current_sid(), task_sid_obj(p),
4156 SECCLASS_PROCESS, PROCESS__SETRLIMIT, NULL);
4161 static int selinux_task_setscheduler(struct task_struct *p)
4163 return avc_has_perm(current_sid(), task_sid_obj(p), SECCLASS_PROCESS,
4164 PROCESS__SETSCHED, NULL);
4167 static int selinux_task_getscheduler(struct task_struct *p)
4169 return avc_has_perm(current_sid(), task_sid_obj(p), SECCLASS_PROCESS,
4170 PROCESS__GETSCHED, NULL);
4173 static int selinux_task_movememory(struct task_struct *p)
4175 return avc_has_perm(current_sid(), task_sid_obj(p), SECCLASS_PROCESS,
4176 PROCESS__SETSCHED, NULL);
4179 static int selinux_task_kill(struct task_struct *p, struct kernel_siginfo *info,
4180 int sig, const struct cred *cred)
4186 perm = PROCESS__SIGNULL; /* null signal; existence test */
4188 perm = signal_to_av(sig);
4190 secid = current_sid();
4192 secid = cred_sid(cred);
4193 return avc_has_perm(secid, task_sid_obj(p), SECCLASS_PROCESS, perm, NULL);
4196 static void selinux_task_to_inode(struct task_struct *p,
4197 struct inode *inode)
4199 struct inode_security_struct *isec = selinux_inode(inode);
4200 u32 sid = task_sid_obj(p);
4202 spin_lock(&isec->lock);
4203 isec->sclass = inode_mode_to_security_class(inode->i_mode);
4205 isec->initialized = LABEL_INITIALIZED;
4206 spin_unlock(&isec->lock);
4209 static int selinux_userns_create(const struct cred *cred)
4211 u32 sid = current_sid();
4213 return avc_has_perm(sid, sid, SECCLASS_USER_NAMESPACE,
4214 USER_NAMESPACE__CREATE, NULL);
4217 /* Returns error only if unable to parse addresses */
4218 static int selinux_parse_skb_ipv4(struct sk_buff *skb,
4219 struct common_audit_data *ad, u8 *proto)
4221 int offset, ihlen, ret = -EINVAL;
4222 struct iphdr _iph, *ih;
4224 offset = skb_network_offset(skb);
4225 ih = skb_header_pointer(skb, offset, sizeof(_iph), &_iph);
4229 ihlen = ih->ihl * 4;
4230 if (ihlen < sizeof(_iph))
4233 ad->u.net->v4info.saddr = ih->saddr;
4234 ad->u.net->v4info.daddr = ih->daddr;
4238 *proto = ih->protocol;
4240 switch (ih->protocol) {
4242 struct tcphdr _tcph, *th;
4244 if (ntohs(ih->frag_off) & IP_OFFSET)
4248 th = skb_header_pointer(skb, offset, sizeof(_tcph), &_tcph);
4252 ad->u.net->sport = th->source;
4253 ad->u.net->dport = th->dest;
4258 struct udphdr _udph, *uh;
4260 if (ntohs(ih->frag_off) & IP_OFFSET)
4264 uh = skb_header_pointer(skb, offset, sizeof(_udph), &_udph);
4268 ad->u.net->sport = uh->source;
4269 ad->u.net->dport = uh->dest;
4273 case IPPROTO_DCCP: {
4274 struct dccp_hdr _dccph, *dh;
4276 if (ntohs(ih->frag_off) & IP_OFFSET)
4280 dh = skb_header_pointer(skb, offset, sizeof(_dccph), &_dccph);
4284 ad->u.net->sport = dh->dccph_sport;
4285 ad->u.net->dport = dh->dccph_dport;
4289 #if IS_ENABLED(CONFIG_IP_SCTP)
4290 case IPPROTO_SCTP: {
4291 struct sctphdr _sctph, *sh;
4293 if (ntohs(ih->frag_off) & IP_OFFSET)
4297 sh = skb_header_pointer(skb, offset, sizeof(_sctph), &_sctph);
4301 ad->u.net->sport = sh->source;
4302 ad->u.net->dport = sh->dest;
4313 #if IS_ENABLED(CONFIG_IPV6)
4315 /* Returns error only if unable to parse addresses */
4316 static int selinux_parse_skb_ipv6(struct sk_buff *skb,
4317 struct common_audit_data *ad, u8 *proto)
4320 int ret = -EINVAL, offset;
4321 struct ipv6hdr _ipv6h, *ip6;
4324 offset = skb_network_offset(skb);
4325 ip6 = skb_header_pointer(skb, offset, sizeof(_ipv6h), &_ipv6h);
4329 ad->u.net->v6info.saddr = ip6->saddr;
4330 ad->u.net->v6info.daddr = ip6->daddr;
4333 nexthdr = ip6->nexthdr;
4334 offset += sizeof(_ipv6h);
4335 offset = ipv6_skip_exthdr(skb, offset, &nexthdr, &frag_off);
4344 struct tcphdr _tcph, *th;
4346 th = skb_header_pointer(skb, offset, sizeof(_tcph), &_tcph);
4350 ad->u.net->sport = th->source;
4351 ad->u.net->dport = th->dest;
4356 struct udphdr _udph, *uh;
4358 uh = skb_header_pointer(skb, offset, sizeof(_udph), &_udph);
4362 ad->u.net->sport = uh->source;
4363 ad->u.net->dport = uh->dest;
4367 case IPPROTO_DCCP: {
4368 struct dccp_hdr _dccph, *dh;
4370 dh = skb_header_pointer(skb, offset, sizeof(_dccph), &_dccph);
4374 ad->u.net->sport = dh->dccph_sport;
4375 ad->u.net->dport = dh->dccph_dport;
4379 #if IS_ENABLED(CONFIG_IP_SCTP)
4380 case IPPROTO_SCTP: {
4381 struct sctphdr _sctph, *sh;
4383 sh = skb_header_pointer(skb, offset, sizeof(_sctph), &_sctph);
4387 ad->u.net->sport = sh->source;
4388 ad->u.net->dport = sh->dest;
4392 /* includes fragments */
4402 static int selinux_parse_skb(struct sk_buff *skb, struct common_audit_data *ad,
4403 char **_addrp, int src, u8 *proto)
4408 switch (ad->u.net->family) {
4410 ret = selinux_parse_skb_ipv4(skb, ad, proto);
4413 addrp = (char *)(src ? &ad->u.net->v4info.saddr :
4414 &ad->u.net->v4info.daddr);
4417 #if IS_ENABLED(CONFIG_IPV6)
4419 ret = selinux_parse_skb_ipv6(skb, ad, proto);
4422 addrp = (char *)(src ? &ad->u.net->v6info.saddr :
4423 &ad->u.net->v6info.daddr);
4433 "SELinux: failure in selinux_parse_skb(),"
4434 " unable to parse packet\n");
4444 * selinux_skb_peerlbl_sid - Determine the peer label of a packet
4446 * @family: protocol family
4447 * @sid: the packet's peer label SID
4450 * Check the various different forms of network peer labeling and determine
4451 * the peer label/SID for the packet; most of the magic actually occurs in
4452 * the security server function security_net_peersid_cmp(). The function
4453 * returns zero if the value in @sid is valid (although it may be SECSID_NULL)
4454 * or -EACCES if @sid is invalid due to inconsistencies with the different
4458 static int selinux_skb_peerlbl_sid(struct sk_buff *skb, u16 family, u32 *sid)
4465 err = selinux_xfrm_skb_sid(skb, &xfrm_sid);
4468 err = selinux_netlbl_skbuff_getsid(skb, family, &nlbl_type, &nlbl_sid);
4472 err = security_net_peersid_resolve(nlbl_sid,
4473 nlbl_type, xfrm_sid, sid);
4474 if (unlikely(err)) {
4476 "SELinux: failure in selinux_skb_peerlbl_sid(),"
4477 " unable to determine packet's peer label\n");
4485 * selinux_conn_sid - Determine the child socket label for a connection
4486 * @sk_sid: the parent socket's SID
4487 * @skb_sid: the packet's SID
4488 * @conn_sid: the resulting connection SID
4490 * If @skb_sid is valid then the user:role:type information from @sk_sid is
4491 * combined with the MLS information from @skb_sid in order to create
4492 * @conn_sid. If @skb_sid is not valid then @conn_sid is simply a copy
4493 * of @sk_sid. Returns zero on success, negative values on failure.
4496 static int selinux_conn_sid(u32 sk_sid, u32 skb_sid, u32 *conn_sid)
4500 if (skb_sid != SECSID_NULL)
4501 err = security_sid_mls_copy(sk_sid, skb_sid,
4509 /* socket security operations */
4511 static int socket_sockcreate_sid(const struct task_security_struct *tsec,
4512 u16 secclass, u32 *socksid)
4514 if (tsec->sockcreate_sid > SECSID_NULL) {
4515 *socksid = tsec->sockcreate_sid;
4519 return security_transition_sid(tsec->sid, tsec->sid,
4520 secclass, NULL, socksid);
4523 static int sock_has_perm(struct sock *sk, u32 perms)
4525 struct sk_security_struct *sksec = sk->sk_security;
4526 struct common_audit_data ad;
4527 struct lsm_network_audit net;
4529 if (sksec->sid == SECINITSID_KERNEL)
4532 ad_net_init_from_sk(&ad, &net, sk);
4534 return avc_has_perm(current_sid(), sksec->sid, sksec->sclass, perms,
4538 static int selinux_socket_create(int family, int type,
4539 int protocol, int kern)
4541 const struct task_security_struct *tsec = selinux_cred(current_cred());
4549 secclass = socket_type_to_security_class(family, type, protocol);
4550 rc = socket_sockcreate_sid(tsec, secclass, &newsid);
4554 return avc_has_perm(tsec->sid, newsid, secclass, SOCKET__CREATE, NULL);
4557 static int selinux_socket_post_create(struct socket *sock, int family,
4558 int type, int protocol, int kern)
4560 const struct task_security_struct *tsec = selinux_cred(current_cred());
4561 struct inode_security_struct *isec = inode_security_novalidate(SOCK_INODE(sock));
4562 struct sk_security_struct *sksec;
4563 u16 sclass = socket_type_to_security_class(family, type, protocol);
4564 u32 sid = SECINITSID_KERNEL;
4568 err = socket_sockcreate_sid(tsec, sclass, &sid);
4573 isec->sclass = sclass;
4575 isec->initialized = LABEL_INITIALIZED;
4578 sksec = sock->sk->sk_security;
4579 sksec->sclass = sclass;
4581 /* Allows detection of the first association on this socket */
4582 if (sksec->sclass == SECCLASS_SCTP_SOCKET)
4583 sksec->sctp_assoc_state = SCTP_ASSOC_UNSET;
4585 err = selinux_netlbl_socket_post_create(sock->sk, family);
4591 static int selinux_socket_socketpair(struct socket *socka,
4592 struct socket *sockb)
4594 struct sk_security_struct *sksec_a = socka->sk->sk_security;
4595 struct sk_security_struct *sksec_b = sockb->sk->sk_security;
4597 sksec_a->peer_sid = sksec_b->sid;
4598 sksec_b->peer_sid = sksec_a->sid;
4603 /* Range of port numbers used to automatically bind.
4604 Need to determine whether we should perform a name_bind
4605 permission check between the socket and the port number. */
4607 static int selinux_socket_bind(struct socket *sock, struct sockaddr *address, int addrlen)
4609 struct sock *sk = sock->sk;
4610 struct sk_security_struct *sksec = sk->sk_security;
4614 err = sock_has_perm(sk, SOCKET__BIND);
4618 /* If PF_INET or PF_INET6, check name_bind permission for the port. */
4619 family = sk->sk_family;
4620 if (family == PF_INET || family == PF_INET6) {
4622 struct common_audit_data ad;
4623 struct lsm_network_audit net = {0,};
4624 struct sockaddr_in *addr4 = NULL;
4625 struct sockaddr_in6 *addr6 = NULL;
4627 unsigned short snum;
4631 * sctp_bindx(3) calls via selinux_sctp_bind_connect()
4632 * that validates multiple binding addresses. Because of this
4633 * need to check address->sa_family as it is possible to have
4634 * sk->sk_family = PF_INET6 with addr->sa_family = AF_INET.
4636 if (addrlen < offsetofend(struct sockaddr, sa_family))
4638 family_sa = address->sa_family;
4639 switch (family_sa) {
4642 if (addrlen < sizeof(struct sockaddr_in))
4644 addr4 = (struct sockaddr_in *)address;
4645 if (family_sa == AF_UNSPEC) {
4646 /* see __inet_bind(), we only want to allow
4647 * AF_UNSPEC if the address is INADDR_ANY
4649 if (addr4->sin_addr.s_addr != htonl(INADDR_ANY))
4651 family_sa = AF_INET;
4653 snum = ntohs(addr4->sin_port);
4654 addrp = (char *)&addr4->sin_addr.s_addr;
4657 if (addrlen < SIN6_LEN_RFC2133)
4659 addr6 = (struct sockaddr_in6 *)address;
4660 snum = ntohs(addr6->sin6_port);
4661 addrp = (char *)&addr6->sin6_addr.s6_addr;
4667 ad.type = LSM_AUDIT_DATA_NET;
4669 ad.u.net->sport = htons(snum);
4670 ad.u.net->family = family_sa;
4675 inet_get_local_port_range(sock_net(sk), &low, &high);
4677 if (inet_port_requires_bind_service(sock_net(sk), snum) ||
4678 snum < low || snum > high) {
4679 err = sel_netport_sid(sk->sk_protocol,
4683 err = avc_has_perm(sksec->sid, sid,
4685 SOCKET__NAME_BIND, &ad);
4691 switch (sksec->sclass) {
4692 case SECCLASS_TCP_SOCKET:
4693 node_perm = TCP_SOCKET__NODE_BIND;
4696 case SECCLASS_UDP_SOCKET:
4697 node_perm = UDP_SOCKET__NODE_BIND;
4700 case SECCLASS_DCCP_SOCKET:
4701 node_perm = DCCP_SOCKET__NODE_BIND;
4704 case SECCLASS_SCTP_SOCKET:
4705 node_perm = SCTP_SOCKET__NODE_BIND;
4709 node_perm = RAWIP_SOCKET__NODE_BIND;
4713 err = sel_netnode_sid(addrp, family_sa, &sid);
4717 if (family_sa == AF_INET)
4718 ad.u.net->v4info.saddr = addr4->sin_addr.s_addr;
4720 ad.u.net->v6info.saddr = addr6->sin6_addr;
4722 err = avc_has_perm(sksec->sid, sid,
4723 sksec->sclass, node_perm, &ad);
4730 /* Note that SCTP services expect -EINVAL, others -EAFNOSUPPORT. */
4731 if (sksec->sclass == SECCLASS_SCTP_SOCKET)
4733 return -EAFNOSUPPORT;
4736 /* This supports connect(2) and SCTP connect services such as sctp_connectx(3)
4737 * and sctp_sendmsg(3) as described in Documentation/security/SCTP.rst
4739 static int selinux_socket_connect_helper(struct socket *sock,
4740 struct sockaddr *address, int addrlen)
4742 struct sock *sk = sock->sk;
4743 struct sk_security_struct *sksec = sk->sk_security;
4746 err = sock_has_perm(sk, SOCKET__CONNECT);
4749 if (addrlen < offsetofend(struct sockaddr, sa_family))
4752 /* connect(AF_UNSPEC) has special handling, as it is a documented
4753 * way to disconnect the socket
4755 if (address->sa_family == AF_UNSPEC)
4759 * If a TCP, DCCP or SCTP socket, check name_connect permission
4762 if (sksec->sclass == SECCLASS_TCP_SOCKET ||
4763 sksec->sclass == SECCLASS_DCCP_SOCKET ||
4764 sksec->sclass == SECCLASS_SCTP_SOCKET) {
4765 struct common_audit_data ad;
4766 struct lsm_network_audit net = {0,};
4767 struct sockaddr_in *addr4 = NULL;
4768 struct sockaddr_in6 *addr6 = NULL;
4769 unsigned short snum;
4772 /* sctp_connectx(3) calls via selinux_sctp_bind_connect()
4773 * that validates multiple connect addresses. Because of this
4774 * need to check address->sa_family as it is possible to have
4775 * sk->sk_family = PF_INET6 with addr->sa_family = AF_INET.
4777 switch (address->sa_family) {
4779 addr4 = (struct sockaddr_in *)address;
4780 if (addrlen < sizeof(struct sockaddr_in))
4782 snum = ntohs(addr4->sin_port);
4785 addr6 = (struct sockaddr_in6 *)address;
4786 if (addrlen < SIN6_LEN_RFC2133)
4788 snum = ntohs(addr6->sin6_port);
4791 /* Note that SCTP services expect -EINVAL, whereas
4792 * others expect -EAFNOSUPPORT.
4794 if (sksec->sclass == SECCLASS_SCTP_SOCKET)
4797 return -EAFNOSUPPORT;
4800 err = sel_netport_sid(sk->sk_protocol, snum, &sid);
4804 switch (sksec->sclass) {
4805 case SECCLASS_TCP_SOCKET:
4806 perm = TCP_SOCKET__NAME_CONNECT;
4808 case SECCLASS_DCCP_SOCKET:
4809 perm = DCCP_SOCKET__NAME_CONNECT;
4811 case SECCLASS_SCTP_SOCKET:
4812 perm = SCTP_SOCKET__NAME_CONNECT;
4816 ad.type = LSM_AUDIT_DATA_NET;
4818 ad.u.net->dport = htons(snum);
4819 ad.u.net->family = address->sa_family;
4820 err = avc_has_perm(sksec->sid, sid, sksec->sclass, perm, &ad);
4828 /* Supports connect(2), see comments in selinux_socket_connect_helper() */
4829 static int selinux_socket_connect(struct socket *sock,
4830 struct sockaddr *address, int addrlen)
4833 struct sock *sk = sock->sk;
4835 err = selinux_socket_connect_helper(sock, address, addrlen);
4839 return selinux_netlbl_socket_connect(sk, address);
4842 static int selinux_socket_listen(struct socket *sock, int backlog)
4844 return sock_has_perm(sock->sk, SOCKET__LISTEN);
4847 static int selinux_socket_accept(struct socket *sock, struct socket *newsock)
4850 struct inode_security_struct *isec;
4851 struct inode_security_struct *newisec;
4855 err = sock_has_perm(sock->sk, SOCKET__ACCEPT);
4859 isec = inode_security_novalidate(SOCK_INODE(sock));
4860 spin_lock(&isec->lock);
4861 sclass = isec->sclass;
4863 spin_unlock(&isec->lock);
4865 newisec = inode_security_novalidate(SOCK_INODE(newsock));
4866 newisec->sclass = sclass;
4868 newisec->initialized = LABEL_INITIALIZED;
4873 static int selinux_socket_sendmsg(struct socket *sock, struct msghdr *msg,
4876 return sock_has_perm(sock->sk, SOCKET__WRITE);
4879 static int selinux_socket_recvmsg(struct socket *sock, struct msghdr *msg,
4880 int size, int flags)
4882 return sock_has_perm(sock->sk, SOCKET__READ);
4885 static int selinux_socket_getsockname(struct socket *sock)
4887 return sock_has_perm(sock->sk, SOCKET__GETATTR);
4890 static int selinux_socket_getpeername(struct socket *sock)
4892 return sock_has_perm(sock->sk, SOCKET__GETATTR);
4895 static int selinux_socket_setsockopt(struct socket *sock, int level, int optname)
4899 err = sock_has_perm(sock->sk, SOCKET__SETOPT);
4903 return selinux_netlbl_socket_setsockopt(sock, level, optname);
4906 static int selinux_socket_getsockopt(struct socket *sock, int level,
4909 return sock_has_perm(sock->sk, SOCKET__GETOPT);
4912 static int selinux_socket_shutdown(struct socket *sock, int how)
4914 return sock_has_perm(sock->sk, SOCKET__SHUTDOWN);
4917 static int selinux_socket_unix_stream_connect(struct sock *sock,
4921 struct sk_security_struct *sksec_sock = sock->sk_security;
4922 struct sk_security_struct *sksec_other = other->sk_security;
4923 struct sk_security_struct *sksec_new = newsk->sk_security;
4924 struct common_audit_data ad;
4925 struct lsm_network_audit net;
4928 ad_net_init_from_sk(&ad, &net, other);
4930 err = avc_has_perm(sksec_sock->sid, sksec_other->sid,
4931 sksec_other->sclass,
4932 UNIX_STREAM_SOCKET__CONNECTTO, &ad);
4936 /* server child socket */
4937 sksec_new->peer_sid = sksec_sock->sid;
4938 err = security_sid_mls_copy(sksec_other->sid,
4939 sksec_sock->sid, &sksec_new->sid);
4943 /* connecting socket */
4944 sksec_sock->peer_sid = sksec_new->sid;
4949 static int selinux_socket_unix_may_send(struct socket *sock,
4950 struct socket *other)
4952 struct sk_security_struct *ssec = sock->sk->sk_security;
4953 struct sk_security_struct *osec = other->sk->sk_security;
4954 struct common_audit_data ad;
4955 struct lsm_network_audit net;
4957 ad_net_init_from_sk(&ad, &net, other->sk);
4959 return avc_has_perm(ssec->sid, osec->sid, osec->sclass, SOCKET__SENDTO,
4963 static int selinux_inet_sys_rcv_skb(struct net *ns, int ifindex,
4964 char *addrp, u16 family, u32 peer_sid,
4965 struct common_audit_data *ad)
4971 err = sel_netif_sid(ns, ifindex, &if_sid);
4974 err = avc_has_perm(peer_sid, if_sid,
4975 SECCLASS_NETIF, NETIF__INGRESS, ad);
4979 err = sel_netnode_sid(addrp, family, &node_sid);
4982 return avc_has_perm(peer_sid, node_sid,
4983 SECCLASS_NODE, NODE__RECVFROM, ad);
4986 static int selinux_sock_rcv_skb_compat(struct sock *sk, struct sk_buff *skb,
4990 struct sk_security_struct *sksec = sk->sk_security;
4991 u32 sk_sid = sksec->sid;
4992 struct common_audit_data ad;
4993 struct lsm_network_audit net;
4996 ad_net_init_from_iif(&ad, &net, skb->skb_iif, family);
4997 err = selinux_parse_skb(skb, &ad, &addrp, 1, NULL);
5001 if (selinux_secmark_enabled()) {
5002 err = avc_has_perm(sk_sid, skb->secmark, SECCLASS_PACKET,
5008 err = selinux_netlbl_sock_rcv_skb(sksec, skb, family, &ad);
5011 err = selinux_xfrm_sock_rcv_skb(sksec->sid, skb, &ad);
5016 static int selinux_socket_sock_rcv_skb(struct sock *sk, struct sk_buff *skb)
5018 int err, peerlbl_active, secmark_active;
5019 struct sk_security_struct *sksec = sk->sk_security;
5020 u16 family = sk->sk_family;
5021 u32 sk_sid = sksec->sid;
5022 struct common_audit_data ad;
5023 struct lsm_network_audit net;
5026 if (family != PF_INET && family != PF_INET6)
5029 /* Handle mapped IPv4 packets arriving via IPv6 sockets */
5030 if (family == PF_INET6 && skb->protocol == htons(ETH_P_IP))
5033 /* If any sort of compatibility mode is enabled then handoff processing
5034 * to the selinux_sock_rcv_skb_compat() function to deal with the
5035 * special handling. We do this in an attempt to keep this function
5036 * as fast and as clean as possible. */
5037 if (!selinux_policycap_netpeer())
5038 return selinux_sock_rcv_skb_compat(sk, skb, family);
5040 secmark_active = selinux_secmark_enabled();
5041 peerlbl_active = selinux_peerlbl_enabled();
5042 if (!secmark_active && !peerlbl_active)
5045 ad_net_init_from_iif(&ad, &net, skb->skb_iif, family);
5046 err = selinux_parse_skb(skb, &ad, &addrp, 1, NULL);
5050 if (peerlbl_active) {
5053 err = selinux_skb_peerlbl_sid(skb, family, &peer_sid);
5056 err = selinux_inet_sys_rcv_skb(sock_net(sk), skb->skb_iif,
5057 addrp, family, peer_sid, &ad);
5059 selinux_netlbl_err(skb, family, err, 0);
5062 err = avc_has_perm(sk_sid, peer_sid, SECCLASS_PEER,
5065 selinux_netlbl_err(skb, family, err, 0);
5070 if (secmark_active) {
5071 err = avc_has_perm(sk_sid, skb->secmark, SECCLASS_PACKET,
5080 static int selinux_socket_getpeersec_stream(struct socket *sock,
5081 sockptr_t optval, sockptr_t optlen,
5085 char *scontext = NULL;
5087 struct sk_security_struct *sksec = sock->sk->sk_security;
5088 u32 peer_sid = SECSID_NULL;
5090 if (sksec->sclass == SECCLASS_UNIX_STREAM_SOCKET ||
5091 sksec->sclass == SECCLASS_TCP_SOCKET ||
5092 sksec->sclass == SECCLASS_SCTP_SOCKET)
5093 peer_sid = sksec->peer_sid;
5094 if (peer_sid == SECSID_NULL)
5095 return -ENOPROTOOPT;
5097 err = security_sid_to_context(peer_sid, &scontext,
5101 if (scontext_len > len) {
5106 if (copy_to_sockptr(optval, scontext, scontext_len))
5109 if (copy_to_sockptr(optlen, &scontext_len, sizeof(scontext_len)))
5115 static int selinux_socket_getpeersec_dgram(struct socket *sock, struct sk_buff *skb, u32 *secid)
5117 u32 peer_secid = SECSID_NULL;
5119 struct inode_security_struct *isec;
5121 if (skb && skb->protocol == htons(ETH_P_IP))
5123 else if (skb && skb->protocol == htons(ETH_P_IPV6))
5126 family = sock->sk->sk_family;
5130 if (sock && family == PF_UNIX) {
5131 isec = inode_security_novalidate(SOCK_INODE(sock));
5132 peer_secid = isec->sid;
5134 selinux_skb_peerlbl_sid(skb, family, &peer_secid);
5137 *secid = peer_secid;
5138 if (peer_secid == SECSID_NULL)
5143 static int selinux_sk_alloc_security(struct sock *sk, int family, gfp_t priority)
5145 struct sk_security_struct *sksec;
5147 sksec = kzalloc(sizeof(*sksec), priority);
5151 sksec->peer_sid = SECINITSID_UNLABELED;
5152 sksec->sid = SECINITSID_UNLABELED;
5153 sksec->sclass = SECCLASS_SOCKET;
5154 selinux_netlbl_sk_security_reset(sksec);
5155 sk->sk_security = sksec;
5160 static void selinux_sk_free_security(struct sock *sk)
5162 struct sk_security_struct *sksec = sk->sk_security;
5164 sk->sk_security = NULL;
5165 selinux_netlbl_sk_security_free(sksec);
5169 static void selinux_sk_clone_security(const struct sock *sk, struct sock *newsk)
5171 struct sk_security_struct *sksec = sk->sk_security;
5172 struct sk_security_struct *newsksec = newsk->sk_security;
5174 newsksec->sid = sksec->sid;
5175 newsksec->peer_sid = sksec->peer_sid;
5176 newsksec->sclass = sksec->sclass;
5178 selinux_netlbl_sk_security_reset(newsksec);
5181 static void selinux_sk_getsecid(struct sock *sk, u32 *secid)
5184 *secid = SECINITSID_ANY_SOCKET;
5186 struct sk_security_struct *sksec = sk->sk_security;
5188 *secid = sksec->sid;
5192 static void selinux_sock_graft(struct sock *sk, struct socket *parent)
5194 struct inode_security_struct *isec =
5195 inode_security_novalidate(SOCK_INODE(parent));
5196 struct sk_security_struct *sksec = sk->sk_security;
5198 if (sk->sk_family == PF_INET || sk->sk_family == PF_INET6 ||
5199 sk->sk_family == PF_UNIX)
5200 isec->sid = sksec->sid;
5201 sksec->sclass = isec->sclass;
5205 * Determines peer_secid for the asoc and updates socket's peer label
5206 * if it's the first association on the socket.
5208 static int selinux_sctp_process_new_assoc(struct sctp_association *asoc,
5209 struct sk_buff *skb)
5211 struct sock *sk = asoc->base.sk;
5212 u16 family = sk->sk_family;
5213 struct sk_security_struct *sksec = sk->sk_security;
5214 struct common_audit_data ad;
5215 struct lsm_network_audit net;
5218 /* handle mapped IPv4 packets arriving via IPv6 sockets */
5219 if (family == PF_INET6 && skb->protocol == htons(ETH_P_IP))
5222 if (selinux_peerlbl_enabled()) {
5223 asoc->peer_secid = SECSID_NULL;
5225 /* This will return peer_sid = SECSID_NULL if there are
5226 * no peer labels, see security_net_peersid_resolve().
5228 err = selinux_skb_peerlbl_sid(skb, family, &asoc->peer_secid);
5232 if (asoc->peer_secid == SECSID_NULL)
5233 asoc->peer_secid = SECINITSID_UNLABELED;
5235 asoc->peer_secid = SECINITSID_UNLABELED;
5238 if (sksec->sctp_assoc_state == SCTP_ASSOC_UNSET) {
5239 sksec->sctp_assoc_state = SCTP_ASSOC_SET;
5241 /* Here as first association on socket. As the peer SID
5242 * was allowed by peer recv (and the netif/node checks),
5243 * then it is approved by policy and used as the primary
5244 * peer SID for getpeercon(3).
5246 sksec->peer_sid = asoc->peer_secid;
5247 } else if (sksec->peer_sid != asoc->peer_secid) {
5248 /* Other association peer SIDs are checked to enforce
5249 * consistency among the peer SIDs.
5251 ad_net_init_from_sk(&ad, &net, asoc->base.sk);
5252 err = avc_has_perm(sksec->peer_sid, asoc->peer_secid,
5253 sksec->sclass, SCTP_SOCKET__ASSOCIATION,
5261 /* Called whenever SCTP receives an INIT or COOKIE ECHO chunk. This
5262 * happens on an incoming connect(2), sctp_connectx(3) or
5263 * sctp_sendmsg(3) (with no association already present).
5265 static int selinux_sctp_assoc_request(struct sctp_association *asoc,
5266 struct sk_buff *skb)
5268 struct sk_security_struct *sksec = asoc->base.sk->sk_security;
5272 if (!selinux_policycap_extsockclass())
5275 err = selinux_sctp_process_new_assoc(asoc, skb);
5279 /* Compute the MLS component for the connection and store
5280 * the information in asoc. This will be used by SCTP TCP type
5281 * sockets and peeled off connections as they cause a new
5282 * socket to be generated. selinux_sctp_sk_clone() will then
5283 * plug this into the new socket.
5285 err = selinux_conn_sid(sksec->sid, asoc->peer_secid, &conn_sid);
5289 asoc->secid = conn_sid;
5291 /* Set any NetLabel labels including CIPSO/CALIPSO options. */
5292 return selinux_netlbl_sctp_assoc_request(asoc, skb);
5295 /* Called when SCTP receives a COOKIE ACK chunk as the final
5296 * response to an association request (initited by us).
5298 static int selinux_sctp_assoc_established(struct sctp_association *asoc,
5299 struct sk_buff *skb)
5301 struct sk_security_struct *sksec = asoc->base.sk->sk_security;
5303 if (!selinux_policycap_extsockclass())
5306 /* Inherit secid from the parent socket - this will be picked up
5307 * by selinux_sctp_sk_clone() if the association gets peeled off
5308 * into a new socket.
5310 asoc->secid = sksec->sid;
5312 return selinux_sctp_process_new_assoc(asoc, skb);
5315 /* Check if sctp IPv4/IPv6 addresses are valid for binding or connecting
5316 * based on their @optname.
5318 static int selinux_sctp_bind_connect(struct sock *sk, int optname,
5319 struct sockaddr *address,
5322 int len, err = 0, walk_size = 0;
5324 struct sockaddr *addr;
5325 struct socket *sock;
5327 if (!selinux_policycap_extsockclass())
5330 /* Process one or more addresses that may be IPv4 or IPv6 */
5331 sock = sk->sk_socket;
5334 while (walk_size < addrlen) {
5335 if (walk_size + sizeof(sa_family_t) > addrlen)
5339 switch (addr->sa_family) {
5342 len = sizeof(struct sockaddr_in);
5345 len = sizeof(struct sockaddr_in6);
5351 if (walk_size + len > addrlen)
5357 case SCTP_PRIMARY_ADDR:
5358 case SCTP_SET_PEER_PRIMARY_ADDR:
5359 case SCTP_SOCKOPT_BINDX_ADD:
5360 err = selinux_socket_bind(sock, addr, len);
5362 /* Connect checks */
5363 case SCTP_SOCKOPT_CONNECTX:
5364 case SCTP_PARAM_SET_PRIMARY:
5365 case SCTP_PARAM_ADD_IP:
5366 case SCTP_SENDMSG_CONNECT:
5367 err = selinux_socket_connect_helper(sock, addr, len);
5371 /* As selinux_sctp_bind_connect() is called by the
5372 * SCTP protocol layer, the socket is already locked,
5373 * therefore selinux_netlbl_socket_connect_locked()
5374 * is called here. The situations handled are:
5375 * sctp_connectx(3), sctp_sendmsg(3), sendmsg(2),
5376 * whenever a new IP address is added or when a new
5377 * primary address is selected.
5378 * Note that an SCTP connect(2) call happens before
5379 * the SCTP protocol layer and is handled via
5380 * selinux_socket_connect().
5382 err = selinux_netlbl_socket_connect_locked(sk, addr);
5396 /* Called whenever a new socket is created by accept(2) or sctp_peeloff(3). */
5397 static void selinux_sctp_sk_clone(struct sctp_association *asoc, struct sock *sk,
5400 struct sk_security_struct *sksec = sk->sk_security;
5401 struct sk_security_struct *newsksec = newsk->sk_security;
5403 /* If policy does not support SECCLASS_SCTP_SOCKET then call
5404 * the non-sctp clone version.
5406 if (!selinux_policycap_extsockclass())
5407 return selinux_sk_clone_security(sk, newsk);
5409 newsksec->sid = asoc->secid;
5410 newsksec->peer_sid = asoc->peer_secid;
5411 newsksec->sclass = sksec->sclass;
5412 selinux_netlbl_sctp_sk_clone(sk, newsk);
5415 static int selinux_mptcp_add_subflow(struct sock *sk, struct sock *ssk)
5417 struct sk_security_struct *ssksec = ssk->sk_security;
5418 struct sk_security_struct *sksec = sk->sk_security;
5420 ssksec->sclass = sksec->sclass;
5421 ssksec->sid = sksec->sid;
5423 /* replace the existing subflow label deleting the existing one
5424 * and re-recreating a new label using the updated context
5426 selinux_netlbl_sk_security_free(ssksec);
5427 return selinux_netlbl_socket_post_create(ssk, ssk->sk_family);
5430 static int selinux_inet_conn_request(const struct sock *sk, struct sk_buff *skb,
5431 struct request_sock *req)
5433 struct sk_security_struct *sksec = sk->sk_security;
5435 u16 family = req->rsk_ops->family;
5439 err = selinux_skb_peerlbl_sid(skb, family, &peersid);
5442 err = selinux_conn_sid(sksec->sid, peersid, &connsid);
5445 req->secid = connsid;
5446 req->peer_secid = peersid;
5448 return selinux_netlbl_inet_conn_request(req, family);
5451 static void selinux_inet_csk_clone(struct sock *newsk,
5452 const struct request_sock *req)
5454 struct sk_security_struct *newsksec = newsk->sk_security;
5456 newsksec->sid = req->secid;
5457 newsksec->peer_sid = req->peer_secid;
5458 /* NOTE: Ideally, we should also get the isec->sid for the
5459 new socket in sync, but we don't have the isec available yet.
5460 So we will wait until sock_graft to do it, by which
5461 time it will have been created and available. */
5463 /* We don't need to take any sort of lock here as we are the only
5464 * thread with access to newsksec */
5465 selinux_netlbl_inet_csk_clone(newsk, req->rsk_ops->family);
5468 static void selinux_inet_conn_established(struct sock *sk, struct sk_buff *skb)
5470 u16 family = sk->sk_family;
5471 struct sk_security_struct *sksec = sk->sk_security;
5473 /* handle mapped IPv4 packets arriving via IPv6 sockets */
5474 if (family == PF_INET6 && skb->protocol == htons(ETH_P_IP))
5477 selinux_skb_peerlbl_sid(skb, family, &sksec->peer_sid);
5480 static int selinux_secmark_relabel_packet(u32 sid)
5482 const struct task_security_struct *tsec;
5485 tsec = selinux_cred(current_cred());
5488 return avc_has_perm(tsid, sid, SECCLASS_PACKET, PACKET__RELABELTO,
5492 static void selinux_secmark_refcount_inc(void)
5494 atomic_inc(&selinux_secmark_refcount);
5497 static void selinux_secmark_refcount_dec(void)
5499 atomic_dec(&selinux_secmark_refcount);
5502 static void selinux_req_classify_flow(const struct request_sock *req,
5503 struct flowi_common *flic)
5505 flic->flowic_secid = req->secid;
5508 static int selinux_tun_dev_alloc_security(void **security)
5510 struct tun_security_struct *tunsec;
5512 tunsec = kzalloc(sizeof(*tunsec), GFP_KERNEL);
5515 tunsec->sid = current_sid();
5521 static void selinux_tun_dev_free_security(void *security)
5526 static int selinux_tun_dev_create(void)
5528 u32 sid = current_sid();
5530 /* we aren't taking into account the "sockcreate" SID since the socket
5531 * that is being created here is not a socket in the traditional sense,
5532 * instead it is a private sock, accessible only to the kernel, and
5533 * representing a wide range of network traffic spanning multiple
5534 * connections unlike traditional sockets - check the TUN driver to
5535 * get a better understanding of why this socket is special */
5537 return avc_has_perm(sid, sid, SECCLASS_TUN_SOCKET, TUN_SOCKET__CREATE,
5541 static int selinux_tun_dev_attach_queue(void *security)
5543 struct tun_security_struct *tunsec = security;
5545 return avc_has_perm(current_sid(), tunsec->sid, SECCLASS_TUN_SOCKET,
5546 TUN_SOCKET__ATTACH_QUEUE, NULL);
5549 static int selinux_tun_dev_attach(struct sock *sk, void *security)
5551 struct tun_security_struct *tunsec = security;
5552 struct sk_security_struct *sksec = sk->sk_security;
5554 /* we don't currently perform any NetLabel based labeling here and it
5555 * isn't clear that we would want to do so anyway; while we could apply
5556 * labeling without the support of the TUN user the resulting labeled
5557 * traffic from the other end of the connection would almost certainly
5558 * cause confusion to the TUN user that had no idea network labeling
5559 * protocols were being used */
5561 sksec->sid = tunsec->sid;
5562 sksec->sclass = SECCLASS_TUN_SOCKET;
5567 static int selinux_tun_dev_open(void *security)
5569 struct tun_security_struct *tunsec = security;
5570 u32 sid = current_sid();
5573 err = avc_has_perm(sid, tunsec->sid, SECCLASS_TUN_SOCKET,
5574 TUN_SOCKET__RELABELFROM, NULL);
5577 err = avc_has_perm(sid, sid, SECCLASS_TUN_SOCKET,
5578 TUN_SOCKET__RELABELTO, NULL);
5586 #ifdef CONFIG_NETFILTER
5588 static unsigned int selinux_ip_forward(void *priv, struct sk_buff *skb,
5589 const struct nf_hook_state *state)
5595 struct common_audit_data ad;
5596 struct lsm_network_audit net;
5597 int secmark_active, peerlbl_active;
5599 if (!selinux_policycap_netpeer())
5602 secmark_active = selinux_secmark_enabled();
5603 peerlbl_active = selinux_peerlbl_enabled();
5604 if (!secmark_active && !peerlbl_active)
5608 if (selinux_skb_peerlbl_sid(skb, family, &peer_sid) != 0)
5611 ifindex = state->in->ifindex;
5612 ad_net_init_from_iif(&ad, &net, ifindex, family);
5613 if (selinux_parse_skb(skb, &ad, &addrp, 1, NULL) != 0)
5616 if (peerlbl_active) {
5619 err = selinux_inet_sys_rcv_skb(state->net, ifindex,
5620 addrp, family, peer_sid, &ad);
5622 selinux_netlbl_err(skb, family, err, 1);
5628 if (avc_has_perm(peer_sid, skb->secmark,
5629 SECCLASS_PACKET, PACKET__FORWARD_IN, &ad))
5632 if (netlbl_enabled())
5633 /* we do this in the FORWARD path and not the POST_ROUTING
5634 * path because we want to make sure we apply the necessary
5635 * labeling before IPsec is applied so we can leverage AH
5637 if (selinux_netlbl_skbuff_setsid(skb, family, peer_sid) != 0)
5643 static unsigned int selinux_ip_output(void *priv, struct sk_buff *skb,
5644 const struct nf_hook_state *state)
5649 if (!netlbl_enabled())
5652 /* we do this in the LOCAL_OUT path and not the POST_ROUTING path
5653 * because we want to make sure we apply the necessary labeling
5654 * before IPsec is applied so we can leverage AH protection */
5657 struct sk_security_struct *sksec;
5659 if (sk_listener(sk))
5660 /* if the socket is the listening state then this
5661 * packet is a SYN-ACK packet which means it needs to
5662 * be labeled based on the connection/request_sock and
5663 * not the parent socket. unfortunately, we can't
5664 * lookup the request_sock yet as it isn't queued on
5665 * the parent socket until after the SYN-ACK is sent.
5666 * the "solution" is to simply pass the packet as-is
5667 * as any IP option based labeling should be copied
5668 * from the initial connection request (in the IP
5669 * layer). it is far from ideal, but until we get a
5670 * security label in the packet itself this is the
5671 * best we can do. */
5674 /* standard practice, label using the parent socket */
5675 sksec = sk->sk_security;
5678 sid = SECINITSID_KERNEL;
5679 if (selinux_netlbl_skbuff_setsid(skb, state->pf, sid) != 0)
5686 static unsigned int selinux_ip_postroute_compat(struct sk_buff *skb,
5687 const struct nf_hook_state *state)
5690 struct sk_security_struct *sksec;
5691 struct common_audit_data ad;
5692 struct lsm_network_audit net;
5695 sk = skb_to_full_sk(skb);
5698 sksec = sk->sk_security;
5700 ad_net_init_from_iif(&ad, &net, state->out->ifindex, state->pf);
5701 if (selinux_parse_skb(skb, &ad, NULL, 0, &proto))
5704 if (selinux_secmark_enabled())
5705 if (avc_has_perm(sksec->sid, skb->secmark,
5706 SECCLASS_PACKET, PACKET__SEND, &ad))
5707 return NF_DROP_ERR(-ECONNREFUSED);
5709 if (selinux_xfrm_postroute_last(sksec->sid, skb, &ad, proto))
5710 return NF_DROP_ERR(-ECONNREFUSED);
5715 static unsigned int selinux_ip_postroute(void *priv,
5716 struct sk_buff *skb,
5717 const struct nf_hook_state *state)
5724 struct common_audit_data ad;
5725 struct lsm_network_audit net;
5727 int secmark_active, peerlbl_active;
5729 /* If any sort of compatibility mode is enabled then handoff processing
5730 * to the selinux_ip_postroute_compat() function to deal with the
5731 * special handling. We do this in an attempt to keep this function
5732 * as fast and as clean as possible. */
5733 if (!selinux_policycap_netpeer())
5734 return selinux_ip_postroute_compat(skb, state);
5736 secmark_active = selinux_secmark_enabled();
5737 peerlbl_active = selinux_peerlbl_enabled();
5738 if (!secmark_active && !peerlbl_active)
5741 sk = skb_to_full_sk(skb);
5744 /* If skb->dst->xfrm is non-NULL then the packet is undergoing an IPsec
5745 * packet transformation so allow the packet to pass without any checks
5746 * since we'll have another chance to perform access control checks
5747 * when the packet is on it's final way out.
5748 * NOTE: there appear to be some IPv6 multicast cases where skb->dst
5749 * is NULL, in this case go ahead and apply access control.
5750 * NOTE: if this is a local socket (skb->sk != NULL) that is in the
5751 * TCP listening state we cannot wait until the XFRM processing
5752 * is done as we will miss out on the SA label if we do;
5753 * unfortunately, this means more work, but it is only once per
5755 if (skb_dst(skb) != NULL && skb_dst(skb)->xfrm != NULL &&
5756 !(sk && sk_listener(sk)))
5762 /* Without an associated socket the packet is either coming
5763 * from the kernel or it is being forwarded; check the packet
5764 * to determine which and if the packet is being forwarded
5765 * query the packet directly to determine the security label. */
5767 secmark_perm = PACKET__FORWARD_OUT;
5768 if (selinux_skb_peerlbl_sid(skb, family, &peer_sid))
5771 secmark_perm = PACKET__SEND;
5772 peer_sid = SECINITSID_KERNEL;
5774 } else if (sk_listener(sk)) {
5775 /* Locally generated packet but the associated socket is in the
5776 * listening state which means this is a SYN-ACK packet. In
5777 * this particular case the correct security label is assigned
5778 * to the connection/request_sock but unfortunately we can't
5779 * query the request_sock as it isn't queued on the parent
5780 * socket until after the SYN-ACK packet is sent; the only
5781 * viable choice is to regenerate the label like we do in
5782 * selinux_inet_conn_request(). See also selinux_ip_output()
5783 * for similar problems. */
5785 struct sk_security_struct *sksec;
5787 sksec = sk->sk_security;
5788 if (selinux_skb_peerlbl_sid(skb, family, &skb_sid))
5790 /* At this point, if the returned skb peerlbl is SECSID_NULL
5791 * and the packet has been through at least one XFRM
5792 * transformation then we must be dealing with the "final"
5793 * form of labeled IPsec packet; since we've already applied
5794 * all of our access controls on this packet we can safely
5795 * pass the packet. */
5796 if (skb_sid == SECSID_NULL) {
5799 if (IPCB(skb)->flags & IPSKB_XFRM_TRANSFORMED)
5803 if (IP6CB(skb)->flags & IP6SKB_XFRM_TRANSFORMED)
5807 return NF_DROP_ERR(-ECONNREFUSED);
5810 if (selinux_conn_sid(sksec->sid, skb_sid, &peer_sid))
5812 secmark_perm = PACKET__SEND;
5814 /* Locally generated packet, fetch the security label from the
5815 * associated socket. */
5816 struct sk_security_struct *sksec = sk->sk_security;
5817 peer_sid = sksec->sid;
5818 secmark_perm = PACKET__SEND;
5821 ifindex = state->out->ifindex;
5822 ad_net_init_from_iif(&ad, &net, ifindex, family);
5823 if (selinux_parse_skb(skb, &ad, &addrp, 0, NULL))
5827 if (avc_has_perm(peer_sid, skb->secmark,
5828 SECCLASS_PACKET, secmark_perm, &ad))
5829 return NF_DROP_ERR(-ECONNREFUSED);
5831 if (peerlbl_active) {
5835 if (sel_netif_sid(state->net, ifindex, &if_sid))
5837 if (avc_has_perm(peer_sid, if_sid,
5838 SECCLASS_NETIF, NETIF__EGRESS, &ad))
5839 return NF_DROP_ERR(-ECONNREFUSED);
5841 if (sel_netnode_sid(addrp, family, &node_sid))
5843 if (avc_has_perm(peer_sid, node_sid,
5844 SECCLASS_NODE, NODE__SENDTO, &ad))
5845 return NF_DROP_ERR(-ECONNREFUSED);
5850 #endif /* CONFIG_NETFILTER */
5852 static int selinux_netlink_send(struct sock *sk, struct sk_buff *skb)
5855 unsigned int msg_len;
5856 unsigned int data_len = skb->len;
5857 unsigned char *data = skb->data;
5858 struct nlmsghdr *nlh;
5859 struct sk_security_struct *sksec = sk->sk_security;
5860 u16 sclass = sksec->sclass;
5863 while (data_len >= nlmsg_total_size(0)) {
5864 nlh = (struct nlmsghdr *)data;
5866 /* NOTE: the nlmsg_len field isn't reliably set by some netlink
5867 * users which means we can't reject skb's with bogus
5868 * length fields; our solution is to follow what
5869 * netlink_rcv_skb() does and simply skip processing at
5870 * messages with length fields that are clearly junk
5872 if (nlh->nlmsg_len < NLMSG_HDRLEN || nlh->nlmsg_len > data_len)
5875 rc = selinux_nlmsg_lookup(sclass, nlh->nlmsg_type, &perm);
5877 rc = sock_has_perm(sk, perm);
5880 } else if (rc == -EINVAL) {
5881 /* -EINVAL is a missing msg/perm mapping */
5882 pr_warn_ratelimited("SELinux: unrecognized netlink"
5883 " message: protocol=%hu nlmsg_type=%hu sclass=%s"
5884 " pid=%d comm=%s\n",
5885 sk->sk_protocol, nlh->nlmsg_type,
5886 secclass_map[sclass - 1].name,
5887 task_pid_nr(current), current->comm);
5888 if (enforcing_enabled() &&
5889 !security_get_allow_unknown())
5892 } else if (rc == -ENOENT) {
5893 /* -ENOENT is a missing socket/class mapping, ignore */
5899 /* move to the next message after applying netlink padding */
5900 msg_len = NLMSG_ALIGN(nlh->nlmsg_len);
5901 if (msg_len >= data_len)
5903 data_len -= msg_len;
5910 static void ipc_init_security(struct ipc_security_struct *isec, u16 sclass)
5912 isec->sclass = sclass;
5913 isec->sid = current_sid();
5916 static int ipc_has_perm(struct kern_ipc_perm *ipc_perms,
5919 struct ipc_security_struct *isec;
5920 struct common_audit_data ad;
5921 u32 sid = current_sid();
5923 isec = selinux_ipc(ipc_perms);
5925 ad.type = LSM_AUDIT_DATA_IPC;
5926 ad.u.ipc_id = ipc_perms->key;
5928 return avc_has_perm(sid, isec->sid, isec->sclass, perms, &ad);
5931 static int selinux_msg_msg_alloc_security(struct msg_msg *msg)
5933 struct msg_security_struct *msec;
5935 msec = selinux_msg_msg(msg);
5936 msec->sid = SECINITSID_UNLABELED;
5941 /* message queue security operations */
5942 static int selinux_msg_queue_alloc_security(struct kern_ipc_perm *msq)
5944 struct ipc_security_struct *isec;
5945 struct common_audit_data ad;
5946 u32 sid = current_sid();
5948 isec = selinux_ipc(msq);
5949 ipc_init_security(isec, SECCLASS_MSGQ);
5951 ad.type = LSM_AUDIT_DATA_IPC;
5952 ad.u.ipc_id = msq->key;
5954 return avc_has_perm(sid, isec->sid, SECCLASS_MSGQ,
5958 static int selinux_msg_queue_associate(struct kern_ipc_perm *msq, int msqflg)
5960 struct ipc_security_struct *isec;
5961 struct common_audit_data ad;
5962 u32 sid = current_sid();
5964 isec = selinux_ipc(msq);
5966 ad.type = LSM_AUDIT_DATA_IPC;
5967 ad.u.ipc_id = msq->key;
5969 return avc_has_perm(sid, isec->sid, SECCLASS_MSGQ,
5970 MSGQ__ASSOCIATE, &ad);
5973 static int selinux_msg_queue_msgctl(struct kern_ipc_perm *msq, int cmd)
5980 /* No specific object, just general system-wide information. */
5981 return avc_has_perm(current_sid(), SECINITSID_KERNEL,
5982 SECCLASS_SYSTEM, SYSTEM__IPC_INFO, NULL);
5986 perms = MSGQ__GETATTR | MSGQ__ASSOCIATE;
5989 perms = MSGQ__SETATTR;
5992 perms = MSGQ__DESTROY;
5998 return ipc_has_perm(msq, perms);
6001 static int selinux_msg_queue_msgsnd(struct kern_ipc_perm *msq, struct msg_msg *msg, int msqflg)
6003 struct ipc_security_struct *isec;
6004 struct msg_security_struct *msec;
6005 struct common_audit_data ad;
6006 u32 sid = current_sid();
6009 isec = selinux_ipc(msq);
6010 msec = selinux_msg_msg(msg);
6013 * First time through, need to assign label to the message
6015 if (msec->sid == SECINITSID_UNLABELED) {
6017 * Compute new sid based on current process and
6018 * message queue this message will be stored in
6020 rc = security_transition_sid(sid, isec->sid,
6021 SECCLASS_MSG, NULL, &msec->sid);
6026 ad.type = LSM_AUDIT_DATA_IPC;
6027 ad.u.ipc_id = msq->key;
6029 /* Can this process write to the queue? */
6030 rc = avc_has_perm(sid, isec->sid, SECCLASS_MSGQ,
6033 /* Can this process send the message */
6034 rc = avc_has_perm(sid, msec->sid, SECCLASS_MSG,
6037 /* Can the message be put in the queue? */
6038 rc = avc_has_perm(msec->sid, isec->sid, SECCLASS_MSGQ,
6039 MSGQ__ENQUEUE, &ad);
6044 static int selinux_msg_queue_msgrcv(struct kern_ipc_perm *msq, struct msg_msg *msg,
6045 struct task_struct *target,
6046 long type, int mode)
6048 struct ipc_security_struct *isec;
6049 struct msg_security_struct *msec;
6050 struct common_audit_data ad;
6051 u32 sid = task_sid_obj(target);
6054 isec = selinux_ipc(msq);
6055 msec = selinux_msg_msg(msg);
6057 ad.type = LSM_AUDIT_DATA_IPC;
6058 ad.u.ipc_id = msq->key;
6060 rc = avc_has_perm(sid, isec->sid,
6061 SECCLASS_MSGQ, MSGQ__READ, &ad);
6063 rc = avc_has_perm(sid, msec->sid,
6064 SECCLASS_MSG, MSG__RECEIVE, &ad);
6068 /* Shared Memory security operations */
6069 static int selinux_shm_alloc_security(struct kern_ipc_perm *shp)
6071 struct ipc_security_struct *isec;
6072 struct common_audit_data ad;
6073 u32 sid = current_sid();
6075 isec = selinux_ipc(shp);
6076 ipc_init_security(isec, SECCLASS_SHM);
6078 ad.type = LSM_AUDIT_DATA_IPC;
6079 ad.u.ipc_id = shp->key;
6081 return avc_has_perm(sid, isec->sid, SECCLASS_SHM,
6085 static int selinux_shm_associate(struct kern_ipc_perm *shp, int shmflg)
6087 struct ipc_security_struct *isec;
6088 struct common_audit_data ad;
6089 u32 sid = current_sid();
6091 isec = selinux_ipc(shp);
6093 ad.type = LSM_AUDIT_DATA_IPC;
6094 ad.u.ipc_id = shp->key;
6096 return avc_has_perm(sid, isec->sid, SECCLASS_SHM,
6097 SHM__ASSOCIATE, &ad);
6100 /* Note, at this point, shp is locked down */
6101 static int selinux_shm_shmctl(struct kern_ipc_perm *shp, int cmd)
6108 /* No specific object, just general system-wide information. */
6109 return avc_has_perm(current_sid(), SECINITSID_KERNEL,
6110 SECCLASS_SYSTEM, SYSTEM__IPC_INFO, NULL);
6114 perms = SHM__GETATTR | SHM__ASSOCIATE;
6117 perms = SHM__SETATTR;
6124 perms = SHM__DESTROY;
6130 return ipc_has_perm(shp, perms);
6133 static int selinux_shm_shmat(struct kern_ipc_perm *shp,
6134 char __user *shmaddr, int shmflg)
6138 if (shmflg & SHM_RDONLY)
6141 perms = SHM__READ | SHM__WRITE;
6143 return ipc_has_perm(shp, perms);
6146 /* Semaphore security operations */
6147 static int selinux_sem_alloc_security(struct kern_ipc_perm *sma)
6149 struct ipc_security_struct *isec;
6150 struct common_audit_data ad;
6151 u32 sid = current_sid();
6153 isec = selinux_ipc(sma);
6154 ipc_init_security(isec, SECCLASS_SEM);
6156 ad.type = LSM_AUDIT_DATA_IPC;
6157 ad.u.ipc_id = sma->key;
6159 return avc_has_perm(sid, isec->sid, SECCLASS_SEM,
6163 static int selinux_sem_associate(struct kern_ipc_perm *sma, int semflg)
6165 struct ipc_security_struct *isec;
6166 struct common_audit_data ad;
6167 u32 sid = current_sid();
6169 isec = selinux_ipc(sma);
6171 ad.type = LSM_AUDIT_DATA_IPC;
6172 ad.u.ipc_id = sma->key;
6174 return avc_has_perm(sid, isec->sid, SECCLASS_SEM,
6175 SEM__ASSOCIATE, &ad);
6178 /* Note, at this point, sma is locked down */
6179 static int selinux_sem_semctl(struct kern_ipc_perm *sma, int cmd)
6187 /* No specific object, just general system-wide information. */
6188 return avc_has_perm(current_sid(), SECINITSID_KERNEL,
6189 SECCLASS_SYSTEM, SYSTEM__IPC_INFO, NULL);
6193 perms = SEM__GETATTR;
6204 perms = SEM__DESTROY;
6207 perms = SEM__SETATTR;
6212 perms = SEM__GETATTR | SEM__ASSOCIATE;
6218 err = ipc_has_perm(sma, perms);
6222 static int selinux_sem_semop(struct kern_ipc_perm *sma,
6223 struct sembuf *sops, unsigned nsops, int alter)
6228 perms = SEM__READ | SEM__WRITE;
6232 return ipc_has_perm(sma, perms);
6235 static int selinux_ipc_permission(struct kern_ipc_perm *ipcp, short flag)
6241 av |= IPC__UNIX_READ;
6243 av |= IPC__UNIX_WRITE;
6248 return ipc_has_perm(ipcp, av);
6251 static void selinux_ipc_getsecid(struct kern_ipc_perm *ipcp, u32 *secid)
6253 struct ipc_security_struct *isec = selinux_ipc(ipcp);
6257 static void selinux_d_instantiate(struct dentry *dentry, struct inode *inode)
6260 inode_doinit_with_dentry(inode, dentry);
6263 static int selinux_getprocattr(struct task_struct *p,
6264 const char *name, char **value)
6266 const struct task_security_struct *__tsec;
6272 __tsec = selinux_cred(__task_cred(p));
6275 error = avc_has_perm(current_sid(), __tsec->sid,
6276 SECCLASS_PROCESS, PROCESS__GETATTR, NULL);
6281 if (!strcmp(name, "current"))
6283 else if (!strcmp(name, "prev"))
6285 else if (!strcmp(name, "exec"))
6286 sid = __tsec->exec_sid;
6287 else if (!strcmp(name, "fscreate"))
6288 sid = __tsec->create_sid;
6289 else if (!strcmp(name, "keycreate"))
6290 sid = __tsec->keycreate_sid;
6291 else if (!strcmp(name, "sockcreate"))
6292 sid = __tsec->sockcreate_sid;
6302 error = security_sid_to_context(sid, value, &len);
6312 static int selinux_setprocattr(const char *name, void *value, size_t size)
6314 struct task_security_struct *tsec;
6316 u32 mysid = current_sid(), sid = 0, ptsid;
6321 * Basic control over ability to set these attributes at all.
6323 if (!strcmp(name, "exec"))
6324 error = avc_has_perm(mysid, mysid, SECCLASS_PROCESS,
6325 PROCESS__SETEXEC, NULL);
6326 else if (!strcmp(name, "fscreate"))
6327 error = avc_has_perm(mysid, mysid, SECCLASS_PROCESS,
6328 PROCESS__SETFSCREATE, NULL);
6329 else if (!strcmp(name, "keycreate"))
6330 error = avc_has_perm(mysid, mysid, SECCLASS_PROCESS,
6331 PROCESS__SETKEYCREATE, NULL);
6332 else if (!strcmp(name, "sockcreate"))
6333 error = avc_has_perm(mysid, mysid, SECCLASS_PROCESS,
6334 PROCESS__SETSOCKCREATE, NULL);
6335 else if (!strcmp(name, "current"))
6336 error = avc_has_perm(mysid, mysid, SECCLASS_PROCESS,
6337 PROCESS__SETCURRENT, NULL);
6343 /* Obtain a SID for the context, if one was specified. */
6344 if (size && str[0] && str[0] != '\n') {
6345 if (str[size-1] == '\n') {
6349 error = security_context_to_sid(value, size,
6351 if (error == -EINVAL && !strcmp(name, "fscreate")) {
6352 if (!has_cap_mac_admin(true)) {
6353 struct audit_buffer *ab;
6356 /* We strip a nul only if it is at the end, otherwise the
6357 * context contains a nul and we should audit that */
6358 if (str[size - 1] == '\0')
6359 audit_size = size - 1;
6362 ab = audit_log_start(audit_context(),
6367 audit_log_format(ab, "op=fscreate invalid_context=");
6368 audit_log_n_untrustedstring(ab, value, audit_size);
6373 error = security_context_to_sid_force(value, size,
6380 new = prepare_creds();
6384 /* Permission checking based on the specified context is
6385 performed during the actual operation (execve,
6386 open/mkdir/...), when we know the full context of the
6387 operation. See selinux_bprm_creds_for_exec for the execve
6388 checks and may_create for the file creation checks. The
6389 operation will then fail if the context is not permitted. */
6390 tsec = selinux_cred(new);
6391 if (!strcmp(name, "exec")) {
6392 tsec->exec_sid = sid;
6393 } else if (!strcmp(name, "fscreate")) {
6394 tsec->create_sid = sid;
6395 } else if (!strcmp(name, "keycreate")) {
6397 error = avc_has_perm(mysid, sid,
6398 SECCLASS_KEY, KEY__CREATE, NULL);
6402 tsec->keycreate_sid = sid;
6403 } else if (!strcmp(name, "sockcreate")) {
6404 tsec->sockcreate_sid = sid;
6405 } else if (!strcmp(name, "current")) {
6410 /* Only allow single threaded processes to change context */
6411 if (!current_is_single_threaded()) {
6412 error = security_bounded_transition(tsec->sid, sid);
6417 /* Check permissions for the transition. */
6418 error = avc_has_perm(tsec->sid, sid, SECCLASS_PROCESS,
6419 PROCESS__DYNTRANSITION, NULL);
6423 /* Check for ptracing, and update the task SID if ok.
6424 Otherwise, leave SID unchanged and fail. */
6425 ptsid = ptrace_parent_sid();
6427 error = avc_has_perm(ptsid, sid, SECCLASS_PROCESS,
6428 PROCESS__PTRACE, NULL);
6447 static int selinux_ismaclabel(const char *name)
6449 return (strcmp(name, XATTR_SELINUX_SUFFIX) == 0);
6452 static int selinux_secid_to_secctx(u32 secid, char **secdata, u32 *seclen)
6454 return security_sid_to_context(secid,
6458 static int selinux_secctx_to_secid(const char *secdata, u32 seclen, u32 *secid)
6460 return security_context_to_sid(secdata, seclen,
6464 static void selinux_release_secctx(char *secdata, u32 seclen)
6469 static void selinux_inode_invalidate_secctx(struct inode *inode)
6471 struct inode_security_struct *isec = selinux_inode(inode);
6473 spin_lock(&isec->lock);
6474 isec->initialized = LABEL_INVALID;
6475 spin_unlock(&isec->lock);
6479 * called with inode->i_mutex locked
6481 static int selinux_inode_notifysecctx(struct inode *inode, void *ctx, u32 ctxlen)
6483 int rc = selinux_inode_setsecurity(inode, XATTR_SELINUX_SUFFIX,
6485 /* Do not return error when suppressing label (SBLABEL_MNT not set). */
6486 return rc == -EOPNOTSUPP ? 0 : rc;
6490 * called with inode->i_mutex locked
6492 static int selinux_inode_setsecctx(struct dentry *dentry, void *ctx, u32 ctxlen)
6494 return __vfs_setxattr_noperm(&nop_mnt_idmap, dentry, XATTR_NAME_SELINUX,
6498 static int selinux_inode_getsecctx(struct inode *inode, void **ctx, u32 *ctxlen)
6501 len = selinux_inode_getsecurity(&nop_mnt_idmap, inode,
6502 XATTR_SELINUX_SUFFIX, ctx, true);
6510 static int selinux_key_alloc(struct key *k, const struct cred *cred,
6511 unsigned long flags)
6513 const struct task_security_struct *tsec;
6514 struct key_security_struct *ksec;
6516 ksec = kzalloc(sizeof(struct key_security_struct), GFP_KERNEL);
6520 tsec = selinux_cred(cred);
6521 if (tsec->keycreate_sid)
6522 ksec->sid = tsec->keycreate_sid;
6524 ksec->sid = tsec->sid;
6530 static void selinux_key_free(struct key *k)
6532 struct key_security_struct *ksec = k->security;
6538 static int selinux_key_permission(key_ref_t key_ref,
6539 const struct cred *cred,
6540 enum key_need_perm need_perm)
6543 struct key_security_struct *ksec;
6546 switch (need_perm) {
6553 case KEY_NEED_WRITE:
6556 case KEY_NEED_SEARCH:
6562 case KEY_NEED_SETATTR:
6563 perm = KEY__SETATTR;
6565 case KEY_NEED_UNLINK:
6566 case KEY_SYSADMIN_OVERRIDE:
6567 case KEY_AUTHTOKEN_OVERRIDE:
6568 case KEY_DEFER_PERM_CHECK:
6576 sid = cred_sid(cred);
6577 key = key_ref_to_ptr(key_ref);
6578 ksec = key->security;
6580 return avc_has_perm(sid, ksec->sid, SECCLASS_KEY, perm, NULL);
6583 static int selinux_key_getsecurity(struct key *key, char **_buffer)
6585 struct key_security_struct *ksec = key->security;
6586 char *context = NULL;
6590 rc = security_sid_to_context(ksec->sid,
6598 #ifdef CONFIG_KEY_NOTIFICATIONS
6599 static int selinux_watch_key(struct key *key)
6601 struct key_security_struct *ksec = key->security;
6602 u32 sid = current_sid();
6604 return avc_has_perm(sid, ksec->sid, SECCLASS_KEY, KEY__VIEW, NULL);
6609 #ifdef CONFIG_SECURITY_INFINIBAND
6610 static int selinux_ib_pkey_access(void *ib_sec, u64 subnet_prefix, u16 pkey_val)
6612 struct common_audit_data ad;
6615 struct ib_security_struct *sec = ib_sec;
6616 struct lsm_ibpkey_audit ibpkey;
6618 err = sel_ib_pkey_sid(subnet_prefix, pkey_val, &sid);
6622 ad.type = LSM_AUDIT_DATA_IBPKEY;
6623 ibpkey.subnet_prefix = subnet_prefix;
6624 ibpkey.pkey = pkey_val;
6625 ad.u.ibpkey = &ibpkey;
6626 return avc_has_perm(sec->sid, sid,
6627 SECCLASS_INFINIBAND_PKEY,
6628 INFINIBAND_PKEY__ACCESS, &ad);
6631 static int selinux_ib_endport_manage_subnet(void *ib_sec, const char *dev_name,
6634 struct common_audit_data ad;
6637 struct ib_security_struct *sec = ib_sec;
6638 struct lsm_ibendport_audit ibendport;
6640 err = security_ib_endport_sid(dev_name, port_num,
6646 ad.type = LSM_AUDIT_DATA_IBENDPORT;
6647 ibendport.dev_name = dev_name;
6648 ibendport.port = port_num;
6649 ad.u.ibendport = &ibendport;
6650 return avc_has_perm(sec->sid, sid,
6651 SECCLASS_INFINIBAND_ENDPORT,
6652 INFINIBAND_ENDPORT__MANAGE_SUBNET, &ad);
6655 static int selinux_ib_alloc_security(void **ib_sec)
6657 struct ib_security_struct *sec;
6659 sec = kzalloc(sizeof(*sec), GFP_KERNEL);
6662 sec->sid = current_sid();
6668 static void selinux_ib_free_security(void *ib_sec)
6674 #ifdef CONFIG_BPF_SYSCALL
6675 static int selinux_bpf(int cmd, union bpf_attr *attr,
6678 u32 sid = current_sid();
6682 case BPF_MAP_CREATE:
6683 ret = avc_has_perm(sid, sid, SECCLASS_BPF, BPF__MAP_CREATE,
6687 ret = avc_has_perm(sid, sid, SECCLASS_BPF, BPF__PROG_LOAD,
6698 static u32 bpf_map_fmode_to_av(fmode_t fmode)
6702 if (fmode & FMODE_READ)
6703 av |= BPF__MAP_READ;
6704 if (fmode & FMODE_WRITE)
6705 av |= BPF__MAP_WRITE;
6709 /* This function will check the file pass through unix socket or binder to see
6710 * if it is a bpf related object. And apply corresponding checks on the bpf
6711 * object based on the type. The bpf maps and programs, not like other files and
6712 * socket, are using a shared anonymous inode inside the kernel as their inode.
6713 * So checking that inode cannot identify if the process have privilege to
6714 * access the bpf object and that's why we have to add this additional check in
6715 * selinux_file_receive and selinux_binder_transfer_files.
6717 static int bpf_fd_pass(struct file *file, u32 sid)
6719 struct bpf_security_struct *bpfsec;
6720 struct bpf_prog *prog;
6721 struct bpf_map *map;
6724 if (file->f_op == &bpf_map_fops) {
6725 map = file->private_data;
6726 bpfsec = map->security;
6727 ret = avc_has_perm(sid, bpfsec->sid, SECCLASS_BPF,
6728 bpf_map_fmode_to_av(file->f_mode), NULL);
6731 } else if (file->f_op == &bpf_prog_fops) {
6732 prog = file->private_data;
6733 bpfsec = prog->aux->security;
6734 ret = avc_has_perm(sid, bpfsec->sid, SECCLASS_BPF,
6735 BPF__PROG_RUN, NULL);
6742 static int selinux_bpf_map(struct bpf_map *map, fmode_t fmode)
6744 u32 sid = current_sid();
6745 struct bpf_security_struct *bpfsec;
6747 bpfsec = map->security;
6748 return avc_has_perm(sid, bpfsec->sid, SECCLASS_BPF,
6749 bpf_map_fmode_to_av(fmode), NULL);
6752 static int selinux_bpf_prog(struct bpf_prog *prog)
6754 u32 sid = current_sid();
6755 struct bpf_security_struct *bpfsec;
6757 bpfsec = prog->aux->security;
6758 return avc_has_perm(sid, bpfsec->sid, SECCLASS_BPF,
6759 BPF__PROG_RUN, NULL);
6762 static int selinux_bpf_map_alloc(struct bpf_map *map)
6764 struct bpf_security_struct *bpfsec;
6766 bpfsec = kzalloc(sizeof(*bpfsec), GFP_KERNEL);
6770 bpfsec->sid = current_sid();
6771 map->security = bpfsec;
6776 static void selinux_bpf_map_free(struct bpf_map *map)
6778 struct bpf_security_struct *bpfsec = map->security;
6780 map->security = NULL;
6784 static int selinux_bpf_prog_alloc(struct bpf_prog_aux *aux)
6786 struct bpf_security_struct *bpfsec;
6788 bpfsec = kzalloc(sizeof(*bpfsec), GFP_KERNEL);
6792 bpfsec->sid = current_sid();
6793 aux->security = bpfsec;
6798 static void selinux_bpf_prog_free(struct bpf_prog_aux *aux)
6800 struct bpf_security_struct *bpfsec = aux->security;
6802 aux->security = NULL;
6807 struct lsm_blob_sizes selinux_blob_sizes __ro_after_init = {
6808 .lbs_cred = sizeof(struct task_security_struct),
6809 .lbs_file = sizeof(struct file_security_struct),
6810 .lbs_inode = sizeof(struct inode_security_struct),
6811 .lbs_ipc = sizeof(struct ipc_security_struct),
6812 .lbs_msg_msg = sizeof(struct msg_security_struct),
6813 .lbs_superblock = sizeof(struct superblock_security_struct),
6816 #ifdef CONFIG_PERF_EVENTS
6817 static int selinux_perf_event_open(struct perf_event_attr *attr, int type)
6819 u32 requested, sid = current_sid();
6821 if (type == PERF_SECURITY_OPEN)
6822 requested = PERF_EVENT__OPEN;
6823 else if (type == PERF_SECURITY_CPU)
6824 requested = PERF_EVENT__CPU;
6825 else if (type == PERF_SECURITY_KERNEL)
6826 requested = PERF_EVENT__KERNEL;
6827 else if (type == PERF_SECURITY_TRACEPOINT)
6828 requested = PERF_EVENT__TRACEPOINT;
6832 return avc_has_perm(sid, sid, SECCLASS_PERF_EVENT,
6836 static int selinux_perf_event_alloc(struct perf_event *event)
6838 struct perf_event_security_struct *perfsec;
6840 perfsec = kzalloc(sizeof(*perfsec), GFP_KERNEL);
6844 perfsec->sid = current_sid();
6845 event->security = perfsec;
6850 static void selinux_perf_event_free(struct perf_event *event)
6852 struct perf_event_security_struct *perfsec = event->security;
6854 event->security = NULL;
6858 static int selinux_perf_event_read(struct perf_event *event)
6860 struct perf_event_security_struct *perfsec = event->security;
6861 u32 sid = current_sid();
6863 return avc_has_perm(sid, perfsec->sid,
6864 SECCLASS_PERF_EVENT, PERF_EVENT__READ, NULL);
6867 static int selinux_perf_event_write(struct perf_event *event)
6869 struct perf_event_security_struct *perfsec = event->security;
6870 u32 sid = current_sid();
6872 return avc_has_perm(sid, perfsec->sid,
6873 SECCLASS_PERF_EVENT, PERF_EVENT__WRITE, NULL);
6877 #ifdef CONFIG_IO_URING
6879 * selinux_uring_override_creds - check the requested cred override
6880 * @new: the target creds
6882 * Check to see if the current task is allowed to override it's credentials
6883 * to service an io_uring operation.
6885 static int selinux_uring_override_creds(const struct cred *new)
6887 return avc_has_perm(current_sid(), cred_sid(new),
6888 SECCLASS_IO_URING, IO_URING__OVERRIDE_CREDS, NULL);
6892 * selinux_uring_sqpoll - check if a io_uring polling thread can be created
6894 * Check to see if the current task is allowed to create a new io_uring
6895 * kernel polling thread.
6897 static int selinux_uring_sqpoll(void)
6899 u32 sid = current_sid();
6901 return avc_has_perm(sid, sid,
6902 SECCLASS_IO_URING, IO_URING__SQPOLL, NULL);
6906 * selinux_uring_cmd - check if IORING_OP_URING_CMD is allowed
6907 * @ioucmd: the io_uring command structure
6909 * Check to see if the current domain is allowed to execute an
6910 * IORING_OP_URING_CMD against the device/file specified in @ioucmd.
6913 static int selinux_uring_cmd(struct io_uring_cmd *ioucmd)
6915 struct file *file = ioucmd->file;
6916 struct inode *inode = file_inode(file);
6917 struct inode_security_struct *isec = selinux_inode(inode);
6918 struct common_audit_data ad;
6920 ad.type = LSM_AUDIT_DATA_FILE;
6923 return avc_has_perm(current_sid(), isec->sid,
6924 SECCLASS_IO_URING, IO_URING__CMD, &ad);
6926 #endif /* CONFIG_IO_URING */
6929 * IMPORTANT NOTE: When adding new hooks, please be careful to keep this order:
6930 * 1. any hooks that don't belong to (2.) or (3.) below,
6931 * 2. hooks that both access structures allocated by other hooks, and allocate
6932 * structures that can be later accessed by other hooks (mostly "cloning"
6934 * 3. hooks that only allocate structures that can be later accessed by other
6935 * hooks ("allocating" hooks).
6937 * Please follow block comment delimiters in the list to keep this order.
6939 static struct security_hook_list selinux_hooks[] __ro_after_init = {
6940 LSM_HOOK_INIT(binder_set_context_mgr, selinux_binder_set_context_mgr),
6941 LSM_HOOK_INIT(binder_transaction, selinux_binder_transaction),
6942 LSM_HOOK_INIT(binder_transfer_binder, selinux_binder_transfer_binder),
6943 LSM_HOOK_INIT(binder_transfer_file, selinux_binder_transfer_file),
6945 LSM_HOOK_INIT(ptrace_access_check, selinux_ptrace_access_check),
6946 LSM_HOOK_INIT(ptrace_traceme, selinux_ptrace_traceme),
6947 LSM_HOOK_INIT(capget, selinux_capget),
6948 LSM_HOOK_INIT(capset, selinux_capset),
6949 LSM_HOOK_INIT(capable, selinux_capable),
6950 LSM_HOOK_INIT(quotactl, selinux_quotactl),
6951 LSM_HOOK_INIT(quota_on, selinux_quota_on),
6952 LSM_HOOK_INIT(syslog, selinux_syslog),
6953 LSM_HOOK_INIT(vm_enough_memory, selinux_vm_enough_memory),
6955 LSM_HOOK_INIT(netlink_send, selinux_netlink_send),
6957 LSM_HOOK_INIT(bprm_creds_for_exec, selinux_bprm_creds_for_exec),
6958 LSM_HOOK_INIT(bprm_committing_creds, selinux_bprm_committing_creds),
6959 LSM_HOOK_INIT(bprm_committed_creds, selinux_bprm_committed_creds),
6961 LSM_HOOK_INIT(sb_free_mnt_opts, selinux_free_mnt_opts),
6962 LSM_HOOK_INIT(sb_mnt_opts_compat, selinux_sb_mnt_opts_compat),
6963 LSM_HOOK_INIT(sb_remount, selinux_sb_remount),
6964 LSM_HOOK_INIT(sb_kern_mount, selinux_sb_kern_mount),
6965 LSM_HOOK_INIT(sb_show_options, selinux_sb_show_options),
6966 LSM_HOOK_INIT(sb_statfs, selinux_sb_statfs),
6967 LSM_HOOK_INIT(sb_mount, selinux_mount),
6968 LSM_HOOK_INIT(sb_umount, selinux_umount),
6969 LSM_HOOK_INIT(sb_set_mnt_opts, selinux_set_mnt_opts),
6970 LSM_HOOK_INIT(sb_clone_mnt_opts, selinux_sb_clone_mnt_opts),
6972 LSM_HOOK_INIT(move_mount, selinux_move_mount),
6974 LSM_HOOK_INIT(dentry_init_security, selinux_dentry_init_security),
6975 LSM_HOOK_INIT(dentry_create_files_as, selinux_dentry_create_files_as),
6977 LSM_HOOK_INIT(inode_free_security, selinux_inode_free_security),
6978 LSM_HOOK_INIT(inode_init_security, selinux_inode_init_security),
6979 LSM_HOOK_INIT(inode_init_security_anon, selinux_inode_init_security_anon),
6980 LSM_HOOK_INIT(inode_create, selinux_inode_create),
6981 LSM_HOOK_INIT(inode_link, selinux_inode_link),
6982 LSM_HOOK_INIT(inode_unlink, selinux_inode_unlink),
6983 LSM_HOOK_INIT(inode_symlink, selinux_inode_symlink),
6984 LSM_HOOK_INIT(inode_mkdir, selinux_inode_mkdir),
6985 LSM_HOOK_INIT(inode_rmdir, selinux_inode_rmdir),
6986 LSM_HOOK_INIT(inode_mknod, selinux_inode_mknod),
6987 LSM_HOOK_INIT(inode_rename, selinux_inode_rename),
6988 LSM_HOOK_INIT(inode_readlink, selinux_inode_readlink),
6989 LSM_HOOK_INIT(inode_follow_link, selinux_inode_follow_link),
6990 LSM_HOOK_INIT(inode_permission, selinux_inode_permission),
6991 LSM_HOOK_INIT(inode_setattr, selinux_inode_setattr),
6992 LSM_HOOK_INIT(inode_getattr, selinux_inode_getattr),
6993 LSM_HOOK_INIT(inode_setxattr, selinux_inode_setxattr),
6994 LSM_HOOK_INIT(inode_post_setxattr, selinux_inode_post_setxattr),
6995 LSM_HOOK_INIT(inode_getxattr, selinux_inode_getxattr),
6996 LSM_HOOK_INIT(inode_listxattr, selinux_inode_listxattr),
6997 LSM_HOOK_INIT(inode_removexattr, selinux_inode_removexattr),
6998 LSM_HOOK_INIT(inode_set_acl, selinux_inode_set_acl),
6999 LSM_HOOK_INIT(inode_get_acl, selinux_inode_get_acl),
7000 LSM_HOOK_INIT(inode_remove_acl, selinux_inode_remove_acl),
7001 LSM_HOOK_INIT(inode_getsecurity, selinux_inode_getsecurity),
7002 LSM_HOOK_INIT(inode_setsecurity, selinux_inode_setsecurity),
7003 LSM_HOOK_INIT(inode_listsecurity, selinux_inode_listsecurity),
7004 LSM_HOOK_INIT(inode_getsecid, selinux_inode_getsecid),
7005 LSM_HOOK_INIT(inode_copy_up, selinux_inode_copy_up),
7006 LSM_HOOK_INIT(inode_copy_up_xattr, selinux_inode_copy_up_xattr),
7007 LSM_HOOK_INIT(path_notify, selinux_path_notify),
7009 LSM_HOOK_INIT(kernfs_init_security, selinux_kernfs_init_security),
7011 LSM_HOOK_INIT(file_permission, selinux_file_permission),
7012 LSM_HOOK_INIT(file_alloc_security, selinux_file_alloc_security),
7013 LSM_HOOK_INIT(file_ioctl, selinux_file_ioctl),
7014 LSM_HOOK_INIT(mmap_file, selinux_mmap_file),
7015 LSM_HOOK_INIT(mmap_addr, selinux_mmap_addr),
7016 LSM_HOOK_INIT(file_mprotect, selinux_file_mprotect),
7017 LSM_HOOK_INIT(file_lock, selinux_file_lock),
7018 LSM_HOOK_INIT(file_fcntl, selinux_file_fcntl),
7019 LSM_HOOK_INIT(file_set_fowner, selinux_file_set_fowner),
7020 LSM_HOOK_INIT(file_send_sigiotask, selinux_file_send_sigiotask),
7021 LSM_HOOK_INIT(file_receive, selinux_file_receive),
7023 LSM_HOOK_INIT(file_open, selinux_file_open),
7025 LSM_HOOK_INIT(task_alloc, selinux_task_alloc),
7026 LSM_HOOK_INIT(cred_prepare, selinux_cred_prepare),
7027 LSM_HOOK_INIT(cred_transfer, selinux_cred_transfer),
7028 LSM_HOOK_INIT(cred_getsecid, selinux_cred_getsecid),
7029 LSM_HOOK_INIT(kernel_act_as, selinux_kernel_act_as),
7030 LSM_HOOK_INIT(kernel_create_files_as, selinux_kernel_create_files_as),
7031 LSM_HOOK_INIT(kernel_module_request, selinux_kernel_module_request),
7032 LSM_HOOK_INIT(kernel_load_data, selinux_kernel_load_data),
7033 LSM_HOOK_INIT(kernel_read_file, selinux_kernel_read_file),
7034 LSM_HOOK_INIT(task_setpgid, selinux_task_setpgid),
7035 LSM_HOOK_INIT(task_getpgid, selinux_task_getpgid),
7036 LSM_HOOK_INIT(task_getsid, selinux_task_getsid),
7037 LSM_HOOK_INIT(current_getsecid_subj, selinux_current_getsecid_subj),
7038 LSM_HOOK_INIT(task_getsecid_obj, selinux_task_getsecid_obj),
7039 LSM_HOOK_INIT(task_setnice, selinux_task_setnice),
7040 LSM_HOOK_INIT(task_setioprio, selinux_task_setioprio),
7041 LSM_HOOK_INIT(task_getioprio, selinux_task_getioprio),
7042 LSM_HOOK_INIT(task_prlimit, selinux_task_prlimit),
7043 LSM_HOOK_INIT(task_setrlimit, selinux_task_setrlimit),
7044 LSM_HOOK_INIT(task_setscheduler, selinux_task_setscheduler),
7045 LSM_HOOK_INIT(task_getscheduler, selinux_task_getscheduler),
7046 LSM_HOOK_INIT(task_movememory, selinux_task_movememory),
7047 LSM_HOOK_INIT(task_kill, selinux_task_kill),
7048 LSM_HOOK_INIT(task_to_inode, selinux_task_to_inode),
7049 LSM_HOOK_INIT(userns_create, selinux_userns_create),
7051 LSM_HOOK_INIT(ipc_permission, selinux_ipc_permission),
7052 LSM_HOOK_INIT(ipc_getsecid, selinux_ipc_getsecid),
7054 LSM_HOOK_INIT(msg_queue_associate, selinux_msg_queue_associate),
7055 LSM_HOOK_INIT(msg_queue_msgctl, selinux_msg_queue_msgctl),
7056 LSM_HOOK_INIT(msg_queue_msgsnd, selinux_msg_queue_msgsnd),
7057 LSM_HOOK_INIT(msg_queue_msgrcv, selinux_msg_queue_msgrcv),
7059 LSM_HOOK_INIT(shm_associate, selinux_shm_associate),
7060 LSM_HOOK_INIT(shm_shmctl, selinux_shm_shmctl),
7061 LSM_HOOK_INIT(shm_shmat, selinux_shm_shmat),
7063 LSM_HOOK_INIT(sem_associate, selinux_sem_associate),
7064 LSM_HOOK_INIT(sem_semctl, selinux_sem_semctl),
7065 LSM_HOOK_INIT(sem_semop, selinux_sem_semop),
7067 LSM_HOOK_INIT(d_instantiate, selinux_d_instantiate),
7069 LSM_HOOK_INIT(getprocattr, selinux_getprocattr),
7070 LSM_HOOK_INIT(setprocattr, selinux_setprocattr),
7072 LSM_HOOK_INIT(ismaclabel, selinux_ismaclabel),
7073 LSM_HOOK_INIT(secctx_to_secid, selinux_secctx_to_secid),
7074 LSM_HOOK_INIT(release_secctx, selinux_release_secctx),
7075 LSM_HOOK_INIT(inode_invalidate_secctx, selinux_inode_invalidate_secctx),
7076 LSM_HOOK_INIT(inode_notifysecctx, selinux_inode_notifysecctx),
7077 LSM_HOOK_INIT(inode_setsecctx, selinux_inode_setsecctx),
7079 LSM_HOOK_INIT(unix_stream_connect, selinux_socket_unix_stream_connect),
7080 LSM_HOOK_INIT(unix_may_send, selinux_socket_unix_may_send),
7082 LSM_HOOK_INIT(socket_create, selinux_socket_create),
7083 LSM_HOOK_INIT(socket_post_create, selinux_socket_post_create),
7084 LSM_HOOK_INIT(socket_socketpair, selinux_socket_socketpair),
7085 LSM_HOOK_INIT(socket_bind, selinux_socket_bind),
7086 LSM_HOOK_INIT(socket_connect, selinux_socket_connect),
7087 LSM_HOOK_INIT(socket_listen, selinux_socket_listen),
7088 LSM_HOOK_INIT(socket_accept, selinux_socket_accept),
7089 LSM_HOOK_INIT(socket_sendmsg, selinux_socket_sendmsg),
7090 LSM_HOOK_INIT(socket_recvmsg, selinux_socket_recvmsg),
7091 LSM_HOOK_INIT(socket_getsockname, selinux_socket_getsockname),
7092 LSM_HOOK_INIT(socket_getpeername, selinux_socket_getpeername),
7093 LSM_HOOK_INIT(socket_getsockopt, selinux_socket_getsockopt),
7094 LSM_HOOK_INIT(socket_setsockopt, selinux_socket_setsockopt),
7095 LSM_HOOK_INIT(socket_shutdown, selinux_socket_shutdown),
7096 LSM_HOOK_INIT(socket_sock_rcv_skb, selinux_socket_sock_rcv_skb),
7097 LSM_HOOK_INIT(socket_getpeersec_stream,
7098 selinux_socket_getpeersec_stream),
7099 LSM_HOOK_INIT(socket_getpeersec_dgram, selinux_socket_getpeersec_dgram),
7100 LSM_HOOK_INIT(sk_free_security, selinux_sk_free_security),
7101 LSM_HOOK_INIT(sk_clone_security, selinux_sk_clone_security),
7102 LSM_HOOK_INIT(sk_getsecid, selinux_sk_getsecid),
7103 LSM_HOOK_INIT(sock_graft, selinux_sock_graft),
7104 LSM_HOOK_INIT(sctp_assoc_request, selinux_sctp_assoc_request),
7105 LSM_HOOK_INIT(sctp_sk_clone, selinux_sctp_sk_clone),
7106 LSM_HOOK_INIT(sctp_bind_connect, selinux_sctp_bind_connect),
7107 LSM_HOOK_INIT(sctp_assoc_established, selinux_sctp_assoc_established),
7108 LSM_HOOK_INIT(mptcp_add_subflow, selinux_mptcp_add_subflow),
7109 LSM_HOOK_INIT(inet_conn_request, selinux_inet_conn_request),
7110 LSM_HOOK_INIT(inet_csk_clone, selinux_inet_csk_clone),
7111 LSM_HOOK_INIT(inet_conn_established, selinux_inet_conn_established),
7112 LSM_HOOK_INIT(secmark_relabel_packet, selinux_secmark_relabel_packet),
7113 LSM_HOOK_INIT(secmark_refcount_inc, selinux_secmark_refcount_inc),
7114 LSM_HOOK_INIT(secmark_refcount_dec, selinux_secmark_refcount_dec),
7115 LSM_HOOK_INIT(req_classify_flow, selinux_req_classify_flow),
7116 LSM_HOOK_INIT(tun_dev_free_security, selinux_tun_dev_free_security),
7117 LSM_HOOK_INIT(tun_dev_create, selinux_tun_dev_create),
7118 LSM_HOOK_INIT(tun_dev_attach_queue, selinux_tun_dev_attach_queue),
7119 LSM_HOOK_INIT(tun_dev_attach, selinux_tun_dev_attach),
7120 LSM_HOOK_INIT(tun_dev_open, selinux_tun_dev_open),
7121 #ifdef CONFIG_SECURITY_INFINIBAND
7122 LSM_HOOK_INIT(ib_pkey_access, selinux_ib_pkey_access),
7123 LSM_HOOK_INIT(ib_endport_manage_subnet,
7124 selinux_ib_endport_manage_subnet),
7125 LSM_HOOK_INIT(ib_free_security, selinux_ib_free_security),
7127 #ifdef CONFIG_SECURITY_NETWORK_XFRM
7128 LSM_HOOK_INIT(xfrm_policy_free_security, selinux_xfrm_policy_free),
7129 LSM_HOOK_INIT(xfrm_policy_delete_security, selinux_xfrm_policy_delete),
7130 LSM_HOOK_INIT(xfrm_state_free_security, selinux_xfrm_state_free),
7131 LSM_HOOK_INIT(xfrm_state_delete_security, selinux_xfrm_state_delete),
7132 LSM_HOOK_INIT(xfrm_policy_lookup, selinux_xfrm_policy_lookup),
7133 LSM_HOOK_INIT(xfrm_state_pol_flow_match,
7134 selinux_xfrm_state_pol_flow_match),
7135 LSM_HOOK_INIT(xfrm_decode_session, selinux_xfrm_decode_session),
7139 LSM_HOOK_INIT(key_free, selinux_key_free),
7140 LSM_HOOK_INIT(key_permission, selinux_key_permission),
7141 LSM_HOOK_INIT(key_getsecurity, selinux_key_getsecurity),
7142 #ifdef CONFIG_KEY_NOTIFICATIONS
7143 LSM_HOOK_INIT(watch_key, selinux_watch_key),
7148 LSM_HOOK_INIT(audit_rule_known, selinux_audit_rule_known),
7149 LSM_HOOK_INIT(audit_rule_match, selinux_audit_rule_match),
7150 LSM_HOOK_INIT(audit_rule_free, selinux_audit_rule_free),
7153 #ifdef CONFIG_BPF_SYSCALL
7154 LSM_HOOK_INIT(bpf, selinux_bpf),
7155 LSM_HOOK_INIT(bpf_map, selinux_bpf_map),
7156 LSM_HOOK_INIT(bpf_prog, selinux_bpf_prog),
7157 LSM_HOOK_INIT(bpf_map_free_security, selinux_bpf_map_free),
7158 LSM_HOOK_INIT(bpf_prog_free_security, selinux_bpf_prog_free),
7161 #ifdef CONFIG_PERF_EVENTS
7162 LSM_HOOK_INIT(perf_event_open, selinux_perf_event_open),
7163 LSM_HOOK_INIT(perf_event_free, selinux_perf_event_free),
7164 LSM_HOOK_INIT(perf_event_read, selinux_perf_event_read),
7165 LSM_HOOK_INIT(perf_event_write, selinux_perf_event_write),
7168 #ifdef CONFIG_IO_URING
7169 LSM_HOOK_INIT(uring_override_creds, selinux_uring_override_creds),
7170 LSM_HOOK_INIT(uring_sqpoll, selinux_uring_sqpoll),
7171 LSM_HOOK_INIT(uring_cmd, selinux_uring_cmd),
7175 * PUT "CLONING" (ACCESSING + ALLOCATING) HOOKS HERE
7177 LSM_HOOK_INIT(fs_context_dup, selinux_fs_context_dup),
7178 LSM_HOOK_INIT(fs_context_parse_param, selinux_fs_context_parse_param),
7179 LSM_HOOK_INIT(sb_eat_lsm_opts, selinux_sb_eat_lsm_opts),
7180 #ifdef CONFIG_SECURITY_NETWORK_XFRM
7181 LSM_HOOK_INIT(xfrm_policy_clone_security, selinux_xfrm_policy_clone),
7185 * PUT "ALLOCATING" HOOKS HERE
7187 LSM_HOOK_INIT(msg_msg_alloc_security, selinux_msg_msg_alloc_security),
7188 LSM_HOOK_INIT(msg_queue_alloc_security,
7189 selinux_msg_queue_alloc_security),
7190 LSM_HOOK_INIT(shm_alloc_security, selinux_shm_alloc_security),
7191 LSM_HOOK_INIT(sb_alloc_security, selinux_sb_alloc_security),
7192 LSM_HOOK_INIT(inode_alloc_security, selinux_inode_alloc_security),
7193 LSM_HOOK_INIT(sem_alloc_security, selinux_sem_alloc_security),
7194 LSM_HOOK_INIT(secid_to_secctx, selinux_secid_to_secctx),
7195 LSM_HOOK_INIT(inode_getsecctx, selinux_inode_getsecctx),
7196 LSM_HOOK_INIT(sk_alloc_security, selinux_sk_alloc_security),
7197 LSM_HOOK_INIT(tun_dev_alloc_security, selinux_tun_dev_alloc_security),
7198 #ifdef CONFIG_SECURITY_INFINIBAND
7199 LSM_HOOK_INIT(ib_alloc_security, selinux_ib_alloc_security),
7201 #ifdef CONFIG_SECURITY_NETWORK_XFRM
7202 LSM_HOOK_INIT(xfrm_policy_alloc_security, selinux_xfrm_policy_alloc),
7203 LSM_HOOK_INIT(xfrm_state_alloc, selinux_xfrm_state_alloc),
7204 LSM_HOOK_INIT(xfrm_state_alloc_acquire,
7205 selinux_xfrm_state_alloc_acquire),
7208 LSM_HOOK_INIT(key_alloc, selinux_key_alloc),
7211 LSM_HOOK_INIT(audit_rule_init, selinux_audit_rule_init),
7213 #ifdef CONFIG_BPF_SYSCALL
7214 LSM_HOOK_INIT(bpf_map_alloc_security, selinux_bpf_map_alloc),
7215 LSM_HOOK_INIT(bpf_prog_alloc_security, selinux_bpf_prog_alloc),
7217 #ifdef CONFIG_PERF_EVENTS
7218 LSM_HOOK_INIT(perf_event_alloc, selinux_perf_event_alloc),
7222 static __init int selinux_init(void)
7224 pr_info("SELinux: Initializing.\n");
7226 memset(&selinux_state, 0, sizeof(selinux_state));
7227 enforcing_set(selinux_enforcing_boot);
7229 mutex_init(&selinux_state.status_lock);
7230 mutex_init(&selinux_state.policy_mutex);
7232 /* Set the security state for the initial task. */
7233 cred_init_security();
7235 default_noexec = !(VM_DATA_DEFAULT_FLAGS & VM_EXEC);
7236 if (!default_noexec)
7237 pr_notice("SELinux: virtual memory is executable by default\n");
7243 ebitmap_cache_init();
7245 hashtab_cache_init();
7247 security_add_hooks(selinux_hooks, ARRAY_SIZE(selinux_hooks), "selinux");
7249 if (avc_add_callback(selinux_netcache_avc_callback, AVC_CALLBACK_RESET))
7250 panic("SELinux: Unable to register AVC netcache callback\n");
7252 if (avc_add_callback(selinux_lsm_notifier_avc_callback, AVC_CALLBACK_RESET))
7253 panic("SELinux: Unable to register AVC LSM notifier callback\n");
7255 if (selinux_enforcing_boot)
7256 pr_debug("SELinux: Starting in enforcing mode\n");
7258 pr_debug("SELinux: Starting in permissive mode\n");
7260 fs_validate_description("selinux", selinux_fs_parameters);
7265 static void delayed_superblock_init(struct super_block *sb, void *unused)
7267 selinux_set_mnt_opts(sb, NULL, 0, NULL);
7270 void selinux_complete_init(void)
7272 pr_debug("SELinux: Completing initialization.\n");
7274 /* Set up any superblocks initialized prior to the policy load. */
7275 pr_debug("SELinux: Setting up existing superblocks.\n");
7276 iterate_supers(delayed_superblock_init, NULL);
7279 /* SELinux requires early initialization in order to label
7280 all processes and objects when they are created. */
7281 DEFINE_LSM(selinux) = {
7283 .flags = LSM_FLAG_LEGACY_MAJOR | LSM_FLAG_EXCLUSIVE,
7284 .enabled = &selinux_enabled_boot,
7285 .blobs = &selinux_blob_sizes,
7286 .init = selinux_init,
7289 #if defined(CONFIG_NETFILTER)
7290 static const struct nf_hook_ops selinux_nf_ops[] = {
7292 .hook = selinux_ip_postroute,
7294 .hooknum = NF_INET_POST_ROUTING,
7295 .priority = NF_IP_PRI_SELINUX_LAST,
7298 .hook = selinux_ip_forward,
7300 .hooknum = NF_INET_FORWARD,
7301 .priority = NF_IP_PRI_SELINUX_FIRST,
7304 .hook = selinux_ip_output,
7306 .hooknum = NF_INET_LOCAL_OUT,
7307 .priority = NF_IP_PRI_SELINUX_FIRST,
7309 #if IS_ENABLED(CONFIG_IPV6)
7311 .hook = selinux_ip_postroute,
7313 .hooknum = NF_INET_POST_ROUTING,
7314 .priority = NF_IP6_PRI_SELINUX_LAST,
7317 .hook = selinux_ip_forward,
7319 .hooknum = NF_INET_FORWARD,
7320 .priority = NF_IP6_PRI_SELINUX_FIRST,
7323 .hook = selinux_ip_output,
7325 .hooknum = NF_INET_LOCAL_OUT,
7326 .priority = NF_IP6_PRI_SELINUX_FIRST,
7331 static int __net_init selinux_nf_register(struct net *net)
7333 return nf_register_net_hooks(net, selinux_nf_ops,
7334 ARRAY_SIZE(selinux_nf_ops));
7337 static void __net_exit selinux_nf_unregister(struct net *net)
7339 nf_unregister_net_hooks(net, selinux_nf_ops,
7340 ARRAY_SIZE(selinux_nf_ops));
7343 static struct pernet_operations selinux_net_ops = {
7344 .init = selinux_nf_register,
7345 .exit = selinux_nf_unregister,
7348 static int __init selinux_nf_ip_init(void)
7352 if (!selinux_enabled_boot)
7355 pr_debug("SELinux: Registering netfilter hooks\n");
7357 err = register_pernet_subsys(&selinux_net_ops);
7359 panic("SELinux: register_pernet_subsys: error %d\n", err);
7363 __initcall(selinux_nf_ip_init);
7364 #endif /* CONFIG_NETFILTER */