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