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