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