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