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