Merge tag 'usb-5.16-rc6' of git://git.kernel.org/pub/scm/linux/kernel/git/gregkh/usb
[linux-block.git] / security / selinux / hooks.c
1 // SPDX-License-Identifier: GPL-2.0-only
2 /*
3  *  NSA Security-Enhanced Linux (SELinux) security module
4  *
5  *  This file contains the SELinux hook function implementations.
6  *
7  *  Authors:  Stephen Smalley, <sds@tycho.nsa.gov>
8  *            Chris Vance, <cvance@nai.com>
9  *            Wayne Salamon, <wsalamon@nai.com>
10  *            James Morris <jmorris@redhat.com>
11  *
12  *  Copyright (C) 2001,2002 Networks Associates Technology, Inc.
13  *  Copyright (C) 2003-2008 Red Hat, Inc., James Morris <jmorris@redhat.com>
14  *                                         Eric Paris <eparis@redhat.com>
15  *  Copyright (C) 2004-2005 Trusted Computer Solutions, Inc.
16  *                          <dgoeddel@trustedcs.com>
17  *  Copyright (C) 2006, 2007, 2009 Hewlett-Packard Development Company, L.P.
18  *      Paul Moore <paul@paul-moore.com>
19  *  Copyright (C) 2007 Hitachi Software Engineering Co., Ltd.
20  *                     Yuichi Nakamura <ynakam@hitachisoft.jp>
21  *  Copyright (C) 2016 Mellanox Technologies
22  */
23
24 #include <linux/init.h>
25 #include <linux/kd.h>
26 #include <linux/kernel.h>
27 #include <linux/kernel_read_file.h>
28 #include <linux/tracehook.h>
29 #include <linux/errno.h>
30 #include <linux/sched/signal.h>
31 #include <linux/sched/task.h>
32 #include <linux/lsm_hooks.h>
33 #include <linux/xattr.h>
34 #include <linux/capability.h>
35 #include <linux/unistd.h>
36 #include <linux/mm.h>
37 #include <linux/mman.h>
38 #include <linux/slab.h>
39 #include <linux/pagemap.h>
40 #include <linux/proc_fs.h>
41 #include <linux/swap.h>
42 #include <linux/spinlock.h>
43 #include <linux/syscalls.h>
44 #include <linux/dcache.h>
45 #include <linux/file.h>
46 #include <linux/fdtable.h>
47 #include <linux/namei.h>
48 #include <linux/mount.h>
49 #include <linux/fs_context.h>
50 #include <linux/fs_parser.h>
51 #include <linux/netfilter_ipv4.h>
52 #include <linux/netfilter_ipv6.h>
53 #include <linux/tty.h>
54 #include <net/icmp.h>
55 #include <net/ip.h>             /* for local_port_range[] */
56 #include <net/tcp.h>            /* struct or_callable used in sock_rcv_skb */
57 #include <net/inet_connection_sock.h>
58 #include <net/net_namespace.h>
59 #include <net/netlabel.h>
60 #include <linux/uaccess.h>
61 #include <asm/ioctls.h>
62 #include <linux/atomic.h>
63 #include <linux/bitops.h>
64 #include <linux/interrupt.h>
65 #include <linux/netdevice.h>    /* for network interface checks */
66 #include <net/netlink.h>
67 #include <linux/tcp.h>
68 #include <linux/udp.h>
69 #include <linux/dccp.h>
70 #include <linux/sctp.h>
71 #include <net/sctp/structs.h>
72 #include <linux/quota.h>
73 #include <linux/un.h>           /* for Unix socket types */
74 #include <net/af_unix.h>        /* for Unix socket types */
75 #include <linux/parser.h>
76 #include <linux/nfs_mount.h>
77 #include <net/ipv6.h>
78 #include <linux/hugetlb.h>
79 #include <linux/personality.h>
80 #include <linux/audit.h>
81 #include <linux/string.h>
82 #include <linux/mutex.h>
83 #include <linux/posix-timers.h>
84 #include <linux/syslog.h>
85 #include <linux/user_namespace.h>
86 #include <linux/export.h>
87 #include <linux/msg.h>
88 #include <linux/shm.h>
89 #include <linux/bpf.h>
90 #include <linux/kernfs.h>
91 #include <linux/stringhash.h>   /* for hashlen_string() */
92 #include <uapi/linux/mount.h>
93 #include <linux/fsnotify.h>
94 #include <linux/fanotify.h>
95
96 #include "avc.h"
97 #include "objsec.h"
98 #include "netif.h"
99 #include "netnode.h"
100 #include "netport.h"
101 #include "ibpkey.h"
102 #include "xfrm.h"
103 #include "netlabel.h"
104 #include "audit.h"
105 #include "avc_ss.h"
106
107 struct selinux_state selinux_state;
108
109 /* SECMARK reference count */
110 static atomic_t selinux_secmark_refcount = ATOMIC_INIT(0);
111
112 #ifdef CONFIG_SECURITY_SELINUX_DEVELOP
113 static int selinux_enforcing_boot __initdata;
114
115 static int __init enforcing_setup(char *str)
116 {
117         unsigned long enforcing;
118         if (!kstrtoul(str, 0, &enforcing))
119                 selinux_enforcing_boot = enforcing ? 1 : 0;
120         return 1;
121 }
122 __setup("enforcing=", enforcing_setup);
123 #else
124 #define selinux_enforcing_boot 1
125 #endif
126
127 int selinux_enabled_boot __initdata = 1;
128 #ifdef CONFIG_SECURITY_SELINUX_BOOTPARAM
129 static int __init selinux_enabled_setup(char *str)
130 {
131         unsigned long enabled;
132         if (!kstrtoul(str, 0, &enabled))
133                 selinux_enabled_boot = enabled ? 1 : 0;
134         return 1;
135 }
136 __setup("selinux=", selinux_enabled_setup);
137 #endif
138
139 static unsigned int selinux_checkreqprot_boot =
140         CONFIG_SECURITY_SELINUX_CHECKREQPROT_VALUE;
141
142 static int __init checkreqprot_setup(char *str)
143 {
144         unsigned long checkreqprot;
145
146         if (!kstrtoul(str, 0, &checkreqprot)) {
147                 selinux_checkreqprot_boot = checkreqprot ? 1 : 0;
148                 if (checkreqprot)
149                         pr_warn("SELinux: checkreqprot set to 1 via kernel parameter.  This is deprecated and will be rejected in a future kernel release.\n");
150         }
151         return 1;
152 }
153 __setup("checkreqprot=", checkreqprot_setup);
154
155 /**
156  * selinux_secmark_enabled - Check to see if SECMARK is currently enabled
157  *
158  * Description:
159  * This function checks the SECMARK reference counter to see if any SECMARK
160  * targets are currently configured, if the reference counter is greater than
161  * zero SECMARK is considered to be enabled.  Returns true (1) if SECMARK is
162  * enabled, false (0) if SECMARK is disabled.  If the always_check_network
163  * policy capability is enabled, SECMARK is always considered enabled.
164  *
165  */
166 static int selinux_secmark_enabled(void)
167 {
168         return (selinux_policycap_alwaysnetwork() ||
169                 atomic_read(&selinux_secmark_refcount));
170 }
171
172 /**
173  * selinux_peerlbl_enabled - Check to see if peer labeling is currently enabled
174  *
175  * Description:
176  * This function checks if NetLabel or labeled IPSEC is enabled.  Returns true
177  * (1) if any are enabled or false (0) if neither are enabled.  If the
178  * always_check_network policy capability is enabled, peer labeling
179  * is always considered enabled.
180  *
181  */
182 static int selinux_peerlbl_enabled(void)
183 {
184         return (selinux_policycap_alwaysnetwork() ||
185                 netlbl_enabled() || selinux_xfrm_enabled());
186 }
187
188 static int selinux_netcache_avc_callback(u32 event)
189 {
190         if (event == AVC_CALLBACK_RESET) {
191                 sel_netif_flush();
192                 sel_netnode_flush();
193                 sel_netport_flush();
194                 synchronize_net();
195         }
196         return 0;
197 }
198
199 static int selinux_lsm_notifier_avc_callback(u32 event)
200 {
201         if (event == AVC_CALLBACK_RESET) {
202                 sel_ib_pkey_flush();
203                 call_blocking_lsm_notifier(LSM_POLICY_CHANGE, NULL);
204         }
205
206         return 0;
207 }
208
209 /*
210  * initialise the security for the init task
211  */
212 static void cred_init_security(void)
213 {
214         struct cred *cred = (struct cred *) current->real_cred;
215         struct task_security_struct *tsec;
216
217         tsec = selinux_cred(cred);
218         tsec->osid = tsec->sid = SECINITSID_KERNEL;
219 }
220
221 /*
222  * get the security ID of a set of credentials
223  */
224 static inline u32 cred_sid(const struct cred *cred)
225 {
226         const struct task_security_struct *tsec;
227
228         tsec = selinux_cred(cred);
229         return tsec->sid;
230 }
231
232 /*
233  * get the subjective security ID of a task
234  */
235 static inline u32 task_sid_subj(const struct task_struct *task)
236 {
237         u32 sid;
238
239         rcu_read_lock();
240         sid = cred_sid(rcu_dereference(task->cred));
241         rcu_read_unlock();
242         return sid;
243 }
244
245 /*
246  * get the objective security ID of a task
247  */
248 static inline u32 task_sid_obj(const struct task_struct *task)
249 {
250         u32 sid;
251
252         rcu_read_lock();
253         sid = cred_sid(__task_cred(task));
254         rcu_read_unlock();
255         return sid;
256 }
257
258 static int inode_doinit_with_dentry(struct inode *inode, struct dentry *opt_dentry);
259
260 /*
261  * Try reloading inode security labels that have been marked as invalid.  The
262  * @may_sleep parameter indicates when sleeping and thus reloading labels is
263  * allowed; when set to false, returns -ECHILD when the label is
264  * invalid.  The @dentry parameter should be set to a dentry of the inode.
265  */
266 static int __inode_security_revalidate(struct inode *inode,
267                                        struct dentry *dentry,
268                                        bool may_sleep)
269 {
270         struct inode_security_struct *isec = selinux_inode(inode);
271
272         might_sleep_if(may_sleep);
273
274         if (selinux_initialized(&selinux_state) &&
275             isec->initialized != LABEL_INITIALIZED) {
276                 if (!may_sleep)
277                         return -ECHILD;
278
279                 /*
280                  * Try reloading the inode security label.  This will fail if
281                  * @opt_dentry is NULL and no dentry for this inode can be
282                  * found; in that case, continue using the old label.
283                  */
284                 inode_doinit_with_dentry(inode, dentry);
285         }
286         return 0;
287 }
288
289 static struct inode_security_struct *inode_security_novalidate(struct inode *inode)
290 {
291         return selinux_inode(inode);
292 }
293
294 static struct inode_security_struct *inode_security_rcu(struct inode *inode, bool rcu)
295 {
296         int error;
297
298         error = __inode_security_revalidate(inode, NULL, !rcu);
299         if (error)
300                 return ERR_PTR(error);
301         return selinux_inode(inode);
302 }
303
304 /*
305  * Get the security label of an inode.
306  */
307 static struct inode_security_struct *inode_security(struct inode *inode)
308 {
309         __inode_security_revalidate(inode, NULL, true);
310         return selinux_inode(inode);
311 }
312
313 static struct inode_security_struct *backing_inode_security_novalidate(struct dentry *dentry)
314 {
315         struct inode *inode = d_backing_inode(dentry);
316
317         return selinux_inode(inode);
318 }
319
320 /*
321  * Get the security label of a dentry's backing inode.
322  */
323 static struct inode_security_struct *backing_inode_security(struct dentry *dentry)
324 {
325         struct inode *inode = d_backing_inode(dentry);
326
327         __inode_security_revalidate(inode, dentry, true);
328         return selinux_inode(inode);
329 }
330
331 static void inode_free_security(struct inode *inode)
332 {
333         struct inode_security_struct *isec = selinux_inode(inode);
334         struct superblock_security_struct *sbsec;
335
336         if (!isec)
337                 return;
338         sbsec = selinux_superblock(inode->i_sb);
339         /*
340          * As not all inode security structures are in a list, we check for
341          * empty list outside of the lock to make sure that we won't waste
342          * time taking a lock doing nothing.
343          *
344          * The list_del_init() function can be safely called more than once.
345          * It should not be possible for this function to be called with
346          * concurrent list_add(), but for better safety against future changes
347          * in the code, we use list_empty_careful() here.
348          */
349         if (!list_empty_careful(&isec->list)) {
350                 spin_lock(&sbsec->isec_lock);
351                 list_del_init(&isec->list);
352                 spin_unlock(&sbsec->isec_lock);
353         }
354 }
355
356 struct selinux_mnt_opts {
357         const char *fscontext, *context, *rootcontext, *defcontext;
358 };
359
360 static void selinux_free_mnt_opts(void *mnt_opts)
361 {
362         struct selinux_mnt_opts *opts = mnt_opts;
363         kfree(opts->fscontext);
364         kfree(opts->context);
365         kfree(opts->rootcontext);
366         kfree(opts->defcontext);
367         kfree(opts);
368 }
369
370 enum {
371         Opt_error = -1,
372         Opt_context = 0,
373         Opt_defcontext = 1,
374         Opt_fscontext = 2,
375         Opt_rootcontext = 3,
376         Opt_seclabel = 4,
377 };
378
379 #define A(s, has_arg) {#s, sizeof(#s) - 1, Opt_##s, has_arg}
380 static struct {
381         const char *name;
382         int len;
383         int opt;
384         bool has_arg;
385 } tokens[] = {
386         A(context, true),
387         A(fscontext, true),
388         A(defcontext, true),
389         A(rootcontext, true),
390         A(seclabel, false),
391 };
392 #undef A
393
394 static int match_opt_prefix(char *s, int l, char **arg)
395 {
396         int i;
397
398         for (i = 0; i < ARRAY_SIZE(tokens); i++) {
399                 size_t len = tokens[i].len;
400                 if (len > l || memcmp(s, tokens[i].name, len))
401                         continue;
402                 if (tokens[i].has_arg) {
403                         if (len == l || s[len] != '=')
404                                 continue;
405                         *arg = s + len + 1;
406                 } else if (len != l)
407                         continue;
408                 return tokens[i].opt;
409         }
410         return Opt_error;
411 }
412
413 #define SEL_MOUNT_FAIL_MSG "SELinux:  duplicate or incompatible mount options\n"
414
415 static int may_context_mount_sb_relabel(u32 sid,
416                         struct superblock_security_struct *sbsec,
417                         const struct cred *cred)
418 {
419         const struct task_security_struct *tsec = selinux_cred(cred);
420         int rc;
421
422         rc = avc_has_perm(&selinux_state,
423                           tsec->sid, sbsec->sid, SECCLASS_FILESYSTEM,
424                           FILESYSTEM__RELABELFROM, NULL);
425         if (rc)
426                 return rc;
427
428         rc = avc_has_perm(&selinux_state,
429                           tsec->sid, sid, SECCLASS_FILESYSTEM,
430                           FILESYSTEM__RELABELTO, NULL);
431         return rc;
432 }
433
434 static int may_context_mount_inode_relabel(u32 sid,
435                         struct superblock_security_struct *sbsec,
436                         const struct cred *cred)
437 {
438         const struct task_security_struct *tsec = selinux_cred(cred);
439         int rc;
440         rc = avc_has_perm(&selinux_state,
441                           tsec->sid, sbsec->sid, SECCLASS_FILESYSTEM,
442                           FILESYSTEM__RELABELFROM, NULL);
443         if (rc)
444                 return rc;
445
446         rc = avc_has_perm(&selinux_state,
447                           sid, sbsec->sid, SECCLASS_FILESYSTEM,
448                           FILESYSTEM__ASSOCIATE, NULL);
449         return rc;
450 }
451
452 static int selinux_is_genfs_special_handling(struct super_block *sb)
453 {
454         /* Special handling. Genfs but also in-core setxattr handler */
455         return  !strcmp(sb->s_type->name, "sysfs") ||
456                 !strcmp(sb->s_type->name, "pstore") ||
457                 !strcmp(sb->s_type->name, "debugfs") ||
458                 !strcmp(sb->s_type->name, "tracefs") ||
459                 !strcmp(sb->s_type->name, "rootfs") ||
460                 (selinux_policycap_cgroupseclabel() &&
461                  (!strcmp(sb->s_type->name, "cgroup") ||
462                   !strcmp(sb->s_type->name, "cgroup2")));
463 }
464
465 static int selinux_is_sblabel_mnt(struct super_block *sb)
466 {
467         struct superblock_security_struct *sbsec = selinux_superblock(sb);
468
469         /*
470          * IMPORTANT: Double-check logic in this function when adding a new
471          * SECURITY_FS_USE_* definition!
472          */
473         BUILD_BUG_ON(SECURITY_FS_USE_MAX != 7);
474
475         switch (sbsec->behavior) {
476         case SECURITY_FS_USE_XATTR:
477         case SECURITY_FS_USE_TRANS:
478         case SECURITY_FS_USE_TASK:
479         case SECURITY_FS_USE_NATIVE:
480                 return 1;
481
482         case SECURITY_FS_USE_GENFS:
483                 return selinux_is_genfs_special_handling(sb);
484
485         /* Never allow relabeling on context mounts */
486         case SECURITY_FS_USE_MNTPOINT:
487         case SECURITY_FS_USE_NONE:
488         default:
489                 return 0;
490         }
491 }
492
493 static int sb_check_xattr_support(struct super_block *sb)
494 {
495         struct superblock_security_struct *sbsec = sb->s_security;
496         struct dentry *root = sb->s_root;
497         struct inode *root_inode = d_backing_inode(root);
498         u32 sid;
499         int rc;
500
501         /*
502          * Make sure that the xattr handler exists and that no
503          * error other than -ENODATA is returned by getxattr on
504          * the root directory.  -ENODATA is ok, as this may be
505          * the first boot of the SELinux kernel before we have
506          * assigned xattr values to the filesystem.
507          */
508         if (!(root_inode->i_opflags & IOP_XATTR)) {
509                 pr_warn("SELinux: (dev %s, type %s) has no xattr support\n",
510                         sb->s_id, sb->s_type->name);
511                 goto fallback;
512         }
513
514         rc = __vfs_getxattr(root, root_inode, XATTR_NAME_SELINUX, NULL, 0);
515         if (rc < 0 && rc != -ENODATA) {
516                 if (rc == -EOPNOTSUPP) {
517                         pr_warn("SELinux: (dev %s, type %s) has no security xattr handler\n",
518                                 sb->s_id, sb->s_type->name);
519                         goto fallback;
520                 } else {
521                         pr_warn("SELinux: (dev %s, type %s) getxattr errno %d\n",
522                                 sb->s_id, sb->s_type->name, -rc);
523                         return rc;
524                 }
525         }
526         return 0;
527
528 fallback:
529         /* No xattr support - try to fallback to genfs if possible. */
530         rc = security_genfs_sid(&selinux_state, sb->s_type->name, "/",
531                                 SECCLASS_DIR, &sid);
532         if (rc)
533                 return -EOPNOTSUPP;
534
535         pr_warn("SELinux: (dev %s, type %s) falling back to genfs\n",
536                 sb->s_id, sb->s_type->name);
537         sbsec->behavior = SECURITY_FS_USE_GENFS;
538         sbsec->sid = sid;
539         return 0;
540 }
541
542 static int sb_finish_set_opts(struct super_block *sb)
543 {
544         struct superblock_security_struct *sbsec = selinux_superblock(sb);
545         struct dentry *root = sb->s_root;
546         struct inode *root_inode = d_backing_inode(root);
547         int rc = 0;
548
549         if (sbsec->behavior == SECURITY_FS_USE_XATTR) {
550                 rc = sb_check_xattr_support(sb);
551                 if (rc)
552                         return rc;
553         }
554
555         sbsec->flags |= SE_SBINITIALIZED;
556
557         /*
558          * Explicitly set or clear SBLABEL_MNT.  It's not sufficient to simply
559          * leave the flag untouched because sb_clone_mnt_opts might be handing
560          * us a superblock that needs the flag to be cleared.
561          */
562         if (selinux_is_sblabel_mnt(sb))
563                 sbsec->flags |= SBLABEL_MNT;
564         else
565                 sbsec->flags &= ~SBLABEL_MNT;
566
567         /* Initialize the root inode. */
568         rc = inode_doinit_with_dentry(root_inode, root);
569
570         /* Initialize any other inodes associated with the superblock, e.g.
571            inodes created prior to initial policy load or inodes created
572            during get_sb by a pseudo filesystem that directly
573            populates itself. */
574         spin_lock(&sbsec->isec_lock);
575         while (!list_empty(&sbsec->isec_head)) {
576                 struct inode_security_struct *isec =
577                                 list_first_entry(&sbsec->isec_head,
578                                            struct inode_security_struct, list);
579                 struct inode *inode = isec->inode;
580                 list_del_init(&isec->list);
581                 spin_unlock(&sbsec->isec_lock);
582                 inode = igrab(inode);
583                 if (inode) {
584                         if (!IS_PRIVATE(inode))
585                                 inode_doinit_with_dentry(inode, NULL);
586                         iput(inode);
587                 }
588                 spin_lock(&sbsec->isec_lock);
589         }
590         spin_unlock(&sbsec->isec_lock);
591         return rc;
592 }
593
594 static int bad_option(struct superblock_security_struct *sbsec, char flag,
595                       u32 old_sid, u32 new_sid)
596 {
597         char mnt_flags = sbsec->flags & SE_MNTMASK;
598
599         /* check if the old mount command had the same options */
600         if (sbsec->flags & SE_SBINITIALIZED)
601                 if (!(sbsec->flags & flag) ||
602                     (old_sid != new_sid))
603                         return 1;
604
605         /* check if we were passed the same options twice,
606          * aka someone passed context=a,context=b
607          */
608         if (!(sbsec->flags & SE_SBINITIALIZED))
609                 if (mnt_flags & flag)
610                         return 1;
611         return 0;
612 }
613
614 static int parse_sid(struct super_block *sb, const char *s, u32 *sid,
615                      gfp_t gfp)
616 {
617         int rc = security_context_str_to_sid(&selinux_state, s,
618                                              sid, gfp);
619         if (rc)
620                 pr_warn("SELinux: security_context_str_to_sid"
621                        "(%s) failed for (dev %s, type %s) errno=%d\n",
622                        s, sb->s_id, sb->s_type->name, rc);
623         return rc;
624 }
625
626 /*
627  * Allow filesystems with binary mount data to explicitly set mount point
628  * labeling information.
629  */
630 static int selinux_set_mnt_opts(struct super_block *sb,
631                                 void *mnt_opts,
632                                 unsigned long kern_flags,
633                                 unsigned long *set_kern_flags)
634 {
635         const struct cred *cred = current_cred();
636         struct superblock_security_struct *sbsec = selinux_superblock(sb);
637         struct dentry *root = sb->s_root;
638         struct selinux_mnt_opts *opts = mnt_opts;
639         struct inode_security_struct *root_isec;
640         u32 fscontext_sid = 0, context_sid = 0, rootcontext_sid = 0;
641         u32 defcontext_sid = 0;
642         int rc = 0;
643
644         mutex_lock(&sbsec->lock);
645
646         if (!selinux_initialized(&selinux_state)) {
647                 if (!opts) {
648                         /* Defer initialization until selinux_complete_init,
649                            after the initial policy is loaded and the security
650                            server is ready to handle calls. */
651                         goto out;
652                 }
653                 rc = -EINVAL;
654                 pr_warn("SELinux: Unable to set superblock options "
655                         "before the security server is initialized\n");
656                 goto out;
657         }
658         if (kern_flags && !set_kern_flags) {
659                 /* Specifying internal flags without providing a place to
660                  * place the results is not allowed */
661                 rc = -EINVAL;
662                 goto out;
663         }
664
665         /*
666          * Binary mount data FS will come through this function twice.  Once
667          * from an explicit call and once from the generic calls from the vfs.
668          * Since the generic VFS calls will not contain any security mount data
669          * we need to skip the double mount verification.
670          *
671          * This does open a hole in which we will not notice if the first
672          * mount using this sb set explict options and a second mount using
673          * this sb does not set any security options.  (The first options
674          * will be used for both mounts)
675          */
676         if ((sbsec->flags & SE_SBINITIALIZED) && (sb->s_type->fs_flags & FS_BINARY_MOUNTDATA)
677             && !opts)
678                 goto out;
679
680         root_isec = backing_inode_security_novalidate(root);
681
682         /*
683          * parse the mount options, check if they are valid sids.
684          * also check if someone is trying to mount the same sb more
685          * than once with different security options.
686          */
687         if (opts) {
688                 if (opts->fscontext) {
689                         rc = parse_sid(sb, opts->fscontext, &fscontext_sid,
690                                         GFP_KERNEL);
691                         if (rc)
692                                 goto out;
693                         if (bad_option(sbsec, FSCONTEXT_MNT, sbsec->sid,
694                                         fscontext_sid))
695                                 goto out_double_mount;
696                         sbsec->flags |= FSCONTEXT_MNT;
697                 }
698                 if (opts->context) {
699                         rc = parse_sid(sb, opts->context, &context_sid,
700                                         GFP_KERNEL);
701                         if (rc)
702                                 goto out;
703                         if (bad_option(sbsec, CONTEXT_MNT, sbsec->mntpoint_sid,
704                                         context_sid))
705                                 goto out_double_mount;
706                         sbsec->flags |= CONTEXT_MNT;
707                 }
708                 if (opts->rootcontext) {
709                         rc = parse_sid(sb, opts->rootcontext, &rootcontext_sid,
710                                         GFP_KERNEL);
711                         if (rc)
712                                 goto out;
713                         if (bad_option(sbsec, ROOTCONTEXT_MNT, root_isec->sid,
714                                         rootcontext_sid))
715                                 goto out_double_mount;
716                         sbsec->flags |= ROOTCONTEXT_MNT;
717                 }
718                 if (opts->defcontext) {
719                         rc = parse_sid(sb, opts->defcontext, &defcontext_sid,
720                                         GFP_KERNEL);
721                         if (rc)
722                                 goto out;
723                         if (bad_option(sbsec, DEFCONTEXT_MNT, sbsec->def_sid,
724                                         defcontext_sid))
725                                 goto out_double_mount;
726                         sbsec->flags |= DEFCONTEXT_MNT;
727                 }
728         }
729
730         if (sbsec->flags & SE_SBINITIALIZED) {
731                 /* previously mounted with options, but not on this attempt? */
732                 if ((sbsec->flags & SE_MNTMASK) && !opts)
733                         goto out_double_mount;
734                 rc = 0;
735                 goto out;
736         }
737
738         if (strcmp(sb->s_type->name, "proc") == 0)
739                 sbsec->flags |= SE_SBPROC | SE_SBGENFS;
740
741         if (!strcmp(sb->s_type->name, "debugfs") ||
742             !strcmp(sb->s_type->name, "tracefs") ||
743             !strcmp(sb->s_type->name, "binder") ||
744             !strcmp(sb->s_type->name, "bpf") ||
745             !strcmp(sb->s_type->name, "pstore") ||
746             !strcmp(sb->s_type->name, "securityfs"))
747                 sbsec->flags |= SE_SBGENFS;
748
749         if (!strcmp(sb->s_type->name, "sysfs") ||
750             !strcmp(sb->s_type->name, "cgroup") ||
751             !strcmp(sb->s_type->name, "cgroup2"))
752                 sbsec->flags |= SE_SBGENFS | SE_SBGENFS_XATTR;
753
754         if (!sbsec->behavior) {
755                 /*
756                  * Determine the labeling behavior to use for this
757                  * filesystem type.
758                  */
759                 rc = security_fs_use(&selinux_state, sb);
760                 if (rc) {
761                         pr_warn("%s: security_fs_use(%s) returned %d\n",
762                                         __func__, sb->s_type->name, rc);
763                         goto out;
764                 }
765         }
766
767         /*
768          * If this is a user namespace mount and the filesystem type is not
769          * explicitly whitelisted, then no contexts are allowed on the command
770          * line and security labels must be ignored.
771          */
772         if (sb->s_user_ns != &init_user_ns &&
773             strcmp(sb->s_type->name, "tmpfs") &&
774             strcmp(sb->s_type->name, "ramfs") &&
775             strcmp(sb->s_type->name, "devpts") &&
776             strcmp(sb->s_type->name, "overlay")) {
777                 if (context_sid || fscontext_sid || rootcontext_sid ||
778                     defcontext_sid) {
779                         rc = -EACCES;
780                         goto out;
781                 }
782                 if (sbsec->behavior == SECURITY_FS_USE_XATTR) {
783                         sbsec->behavior = SECURITY_FS_USE_MNTPOINT;
784                         rc = security_transition_sid(&selinux_state,
785                                                      current_sid(),
786                                                      current_sid(),
787                                                      SECCLASS_FILE, NULL,
788                                                      &sbsec->mntpoint_sid);
789                         if (rc)
790                                 goto out;
791                 }
792                 goto out_set_opts;
793         }
794
795         /* sets the context of the superblock for the fs being mounted. */
796         if (fscontext_sid) {
797                 rc = may_context_mount_sb_relabel(fscontext_sid, sbsec, cred);
798                 if (rc)
799                         goto out;
800
801                 sbsec->sid = fscontext_sid;
802         }
803
804         /*
805          * Switch to using mount point labeling behavior.
806          * sets the label used on all file below the mountpoint, and will set
807          * the superblock context if not already set.
808          */
809         if (kern_flags & SECURITY_LSM_NATIVE_LABELS && !context_sid) {
810                 sbsec->behavior = SECURITY_FS_USE_NATIVE;
811                 *set_kern_flags |= SECURITY_LSM_NATIVE_LABELS;
812         }
813
814         if (context_sid) {
815                 if (!fscontext_sid) {
816                         rc = may_context_mount_sb_relabel(context_sid, sbsec,
817                                                           cred);
818                         if (rc)
819                                 goto out;
820                         sbsec->sid = context_sid;
821                 } else {
822                         rc = may_context_mount_inode_relabel(context_sid, sbsec,
823                                                              cred);
824                         if (rc)
825                                 goto out;
826                 }
827                 if (!rootcontext_sid)
828                         rootcontext_sid = context_sid;
829
830                 sbsec->mntpoint_sid = context_sid;
831                 sbsec->behavior = SECURITY_FS_USE_MNTPOINT;
832         }
833
834         if (rootcontext_sid) {
835                 rc = may_context_mount_inode_relabel(rootcontext_sid, sbsec,
836                                                      cred);
837                 if (rc)
838                         goto out;
839
840                 root_isec->sid = rootcontext_sid;
841                 root_isec->initialized = LABEL_INITIALIZED;
842         }
843
844         if (defcontext_sid) {
845                 if (sbsec->behavior != SECURITY_FS_USE_XATTR &&
846                         sbsec->behavior != SECURITY_FS_USE_NATIVE) {
847                         rc = -EINVAL;
848                         pr_warn("SELinux: defcontext option is "
849                                "invalid for this filesystem type\n");
850                         goto out;
851                 }
852
853                 if (defcontext_sid != sbsec->def_sid) {
854                         rc = may_context_mount_inode_relabel(defcontext_sid,
855                                                              sbsec, cred);
856                         if (rc)
857                                 goto out;
858                 }
859
860                 sbsec->def_sid = defcontext_sid;
861         }
862
863 out_set_opts:
864         rc = sb_finish_set_opts(sb);
865 out:
866         mutex_unlock(&sbsec->lock);
867         return rc;
868 out_double_mount:
869         rc = -EINVAL;
870         pr_warn("SELinux: mount invalid.  Same superblock, different "
871                "security settings for (dev %s, type %s)\n", sb->s_id,
872                sb->s_type->name);
873         goto out;
874 }
875
876 static int selinux_cmp_sb_context(const struct super_block *oldsb,
877                                     const struct super_block *newsb)
878 {
879         struct superblock_security_struct *old = selinux_superblock(oldsb);
880         struct superblock_security_struct *new = selinux_superblock(newsb);
881         char oldflags = old->flags & SE_MNTMASK;
882         char newflags = new->flags & SE_MNTMASK;
883
884         if (oldflags != newflags)
885                 goto mismatch;
886         if ((oldflags & FSCONTEXT_MNT) && old->sid != new->sid)
887                 goto mismatch;
888         if ((oldflags & CONTEXT_MNT) && old->mntpoint_sid != new->mntpoint_sid)
889                 goto mismatch;
890         if ((oldflags & DEFCONTEXT_MNT) && old->def_sid != new->def_sid)
891                 goto mismatch;
892         if (oldflags & ROOTCONTEXT_MNT) {
893                 struct inode_security_struct *oldroot = backing_inode_security(oldsb->s_root);
894                 struct inode_security_struct *newroot = backing_inode_security(newsb->s_root);
895                 if (oldroot->sid != newroot->sid)
896                         goto mismatch;
897         }
898         return 0;
899 mismatch:
900         pr_warn("SELinux: mount invalid.  Same superblock, "
901                             "different security settings for (dev %s, "
902                             "type %s)\n", newsb->s_id, newsb->s_type->name);
903         return -EBUSY;
904 }
905
906 static int selinux_sb_clone_mnt_opts(const struct super_block *oldsb,
907                                         struct super_block *newsb,
908                                         unsigned long kern_flags,
909                                         unsigned long *set_kern_flags)
910 {
911         int rc = 0;
912         const struct superblock_security_struct *oldsbsec =
913                                                 selinux_superblock(oldsb);
914         struct superblock_security_struct *newsbsec = selinux_superblock(newsb);
915
916         int set_fscontext =     (oldsbsec->flags & FSCONTEXT_MNT);
917         int set_context =       (oldsbsec->flags & CONTEXT_MNT);
918         int set_rootcontext =   (oldsbsec->flags & ROOTCONTEXT_MNT);
919
920         /*
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
923          */
924         if (!selinux_initialized(&selinux_state))
925                 return 0;
926
927         /*
928          * Specifying internal flags without providing a place to
929          * place the results is not allowed.
930          */
931         if (kern_flags && !set_kern_flags)
932                 return -EINVAL;
933
934         /* how can we clone if the old one wasn't set up?? */
935         BUG_ON(!(oldsbsec->flags & SE_SBINITIALIZED));
936
937         /* if fs is reusing a sb, make sure that the contexts match */
938         if (newsbsec->flags & SE_SBINITIALIZED) {
939                 if ((kern_flags & SECURITY_LSM_NATIVE_LABELS) && !set_context)
940                         *set_kern_flags |= SECURITY_LSM_NATIVE_LABELS;
941                 return selinux_cmp_sb_context(oldsb, newsb);
942         }
943
944         mutex_lock(&newsbsec->lock);
945
946         newsbsec->flags = oldsbsec->flags;
947
948         newsbsec->sid = oldsbsec->sid;
949         newsbsec->def_sid = oldsbsec->def_sid;
950         newsbsec->behavior = oldsbsec->behavior;
951
952         if (newsbsec->behavior == SECURITY_FS_USE_NATIVE &&
953                 !(kern_flags & SECURITY_LSM_NATIVE_LABELS) && !set_context) {
954                 rc = security_fs_use(&selinux_state, newsb);
955                 if (rc)
956                         goto out;
957         }
958
959         if (kern_flags & SECURITY_LSM_NATIVE_LABELS && !set_context) {
960                 newsbsec->behavior = SECURITY_FS_USE_NATIVE;
961                 *set_kern_flags |= SECURITY_LSM_NATIVE_LABELS;
962         }
963
964         if (set_context) {
965                 u32 sid = oldsbsec->mntpoint_sid;
966
967                 if (!set_fscontext)
968                         newsbsec->sid = sid;
969                 if (!set_rootcontext) {
970                         struct inode_security_struct *newisec = backing_inode_security(newsb->s_root);
971                         newisec->sid = sid;
972                 }
973                 newsbsec->mntpoint_sid = sid;
974         }
975         if (set_rootcontext) {
976                 const struct inode_security_struct *oldisec = backing_inode_security(oldsb->s_root);
977                 struct inode_security_struct *newisec = backing_inode_security(newsb->s_root);
978
979                 newisec->sid = oldisec->sid;
980         }
981
982         sb_finish_set_opts(newsb);
983 out:
984         mutex_unlock(&newsbsec->lock);
985         return rc;
986 }
987
988 static int selinux_add_opt(int token, const char *s, void **mnt_opts)
989 {
990         struct selinux_mnt_opts *opts = *mnt_opts;
991
992         if (token == Opt_seclabel)      /* eaten and completely ignored */
993                 return 0;
994
995         if (!opts) {
996                 opts = kzalloc(sizeof(struct selinux_mnt_opts), GFP_KERNEL);
997                 if (!opts)
998                         return -ENOMEM;
999                 *mnt_opts = opts;
1000         }
1001         if (!s)
1002                 return -ENOMEM;
1003         switch (token) {
1004         case Opt_context:
1005                 if (opts->context || opts->defcontext)
1006                         goto Einval;
1007                 opts->context = s;
1008                 break;
1009         case Opt_fscontext:
1010                 if (opts->fscontext)
1011                         goto Einval;
1012                 opts->fscontext = s;
1013                 break;
1014         case Opt_rootcontext:
1015                 if (opts->rootcontext)
1016                         goto Einval;
1017                 opts->rootcontext = s;
1018                 break;
1019         case Opt_defcontext:
1020                 if (opts->context || opts->defcontext)
1021                         goto Einval;
1022                 opts->defcontext = s;
1023                 break;
1024         }
1025         return 0;
1026 Einval:
1027         pr_warn(SEL_MOUNT_FAIL_MSG);
1028         return -EINVAL;
1029 }
1030
1031 static int selinux_add_mnt_opt(const char *option, const char *val, int len,
1032                                void **mnt_opts)
1033 {
1034         int token = Opt_error;
1035         int rc, i;
1036
1037         for (i = 0; i < ARRAY_SIZE(tokens); i++) {
1038                 if (strcmp(option, tokens[i].name) == 0) {
1039                         token = tokens[i].opt;
1040                         break;
1041                 }
1042         }
1043
1044         if (token == Opt_error)
1045                 return -EINVAL;
1046
1047         if (token != Opt_seclabel) {
1048                 val = kmemdup_nul(val, len, GFP_KERNEL);
1049                 if (!val) {
1050                         rc = -ENOMEM;
1051                         goto free_opt;
1052                 }
1053         }
1054         rc = selinux_add_opt(token, val, mnt_opts);
1055         if (unlikely(rc)) {
1056                 kfree(val);
1057                 goto free_opt;
1058         }
1059         return rc;
1060
1061 free_opt:
1062         if (*mnt_opts) {
1063                 selinux_free_mnt_opts(*mnt_opts);
1064                 *mnt_opts = NULL;
1065         }
1066         return rc;
1067 }
1068
1069 static int show_sid(struct seq_file *m, u32 sid)
1070 {
1071         char *context = NULL;
1072         u32 len;
1073         int rc;
1074
1075         rc = security_sid_to_context(&selinux_state, sid,
1076                                              &context, &len);
1077         if (!rc) {
1078                 bool has_comma = context && strchr(context, ',');
1079
1080                 seq_putc(m, '=');
1081                 if (has_comma)
1082                         seq_putc(m, '\"');
1083                 seq_escape(m, context, "\"\n\\");
1084                 if (has_comma)
1085                         seq_putc(m, '\"');
1086         }
1087         kfree(context);
1088         return rc;
1089 }
1090
1091 static int selinux_sb_show_options(struct seq_file *m, struct super_block *sb)
1092 {
1093         struct superblock_security_struct *sbsec = selinux_superblock(sb);
1094         int rc;
1095
1096         if (!(sbsec->flags & SE_SBINITIALIZED))
1097                 return 0;
1098
1099         if (!selinux_initialized(&selinux_state))
1100                 return 0;
1101
1102         if (sbsec->flags & FSCONTEXT_MNT) {
1103                 seq_putc(m, ',');
1104                 seq_puts(m, FSCONTEXT_STR);
1105                 rc = show_sid(m, sbsec->sid);
1106                 if (rc)
1107                         return rc;
1108         }
1109         if (sbsec->flags & CONTEXT_MNT) {
1110                 seq_putc(m, ',');
1111                 seq_puts(m, CONTEXT_STR);
1112                 rc = show_sid(m, sbsec->mntpoint_sid);
1113                 if (rc)
1114                         return rc;
1115         }
1116         if (sbsec->flags & DEFCONTEXT_MNT) {
1117                 seq_putc(m, ',');
1118                 seq_puts(m, DEFCONTEXT_STR);
1119                 rc = show_sid(m, sbsec->def_sid);
1120                 if (rc)
1121                         return rc;
1122         }
1123         if (sbsec->flags & ROOTCONTEXT_MNT) {
1124                 struct dentry *root = sb->s_root;
1125                 struct inode_security_struct *isec = backing_inode_security(root);
1126                 seq_putc(m, ',');
1127                 seq_puts(m, ROOTCONTEXT_STR);
1128                 rc = show_sid(m, isec->sid);
1129                 if (rc)
1130                         return rc;
1131         }
1132         if (sbsec->flags & SBLABEL_MNT) {
1133                 seq_putc(m, ',');
1134                 seq_puts(m, SECLABEL_STR);
1135         }
1136         return 0;
1137 }
1138
1139 static inline u16 inode_mode_to_security_class(umode_t mode)
1140 {
1141         switch (mode & S_IFMT) {
1142         case S_IFSOCK:
1143                 return SECCLASS_SOCK_FILE;
1144         case S_IFLNK:
1145                 return SECCLASS_LNK_FILE;
1146         case S_IFREG:
1147                 return SECCLASS_FILE;
1148         case S_IFBLK:
1149                 return SECCLASS_BLK_FILE;
1150         case S_IFDIR:
1151                 return SECCLASS_DIR;
1152         case S_IFCHR:
1153                 return SECCLASS_CHR_FILE;
1154         case S_IFIFO:
1155                 return SECCLASS_FIFO_FILE;
1156
1157         }
1158
1159         return SECCLASS_FILE;
1160 }
1161
1162 static inline int default_protocol_stream(int protocol)
1163 {
1164         return (protocol == IPPROTO_IP || protocol == IPPROTO_TCP ||
1165                 protocol == IPPROTO_MPTCP);
1166 }
1167
1168 static inline int default_protocol_dgram(int protocol)
1169 {
1170         return (protocol == IPPROTO_IP || protocol == IPPROTO_UDP);
1171 }
1172
1173 static inline u16 socket_type_to_security_class(int family, int type, int protocol)
1174 {
1175         int extsockclass = selinux_policycap_extsockclass();
1176
1177         switch (family) {
1178         case PF_UNIX:
1179                 switch (type) {
1180                 case SOCK_STREAM:
1181                 case SOCK_SEQPACKET:
1182                         return SECCLASS_UNIX_STREAM_SOCKET;
1183                 case SOCK_DGRAM:
1184                 case SOCK_RAW:
1185                         return SECCLASS_UNIX_DGRAM_SOCKET;
1186                 }
1187                 break;
1188         case PF_INET:
1189         case PF_INET6:
1190                 switch (type) {
1191                 case SOCK_STREAM:
1192                 case SOCK_SEQPACKET:
1193                         if (default_protocol_stream(protocol))
1194                                 return SECCLASS_TCP_SOCKET;
1195                         else if (extsockclass && protocol == IPPROTO_SCTP)
1196                                 return SECCLASS_SCTP_SOCKET;
1197                         else
1198                                 return SECCLASS_RAWIP_SOCKET;
1199                 case SOCK_DGRAM:
1200                         if (default_protocol_dgram(protocol))
1201                                 return SECCLASS_UDP_SOCKET;
1202                         else if (extsockclass && (protocol == IPPROTO_ICMP ||
1203                                                   protocol == IPPROTO_ICMPV6))
1204                                 return SECCLASS_ICMP_SOCKET;
1205                         else
1206                                 return SECCLASS_RAWIP_SOCKET;
1207                 case SOCK_DCCP:
1208                         return SECCLASS_DCCP_SOCKET;
1209                 default:
1210                         return SECCLASS_RAWIP_SOCKET;
1211                 }
1212                 break;
1213         case PF_NETLINK:
1214                 switch (protocol) {
1215                 case NETLINK_ROUTE:
1216                         return SECCLASS_NETLINK_ROUTE_SOCKET;
1217                 case NETLINK_SOCK_DIAG:
1218                         return SECCLASS_NETLINK_TCPDIAG_SOCKET;
1219                 case NETLINK_NFLOG:
1220                         return SECCLASS_NETLINK_NFLOG_SOCKET;
1221                 case NETLINK_XFRM:
1222                         return SECCLASS_NETLINK_XFRM_SOCKET;
1223                 case NETLINK_SELINUX:
1224                         return SECCLASS_NETLINK_SELINUX_SOCKET;
1225                 case NETLINK_ISCSI:
1226                         return SECCLASS_NETLINK_ISCSI_SOCKET;
1227                 case NETLINK_AUDIT:
1228                         return SECCLASS_NETLINK_AUDIT_SOCKET;
1229                 case NETLINK_FIB_LOOKUP:
1230                         return SECCLASS_NETLINK_FIB_LOOKUP_SOCKET;
1231                 case NETLINK_CONNECTOR:
1232                         return SECCLASS_NETLINK_CONNECTOR_SOCKET;
1233                 case NETLINK_NETFILTER:
1234                         return SECCLASS_NETLINK_NETFILTER_SOCKET;
1235                 case NETLINK_DNRTMSG:
1236                         return SECCLASS_NETLINK_DNRT_SOCKET;
1237                 case NETLINK_KOBJECT_UEVENT:
1238                         return SECCLASS_NETLINK_KOBJECT_UEVENT_SOCKET;
1239                 case NETLINK_GENERIC:
1240                         return SECCLASS_NETLINK_GENERIC_SOCKET;
1241                 case NETLINK_SCSITRANSPORT:
1242                         return SECCLASS_NETLINK_SCSITRANSPORT_SOCKET;
1243                 case NETLINK_RDMA:
1244                         return SECCLASS_NETLINK_RDMA_SOCKET;
1245                 case NETLINK_CRYPTO:
1246                         return SECCLASS_NETLINK_CRYPTO_SOCKET;
1247                 default:
1248                         return SECCLASS_NETLINK_SOCKET;
1249                 }
1250         case PF_PACKET:
1251                 return SECCLASS_PACKET_SOCKET;
1252         case PF_KEY:
1253                 return SECCLASS_KEY_SOCKET;
1254         case PF_APPLETALK:
1255                 return SECCLASS_APPLETALK_SOCKET;
1256         }
1257
1258         if (extsockclass) {
1259                 switch (family) {
1260                 case PF_AX25:
1261                         return SECCLASS_AX25_SOCKET;
1262                 case PF_IPX:
1263                         return SECCLASS_IPX_SOCKET;
1264                 case PF_NETROM:
1265                         return SECCLASS_NETROM_SOCKET;
1266                 case PF_ATMPVC:
1267                         return SECCLASS_ATMPVC_SOCKET;
1268                 case PF_X25:
1269                         return SECCLASS_X25_SOCKET;
1270                 case PF_ROSE:
1271                         return SECCLASS_ROSE_SOCKET;
1272                 case PF_DECnet:
1273                         return SECCLASS_DECNET_SOCKET;
1274                 case PF_ATMSVC:
1275                         return SECCLASS_ATMSVC_SOCKET;
1276                 case PF_RDS:
1277                         return SECCLASS_RDS_SOCKET;
1278                 case PF_IRDA:
1279                         return SECCLASS_IRDA_SOCKET;
1280                 case PF_PPPOX:
1281                         return SECCLASS_PPPOX_SOCKET;
1282                 case PF_LLC:
1283                         return SECCLASS_LLC_SOCKET;
1284                 case PF_CAN:
1285                         return SECCLASS_CAN_SOCKET;
1286                 case PF_TIPC:
1287                         return SECCLASS_TIPC_SOCKET;
1288                 case PF_BLUETOOTH:
1289                         return SECCLASS_BLUETOOTH_SOCKET;
1290                 case PF_IUCV:
1291                         return SECCLASS_IUCV_SOCKET;
1292                 case PF_RXRPC:
1293                         return SECCLASS_RXRPC_SOCKET;
1294                 case PF_ISDN:
1295                         return SECCLASS_ISDN_SOCKET;
1296                 case PF_PHONET:
1297                         return SECCLASS_PHONET_SOCKET;
1298                 case PF_IEEE802154:
1299                         return SECCLASS_IEEE802154_SOCKET;
1300                 case PF_CAIF:
1301                         return SECCLASS_CAIF_SOCKET;
1302                 case PF_ALG:
1303                         return SECCLASS_ALG_SOCKET;
1304                 case PF_NFC:
1305                         return SECCLASS_NFC_SOCKET;
1306                 case PF_VSOCK:
1307                         return SECCLASS_VSOCK_SOCKET;
1308                 case PF_KCM:
1309                         return SECCLASS_KCM_SOCKET;
1310                 case PF_QIPCRTR:
1311                         return SECCLASS_QIPCRTR_SOCKET;
1312                 case PF_SMC:
1313                         return SECCLASS_SMC_SOCKET;
1314                 case PF_XDP:
1315                         return SECCLASS_XDP_SOCKET;
1316                 case PF_MCTP:
1317                         return SECCLASS_MCTP_SOCKET;
1318 #if PF_MAX > 46
1319 #error New address family defined, please update this function.
1320 #endif
1321                 }
1322         }
1323
1324         return SECCLASS_SOCKET;
1325 }
1326
1327 static int selinux_genfs_get_sid(struct dentry *dentry,
1328                                  u16 tclass,
1329                                  u16 flags,
1330                                  u32 *sid)
1331 {
1332         int rc;
1333         struct super_block *sb = dentry->d_sb;
1334         char *buffer, *path;
1335
1336         buffer = (char *)__get_free_page(GFP_KERNEL);
1337         if (!buffer)
1338                 return -ENOMEM;
1339
1340         path = dentry_path_raw(dentry, buffer, PAGE_SIZE);
1341         if (IS_ERR(path))
1342                 rc = PTR_ERR(path);
1343         else {
1344                 if (flags & SE_SBPROC) {
1345                         /* each process gets a /proc/PID/ entry. Strip off the
1346                          * PID part to get a valid selinux labeling.
1347                          * e.g. /proc/1/net/rpc/nfs -> /net/rpc/nfs */
1348                         while (path[1] >= '0' && path[1] <= '9') {
1349                                 path[1] = '/';
1350                                 path++;
1351                         }
1352                 }
1353                 rc = security_genfs_sid(&selinux_state, sb->s_type->name,
1354                                         path, tclass, sid);
1355                 if (rc == -ENOENT) {
1356                         /* No match in policy, mark as unlabeled. */
1357                         *sid = SECINITSID_UNLABELED;
1358                         rc = 0;
1359                 }
1360         }
1361         free_page((unsigned long)buffer);
1362         return rc;
1363 }
1364
1365 static int inode_doinit_use_xattr(struct inode *inode, struct dentry *dentry,
1366                                   u32 def_sid, u32 *sid)
1367 {
1368 #define INITCONTEXTLEN 255
1369         char *context;
1370         unsigned int len;
1371         int rc;
1372
1373         len = INITCONTEXTLEN;
1374         context = kmalloc(len + 1, GFP_NOFS);
1375         if (!context)
1376                 return -ENOMEM;
1377
1378         context[len] = '\0';
1379         rc = __vfs_getxattr(dentry, inode, XATTR_NAME_SELINUX, context, len);
1380         if (rc == -ERANGE) {
1381                 kfree(context);
1382
1383                 /* Need a larger buffer.  Query for the right size. */
1384                 rc = __vfs_getxattr(dentry, inode, XATTR_NAME_SELINUX, NULL, 0);
1385                 if (rc < 0)
1386                         return rc;
1387
1388                 len = rc;
1389                 context = kmalloc(len + 1, GFP_NOFS);
1390                 if (!context)
1391                         return -ENOMEM;
1392
1393                 context[len] = '\0';
1394                 rc = __vfs_getxattr(dentry, inode, XATTR_NAME_SELINUX,
1395                                     context, len);
1396         }
1397         if (rc < 0) {
1398                 kfree(context);
1399                 if (rc != -ENODATA) {
1400                         pr_warn("SELinux: %s:  getxattr returned %d for dev=%s ino=%ld\n",
1401                                 __func__, -rc, inode->i_sb->s_id, inode->i_ino);
1402                         return rc;
1403                 }
1404                 *sid = def_sid;
1405                 return 0;
1406         }
1407
1408         rc = security_context_to_sid_default(&selinux_state, context, rc, sid,
1409                                              def_sid, GFP_NOFS);
1410         if (rc) {
1411                 char *dev = inode->i_sb->s_id;
1412                 unsigned long ino = inode->i_ino;
1413
1414                 if (rc == -EINVAL) {
1415                         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",
1416                                               ino, dev, context);
1417                 } else {
1418                         pr_warn("SELinux: %s:  context_to_sid(%s) returned %d for dev=%s ino=%ld\n",
1419                                 __func__, context, -rc, dev, ino);
1420                 }
1421         }
1422         kfree(context);
1423         return 0;
1424 }
1425
1426 /* The inode's security attributes must be initialized before first use. */
1427 static int inode_doinit_with_dentry(struct inode *inode, struct dentry *opt_dentry)
1428 {
1429         struct superblock_security_struct *sbsec = NULL;
1430         struct inode_security_struct *isec = selinux_inode(inode);
1431         u32 task_sid, sid = 0;
1432         u16 sclass;
1433         struct dentry *dentry;
1434         int rc = 0;
1435
1436         if (isec->initialized == LABEL_INITIALIZED)
1437                 return 0;
1438
1439         spin_lock(&isec->lock);
1440         if (isec->initialized == LABEL_INITIALIZED)
1441                 goto out_unlock;
1442
1443         if (isec->sclass == SECCLASS_FILE)
1444                 isec->sclass = inode_mode_to_security_class(inode->i_mode);
1445
1446         sbsec = selinux_superblock(inode->i_sb);
1447         if (!(sbsec->flags & SE_SBINITIALIZED)) {
1448                 /* Defer initialization until selinux_complete_init,
1449                    after the initial policy is loaded and the security
1450                    server is ready to handle calls. */
1451                 spin_lock(&sbsec->isec_lock);
1452                 if (list_empty(&isec->list))
1453                         list_add(&isec->list, &sbsec->isec_head);
1454                 spin_unlock(&sbsec->isec_lock);
1455                 goto out_unlock;
1456         }
1457
1458         sclass = isec->sclass;
1459         task_sid = isec->task_sid;
1460         sid = isec->sid;
1461         isec->initialized = LABEL_PENDING;
1462         spin_unlock(&isec->lock);
1463
1464         switch (sbsec->behavior) {
1465         case SECURITY_FS_USE_NATIVE:
1466                 break;
1467         case SECURITY_FS_USE_XATTR:
1468                 if (!(inode->i_opflags & IOP_XATTR)) {
1469                         sid = sbsec->def_sid;
1470                         break;
1471                 }
1472                 /* Need a dentry, since the xattr API requires one.
1473                    Life would be simpler if we could just pass the inode. */
1474                 if (opt_dentry) {
1475                         /* Called from d_instantiate or d_splice_alias. */
1476                         dentry = dget(opt_dentry);
1477                 } else {
1478                         /*
1479                          * Called from selinux_complete_init, try to find a dentry.
1480                          * Some filesystems really want a connected one, so try
1481                          * that first.  We could split SECURITY_FS_USE_XATTR in
1482                          * two, depending upon that...
1483                          */
1484                         dentry = d_find_alias(inode);
1485                         if (!dentry)
1486                                 dentry = d_find_any_alias(inode);
1487                 }
1488                 if (!dentry) {
1489                         /*
1490                          * this is can be hit on boot when a file is accessed
1491                          * before the policy is loaded.  When we load policy we
1492                          * may find inodes that have no dentry on the
1493                          * sbsec->isec_head list.  No reason to complain as these
1494                          * will get fixed up the next time we go through
1495                          * inode_doinit with a dentry, before these inodes could
1496                          * be used again by userspace.
1497                          */
1498                         goto out_invalid;
1499                 }
1500
1501                 rc = inode_doinit_use_xattr(inode, dentry, sbsec->def_sid,
1502                                             &sid);
1503                 dput(dentry);
1504                 if (rc)
1505                         goto out;
1506                 break;
1507         case SECURITY_FS_USE_TASK:
1508                 sid = task_sid;
1509                 break;
1510         case SECURITY_FS_USE_TRANS:
1511                 /* Default to the fs SID. */
1512                 sid = sbsec->sid;
1513
1514                 /* Try to obtain a transition SID. */
1515                 rc = security_transition_sid(&selinux_state, task_sid, sid,
1516                                              sclass, NULL, &sid);
1517                 if (rc)
1518                         goto out;
1519                 break;
1520         case SECURITY_FS_USE_MNTPOINT:
1521                 sid = sbsec->mntpoint_sid;
1522                 break;
1523         default:
1524                 /* Default to the fs superblock SID. */
1525                 sid = sbsec->sid;
1526
1527                 if ((sbsec->flags & SE_SBGENFS) &&
1528                      (!S_ISLNK(inode->i_mode) ||
1529                       selinux_policycap_genfs_seclabel_symlinks())) {
1530                         /* We must have a dentry to determine the label on
1531                          * procfs inodes */
1532                         if (opt_dentry) {
1533                                 /* Called from d_instantiate or
1534                                  * d_splice_alias. */
1535                                 dentry = dget(opt_dentry);
1536                         } else {
1537                                 /* Called from selinux_complete_init, try to
1538                                  * find a dentry.  Some filesystems really want
1539                                  * a connected one, so try that first.
1540                                  */
1541                                 dentry = d_find_alias(inode);
1542                                 if (!dentry)
1543                                         dentry = d_find_any_alias(inode);
1544                         }
1545                         /*
1546                          * This can be hit on boot when a file is accessed
1547                          * before the policy is loaded.  When we load policy we
1548                          * may find inodes that have no dentry on the
1549                          * sbsec->isec_head list.  No reason to complain as
1550                          * these will get fixed up the next time we go through
1551                          * inode_doinit() with a dentry, before these inodes
1552                          * could be used again by userspace.
1553                          */
1554                         if (!dentry)
1555                                 goto out_invalid;
1556                         rc = selinux_genfs_get_sid(dentry, sclass,
1557                                                    sbsec->flags, &sid);
1558                         if (rc) {
1559                                 dput(dentry);
1560                                 goto out;
1561                         }
1562
1563                         if ((sbsec->flags & SE_SBGENFS_XATTR) &&
1564                             (inode->i_opflags & IOP_XATTR)) {
1565                                 rc = inode_doinit_use_xattr(inode, dentry,
1566                                                             sid, &sid);
1567                                 if (rc) {
1568                                         dput(dentry);
1569                                         goto out;
1570                                 }
1571                         }
1572                         dput(dentry);
1573                 }
1574                 break;
1575         }
1576
1577 out:
1578         spin_lock(&isec->lock);
1579         if (isec->initialized == LABEL_PENDING) {
1580                 if (rc) {
1581                         isec->initialized = LABEL_INVALID;
1582                         goto out_unlock;
1583                 }
1584                 isec->initialized = LABEL_INITIALIZED;
1585                 isec->sid = sid;
1586         }
1587
1588 out_unlock:
1589         spin_unlock(&isec->lock);
1590         return rc;
1591
1592 out_invalid:
1593         spin_lock(&isec->lock);
1594         if (isec->initialized == LABEL_PENDING) {
1595                 isec->initialized = LABEL_INVALID;
1596                 isec->sid = sid;
1597         }
1598         spin_unlock(&isec->lock);
1599         return 0;
1600 }
1601
1602 /* Convert a Linux signal to an access vector. */
1603 static inline u32 signal_to_av(int sig)
1604 {
1605         u32 perm = 0;
1606
1607         switch (sig) {
1608         case SIGCHLD:
1609                 /* Commonly granted from child to parent. */
1610                 perm = PROCESS__SIGCHLD;
1611                 break;
1612         case SIGKILL:
1613                 /* Cannot be caught or ignored */
1614                 perm = PROCESS__SIGKILL;
1615                 break;
1616         case SIGSTOP:
1617                 /* Cannot be caught or ignored */
1618                 perm = PROCESS__SIGSTOP;
1619                 break;
1620         default:
1621                 /* All other signals. */
1622                 perm = PROCESS__SIGNAL;
1623                 break;
1624         }
1625
1626         return perm;
1627 }
1628
1629 #if CAP_LAST_CAP > 63
1630 #error Fix SELinux to handle capabilities > 63.
1631 #endif
1632
1633 /* Check whether a task is allowed to use a capability. */
1634 static int cred_has_capability(const struct cred *cred,
1635                                int cap, unsigned int opts, bool initns)
1636 {
1637         struct common_audit_data ad;
1638         struct av_decision avd;
1639         u16 sclass;
1640         u32 sid = cred_sid(cred);
1641         u32 av = CAP_TO_MASK(cap);
1642         int rc;
1643
1644         ad.type = LSM_AUDIT_DATA_CAP;
1645         ad.u.cap = cap;
1646
1647         switch (CAP_TO_INDEX(cap)) {
1648         case 0:
1649                 sclass = initns ? SECCLASS_CAPABILITY : SECCLASS_CAP_USERNS;
1650                 break;
1651         case 1:
1652                 sclass = initns ? SECCLASS_CAPABILITY2 : SECCLASS_CAP2_USERNS;
1653                 break;
1654         default:
1655                 pr_err("SELinux:  out of range capability %d\n", cap);
1656                 BUG();
1657                 return -EINVAL;
1658         }
1659
1660         rc = avc_has_perm_noaudit(&selinux_state,
1661                                   sid, sid, sclass, av, 0, &avd);
1662         if (!(opts & CAP_OPT_NOAUDIT)) {
1663                 int rc2 = avc_audit(&selinux_state,
1664                                     sid, sid, sclass, av, &avd, rc, &ad);
1665                 if (rc2)
1666                         return rc2;
1667         }
1668         return rc;
1669 }
1670
1671 /* Check whether a task has a particular permission to an inode.
1672    The 'adp' parameter is optional and allows other audit
1673    data to be passed (e.g. the dentry). */
1674 static int inode_has_perm(const struct cred *cred,
1675                           struct inode *inode,
1676                           u32 perms,
1677                           struct common_audit_data *adp)
1678 {
1679         struct inode_security_struct *isec;
1680         u32 sid;
1681
1682         validate_creds(cred);
1683
1684         if (unlikely(IS_PRIVATE(inode)))
1685                 return 0;
1686
1687         sid = cred_sid(cred);
1688         isec = selinux_inode(inode);
1689
1690         return avc_has_perm(&selinux_state,
1691                             sid, isec->sid, isec->sclass, perms, adp);
1692 }
1693
1694 /* Same as inode_has_perm, but pass explicit audit data containing
1695    the dentry to help the auditing code to more easily generate the
1696    pathname if needed. */
1697 static inline int dentry_has_perm(const struct cred *cred,
1698                                   struct dentry *dentry,
1699                                   u32 av)
1700 {
1701         struct inode *inode = d_backing_inode(dentry);
1702         struct common_audit_data ad;
1703
1704         ad.type = LSM_AUDIT_DATA_DENTRY;
1705         ad.u.dentry = dentry;
1706         __inode_security_revalidate(inode, dentry, true);
1707         return inode_has_perm(cred, inode, av, &ad);
1708 }
1709
1710 /* Same as inode_has_perm, but pass explicit audit data containing
1711    the path to help the auditing code to more easily generate the
1712    pathname if needed. */
1713 static inline int path_has_perm(const struct cred *cred,
1714                                 const struct path *path,
1715                                 u32 av)
1716 {
1717         struct inode *inode = d_backing_inode(path->dentry);
1718         struct common_audit_data ad;
1719
1720         ad.type = LSM_AUDIT_DATA_PATH;
1721         ad.u.path = *path;
1722         __inode_security_revalidate(inode, path->dentry, true);
1723         return inode_has_perm(cred, inode, av, &ad);
1724 }
1725
1726 /* Same as path_has_perm, but uses the inode from the file struct. */
1727 static inline int file_path_has_perm(const struct cred *cred,
1728                                      struct file *file,
1729                                      u32 av)
1730 {
1731         struct common_audit_data ad;
1732
1733         ad.type = LSM_AUDIT_DATA_FILE;
1734         ad.u.file = file;
1735         return inode_has_perm(cred, file_inode(file), av, &ad);
1736 }
1737
1738 #ifdef CONFIG_BPF_SYSCALL
1739 static int bpf_fd_pass(struct file *file, u32 sid);
1740 #endif
1741
1742 /* Check whether a task can use an open file descriptor to
1743    access an inode in a given way.  Check access to the
1744    descriptor itself, and then use dentry_has_perm to
1745    check a particular permission to the file.
1746    Access to the descriptor is implicitly granted if it
1747    has the same SID as the process.  If av is zero, then
1748    access to the file is not checked, e.g. for cases
1749    where only the descriptor is affected like seek. */
1750 static int file_has_perm(const struct cred *cred,
1751                          struct file *file,
1752                          u32 av)
1753 {
1754         struct file_security_struct *fsec = selinux_file(file);
1755         struct inode *inode = file_inode(file);
1756         struct common_audit_data ad;
1757         u32 sid = cred_sid(cred);
1758         int rc;
1759
1760         ad.type = LSM_AUDIT_DATA_FILE;
1761         ad.u.file = file;
1762
1763         if (sid != fsec->sid) {
1764                 rc = avc_has_perm(&selinux_state,
1765                                   sid, fsec->sid,
1766                                   SECCLASS_FD,
1767                                   FD__USE,
1768                                   &ad);
1769                 if (rc)
1770                         goto out;
1771         }
1772
1773 #ifdef CONFIG_BPF_SYSCALL
1774         rc = bpf_fd_pass(file, cred_sid(cred));
1775         if (rc)
1776                 return rc;
1777 #endif
1778
1779         /* av is zero if only checking access to the descriptor. */
1780         rc = 0;
1781         if (av)
1782                 rc = inode_has_perm(cred, inode, av, &ad);
1783
1784 out:
1785         return rc;
1786 }
1787
1788 /*
1789  * Determine the label for an inode that might be unioned.
1790  */
1791 static int
1792 selinux_determine_inode_label(const struct task_security_struct *tsec,
1793                                  struct inode *dir,
1794                                  const struct qstr *name, u16 tclass,
1795                                  u32 *_new_isid)
1796 {
1797         const struct superblock_security_struct *sbsec =
1798                                                 selinux_superblock(dir->i_sb);
1799
1800         if ((sbsec->flags & SE_SBINITIALIZED) &&
1801             (sbsec->behavior == SECURITY_FS_USE_MNTPOINT)) {
1802                 *_new_isid = sbsec->mntpoint_sid;
1803         } else if ((sbsec->flags & SBLABEL_MNT) &&
1804                    tsec->create_sid) {
1805                 *_new_isid = tsec->create_sid;
1806         } else {
1807                 const struct inode_security_struct *dsec = inode_security(dir);
1808                 return security_transition_sid(&selinux_state, tsec->sid,
1809                                                dsec->sid, tclass,
1810                                                name, _new_isid);
1811         }
1812
1813         return 0;
1814 }
1815
1816 /* Check whether a task can create a file. */
1817 static int may_create(struct inode *dir,
1818                       struct dentry *dentry,
1819                       u16 tclass)
1820 {
1821         const struct task_security_struct *tsec = selinux_cred(current_cred());
1822         struct inode_security_struct *dsec;
1823         struct superblock_security_struct *sbsec;
1824         u32 sid, newsid;
1825         struct common_audit_data ad;
1826         int rc;
1827
1828         dsec = inode_security(dir);
1829         sbsec = selinux_superblock(dir->i_sb);
1830
1831         sid = tsec->sid;
1832
1833         ad.type = LSM_AUDIT_DATA_DENTRY;
1834         ad.u.dentry = dentry;
1835
1836         rc = avc_has_perm(&selinux_state,
1837                           sid, dsec->sid, SECCLASS_DIR,
1838                           DIR__ADD_NAME | DIR__SEARCH,
1839                           &ad);
1840         if (rc)
1841                 return rc;
1842
1843         rc = selinux_determine_inode_label(tsec, dir, &dentry->d_name, tclass,
1844                                            &newsid);
1845         if (rc)
1846                 return rc;
1847
1848         rc = avc_has_perm(&selinux_state,
1849                           sid, newsid, tclass, FILE__CREATE, &ad);
1850         if (rc)
1851                 return rc;
1852
1853         return avc_has_perm(&selinux_state,
1854                             newsid, sbsec->sid,
1855                             SECCLASS_FILESYSTEM,
1856                             FILESYSTEM__ASSOCIATE, &ad);
1857 }
1858
1859 #define MAY_LINK        0
1860 #define MAY_UNLINK      1
1861 #define MAY_RMDIR       2
1862
1863 /* Check whether a task can link, unlink, or rmdir a file/directory. */
1864 static int may_link(struct inode *dir,
1865                     struct dentry *dentry,
1866                     int kind)
1867
1868 {
1869         struct inode_security_struct *dsec, *isec;
1870         struct common_audit_data ad;
1871         u32 sid = current_sid();
1872         u32 av;
1873         int rc;
1874
1875         dsec = inode_security(dir);
1876         isec = backing_inode_security(dentry);
1877
1878         ad.type = LSM_AUDIT_DATA_DENTRY;
1879         ad.u.dentry = dentry;
1880
1881         av = DIR__SEARCH;
1882         av |= (kind ? DIR__REMOVE_NAME : DIR__ADD_NAME);
1883         rc = avc_has_perm(&selinux_state,
1884                           sid, dsec->sid, SECCLASS_DIR, av, &ad);
1885         if (rc)
1886                 return rc;
1887
1888         switch (kind) {
1889         case MAY_LINK:
1890                 av = FILE__LINK;
1891                 break;
1892         case MAY_UNLINK:
1893                 av = FILE__UNLINK;
1894                 break;
1895         case MAY_RMDIR:
1896                 av = DIR__RMDIR;
1897                 break;
1898         default:
1899                 pr_warn("SELinux: %s:  unrecognized kind %d\n",
1900                         __func__, kind);
1901                 return 0;
1902         }
1903
1904         rc = avc_has_perm(&selinux_state,
1905                           sid, isec->sid, isec->sclass, av, &ad);
1906         return rc;
1907 }
1908
1909 static inline int may_rename(struct inode *old_dir,
1910                              struct dentry *old_dentry,
1911                              struct inode *new_dir,
1912                              struct dentry *new_dentry)
1913 {
1914         struct inode_security_struct *old_dsec, *new_dsec, *old_isec, *new_isec;
1915         struct common_audit_data ad;
1916         u32 sid = current_sid();
1917         u32 av;
1918         int old_is_dir, new_is_dir;
1919         int rc;
1920
1921         old_dsec = inode_security(old_dir);
1922         old_isec = backing_inode_security(old_dentry);
1923         old_is_dir = d_is_dir(old_dentry);
1924         new_dsec = inode_security(new_dir);
1925
1926         ad.type = LSM_AUDIT_DATA_DENTRY;
1927
1928         ad.u.dentry = old_dentry;
1929         rc = avc_has_perm(&selinux_state,
1930                           sid, old_dsec->sid, SECCLASS_DIR,
1931                           DIR__REMOVE_NAME | DIR__SEARCH, &ad);
1932         if (rc)
1933                 return rc;
1934         rc = avc_has_perm(&selinux_state,
1935                           sid, old_isec->sid,
1936                           old_isec->sclass, FILE__RENAME, &ad);
1937         if (rc)
1938                 return rc;
1939         if (old_is_dir && new_dir != old_dir) {
1940                 rc = avc_has_perm(&selinux_state,
1941                                   sid, old_isec->sid,
1942                                   old_isec->sclass, DIR__REPARENT, &ad);
1943                 if (rc)
1944                         return rc;
1945         }
1946
1947         ad.u.dentry = new_dentry;
1948         av = DIR__ADD_NAME | DIR__SEARCH;
1949         if (d_is_positive(new_dentry))
1950                 av |= DIR__REMOVE_NAME;
1951         rc = avc_has_perm(&selinux_state,
1952                           sid, new_dsec->sid, SECCLASS_DIR, av, &ad);
1953         if (rc)
1954                 return rc;
1955         if (d_is_positive(new_dentry)) {
1956                 new_isec = backing_inode_security(new_dentry);
1957                 new_is_dir = d_is_dir(new_dentry);
1958                 rc = avc_has_perm(&selinux_state,
1959                                   sid, new_isec->sid,
1960                                   new_isec->sclass,
1961                                   (new_is_dir ? DIR__RMDIR : FILE__UNLINK), &ad);
1962                 if (rc)
1963                         return rc;
1964         }
1965
1966         return 0;
1967 }
1968
1969 /* Check whether a task can perform a filesystem operation. */
1970 static int superblock_has_perm(const struct cred *cred,
1971                                struct super_block *sb,
1972                                u32 perms,
1973                                struct common_audit_data *ad)
1974 {
1975         struct superblock_security_struct *sbsec;
1976         u32 sid = cred_sid(cred);
1977
1978         sbsec = selinux_superblock(sb);
1979         return avc_has_perm(&selinux_state,
1980                             sid, sbsec->sid, SECCLASS_FILESYSTEM, perms, ad);
1981 }
1982
1983 /* Convert a Linux mode and permission mask to an access vector. */
1984 static inline u32 file_mask_to_av(int mode, int mask)
1985 {
1986         u32 av = 0;
1987
1988         if (!S_ISDIR(mode)) {
1989                 if (mask & MAY_EXEC)
1990                         av |= FILE__EXECUTE;
1991                 if (mask & MAY_READ)
1992                         av |= FILE__READ;
1993
1994                 if (mask & MAY_APPEND)
1995                         av |= FILE__APPEND;
1996                 else if (mask & MAY_WRITE)
1997                         av |= FILE__WRITE;
1998
1999         } else {
2000                 if (mask & MAY_EXEC)
2001                         av |= DIR__SEARCH;
2002                 if (mask & MAY_WRITE)
2003                         av |= DIR__WRITE;
2004                 if (mask & MAY_READ)
2005                         av |= DIR__READ;
2006         }
2007
2008         return av;
2009 }
2010
2011 /* Convert a Linux file to an access vector. */
2012 static inline u32 file_to_av(struct file *file)
2013 {
2014         u32 av = 0;
2015
2016         if (file->f_mode & FMODE_READ)
2017                 av |= FILE__READ;
2018         if (file->f_mode & FMODE_WRITE) {
2019                 if (file->f_flags & O_APPEND)
2020                         av |= FILE__APPEND;
2021                 else
2022                         av |= FILE__WRITE;
2023         }
2024         if (!av) {
2025                 /*
2026                  * Special file opened with flags 3 for ioctl-only use.
2027                  */
2028                 av = FILE__IOCTL;
2029         }
2030
2031         return av;
2032 }
2033
2034 /*
2035  * Convert a file to an access vector and include the correct
2036  * open permission.
2037  */
2038 static inline u32 open_file_to_av(struct file *file)
2039 {
2040         u32 av = file_to_av(file);
2041         struct inode *inode = file_inode(file);
2042
2043         if (selinux_policycap_openperm() &&
2044             inode->i_sb->s_magic != SOCKFS_MAGIC)
2045                 av |= FILE__OPEN;
2046
2047         return av;
2048 }
2049
2050 /* Hook functions begin here. */
2051
2052 static int selinux_binder_set_context_mgr(const struct cred *mgr)
2053 {
2054         return avc_has_perm(&selinux_state,
2055                             current_sid(), cred_sid(mgr), SECCLASS_BINDER,
2056                             BINDER__SET_CONTEXT_MGR, NULL);
2057 }
2058
2059 static int selinux_binder_transaction(const struct cred *from,
2060                                       const struct cred *to)
2061 {
2062         u32 mysid = current_sid();
2063         u32 fromsid = cred_sid(from);
2064         u32 tosid = cred_sid(to);
2065         int rc;
2066
2067         if (mysid != fromsid) {
2068                 rc = avc_has_perm(&selinux_state,
2069                                   mysid, fromsid, SECCLASS_BINDER,
2070                                   BINDER__IMPERSONATE, NULL);
2071                 if (rc)
2072                         return rc;
2073         }
2074
2075         return avc_has_perm(&selinux_state, fromsid, tosid,
2076                             SECCLASS_BINDER, BINDER__CALL, NULL);
2077 }
2078
2079 static int selinux_binder_transfer_binder(const struct cred *from,
2080                                           const struct cred *to)
2081 {
2082         return avc_has_perm(&selinux_state,
2083                             cred_sid(from), cred_sid(to),
2084                             SECCLASS_BINDER, BINDER__TRANSFER,
2085                             NULL);
2086 }
2087
2088 static int selinux_binder_transfer_file(const struct cred *from,
2089                                         const struct cred *to,
2090                                         struct file *file)
2091 {
2092         u32 sid = cred_sid(to);
2093         struct file_security_struct *fsec = selinux_file(file);
2094         struct dentry *dentry = file->f_path.dentry;
2095         struct inode_security_struct *isec;
2096         struct common_audit_data ad;
2097         int rc;
2098
2099         ad.type = LSM_AUDIT_DATA_PATH;
2100         ad.u.path = file->f_path;
2101
2102         if (sid != fsec->sid) {
2103                 rc = avc_has_perm(&selinux_state,
2104                                   sid, fsec->sid,
2105                                   SECCLASS_FD,
2106                                   FD__USE,
2107                                   &ad);
2108                 if (rc)
2109                         return rc;
2110         }
2111
2112 #ifdef CONFIG_BPF_SYSCALL
2113         rc = bpf_fd_pass(file, sid);
2114         if (rc)
2115                 return rc;
2116 #endif
2117
2118         if (unlikely(IS_PRIVATE(d_backing_inode(dentry))))
2119                 return 0;
2120
2121         isec = backing_inode_security(dentry);
2122         return avc_has_perm(&selinux_state,
2123                             sid, isec->sid, isec->sclass, file_to_av(file),
2124                             &ad);
2125 }
2126
2127 static int selinux_ptrace_access_check(struct task_struct *child,
2128                                        unsigned int mode)
2129 {
2130         u32 sid = current_sid();
2131         u32 csid = task_sid_obj(child);
2132
2133         if (mode & PTRACE_MODE_READ)
2134                 return avc_has_perm(&selinux_state,
2135                                     sid, csid, SECCLASS_FILE, FILE__READ, NULL);
2136
2137         return avc_has_perm(&selinux_state,
2138                             sid, csid, SECCLASS_PROCESS, PROCESS__PTRACE, NULL);
2139 }
2140
2141 static int selinux_ptrace_traceme(struct task_struct *parent)
2142 {
2143         return avc_has_perm(&selinux_state,
2144                             task_sid_obj(parent), task_sid_obj(current),
2145                             SECCLASS_PROCESS, PROCESS__PTRACE, NULL);
2146 }
2147
2148 static int selinux_capget(struct task_struct *target, kernel_cap_t *effective,
2149                           kernel_cap_t *inheritable, kernel_cap_t *permitted)
2150 {
2151         return avc_has_perm(&selinux_state,
2152                             current_sid(), task_sid_obj(target), SECCLASS_PROCESS,
2153                             PROCESS__GETCAP, NULL);
2154 }
2155
2156 static int selinux_capset(struct cred *new, const struct cred *old,
2157                           const kernel_cap_t *effective,
2158                           const kernel_cap_t *inheritable,
2159                           const kernel_cap_t *permitted)
2160 {
2161         return avc_has_perm(&selinux_state,
2162                             cred_sid(old), cred_sid(new), SECCLASS_PROCESS,
2163                             PROCESS__SETCAP, NULL);
2164 }
2165
2166 /*
2167  * (This comment used to live with the selinux_task_setuid hook,
2168  * which was removed).
2169  *
2170  * Since setuid only affects the current process, and since the SELinux
2171  * controls are not based on the Linux identity attributes, SELinux does not
2172  * need to control this operation.  However, SELinux does control the use of
2173  * the CAP_SETUID and CAP_SETGID capabilities using the capable hook.
2174  */
2175
2176 static int selinux_capable(const struct cred *cred, struct user_namespace *ns,
2177                            int cap, unsigned int opts)
2178 {
2179         return cred_has_capability(cred, cap, opts, ns == &init_user_ns);
2180 }
2181
2182 static int selinux_quotactl(int cmds, int type, int id, struct super_block *sb)
2183 {
2184         const struct cred *cred = current_cred();
2185         int rc = 0;
2186
2187         if (!sb)
2188                 return 0;
2189
2190         switch (cmds) {
2191         case Q_SYNC:
2192         case Q_QUOTAON:
2193         case Q_QUOTAOFF:
2194         case Q_SETINFO:
2195         case Q_SETQUOTA:
2196         case Q_XQUOTAOFF:
2197         case Q_XQUOTAON:
2198         case Q_XSETQLIM:
2199                 rc = superblock_has_perm(cred, sb, FILESYSTEM__QUOTAMOD, NULL);
2200                 break;
2201         case Q_GETFMT:
2202         case Q_GETINFO:
2203         case Q_GETQUOTA:
2204         case Q_XGETQUOTA:
2205         case Q_XGETQSTAT:
2206         case Q_XGETQSTATV:
2207         case Q_XGETNEXTQUOTA:
2208                 rc = superblock_has_perm(cred, sb, FILESYSTEM__QUOTAGET, NULL);
2209                 break;
2210         default:
2211                 rc = 0;  /* let the kernel handle invalid cmds */
2212                 break;
2213         }
2214         return rc;
2215 }
2216
2217 static int selinux_quota_on(struct dentry *dentry)
2218 {
2219         const struct cred *cred = current_cred();
2220
2221         return dentry_has_perm(cred, dentry, FILE__QUOTAON);
2222 }
2223
2224 static int selinux_syslog(int type)
2225 {
2226         switch (type) {
2227         case SYSLOG_ACTION_READ_ALL:    /* Read last kernel messages */
2228         case SYSLOG_ACTION_SIZE_BUFFER: /* Return size of the log buffer */
2229                 return avc_has_perm(&selinux_state,
2230                                     current_sid(), SECINITSID_KERNEL,
2231                                     SECCLASS_SYSTEM, SYSTEM__SYSLOG_READ, NULL);
2232         case SYSLOG_ACTION_CONSOLE_OFF: /* Disable logging to console */
2233         case SYSLOG_ACTION_CONSOLE_ON:  /* Enable logging to console */
2234         /* Set level of messages printed to console */
2235         case SYSLOG_ACTION_CONSOLE_LEVEL:
2236                 return avc_has_perm(&selinux_state,
2237                                     current_sid(), SECINITSID_KERNEL,
2238                                     SECCLASS_SYSTEM, SYSTEM__SYSLOG_CONSOLE,
2239                                     NULL);
2240         }
2241         /* All other syslog types */
2242         return avc_has_perm(&selinux_state,
2243                             current_sid(), SECINITSID_KERNEL,
2244                             SECCLASS_SYSTEM, SYSTEM__SYSLOG_MOD, NULL);
2245 }
2246
2247 /*
2248  * Check that a process has enough memory to allocate a new virtual
2249  * mapping. 0 means there is enough memory for the allocation to
2250  * succeed and -ENOMEM implies there is not.
2251  *
2252  * Do not audit the selinux permission check, as this is applied to all
2253  * processes that allocate mappings.
2254  */
2255 static int selinux_vm_enough_memory(struct mm_struct *mm, long pages)
2256 {
2257         int rc, cap_sys_admin = 0;
2258
2259         rc = cred_has_capability(current_cred(), CAP_SYS_ADMIN,
2260                                  CAP_OPT_NOAUDIT, true);
2261         if (rc == 0)
2262                 cap_sys_admin = 1;
2263
2264         return cap_sys_admin;
2265 }
2266
2267 /* binprm security operations */
2268
2269 static u32 ptrace_parent_sid(void)
2270 {
2271         u32 sid = 0;
2272         struct task_struct *tracer;
2273
2274         rcu_read_lock();
2275         tracer = ptrace_parent(current);
2276         if (tracer)
2277                 sid = task_sid_obj(tracer);
2278         rcu_read_unlock();
2279
2280         return sid;
2281 }
2282
2283 static int check_nnp_nosuid(const struct linux_binprm *bprm,
2284                             const struct task_security_struct *old_tsec,
2285                             const struct task_security_struct *new_tsec)
2286 {
2287         int nnp = (bprm->unsafe & LSM_UNSAFE_NO_NEW_PRIVS);
2288         int nosuid = !mnt_may_suid(bprm->file->f_path.mnt);
2289         int rc;
2290         u32 av;
2291
2292         if (!nnp && !nosuid)
2293                 return 0; /* neither NNP nor nosuid */
2294
2295         if (new_tsec->sid == old_tsec->sid)
2296                 return 0; /* No change in credentials */
2297
2298         /*
2299          * If the policy enables the nnp_nosuid_transition policy capability,
2300          * then we permit transitions under NNP or nosuid if the
2301          * policy allows the corresponding permission between
2302          * the old and new contexts.
2303          */
2304         if (selinux_policycap_nnp_nosuid_transition()) {
2305                 av = 0;
2306                 if (nnp)
2307                         av |= PROCESS2__NNP_TRANSITION;
2308                 if (nosuid)
2309                         av |= PROCESS2__NOSUID_TRANSITION;
2310                 rc = avc_has_perm(&selinux_state,
2311                                   old_tsec->sid, new_tsec->sid,
2312                                   SECCLASS_PROCESS2, av, NULL);
2313                 if (!rc)
2314                         return 0;
2315         }
2316
2317         /*
2318          * We also permit NNP or nosuid transitions to bounded SIDs,
2319          * i.e. SIDs that are guaranteed to only be allowed a subset
2320          * of the permissions of the current SID.
2321          */
2322         rc = security_bounded_transition(&selinux_state, old_tsec->sid,
2323                                          new_tsec->sid);
2324         if (!rc)
2325                 return 0;
2326
2327         /*
2328          * On failure, preserve the errno values for NNP vs nosuid.
2329          * NNP:  Operation not permitted for caller.
2330          * nosuid:  Permission denied to file.
2331          */
2332         if (nnp)
2333                 return -EPERM;
2334         return -EACCES;
2335 }
2336
2337 static int selinux_bprm_creds_for_exec(struct linux_binprm *bprm)
2338 {
2339         const struct task_security_struct *old_tsec;
2340         struct task_security_struct *new_tsec;
2341         struct inode_security_struct *isec;
2342         struct common_audit_data ad;
2343         struct inode *inode = file_inode(bprm->file);
2344         int rc;
2345
2346         /* SELinux context only depends on initial program or script and not
2347          * the script interpreter */
2348
2349         old_tsec = selinux_cred(current_cred());
2350         new_tsec = selinux_cred(bprm->cred);
2351         isec = inode_security(inode);
2352
2353         /* Default to the current task SID. */
2354         new_tsec->sid = old_tsec->sid;
2355         new_tsec->osid = old_tsec->sid;
2356
2357         /* Reset fs, key, and sock SIDs on execve. */
2358         new_tsec->create_sid = 0;
2359         new_tsec->keycreate_sid = 0;
2360         new_tsec->sockcreate_sid = 0;
2361
2362         if (old_tsec->exec_sid) {
2363                 new_tsec->sid = old_tsec->exec_sid;
2364                 /* Reset exec SID on execve. */
2365                 new_tsec->exec_sid = 0;
2366
2367                 /* Fail on NNP or nosuid if not an allowed transition. */
2368                 rc = check_nnp_nosuid(bprm, old_tsec, new_tsec);
2369                 if (rc)
2370                         return rc;
2371         } else {
2372                 /* Check for a default transition on this program. */
2373                 rc = security_transition_sid(&selinux_state, old_tsec->sid,
2374                                              isec->sid, SECCLASS_PROCESS, NULL,
2375                                              &new_tsec->sid);
2376                 if (rc)
2377                         return rc;
2378
2379                 /*
2380                  * Fallback to old SID on NNP or nosuid if not an allowed
2381                  * transition.
2382                  */
2383                 rc = check_nnp_nosuid(bprm, old_tsec, new_tsec);
2384                 if (rc)
2385                         new_tsec->sid = old_tsec->sid;
2386         }
2387
2388         ad.type = LSM_AUDIT_DATA_FILE;
2389         ad.u.file = bprm->file;
2390
2391         if (new_tsec->sid == old_tsec->sid) {
2392                 rc = avc_has_perm(&selinux_state,
2393                                   old_tsec->sid, isec->sid,
2394                                   SECCLASS_FILE, FILE__EXECUTE_NO_TRANS, &ad);
2395                 if (rc)
2396                         return rc;
2397         } else {
2398                 /* Check permissions for the transition. */
2399                 rc = avc_has_perm(&selinux_state,
2400                                   old_tsec->sid, new_tsec->sid,
2401                                   SECCLASS_PROCESS, PROCESS__TRANSITION, &ad);
2402                 if (rc)
2403                         return rc;
2404
2405                 rc = avc_has_perm(&selinux_state,
2406                                   new_tsec->sid, isec->sid,
2407                                   SECCLASS_FILE, FILE__ENTRYPOINT, &ad);
2408                 if (rc)
2409                         return rc;
2410
2411                 /* Check for shared state */
2412                 if (bprm->unsafe & LSM_UNSAFE_SHARE) {
2413                         rc = avc_has_perm(&selinux_state,
2414                                           old_tsec->sid, new_tsec->sid,
2415                                           SECCLASS_PROCESS, PROCESS__SHARE,
2416                                           NULL);
2417                         if (rc)
2418                                 return -EPERM;
2419                 }
2420
2421                 /* Make sure that anyone attempting to ptrace over a task that
2422                  * changes its SID has the appropriate permit */
2423                 if (bprm->unsafe & LSM_UNSAFE_PTRACE) {
2424                         u32 ptsid = ptrace_parent_sid();
2425                         if (ptsid != 0) {
2426                                 rc = avc_has_perm(&selinux_state,
2427                                                   ptsid, new_tsec->sid,
2428                                                   SECCLASS_PROCESS,
2429                                                   PROCESS__PTRACE, NULL);
2430                                 if (rc)
2431                                         return -EPERM;
2432                         }
2433                 }
2434
2435                 /* Clear any possibly unsafe personality bits on exec: */
2436                 bprm->per_clear |= PER_CLEAR_ON_SETID;
2437
2438                 /* Enable secure mode for SIDs transitions unless
2439                    the noatsecure permission is granted between
2440                    the two SIDs, i.e. ahp returns 0. */
2441                 rc = avc_has_perm(&selinux_state,
2442                                   old_tsec->sid, new_tsec->sid,
2443                                   SECCLASS_PROCESS, PROCESS__NOATSECURE,
2444                                   NULL);
2445                 bprm->secureexec |= !!rc;
2446         }
2447
2448         return 0;
2449 }
2450
2451 static int match_file(const void *p, struct file *file, unsigned fd)
2452 {
2453         return file_has_perm(p, file, file_to_av(file)) ? fd + 1 : 0;
2454 }
2455
2456 /* Derived from fs/exec.c:flush_old_files. */
2457 static inline void flush_unauthorized_files(const struct cred *cred,
2458                                             struct files_struct *files)
2459 {
2460         struct file *file, *devnull = NULL;
2461         struct tty_struct *tty;
2462         int drop_tty = 0;
2463         unsigned n;
2464
2465         tty = get_current_tty();
2466         if (tty) {
2467                 spin_lock(&tty->files_lock);
2468                 if (!list_empty(&tty->tty_files)) {
2469                         struct tty_file_private *file_priv;
2470
2471                         /* Revalidate access to controlling tty.
2472                            Use file_path_has_perm on the tty path directly
2473                            rather than using file_has_perm, as this particular
2474                            open file may belong to another process and we are
2475                            only interested in the inode-based check here. */
2476                         file_priv = list_first_entry(&tty->tty_files,
2477                                                 struct tty_file_private, list);
2478                         file = file_priv->file;
2479                         if (file_path_has_perm(cred, file, FILE__READ | FILE__WRITE))
2480                                 drop_tty = 1;
2481                 }
2482                 spin_unlock(&tty->files_lock);
2483                 tty_kref_put(tty);
2484         }
2485         /* Reset controlling tty. */
2486         if (drop_tty)
2487                 no_tty();
2488
2489         /* Revalidate access to inherited open files. */
2490         n = iterate_fd(files, 0, match_file, cred);
2491         if (!n) /* none found? */
2492                 return;
2493
2494         devnull = dentry_open(&selinux_null, O_RDWR, cred);
2495         if (IS_ERR(devnull))
2496                 devnull = NULL;
2497         /* replace all the matching ones with this */
2498         do {
2499                 replace_fd(n - 1, devnull, 0);
2500         } while ((n = iterate_fd(files, n, match_file, cred)) != 0);
2501         if (devnull)
2502                 fput(devnull);
2503 }
2504
2505 /*
2506  * Prepare a process for imminent new credential changes due to exec
2507  */
2508 static void selinux_bprm_committing_creds(struct linux_binprm *bprm)
2509 {
2510         struct task_security_struct *new_tsec;
2511         struct rlimit *rlim, *initrlim;
2512         int rc, i;
2513
2514         new_tsec = selinux_cred(bprm->cred);
2515         if (new_tsec->sid == new_tsec->osid)
2516                 return;
2517
2518         /* Close files for which the new task SID is not authorized. */
2519         flush_unauthorized_files(bprm->cred, current->files);
2520
2521         /* Always clear parent death signal on SID transitions. */
2522         current->pdeath_signal = 0;
2523
2524         /* Check whether the new SID can inherit resource limits from the old
2525          * SID.  If not, reset all soft limits to the lower of the current
2526          * task's hard limit and the init task's soft limit.
2527          *
2528          * Note that the setting of hard limits (even to lower them) can be
2529          * controlled by the setrlimit check.  The inclusion of the init task's
2530          * soft limit into the computation is to avoid resetting soft limits
2531          * higher than the default soft limit for cases where the default is
2532          * lower than the hard limit, e.g. RLIMIT_CORE or RLIMIT_STACK.
2533          */
2534         rc = avc_has_perm(&selinux_state,
2535                           new_tsec->osid, new_tsec->sid, SECCLASS_PROCESS,
2536                           PROCESS__RLIMITINH, NULL);
2537         if (rc) {
2538                 /* protect against do_prlimit() */
2539                 task_lock(current);
2540                 for (i = 0; i < RLIM_NLIMITS; i++) {
2541                         rlim = current->signal->rlim + i;
2542                         initrlim = init_task.signal->rlim + i;
2543                         rlim->rlim_cur = min(rlim->rlim_max, initrlim->rlim_cur);
2544                 }
2545                 task_unlock(current);
2546                 if (IS_ENABLED(CONFIG_POSIX_TIMERS))
2547                         update_rlimit_cpu(current, rlimit(RLIMIT_CPU));
2548         }
2549 }
2550
2551 /*
2552  * Clean up the process immediately after the installation of new credentials
2553  * due to exec
2554  */
2555 static void selinux_bprm_committed_creds(struct linux_binprm *bprm)
2556 {
2557         const struct task_security_struct *tsec = selinux_cred(current_cred());
2558         u32 osid, sid;
2559         int rc;
2560
2561         osid = tsec->osid;
2562         sid = tsec->sid;
2563
2564         if (sid == osid)
2565                 return;
2566
2567         /* Check whether the new SID can inherit signal state from the old SID.
2568          * If not, clear itimers to avoid subsequent signal generation and
2569          * flush and unblock signals.
2570          *
2571          * This must occur _after_ the task SID has been updated so that any
2572          * kill done after the flush will be checked against the new SID.
2573          */
2574         rc = avc_has_perm(&selinux_state,
2575                           osid, sid, SECCLASS_PROCESS, PROCESS__SIGINH, NULL);
2576         if (rc) {
2577                 clear_itimer();
2578
2579                 spin_lock_irq(&current->sighand->siglock);
2580                 if (!fatal_signal_pending(current)) {
2581                         flush_sigqueue(&current->pending);
2582                         flush_sigqueue(&current->signal->shared_pending);
2583                         flush_signal_handlers(current, 1);
2584                         sigemptyset(&current->blocked);
2585                         recalc_sigpending();
2586                 }
2587                 spin_unlock_irq(&current->sighand->siglock);
2588         }
2589
2590         /* Wake up the parent if it is waiting so that it can recheck
2591          * wait permission to the new task SID. */
2592         read_lock(&tasklist_lock);
2593         __wake_up_parent(current, current->real_parent);
2594         read_unlock(&tasklist_lock);
2595 }
2596
2597 /* superblock security operations */
2598
2599 static int selinux_sb_alloc_security(struct super_block *sb)
2600 {
2601         struct superblock_security_struct *sbsec = selinux_superblock(sb);
2602
2603         mutex_init(&sbsec->lock);
2604         INIT_LIST_HEAD(&sbsec->isec_head);
2605         spin_lock_init(&sbsec->isec_lock);
2606         sbsec->sid = SECINITSID_UNLABELED;
2607         sbsec->def_sid = SECINITSID_FILE;
2608         sbsec->mntpoint_sid = SECINITSID_UNLABELED;
2609
2610         return 0;
2611 }
2612
2613 static inline int opt_len(const char *s)
2614 {
2615         bool open_quote = false;
2616         int len;
2617         char c;
2618
2619         for (len = 0; (c = s[len]) != '\0'; len++) {
2620                 if (c == '"')
2621                         open_quote = !open_quote;
2622                 if (c == ',' && !open_quote)
2623                         break;
2624         }
2625         return len;
2626 }
2627
2628 static int selinux_sb_eat_lsm_opts(char *options, void **mnt_opts)
2629 {
2630         char *from = options;
2631         char *to = options;
2632         bool first = true;
2633         int rc;
2634
2635         while (1) {
2636                 int len = opt_len(from);
2637                 int token;
2638                 char *arg = NULL;
2639
2640                 token = match_opt_prefix(from, len, &arg);
2641
2642                 if (token != Opt_error) {
2643                         char *p, *q;
2644
2645                         /* strip quotes */
2646                         if (arg) {
2647                                 for (p = q = arg; p < from + len; p++) {
2648                                         char c = *p;
2649                                         if (c != '"')
2650                                                 *q++ = c;
2651                                 }
2652                                 arg = kmemdup_nul(arg, q - arg, GFP_KERNEL);
2653                                 if (!arg) {
2654                                         rc = -ENOMEM;
2655                                         goto free_opt;
2656                                 }
2657                         }
2658                         rc = selinux_add_opt(token, arg, mnt_opts);
2659                         if (unlikely(rc)) {
2660                                 kfree(arg);
2661                                 goto free_opt;
2662                         }
2663                 } else {
2664                         if (!first) {   // copy with preceding comma
2665                                 from--;
2666                                 len++;
2667                         }
2668                         if (to != from)
2669                                 memmove(to, from, len);
2670                         to += len;
2671                         first = false;
2672                 }
2673                 if (!from[len])
2674                         break;
2675                 from += len + 1;
2676         }
2677         *to = '\0';
2678         return 0;
2679
2680 free_opt:
2681         if (*mnt_opts) {
2682                 selinux_free_mnt_opts(*mnt_opts);
2683                 *mnt_opts = NULL;
2684         }
2685         return rc;
2686 }
2687
2688 static int selinux_sb_mnt_opts_compat(struct super_block *sb, void *mnt_opts)
2689 {
2690         struct selinux_mnt_opts *opts = mnt_opts;
2691         struct superblock_security_struct *sbsec = sb->s_security;
2692         u32 sid;
2693         int rc;
2694
2695         /*
2696          * Superblock not initialized (i.e. no options) - reject if any
2697          * options specified, otherwise accept.
2698          */
2699         if (!(sbsec->flags & SE_SBINITIALIZED))
2700                 return opts ? 1 : 0;
2701
2702         /*
2703          * Superblock initialized and no options specified - reject if
2704          * superblock has any options set, otherwise accept.
2705          */
2706         if (!opts)
2707                 return (sbsec->flags & SE_MNTMASK) ? 1 : 0;
2708
2709         if (opts->fscontext) {
2710                 rc = parse_sid(sb, opts->fscontext, &sid, GFP_NOWAIT);
2711                 if (rc)
2712                         return 1;
2713                 if (bad_option(sbsec, FSCONTEXT_MNT, sbsec->sid, sid))
2714                         return 1;
2715         }
2716         if (opts->context) {
2717                 rc = parse_sid(sb, opts->context, &sid, GFP_NOWAIT);
2718                 if (rc)
2719                         return 1;
2720                 if (bad_option(sbsec, CONTEXT_MNT, sbsec->mntpoint_sid, sid))
2721                         return 1;
2722         }
2723         if (opts->rootcontext) {
2724                 struct inode_security_struct *root_isec;
2725
2726                 root_isec = backing_inode_security(sb->s_root);
2727                 rc = parse_sid(sb, opts->rootcontext, &sid, GFP_NOWAIT);
2728                 if (rc)
2729                         return 1;
2730                 if (bad_option(sbsec, ROOTCONTEXT_MNT, root_isec->sid, sid))
2731                         return 1;
2732         }
2733         if (opts->defcontext) {
2734                 rc = parse_sid(sb, opts->defcontext, &sid, GFP_NOWAIT);
2735                 if (rc)
2736                         return 1;
2737                 if (bad_option(sbsec, DEFCONTEXT_MNT, sbsec->def_sid, sid))
2738                         return 1;
2739         }
2740         return 0;
2741 }
2742
2743 static int selinux_sb_remount(struct super_block *sb, void *mnt_opts)
2744 {
2745         struct selinux_mnt_opts *opts = mnt_opts;
2746         struct superblock_security_struct *sbsec = selinux_superblock(sb);
2747         u32 sid;
2748         int rc;
2749
2750         if (!(sbsec->flags & SE_SBINITIALIZED))
2751                 return 0;
2752
2753         if (!opts)
2754                 return 0;
2755
2756         if (opts->fscontext) {
2757                 rc = parse_sid(sb, opts->fscontext, &sid, GFP_KERNEL);
2758                 if (rc)
2759                         return rc;
2760                 if (bad_option(sbsec, FSCONTEXT_MNT, sbsec->sid, sid))
2761                         goto out_bad_option;
2762         }
2763         if (opts->context) {
2764                 rc = parse_sid(sb, opts->context, &sid, GFP_KERNEL);
2765                 if (rc)
2766                         return rc;
2767                 if (bad_option(sbsec, CONTEXT_MNT, sbsec->mntpoint_sid, sid))
2768                         goto out_bad_option;
2769         }
2770         if (opts->rootcontext) {
2771                 struct inode_security_struct *root_isec;
2772                 root_isec = backing_inode_security(sb->s_root);
2773                 rc = parse_sid(sb, opts->rootcontext, &sid, GFP_KERNEL);
2774                 if (rc)
2775                         return rc;
2776                 if (bad_option(sbsec, ROOTCONTEXT_MNT, root_isec->sid, sid))
2777                         goto out_bad_option;
2778         }
2779         if (opts->defcontext) {
2780                 rc = parse_sid(sb, opts->defcontext, &sid, GFP_KERNEL);
2781                 if (rc)
2782                         return rc;
2783                 if (bad_option(sbsec, DEFCONTEXT_MNT, sbsec->def_sid, sid))
2784                         goto out_bad_option;
2785         }
2786         return 0;
2787
2788 out_bad_option:
2789         pr_warn("SELinux: unable to change security options "
2790                "during remount (dev %s, type=%s)\n", sb->s_id,
2791                sb->s_type->name);
2792         return -EINVAL;
2793 }
2794
2795 static int selinux_sb_kern_mount(struct super_block *sb)
2796 {
2797         const struct cred *cred = current_cred();
2798         struct common_audit_data ad;
2799
2800         ad.type = LSM_AUDIT_DATA_DENTRY;
2801         ad.u.dentry = sb->s_root;
2802         return superblock_has_perm(cred, sb, FILESYSTEM__MOUNT, &ad);
2803 }
2804
2805 static int selinux_sb_statfs(struct dentry *dentry)
2806 {
2807         const struct cred *cred = current_cred();
2808         struct common_audit_data ad;
2809
2810         ad.type = LSM_AUDIT_DATA_DENTRY;
2811         ad.u.dentry = dentry->d_sb->s_root;
2812         return superblock_has_perm(cred, dentry->d_sb, FILESYSTEM__GETATTR, &ad);
2813 }
2814
2815 static int selinux_mount(const char *dev_name,
2816                          const struct path *path,
2817                          const char *type,
2818                          unsigned long flags,
2819                          void *data)
2820 {
2821         const struct cred *cred = current_cred();
2822
2823         if (flags & MS_REMOUNT)
2824                 return superblock_has_perm(cred, path->dentry->d_sb,
2825                                            FILESYSTEM__REMOUNT, NULL);
2826         else
2827                 return path_has_perm(cred, path, FILE__MOUNTON);
2828 }
2829
2830 static int selinux_move_mount(const struct path *from_path,
2831                               const struct path *to_path)
2832 {
2833         const struct cred *cred = current_cred();
2834
2835         return path_has_perm(cred, to_path, FILE__MOUNTON);
2836 }
2837
2838 static int selinux_umount(struct vfsmount *mnt, int flags)
2839 {
2840         const struct cred *cred = current_cred();
2841
2842         return superblock_has_perm(cred, mnt->mnt_sb,
2843                                    FILESYSTEM__UNMOUNT, NULL);
2844 }
2845
2846 static int selinux_fs_context_dup(struct fs_context *fc,
2847                                   struct fs_context *src_fc)
2848 {
2849         const struct selinux_mnt_opts *src = src_fc->security;
2850         struct selinux_mnt_opts *opts;
2851
2852         if (!src)
2853                 return 0;
2854
2855         fc->security = kzalloc(sizeof(struct selinux_mnt_opts), GFP_KERNEL);
2856         if (!fc->security)
2857                 return -ENOMEM;
2858
2859         opts = fc->security;
2860
2861         if (src->fscontext) {
2862                 opts->fscontext = kstrdup(src->fscontext, GFP_KERNEL);
2863                 if (!opts->fscontext)
2864                         return -ENOMEM;
2865         }
2866         if (src->context) {
2867                 opts->context = kstrdup(src->context, GFP_KERNEL);
2868                 if (!opts->context)
2869                         return -ENOMEM;
2870         }
2871         if (src->rootcontext) {
2872                 opts->rootcontext = kstrdup(src->rootcontext, GFP_KERNEL);
2873                 if (!opts->rootcontext)
2874                         return -ENOMEM;
2875         }
2876         if (src->defcontext) {
2877                 opts->defcontext = kstrdup(src->defcontext, GFP_KERNEL);
2878                 if (!opts->defcontext)
2879                         return -ENOMEM;
2880         }
2881         return 0;
2882 }
2883
2884 static const struct fs_parameter_spec selinux_fs_parameters[] = {
2885         fsparam_string(CONTEXT_STR,     Opt_context),
2886         fsparam_string(DEFCONTEXT_STR,  Opt_defcontext),
2887         fsparam_string(FSCONTEXT_STR,   Opt_fscontext),
2888         fsparam_string(ROOTCONTEXT_STR, Opt_rootcontext),
2889         fsparam_flag  (SECLABEL_STR,    Opt_seclabel),
2890         {}
2891 };
2892
2893 static int selinux_fs_context_parse_param(struct fs_context *fc,
2894                                           struct fs_parameter *param)
2895 {
2896         struct fs_parse_result result;
2897         int opt, rc;
2898
2899         opt = fs_parse(fc, selinux_fs_parameters, param, &result);
2900         if (opt < 0)
2901                 return opt;
2902
2903         rc = selinux_add_opt(opt, param->string, &fc->security);
2904         if (!rc) {
2905                 param->string = NULL;
2906                 rc = 1;
2907         }
2908         return rc;
2909 }
2910
2911 /* inode security operations */
2912
2913 static int selinux_inode_alloc_security(struct inode *inode)
2914 {
2915         struct inode_security_struct *isec = selinux_inode(inode);
2916         u32 sid = current_sid();
2917
2918         spin_lock_init(&isec->lock);
2919         INIT_LIST_HEAD(&isec->list);
2920         isec->inode = inode;
2921         isec->sid = SECINITSID_UNLABELED;
2922         isec->sclass = SECCLASS_FILE;
2923         isec->task_sid = sid;
2924         isec->initialized = LABEL_INVALID;
2925
2926         return 0;
2927 }
2928
2929 static void selinux_inode_free_security(struct inode *inode)
2930 {
2931         inode_free_security(inode);
2932 }
2933
2934 static int selinux_dentry_init_security(struct dentry *dentry, int mode,
2935                                         const struct qstr *name,
2936                                         const char **xattr_name, void **ctx,
2937                                         u32 *ctxlen)
2938 {
2939         u32 newsid;
2940         int rc;
2941
2942         rc = selinux_determine_inode_label(selinux_cred(current_cred()),
2943                                            d_inode(dentry->d_parent), name,
2944                                            inode_mode_to_security_class(mode),
2945                                            &newsid);
2946         if (rc)
2947                 return rc;
2948
2949         if (xattr_name)
2950                 *xattr_name = XATTR_NAME_SELINUX;
2951
2952         return security_sid_to_context(&selinux_state, newsid, (char **)ctx,
2953                                        ctxlen);
2954 }
2955
2956 static int selinux_dentry_create_files_as(struct dentry *dentry, int mode,
2957                                           struct qstr *name,
2958                                           const struct cred *old,
2959                                           struct cred *new)
2960 {
2961         u32 newsid;
2962         int rc;
2963         struct task_security_struct *tsec;
2964
2965         rc = selinux_determine_inode_label(selinux_cred(old),
2966                                            d_inode(dentry->d_parent), name,
2967                                            inode_mode_to_security_class(mode),
2968                                            &newsid);
2969         if (rc)
2970                 return rc;
2971
2972         tsec = selinux_cred(new);
2973         tsec->create_sid = newsid;
2974         return 0;
2975 }
2976
2977 static int selinux_inode_init_security(struct inode *inode, struct inode *dir,
2978                                        const struct qstr *qstr,
2979                                        const char **name,
2980                                        void **value, size_t *len)
2981 {
2982         const struct task_security_struct *tsec = selinux_cred(current_cred());
2983         struct superblock_security_struct *sbsec;
2984         u32 newsid, clen;
2985         int rc;
2986         char *context;
2987
2988         sbsec = selinux_superblock(dir->i_sb);
2989
2990         newsid = tsec->create_sid;
2991
2992         rc = selinux_determine_inode_label(tsec, dir, qstr,
2993                 inode_mode_to_security_class(inode->i_mode),
2994                 &newsid);
2995         if (rc)
2996                 return rc;
2997
2998         /* Possibly defer initialization to selinux_complete_init. */
2999         if (sbsec->flags & SE_SBINITIALIZED) {
3000                 struct inode_security_struct *isec = selinux_inode(inode);
3001                 isec->sclass = inode_mode_to_security_class(inode->i_mode);
3002                 isec->sid = newsid;
3003                 isec->initialized = LABEL_INITIALIZED;
3004         }
3005
3006         if (!selinux_initialized(&selinux_state) ||
3007             !(sbsec->flags & SBLABEL_MNT))
3008                 return -EOPNOTSUPP;
3009
3010         if (name)
3011                 *name = XATTR_SELINUX_SUFFIX;
3012
3013         if (value && len) {
3014                 rc = security_sid_to_context_force(&selinux_state, newsid,
3015                                                    &context, &clen);
3016                 if (rc)
3017                         return rc;
3018                 *value = context;
3019                 *len = clen;
3020         }
3021
3022         return 0;
3023 }
3024
3025 static int selinux_inode_init_security_anon(struct inode *inode,
3026                                             const struct qstr *name,
3027                                             const struct inode *context_inode)
3028 {
3029         const struct task_security_struct *tsec = selinux_cred(current_cred());
3030         struct common_audit_data ad;
3031         struct inode_security_struct *isec;
3032         int rc;
3033
3034         if (unlikely(!selinux_initialized(&selinux_state)))
3035                 return 0;
3036
3037         isec = selinux_inode(inode);
3038
3039         /*
3040          * We only get here once per ephemeral inode.  The inode has
3041          * been initialized via inode_alloc_security but is otherwise
3042          * untouched.
3043          */
3044
3045         if (context_inode) {
3046                 struct inode_security_struct *context_isec =
3047                         selinux_inode(context_inode);
3048                 if (context_isec->initialized != LABEL_INITIALIZED) {
3049                         pr_err("SELinux:  context_inode is not initialized");
3050                         return -EACCES;
3051                 }
3052
3053                 isec->sclass = context_isec->sclass;
3054                 isec->sid = context_isec->sid;
3055         } else {
3056                 isec->sclass = SECCLASS_ANON_INODE;
3057                 rc = security_transition_sid(
3058                         &selinux_state, tsec->sid, tsec->sid,
3059                         isec->sclass, name, &isec->sid);
3060                 if (rc)
3061                         return rc;
3062         }
3063
3064         isec->initialized = LABEL_INITIALIZED;
3065         /*
3066          * Now that we've initialized security, check whether we're
3067          * allowed to actually create this type of anonymous inode.
3068          */
3069
3070         ad.type = LSM_AUDIT_DATA_INODE;
3071         ad.u.inode = inode;
3072
3073         return avc_has_perm(&selinux_state,
3074                             tsec->sid,
3075                             isec->sid,
3076                             isec->sclass,
3077                             FILE__CREATE,
3078                             &ad);
3079 }
3080
3081 static int selinux_inode_create(struct inode *dir, struct dentry *dentry, umode_t mode)
3082 {
3083         return may_create(dir, dentry, SECCLASS_FILE);
3084 }
3085
3086 static int selinux_inode_link(struct dentry *old_dentry, struct inode *dir, struct dentry *new_dentry)
3087 {
3088         return may_link(dir, old_dentry, MAY_LINK);
3089 }
3090
3091 static int selinux_inode_unlink(struct inode *dir, struct dentry *dentry)
3092 {
3093         return may_link(dir, dentry, MAY_UNLINK);
3094 }
3095
3096 static int selinux_inode_symlink(struct inode *dir, struct dentry *dentry, const char *name)
3097 {
3098         return may_create(dir, dentry, SECCLASS_LNK_FILE);
3099 }
3100
3101 static int selinux_inode_mkdir(struct inode *dir, struct dentry *dentry, umode_t mask)
3102 {
3103         return may_create(dir, dentry, SECCLASS_DIR);
3104 }
3105
3106 static int selinux_inode_rmdir(struct inode *dir, struct dentry *dentry)
3107 {
3108         return may_link(dir, dentry, MAY_RMDIR);
3109 }
3110
3111 static int selinux_inode_mknod(struct inode *dir, struct dentry *dentry, umode_t mode, dev_t dev)
3112 {
3113         return may_create(dir, dentry, inode_mode_to_security_class(mode));
3114 }
3115
3116 static int selinux_inode_rename(struct inode *old_inode, struct dentry *old_dentry,
3117                                 struct inode *new_inode, struct dentry *new_dentry)
3118 {
3119         return may_rename(old_inode, old_dentry, new_inode, new_dentry);
3120 }
3121
3122 static int selinux_inode_readlink(struct dentry *dentry)
3123 {
3124         const struct cred *cred = current_cred();
3125
3126         return dentry_has_perm(cred, dentry, FILE__READ);
3127 }
3128
3129 static int selinux_inode_follow_link(struct dentry *dentry, struct inode *inode,
3130                                      bool rcu)
3131 {
3132         const struct cred *cred = current_cred();
3133         struct common_audit_data ad;
3134         struct inode_security_struct *isec;
3135         u32 sid;
3136
3137         validate_creds(cred);
3138
3139         ad.type = LSM_AUDIT_DATA_DENTRY;
3140         ad.u.dentry = dentry;
3141         sid = cred_sid(cred);
3142         isec = inode_security_rcu(inode, rcu);
3143         if (IS_ERR(isec))
3144                 return PTR_ERR(isec);
3145
3146         return avc_has_perm(&selinux_state,
3147                                   sid, isec->sid, isec->sclass, FILE__READ, &ad);
3148 }
3149
3150 static noinline int audit_inode_permission(struct inode *inode,
3151                                            u32 perms, u32 audited, u32 denied,
3152                                            int result)
3153 {
3154         struct common_audit_data ad;
3155         struct inode_security_struct *isec = selinux_inode(inode);
3156
3157         ad.type = LSM_AUDIT_DATA_INODE;
3158         ad.u.inode = inode;
3159
3160         return slow_avc_audit(&selinux_state,
3161                             current_sid(), isec->sid, isec->sclass, perms,
3162                             audited, denied, result, &ad);
3163 }
3164
3165 static int selinux_inode_permission(struct inode *inode, int mask)
3166 {
3167         const struct cred *cred = current_cred();
3168         u32 perms;
3169         bool from_access;
3170         bool no_block = mask & MAY_NOT_BLOCK;
3171         struct inode_security_struct *isec;
3172         u32 sid;
3173         struct av_decision avd;
3174         int rc, rc2;
3175         u32 audited, denied;
3176
3177         from_access = mask & MAY_ACCESS;
3178         mask &= (MAY_READ|MAY_WRITE|MAY_EXEC|MAY_APPEND);
3179
3180         /* No permission to check.  Existence test. */
3181         if (!mask)
3182                 return 0;
3183
3184         validate_creds(cred);
3185
3186         if (unlikely(IS_PRIVATE(inode)))
3187                 return 0;
3188
3189         perms = file_mask_to_av(inode->i_mode, mask);
3190
3191         sid = cred_sid(cred);
3192         isec = inode_security_rcu(inode, no_block);
3193         if (IS_ERR(isec))
3194                 return PTR_ERR(isec);
3195
3196         rc = avc_has_perm_noaudit(&selinux_state,
3197                                   sid, isec->sid, isec->sclass, perms, 0,
3198                                   &avd);
3199         audited = avc_audit_required(perms, &avd, rc,
3200                                      from_access ? FILE__AUDIT_ACCESS : 0,
3201                                      &denied);
3202         if (likely(!audited))
3203                 return rc;
3204
3205         rc2 = audit_inode_permission(inode, perms, audited, denied, rc);
3206         if (rc2)
3207                 return rc2;
3208         return rc;
3209 }
3210
3211 static int selinux_inode_setattr(struct dentry *dentry, struct iattr *iattr)
3212 {
3213         const struct cred *cred = current_cred();
3214         struct inode *inode = d_backing_inode(dentry);
3215         unsigned int ia_valid = iattr->ia_valid;
3216         __u32 av = FILE__WRITE;
3217
3218         /* ATTR_FORCE is just used for ATTR_KILL_S[UG]ID. */
3219         if (ia_valid & ATTR_FORCE) {
3220                 ia_valid &= ~(ATTR_KILL_SUID | ATTR_KILL_SGID | ATTR_MODE |
3221                               ATTR_FORCE);
3222                 if (!ia_valid)
3223                         return 0;
3224         }
3225
3226         if (ia_valid & (ATTR_MODE | ATTR_UID | ATTR_GID |
3227                         ATTR_ATIME_SET | ATTR_MTIME_SET | ATTR_TIMES_SET))
3228                 return dentry_has_perm(cred, dentry, FILE__SETATTR);
3229
3230         if (selinux_policycap_openperm() &&
3231             inode->i_sb->s_magic != SOCKFS_MAGIC &&
3232             (ia_valid & ATTR_SIZE) &&
3233             !(ia_valid & ATTR_FILE))
3234                 av |= FILE__OPEN;
3235
3236         return dentry_has_perm(cred, dentry, av);
3237 }
3238
3239 static int selinux_inode_getattr(const struct path *path)
3240 {
3241         return path_has_perm(current_cred(), path, FILE__GETATTR);
3242 }
3243
3244 static bool has_cap_mac_admin(bool audit)
3245 {
3246         const struct cred *cred = current_cred();
3247         unsigned int opts = audit ? CAP_OPT_NONE : CAP_OPT_NOAUDIT;
3248
3249         if (cap_capable(cred, &init_user_ns, CAP_MAC_ADMIN, opts))
3250                 return false;
3251         if (cred_has_capability(cred, CAP_MAC_ADMIN, opts, true))
3252                 return false;
3253         return true;
3254 }
3255
3256 static int selinux_inode_setxattr(struct user_namespace *mnt_userns,
3257                                   struct dentry *dentry, const char *name,
3258                                   const void *value, size_t size, int flags)
3259 {
3260         struct inode *inode = d_backing_inode(dentry);
3261         struct inode_security_struct *isec;
3262         struct superblock_security_struct *sbsec;
3263         struct common_audit_data ad;
3264         u32 newsid, sid = current_sid();
3265         int rc = 0;
3266
3267         if (strcmp(name, XATTR_NAME_SELINUX)) {
3268                 rc = cap_inode_setxattr(dentry, name, value, size, flags);
3269                 if (rc)
3270                         return rc;
3271
3272                 /* Not an attribute we recognize, so just check the
3273                    ordinary setattr permission. */
3274                 return dentry_has_perm(current_cred(), dentry, FILE__SETATTR);
3275         }
3276
3277         if (!selinux_initialized(&selinux_state))
3278                 return (inode_owner_or_capable(mnt_userns, inode) ? 0 : -EPERM);
3279
3280         sbsec = selinux_superblock(inode->i_sb);
3281         if (!(sbsec->flags & SBLABEL_MNT))
3282                 return -EOPNOTSUPP;
3283
3284         if (!inode_owner_or_capable(mnt_userns, inode))
3285                 return -EPERM;
3286
3287         ad.type = LSM_AUDIT_DATA_DENTRY;
3288         ad.u.dentry = dentry;
3289
3290         isec = backing_inode_security(dentry);
3291         rc = avc_has_perm(&selinux_state,
3292                           sid, isec->sid, isec->sclass,
3293                           FILE__RELABELFROM, &ad);
3294         if (rc)
3295                 return rc;
3296
3297         rc = security_context_to_sid(&selinux_state, value, size, &newsid,
3298                                      GFP_KERNEL);
3299         if (rc == -EINVAL) {
3300                 if (!has_cap_mac_admin(true)) {
3301                         struct audit_buffer *ab;
3302                         size_t audit_size;
3303
3304                         /* We strip a nul only if it is at the end, otherwise the
3305                          * context contains a nul and we should audit that */
3306                         if (value) {
3307                                 const char *str = value;
3308
3309                                 if (str[size - 1] == '\0')
3310                                         audit_size = size - 1;
3311                                 else
3312                                         audit_size = size;
3313                         } else {
3314                                 audit_size = 0;
3315                         }
3316                         ab = audit_log_start(audit_context(),
3317                                              GFP_ATOMIC, AUDIT_SELINUX_ERR);
3318                         if (!ab)
3319                                 return rc;
3320                         audit_log_format(ab, "op=setxattr invalid_context=");
3321                         audit_log_n_untrustedstring(ab, value, audit_size);
3322                         audit_log_end(ab);
3323
3324                         return rc;
3325                 }
3326                 rc = security_context_to_sid_force(&selinux_state, value,
3327                                                    size, &newsid);
3328         }
3329         if (rc)
3330                 return rc;
3331
3332         rc = avc_has_perm(&selinux_state,
3333                           sid, newsid, isec->sclass,
3334                           FILE__RELABELTO, &ad);
3335         if (rc)
3336                 return rc;
3337
3338         rc = security_validate_transition(&selinux_state, isec->sid, newsid,
3339                                           sid, isec->sclass);
3340         if (rc)
3341                 return rc;
3342
3343         return avc_has_perm(&selinux_state,
3344                             newsid,
3345                             sbsec->sid,
3346                             SECCLASS_FILESYSTEM,
3347                             FILESYSTEM__ASSOCIATE,
3348                             &ad);
3349 }
3350
3351 static void selinux_inode_post_setxattr(struct dentry *dentry, const char *name,
3352                                         const void *value, size_t size,
3353                                         int flags)
3354 {
3355         struct inode *inode = d_backing_inode(dentry);
3356         struct inode_security_struct *isec;
3357         u32 newsid;
3358         int rc;
3359
3360         if (strcmp(name, XATTR_NAME_SELINUX)) {
3361                 /* Not an attribute we recognize, so nothing to do. */
3362                 return;
3363         }
3364
3365         if (!selinux_initialized(&selinux_state)) {
3366                 /* If we haven't even been initialized, then we can't validate
3367                  * against a policy, so leave the label as invalid. It may
3368                  * resolve to a valid label on the next revalidation try if
3369                  * we've since initialized.
3370                  */
3371                 return;
3372         }
3373
3374         rc = security_context_to_sid_force(&selinux_state, value, size,
3375                                            &newsid);
3376         if (rc) {
3377                 pr_err("SELinux:  unable to map context to SID"
3378                        "for (%s, %lu), rc=%d\n",
3379                        inode->i_sb->s_id, inode->i_ino, -rc);
3380                 return;
3381         }
3382
3383         isec = backing_inode_security(dentry);
3384         spin_lock(&isec->lock);
3385         isec->sclass = inode_mode_to_security_class(inode->i_mode);
3386         isec->sid = newsid;
3387         isec->initialized = LABEL_INITIALIZED;
3388         spin_unlock(&isec->lock);
3389
3390         return;
3391 }
3392
3393 static int selinux_inode_getxattr(struct dentry *dentry, const char *name)
3394 {
3395         const struct cred *cred = current_cred();
3396
3397         return dentry_has_perm(cred, dentry, FILE__GETATTR);
3398 }
3399
3400 static int selinux_inode_listxattr(struct dentry *dentry)
3401 {
3402         const struct cred *cred = current_cred();
3403
3404         return dentry_has_perm(cred, dentry, FILE__GETATTR);
3405 }
3406
3407 static int selinux_inode_removexattr(struct user_namespace *mnt_userns,
3408                                      struct dentry *dentry, const char *name)
3409 {
3410         if (strcmp(name, XATTR_NAME_SELINUX)) {
3411                 int rc = cap_inode_removexattr(mnt_userns, dentry, name);
3412                 if (rc)
3413                         return rc;
3414
3415                 /* Not an attribute we recognize, so just check the
3416                    ordinary setattr permission. */
3417                 return dentry_has_perm(current_cred(), dentry, FILE__SETATTR);
3418         }
3419
3420         if (!selinux_initialized(&selinux_state))
3421                 return 0;
3422
3423         /* No one is allowed to remove a SELinux security label.
3424            You can change the label, but all data must be labeled. */
3425         return -EACCES;
3426 }
3427
3428 static int selinux_path_notify(const struct path *path, u64 mask,
3429                                                 unsigned int obj_type)
3430 {
3431         int ret;
3432         u32 perm;
3433
3434         struct common_audit_data ad;
3435
3436         ad.type = LSM_AUDIT_DATA_PATH;
3437         ad.u.path = *path;
3438
3439         /*
3440          * Set permission needed based on the type of mark being set.
3441          * Performs an additional check for sb watches.
3442          */
3443         switch (obj_type) {
3444         case FSNOTIFY_OBJ_TYPE_VFSMOUNT:
3445                 perm = FILE__WATCH_MOUNT;
3446                 break;
3447         case FSNOTIFY_OBJ_TYPE_SB:
3448                 perm = FILE__WATCH_SB;
3449                 ret = superblock_has_perm(current_cred(), path->dentry->d_sb,
3450                                                 FILESYSTEM__WATCH, &ad);
3451                 if (ret)
3452                         return ret;
3453                 break;
3454         case FSNOTIFY_OBJ_TYPE_INODE:
3455                 perm = FILE__WATCH;
3456                 break;
3457         default:
3458                 return -EINVAL;
3459         }
3460
3461         /* blocking watches require the file:watch_with_perm permission */
3462         if (mask & (ALL_FSNOTIFY_PERM_EVENTS))
3463                 perm |= FILE__WATCH_WITH_PERM;
3464
3465         /* watches on read-like events need the file:watch_reads permission */
3466         if (mask & (FS_ACCESS | FS_ACCESS_PERM | FS_CLOSE_NOWRITE))
3467                 perm |= FILE__WATCH_READS;
3468
3469         return path_has_perm(current_cred(), path, perm);
3470 }
3471
3472 /*
3473  * Copy the inode security context value to the user.
3474  *
3475  * Permission check is handled by selinux_inode_getxattr hook.
3476  */
3477 static int selinux_inode_getsecurity(struct user_namespace *mnt_userns,
3478                                      struct inode *inode, const char *name,
3479                                      void **buffer, bool alloc)
3480 {
3481         u32 size;
3482         int error;
3483         char *context = NULL;
3484         struct inode_security_struct *isec;
3485
3486         /*
3487          * If we're not initialized yet, then we can't validate contexts, so
3488          * just let vfs_getxattr fall back to using the on-disk xattr.
3489          */
3490         if (!selinux_initialized(&selinux_state) ||
3491             strcmp(name, XATTR_SELINUX_SUFFIX))
3492                 return -EOPNOTSUPP;
3493
3494         /*
3495          * If the caller has CAP_MAC_ADMIN, then get the raw context
3496          * value even if it is not defined by current policy; otherwise,
3497          * use the in-core value under current policy.
3498          * Use the non-auditing forms of the permission checks since
3499          * getxattr may be called by unprivileged processes commonly
3500          * and lack of permission just means that we fall back to the
3501          * in-core context value, not a denial.
3502          */
3503         isec = inode_security(inode);
3504         if (has_cap_mac_admin(false))
3505                 error = security_sid_to_context_force(&selinux_state,
3506                                                       isec->sid, &context,
3507                                                       &size);
3508         else
3509                 error = security_sid_to_context(&selinux_state, isec->sid,
3510                                                 &context, &size);
3511         if (error)
3512                 return error;
3513         error = size;
3514         if (alloc) {
3515                 *buffer = context;
3516                 goto out_nofree;
3517         }
3518         kfree(context);
3519 out_nofree:
3520         return error;
3521 }
3522
3523 static int selinux_inode_setsecurity(struct inode *inode, const char *name,
3524                                      const void *value, size_t size, int flags)
3525 {
3526         struct inode_security_struct *isec = inode_security_novalidate(inode);
3527         struct superblock_security_struct *sbsec;
3528         u32 newsid;
3529         int rc;
3530
3531         if (strcmp(name, XATTR_SELINUX_SUFFIX))
3532                 return -EOPNOTSUPP;
3533
3534         sbsec = selinux_superblock(inode->i_sb);
3535         if (!(sbsec->flags & SBLABEL_MNT))
3536                 return -EOPNOTSUPP;
3537
3538         if (!value || !size)
3539                 return -EACCES;
3540
3541         rc = security_context_to_sid(&selinux_state, value, size, &newsid,
3542                                      GFP_KERNEL);
3543         if (rc)
3544                 return rc;
3545
3546         spin_lock(&isec->lock);
3547         isec->sclass = inode_mode_to_security_class(inode->i_mode);
3548         isec->sid = newsid;
3549         isec->initialized = LABEL_INITIALIZED;
3550         spin_unlock(&isec->lock);
3551         return 0;
3552 }
3553
3554 static int selinux_inode_listsecurity(struct inode *inode, char *buffer, size_t buffer_size)
3555 {
3556         const int len = sizeof(XATTR_NAME_SELINUX);
3557
3558         if (!selinux_initialized(&selinux_state))
3559                 return 0;
3560
3561         if (buffer && len <= buffer_size)
3562                 memcpy(buffer, XATTR_NAME_SELINUX, len);
3563         return len;
3564 }
3565
3566 static void selinux_inode_getsecid(struct inode *inode, u32 *secid)
3567 {
3568         struct inode_security_struct *isec = inode_security_novalidate(inode);
3569         *secid = isec->sid;
3570 }
3571
3572 static int selinux_inode_copy_up(struct dentry *src, struct cred **new)
3573 {
3574         u32 sid;
3575         struct task_security_struct *tsec;
3576         struct cred *new_creds = *new;
3577
3578         if (new_creds == NULL) {
3579                 new_creds = prepare_creds();
3580                 if (!new_creds)
3581                         return -ENOMEM;
3582         }
3583
3584         tsec = selinux_cred(new_creds);
3585         /* Get label from overlay inode and set it in create_sid */
3586         selinux_inode_getsecid(d_inode(src), &sid);
3587         tsec->create_sid = sid;
3588         *new = new_creds;
3589         return 0;
3590 }
3591
3592 static int selinux_inode_copy_up_xattr(const char *name)
3593 {
3594         /* The copy_up hook above sets the initial context on an inode, but we
3595          * don't then want to overwrite it by blindly copying all the lower
3596          * xattrs up.  Instead, we have to filter out SELinux-related xattrs.
3597          */
3598         if (strcmp(name, XATTR_NAME_SELINUX) == 0)
3599                 return 1; /* Discard */
3600         /*
3601          * Any other attribute apart from SELINUX is not claimed, supported
3602          * by selinux.
3603          */
3604         return -EOPNOTSUPP;
3605 }
3606
3607 /* kernfs node operations */
3608
3609 static int selinux_kernfs_init_security(struct kernfs_node *kn_dir,
3610                                         struct kernfs_node *kn)
3611 {
3612         const struct task_security_struct *tsec = selinux_cred(current_cred());
3613         u32 parent_sid, newsid, clen;
3614         int rc;
3615         char *context;
3616
3617         rc = kernfs_xattr_get(kn_dir, XATTR_NAME_SELINUX, NULL, 0);
3618         if (rc == -ENODATA)
3619                 return 0;
3620         else if (rc < 0)
3621                 return rc;
3622
3623         clen = (u32)rc;
3624         context = kmalloc(clen, GFP_KERNEL);
3625         if (!context)
3626                 return -ENOMEM;
3627
3628         rc = kernfs_xattr_get(kn_dir, XATTR_NAME_SELINUX, context, clen);
3629         if (rc < 0) {
3630                 kfree(context);
3631                 return rc;
3632         }
3633
3634         rc = security_context_to_sid(&selinux_state, context, clen, &parent_sid,
3635                                      GFP_KERNEL);
3636         kfree(context);
3637         if (rc)
3638                 return rc;
3639
3640         if (tsec->create_sid) {
3641                 newsid = tsec->create_sid;
3642         } else {
3643                 u16 secclass = inode_mode_to_security_class(kn->mode);
3644                 struct qstr q;
3645
3646                 q.name = kn->name;
3647                 q.hash_len = hashlen_string(kn_dir, kn->name);
3648
3649                 rc = security_transition_sid(&selinux_state, tsec->sid,
3650                                              parent_sid, secclass, &q,
3651                                              &newsid);
3652                 if (rc)
3653                         return rc;
3654         }
3655
3656         rc = security_sid_to_context_force(&selinux_state, newsid,
3657                                            &context, &clen);
3658         if (rc)
3659                 return rc;
3660
3661         rc = kernfs_xattr_set(kn, XATTR_NAME_SELINUX, context, clen,
3662                               XATTR_CREATE);
3663         kfree(context);
3664         return rc;
3665 }
3666
3667
3668 /* file security operations */
3669
3670 static int selinux_revalidate_file_permission(struct file *file, int mask)
3671 {
3672         const struct cred *cred = current_cred();
3673         struct inode *inode = file_inode(file);
3674
3675         /* file_mask_to_av won't add FILE__WRITE if MAY_APPEND is set */
3676         if ((file->f_flags & O_APPEND) && (mask & MAY_WRITE))
3677                 mask |= MAY_APPEND;
3678
3679         return file_has_perm(cred, file,
3680                              file_mask_to_av(inode->i_mode, mask));
3681 }
3682
3683 static int selinux_file_permission(struct file *file, int mask)
3684 {
3685         struct inode *inode = file_inode(file);
3686         struct file_security_struct *fsec = selinux_file(file);
3687         struct inode_security_struct *isec;
3688         u32 sid = current_sid();
3689
3690         if (!mask)
3691                 /* No permission to check.  Existence test. */
3692                 return 0;
3693
3694         isec = inode_security(inode);
3695         if (sid == fsec->sid && fsec->isid == isec->sid &&
3696             fsec->pseqno == avc_policy_seqno(&selinux_state))
3697                 /* No change since file_open check. */
3698                 return 0;
3699
3700         return selinux_revalidate_file_permission(file, mask);
3701 }
3702
3703 static int selinux_file_alloc_security(struct file *file)
3704 {
3705         struct file_security_struct *fsec = selinux_file(file);
3706         u32 sid = current_sid();
3707
3708         fsec->sid = sid;
3709         fsec->fown_sid = sid;
3710
3711         return 0;
3712 }
3713
3714 /*
3715  * Check whether a task has the ioctl permission and cmd
3716  * operation to an inode.
3717  */
3718 static int ioctl_has_perm(const struct cred *cred, struct file *file,
3719                 u32 requested, u16 cmd)
3720 {
3721         struct common_audit_data ad;
3722         struct file_security_struct *fsec = selinux_file(file);
3723         struct inode *inode = file_inode(file);
3724         struct inode_security_struct *isec;
3725         struct lsm_ioctlop_audit ioctl;
3726         u32 ssid = cred_sid(cred);
3727         int rc;
3728         u8 driver = cmd >> 8;
3729         u8 xperm = cmd & 0xff;
3730
3731         ad.type = LSM_AUDIT_DATA_IOCTL_OP;
3732         ad.u.op = &ioctl;
3733         ad.u.op->cmd = cmd;
3734         ad.u.op->path = file->f_path;
3735
3736         if (ssid != fsec->sid) {
3737                 rc = avc_has_perm(&selinux_state,
3738                                   ssid, fsec->sid,
3739                                 SECCLASS_FD,
3740                                 FD__USE,
3741                                 &ad);
3742                 if (rc)
3743                         goto out;
3744         }
3745
3746         if (unlikely(IS_PRIVATE(inode)))
3747                 return 0;
3748
3749         isec = inode_security(inode);
3750         rc = avc_has_extended_perms(&selinux_state,
3751                                     ssid, isec->sid, isec->sclass,
3752                                     requested, driver, xperm, &ad);
3753 out:
3754         return rc;
3755 }
3756
3757 static int selinux_file_ioctl(struct file *file, unsigned int cmd,
3758                               unsigned long arg)
3759 {
3760         const struct cred *cred = current_cred();
3761         int error = 0;
3762
3763         switch (cmd) {
3764         case FIONREAD:
3765         case FIBMAP:
3766         case FIGETBSZ:
3767         case FS_IOC_GETFLAGS:
3768         case FS_IOC_GETVERSION:
3769                 error = file_has_perm(cred, file, FILE__GETATTR);
3770                 break;
3771
3772         case FS_IOC_SETFLAGS:
3773         case FS_IOC_SETVERSION:
3774                 error = file_has_perm(cred, file, FILE__SETATTR);
3775                 break;
3776
3777         /* sys_ioctl() checks */
3778         case FIONBIO:
3779         case FIOASYNC:
3780                 error = file_has_perm(cred, file, 0);
3781                 break;
3782
3783         case KDSKBENT:
3784         case KDSKBSENT:
3785                 error = cred_has_capability(cred, CAP_SYS_TTY_CONFIG,
3786                                             CAP_OPT_NONE, true);
3787                 break;
3788
3789         /* default case assumes that the command will go
3790          * to the file's ioctl() function.
3791          */
3792         default:
3793                 error = ioctl_has_perm(cred, file, FILE__IOCTL, (u16) cmd);
3794         }
3795         return error;
3796 }
3797
3798 static int default_noexec __ro_after_init;
3799
3800 static int file_map_prot_check(struct file *file, unsigned long prot, int shared)
3801 {
3802         const struct cred *cred = current_cred();
3803         u32 sid = cred_sid(cred);
3804         int rc = 0;
3805
3806         if (default_noexec &&
3807             (prot & PROT_EXEC) && (!file || IS_PRIVATE(file_inode(file)) ||
3808                                    (!shared && (prot & PROT_WRITE)))) {
3809                 /*
3810                  * We are making executable an anonymous mapping or a
3811                  * private file mapping that will also be writable.
3812                  * This has an additional check.
3813                  */
3814                 rc = avc_has_perm(&selinux_state,
3815                                   sid, sid, SECCLASS_PROCESS,
3816                                   PROCESS__EXECMEM, NULL);
3817                 if (rc)
3818                         goto error;
3819         }
3820
3821         if (file) {
3822                 /* read access is always possible with a mapping */
3823                 u32 av = FILE__READ;
3824
3825                 /* write access only matters if the mapping is shared */
3826                 if (shared && (prot & PROT_WRITE))
3827                         av |= FILE__WRITE;
3828
3829                 if (prot & PROT_EXEC)
3830                         av |= FILE__EXECUTE;
3831
3832                 return file_has_perm(cred, file, av);
3833         }
3834
3835 error:
3836         return rc;
3837 }
3838
3839 static int selinux_mmap_addr(unsigned long addr)
3840 {
3841         int rc = 0;
3842
3843         if (addr < CONFIG_LSM_MMAP_MIN_ADDR) {
3844                 u32 sid = current_sid();
3845                 rc = avc_has_perm(&selinux_state,
3846                                   sid, sid, SECCLASS_MEMPROTECT,
3847                                   MEMPROTECT__MMAP_ZERO, NULL);
3848         }
3849
3850         return rc;
3851 }
3852
3853 static int selinux_mmap_file(struct file *file, unsigned long reqprot,
3854                              unsigned long prot, unsigned long flags)
3855 {
3856         struct common_audit_data ad;
3857         int rc;
3858
3859         if (file) {
3860                 ad.type = LSM_AUDIT_DATA_FILE;
3861                 ad.u.file = file;
3862                 rc = inode_has_perm(current_cred(), file_inode(file),
3863                                     FILE__MAP, &ad);
3864                 if (rc)
3865                         return rc;
3866         }
3867
3868         if (checkreqprot_get(&selinux_state))
3869                 prot = reqprot;
3870
3871         return file_map_prot_check(file, prot,
3872                                    (flags & MAP_TYPE) == MAP_SHARED);
3873 }
3874
3875 static int selinux_file_mprotect(struct vm_area_struct *vma,
3876                                  unsigned long reqprot,
3877                                  unsigned long prot)
3878 {
3879         const struct cred *cred = current_cred();
3880         u32 sid = cred_sid(cred);
3881
3882         if (checkreqprot_get(&selinux_state))
3883                 prot = reqprot;
3884
3885         if (default_noexec &&
3886             (prot & PROT_EXEC) && !(vma->vm_flags & VM_EXEC)) {
3887                 int rc = 0;
3888                 if (vma->vm_start >= vma->vm_mm->start_brk &&
3889                     vma->vm_end <= vma->vm_mm->brk) {
3890                         rc = avc_has_perm(&selinux_state,
3891                                           sid, sid, SECCLASS_PROCESS,
3892                                           PROCESS__EXECHEAP, NULL);
3893                 } else if (!vma->vm_file &&
3894                            ((vma->vm_start <= vma->vm_mm->start_stack &&
3895                              vma->vm_end >= vma->vm_mm->start_stack) ||
3896                             vma_is_stack_for_current(vma))) {
3897                         rc = avc_has_perm(&selinux_state,
3898                                           sid, sid, SECCLASS_PROCESS,
3899                                           PROCESS__EXECSTACK, NULL);
3900                 } else if (vma->vm_file && vma->anon_vma) {
3901                         /*
3902                          * We are making executable a file mapping that has
3903                          * had some COW done. Since pages might have been
3904                          * written, check ability to execute the possibly
3905                          * modified content.  This typically should only
3906                          * occur for text relocations.
3907                          */
3908                         rc = file_has_perm(cred, vma->vm_file, FILE__EXECMOD);
3909                 }
3910                 if (rc)
3911                         return rc;
3912         }
3913
3914         return file_map_prot_check(vma->vm_file, prot, vma->vm_flags&VM_SHARED);
3915 }
3916
3917 static int selinux_file_lock(struct file *file, unsigned int cmd)
3918 {
3919         const struct cred *cred = current_cred();
3920
3921         return file_has_perm(cred, file, FILE__LOCK);
3922 }
3923
3924 static int selinux_file_fcntl(struct file *file, unsigned int cmd,
3925                               unsigned long arg)
3926 {
3927         const struct cred *cred = current_cred();
3928         int err = 0;
3929
3930         switch (cmd) {
3931         case F_SETFL:
3932                 if ((file->f_flags & O_APPEND) && !(arg & O_APPEND)) {
3933                         err = file_has_perm(cred, file, FILE__WRITE);
3934                         break;
3935                 }
3936                 fallthrough;
3937         case F_SETOWN:
3938         case F_SETSIG:
3939         case F_GETFL:
3940         case F_GETOWN:
3941         case F_GETSIG:
3942         case F_GETOWNER_UIDS:
3943                 /* Just check FD__USE permission */
3944                 err = file_has_perm(cred, file, 0);
3945                 break;
3946         case F_GETLK:
3947         case F_SETLK:
3948         case F_SETLKW:
3949         case F_OFD_GETLK:
3950         case F_OFD_SETLK:
3951         case F_OFD_SETLKW:
3952 #if BITS_PER_LONG == 32
3953         case F_GETLK64:
3954         case F_SETLK64:
3955         case F_SETLKW64:
3956 #endif
3957                 err = file_has_perm(cred, file, FILE__LOCK);
3958                 break;
3959         }
3960
3961         return err;
3962 }
3963
3964 static void selinux_file_set_fowner(struct file *file)
3965 {
3966         struct file_security_struct *fsec;
3967
3968         fsec = selinux_file(file);
3969         fsec->fown_sid = current_sid();
3970 }
3971
3972 static int selinux_file_send_sigiotask(struct task_struct *tsk,
3973                                        struct fown_struct *fown, int signum)
3974 {
3975         struct file *file;
3976         u32 sid = task_sid_obj(tsk);
3977         u32 perm;
3978         struct file_security_struct *fsec;
3979
3980         /* struct fown_struct is never outside the context of a struct file */
3981         file = container_of(fown, struct file, f_owner);
3982
3983         fsec = selinux_file(file);
3984
3985         if (!signum)
3986                 perm = signal_to_av(SIGIO); /* as per send_sigio_to_task */
3987         else
3988                 perm = signal_to_av(signum);
3989
3990         return avc_has_perm(&selinux_state,
3991                             fsec->fown_sid, sid,
3992                             SECCLASS_PROCESS, perm, NULL);
3993 }
3994
3995 static int selinux_file_receive(struct file *file)
3996 {
3997         const struct cred *cred = current_cred();
3998
3999         return file_has_perm(cred, file, file_to_av(file));
4000 }
4001
4002 static int selinux_file_open(struct file *file)
4003 {
4004         struct file_security_struct *fsec;
4005         struct inode_security_struct *isec;
4006
4007         fsec = selinux_file(file);
4008         isec = inode_security(file_inode(file));
4009         /*
4010          * Save inode label and policy sequence number
4011          * at open-time so that selinux_file_permission
4012          * can determine whether revalidation is necessary.
4013          * Task label is already saved in the file security
4014          * struct as its SID.
4015          */
4016         fsec->isid = isec->sid;
4017         fsec->pseqno = avc_policy_seqno(&selinux_state);
4018         /*
4019          * Since the inode label or policy seqno may have changed
4020          * between the selinux_inode_permission check and the saving
4021          * of state above, recheck that access is still permitted.
4022          * Otherwise, access might never be revalidated against the
4023          * new inode label or new policy.
4024          * This check is not redundant - do not remove.
4025          */
4026         return file_path_has_perm(file->f_cred, file, open_file_to_av(file));
4027 }
4028
4029 /* task security operations */
4030
4031 static int selinux_task_alloc(struct task_struct *task,
4032                               unsigned long clone_flags)
4033 {
4034         u32 sid = current_sid();
4035
4036         return avc_has_perm(&selinux_state,
4037                             sid, sid, SECCLASS_PROCESS, PROCESS__FORK, NULL);
4038 }
4039
4040 /*
4041  * prepare a new set of credentials for modification
4042  */
4043 static int selinux_cred_prepare(struct cred *new, const struct cred *old,
4044                                 gfp_t gfp)
4045 {
4046         const struct task_security_struct *old_tsec = selinux_cred(old);
4047         struct task_security_struct *tsec = selinux_cred(new);
4048
4049         *tsec = *old_tsec;
4050         return 0;
4051 }
4052
4053 /*
4054  * transfer the SELinux data to a blank set of creds
4055  */
4056 static void selinux_cred_transfer(struct cred *new, const struct cred *old)
4057 {
4058         const struct task_security_struct *old_tsec = selinux_cred(old);
4059         struct task_security_struct *tsec = selinux_cred(new);
4060
4061         *tsec = *old_tsec;
4062 }
4063
4064 static void selinux_cred_getsecid(const struct cred *c, u32 *secid)
4065 {
4066         *secid = cred_sid(c);
4067 }
4068
4069 /*
4070  * set the security data for a kernel service
4071  * - all the creation contexts are set to unlabelled
4072  */
4073 static int selinux_kernel_act_as(struct cred *new, u32 secid)
4074 {
4075         struct task_security_struct *tsec = selinux_cred(new);
4076         u32 sid = current_sid();
4077         int ret;
4078
4079         ret = avc_has_perm(&selinux_state,
4080                            sid, secid,
4081                            SECCLASS_KERNEL_SERVICE,
4082                            KERNEL_SERVICE__USE_AS_OVERRIDE,
4083                            NULL);
4084         if (ret == 0) {
4085                 tsec->sid = secid;
4086                 tsec->create_sid = 0;
4087                 tsec->keycreate_sid = 0;
4088                 tsec->sockcreate_sid = 0;
4089         }
4090         return ret;
4091 }
4092
4093 /*
4094  * set the file creation context in a security record to the same as the
4095  * objective context of the specified inode
4096  */
4097 static int selinux_kernel_create_files_as(struct cred *new, struct inode *inode)
4098 {
4099         struct inode_security_struct *isec = inode_security(inode);
4100         struct task_security_struct *tsec = selinux_cred(new);
4101         u32 sid = current_sid();
4102         int ret;
4103
4104         ret = avc_has_perm(&selinux_state,
4105                            sid, isec->sid,
4106                            SECCLASS_KERNEL_SERVICE,
4107                            KERNEL_SERVICE__CREATE_FILES_AS,
4108                            NULL);
4109
4110         if (ret == 0)
4111                 tsec->create_sid = isec->sid;
4112         return ret;
4113 }
4114
4115 static int selinux_kernel_module_request(char *kmod_name)
4116 {
4117         struct common_audit_data ad;
4118
4119         ad.type = LSM_AUDIT_DATA_KMOD;
4120         ad.u.kmod_name = kmod_name;
4121
4122         return avc_has_perm(&selinux_state,
4123                             current_sid(), SECINITSID_KERNEL, SECCLASS_SYSTEM,
4124                             SYSTEM__MODULE_REQUEST, &ad);
4125 }
4126
4127 static int selinux_kernel_module_from_file(struct file *file)
4128 {
4129         struct common_audit_data ad;
4130         struct inode_security_struct *isec;
4131         struct file_security_struct *fsec;
4132         u32 sid = current_sid();
4133         int rc;
4134
4135         /* init_module */
4136         if (file == NULL)
4137                 return avc_has_perm(&selinux_state,
4138                                     sid, sid, SECCLASS_SYSTEM,
4139                                         SYSTEM__MODULE_LOAD, NULL);
4140
4141         /* finit_module */
4142
4143         ad.type = LSM_AUDIT_DATA_FILE;
4144         ad.u.file = file;
4145
4146         fsec = selinux_file(file);
4147         if (sid != fsec->sid) {
4148                 rc = avc_has_perm(&selinux_state,
4149                                   sid, fsec->sid, SECCLASS_FD, FD__USE, &ad);
4150                 if (rc)
4151                         return rc;
4152         }
4153
4154         isec = inode_security(file_inode(file));
4155         return avc_has_perm(&selinux_state,
4156                             sid, isec->sid, SECCLASS_SYSTEM,
4157                                 SYSTEM__MODULE_LOAD, &ad);
4158 }
4159
4160 static int selinux_kernel_read_file(struct file *file,
4161                                     enum kernel_read_file_id id,
4162                                     bool contents)
4163 {
4164         int rc = 0;
4165
4166         switch (id) {
4167         case READING_MODULE:
4168                 rc = selinux_kernel_module_from_file(contents ? file : NULL);
4169                 break;
4170         default:
4171                 break;
4172         }
4173
4174         return rc;
4175 }
4176
4177 static int selinux_kernel_load_data(enum kernel_load_data_id id, bool contents)
4178 {
4179         int rc = 0;
4180
4181         switch (id) {
4182         case LOADING_MODULE:
4183                 rc = selinux_kernel_module_from_file(NULL);
4184                 break;
4185         default:
4186                 break;
4187         }
4188
4189         return rc;
4190 }
4191
4192 static int selinux_task_setpgid(struct task_struct *p, pid_t pgid)
4193 {
4194         return avc_has_perm(&selinux_state,
4195                             current_sid(), task_sid_obj(p), SECCLASS_PROCESS,
4196                             PROCESS__SETPGID, NULL);
4197 }
4198
4199 static int selinux_task_getpgid(struct task_struct *p)
4200 {
4201         return avc_has_perm(&selinux_state,
4202                             current_sid(), task_sid_obj(p), SECCLASS_PROCESS,
4203                             PROCESS__GETPGID, NULL);
4204 }
4205
4206 static int selinux_task_getsid(struct task_struct *p)
4207 {
4208         return avc_has_perm(&selinux_state,
4209                             current_sid(), task_sid_obj(p), SECCLASS_PROCESS,
4210                             PROCESS__GETSESSION, NULL);
4211 }
4212
4213 static void selinux_task_getsecid_subj(struct task_struct *p, u32 *secid)
4214 {
4215         *secid = task_sid_subj(p);
4216 }
4217
4218 static void selinux_task_getsecid_obj(struct task_struct *p, u32 *secid)
4219 {
4220         *secid = task_sid_obj(p);
4221 }
4222
4223 static int selinux_task_setnice(struct task_struct *p, int nice)
4224 {
4225         return avc_has_perm(&selinux_state,
4226                             current_sid(), task_sid_obj(p), SECCLASS_PROCESS,
4227                             PROCESS__SETSCHED, NULL);
4228 }
4229
4230 static int selinux_task_setioprio(struct task_struct *p, int ioprio)
4231 {
4232         return avc_has_perm(&selinux_state,
4233                             current_sid(), task_sid_obj(p), SECCLASS_PROCESS,
4234                             PROCESS__SETSCHED, NULL);
4235 }
4236
4237 static int selinux_task_getioprio(struct task_struct *p)
4238 {
4239         return avc_has_perm(&selinux_state,
4240                             current_sid(), task_sid_obj(p), SECCLASS_PROCESS,
4241                             PROCESS__GETSCHED, NULL);
4242 }
4243
4244 static int selinux_task_prlimit(const struct cred *cred, const struct cred *tcred,
4245                                 unsigned int flags)
4246 {
4247         u32 av = 0;
4248
4249         if (!flags)
4250                 return 0;
4251         if (flags & LSM_PRLIMIT_WRITE)
4252                 av |= PROCESS__SETRLIMIT;
4253         if (flags & LSM_PRLIMIT_READ)
4254                 av |= PROCESS__GETRLIMIT;
4255         return avc_has_perm(&selinux_state,
4256                             cred_sid(cred), cred_sid(tcred),
4257                             SECCLASS_PROCESS, av, NULL);
4258 }
4259
4260 static int selinux_task_setrlimit(struct task_struct *p, unsigned int resource,
4261                 struct rlimit *new_rlim)
4262 {
4263         struct rlimit *old_rlim = p->signal->rlim + resource;
4264
4265         /* Control the ability to change the hard limit (whether
4266            lowering or raising it), so that the hard limit can
4267            later be used as a safe reset point for the soft limit
4268            upon context transitions.  See selinux_bprm_committing_creds. */
4269         if (old_rlim->rlim_max != new_rlim->rlim_max)
4270                 return avc_has_perm(&selinux_state,
4271                                     current_sid(), task_sid_obj(p),
4272                                     SECCLASS_PROCESS, PROCESS__SETRLIMIT, NULL);
4273
4274         return 0;
4275 }
4276
4277 static int selinux_task_setscheduler(struct task_struct *p)
4278 {
4279         return avc_has_perm(&selinux_state,
4280                             current_sid(), task_sid_obj(p), SECCLASS_PROCESS,
4281                             PROCESS__SETSCHED, NULL);
4282 }
4283
4284 static int selinux_task_getscheduler(struct task_struct *p)
4285 {
4286         return avc_has_perm(&selinux_state,
4287                             current_sid(), task_sid_obj(p), SECCLASS_PROCESS,
4288                             PROCESS__GETSCHED, NULL);
4289 }
4290
4291 static int selinux_task_movememory(struct task_struct *p)
4292 {
4293         return avc_has_perm(&selinux_state,
4294                             current_sid(), task_sid_obj(p), SECCLASS_PROCESS,
4295                             PROCESS__SETSCHED, NULL);
4296 }
4297
4298 static int selinux_task_kill(struct task_struct *p, struct kernel_siginfo *info,
4299                                 int sig, const struct cred *cred)
4300 {
4301         u32 secid;
4302         u32 perm;
4303
4304         if (!sig)
4305                 perm = PROCESS__SIGNULL; /* null signal; existence test */
4306         else
4307                 perm = signal_to_av(sig);
4308         if (!cred)
4309                 secid = current_sid();
4310         else
4311                 secid = cred_sid(cred);
4312         return avc_has_perm(&selinux_state,
4313                             secid, task_sid_obj(p), SECCLASS_PROCESS, perm, NULL);
4314 }
4315
4316 static void selinux_task_to_inode(struct task_struct *p,
4317                                   struct inode *inode)
4318 {
4319         struct inode_security_struct *isec = selinux_inode(inode);
4320         u32 sid = task_sid_obj(p);
4321
4322         spin_lock(&isec->lock);
4323         isec->sclass = inode_mode_to_security_class(inode->i_mode);
4324         isec->sid = sid;
4325         isec->initialized = LABEL_INITIALIZED;
4326         spin_unlock(&isec->lock);
4327 }
4328
4329 /* Returns error only if unable to parse addresses */
4330 static int selinux_parse_skb_ipv4(struct sk_buff *skb,
4331                         struct common_audit_data *ad, u8 *proto)
4332 {
4333         int offset, ihlen, ret = -EINVAL;
4334         struct iphdr _iph, *ih;
4335
4336         offset = skb_network_offset(skb);
4337         ih = skb_header_pointer(skb, offset, sizeof(_iph), &_iph);
4338         if (ih == NULL)
4339                 goto out;
4340
4341         ihlen = ih->ihl * 4;
4342         if (ihlen < sizeof(_iph))
4343                 goto out;
4344
4345         ad->u.net->v4info.saddr = ih->saddr;
4346         ad->u.net->v4info.daddr = ih->daddr;
4347         ret = 0;
4348
4349         if (proto)
4350                 *proto = ih->protocol;
4351
4352         switch (ih->protocol) {
4353         case IPPROTO_TCP: {
4354                 struct tcphdr _tcph, *th;
4355
4356                 if (ntohs(ih->frag_off) & IP_OFFSET)
4357                         break;
4358
4359                 offset += ihlen;
4360                 th = skb_header_pointer(skb, offset, sizeof(_tcph), &_tcph);
4361                 if (th == NULL)
4362                         break;
4363
4364                 ad->u.net->sport = th->source;
4365                 ad->u.net->dport = th->dest;
4366                 break;
4367         }
4368
4369         case IPPROTO_UDP: {
4370                 struct udphdr _udph, *uh;
4371
4372                 if (ntohs(ih->frag_off) & IP_OFFSET)
4373                         break;
4374
4375                 offset += ihlen;
4376                 uh = skb_header_pointer(skb, offset, sizeof(_udph), &_udph);
4377                 if (uh == NULL)
4378                         break;
4379
4380                 ad->u.net->sport = uh->source;
4381                 ad->u.net->dport = uh->dest;
4382                 break;
4383         }
4384
4385         case IPPROTO_DCCP: {
4386                 struct dccp_hdr _dccph, *dh;
4387
4388                 if (ntohs(ih->frag_off) & IP_OFFSET)
4389                         break;
4390
4391                 offset += ihlen;
4392                 dh = skb_header_pointer(skb, offset, sizeof(_dccph), &_dccph);
4393                 if (dh == NULL)
4394                         break;
4395
4396                 ad->u.net->sport = dh->dccph_sport;
4397                 ad->u.net->dport = dh->dccph_dport;
4398                 break;
4399         }
4400
4401 #if IS_ENABLED(CONFIG_IP_SCTP)
4402         case IPPROTO_SCTP: {
4403                 struct sctphdr _sctph, *sh;
4404
4405                 if (ntohs(ih->frag_off) & IP_OFFSET)
4406                         break;
4407
4408                 offset += ihlen;
4409                 sh = skb_header_pointer(skb, offset, sizeof(_sctph), &_sctph);
4410                 if (sh == NULL)
4411                         break;
4412
4413                 ad->u.net->sport = sh->source;
4414                 ad->u.net->dport = sh->dest;
4415                 break;
4416         }
4417 #endif
4418         default:
4419                 break;
4420         }
4421 out:
4422         return ret;
4423 }
4424
4425 #if IS_ENABLED(CONFIG_IPV6)
4426
4427 /* Returns error only if unable to parse addresses */
4428 static int selinux_parse_skb_ipv6(struct sk_buff *skb,
4429                         struct common_audit_data *ad, u8 *proto)
4430 {
4431         u8 nexthdr;
4432         int ret = -EINVAL, offset;
4433         struct ipv6hdr _ipv6h, *ip6;
4434         __be16 frag_off;
4435
4436         offset = skb_network_offset(skb);
4437         ip6 = skb_header_pointer(skb, offset, sizeof(_ipv6h), &_ipv6h);
4438         if (ip6 == NULL)
4439                 goto out;
4440
4441         ad->u.net->v6info.saddr = ip6->saddr;
4442         ad->u.net->v6info.daddr = ip6->daddr;
4443         ret = 0;
4444
4445         nexthdr = ip6->nexthdr;
4446         offset += sizeof(_ipv6h);
4447         offset = ipv6_skip_exthdr(skb, offset, &nexthdr, &frag_off);
4448         if (offset < 0)
4449                 goto out;
4450
4451         if (proto)
4452                 *proto = nexthdr;
4453
4454         switch (nexthdr) {
4455         case IPPROTO_TCP: {
4456                 struct tcphdr _tcph, *th;
4457
4458                 th = skb_header_pointer(skb, offset, sizeof(_tcph), &_tcph);
4459                 if (th == NULL)
4460                         break;
4461
4462                 ad->u.net->sport = th->source;
4463                 ad->u.net->dport = th->dest;
4464                 break;
4465         }
4466
4467         case IPPROTO_UDP: {
4468                 struct udphdr _udph, *uh;
4469
4470                 uh = skb_header_pointer(skb, offset, sizeof(_udph), &_udph);
4471                 if (uh == NULL)
4472                         break;
4473
4474                 ad->u.net->sport = uh->source;
4475                 ad->u.net->dport = uh->dest;
4476                 break;
4477         }
4478
4479         case IPPROTO_DCCP: {
4480                 struct dccp_hdr _dccph, *dh;
4481
4482                 dh = skb_header_pointer(skb, offset, sizeof(_dccph), &_dccph);
4483                 if (dh == NULL)
4484                         break;
4485
4486                 ad->u.net->sport = dh->dccph_sport;
4487                 ad->u.net->dport = dh->dccph_dport;
4488                 break;
4489         }
4490
4491 #if IS_ENABLED(CONFIG_IP_SCTP)
4492         case IPPROTO_SCTP: {
4493                 struct sctphdr _sctph, *sh;
4494
4495                 sh = skb_header_pointer(skb, offset, sizeof(_sctph), &_sctph);
4496                 if (sh == NULL)
4497                         break;
4498
4499                 ad->u.net->sport = sh->source;
4500                 ad->u.net->dport = sh->dest;
4501                 break;
4502         }
4503 #endif
4504         /* includes fragments */
4505         default:
4506                 break;
4507         }
4508 out:
4509         return ret;
4510 }
4511
4512 #endif /* IPV6 */
4513
4514 static int selinux_parse_skb(struct sk_buff *skb, struct common_audit_data *ad,
4515                              char **_addrp, int src, u8 *proto)
4516 {
4517         char *addrp;
4518         int ret;
4519
4520         switch (ad->u.net->family) {
4521         case PF_INET:
4522                 ret = selinux_parse_skb_ipv4(skb, ad, proto);
4523                 if (ret)
4524                         goto parse_error;
4525                 addrp = (char *)(src ? &ad->u.net->v4info.saddr :
4526                                        &ad->u.net->v4info.daddr);
4527                 goto okay;
4528
4529 #if IS_ENABLED(CONFIG_IPV6)
4530         case PF_INET6:
4531                 ret = selinux_parse_skb_ipv6(skb, ad, proto);
4532                 if (ret)
4533                         goto parse_error;
4534                 addrp = (char *)(src ? &ad->u.net->v6info.saddr :
4535                                        &ad->u.net->v6info.daddr);
4536                 goto okay;
4537 #endif  /* IPV6 */
4538         default:
4539                 addrp = NULL;
4540                 goto okay;
4541         }
4542
4543 parse_error:
4544         pr_warn(
4545                "SELinux: failure in selinux_parse_skb(),"
4546                " unable to parse packet\n");
4547         return ret;
4548
4549 okay:
4550         if (_addrp)
4551                 *_addrp = addrp;
4552         return 0;
4553 }
4554
4555 /**
4556  * selinux_skb_peerlbl_sid - Determine the peer label of a packet
4557  * @skb: the packet
4558  * @family: protocol family
4559  * @sid: the packet's peer label SID
4560  *
4561  * Description:
4562  * Check the various different forms of network peer labeling and determine
4563  * the peer label/SID for the packet; most of the magic actually occurs in
4564  * the security server function security_net_peersid_cmp().  The function
4565  * returns zero if the value in @sid is valid (although it may be SECSID_NULL)
4566  * or -EACCES if @sid is invalid due to inconsistencies with the different
4567  * peer labels.
4568  *
4569  */
4570 static int selinux_skb_peerlbl_sid(struct sk_buff *skb, u16 family, u32 *sid)
4571 {
4572         int err;
4573         u32 xfrm_sid;
4574         u32 nlbl_sid;
4575         u32 nlbl_type;
4576
4577         err = selinux_xfrm_skb_sid(skb, &xfrm_sid);
4578         if (unlikely(err))
4579                 return -EACCES;
4580         err = selinux_netlbl_skbuff_getsid(skb, family, &nlbl_type, &nlbl_sid);
4581         if (unlikely(err))
4582                 return -EACCES;
4583
4584         err = security_net_peersid_resolve(&selinux_state, nlbl_sid,
4585                                            nlbl_type, xfrm_sid, sid);
4586         if (unlikely(err)) {
4587                 pr_warn(
4588                        "SELinux: failure in selinux_skb_peerlbl_sid(),"
4589                        " unable to determine packet's peer label\n");
4590                 return -EACCES;
4591         }
4592
4593         return 0;
4594 }
4595
4596 /**
4597  * selinux_conn_sid - Determine the child socket label for a connection
4598  * @sk_sid: the parent socket's SID
4599  * @skb_sid: the packet's SID
4600  * @conn_sid: the resulting connection SID
4601  *
4602  * If @skb_sid is valid then the user:role:type information from @sk_sid is
4603  * combined with the MLS information from @skb_sid in order to create
4604  * @conn_sid.  If @skb_sid is not valid then @conn_sid is simply a copy
4605  * of @sk_sid.  Returns zero on success, negative values on failure.
4606  *
4607  */
4608 static int selinux_conn_sid(u32 sk_sid, u32 skb_sid, u32 *conn_sid)
4609 {
4610         int err = 0;
4611
4612         if (skb_sid != SECSID_NULL)
4613                 err = security_sid_mls_copy(&selinux_state, sk_sid, skb_sid,
4614                                             conn_sid);
4615         else
4616                 *conn_sid = sk_sid;
4617
4618         return err;
4619 }
4620
4621 /* socket security operations */
4622
4623 static int socket_sockcreate_sid(const struct task_security_struct *tsec,
4624                                  u16 secclass, u32 *socksid)
4625 {
4626         if (tsec->sockcreate_sid > SECSID_NULL) {
4627                 *socksid = tsec->sockcreate_sid;
4628                 return 0;
4629         }
4630
4631         return security_transition_sid(&selinux_state, tsec->sid, tsec->sid,
4632                                        secclass, NULL, socksid);
4633 }
4634
4635 static int sock_has_perm(struct sock *sk, u32 perms)
4636 {
4637         struct sk_security_struct *sksec = sk->sk_security;
4638         struct common_audit_data ad;
4639         struct lsm_network_audit net = {0,};
4640
4641         if (sksec->sid == SECINITSID_KERNEL)
4642                 return 0;
4643
4644         ad.type = LSM_AUDIT_DATA_NET;
4645         ad.u.net = &net;
4646         ad.u.net->sk = sk;
4647
4648         return avc_has_perm(&selinux_state,
4649                             current_sid(), sksec->sid, sksec->sclass, perms,
4650                             &ad);
4651 }
4652
4653 static int selinux_socket_create(int family, int type,
4654                                  int protocol, int kern)
4655 {
4656         const struct task_security_struct *tsec = selinux_cred(current_cred());
4657         u32 newsid;
4658         u16 secclass;
4659         int rc;
4660
4661         if (kern)
4662                 return 0;
4663
4664         secclass = socket_type_to_security_class(family, type, protocol);
4665         rc = socket_sockcreate_sid(tsec, secclass, &newsid);
4666         if (rc)
4667                 return rc;
4668
4669         return avc_has_perm(&selinux_state,
4670                             tsec->sid, newsid, secclass, SOCKET__CREATE, NULL);
4671 }
4672
4673 static int selinux_socket_post_create(struct socket *sock, int family,
4674                                       int type, int protocol, int kern)
4675 {
4676         const struct task_security_struct *tsec = selinux_cred(current_cred());
4677         struct inode_security_struct *isec = inode_security_novalidate(SOCK_INODE(sock));
4678         struct sk_security_struct *sksec;
4679         u16 sclass = socket_type_to_security_class(family, type, protocol);
4680         u32 sid = SECINITSID_KERNEL;
4681         int err = 0;
4682
4683         if (!kern) {
4684                 err = socket_sockcreate_sid(tsec, sclass, &sid);
4685                 if (err)
4686                         return err;
4687         }
4688
4689         isec->sclass = sclass;
4690         isec->sid = sid;
4691         isec->initialized = LABEL_INITIALIZED;
4692
4693         if (sock->sk) {
4694                 sksec = sock->sk->sk_security;
4695                 sksec->sclass = sclass;
4696                 sksec->sid = sid;
4697                 /* Allows detection of the first association on this socket */
4698                 if (sksec->sclass == SECCLASS_SCTP_SOCKET)
4699                         sksec->sctp_assoc_state = SCTP_ASSOC_UNSET;
4700
4701                 err = selinux_netlbl_socket_post_create(sock->sk, family);
4702         }
4703
4704         return err;
4705 }
4706
4707 static int selinux_socket_socketpair(struct socket *socka,
4708                                      struct socket *sockb)
4709 {
4710         struct sk_security_struct *sksec_a = socka->sk->sk_security;
4711         struct sk_security_struct *sksec_b = sockb->sk->sk_security;
4712
4713         sksec_a->peer_sid = sksec_b->sid;
4714         sksec_b->peer_sid = sksec_a->sid;
4715
4716         return 0;
4717 }
4718
4719 /* Range of port numbers used to automatically bind.
4720    Need to determine whether we should perform a name_bind
4721    permission check between the socket and the port number. */
4722
4723 static int selinux_socket_bind(struct socket *sock, struct sockaddr *address, int addrlen)
4724 {
4725         struct sock *sk = sock->sk;
4726         struct sk_security_struct *sksec = sk->sk_security;
4727         u16 family;
4728         int err;
4729
4730         err = sock_has_perm(sk, SOCKET__BIND);
4731         if (err)
4732                 goto out;
4733
4734         /* If PF_INET or PF_INET6, check name_bind permission for the port. */
4735         family = sk->sk_family;
4736         if (family == PF_INET || family == PF_INET6) {
4737                 char *addrp;
4738                 struct common_audit_data ad;
4739                 struct lsm_network_audit net = {0,};
4740                 struct sockaddr_in *addr4 = NULL;
4741                 struct sockaddr_in6 *addr6 = NULL;
4742                 u16 family_sa;
4743                 unsigned short snum;
4744                 u32 sid, node_perm;
4745
4746                 /*
4747                  * sctp_bindx(3) calls via selinux_sctp_bind_connect()
4748                  * that validates multiple binding addresses. Because of this
4749                  * need to check address->sa_family as it is possible to have
4750                  * sk->sk_family = PF_INET6 with addr->sa_family = AF_INET.
4751                  */
4752                 if (addrlen < offsetofend(struct sockaddr, sa_family))
4753                         return -EINVAL;
4754                 family_sa = address->sa_family;
4755                 switch (family_sa) {
4756                 case AF_UNSPEC:
4757                 case AF_INET:
4758                         if (addrlen < sizeof(struct sockaddr_in))
4759                                 return -EINVAL;
4760                         addr4 = (struct sockaddr_in *)address;
4761                         if (family_sa == AF_UNSPEC) {
4762                                 /* see __inet_bind(), we only want to allow
4763                                  * AF_UNSPEC if the address is INADDR_ANY
4764                                  */
4765                                 if (addr4->sin_addr.s_addr != htonl(INADDR_ANY))
4766                                         goto err_af;
4767                                 family_sa = AF_INET;
4768                         }
4769                         snum = ntohs(addr4->sin_port);
4770                         addrp = (char *)&addr4->sin_addr.s_addr;
4771                         break;
4772                 case AF_INET6:
4773                         if (addrlen < SIN6_LEN_RFC2133)
4774                                 return -EINVAL;
4775                         addr6 = (struct sockaddr_in6 *)address;
4776                         snum = ntohs(addr6->sin6_port);
4777                         addrp = (char *)&addr6->sin6_addr.s6_addr;
4778                         break;
4779                 default:
4780                         goto err_af;
4781                 }
4782
4783                 ad.type = LSM_AUDIT_DATA_NET;
4784                 ad.u.net = &net;
4785                 ad.u.net->sport = htons(snum);
4786                 ad.u.net->family = family_sa;
4787
4788                 if (snum) {
4789                         int low, high;
4790
4791                         inet_get_local_port_range(sock_net(sk), &low, &high);
4792
4793                         if (inet_port_requires_bind_service(sock_net(sk), snum) ||
4794                             snum < low || snum > high) {
4795                                 err = sel_netport_sid(sk->sk_protocol,
4796                                                       snum, &sid);
4797                                 if (err)
4798                                         goto out;
4799                                 err = avc_has_perm(&selinux_state,
4800                                                    sksec->sid, sid,
4801                                                    sksec->sclass,
4802                                                    SOCKET__NAME_BIND, &ad);
4803                                 if (err)
4804                                         goto out;
4805                         }
4806                 }
4807
4808                 switch (sksec->sclass) {
4809                 case SECCLASS_TCP_SOCKET:
4810                         node_perm = TCP_SOCKET__NODE_BIND;
4811                         break;
4812
4813                 case SECCLASS_UDP_SOCKET:
4814                         node_perm = UDP_SOCKET__NODE_BIND;
4815                         break;
4816
4817                 case SECCLASS_DCCP_SOCKET:
4818                         node_perm = DCCP_SOCKET__NODE_BIND;
4819                         break;
4820
4821                 case SECCLASS_SCTP_SOCKET:
4822                         node_perm = SCTP_SOCKET__NODE_BIND;
4823                         break;
4824
4825                 default:
4826                         node_perm = RAWIP_SOCKET__NODE_BIND;
4827                         break;
4828                 }
4829
4830                 err = sel_netnode_sid(addrp, family_sa, &sid);
4831                 if (err)
4832                         goto out;
4833
4834                 if (family_sa == AF_INET)
4835                         ad.u.net->v4info.saddr = addr4->sin_addr.s_addr;
4836                 else
4837                         ad.u.net->v6info.saddr = addr6->sin6_addr;
4838
4839                 err = avc_has_perm(&selinux_state,
4840                                    sksec->sid, sid,
4841                                    sksec->sclass, node_perm, &ad);
4842                 if (err)
4843                         goto out;
4844         }
4845 out:
4846         return err;
4847 err_af:
4848         /* Note that SCTP services expect -EINVAL, others -EAFNOSUPPORT. */
4849         if (sksec->sclass == SECCLASS_SCTP_SOCKET)
4850                 return -EINVAL;
4851         return -EAFNOSUPPORT;
4852 }
4853
4854 /* This supports connect(2) and SCTP connect services such as sctp_connectx(3)
4855  * and sctp_sendmsg(3) as described in Documentation/security/SCTP.rst
4856  */
4857 static int selinux_socket_connect_helper(struct socket *sock,
4858                                          struct sockaddr *address, int addrlen)
4859 {
4860         struct sock *sk = sock->sk;
4861         struct sk_security_struct *sksec = sk->sk_security;
4862         int err;
4863
4864         err = sock_has_perm(sk, SOCKET__CONNECT);
4865         if (err)
4866                 return err;
4867         if (addrlen < offsetofend(struct sockaddr, sa_family))
4868                 return -EINVAL;
4869
4870         /* connect(AF_UNSPEC) has special handling, as it is a documented
4871          * way to disconnect the socket
4872          */
4873         if (address->sa_family == AF_UNSPEC)
4874                 return 0;
4875
4876         /*
4877          * If a TCP, DCCP or SCTP socket, check name_connect permission
4878          * for the port.
4879          */
4880         if (sksec->sclass == SECCLASS_TCP_SOCKET ||
4881             sksec->sclass == SECCLASS_DCCP_SOCKET ||
4882             sksec->sclass == SECCLASS_SCTP_SOCKET) {
4883                 struct common_audit_data ad;
4884                 struct lsm_network_audit net = {0,};
4885                 struct sockaddr_in *addr4 = NULL;
4886                 struct sockaddr_in6 *addr6 = NULL;
4887                 unsigned short snum;
4888                 u32 sid, perm;
4889
4890                 /* sctp_connectx(3) calls via selinux_sctp_bind_connect()
4891                  * that validates multiple connect addresses. Because of this
4892                  * need to check address->sa_family as it is possible to have
4893                  * sk->sk_family = PF_INET6 with addr->sa_family = AF_INET.
4894                  */
4895                 switch (address->sa_family) {
4896                 case AF_INET:
4897                         addr4 = (struct sockaddr_in *)address;
4898                         if (addrlen < sizeof(struct sockaddr_in))
4899                                 return -EINVAL;
4900                         snum = ntohs(addr4->sin_port);
4901                         break;
4902                 case AF_INET6:
4903                         addr6 = (struct sockaddr_in6 *)address;
4904                         if (addrlen < SIN6_LEN_RFC2133)
4905                                 return -EINVAL;
4906                         snum = ntohs(addr6->sin6_port);
4907                         break;
4908                 default:
4909                         /* Note that SCTP services expect -EINVAL, whereas
4910                          * others expect -EAFNOSUPPORT.
4911                          */
4912                         if (sksec->sclass == SECCLASS_SCTP_SOCKET)
4913                                 return -EINVAL;
4914                         else
4915                                 return -EAFNOSUPPORT;
4916                 }
4917
4918                 err = sel_netport_sid(sk->sk_protocol, snum, &sid);
4919                 if (err)
4920                         return err;
4921
4922                 switch (sksec->sclass) {
4923                 case SECCLASS_TCP_SOCKET:
4924                         perm = TCP_SOCKET__NAME_CONNECT;
4925                         break;
4926                 case SECCLASS_DCCP_SOCKET:
4927                         perm = DCCP_SOCKET__NAME_CONNECT;
4928                         break;
4929                 case SECCLASS_SCTP_SOCKET:
4930                         perm = SCTP_SOCKET__NAME_CONNECT;
4931                         break;
4932                 }
4933
4934                 ad.type = LSM_AUDIT_DATA_NET;
4935                 ad.u.net = &net;
4936                 ad.u.net->dport = htons(snum);
4937                 ad.u.net->family = address->sa_family;
4938                 err = avc_has_perm(&selinux_state,
4939                                    sksec->sid, sid, sksec->sclass, perm, &ad);
4940                 if (err)
4941                         return err;
4942         }
4943
4944         return 0;
4945 }
4946
4947 /* Supports connect(2), see comments in selinux_socket_connect_helper() */
4948 static int selinux_socket_connect(struct socket *sock,
4949                                   struct sockaddr *address, int addrlen)
4950 {
4951         int err;
4952         struct sock *sk = sock->sk;
4953
4954         err = selinux_socket_connect_helper(sock, address, addrlen);
4955         if (err)
4956                 return err;
4957
4958         return selinux_netlbl_socket_connect(sk, address);
4959 }
4960
4961 static int selinux_socket_listen(struct socket *sock, int backlog)
4962 {
4963         return sock_has_perm(sock->sk, SOCKET__LISTEN);
4964 }
4965
4966 static int selinux_socket_accept(struct socket *sock, struct socket *newsock)
4967 {
4968         int err;
4969         struct inode_security_struct *isec;
4970         struct inode_security_struct *newisec;
4971         u16 sclass;
4972         u32 sid;
4973
4974         err = sock_has_perm(sock->sk, SOCKET__ACCEPT);
4975         if (err)
4976                 return err;
4977
4978         isec = inode_security_novalidate(SOCK_INODE(sock));
4979         spin_lock(&isec->lock);
4980         sclass = isec->sclass;
4981         sid = isec->sid;
4982         spin_unlock(&isec->lock);
4983
4984         newisec = inode_security_novalidate(SOCK_INODE(newsock));
4985         newisec->sclass = sclass;
4986         newisec->sid = sid;
4987         newisec->initialized = LABEL_INITIALIZED;
4988
4989         return 0;
4990 }
4991
4992 static int selinux_socket_sendmsg(struct socket *sock, struct msghdr *msg,
4993                                   int size)
4994 {
4995         return sock_has_perm(sock->sk, SOCKET__WRITE);
4996 }
4997
4998 static int selinux_socket_recvmsg(struct socket *sock, struct msghdr *msg,
4999                                   int size, int flags)
5000 {
5001         return sock_has_perm(sock->sk, SOCKET__READ);
5002 }
5003
5004 static int selinux_socket_getsockname(struct socket *sock)
5005 {
5006         return sock_has_perm(sock->sk, SOCKET__GETATTR);
5007 }
5008
5009 static int selinux_socket_getpeername(struct socket *sock)
5010 {
5011         return sock_has_perm(sock->sk, SOCKET__GETATTR);
5012 }
5013
5014 static int selinux_socket_setsockopt(struct socket *sock, int level, int optname)
5015 {
5016         int err;
5017
5018         err = sock_has_perm(sock->sk, SOCKET__SETOPT);
5019         if (err)
5020                 return err;
5021
5022         return selinux_netlbl_socket_setsockopt(sock, level, optname);
5023 }
5024
5025 static int selinux_socket_getsockopt(struct socket *sock, int level,
5026                                      int optname)
5027 {
5028         return sock_has_perm(sock->sk, SOCKET__GETOPT);
5029 }
5030
5031 static int selinux_socket_shutdown(struct socket *sock, int how)
5032 {
5033         return sock_has_perm(sock->sk, SOCKET__SHUTDOWN);
5034 }
5035
5036 static int selinux_socket_unix_stream_connect(struct sock *sock,
5037                                               struct sock *other,
5038                                               struct sock *newsk)
5039 {
5040         struct sk_security_struct *sksec_sock = sock->sk_security;
5041         struct sk_security_struct *sksec_other = other->sk_security;
5042         struct sk_security_struct *sksec_new = newsk->sk_security;
5043         struct common_audit_data ad;
5044         struct lsm_network_audit net = {0,};
5045         int err;
5046
5047         ad.type = LSM_AUDIT_DATA_NET;
5048         ad.u.net = &net;
5049         ad.u.net->sk = other;
5050
5051         err = avc_has_perm(&selinux_state,
5052                            sksec_sock->sid, sksec_other->sid,
5053                            sksec_other->sclass,
5054                            UNIX_STREAM_SOCKET__CONNECTTO, &ad);
5055         if (err)
5056                 return err;
5057
5058         /* server child socket */
5059         sksec_new->peer_sid = sksec_sock->sid;
5060         err = security_sid_mls_copy(&selinux_state, sksec_other->sid,
5061                                     sksec_sock->sid, &sksec_new->sid);
5062         if (err)
5063                 return err;
5064
5065         /* connecting socket */
5066         sksec_sock->peer_sid = sksec_new->sid;
5067
5068         return 0;
5069 }
5070
5071 static int selinux_socket_unix_may_send(struct socket *sock,
5072                                         struct socket *other)
5073 {
5074         struct sk_security_struct *ssec = sock->sk->sk_security;
5075         struct sk_security_struct *osec = other->sk->sk_security;
5076         struct common_audit_data ad;
5077         struct lsm_network_audit net = {0,};
5078
5079         ad.type = LSM_AUDIT_DATA_NET;
5080         ad.u.net = &net;
5081         ad.u.net->sk = other->sk;
5082
5083         return avc_has_perm(&selinux_state,
5084                             ssec->sid, osec->sid, osec->sclass, SOCKET__SENDTO,
5085                             &ad);
5086 }
5087
5088 static int selinux_inet_sys_rcv_skb(struct net *ns, int ifindex,
5089                                     char *addrp, u16 family, u32 peer_sid,
5090                                     struct common_audit_data *ad)
5091 {
5092         int err;
5093         u32 if_sid;
5094         u32 node_sid;
5095
5096         err = sel_netif_sid(ns, ifindex, &if_sid);
5097         if (err)
5098                 return err;
5099         err = avc_has_perm(&selinux_state,
5100                            peer_sid, if_sid,
5101                            SECCLASS_NETIF, NETIF__INGRESS, ad);
5102         if (err)
5103                 return err;
5104
5105         err = sel_netnode_sid(addrp, family, &node_sid);
5106         if (err)
5107                 return err;
5108         return avc_has_perm(&selinux_state,
5109                             peer_sid, node_sid,
5110                             SECCLASS_NODE, NODE__RECVFROM, ad);
5111 }
5112
5113 static int selinux_sock_rcv_skb_compat(struct sock *sk, struct sk_buff *skb,
5114                                        u16 family)
5115 {
5116         int err = 0;
5117         struct sk_security_struct *sksec = sk->sk_security;
5118         u32 sk_sid = sksec->sid;
5119         struct common_audit_data ad;
5120         struct lsm_network_audit net = {0,};
5121         char *addrp;
5122
5123         ad.type = LSM_AUDIT_DATA_NET;
5124         ad.u.net = &net;
5125         ad.u.net->netif = skb->skb_iif;
5126         ad.u.net->family = family;
5127         err = selinux_parse_skb(skb, &ad, &addrp, 1, NULL);
5128         if (err)
5129                 return err;
5130
5131         if (selinux_secmark_enabled()) {
5132                 err = avc_has_perm(&selinux_state,
5133                                    sk_sid, skb->secmark, SECCLASS_PACKET,
5134                                    PACKET__RECV, &ad);
5135                 if (err)
5136                         return err;
5137         }
5138
5139         err = selinux_netlbl_sock_rcv_skb(sksec, skb, family, &ad);
5140         if (err)
5141                 return err;
5142         err = selinux_xfrm_sock_rcv_skb(sksec->sid, skb, &ad);
5143
5144         return err;
5145 }
5146
5147 static int selinux_socket_sock_rcv_skb(struct sock *sk, struct sk_buff *skb)
5148 {
5149         int err;
5150         struct sk_security_struct *sksec = sk->sk_security;
5151         u16 family = sk->sk_family;
5152         u32 sk_sid = sksec->sid;
5153         struct common_audit_data ad;
5154         struct lsm_network_audit net = {0,};
5155         char *addrp;
5156         u8 secmark_active;
5157         u8 peerlbl_active;
5158
5159         if (family != PF_INET && family != PF_INET6)
5160                 return 0;
5161
5162         /* Handle mapped IPv4 packets arriving via IPv6 sockets */
5163         if (family == PF_INET6 && skb->protocol == htons(ETH_P_IP))
5164                 family = PF_INET;
5165
5166         /* If any sort of compatibility mode is enabled then handoff processing
5167          * to the selinux_sock_rcv_skb_compat() function to deal with the
5168          * special handling.  We do this in an attempt to keep this function
5169          * as fast and as clean as possible. */
5170         if (!selinux_policycap_netpeer())
5171                 return selinux_sock_rcv_skb_compat(sk, skb, family);
5172
5173         secmark_active = selinux_secmark_enabled();
5174         peerlbl_active = selinux_peerlbl_enabled();
5175         if (!secmark_active && !peerlbl_active)
5176                 return 0;
5177
5178         ad.type = LSM_AUDIT_DATA_NET;
5179         ad.u.net = &net;
5180         ad.u.net->netif = skb->skb_iif;
5181         ad.u.net->family = family;
5182         err = selinux_parse_skb(skb, &ad, &addrp, 1, NULL);
5183         if (err)
5184                 return err;
5185
5186         if (peerlbl_active) {
5187                 u32 peer_sid;
5188
5189                 err = selinux_skb_peerlbl_sid(skb, family, &peer_sid);
5190                 if (err)
5191                         return err;
5192                 err = selinux_inet_sys_rcv_skb(sock_net(sk), skb->skb_iif,
5193                                                addrp, family, peer_sid, &ad);
5194                 if (err) {
5195                         selinux_netlbl_err(skb, family, err, 0);
5196                         return err;
5197                 }
5198                 err = avc_has_perm(&selinux_state,
5199                                    sk_sid, peer_sid, SECCLASS_PEER,
5200                                    PEER__RECV, &ad);
5201                 if (err) {
5202                         selinux_netlbl_err(skb, family, err, 0);
5203                         return err;
5204                 }
5205         }
5206
5207         if (secmark_active) {
5208                 err = avc_has_perm(&selinux_state,
5209                                    sk_sid, skb->secmark, SECCLASS_PACKET,
5210                                    PACKET__RECV, &ad);
5211                 if (err)
5212                         return err;
5213         }
5214
5215         return err;
5216 }
5217
5218 static int selinux_socket_getpeersec_stream(struct socket *sock, char __user *optval,
5219                                             int __user *optlen, unsigned len)
5220 {
5221         int err = 0;
5222         char *scontext;
5223         u32 scontext_len;
5224         struct sk_security_struct *sksec = sock->sk->sk_security;
5225         u32 peer_sid = SECSID_NULL;
5226
5227         if (sksec->sclass == SECCLASS_UNIX_STREAM_SOCKET ||
5228             sksec->sclass == SECCLASS_TCP_SOCKET ||
5229             sksec->sclass == SECCLASS_SCTP_SOCKET)
5230                 peer_sid = sksec->peer_sid;
5231         if (peer_sid == SECSID_NULL)
5232                 return -ENOPROTOOPT;
5233
5234         err = security_sid_to_context(&selinux_state, peer_sid, &scontext,
5235                                       &scontext_len);
5236         if (err)
5237                 return err;
5238
5239         if (scontext_len > len) {
5240                 err = -ERANGE;
5241                 goto out_len;
5242         }
5243
5244         if (copy_to_user(optval, scontext, scontext_len))
5245                 err = -EFAULT;
5246
5247 out_len:
5248         if (put_user(scontext_len, optlen))
5249                 err = -EFAULT;
5250         kfree(scontext);
5251         return err;
5252 }
5253
5254 static int selinux_socket_getpeersec_dgram(struct socket *sock, struct sk_buff *skb, u32 *secid)
5255 {
5256         u32 peer_secid = SECSID_NULL;
5257         u16 family;
5258         struct inode_security_struct *isec;
5259
5260         if (skb && skb->protocol == htons(ETH_P_IP))
5261                 family = PF_INET;
5262         else if (skb && skb->protocol == htons(ETH_P_IPV6))
5263                 family = PF_INET6;
5264         else if (sock)
5265                 family = sock->sk->sk_family;
5266         else
5267                 goto out;
5268
5269         if (sock && family == PF_UNIX) {
5270                 isec = inode_security_novalidate(SOCK_INODE(sock));
5271                 peer_secid = isec->sid;
5272         } else if (skb)
5273                 selinux_skb_peerlbl_sid(skb, family, &peer_secid);
5274
5275 out:
5276         *secid = peer_secid;
5277         if (peer_secid == SECSID_NULL)
5278                 return -EINVAL;
5279         return 0;
5280 }
5281
5282 static int selinux_sk_alloc_security(struct sock *sk, int family, gfp_t priority)
5283 {
5284         struct sk_security_struct *sksec;
5285
5286         sksec = kzalloc(sizeof(*sksec), priority);
5287         if (!sksec)
5288                 return -ENOMEM;
5289
5290         sksec->peer_sid = SECINITSID_UNLABELED;
5291         sksec->sid = SECINITSID_UNLABELED;
5292         sksec->sclass = SECCLASS_SOCKET;
5293         selinux_netlbl_sk_security_reset(sksec);
5294         sk->sk_security = sksec;
5295
5296         return 0;
5297 }
5298
5299 static void selinux_sk_free_security(struct sock *sk)
5300 {
5301         struct sk_security_struct *sksec = sk->sk_security;
5302
5303         sk->sk_security = NULL;
5304         selinux_netlbl_sk_security_free(sksec);
5305         kfree(sksec);
5306 }
5307
5308 static void selinux_sk_clone_security(const struct sock *sk, struct sock *newsk)
5309 {
5310         struct sk_security_struct *sksec = sk->sk_security;
5311         struct sk_security_struct *newsksec = newsk->sk_security;
5312
5313         newsksec->sid = sksec->sid;
5314         newsksec->peer_sid = sksec->peer_sid;
5315         newsksec->sclass = sksec->sclass;
5316
5317         selinux_netlbl_sk_security_reset(newsksec);
5318 }
5319
5320 static void selinux_sk_getsecid(struct sock *sk, u32 *secid)
5321 {
5322         if (!sk)
5323                 *secid = SECINITSID_ANY_SOCKET;
5324         else {
5325                 struct sk_security_struct *sksec = sk->sk_security;
5326
5327                 *secid = sksec->sid;
5328         }
5329 }
5330
5331 static void selinux_sock_graft(struct sock *sk, struct socket *parent)
5332 {
5333         struct inode_security_struct *isec =
5334                 inode_security_novalidate(SOCK_INODE(parent));
5335         struct sk_security_struct *sksec = sk->sk_security;
5336
5337         if (sk->sk_family == PF_INET || sk->sk_family == PF_INET6 ||
5338             sk->sk_family == PF_UNIX)
5339                 isec->sid = sksec->sid;
5340         sksec->sclass = isec->sclass;
5341 }
5342
5343 /* Called whenever SCTP receives an INIT chunk. This happens when an incoming
5344  * connect(2), sctp_connectx(3) or sctp_sendmsg(3) (with no association
5345  * already present).
5346  */
5347 static int selinux_sctp_assoc_request(struct sctp_association *asoc,
5348                                       struct sk_buff *skb)
5349 {
5350         struct sk_security_struct *sksec = asoc->base.sk->sk_security;
5351         struct common_audit_data ad;
5352         struct lsm_network_audit net = {0,};
5353         u8 peerlbl_active;
5354         u32 peer_sid = SECINITSID_UNLABELED;
5355         u32 conn_sid;
5356         int err = 0;
5357
5358         if (!selinux_policycap_extsockclass())
5359                 return 0;
5360
5361         peerlbl_active = selinux_peerlbl_enabled();
5362
5363         if (peerlbl_active) {
5364                 /* This will return peer_sid = SECSID_NULL if there are
5365                  * no peer labels, see security_net_peersid_resolve().
5366                  */
5367                 err = selinux_skb_peerlbl_sid(skb, asoc->base.sk->sk_family,
5368                                               &peer_sid);
5369                 if (err)
5370                         return err;
5371
5372                 if (peer_sid == SECSID_NULL)
5373                         peer_sid = SECINITSID_UNLABELED;
5374         }
5375
5376         if (sksec->sctp_assoc_state == SCTP_ASSOC_UNSET) {
5377                 sksec->sctp_assoc_state = SCTP_ASSOC_SET;
5378
5379                 /* Here as first association on socket. As the peer SID
5380                  * was allowed by peer recv (and the netif/node checks),
5381                  * then it is approved by policy and used as the primary
5382                  * peer SID for getpeercon(3).
5383                  */
5384                 sksec->peer_sid = peer_sid;
5385         } else if  (sksec->peer_sid != peer_sid) {
5386                 /* Other association peer SIDs are checked to enforce
5387                  * consistency among the peer SIDs.
5388                  */
5389                 ad.type = LSM_AUDIT_DATA_NET;
5390                 ad.u.net = &net;
5391                 ad.u.net->sk = asoc->base.sk;
5392                 err = avc_has_perm(&selinux_state,
5393                                    sksec->peer_sid, peer_sid, sksec->sclass,
5394                                    SCTP_SOCKET__ASSOCIATION, &ad);
5395                 if (err)
5396                         return err;
5397         }
5398
5399         /* Compute the MLS component for the connection and store
5400          * the information in asoc. This will be used by SCTP TCP type
5401          * sockets and peeled off connections as they cause a new
5402          * socket to be generated. selinux_sctp_sk_clone() will then
5403          * plug this into the new socket.
5404          */
5405         err = selinux_conn_sid(sksec->sid, peer_sid, &conn_sid);
5406         if (err)
5407                 return err;
5408
5409         asoc->secid = conn_sid;
5410         asoc->peer_secid = peer_sid;
5411
5412         /* Set any NetLabel labels including CIPSO/CALIPSO options. */
5413         return selinux_netlbl_sctp_assoc_request(asoc, skb);
5414 }
5415
5416 /* Check if sctp IPv4/IPv6 addresses are valid for binding or connecting
5417  * based on their @optname.
5418  */
5419 static int selinux_sctp_bind_connect(struct sock *sk, int optname,
5420                                      struct sockaddr *address,
5421                                      int addrlen)
5422 {
5423         int len, err = 0, walk_size = 0;
5424         void *addr_buf;
5425         struct sockaddr *addr;
5426         struct socket *sock;
5427
5428         if (!selinux_policycap_extsockclass())
5429                 return 0;
5430
5431         /* Process one or more addresses that may be IPv4 or IPv6 */
5432         sock = sk->sk_socket;
5433         addr_buf = address;
5434
5435         while (walk_size < addrlen) {
5436                 if (walk_size + sizeof(sa_family_t) > addrlen)
5437                         return -EINVAL;
5438
5439                 addr = addr_buf;
5440                 switch (addr->sa_family) {
5441                 case AF_UNSPEC:
5442                 case AF_INET:
5443                         len = sizeof(struct sockaddr_in);
5444                         break;
5445                 case AF_INET6:
5446                         len = sizeof(struct sockaddr_in6);
5447                         break;
5448                 default:
5449                         return -EINVAL;
5450                 }
5451
5452                 if (walk_size + len > addrlen)
5453                         return -EINVAL;
5454
5455                 err = -EINVAL;
5456                 switch (optname) {
5457                 /* Bind checks */
5458                 case SCTP_PRIMARY_ADDR:
5459                 case SCTP_SET_PEER_PRIMARY_ADDR:
5460                 case SCTP_SOCKOPT_BINDX_ADD:
5461                         err = selinux_socket_bind(sock, addr, len);
5462                         break;
5463                 /* Connect checks */
5464                 case SCTP_SOCKOPT_CONNECTX:
5465                 case SCTP_PARAM_SET_PRIMARY:
5466                 case SCTP_PARAM_ADD_IP:
5467                 case SCTP_SENDMSG_CONNECT:
5468                         err = selinux_socket_connect_helper(sock, addr, len);
5469                         if (err)
5470                                 return err;
5471
5472                         /* As selinux_sctp_bind_connect() is called by the
5473                          * SCTP protocol layer, the socket is already locked,
5474                          * therefore selinux_netlbl_socket_connect_locked()
5475                          * is called here. The situations handled are:
5476                          * sctp_connectx(3), sctp_sendmsg(3), sendmsg(2),
5477                          * whenever a new IP address is added or when a new
5478                          * primary address is selected.
5479                          * Note that an SCTP connect(2) call happens before
5480                          * the SCTP protocol layer and is handled via
5481                          * selinux_socket_connect().
5482                          */
5483                         err = selinux_netlbl_socket_connect_locked(sk, addr);
5484                         break;
5485                 }
5486
5487                 if (err)
5488                         return err;
5489
5490                 addr_buf += len;
5491                 walk_size += len;
5492         }
5493
5494         return 0;
5495 }
5496
5497 /* Called whenever a new socket is created by accept(2) or sctp_peeloff(3). */
5498 static void selinux_sctp_sk_clone(struct sctp_association *asoc, struct sock *sk,
5499                                   struct sock *newsk)
5500 {
5501         struct sk_security_struct *sksec = sk->sk_security;
5502         struct sk_security_struct *newsksec = newsk->sk_security;
5503
5504         /* If policy does not support SECCLASS_SCTP_SOCKET then call
5505          * the non-sctp clone version.
5506          */
5507         if (!selinux_policycap_extsockclass())
5508                 return selinux_sk_clone_security(sk, newsk);
5509
5510         newsksec->sid = asoc->secid;
5511         newsksec->peer_sid = asoc->peer_secid;
5512         newsksec->sclass = sksec->sclass;
5513         selinux_netlbl_sctp_sk_clone(sk, newsk);
5514 }
5515
5516 static int selinux_inet_conn_request(const struct sock *sk, struct sk_buff *skb,
5517                                      struct request_sock *req)
5518 {
5519         struct sk_security_struct *sksec = sk->sk_security;
5520         int err;
5521         u16 family = req->rsk_ops->family;
5522         u32 connsid;
5523         u32 peersid;
5524
5525         err = selinux_skb_peerlbl_sid(skb, family, &peersid);
5526         if (err)
5527                 return err;
5528         err = selinux_conn_sid(sksec->sid, peersid, &connsid);
5529         if (err)
5530                 return err;
5531         req->secid = connsid;
5532         req->peer_secid = peersid;
5533
5534         return selinux_netlbl_inet_conn_request(req, family);
5535 }
5536
5537 static void selinux_inet_csk_clone(struct sock *newsk,
5538                                    const struct request_sock *req)
5539 {
5540         struct sk_security_struct *newsksec = newsk->sk_security;
5541
5542         newsksec->sid = req->secid;
5543         newsksec->peer_sid = req->peer_secid;
5544         /* NOTE: Ideally, we should also get the isec->sid for the
5545            new socket in sync, but we don't have the isec available yet.
5546            So we will wait until sock_graft to do it, by which
5547            time it will have been created and available. */
5548
5549         /* We don't need to take any sort of lock here as we are the only
5550          * thread with access to newsksec */
5551         selinux_netlbl_inet_csk_clone(newsk, req->rsk_ops->family);
5552 }
5553
5554 static void selinux_inet_conn_established(struct sock *sk, struct sk_buff *skb)
5555 {
5556         u16 family = sk->sk_family;
5557         struct sk_security_struct *sksec = sk->sk_security;
5558
5559         /* handle mapped IPv4 packets arriving via IPv6 sockets */
5560         if (family == PF_INET6 && skb->protocol == htons(ETH_P_IP))
5561                 family = PF_INET;
5562
5563         selinux_skb_peerlbl_sid(skb, family, &sksec->peer_sid);
5564 }
5565
5566 static int selinux_secmark_relabel_packet(u32 sid)
5567 {
5568         const struct task_security_struct *__tsec;
5569         u32 tsid;
5570
5571         __tsec = selinux_cred(current_cred());
5572         tsid = __tsec->sid;
5573
5574         return avc_has_perm(&selinux_state,
5575                             tsid, sid, SECCLASS_PACKET, PACKET__RELABELTO,
5576                             NULL);
5577 }
5578
5579 static void selinux_secmark_refcount_inc(void)
5580 {
5581         atomic_inc(&selinux_secmark_refcount);
5582 }
5583
5584 static void selinux_secmark_refcount_dec(void)
5585 {
5586         atomic_dec(&selinux_secmark_refcount);
5587 }
5588
5589 static void selinux_req_classify_flow(const struct request_sock *req,
5590                                       struct flowi_common *flic)
5591 {
5592         flic->flowic_secid = req->secid;
5593 }
5594
5595 static int selinux_tun_dev_alloc_security(void **security)
5596 {
5597         struct tun_security_struct *tunsec;
5598
5599         tunsec = kzalloc(sizeof(*tunsec), GFP_KERNEL);
5600         if (!tunsec)
5601                 return -ENOMEM;
5602         tunsec->sid = current_sid();
5603
5604         *security = tunsec;
5605         return 0;
5606 }
5607
5608 static void selinux_tun_dev_free_security(void *security)
5609 {
5610         kfree(security);
5611 }
5612
5613 static int selinux_tun_dev_create(void)
5614 {
5615         u32 sid = current_sid();
5616
5617         /* we aren't taking into account the "sockcreate" SID since the socket
5618          * that is being created here is not a socket in the traditional sense,
5619          * instead it is a private sock, accessible only to the kernel, and
5620          * representing a wide range of network traffic spanning multiple
5621          * connections unlike traditional sockets - check the TUN driver to
5622          * get a better understanding of why this socket is special */
5623
5624         return avc_has_perm(&selinux_state,
5625                             sid, sid, SECCLASS_TUN_SOCKET, TUN_SOCKET__CREATE,
5626                             NULL);
5627 }
5628
5629 static int selinux_tun_dev_attach_queue(void *security)
5630 {
5631         struct tun_security_struct *tunsec = security;
5632
5633         return avc_has_perm(&selinux_state,
5634                             current_sid(), tunsec->sid, SECCLASS_TUN_SOCKET,
5635                             TUN_SOCKET__ATTACH_QUEUE, NULL);
5636 }
5637
5638 static int selinux_tun_dev_attach(struct sock *sk, void *security)
5639 {
5640         struct tun_security_struct *tunsec = security;
5641         struct sk_security_struct *sksec = sk->sk_security;
5642
5643         /* we don't currently perform any NetLabel based labeling here and it
5644          * isn't clear that we would want to do so anyway; while we could apply
5645          * labeling without the support of the TUN user the resulting labeled
5646          * traffic from the other end of the connection would almost certainly
5647          * cause confusion to the TUN user that had no idea network labeling
5648          * protocols were being used */
5649
5650         sksec->sid = tunsec->sid;
5651         sksec->sclass = SECCLASS_TUN_SOCKET;
5652
5653         return 0;
5654 }
5655
5656 static int selinux_tun_dev_open(void *security)
5657 {
5658         struct tun_security_struct *tunsec = security;
5659         u32 sid = current_sid();
5660         int err;
5661
5662         err = avc_has_perm(&selinux_state,
5663                            sid, tunsec->sid, SECCLASS_TUN_SOCKET,
5664                            TUN_SOCKET__RELABELFROM, NULL);
5665         if (err)
5666                 return err;
5667         err = avc_has_perm(&selinux_state,
5668                            sid, sid, SECCLASS_TUN_SOCKET,
5669                            TUN_SOCKET__RELABELTO, NULL);
5670         if (err)
5671                 return err;
5672         tunsec->sid = sid;
5673
5674         return 0;
5675 }
5676
5677 #ifdef CONFIG_NETFILTER
5678
5679 static unsigned int selinux_ip_forward(void *priv, struct sk_buff *skb,
5680                                        const struct nf_hook_state *state)
5681 {
5682         int ifindex;
5683         u16 family;
5684         char *addrp;
5685         u32 peer_sid;
5686         struct common_audit_data ad;
5687         struct lsm_network_audit net = {0,};
5688         int secmark_active, peerlbl_active;
5689
5690         if (!selinux_policycap_netpeer())
5691                 return NF_ACCEPT;
5692
5693         secmark_active = selinux_secmark_enabled();
5694         peerlbl_active = selinux_peerlbl_enabled();
5695         if (!secmark_active && !peerlbl_active)
5696                 return NF_ACCEPT;
5697
5698         family = state->pf;
5699         if (selinux_skb_peerlbl_sid(skb, family, &peer_sid) != 0)
5700                 return NF_DROP;
5701
5702         ifindex = state->in->ifindex;
5703         ad.type = LSM_AUDIT_DATA_NET;
5704         ad.u.net = &net;
5705         ad.u.net->netif = ifindex;
5706         ad.u.net->family = family;
5707         if (selinux_parse_skb(skb, &ad, &addrp, 1, NULL) != 0)
5708                 return NF_DROP;
5709
5710         if (peerlbl_active) {
5711                 int err;
5712
5713                 err = selinux_inet_sys_rcv_skb(state->net, ifindex,
5714                                                addrp, family, peer_sid, &ad);
5715                 if (err) {
5716                         selinux_netlbl_err(skb, family, err, 1);
5717                         return NF_DROP;
5718                 }
5719         }
5720
5721         if (secmark_active)
5722                 if (avc_has_perm(&selinux_state,
5723                                  peer_sid, skb->secmark,
5724                                  SECCLASS_PACKET, PACKET__FORWARD_IN, &ad))
5725                         return NF_DROP;
5726
5727         if (netlbl_enabled())
5728                 /* we do this in the FORWARD path and not the POST_ROUTING
5729                  * path because we want to make sure we apply the necessary
5730                  * labeling before IPsec is applied so we can leverage AH
5731                  * protection */
5732                 if (selinux_netlbl_skbuff_setsid(skb, family, peer_sid) != 0)
5733                         return NF_DROP;
5734
5735         return NF_ACCEPT;
5736 }
5737
5738 static unsigned int selinux_ip_output(void *priv, struct sk_buff *skb,
5739                                       const struct nf_hook_state *state)
5740 {
5741         struct sock *sk;
5742         u32 sid;
5743
5744         if (!netlbl_enabled())
5745                 return NF_ACCEPT;
5746
5747         /* we do this in the LOCAL_OUT path and not the POST_ROUTING path
5748          * because we want to make sure we apply the necessary labeling
5749          * before IPsec is applied so we can leverage AH protection */
5750         sk = skb->sk;
5751         if (sk) {
5752                 struct sk_security_struct *sksec;
5753
5754                 if (sk_listener(sk))
5755                         /* if the socket is the listening state then this
5756                          * packet is a SYN-ACK packet which means it needs to
5757                          * be labeled based on the connection/request_sock and
5758                          * not the parent socket.  unfortunately, we can't
5759                          * lookup the request_sock yet as it isn't queued on
5760                          * the parent socket until after the SYN-ACK is sent.
5761                          * the "solution" is to simply pass the packet as-is
5762                          * as any IP option based labeling should be copied
5763                          * from the initial connection request (in the IP
5764                          * layer).  it is far from ideal, but until we get a
5765                          * security label in the packet itself this is the
5766                          * best we can do. */
5767                         return NF_ACCEPT;
5768
5769                 /* standard practice, label using the parent socket */
5770                 sksec = sk->sk_security;
5771                 sid = sksec->sid;
5772         } else
5773                 sid = SECINITSID_KERNEL;
5774         if (selinux_netlbl_skbuff_setsid(skb, state->pf, sid) != 0)
5775                 return NF_DROP;
5776
5777         return NF_ACCEPT;
5778 }
5779
5780
5781 static unsigned int selinux_ip_postroute_compat(struct sk_buff *skb,
5782                                         const struct nf_hook_state *state)
5783 {
5784         struct sock *sk;
5785         struct sk_security_struct *sksec;
5786         struct common_audit_data ad;
5787         struct lsm_network_audit net = {0,};
5788         u8 proto;
5789
5790         sk = skb_to_full_sk(skb);
5791         if (sk == NULL)
5792                 return NF_ACCEPT;
5793         sksec = sk->sk_security;
5794
5795         ad.type = LSM_AUDIT_DATA_NET;
5796         ad.u.net = &net;
5797         ad.u.net->netif = state->out->ifindex;
5798         ad.u.net->family = state->pf;
5799         if (selinux_parse_skb(skb, &ad, NULL, 0, &proto))
5800                 return NF_DROP;
5801
5802         if (selinux_secmark_enabled())
5803                 if (avc_has_perm(&selinux_state,
5804                                  sksec->sid, skb->secmark,
5805                                  SECCLASS_PACKET, PACKET__SEND, &ad))
5806                         return NF_DROP_ERR(-ECONNREFUSED);
5807
5808         if (selinux_xfrm_postroute_last(sksec->sid, skb, &ad, proto))
5809                 return NF_DROP_ERR(-ECONNREFUSED);
5810
5811         return NF_ACCEPT;
5812 }
5813
5814 static unsigned int selinux_ip_postroute(void *priv,
5815                                          struct sk_buff *skb,
5816                                          const struct nf_hook_state *state)
5817 {
5818         u16 family;
5819         u32 secmark_perm;
5820         u32 peer_sid;
5821         int ifindex;
5822         struct sock *sk;
5823         struct common_audit_data ad;
5824         struct lsm_network_audit net = {0,};
5825         char *addrp;
5826         int secmark_active, peerlbl_active;
5827
5828         /* If any sort of compatibility mode is enabled then handoff processing
5829          * to the selinux_ip_postroute_compat() function to deal with the
5830          * special handling.  We do this in an attempt to keep this function
5831          * as fast and as clean as possible. */
5832         if (!selinux_policycap_netpeer())
5833                 return selinux_ip_postroute_compat(skb, state);
5834
5835         secmark_active = selinux_secmark_enabled();
5836         peerlbl_active = selinux_peerlbl_enabled();
5837         if (!secmark_active && !peerlbl_active)
5838                 return NF_ACCEPT;
5839
5840         sk = skb_to_full_sk(skb);
5841
5842 #ifdef CONFIG_XFRM
5843         /* If skb->dst->xfrm is non-NULL then the packet is undergoing an IPsec
5844          * packet transformation so allow the packet to pass without any checks
5845          * since we'll have another chance to perform access control checks
5846          * when the packet is on it's final way out.
5847          * NOTE: there appear to be some IPv6 multicast cases where skb->dst
5848          *       is NULL, in this case go ahead and apply access control.
5849          * NOTE: if this is a local socket (skb->sk != NULL) that is in the
5850          *       TCP listening state we cannot wait until the XFRM processing
5851          *       is done as we will miss out on the SA label if we do;
5852          *       unfortunately, this means more work, but it is only once per
5853          *       connection. */
5854         if (skb_dst(skb) != NULL && skb_dst(skb)->xfrm != NULL &&
5855             !(sk && sk_listener(sk)))
5856                 return NF_ACCEPT;
5857 #endif
5858
5859         family = state->pf;
5860         if (sk == NULL) {
5861                 /* Without an associated socket the packet is either coming
5862                  * from the kernel or it is being forwarded; check the packet
5863                  * to determine which and if the packet is being forwarded
5864                  * query the packet directly to determine the security label. */
5865                 if (skb->skb_iif) {
5866                         secmark_perm = PACKET__FORWARD_OUT;
5867                         if (selinux_skb_peerlbl_sid(skb, family, &peer_sid))
5868                                 return NF_DROP;
5869                 } else {
5870                         secmark_perm = PACKET__SEND;
5871                         peer_sid = SECINITSID_KERNEL;
5872                 }
5873         } else if (sk_listener(sk)) {
5874                 /* Locally generated packet but the associated socket is in the
5875                  * listening state which means this is a SYN-ACK packet.  In
5876                  * this particular case the correct security label is assigned
5877                  * to the connection/request_sock but unfortunately we can't
5878                  * query the request_sock as it isn't queued on the parent
5879                  * socket until after the SYN-ACK packet is sent; the only
5880                  * viable choice is to regenerate the label like we do in
5881                  * selinux_inet_conn_request().  See also selinux_ip_output()
5882                  * for similar problems. */
5883                 u32 skb_sid;
5884                 struct sk_security_struct *sksec;
5885
5886                 sksec = sk->sk_security;
5887                 if (selinux_skb_peerlbl_sid(skb, family, &skb_sid))
5888                         return NF_DROP;
5889                 /* At this point, if the returned skb peerlbl is SECSID_NULL
5890                  * and the packet has been through at least one XFRM
5891                  * transformation then we must be dealing with the "final"
5892                  * form of labeled IPsec packet; since we've already applied
5893                  * all of our access controls on this packet we can safely
5894                  * pass the packet. */
5895                 if (skb_sid == SECSID_NULL) {
5896                         switch (family) {
5897                         case PF_INET:
5898                                 if (IPCB(skb)->flags & IPSKB_XFRM_TRANSFORMED)
5899                                         return NF_ACCEPT;
5900                                 break;
5901                         case PF_INET6:
5902                                 if (IP6CB(skb)->flags & IP6SKB_XFRM_TRANSFORMED)
5903                                         return NF_ACCEPT;
5904                                 break;
5905                         default:
5906                                 return NF_DROP_ERR(-ECONNREFUSED);
5907                         }
5908                 }
5909                 if (selinux_conn_sid(sksec->sid, skb_sid, &peer_sid))
5910                         return NF_DROP;
5911                 secmark_perm = PACKET__SEND;
5912         } else {
5913                 /* Locally generated packet, fetch the security label from the
5914                  * associated socket. */
5915                 struct sk_security_struct *sksec = sk->sk_security;
5916                 peer_sid = sksec->sid;
5917                 secmark_perm = PACKET__SEND;
5918         }
5919
5920         ifindex = state->out->ifindex;
5921         ad.type = LSM_AUDIT_DATA_NET;
5922         ad.u.net = &net;
5923         ad.u.net->netif = ifindex;
5924         ad.u.net->family = family;
5925         if (selinux_parse_skb(skb, &ad, &addrp, 0, NULL))
5926                 return NF_DROP;
5927
5928         if (secmark_active)
5929                 if (avc_has_perm(&selinux_state,
5930                                  peer_sid, skb->secmark,
5931                                  SECCLASS_PACKET, secmark_perm, &ad))
5932                         return NF_DROP_ERR(-ECONNREFUSED);
5933
5934         if (peerlbl_active) {
5935                 u32 if_sid;
5936                 u32 node_sid;
5937
5938                 if (sel_netif_sid(state->net, ifindex, &if_sid))
5939                         return NF_DROP;
5940                 if (avc_has_perm(&selinux_state,
5941                                  peer_sid, if_sid,
5942                                  SECCLASS_NETIF, NETIF__EGRESS, &ad))
5943                         return NF_DROP_ERR(-ECONNREFUSED);
5944
5945                 if (sel_netnode_sid(addrp, family, &node_sid))
5946                         return NF_DROP;
5947                 if (avc_has_perm(&selinux_state,
5948                                  peer_sid, node_sid,
5949                                  SECCLASS_NODE, NODE__SENDTO, &ad))
5950                         return NF_DROP_ERR(-ECONNREFUSED);
5951         }
5952
5953         return NF_ACCEPT;
5954 }
5955 #endif  /* CONFIG_NETFILTER */
5956
5957 static int selinux_netlink_send(struct sock *sk, struct sk_buff *skb)
5958 {
5959         int rc = 0;
5960         unsigned int msg_len;
5961         unsigned int data_len = skb->len;
5962         unsigned char *data = skb->data;
5963         struct nlmsghdr *nlh;
5964         struct sk_security_struct *sksec = sk->sk_security;
5965         u16 sclass = sksec->sclass;
5966         u32 perm;
5967
5968         while (data_len >= nlmsg_total_size(0)) {
5969                 nlh = (struct nlmsghdr *)data;
5970
5971                 /* NOTE: the nlmsg_len field isn't reliably set by some netlink
5972                  *       users which means we can't reject skb's with bogus
5973                  *       length fields; our solution is to follow what
5974                  *       netlink_rcv_skb() does and simply skip processing at
5975                  *       messages with length fields that are clearly junk
5976                  */
5977                 if (nlh->nlmsg_len < NLMSG_HDRLEN || nlh->nlmsg_len > data_len)
5978                         return 0;
5979
5980                 rc = selinux_nlmsg_lookup(sclass, nlh->nlmsg_type, &perm);
5981                 if (rc == 0) {
5982                         rc = sock_has_perm(sk, perm);
5983                         if (rc)
5984                                 return rc;
5985                 } else if (rc == -EINVAL) {
5986                         /* -EINVAL is a missing msg/perm mapping */
5987                         pr_warn_ratelimited("SELinux: unrecognized netlink"
5988                                 " message: protocol=%hu nlmsg_type=%hu sclass=%s"
5989                                 " pid=%d comm=%s\n",
5990                                 sk->sk_protocol, nlh->nlmsg_type,
5991                                 secclass_map[sclass - 1].name,
5992                                 task_pid_nr(current), current->comm);
5993                         if (enforcing_enabled(&selinux_state) &&
5994                             !security_get_allow_unknown(&selinux_state))
5995                                 return rc;
5996                         rc = 0;
5997                 } else if (rc == -ENOENT) {
5998                         /* -ENOENT is a missing socket/class mapping, ignore */
5999                         rc = 0;
6000                 } else {
6001                         return rc;
6002                 }
6003
6004                 /* move to the next message after applying netlink padding */
6005                 msg_len = NLMSG_ALIGN(nlh->nlmsg_len);
6006                 if (msg_len >= data_len)
6007                         return 0;
6008                 data_len -= msg_len;
6009                 data += msg_len;
6010         }
6011
6012         return rc;
6013 }
6014
6015 static void ipc_init_security(struct ipc_security_struct *isec, u16 sclass)
6016 {
6017         isec->sclass = sclass;
6018         isec->sid = current_sid();
6019 }
6020
6021 static int ipc_has_perm(struct kern_ipc_perm *ipc_perms,
6022                         u32 perms)
6023 {
6024         struct ipc_security_struct *isec;
6025         struct common_audit_data ad;
6026         u32 sid = current_sid();
6027
6028         isec = selinux_ipc(ipc_perms);
6029
6030         ad.type = LSM_AUDIT_DATA_IPC;
6031         ad.u.ipc_id = ipc_perms->key;
6032
6033         return avc_has_perm(&selinux_state,
6034                             sid, isec->sid, isec->sclass, perms, &ad);
6035 }
6036
6037 static int selinux_msg_msg_alloc_security(struct msg_msg *msg)
6038 {
6039         struct msg_security_struct *msec;
6040
6041         msec = selinux_msg_msg(msg);
6042         msec->sid = SECINITSID_UNLABELED;
6043
6044         return 0;
6045 }
6046
6047 /* message queue security operations */
6048 static int selinux_msg_queue_alloc_security(struct kern_ipc_perm *msq)
6049 {
6050         struct ipc_security_struct *isec;
6051         struct common_audit_data ad;
6052         u32 sid = current_sid();
6053         int rc;
6054
6055         isec = selinux_ipc(msq);
6056         ipc_init_security(isec, SECCLASS_MSGQ);
6057
6058         ad.type = LSM_AUDIT_DATA_IPC;
6059         ad.u.ipc_id = msq->key;
6060
6061         rc = avc_has_perm(&selinux_state,
6062                           sid, isec->sid, SECCLASS_MSGQ,
6063                           MSGQ__CREATE, &ad);
6064         return rc;
6065 }
6066
6067 static int selinux_msg_queue_associate(struct kern_ipc_perm *msq, int msqflg)
6068 {
6069         struct ipc_security_struct *isec;
6070         struct common_audit_data ad;
6071         u32 sid = current_sid();
6072
6073         isec = selinux_ipc(msq);
6074
6075         ad.type = LSM_AUDIT_DATA_IPC;
6076         ad.u.ipc_id = msq->key;
6077
6078         return avc_has_perm(&selinux_state,
6079                             sid, isec->sid, SECCLASS_MSGQ,
6080                             MSGQ__ASSOCIATE, &ad);
6081 }
6082
6083 static int selinux_msg_queue_msgctl(struct kern_ipc_perm *msq, int cmd)
6084 {
6085         int err;
6086         int perms;
6087
6088         switch (cmd) {
6089         case IPC_INFO:
6090         case MSG_INFO:
6091                 /* No specific object, just general system-wide information. */
6092                 return avc_has_perm(&selinux_state,
6093                                     current_sid(), SECINITSID_KERNEL,
6094                                     SECCLASS_SYSTEM, SYSTEM__IPC_INFO, NULL);
6095         case IPC_STAT:
6096         case MSG_STAT:
6097         case MSG_STAT_ANY:
6098                 perms = MSGQ__GETATTR | MSGQ__ASSOCIATE;
6099                 break;
6100         case IPC_SET:
6101                 perms = MSGQ__SETATTR;
6102                 break;
6103         case IPC_RMID:
6104                 perms = MSGQ__DESTROY;
6105                 break;
6106         default:
6107                 return 0;
6108         }
6109
6110         err = ipc_has_perm(msq, perms);
6111         return err;
6112 }
6113
6114 static int selinux_msg_queue_msgsnd(struct kern_ipc_perm *msq, struct msg_msg *msg, int msqflg)
6115 {
6116         struct ipc_security_struct *isec;
6117         struct msg_security_struct *msec;
6118         struct common_audit_data ad;
6119         u32 sid = current_sid();
6120         int rc;
6121
6122         isec = selinux_ipc(msq);
6123         msec = selinux_msg_msg(msg);
6124
6125         /*
6126          * First time through, need to assign label to the message
6127          */
6128         if (msec->sid == SECINITSID_UNLABELED) {
6129                 /*
6130                  * Compute new sid based on current process and
6131                  * message queue this message will be stored in
6132                  */
6133                 rc = security_transition_sid(&selinux_state, sid, isec->sid,
6134                                              SECCLASS_MSG, NULL, &msec->sid);
6135                 if (rc)
6136                         return rc;
6137         }
6138
6139         ad.type = LSM_AUDIT_DATA_IPC;
6140         ad.u.ipc_id = msq->key;
6141
6142         /* Can this process write to the queue? */
6143         rc = avc_has_perm(&selinux_state,
6144                           sid, isec->sid, SECCLASS_MSGQ,
6145                           MSGQ__WRITE, &ad);
6146         if (!rc)
6147                 /* Can this process send the message */
6148                 rc = avc_has_perm(&selinux_state,
6149                                   sid, msec->sid, SECCLASS_MSG,
6150                                   MSG__SEND, &ad);
6151         if (!rc)
6152                 /* Can the message be put in the queue? */
6153                 rc = avc_has_perm(&selinux_state,
6154                                   msec->sid, isec->sid, SECCLASS_MSGQ,
6155                                   MSGQ__ENQUEUE, &ad);
6156
6157         return rc;
6158 }
6159
6160 static int selinux_msg_queue_msgrcv(struct kern_ipc_perm *msq, struct msg_msg *msg,
6161                                     struct task_struct *target,
6162                                     long type, int mode)
6163 {
6164         struct ipc_security_struct *isec;
6165         struct msg_security_struct *msec;
6166         struct common_audit_data ad;
6167         u32 sid = task_sid_obj(target);
6168         int rc;
6169
6170         isec = selinux_ipc(msq);
6171         msec = selinux_msg_msg(msg);
6172
6173         ad.type = LSM_AUDIT_DATA_IPC;
6174         ad.u.ipc_id = msq->key;
6175
6176         rc = avc_has_perm(&selinux_state,
6177                           sid, isec->sid,
6178                           SECCLASS_MSGQ, MSGQ__READ, &ad);
6179         if (!rc)
6180                 rc = avc_has_perm(&selinux_state,
6181                                   sid, msec->sid,
6182                                   SECCLASS_MSG, MSG__RECEIVE, &ad);
6183         return rc;
6184 }
6185
6186 /* Shared Memory security operations */
6187 static int selinux_shm_alloc_security(struct kern_ipc_perm *shp)
6188 {
6189         struct ipc_security_struct *isec;
6190         struct common_audit_data ad;
6191         u32 sid = current_sid();
6192         int rc;
6193
6194         isec = selinux_ipc(shp);
6195         ipc_init_security(isec, SECCLASS_SHM);
6196
6197         ad.type = LSM_AUDIT_DATA_IPC;
6198         ad.u.ipc_id = shp->key;
6199
6200         rc = avc_has_perm(&selinux_state,
6201                           sid, isec->sid, SECCLASS_SHM,
6202                           SHM__CREATE, &ad);
6203         return rc;
6204 }
6205
6206 static int selinux_shm_associate(struct kern_ipc_perm *shp, int shmflg)
6207 {
6208         struct ipc_security_struct *isec;
6209         struct common_audit_data ad;
6210         u32 sid = current_sid();
6211
6212         isec = selinux_ipc(shp);
6213
6214         ad.type = LSM_AUDIT_DATA_IPC;
6215         ad.u.ipc_id = shp->key;
6216
6217         return avc_has_perm(&selinux_state,
6218                             sid, isec->sid, SECCLASS_SHM,
6219                             SHM__ASSOCIATE, &ad);
6220 }
6221
6222 /* Note, at this point, shp is locked down */
6223 static int selinux_shm_shmctl(struct kern_ipc_perm *shp, int cmd)
6224 {
6225         int perms;
6226         int err;
6227
6228         switch (cmd) {
6229         case IPC_INFO:
6230         case SHM_INFO:
6231                 /* No specific object, just general system-wide information. */
6232                 return avc_has_perm(&selinux_state,
6233                                     current_sid(), SECINITSID_KERNEL,
6234                                     SECCLASS_SYSTEM, SYSTEM__IPC_INFO, NULL);
6235         case IPC_STAT:
6236         case SHM_STAT:
6237         case SHM_STAT_ANY:
6238                 perms = SHM__GETATTR | SHM__ASSOCIATE;
6239                 break;
6240         case IPC_SET:
6241                 perms = SHM__SETATTR;
6242                 break;
6243         case SHM_LOCK:
6244         case SHM_UNLOCK:
6245                 perms = SHM__LOCK;
6246                 break;
6247         case IPC_RMID:
6248                 perms = SHM__DESTROY;
6249                 break;
6250         default:
6251                 return 0;
6252         }
6253
6254         err = ipc_has_perm(shp, perms);
6255         return err;
6256 }
6257
6258 static int selinux_shm_shmat(struct kern_ipc_perm *shp,
6259                              char __user *shmaddr, int shmflg)
6260 {
6261         u32 perms;
6262
6263         if (shmflg & SHM_RDONLY)
6264                 perms = SHM__READ;
6265         else
6266                 perms = SHM__READ | SHM__WRITE;
6267
6268         return ipc_has_perm(shp, perms);
6269 }
6270
6271 /* Semaphore security operations */
6272 static int selinux_sem_alloc_security(struct kern_ipc_perm *sma)
6273 {
6274         struct ipc_security_struct *isec;
6275         struct common_audit_data ad;
6276         u32 sid = current_sid();
6277         int rc;
6278
6279         isec = selinux_ipc(sma);
6280         ipc_init_security(isec, SECCLASS_SEM);
6281
6282         ad.type = LSM_AUDIT_DATA_IPC;
6283         ad.u.ipc_id = sma->key;
6284
6285         rc = avc_has_perm(&selinux_state,
6286                           sid, isec->sid, SECCLASS_SEM,
6287                           SEM__CREATE, &ad);
6288         return rc;
6289 }
6290
6291 static int selinux_sem_associate(struct kern_ipc_perm *sma, int semflg)
6292 {
6293         struct ipc_security_struct *isec;
6294         struct common_audit_data ad;
6295         u32 sid = current_sid();
6296
6297         isec = selinux_ipc(sma);
6298
6299         ad.type = LSM_AUDIT_DATA_IPC;
6300         ad.u.ipc_id = sma->key;
6301
6302         return avc_has_perm(&selinux_state,
6303                             sid, isec->sid, SECCLASS_SEM,
6304                             SEM__ASSOCIATE, &ad);
6305 }
6306
6307 /* Note, at this point, sma is locked down */
6308 static int selinux_sem_semctl(struct kern_ipc_perm *sma, int cmd)
6309 {
6310         int err;
6311         u32 perms;
6312
6313         switch (cmd) {
6314         case IPC_INFO:
6315         case SEM_INFO:
6316                 /* No specific object, just general system-wide information. */
6317                 return avc_has_perm(&selinux_state,
6318                                     current_sid(), SECINITSID_KERNEL,
6319                                     SECCLASS_SYSTEM, SYSTEM__IPC_INFO, NULL);
6320         case GETPID:
6321         case GETNCNT:
6322         case GETZCNT:
6323                 perms = SEM__GETATTR;
6324                 break;
6325         case GETVAL:
6326         case GETALL:
6327                 perms = SEM__READ;
6328                 break;
6329         case SETVAL:
6330         case SETALL:
6331                 perms = SEM__WRITE;
6332                 break;
6333         case IPC_RMID:
6334                 perms = SEM__DESTROY;
6335                 break;
6336         case IPC_SET:
6337                 perms = SEM__SETATTR;
6338                 break;
6339         case IPC_STAT:
6340         case SEM_STAT:
6341         case SEM_STAT_ANY:
6342                 perms = SEM__GETATTR | SEM__ASSOCIATE;
6343                 break;
6344         default:
6345                 return 0;
6346         }
6347
6348         err = ipc_has_perm(sma, perms);
6349         return err;
6350 }
6351
6352 static int selinux_sem_semop(struct kern_ipc_perm *sma,
6353                              struct sembuf *sops, unsigned nsops, int alter)
6354 {
6355         u32 perms;
6356
6357         if (alter)
6358                 perms = SEM__READ | SEM__WRITE;
6359         else
6360                 perms = SEM__READ;
6361
6362         return ipc_has_perm(sma, perms);
6363 }
6364
6365 static int selinux_ipc_permission(struct kern_ipc_perm *ipcp, short flag)
6366 {
6367         u32 av = 0;
6368
6369         av = 0;
6370         if (flag & S_IRUGO)
6371                 av |= IPC__UNIX_READ;
6372         if (flag & S_IWUGO)
6373                 av |= IPC__UNIX_WRITE;
6374
6375         if (av == 0)
6376                 return 0;
6377
6378         return ipc_has_perm(ipcp, av);
6379 }
6380
6381 static void selinux_ipc_getsecid(struct kern_ipc_perm *ipcp, u32 *secid)
6382 {
6383         struct ipc_security_struct *isec = selinux_ipc(ipcp);
6384         *secid = isec->sid;
6385 }
6386
6387 static void selinux_d_instantiate(struct dentry *dentry, struct inode *inode)
6388 {
6389         if (inode)
6390                 inode_doinit_with_dentry(inode, dentry);
6391 }
6392
6393 static int selinux_getprocattr(struct task_struct *p,
6394                                char *name, char **value)
6395 {
6396         const struct task_security_struct *__tsec;
6397         u32 sid;
6398         int error;
6399         unsigned len;
6400
6401         rcu_read_lock();
6402         __tsec = selinux_cred(__task_cred(p));
6403
6404         if (current != p) {
6405                 error = avc_has_perm(&selinux_state,
6406                                      current_sid(), __tsec->sid,
6407                                      SECCLASS_PROCESS, PROCESS__GETATTR, NULL);
6408                 if (error)
6409                         goto bad;
6410         }
6411
6412         if (!strcmp(name, "current"))
6413                 sid = __tsec->sid;
6414         else if (!strcmp(name, "prev"))
6415                 sid = __tsec->osid;
6416         else if (!strcmp(name, "exec"))
6417                 sid = __tsec->exec_sid;
6418         else if (!strcmp(name, "fscreate"))
6419                 sid = __tsec->create_sid;
6420         else if (!strcmp(name, "keycreate"))
6421                 sid = __tsec->keycreate_sid;
6422         else if (!strcmp(name, "sockcreate"))
6423                 sid = __tsec->sockcreate_sid;
6424         else {
6425                 error = -EINVAL;
6426                 goto bad;
6427         }
6428         rcu_read_unlock();
6429
6430         if (!sid)
6431                 return 0;
6432
6433         error = security_sid_to_context(&selinux_state, sid, value, &len);
6434         if (error)
6435                 return error;
6436         return len;
6437
6438 bad:
6439         rcu_read_unlock();
6440         return error;
6441 }
6442
6443 static int selinux_setprocattr(const char *name, void *value, size_t size)
6444 {
6445         struct task_security_struct *tsec;
6446         struct cred *new;
6447         u32 mysid = current_sid(), sid = 0, ptsid;
6448         int error;
6449         char *str = value;
6450
6451         /*
6452          * Basic control over ability to set these attributes at all.
6453          */
6454         if (!strcmp(name, "exec"))
6455                 error = avc_has_perm(&selinux_state,
6456                                      mysid, mysid, SECCLASS_PROCESS,
6457                                      PROCESS__SETEXEC, NULL);
6458         else if (!strcmp(name, "fscreate"))
6459                 error = avc_has_perm(&selinux_state,
6460                                      mysid, mysid, SECCLASS_PROCESS,
6461                                      PROCESS__SETFSCREATE, NULL);
6462         else if (!strcmp(name, "keycreate"))
6463                 error = avc_has_perm(&selinux_state,
6464                                      mysid, mysid, SECCLASS_PROCESS,
6465                                      PROCESS__SETKEYCREATE, NULL);
6466         else if (!strcmp(name, "sockcreate"))
6467                 error = avc_has_perm(&selinux_state,
6468                                      mysid, mysid, SECCLASS_PROCESS,
6469                                      PROCESS__SETSOCKCREATE, NULL);
6470         else if (!strcmp(name, "current"))
6471                 error = avc_has_perm(&selinux_state,
6472                                      mysid, mysid, SECCLASS_PROCESS,
6473                                      PROCESS__SETCURRENT, NULL);
6474         else
6475                 error = -EINVAL;
6476         if (error)
6477                 return error;
6478
6479         /* Obtain a SID for the context, if one was specified. */
6480         if (size && str[0] && str[0] != '\n') {
6481                 if (str[size-1] == '\n') {
6482                         str[size-1] = 0;
6483                         size--;
6484                 }
6485                 error = security_context_to_sid(&selinux_state, value, size,
6486                                                 &sid, GFP_KERNEL);
6487                 if (error == -EINVAL && !strcmp(name, "fscreate")) {
6488                         if (!has_cap_mac_admin(true)) {
6489                                 struct audit_buffer *ab;
6490                                 size_t audit_size;
6491
6492                                 /* We strip a nul only if it is at the end, otherwise the
6493                                  * context contains a nul and we should audit that */
6494                                 if (str[size - 1] == '\0')
6495                                         audit_size = size - 1;
6496                                 else
6497                                         audit_size = size;
6498                                 ab = audit_log_start(audit_context(),
6499                                                      GFP_ATOMIC,
6500                                                      AUDIT_SELINUX_ERR);
6501                                 if (!ab)
6502                                         return error;
6503                                 audit_log_format(ab, "op=fscreate invalid_context=");
6504                                 audit_log_n_untrustedstring(ab, value, audit_size);
6505                                 audit_log_end(ab);
6506
6507                                 return error;
6508                         }
6509                         error = security_context_to_sid_force(
6510                                                       &selinux_state,
6511                                                       value, size, &sid);
6512                 }
6513                 if (error)
6514                         return error;
6515         }
6516
6517         new = prepare_creds();
6518         if (!new)
6519                 return -ENOMEM;
6520
6521         /* Permission checking based on the specified context is
6522            performed during the actual operation (execve,
6523            open/mkdir/...), when we know the full context of the
6524            operation.  See selinux_bprm_creds_for_exec for the execve
6525            checks and may_create for the file creation checks. The
6526            operation will then fail if the context is not permitted. */
6527         tsec = selinux_cred(new);
6528         if (!strcmp(name, "exec")) {
6529                 tsec->exec_sid = sid;
6530         } else if (!strcmp(name, "fscreate")) {
6531                 tsec->create_sid = sid;
6532         } else if (!strcmp(name, "keycreate")) {
6533                 if (sid) {
6534                         error = avc_has_perm(&selinux_state, mysid, sid,
6535                                              SECCLASS_KEY, KEY__CREATE, NULL);
6536                         if (error)
6537                                 goto abort_change;
6538                 }
6539                 tsec->keycreate_sid = sid;
6540         } else if (!strcmp(name, "sockcreate")) {
6541                 tsec->sockcreate_sid = sid;
6542         } else if (!strcmp(name, "current")) {
6543                 error = -EINVAL;
6544                 if (sid == 0)
6545                         goto abort_change;
6546
6547                 /* Only allow single threaded processes to change context */
6548                 error = -EPERM;
6549                 if (!current_is_single_threaded()) {
6550                         error = security_bounded_transition(&selinux_state,
6551                                                             tsec->sid, sid);
6552                         if (error)
6553                                 goto abort_change;
6554                 }
6555
6556                 /* Check permissions for the transition. */
6557                 error = avc_has_perm(&selinux_state,
6558                                      tsec->sid, sid, SECCLASS_PROCESS,
6559                                      PROCESS__DYNTRANSITION, NULL);
6560                 if (error)
6561                         goto abort_change;
6562
6563                 /* Check for ptracing, and update the task SID if ok.
6564                    Otherwise, leave SID unchanged and fail. */
6565                 ptsid = ptrace_parent_sid();
6566                 if (ptsid != 0) {
6567                         error = avc_has_perm(&selinux_state,
6568                                              ptsid, sid, SECCLASS_PROCESS,
6569                                              PROCESS__PTRACE, NULL);
6570                         if (error)
6571                                 goto abort_change;
6572                 }
6573
6574                 tsec->sid = sid;
6575         } else {
6576                 error = -EINVAL;
6577                 goto abort_change;
6578         }
6579
6580         commit_creds(new);
6581         return size;
6582
6583 abort_change:
6584         abort_creds(new);
6585         return error;
6586 }
6587
6588 static int selinux_ismaclabel(const char *name)
6589 {
6590         return (strcmp(name, XATTR_SELINUX_SUFFIX) == 0);
6591 }
6592
6593 static int selinux_secid_to_secctx(u32 secid, char **secdata, u32 *seclen)
6594 {
6595         return security_sid_to_context(&selinux_state, secid,
6596                                        secdata, seclen);
6597 }
6598
6599 static int selinux_secctx_to_secid(const char *secdata, u32 seclen, u32 *secid)
6600 {
6601         return security_context_to_sid(&selinux_state, secdata, seclen,
6602                                        secid, GFP_KERNEL);
6603 }
6604
6605 static void selinux_release_secctx(char *secdata, u32 seclen)
6606 {
6607         kfree(secdata);
6608 }
6609
6610 static void selinux_inode_invalidate_secctx(struct inode *inode)
6611 {
6612         struct inode_security_struct *isec = selinux_inode(inode);
6613
6614         spin_lock(&isec->lock);
6615         isec->initialized = LABEL_INVALID;
6616         spin_unlock(&isec->lock);
6617 }
6618
6619 /*
6620  *      called with inode->i_mutex locked
6621  */
6622 static int selinux_inode_notifysecctx(struct inode *inode, void *ctx, u32 ctxlen)
6623 {
6624         int rc = selinux_inode_setsecurity(inode, XATTR_SELINUX_SUFFIX,
6625                                            ctx, ctxlen, 0);
6626         /* Do not return error when suppressing label (SBLABEL_MNT not set). */
6627         return rc == -EOPNOTSUPP ? 0 : rc;
6628 }
6629
6630 /*
6631  *      called with inode->i_mutex locked
6632  */
6633 static int selinux_inode_setsecctx(struct dentry *dentry, void *ctx, u32 ctxlen)
6634 {
6635         return __vfs_setxattr_noperm(&init_user_ns, dentry, XATTR_NAME_SELINUX,
6636                                      ctx, ctxlen, 0);
6637 }
6638
6639 static int selinux_inode_getsecctx(struct inode *inode, void **ctx, u32 *ctxlen)
6640 {
6641         int len = 0;
6642         len = selinux_inode_getsecurity(&init_user_ns, inode,
6643                                         XATTR_SELINUX_SUFFIX, ctx, true);
6644         if (len < 0)
6645                 return len;
6646         *ctxlen = len;
6647         return 0;
6648 }
6649 #ifdef CONFIG_KEYS
6650
6651 static int selinux_key_alloc(struct key *k, const struct cred *cred,
6652                              unsigned long flags)
6653 {
6654         const struct task_security_struct *tsec;
6655         struct key_security_struct *ksec;
6656
6657         ksec = kzalloc(sizeof(struct key_security_struct), GFP_KERNEL);
6658         if (!ksec)
6659                 return -ENOMEM;
6660
6661         tsec = selinux_cred(cred);
6662         if (tsec->keycreate_sid)
6663                 ksec->sid = tsec->keycreate_sid;
6664         else
6665                 ksec->sid = tsec->sid;
6666
6667         k->security = ksec;
6668         return 0;
6669 }
6670
6671 static void selinux_key_free(struct key *k)
6672 {
6673         struct key_security_struct *ksec = k->security;
6674
6675         k->security = NULL;
6676         kfree(ksec);
6677 }
6678
6679 static int selinux_key_permission(key_ref_t key_ref,
6680                                   const struct cred *cred,
6681                                   enum key_need_perm need_perm)
6682 {
6683         struct key *key;
6684         struct key_security_struct *ksec;
6685         u32 perm, sid;
6686
6687         switch (need_perm) {
6688         case KEY_NEED_VIEW:
6689                 perm = KEY__VIEW;
6690                 break;
6691         case KEY_NEED_READ:
6692                 perm = KEY__READ;
6693                 break;
6694         case KEY_NEED_WRITE:
6695                 perm = KEY__WRITE;
6696                 break;
6697         case KEY_NEED_SEARCH:
6698                 perm = KEY__SEARCH;
6699                 break;
6700         case KEY_NEED_LINK:
6701                 perm = KEY__LINK;
6702                 break;
6703         case KEY_NEED_SETATTR:
6704                 perm = KEY__SETATTR;
6705                 break;
6706         case KEY_NEED_UNLINK:
6707         case KEY_SYSADMIN_OVERRIDE:
6708         case KEY_AUTHTOKEN_OVERRIDE:
6709         case KEY_DEFER_PERM_CHECK:
6710                 return 0;
6711         default:
6712                 WARN_ON(1);
6713                 return -EPERM;
6714
6715         }
6716
6717         sid = cred_sid(cred);
6718         key = key_ref_to_ptr(key_ref);
6719         ksec = key->security;
6720
6721         return avc_has_perm(&selinux_state,
6722                             sid, ksec->sid, SECCLASS_KEY, perm, NULL);
6723 }
6724
6725 static int selinux_key_getsecurity(struct key *key, char **_buffer)
6726 {
6727         struct key_security_struct *ksec = key->security;
6728         char *context = NULL;
6729         unsigned len;
6730         int rc;
6731
6732         rc = security_sid_to_context(&selinux_state, ksec->sid,
6733                                      &context, &len);
6734         if (!rc)
6735                 rc = len;
6736         *_buffer = context;
6737         return rc;
6738 }
6739
6740 #ifdef CONFIG_KEY_NOTIFICATIONS
6741 static int selinux_watch_key(struct key *key)
6742 {
6743         struct key_security_struct *ksec = key->security;
6744         u32 sid = current_sid();
6745
6746         return avc_has_perm(&selinux_state,
6747                             sid, ksec->sid, SECCLASS_KEY, KEY__VIEW, NULL);
6748 }
6749 #endif
6750 #endif
6751
6752 #ifdef CONFIG_SECURITY_INFINIBAND
6753 static int selinux_ib_pkey_access(void *ib_sec, u64 subnet_prefix, u16 pkey_val)
6754 {
6755         struct common_audit_data ad;
6756         int err;
6757         u32 sid = 0;
6758         struct ib_security_struct *sec = ib_sec;
6759         struct lsm_ibpkey_audit ibpkey;
6760
6761         err = sel_ib_pkey_sid(subnet_prefix, pkey_val, &sid);
6762         if (err)
6763                 return err;
6764
6765         ad.type = LSM_AUDIT_DATA_IBPKEY;
6766         ibpkey.subnet_prefix = subnet_prefix;
6767         ibpkey.pkey = pkey_val;
6768         ad.u.ibpkey = &ibpkey;
6769         return avc_has_perm(&selinux_state,
6770                             sec->sid, sid,
6771                             SECCLASS_INFINIBAND_PKEY,
6772                             INFINIBAND_PKEY__ACCESS, &ad);
6773 }
6774
6775 static int selinux_ib_endport_manage_subnet(void *ib_sec, const char *dev_name,
6776                                             u8 port_num)
6777 {
6778         struct common_audit_data ad;
6779         int err;
6780         u32 sid = 0;
6781         struct ib_security_struct *sec = ib_sec;
6782         struct lsm_ibendport_audit ibendport;
6783
6784         err = security_ib_endport_sid(&selinux_state, dev_name, port_num,
6785                                       &sid);
6786
6787         if (err)
6788                 return err;
6789
6790         ad.type = LSM_AUDIT_DATA_IBENDPORT;
6791         ibendport.dev_name = dev_name;
6792         ibendport.port = port_num;
6793         ad.u.ibendport = &ibendport;
6794         return avc_has_perm(&selinux_state,
6795                             sec->sid, sid,
6796                             SECCLASS_INFINIBAND_ENDPORT,
6797                             INFINIBAND_ENDPORT__MANAGE_SUBNET, &ad);
6798 }
6799
6800 static int selinux_ib_alloc_security(void **ib_sec)
6801 {
6802         struct ib_security_struct *sec;
6803
6804         sec = kzalloc(sizeof(*sec), GFP_KERNEL);
6805         if (!sec)
6806                 return -ENOMEM;
6807         sec->sid = current_sid();
6808
6809         *ib_sec = sec;
6810         return 0;
6811 }
6812
6813 static void selinux_ib_free_security(void *ib_sec)
6814 {
6815         kfree(ib_sec);
6816 }
6817 #endif
6818
6819 #ifdef CONFIG_BPF_SYSCALL
6820 static int selinux_bpf(int cmd, union bpf_attr *attr,
6821                                      unsigned int size)
6822 {
6823         u32 sid = current_sid();
6824         int ret;
6825
6826         switch (cmd) {
6827         case BPF_MAP_CREATE:
6828                 ret = avc_has_perm(&selinux_state,
6829                                    sid, sid, SECCLASS_BPF, BPF__MAP_CREATE,
6830                                    NULL);
6831                 break;
6832         case BPF_PROG_LOAD:
6833                 ret = avc_has_perm(&selinux_state,
6834                                    sid, sid, SECCLASS_BPF, BPF__PROG_LOAD,
6835                                    NULL);
6836                 break;
6837         default:
6838                 ret = 0;
6839                 break;
6840         }
6841
6842         return ret;
6843 }
6844
6845 static u32 bpf_map_fmode_to_av(fmode_t fmode)
6846 {
6847         u32 av = 0;
6848
6849         if (fmode & FMODE_READ)
6850                 av |= BPF__MAP_READ;
6851         if (fmode & FMODE_WRITE)
6852                 av |= BPF__MAP_WRITE;
6853         return av;
6854 }
6855
6856 /* This function will check the file pass through unix socket or binder to see
6857  * if it is a bpf related object. And apply correspinding checks on the bpf
6858  * object based on the type. The bpf maps and programs, not like other files and
6859  * socket, are using a shared anonymous inode inside the kernel as their inode.
6860  * So checking that inode cannot identify if the process have privilege to
6861  * access the bpf object and that's why we have to add this additional check in
6862  * selinux_file_receive and selinux_binder_transfer_files.
6863  */
6864 static int bpf_fd_pass(struct file *file, u32 sid)
6865 {
6866         struct bpf_security_struct *bpfsec;
6867         struct bpf_prog *prog;
6868         struct bpf_map *map;
6869         int ret;
6870
6871         if (file->f_op == &bpf_map_fops) {
6872                 map = file->private_data;
6873                 bpfsec = map->security;
6874                 ret = avc_has_perm(&selinux_state,
6875                                    sid, bpfsec->sid, SECCLASS_BPF,
6876                                    bpf_map_fmode_to_av(file->f_mode), NULL);
6877                 if (ret)
6878                         return ret;
6879         } else if (file->f_op == &bpf_prog_fops) {
6880                 prog = file->private_data;
6881                 bpfsec = prog->aux->security;
6882                 ret = avc_has_perm(&selinux_state,
6883                                    sid, bpfsec->sid, SECCLASS_BPF,
6884                                    BPF__PROG_RUN, NULL);
6885                 if (ret)
6886                         return ret;
6887         }
6888         return 0;
6889 }
6890
6891 static int selinux_bpf_map(struct bpf_map *map, fmode_t fmode)
6892 {
6893         u32 sid = current_sid();
6894         struct bpf_security_struct *bpfsec;
6895
6896         bpfsec = map->security;
6897         return avc_has_perm(&selinux_state,
6898                             sid, bpfsec->sid, SECCLASS_BPF,
6899                             bpf_map_fmode_to_av(fmode), NULL);
6900 }
6901
6902 static int selinux_bpf_prog(struct bpf_prog *prog)
6903 {
6904         u32 sid = current_sid();
6905         struct bpf_security_struct *bpfsec;
6906
6907         bpfsec = prog->aux->security;
6908         return avc_has_perm(&selinux_state,
6909                             sid, bpfsec->sid, SECCLASS_BPF,
6910                             BPF__PROG_RUN, NULL);
6911 }
6912
6913 static int selinux_bpf_map_alloc(struct bpf_map *map)
6914 {
6915         struct bpf_security_struct *bpfsec;
6916
6917         bpfsec = kzalloc(sizeof(*bpfsec), GFP_KERNEL);
6918         if (!bpfsec)
6919                 return -ENOMEM;
6920
6921         bpfsec->sid = current_sid();
6922         map->security = bpfsec;
6923
6924         return 0;
6925 }
6926
6927 static void selinux_bpf_map_free(struct bpf_map *map)
6928 {
6929         struct bpf_security_struct *bpfsec = map->security;
6930
6931         map->security = NULL;
6932         kfree(bpfsec);
6933 }
6934
6935 static int selinux_bpf_prog_alloc(struct bpf_prog_aux *aux)
6936 {
6937         struct bpf_security_struct *bpfsec;
6938
6939         bpfsec = kzalloc(sizeof(*bpfsec), GFP_KERNEL);
6940         if (!bpfsec)
6941                 return -ENOMEM;
6942
6943         bpfsec->sid = current_sid();
6944         aux->security = bpfsec;
6945
6946         return 0;
6947 }
6948
6949 static void selinux_bpf_prog_free(struct bpf_prog_aux *aux)
6950 {
6951         struct bpf_security_struct *bpfsec = aux->security;
6952
6953         aux->security = NULL;
6954         kfree(bpfsec);
6955 }
6956 #endif
6957
6958 struct lsm_blob_sizes selinux_blob_sizes __lsm_ro_after_init = {
6959         .lbs_cred = sizeof(struct task_security_struct),
6960         .lbs_file = sizeof(struct file_security_struct),
6961         .lbs_inode = sizeof(struct inode_security_struct),
6962         .lbs_ipc = sizeof(struct ipc_security_struct),
6963         .lbs_msg_msg = sizeof(struct msg_security_struct),
6964         .lbs_superblock = sizeof(struct superblock_security_struct),
6965 };
6966
6967 #ifdef CONFIG_PERF_EVENTS
6968 static int selinux_perf_event_open(struct perf_event_attr *attr, int type)
6969 {
6970         u32 requested, sid = current_sid();
6971
6972         if (type == PERF_SECURITY_OPEN)
6973                 requested = PERF_EVENT__OPEN;
6974         else if (type == PERF_SECURITY_CPU)
6975                 requested = PERF_EVENT__CPU;
6976         else if (type == PERF_SECURITY_KERNEL)
6977                 requested = PERF_EVENT__KERNEL;
6978         else if (type == PERF_SECURITY_TRACEPOINT)
6979                 requested = PERF_EVENT__TRACEPOINT;
6980         else
6981                 return -EINVAL;
6982
6983         return avc_has_perm(&selinux_state, sid, sid, SECCLASS_PERF_EVENT,
6984                             requested, NULL);
6985 }
6986
6987 static int selinux_perf_event_alloc(struct perf_event *event)
6988 {
6989         struct perf_event_security_struct *perfsec;
6990
6991         perfsec = kzalloc(sizeof(*perfsec), GFP_KERNEL);
6992         if (!perfsec)
6993                 return -ENOMEM;
6994
6995         perfsec->sid = current_sid();
6996         event->security = perfsec;
6997
6998         return 0;
6999 }
7000
7001 static void selinux_perf_event_free(struct perf_event *event)
7002 {
7003         struct perf_event_security_struct *perfsec = event->security;
7004
7005         event->security = NULL;
7006         kfree(perfsec);
7007 }
7008
7009 static int selinux_perf_event_read(struct perf_event *event)
7010 {
7011         struct perf_event_security_struct *perfsec = event->security;
7012         u32 sid = current_sid();
7013
7014         return avc_has_perm(&selinux_state, sid, perfsec->sid,
7015                             SECCLASS_PERF_EVENT, PERF_EVENT__READ, NULL);
7016 }
7017
7018 static int selinux_perf_event_write(struct perf_event *event)
7019 {
7020         struct perf_event_security_struct *perfsec = event->security;
7021         u32 sid = current_sid();
7022
7023         return avc_has_perm(&selinux_state, sid, perfsec->sid,
7024                             SECCLASS_PERF_EVENT, PERF_EVENT__WRITE, NULL);
7025 }
7026 #endif
7027
7028 #ifdef CONFIG_IO_URING
7029 /**
7030  * selinux_uring_override_creds - check the requested cred override
7031  * @new: the target creds
7032  *
7033  * Check to see if the current task is allowed to override it's credentials
7034  * to service an io_uring operation.
7035  */
7036 static int selinux_uring_override_creds(const struct cred *new)
7037 {
7038         return avc_has_perm(&selinux_state, current_sid(), cred_sid(new),
7039                             SECCLASS_IO_URING, IO_URING__OVERRIDE_CREDS, NULL);
7040 }
7041
7042 /**
7043  * selinux_uring_sqpoll - check if a io_uring polling thread can be created
7044  *
7045  * Check to see if the current task is allowed to create a new io_uring
7046  * kernel polling thread.
7047  */
7048 static int selinux_uring_sqpoll(void)
7049 {
7050         int sid = current_sid();
7051
7052         return avc_has_perm(&selinux_state, sid, sid,
7053                             SECCLASS_IO_URING, IO_URING__SQPOLL, NULL);
7054 }
7055 #endif /* CONFIG_IO_URING */
7056
7057 /*
7058  * IMPORTANT NOTE: When adding new hooks, please be careful to keep this order:
7059  * 1. any hooks that don't belong to (2.) or (3.) below,
7060  * 2. hooks that both access structures allocated by other hooks, and allocate
7061  *    structures that can be later accessed by other hooks (mostly "cloning"
7062  *    hooks),
7063  * 3. hooks that only allocate structures that can be later accessed by other
7064  *    hooks ("allocating" hooks).
7065  *
7066  * Please follow block comment delimiters in the list to keep this order.
7067  *
7068  * This ordering is needed for SELinux runtime disable to work at least somewhat
7069  * safely. Breaking the ordering rules above might lead to NULL pointer derefs
7070  * when disabling SELinux at runtime.
7071  */
7072 static struct security_hook_list selinux_hooks[] __lsm_ro_after_init = {
7073         LSM_HOOK_INIT(binder_set_context_mgr, selinux_binder_set_context_mgr),
7074         LSM_HOOK_INIT(binder_transaction, selinux_binder_transaction),
7075         LSM_HOOK_INIT(binder_transfer_binder, selinux_binder_transfer_binder),
7076         LSM_HOOK_INIT(binder_transfer_file, selinux_binder_transfer_file),
7077
7078         LSM_HOOK_INIT(ptrace_access_check, selinux_ptrace_access_check),
7079         LSM_HOOK_INIT(ptrace_traceme, selinux_ptrace_traceme),
7080         LSM_HOOK_INIT(capget, selinux_capget),
7081         LSM_HOOK_INIT(capset, selinux_capset),
7082         LSM_HOOK_INIT(capable, selinux_capable),
7083         LSM_HOOK_INIT(quotactl, selinux_quotactl),
7084         LSM_HOOK_INIT(quota_on, selinux_quota_on),
7085         LSM_HOOK_INIT(syslog, selinux_syslog),
7086         LSM_HOOK_INIT(vm_enough_memory, selinux_vm_enough_memory),
7087
7088         LSM_HOOK_INIT(netlink_send, selinux_netlink_send),
7089
7090         LSM_HOOK_INIT(bprm_creds_for_exec, selinux_bprm_creds_for_exec),
7091         LSM_HOOK_INIT(bprm_committing_creds, selinux_bprm_committing_creds),
7092         LSM_HOOK_INIT(bprm_committed_creds, selinux_bprm_committed_creds),
7093
7094         LSM_HOOK_INIT(sb_free_mnt_opts, selinux_free_mnt_opts),
7095         LSM_HOOK_INIT(sb_mnt_opts_compat, selinux_sb_mnt_opts_compat),
7096         LSM_HOOK_INIT(sb_remount, selinux_sb_remount),
7097         LSM_HOOK_INIT(sb_kern_mount, selinux_sb_kern_mount),
7098         LSM_HOOK_INIT(sb_show_options, selinux_sb_show_options),
7099         LSM_HOOK_INIT(sb_statfs, selinux_sb_statfs),
7100         LSM_HOOK_INIT(sb_mount, selinux_mount),
7101         LSM_HOOK_INIT(sb_umount, selinux_umount),
7102         LSM_HOOK_INIT(sb_set_mnt_opts, selinux_set_mnt_opts),
7103         LSM_HOOK_INIT(sb_clone_mnt_opts, selinux_sb_clone_mnt_opts),
7104
7105         LSM_HOOK_INIT(move_mount, selinux_move_mount),
7106
7107         LSM_HOOK_INIT(dentry_init_security, selinux_dentry_init_security),
7108         LSM_HOOK_INIT(dentry_create_files_as, selinux_dentry_create_files_as),
7109
7110         LSM_HOOK_INIT(inode_free_security, selinux_inode_free_security),
7111         LSM_HOOK_INIT(inode_init_security, selinux_inode_init_security),
7112         LSM_HOOK_INIT(inode_init_security_anon, selinux_inode_init_security_anon),
7113         LSM_HOOK_INIT(inode_create, selinux_inode_create),
7114         LSM_HOOK_INIT(inode_link, selinux_inode_link),
7115         LSM_HOOK_INIT(inode_unlink, selinux_inode_unlink),
7116         LSM_HOOK_INIT(inode_symlink, selinux_inode_symlink),
7117         LSM_HOOK_INIT(inode_mkdir, selinux_inode_mkdir),
7118         LSM_HOOK_INIT(inode_rmdir, selinux_inode_rmdir),
7119         LSM_HOOK_INIT(inode_mknod, selinux_inode_mknod),
7120         LSM_HOOK_INIT(inode_rename, selinux_inode_rename),
7121         LSM_HOOK_INIT(inode_readlink, selinux_inode_readlink),
7122         LSM_HOOK_INIT(inode_follow_link, selinux_inode_follow_link),
7123         LSM_HOOK_INIT(inode_permission, selinux_inode_permission),
7124         LSM_HOOK_INIT(inode_setattr, selinux_inode_setattr),
7125         LSM_HOOK_INIT(inode_getattr, selinux_inode_getattr),
7126         LSM_HOOK_INIT(inode_setxattr, selinux_inode_setxattr),
7127         LSM_HOOK_INIT(inode_post_setxattr, selinux_inode_post_setxattr),
7128         LSM_HOOK_INIT(inode_getxattr, selinux_inode_getxattr),
7129         LSM_HOOK_INIT(inode_listxattr, selinux_inode_listxattr),
7130         LSM_HOOK_INIT(inode_removexattr, selinux_inode_removexattr),
7131         LSM_HOOK_INIT(inode_getsecurity, selinux_inode_getsecurity),
7132         LSM_HOOK_INIT(inode_setsecurity, selinux_inode_setsecurity),
7133         LSM_HOOK_INIT(inode_listsecurity, selinux_inode_listsecurity),
7134         LSM_HOOK_INIT(inode_getsecid, selinux_inode_getsecid),
7135         LSM_HOOK_INIT(inode_copy_up, selinux_inode_copy_up),
7136         LSM_HOOK_INIT(inode_copy_up_xattr, selinux_inode_copy_up_xattr),
7137         LSM_HOOK_INIT(path_notify, selinux_path_notify),
7138
7139         LSM_HOOK_INIT(kernfs_init_security, selinux_kernfs_init_security),
7140
7141         LSM_HOOK_INIT(file_permission, selinux_file_permission),
7142         LSM_HOOK_INIT(file_alloc_security, selinux_file_alloc_security),
7143         LSM_HOOK_INIT(file_ioctl, selinux_file_ioctl),
7144         LSM_HOOK_INIT(mmap_file, selinux_mmap_file),
7145         LSM_HOOK_INIT(mmap_addr, selinux_mmap_addr),
7146         LSM_HOOK_INIT(file_mprotect, selinux_file_mprotect),
7147         LSM_HOOK_INIT(file_lock, selinux_file_lock),
7148         LSM_HOOK_INIT(file_fcntl, selinux_file_fcntl),
7149         LSM_HOOK_INIT(file_set_fowner, selinux_file_set_fowner),
7150         LSM_HOOK_INIT(file_send_sigiotask, selinux_file_send_sigiotask),
7151         LSM_HOOK_INIT(file_receive, selinux_file_receive),
7152
7153         LSM_HOOK_INIT(file_open, selinux_file_open),
7154
7155         LSM_HOOK_INIT(task_alloc, selinux_task_alloc),
7156         LSM_HOOK_INIT(cred_prepare, selinux_cred_prepare),
7157         LSM_HOOK_INIT(cred_transfer, selinux_cred_transfer),
7158         LSM_HOOK_INIT(cred_getsecid, selinux_cred_getsecid),
7159         LSM_HOOK_INIT(kernel_act_as, selinux_kernel_act_as),
7160         LSM_HOOK_INIT(kernel_create_files_as, selinux_kernel_create_files_as),
7161         LSM_HOOK_INIT(kernel_module_request, selinux_kernel_module_request),
7162         LSM_HOOK_INIT(kernel_load_data, selinux_kernel_load_data),
7163         LSM_HOOK_INIT(kernel_read_file, selinux_kernel_read_file),
7164         LSM_HOOK_INIT(task_setpgid, selinux_task_setpgid),
7165         LSM_HOOK_INIT(task_getpgid, selinux_task_getpgid),
7166         LSM_HOOK_INIT(task_getsid, selinux_task_getsid),
7167         LSM_HOOK_INIT(task_getsecid_subj, selinux_task_getsecid_subj),
7168         LSM_HOOK_INIT(task_getsecid_obj, selinux_task_getsecid_obj),
7169         LSM_HOOK_INIT(task_setnice, selinux_task_setnice),
7170         LSM_HOOK_INIT(task_setioprio, selinux_task_setioprio),
7171         LSM_HOOK_INIT(task_getioprio, selinux_task_getioprio),
7172         LSM_HOOK_INIT(task_prlimit, selinux_task_prlimit),
7173         LSM_HOOK_INIT(task_setrlimit, selinux_task_setrlimit),
7174         LSM_HOOK_INIT(task_setscheduler, selinux_task_setscheduler),
7175         LSM_HOOK_INIT(task_getscheduler, selinux_task_getscheduler),
7176         LSM_HOOK_INIT(task_movememory, selinux_task_movememory),
7177         LSM_HOOK_INIT(task_kill, selinux_task_kill),
7178         LSM_HOOK_INIT(task_to_inode, selinux_task_to_inode),
7179
7180         LSM_HOOK_INIT(ipc_permission, selinux_ipc_permission),
7181         LSM_HOOK_INIT(ipc_getsecid, selinux_ipc_getsecid),
7182
7183         LSM_HOOK_INIT(msg_queue_associate, selinux_msg_queue_associate),
7184         LSM_HOOK_INIT(msg_queue_msgctl, selinux_msg_queue_msgctl),
7185         LSM_HOOK_INIT(msg_queue_msgsnd, selinux_msg_queue_msgsnd),
7186         LSM_HOOK_INIT(msg_queue_msgrcv, selinux_msg_queue_msgrcv),
7187
7188         LSM_HOOK_INIT(shm_associate, selinux_shm_associate),
7189         LSM_HOOK_INIT(shm_shmctl, selinux_shm_shmctl),
7190         LSM_HOOK_INIT(shm_shmat, selinux_shm_shmat),
7191
7192         LSM_HOOK_INIT(sem_associate, selinux_sem_associate),
7193         LSM_HOOK_INIT(sem_semctl, selinux_sem_semctl),
7194         LSM_HOOK_INIT(sem_semop, selinux_sem_semop),
7195
7196         LSM_HOOK_INIT(d_instantiate, selinux_d_instantiate),
7197
7198         LSM_HOOK_INIT(getprocattr, selinux_getprocattr),
7199         LSM_HOOK_INIT(setprocattr, selinux_setprocattr),
7200
7201         LSM_HOOK_INIT(ismaclabel, selinux_ismaclabel),
7202         LSM_HOOK_INIT(secctx_to_secid, selinux_secctx_to_secid),
7203         LSM_HOOK_INIT(release_secctx, selinux_release_secctx),
7204         LSM_HOOK_INIT(inode_invalidate_secctx, selinux_inode_invalidate_secctx),
7205         LSM_HOOK_INIT(inode_notifysecctx, selinux_inode_notifysecctx),
7206         LSM_HOOK_INIT(inode_setsecctx, selinux_inode_setsecctx),
7207
7208         LSM_HOOK_INIT(unix_stream_connect, selinux_socket_unix_stream_connect),
7209         LSM_HOOK_INIT(unix_may_send, selinux_socket_unix_may_send),
7210
7211         LSM_HOOK_INIT(socket_create, selinux_socket_create),
7212         LSM_HOOK_INIT(socket_post_create, selinux_socket_post_create),
7213         LSM_HOOK_INIT(socket_socketpair, selinux_socket_socketpair),
7214         LSM_HOOK_INIT(socket_bind, selinux_socket_bind),
7215         LSM_HOOK_INIT(socket_connect, selinux_socket_connect),
7216         LSM_HOOK_INIT(socket_listen, selinux_socket_listen),
7217         LSM_HOOK_INIT(socket_accept, selinux_socket_accept),
7218         LSM_HOOK_INIT(socket_sendmsg, selinux_socket_sendmsg),
7219         LSM_HOOK_INIT(socket_recvmsg, selinux_socket_recvmsg),
7220         LSM_HOOK_INIT(socket_getsockname, selinux_socket_getsockname),
7221         LSM_HOOK_INIT(socket_getpeername, selinux_socket_getpeername),
7222         LSM_HOOK_INIT(socket_getsockopt, selinux_socket_getsockopt),
7223         LSM_HOOK_INIT(socket_setsockopt, selinux_socket_setsockopt),
7224         LSM_HOOK_INIT(socket_shutdown, selinux_socket_shutdown),
7225         LSM_HOOK_INIT(socket_sock_rcv_skb, selinux_socket_sock_rcv_skb),
7226         LSM_HOOK_INIT(socket_getpeersec_stream,
7227                         selinux_socket_getpeersec_stream),
7228         LSM_HOOK_INIT(socket_getpeersec_dgram, selinux_socket_getpeersec_dgram),
7229         LSM_HOOK_INIT(sk_free_security, selinux_sk_free_security),
7230         LSM_HOOK_INIT(sk_clone_security, selinux_sk_clone_security),
7231         LSM_HOOK_INIT(sk_getsecid, selinux_sk_getsecid),
7232         LSM_HOOK_INIT(sock_graft, selinux_sock_graft),
7233         LSM_HOOK_INIT(sctp_assoc_request, selinux_sctp_assoc_request),
7234         LSM_HOOK_INIT(sctp_sk_clone, selinux_sctp_sk_clone),
7235         LSM_HOOK_INIT(sctp_bind_connect, selinux_sctp_bind_connect),
7236         LSM_HOOK_INIT(inet_conn_request, selinux_inet_conn_request),
7237         LSM_HOOK_INIT(inet_csk_clone, selinux_inet_csk_clone),
7238         LSM_HOOK_INIT(inet_conn_established, selinux_inet_conn_established),
7239         LSM_HOOK_INIT(secmark_relabel_packet, selinux_secmark_relabel_packet),
7240         LSM_HOOK_INIT(secmark_refcount_inc, selinux_secmark_refcount_inc),
7241         LSM_HOOK_INIT(secmark_refcount_dec, selinux_secmark_refcount_dec),
7242         LSM_HOOK_INIT(req_classify_flow, selinux_req_classify_flow),
7243         LSM_HOOK_INIT(tun_dev_free_security, selinux_tun_dev_free_security),
7244         LSM_HOOK_INIT(tun_dev_create, selinux_tun_dev_create),
7245         LSM_HOOK_INIT(tun_dev_attach_queue, selinux_tun_dev_attach_queue),
7246         LSM_HOOK_INIT(tun_dev_attach, selinux_tun_dev_attach),
7247         LSM_HOOK_INIT(tun_dev_open, selinux_tun_dev_open),
7248 #ifdef CONFIG_SECURITY_INFINIBAND
7249         LSM_HOOK_INIT(ib_pkey_access, selinux_ib_pkey_access),
7250         LSM_HOOK_INIT(ib_endport_manage_subnet,
7251                       selinux_ib_endport_manage_subnet),
7252         LSM_HOOK_INIT(ib_free_security, selinux_ib_free_security),
7253 #endif
7254 #ifdef CONFIG_SECURITY_NETWORK_XFRM
7255         LSM_HOOK_INIT(xfrm_policy_free_security, selinux_xfrm_policy_free),
7256         LSM_HOOK_INIT(xfrm_policy_delete_security, selinux_xfrm_policy_delete),
7257         LSM_HOOK_INIT(xfrm_state_free_security, selinux_xfrm_state_free),
7258         LSM_HOOK_INIT(xfrm_state_delete_security, selinux_xfrm_state_delete),
7259         LSM_HOOK_INIT(xfrm_policy_lookup, selinux_xfrm_policy_lookup),
7260         LSM_HOOK_INIT(xfrm_state_pol_flow_match,
7261                         selinux_xfrm_state_pol_flow_match),
7262         LSM_HOOK_INIT(xfrm_decode_session, selinux_xfrm_decode_session),
7263 #endif
7264
7265 #ifdef CONFIG_KEYS
7266         LSM_HOOK_INIT(key_free, selinux_key_free),
7267         LSM_HOOK_INIT(key_permission, selinux_key_permission),
7268         LSM_HOOK_INIT(key_getsecurity, selinux_key_getsecurity),
7269 #ifdef CONFIG_KEY_NOTIFICATIONS
7270         LSM_HOOK_INIT(watch_key, selinux_watch_key),
7271 #endif
7272 #endif
7273
7274 #ifdef CONFIG_AUDIT
7275         LSM_HOOK_INIT(audit_rule_known, selinux_audit_rule_known),
7276         LSM_HOOK_INIT(audit_rule_match, selinux_audit_rule_match),
7277         LSM_HOOK_INIT(audit_rule_free, selinux_audit_rule_free),
7278 #endif
7279
7280 #ifdef CONFIG_BPF_SYSCALL
7281         LSM_HOOK_INIT(bpf, selinux_bpf),
7282         LSM_HOOK_INIT(bpf_map, selinux_bpf_map),
7283         LSM_HOOK_INIT(bpf_prog, selinux_bpf_prog),
7284         LSM_HOOK_INIT(bpf_map_free_security, selinux_bpf_map_free),
7285         LSM_HOOK_INIT(bpf_prog_free_security, selinux_bpf_prog_free),
7286 #endif
7287
7288 #ifdef CONFIG_PERF_EVENTS
7289         LSM_HOOK_INIT(perf_event_open, selinux_perf_event_open),
7290         LSM_HOOK_INIT(perf_event_free, selinux_perf_event_free),
7291         LSM_HOOK_INIT(perf_event_read, selinux_perf_event_read),
7292         LSM_HOOK_INIT(perf_event_write, selinux_perf_event_write),
7293 #endif
7294
7295 #ifdef CONFIG_IO_URING
7296         LSM_HOOK_INIT(uring_override_creds, selinux_uring_override_creds),
7297         LSM_HOOK_INIT(uring_sqpoll, selinux_uring_sqpoll),
7298 #endif
7299
7300         /*
7301          * PUT "CLONING" (ACCESSING + ALLOCATING) HOOKS HERE
7302          */
7303         LSM_HOOK_INIT(fs_context_dup, selinux_fs_context_dup),
7304         LSM_HOOK_INIT(fs_context_parse_param, selinux_fs_context_parse_param),
7305         LSM_HOOK_INIT(sb_eat_lsm_opts, selinux_sb_eat_lsm_opts),
7306         LSM_HOOK_INIT(sb_add_mnt_opt, selinux_add_mnt_opt),
7307 #ifdef CONFIG_SECURITY_NETWORK_XFRM
7308         LSM_HOOK_INIT(xfrm_policy_clone_security, selinux_xfrm_policy_clone),
7309 #endif
7310
7311         /*
7312          * PUT "ALLOCATING" HOOKS HERE
7313          */
7314         LSM_HOOK_INIT(msg_msg_alloc_security, selinux_msg_msg_alloc_security),
7315         LSM_HOOK_INIT(msg_queue_alloc_security,
7316                       selinux_msg_queue_alloc_security),
7317         LSM_HOOK_INIT(shm_alloc_security, selinux_shm_alloc_security),
7318         LSM_HOOK_INIT(sb_alloc_security, selinux_sb_alloc_security),
7319         LSM_HOOK_INIT(inode_alloc_security, selinux_inode_alloc_security),
7320         LSM_HOOK_INIT(sem_alloc_security, selinux_sem_alloc_security),
7321         LSM_HOOK_INIT(secid_to_secctx, selinux_secid_to_secctx),
7322         LSM_HOOK_INIT(inode_getsecctx, selinux_inode_getsecctx),
7323         LSM_HOOK_INIT(sk_alloc_security, selinux_sk_alloc_security),
7324         LSM_HOOK_INIT(tun_dev_alloc_security, selinux_tun_dev_alloc_security),
7325 #ifdef CONFIG_SECURITY_INFINIBAND
7326         LSM_HOOK_INIT(ib_alloc_security, selinux_ib_alloc_security),
7327 #endif
7328 #ifdef CONFIG_SECURITY_NETWORK_XFRM
7329         LSM_HOOK_INIT(xfrm_policy_alloc_security, selinux_xfrm_policy_alloc),
7330         LSM_HOOK_INIT(xfrm_state_alloc, selinux_xfrm_state_alloc),
7331         LSM_HOOK_INIT(xfrm_state_alloc_acquire,
7332                       selinux_xfrm_state_alloc_acquire),
7333 #endif
7334 #ifdef CONFIG_KEYS
7335         LSM_HOOK_INIT(key_alloc, selinux_key_alloc),
7336 #endif
7337 #ifdef CONFIG_AUDIT
7338         LSM_HOOK_INIT(audit_rule_init, selinux_audit_rule_init),
7339 #endif
7340 #ifdef CONFIG_BPF_SYSCALL
7341         LSM_HOOK_INIT(bpf_map_alloc_security, selinux_bpf_map_alloc),
7342         LSM_HOOK_INIT(bpf_prog_alloc_security, selinux_bpf_prog_alloc),
7343 #endif
7344 #ifdef CONFIG_PERF_EVENTS
7345         LSM_HOOK_INIT(perf_event_alloc, selinux_perf_event_alloc),
7346 #endif
7347 };
7348
7349 static __init int selinux_init(void)
7350 {
7351         pr_info("SELinux:  Initializing.\n");
7352
7353         memset(&selinux_state, 0, sizeof(selinux_state));
7354         enforcing_set(&selinux_state, selinux_enforcing_boot);
7355         checkreqprot_set(&selinux_state, selinux_checkreqprot_boot);
7356         selinux_avc_init(&selinux_state.avc);
7357         mutex_init(&selinux_state.status_lock);
7358         mutex_init(&selinux_state.policy_mutex);
7359
7360         /* Set the security state for the initial task. */
7361         cred_init_security();
7362
7363         default_noexec = !(VM_DATA_DEFAULT_FLAGS & VM_EXEC);
7364
7365         avc_init();
7366
7367         avtab_cache_init();
7368
7369         ebitmap_cache_init();
7370
7371         hashtab_cache_init();
7372
7373         security_add_hooks(selinux_hooks, ARRAY_SIZE(selinux_hooks), "selinux");
7374
7375         if (avc_add_callback(selinux_netcache_avc_callback, AVC_CALLBACK_RESET))
7376                 panic("SELinux: Unable to register AVC netcache callback\n");
7377
7378         if (avc_add_callback(selinux_lsm_notifier_avc_callback, AVC_CALLBACK_RESET))
7379                 panic("SELinux: Unable to register AVC LSM notifier callback\n");
7380
7381         if (selinux_enforcing_boot)
7382                 pr_debug("SELinux:  Starting in enforcing mode\n");
7383         else
7384                 pr_debug("SELinux:  Starting in permissive mode\n");
7385
7386         fs_validate_description("selinux", selinux_fs_parameters);
7387
7388         return 0;
7389 }
7390
7391 static void delayed_superblock_init(struct super_block *sb, void *unused)
7392 {
7393         selinux_set_mnt_opts(sb, NULL, 0, NULL);
7394 }
7395
7396 void selinux_complete_init(void)
7397 {
7398         pr_debug("SELinux:  Completing initialization.\n");
7399
7400         /* Set up any superblocks initialized prior to the policy load. */
7401         pr_debug("SELinux:  Setting up existing superblocks.\n");
7402         iterate_supers(delayed_superblock_init, NULL);
7403 }
7404
7405 /* SELinux requires early initialization in order to label
7406    all processes and objects when they are created. */
7407 DEFINE_LSM(selinux) = {
7408         .name = "selinux",
7409         .flags = LSM_FLAG_LEGACY_MAJOR | LSM_FLAG_EXCLUSIVE,
7410         .enabled = &selinux_enabled_boot,
7411         .blobs = &selinux_blob_sizes,
7412         .init = selinux_init,
7413 };
7414
7415 #if defined(CONFIG_NETFILTER)
7416
7417 static const struct nf_hook_ops selinux_nf_ops[] = {
7418         {
7419                 .hook =         selinux_ip_postroute,
7420                 .pf =           NFPROTO_IPV4,
7421                 .hooknum =      NF_INET_POST_ROUTING,
7422                 .priority =     NF_IP_PRI_SELINUX_LAST,
7423         },
7424         {
7425                 .hook =         selinux_ip_forward,
7426                 .pf =           NFPROTO_IPV4,
7427                 .hooknum =      NF_INET_FORWARD,
7428                 .priority =     NF_IP_PRI_SELINUX_FIRST,
7429         },
7430         {
7431                 .hook =         selinux_ip_output,
7432                 .pf =           NFPROTO_IPV4,
7433                 .hooknum =      NF_INET_LOCAL_OUT,
7434                 .priority =     NF_IP_PRI_SELINUX_FIRST,
7435         },
7436 #if IS_ENABLED(CONFIG_IPV6)
7437         {
7438                 .hook =         selinux_ip_postroute,
7439                 .pf =           NFPROTO_IPV6,
7440                 .hooknum =      NF_INET_POST_ROUTING,
7441                 .priority =     NF_IP6_PRI_SELINUX_LAST,
7442         },
7443         {
7444                 .hook =         selinux_ip_forward,
7445                 .pf =           NFPROTO_IPV6,
7446                 .hooknum =      NF_INET_FORWARD,
7447                 .priority =     NF_IP6_PRI_SELINUX_FIRST,
7448         },
7449         {
7450                 .hook =         selinux_ip_output,
7451                 .pf =           NFPROTO_IPV6,
7452                 .hooknum =      NF_INET_LOCAL_OUT,
7453                 .priority =     NF_IP6_PRI_SELINUX_FIRST,
7454         },
7455 #endif  /* IPV6 */
7456 };
7457
7458 static int __net_init selinux_nf_register(struct net *net)
7459 {
7460         return nf_register_net_hooks(net, selinux_nf_ops,
7461                                      ARRAY_SIZE(selinux_nf_ops));
7462 }
7463
7464 static void __net_exit selinux_nf_unregister(struct net *net)
7465 {
7466         nf_unregister_net_hooks(net, selinux_nf_ops,
7467                                 ARRAY_SIZE(selinux_nf_ops));
7468 }
7469
7470 static struct pernet_operations selinux_net_ops = {
7471         .init = selinux_nf_register,
7472         .exit = selinux_nf_unregister,
7473 };
7474
7475 static int __init selinux_nf_ip_init(void)
7476 {
7477         int err;
7478
7479         if (!selinux_enabled_boot)
7480                 return 0;
7481
7482         pr_debug("SELinux:  Registering netfilter hooks\n");
7483
7484         err = register_pernet_subsys(&selinux_net_ops);
7485         if (err)
7486                 panic("SELinux: register_pernet_subsys: error %d\n", err);
7487
7488         return 0;
7489 }
7490 __initcall(selinux_nf_ip_init);
7491
7492 #ifdef CONFIG_SECURITY_SELINUX_DISABLE
7493 static void selinux_nf_ip_exit(void)
7494 {
7495         pr_debug("SELinux:  Unregistering netfilter hooks\n");
7496
7497         unregister_pernet_subsys(&selinux_net_ops);
7498 }
7499 #endif
7500
7501 #else /* CONFIG_NETFILTER */
7502
7503 #ifdef CONFIG_SECURITY_SELINUX_DISABLE
7504 #define selinux_nf_ip_exit()
7505 #endif
7506
7507 #endif /* CONFIG_NETFILTER */
7508
7509 #ifdef CONFIG_SECURITY_SELINUX_DISABLE
7510 int selinux_disable(struct selinux_state *state)
7511 {
7512         if (selinux_initialized(state)) {
7513                 /* Not permitted after initial policy load. */
7514                 return -EINVAL;
7515         }
7516
7517         if (selinux_disabled(state)) {
7518                 /* Only do this once. */
7519                 return -EINVAL;
7520         }
7521
7522         selinux_mark_disabled(state);
7523
7524         pr_info("SELinux:  Disabled at runtime.\n");
7525
7526         /*
7527          * Unregister netfilter hooks.
7528          * Must be done before security_delete_hooks() to avoid breaking
7529          * runtime disable.
7530          */
7531         selinux_nf_ip_exit();
7532
7533         security_delete_hooks(selinux_hooks, ARRAY_SIZE(selinux_hooks));
7534
7535         /* Try to destroy the avc node cache */
7536         avc_disable();
7537
7538         /* Unregister selinuxfs. */
7539         exit_sel_fs();
7540
7541         return 0;
7542 }
7543 #endif