GNU Linux-libre 4.14.290-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(const struct cred *mgr)
2140 {
2141         return avc_has_perm(current_sid(), cred_sid(mgr), SECCLASS_BINDER,
2142                             BINDER__SET_CONTEXT_MGR, NULL);
2143 }
2144
2145 static int selinux_binder_transaction(const struct cred *from,
2146                                       const struct cred *to)
2147 {
2148         u32 mysid = current_sid();
2149         u32 fromsid = cred_sid(from);
2150         u32 tosid = cred_sid(to);
2151         int rc;
2152
2153         if (mysid != fromsid) {
2154                 rc = avc_has_perm(mysid, fromsid, SECCLASS_BINDER,
2155                                   BINDER__IMPERSONATE, NULL);
2156                 if (rc)
2157                         return rc;
2158         }
2159
2160         return avc_has_perm(fromsid, tosid, SECCLASS_BINDER, BINDER__CALL,
2161                             NULL);
2162 }
2163
2164 static int selinux_binder_transfer_binder(const struct cred *from,
2165                                           const struct cred *to)
2166 {
2167         return avc_has_perm(cred_sid(from), cred_sid(to),
2168                             SECCLASS_BINDER, BINDER__TRANSFER,
2169                             NULL);
2170 }
2171
2172 static int selinux_binder_transfer_file(const struct cred *from,
2173                                         const struct cred *to,
2174                                         struct file *file)
2175 {
2176         u32 sid = cred_sid(to);
2177         struct file_security_struct *fsec = file->f_security;
2178         struct dentry *dentry = file->f_path.dentry;
2179         struct inode_security_struct *isec;
2180         struct common_audit_data ad;
2181         int rc;
2182
2183         ad.type = LSM_AUDIT_DATA_PATH;
2184         ad.u.path = file->f_path;
2185
2186         if (sid != fsec->sid) {
2187                 rc = avc_has_perm(sid, fsec->sid,
2188                                   SECCLASS_FD,
2189                                   FD__USE,
2190                                   &ad);
2191                 if (rc)
2192                         return rc;
2193         }
2194
2195         if (unlikely(IS_PRIVATE(d_backing_inode(dentry))))
2196                 return 0;
2197
2198         isec = backing_inode_security(dentry);
2199         return avc_has_perm(sid, isec->sid, isec->sclass, file_to_av(file),
2200                             &ad);
2201 }
2202
2203 static int selinux_ptrace_access_check(struct task_struct *child,
2204                                      unsigned int mode)
2205 {
2206         u32 sid = current_sid();
2207         u32 csid = task_sid(child);
2208
2209         if (mode & PTRACE_MODE_READ)
2210                 return avc_has_perm(sid, csid, SECCLASS_FILE, FILE__READ, NULL);
2211
2212         return avc_has_perm(sid, csid, SECCLASS_PROCESS, PROCESS__PTRACE, NULL);
2213 }
2214
2215 static int selinux_ptrace_traceme(struct task_struct *parent)
2216 {
2217         return avc_has_perm(task_sid(parent), current_sid(), SECCLASS_PROCESS,
2218                             PROCESS__PTRACE, NULL);
2219 }
2220
2221 static int selinux_capget(struct task_struct *target, kernel_cap_t *effective,
2222                           kernel_cap_t *inheritable, kernel_cap_t *permitted)
2223 {
2224         return avc_has_perm(current_sid(), task_sid(target), SECCLASS_PROCESS,
2225                             PROCESS__GETCAP, NULL);
2226 }
2227
2228 static int selinux_capset(struct cred *new, const struct cred *old,
2229                           const kernel_cap_t *effective,
2230                           const kernel_cap_t *inheritable,
2231                           const kernel_cap_t *permitted)
2232 {
2233         return avc_has_perm(cred_sid(old), cred_sid(new), SECCLASS_PROCESS,
2234                             PROCESS__SETCAP, NULL);
2235 }
2236
2237 /*
2238  * (This comment used to live with the selinux_task_setuid hook,
2239  * which was removed).
2240  *
2241  * Since setuid only affects the current process, and since the SELinux
2242  * controls are not based on the Linux identity attributes, SELinux does not
2243  * need to control this operation.  However, SELinux does control the use of
2244  * the CAP_SETUID and CAP_SETGID capabilities using the capable hook.
2245  */
2246
2247 static int selinux_capable(const struct cred *cred, struct user_namespace *ns,
2248                            int cap, int audit)
2249 {
2250         return cred_has_capability(cred, cap, audit, ns == &init_user_ns);
2251 }
2252
2253 static int selinux_quotactl(int cmds, int type, int id, struct super_block *sb)
2254 {
2255         const struct cred *cred = current_cred();
2256         int rc = 0;
2257
2258         if (!sb)
2259                 return 0;
2260
2261         switch (cmds) {
2262         case Q_SYNC:
2263         case Q_QUOTAON:
2264         case Q_QUOTAOFF:
2265         case Q_SETINFO:
2266         case Q_SETQUOTA:
2267                 rc = superblock_has_perm(cred, sb, FILESYSTEM__QUOTAMOD, NULL);
2268                 break;
2269         case Q_GETFMT:
2270         case Q_GETINFO:
2271         case Q_GETQUOTA:
2272                 rc = superblock_has_perm(cred, sb, FILESYSTEM__QUOTAGET, NULL);
2273                 break;
2274         default:
2275                 rc = 0;  /* let the kernel handle invalid cmds */
2276                 break;
2277         }
2278         return rc;
2279 }
2280
2281 static int selinux_quota_on(struct dentry *dentry)
2282 {
2283         const struct cred *cred = current_cred();
2284
2285         return dentry_has_perm(cred, dentry, FILE__QUOTAON);
2286 }
2287
2288 static int selinux_syslog(int type)
2289 {
2290         switch (type) {
2291         case SYSLOG_ACTION_READ_ALL:    /* Read last kernel messages */
2292         case SYSLOG_ACTION_SIZE_BUFFER: /* Return size of the log buffer */
2293                 return avc_has_perm(current_sid(), SECINITSID_KERNEL,
2294                                     SECCLASS_SYSTEM, SYSTEM__SYSLOG_READ, NULL);
2295         case SYSLOG_ACTION_CONSOLE_OFF: /* Disable logging to console */
2296         case SYSLOG_ACTION_CONSOLE_ON:  /* Enable logging to console */
2297         /* Set level of messages printed to console */
2298         case SYSLOG_ACTION_CONSOLE_LEVEL:
2299                 return avc_has_perm(current_sid(), SECINITSID_KERNEL,
2300                                     SECCLASS_SYSTEM, SYSTEM__SYSLOG_CONSOLE,
2301                                     NULL);
2302         }
2303         /* All other syslog types */
2304         return avc_has_perm(current_sid(), SECINITSID_KERNEL,
2305                             SECCLASS_SYSTEM, SYSTEM__SYSLOG_MOD, NULL);
2306 }
2307
2308 /*
2309  * Check that a process has enough memory to allocate a new virtual
2310  * mapping. 0 means there is enough memory for the allocation to
2311  * succeed and -ENOMEM implies there is not.
2312  *
2313  * Do not audit the selinux permission check, as this is applied to all
2314  * processes that allocate mappings.
2315  */
2316 static int selinux_vm_enough_memory(struct mm_struct *mm, long pages)
2317 {
2318         int rc, cap_sys_admin = 0;
2319
2320         rc = cred_has_capability(current_cred(), CAP_SYS_ADMIN,
2321                                  SECURITY_CAP_NOAUDIT, true);
2322         if (rc == 0)
2323                 cap_sys_admin = 1;
2324
2325         return cap_sys_admin;
2326 }
2327
2328 /* binprm security operations */
2329
2330 static u32 ptrace_parent_sid(void)
2331 {
2332         u32 sid = 0;
2333         struct task_struct *tracer;
2334
2335         rcu_read_lock();
2336         tracer = ptrace_parent(current);
2337         if (tracer)
2338                 sid = task_sid(tracer);
2339         rcu_read_unlock();
2340
2341         return sid;
2342 }
2343
2344 static int check_nnp_nosuid(const struct linux_binprm *bprm,
2345                             const struct task_security_struct *old_tsec,
2346                             const struct task_security_struct *new_tsec)
2347 {
2348         int nnp = (bprm->unsafe & LSM_UNSAFE_NO_NEW_PRIVS);
2349         int nosuid = !mnt_may_suid(bprm->file->f_path.mnt);
2350         int rc;
2351         u32 av;
2352
2353         if (!nnp && !nosuid)
2354                 return 0; /* neither NNP nor nosuid */
2355
2356         if (new_tsec->sid == old_tsec->sid)
2357                 return 0; /* No change in credentials */
2358
2359         /*
2360          * If the policy enables the nnp_nosuid_transition policy capability,
2361          * then we permit transitions under NNP or nosuid if the
2362          * policy allows the corresponding permission between
2363          * the old and new contexts.
2364          */
2365         if (selinux_policycap_nnp_nosuid_transition) {
2366                 av = 0;
2367                 if (nnp)
2368                         av |= PROCESS2__NNP_TRANSITION;
2369                 if (nosuid)
2370                         av |= PROCESS2__NOSUID_TRANSITION;
2371                 rc = avc_has_perm(old_tsec->sid, new_tsec->sid,
2372                                   SECCLASS_PROCESS2, av, NULL);
2373                 if (!rc)
2374                         return 0;
2375         }
2376
2377         /*
2378          * We also permit NNP or nosuid transitions to bounded SIDs,
2379          * i.e. SIDs that are guaranteed to only be allowed a subset
2380          * of the permissions of the current SID.
2381          */
2382         rc = security_bounded_transition(old_tsec->sid, new_tsec->sid);
2383         if (!rc)
2384                 return 0;
2385
2386         /*
2387          * On failure, preserve the errno values for NNP vs nosuid.
2388          * NNP:  Operation not permitted for caller.
2389          * nosuid:  Permission denied to file.
2390          */
2391         if (nnp)
2392                 return -EPERM;
2393         return -EACCES;
2394 }
2395
2396 static int selinux_bprm_set_creds(struct linux_binprm *bprm)
2397 {
2398         const struct task_security_struct *old_tsec;
2399         struct task_security_struct *new_tsec;
2400         struct inode_security_struct *isec;
2401         struct common_audit_data ad;
2402         struct inode *inode = file_inode(bprm->file);
2403         int rc;
2404
2405         /* SELinux context only depends on initial program or script and not
2406          * the script interpreter */
2407         if (bprm->called_set_creds)
2408                 return 0;
2409
2410         old_tsec = current_security();
2411         new_tsec = bprm->cred->security;
2412         isec = inode_security(inode);
2413
2414         /* Default to the current task SID. */
2415         new_tsec->sid = old_tsec->sid;
2416         new_tsec->osid = old_tsec->sid;
2417
2418         /* Reset fs, key, and sock SIDs on execve. */
2419         new_tsec->create_sid = 0;
2420         new_tsec->keycreate_sid = 0;
2421         new_tsec->sockcreate_sid = 0;
2422
2423         if (old_tsec->exec_sid) {
2424                 new_tsec->sid = old_tsec->exec_sid;
2425                 /* Reset exec SID on execve. */
2426                 new_tsec->exec_sid = 0;
2427
2428                 /* Fail on NNP or nosuid if not an allowed transition. */
2429                 rc = check_nnp_nosuid(bprm, old_tsec, new_tsec);
2430                 if (rc)
2431                         return rc;
2432         } else {
2433                 /* Check for a default transition on this program. */
2434                 rc = security_transition_sid(old_tsec->sid, isec->sid,
2435                                              SECCLASS_PROCESS, NULL,
2436                                              &new_tsec->sid);
2437                 if (rc)
2438                         return rc;
2439
2440                 /*
2441                  * Fallback to old SID on NNP or nosuid if not an allowed
2442                  * transition.
2443                  */
2444                 rc = check_nnp_nosuid(bprm, old_tsec, new_tsec);
2445                 if (rc)
2446                         new_tsec->sid = old_tsec->sid;
2447         }
2448
2449         ad.type = LSM_AUDIT_DATA_FILE;
2450         ad.u.file = bprm->file;
2451
2452         if (new_tsec->sid == old_tsec->sid) {
2453                 rc = avc_has_perm(old_tsec->sid, isec->sid,
2454                                   SECCLASS_FILE, FILE__EXECUTE_NO_TRANS, &ad);
2455                 if (rc)
2456                         return rc;
2457         } else {
2458                 /* Check permissions for the transition. */
2459                 rc = avc_has_perm(old_tsec->sid, new_tsec->sid,
2460                                   SECCLASS_PROCESS, PROCESS__TRANSITION, &ad);
2461                 if (rc)
2462                         return rc;
2463
2464                 rc = avc_has_perm(new_tsec->sid, isec->sid,
2465                                   SECCLASS_FILE, FILE__ENTRYPOINT, &ad);
2466                 if (rc)
2467                         return rc;
2468
2469                 /* Check for shared state */
2470                 if (bprm->unsafe & LSM_UNSAFE_SHARE) {
2471                         rc = avc_has_perm(old_tsec->sid, new_tsec->sid,
2472                                           SECCLASS_PROCESS, PROCESS__SHARE,
2473                                           NULL);
2474                         if (rc)
2475                                 return -EPERM;
2476                 }
2477
2478                 /* Make sure that anyone attempting to ptrace over a task that
2479                  * changes its SID has the appropriate permit */
2480                 if (bprm->unsafe & LSM_UNSAFE_PTRACE) {
2481                         u32 ptsid = ptrace_parent_sid();
2482                         if (ptsid != 0) {
2483                                 rc = avc_has_perm(ptsid, new_tsec->sid,
2484                                                   SECCLASS_PROCESS,
2485                                                   PROCESS__PTRACE, NULL);
2486                                 if (rc)
2487                                         return -EPERM;
2488                         }
2489                 }
2490
2491                 /* Clear any possibly unsafe personality bits on exec: */
2492                 bprm->per_clear |= PER_CLEAR_ON_SETID;
2493
2494                 /* Enable secure mode for SIDs transitions unless
2495                    the noatsecure permission is granted between
2496                    the two SIDs, i.e. ahp returns 0. */
2497                 rc = avc_has_perm(old_tsec->sid, new_tsec->sid,
2498                                   SECCLASS_PROCESS, PROCESS__NOATSECURE,
2499                                   NULL);
2500                 bprm->secureexec |= !!rc;
2501         }
2502
2503         return 0;
2504 }
2505
2506 static int match_file(const void *p, struct file *file, unsigned fd)
2507 {
2508         return file_has_perm(p, file, file_to_av(file)) ? fd + 1 : 0;
2509 }
2510
2511 /* Derived from fs/exec.c:flush_old_files. */
2512 static inline void flush_unauthorized_files(const struct cred *cred,
2513                                             struct files_struct *files)
2514 {
2515         struct file *file, *devnull = NULL;
2516         struct tty_struct *tty;
2517         int drop_tty = 0;
2518         unsigned n;
2519
2520         tty = get_current_tty();
2521         if (tty) {
2522                 spin_lock(&tty->files_lock);
2523                 if (!list_empty(&tty->tty_files)) {
2524                         struct tty_file_private *file_priv;
2525
2526                         /* Revalidate access to controlling tty.
2527                            Use file_path_has_perm on the tty path directly
2528                            rather than using file_has_perm, as this particular
2529                            open file may belong to another process and we are
2530                            only interested in the inode-based check here. */
2531                         file_priv = list_first_entry(&tty->tty_files,
2532                                                 struct tty_file_private, list);
2533                         file = file_priv->file;
2534                         if (file_path_has_perm(cred, file, FILE__READ | FILE__WRITE))
2535                                 drop_tty = 1;
2536                 }
2537                 spin_unlock(&tty->files_lock);
2538                 tty_kref_put(tty);
2539         }
2540         /* Reset controlling tty. */
2541         if (drop_tty)
2542                 no_tty();
2543
2544         /* Revalidate access to inherited open files. */
2545         n = iterate_fd(files, 0, match_file, cred);
2546         if (!n) /* none found? */
2547                 return;
2548
2549         devnull = dentry_open(&selinux_null, O_RDWR, cred);
2550         if (IS_ERR(devnull))
2551                 devnull = NULL;
2552         /* replace all the matching ones with this */
2553         do {
2554                 replace_fd(n - 1, devnull, 0);
2555         } while ((n = iterate_fd(files, n, match_file, cred)) != 0);
2556         if (devnull)
2557                 fput(devnull);
2558 }
2559
2560 /*
2561  * Prepare a process for imminent new credential changes due to exec
2562  */
2563 static void selinux_bprm_committing_creds(struct linux_binprm *bprm)
2564 {
2565         struct task_security_struct *new_tsec;
2566         struct rlimit *rlim, *initrlim;
2567         int rc, i;
2568
2569         new_tsec = bprm->cred->security;
2570         if (new_tsec->sid == new_tsec->osid)
2571                 return;
2572
2573         /* Close files for which the new task SID is not authorized. */
2574         flush_unauthorized_files(bprm->cred, current->files);
2575
2576         /* Always clear parent death signal on SID transitions. */
2577         current->pdeath_signal = 0;
2578
2579         /* Check whether the new SID can inherit resource limits from the old
2580          * SID.  If not, reset all soft limits to the lower of the current
2581          * task's hard limit and the init task's soft limit.
2582          *
2583          * Note that the setting of hard limits (even to lower them) can be
2584          * controlled by the setrlimit check.  The inclusion of the init task's
2585          * soft limit into the computation is to avoid resetting soft limits
2586          * higher than the default soft limit for cases where the default is
2587          * lower than the hard limit, e.g. RLIMIT_CORE or RLIMIT_STACK.
2588          */
2589         rc = avc_has_perm(new_tsec->osid, new_tsec->sid, SECCLASS_PROCESS,
2590                           PROCESS__RLIMITINH, NULL);
2591         if (rc) {
2592                 /* protect against do_prlimit() */
2593                 task_lock(current);
2594                 for (i = 0; i < RLIM_NLIMITS; i++) {
2595                         rlim = current->signal->rlim + i;
2596                         initrlim = init_task.signal->rlim + i;
2597                         rlim->rlim_cur = min(rlim->rlim_max, initrlim->rlim_cur);
2598                 }
2599                 task_unlock(current);
2600                 if (IS_ENABLED(CONFIG_POSIX_TIMERS))
2601                         update_rlimit_cpu(current, rlimit(RLIMIT_CPU));
2602         }
2603 }
2604
2605 /*
2606  * Clean up the process immediately after the installation of new credentials
2607  * due to exec
2608  */
2609 static void selinux_bprm_committed_creds(struct linux_binprm *bprm)
2610 {
2611         const struct task_security_struct *tsec = current_security();
2612         struct itimerval itimer;
2613         u32 osid, sid;
2614         int rc, i;
2615
2616         osid = tsec->osid;
2617         sid = tsec->sid;
2618
2619         if (sid == osid)
2620                 return;
2621
2622         /* Check whether the new SID can inherit signal state from the old SID.
2623          * If not, clear itimers to avoid subsequent signal generation and
2624          * flush and unblock signals.
2625          *
2626          * This must occur _after_ the task SID has been updated so that any
2627          * kill done after the flush will be checked against the new SID.
2628          */
2629         rc = avc_has_perm(osid, sid, SECCLASS_PROCESS, PROCESS__SIGINH, NULL);
2630         if (rc) {
2631                 if (IS_ENABLED(CONFIG_POSIX_TIMERS)) {
2632                         memset(&itimer, 0, sizeof itimer);
2633                         for (i = 0; i < 3; i++)
2634                                 do_setitimer(i, &itimer, NULL);
2635                 }
2636                 spin_lock_irq(&current->sighand->siglock);
2637                 if (!fatal_signal_pending(current)) {
2638                         flush_sigqueue(&current->pending);
2639                         flush_sigqueue(&current->signal->shared_pending);
2640                         flush_signal_handlers(current, 1);
2641                         sigemptyset(&current->blocked);
2642                         recalc_sigpending();
2643                 }
2644                 spin_unlock_irq(&current->sighand->siglock);
2645         }
2646
2647         /* Wake up the parent if it is waiting so that it can recheck
2648          * wait permission to the new task SID. */
2649         read_lock(&tasklist_lock);
2650         __wake_up_parent(current, current->real_parent);
2651         read_unlock(&tasklist_lock);
2652 }
2653
2654 /* superblock security operations */
2655
2656 static int selinux_sb_alloc_security(struct super_block *sb)
2657 {
2658         return superblock_alloc_security(sb);
2659 }
2660
2661 static void selinux_sb_free_security(struct super_block *sb)
2662 {
2663         superblock_free_security(sb);
2664 }
2665
2666 static inline int match_prefix(char *prefix, int plen, char *option, int olen)
2667 {
2668         if (plen > olen)
2669                 return 0;
2670
2671         return !memcmp(prefix, option, plen);
2672 }
2673
2674 static inline int selinux_option(char *option, int len)
2675 {
2676         return (match_prefix(CONTEXT_STR, sizeof(CONTEXT_STR)-1, option, len) ||
2677                 match_prefix(FSCONTEXT_STR, sizeof(FSCONTEXT_STR)-1, option, len) ||
2678                 match_prefix(DEFCONTEXT_STR, sizeof(DEFCONTEXT_STR)-1, option, len) ||
2679                 match_prefix(ROOTCONTEXT_STR, sizeof(ROOTCONTEXT_STR)-1, option, len) ||
2680                 match_prefix(LABELSUPP_STR, sizeof(LABELSUPP_STR)-1, option, len));
2681 }
2682
2683 static inline void take_option(char **to, char *from, int *first, int len)
2684 {
2685         if (!*first) {
2686                 **to = ',';
2687                 *to += 1;
2688         } else
2689                 *first = 0;
2690         memcpy(*to, from, len);
2691         *to += len;
2692 }
2693
2694 static inline void take_selinux_option(char **to, char *from, int *first,
2695                                        int len)
2696 {
2697         int current_size = 0;
2698
2699         if (!*first) {
2700                 **to = '|';
2701                 *to += 1;
2702         } else
2703                 *first = 0;
2704
2705         while (current_size < len) {
2706                 if (*from != '"') {
2707                         **to = *from;
2708                         *to += 1;
2709                 }
2710                 from += 1;
2711                 current_size += 1;
2712         }
2713 }
2714
2715 static int selinux_sb_copy_data(char *orig, char *copy)
2716 {
2717         int fnosec, fsec, rc = 0;
2718         char *in_save, *in_curr, *in_end;
2719         char *sec_curr, *nosec_save, *nosec;
2720         int open_quote = 0;
2721
2722         in_curr = orig;
2723         sec_curr = copy;
2724
2725         nosec = (char *)get_zeroed_page(GFP_KERNEL);
2726         if (!nosec) {
2727                 rc = -ENOMEM;
2728                 goto out;
2729         }
2730
2731         nosec_save = nosec;
2732         fnosec = fsec = 1;
2733         in_save = in_end = orig;
2734
2735         do {
2736                 if (*in_end == '"')
2737                         open_quote = !open_quote;
2738                 if ((*in_end == ',' && open_quote == 0) ||
2739                                 *in_end == '\0') {
2740                         int len = in_end - in_curr;
2741
2742                         if (selinux_option(in_curr, len))
2743                                 take_selinux_option(&sec_curr, in_curr, &fsec, len);
2744                         else
2745                                 take_option(&nosec, in_curr, &fnosec, len);
2746
2747                         in_curr = in_end + 1;
2748                 }
2749         } while (*in_end++);
2750
2751         strcpy(in_save, nosec_save);
2752         free_page((unsigned long)nosec_save);
2753 out:
2754         return rc;
2755 }
2756
2757 static int selinux_sb_remount(struct super_block *sb, void *data)
2758 {
2759         int rc, i, *flags;
2760         struct security_mnt_opts opts;
2761         char *secdata, **mount_options;
2762         struct superblock_security_struct *sbsec = sb->s_security;
2763
2764         if (!(sbsec->flags & SE_SBINITIALIZED))
2765                 return 0;
2766
2767         if (!data)
2768                 return 0;
2769
2770         if (sb->s_type->fs_flags & FS_BINARY_MOUNTDATA)
2771                 return 0;
2772
2773         security_init_mnt_opts(&opts);
2774         secdata = alloc_secdata();
2775         if (!secdata)
2776                 return -ENOMEM;
2777         rc = selinux_sb_copy_data(data, secdata);
2778         if (rc)
2779                 goto out_free_secdata;
2780
2781         rc = selinux_parse_opts_str(secdata, &opts);
2782         if (rc)
2783                 goto out_free_secdata;
2784
2785         mount_options = opts.mnt_opts;
2786         flags = opts.mnt_opts_flags;
2787
2788         for (i = 0; i < opts.num_mnt_opts; i++) {
2789                 u32 sid;
2790
2791                 if (flags[i] == SBLABEL_MNT)
2792                         continue;
2793                 rc = security_context_str_to_sid(mount_options[i], &sid, GFP_KERNEL);
2794                 if (rc) {
2795                         printk(KERN_WARNING "SELinux: security_context_str_to_sid"
2796                                "(%s) failed for (dev %s, type %s) errno=%d\n",
2797                                mount_options[i], sb->s_id, sb->s_type->name, rc);
2798                         goto out_free_opts;
2799                 }
2800                 rc = -EINVAL;
2801                 switch (flags[i]) {
2802                 case FSCONTEXT_MNT:
2803                         if (bad_option(sbsec, FSCONTEXT_MNT, sbsec->sid, sid))
2804                                 goto out_bad_option;
2805                         break;
2806                 case CONTEXT_MNT:
2807                         if (bad_option(sbsec, CONTEXT_MNT, sbsec->mntpoint_sid, sid))
2808                                 goto out_bad_option;
2809                         break;
2810                 case ROOTCONTEXT_MNT: {
2811                         struct inode_security_struct *root_isec;
2812                         root_isec = backing_inode_security(sb->s_root);
2813
2814                         if (bad_option(sbsec, ROOTCONTEXT_MNT, root_isec->sid, sid))
2815                                 goto out_bad_option;
2816                         break;
2817                 }
2818                 case DEFCONTEXT_MNT:
2819                         if (bad_option(sbsec, DEFCONTEXT_MNT, sbsec->def_sid, sid))
2820                                 goto out_bad_option;
2821                         break;
2822                 default:
2823                         goto out_free_opts;
2824                 }
2825         }
2826
2827         rc = 0;
2828 out_free_opts:
2829         security_free_mnt_opts(&opts);
2830 out_free_secdata:
2831         free_secdata(secdata);
2832         return rc;
2833 out_bad_option:
2834         printk(KERN_WARNING "SELinux: unable to change security options "
2835                "during remount (dev %s, type=%s)\n", sb->s_id,
2836                sb->s_type->name);
2837         goto out_free_opts;
2838 }
2839
2840 static int selinux_sb_kern_mount(struct super_block *sb, int flags, void *data)
2841 {
2842         const struct cred *cred = current_cred();
2843         struct common_audit_data ad;
2844         int rc;
2845
2846         rc = superblock_doinit(sb, data);
2847         if (rc)
2848                 return rc;
2849
2850         /* Allow all mounts performed by the kernel */
2851         if (flags & (MS_KERNMOUNT | MS_SUBMOUNT))
2852                 return 0;
2853
2854         ad.type = LSM_AUDIT_DATA_DENTRY;
2855         ad.u.dentry = sb->s_root;
2856         return superblock_has_perm(cred, sb, FILESYSTEM__MOUNT, &ad);
2857 }
2858
2859 static int selinux_sb_statfs(struct dentry *dentry)
2860 {
2861         const struct cred *cred = current_cred();
2862         struct common_audit_data ad;
2863
2864         ad.type = LSM_AUDIT_DATA_DENTRY;
2865         ad.u.dentry = dentry->d_sb->s_root;
2866         return superblock_has_perm(cred, dentry->d_sb, FILESYSTEM__GETATTR, &ad);
2867 }
2868
2869 static int selinux_mount(const char *dev_name,
2870                          const struct path *path,
2871                          const char *type,
2872                          unsigned long flags,
2873                          void *data)
2874 {
2875         const struct cred *cred = current_cred();
2876
2877         if (flags & MS_REMOUNT)
2878                 return superblock_has_perm(cred, path->dentry->d_sb,
2879                                            FILESYSTEM__REMOUNT, NULL);
2880         else
2881                 return path_has_perm(cred, path, FILE__MOUNTON);
2882 }
2883
2884 static int selinux_umount(struct vfsmount *mnt, int flags)
2885 {
2886         const struct cred *cred = current_cred();
2887
2888         return superblock_has_perm(cred, mnt->mnt_sb,
2889                                    FILESYSTEM__UNMOUNT, NULL);
2890 }
2891
2892 /* inode security operations */
2893
2894 static int selinux_inode_alloc_security(struct inode *inode)
2895 {
2896         return inode_alloc_security(inode);
2897 }
2898
2899 static void selinux_inode_free_security(struct inode *inode)
2900 {
2901         inode_free_security(inode);
2902 }
2903
2904 static int selinux_dentry_init_security(struct dentry *dentry, int mode,
2905                                         const struct qstr *name, void **ctx,
2906                                         u32 *ctxlen)
2907 {
2908         u32 newsid;
2909         int rc;
2910
2911         rc = selinux_determine_inode_label(current_security(),
2912                                            d_inode(dentry->d_parent), name,
2913                                            inode_mode_to_security_class(mode),
2914                                            &newsid);
2915         if (rc)
2916                 return rc;
2917
2918         return security_sid_to_context(newsid, (char **)ctx, ctxlen);
2919 }
2920
2921 static int selinux_dentry_create_files_as(struct dentry *dentry, int mode,
2922                                           struct qstr *name,
2923                                           const struct cred *old,
2924                                           struct cred *new)
2925 {
2926         u32 newsid;
2927         int rc;
2928         struct task_security_struct *tsec;
2929
2930         rc = selinux_determine_inode_label(old->security,
2931                                            d_inode(dentry->d_parent), name,
2932                                            inode_mode_to_security_class(mode),
2933                                            &newsid);
2934         if (rc)
2935                 return rc;
2936
2937         tsec = new->security;
2938         tsec->create_sid = newsid;
2939         return 0;
2940 }
2941
2942 static int selinux_inode_init_security(struct inode *inode, struct inode *dir,
2943                                        const struct qstr *qstr,
2944                                        const char **name,
2945                                        void **value, size_t *len)
2946 {
2947         const struct task_security_struct *tsec = current_security();
2948         struct superblock_security_struct *sbsec;
2949         u32 sid, newsid, clen;
2950         int rc;
2951         char *context;
2952
2953         sbsec = dir->i_sb->s_security;
2954
2955         sid = tsec->sid;
2956         newsid = tsec->create_sid;
2957
2958         rc = selinux_determine_inode_label(current_security(),
2959                 dir, qstr,
2960                 inode_mode_to_security_class(inode->i_mode),
2961                 &newsid);
2962         if (rc)
2963                 return rc;
2964
2965         /* Possibly defer initialization to selinux_complete_init. */
2966         if (sbsec->flags & SE_SBINITIALIZED) {
2967                 struct inode_security_struct *isec = inode->i_security;
2968                 isec->sclass = inode_mode_to_security_class(inode->i_mode);
2969                 isec->sid = newsid;
2970                 isec->initialized = LABEL_INITIALIZED;
2971         }
2972
2973         if (!ss_initialized || !(sbsec->flags & SBLABEL_MNT))
2974                 return -EOPNOTSUPP;
2975
2976         if (name)
2977                 *name = XATTR_SELINUX_SUFFIX;
2978
2979         if (value && len) {
2980                 rc = security_sid_to_context_force(newsid, &context, &clen);
2981                 if (rc)
2982                         return rc;
2983                 *value = context;
2984                 *len = clen;
2985         }
2986
2987         return 0;
2988 }
2989
2990 static int selinux_inode_create(struct inode *dir, struct dentry *dentry, umode_t mode)
2991 {
2992         return may_create(dir, dentry, SECCLASS_FILE);
2993 }
2994
2995 static int selinux_inode_link(struct dentry *old_dentry, struct inode *dir, struct dentry *new_dentry)
2996 {
2997         return may_link(dir, old_dentry, MAY_LINK);
2998 }
2999
3000 static int selinux_inode_unlink(struct inode *dir, struct dentry *dentry)
3001 {
3002         return may_link(dir, dentry, MAY_UNLINK);
3003 }
3004
3005 static int selinux_inode_symlink(struct inode *dir, struct dentry *dentry, const char *name)
3006 {
3007         return may_create(dir, dentry, SECCLASS_LNK_FILE);
3008 }
3009
3010 static int selinux_inode_mkdir(struct inode *dir, struct dentry *dentry, umode_t mask)
3011 {
3012         return may_create(dir, dentry, SECCLASS_DIR);
3013 }
3014
3015 static int selinux_inode_rmdir(struct inode *dir, struct dentry *dentry)
3016 {
3017         return may_link(dir, dentry, MAY_RMDIR);
3018 }
3019
3020 static int selinux_inode_mknod(struct inode *dir, struct dentry *dentry, umode_t mode, dev_t dev)
3021 {
3022         return may_create(dir, dentry, inode_mode_to_security_class(mode));
3023 }
3024
3025 static int selinux_inode_rename(struct inode *old_inode, struct dentry *old_dentry,
3026                                 struct inode *new_inode, struct dentry *new_dentry)
3027 {
3028         return may_rename(old_inode, old_dentry, new_inode, new_dentry);
3029 }
3030
3031 static int selinux_inode_readlink(struct dentry *dentry)
3032 {
3033         const struct cred *cred = current_cred();
3034
3035         return dentry_has_perm(cred, dentry, FILE__READ);
3036 }
3037
3038 static int selinux_inode_follow_link(struct dentry *dentry, struct inode *inode,
3039                                      bool rcu)
3040 {
3041         const struct cred *cred = current_cred();
3042         struct common_audit_data ad;
3043         struct inode_security_struct *isec;
3044         u32 sid;
3045
3046         validate_creds(cred);
3047
3048         ad.type = LSM_AUDIT_DATA_DENTRY;
3049         ad.u.dentry = dentry;
3050         sid = cred_sid(cred);
3051         isec = inode_security_rcu(inode, rcu);
3052         if (IS_ERR(isec))
3053                 return PTR_ERR(isec);
3054
3055         return avc_has_perm_flags(sid, isec->sid, isec->sclass, FILE__READ, &ad,
3056                                   rcu ? MAY_NOT_BLOCK : 0);
3057 }
3058
3059 static noinline int audit_inode_permission(struct inode *inode,
3060                                            u32 perms, u32 audited, u32 denied,
3061                                            int result,
3062                                            unsigned flags)
3063 {
3064         struct common_audit_data ad;
3065         struct inode_security_struct *isec = inode->i_security;
3066         int rc;
3067
3068         ad.type = LSM_AUDIT_DATA_INODE;
3069         ad.u.inode = inode;
3070
3071         rc = slow_avc_audit(current_sid(), isec->sid, isec->sclass, perms,
3072                             audited, denied, result, &ad, flags);
3073         if (rc)
3074                 return rc;
3075         return 0;
3076 }
3077
3078 static int selinux_inode_permission(struct inode *inode, int mask)
3079 {
3080         const struct cred *cred = current_cred();
3081         u32 perms;
3082         bool from_access;
3083         unsigned flags = mask & MAY_NOT_BLOCK;
3084         struct inode_security_struct *isec;
3085         u32 sid;
3086         struct av_decision avd;
3087         int rc, rc2;
3088         u32 audited, denied;
3089
3090         from_access = mask & MAY_ACCESS;
3091         mask &= (MAY_READ|MAY_WRITE|MAY_EXEC|MAY_APPEND);
3092
3093         /* No permission to check.  Existence test. */
3094         if (!mask)
3095                 return 0;
3096
3097         validate_creds(cred);
3098
3099         if (unlikely(IS_PRIVATE(inode)))
3100                 return 0;
3101
3102         perms = file_mask_to_av(inode->i_mode, mask);
3103
3104         sid = cred_sid(cred);
3105         isec = inode_security_rcu(inode, flags & MAY_NOT_BLOCK);
3106         if (IS_ERR(isec))
3107                 return PTR_ERR(isec);
3108
3109         rc = avc_has_perm_noaudit(sid, isec->sid, isec->sclass, perms, 0, &avd);
3110         audited = avc_audit_required(perms, &avd, rc,
3111                                      from_access ? FILE__AUDIT_ACCESS : 0,
3112                                      &denied);
3113         if (likely(!audited))
3114                 return rc;
3115
3116         rc2 = audit_inode_permission(inode, perms, audited, denied, rc, flags);
3117         if (rc2)
3118                 return rc2;
3119         return rc;
3120 }
3121
3122 static int selinux_inode_setattr(struct dentry *dentry, struct iattr *iattr)
3123 {
3124         const struct cred *cred = current_cred();
3125         struct inode *inode = d_backing_inode(dentry);
3126         unsigned int ia_valid = iattr->ia_valid;
3127         __u32 av = FILE__WRITE;
3128
3129         /* ATTR_FORCE is just used for ATTR_KILL_S[UG]ID. */
3130         if (ia_valid & ATTR_FORCE) {
3131                 ia_valid &= ~(ATTR_KILL_SUID | ATTR_KILL_SGID | ATTR_MODE |
3132                               ATTR_FORCE);
3133                 if (!ia_valid)
3134                         return 0;
3135         }
3136
3137         if (ia_valid & (ATTR_MODE | ATTR_UID | ATTR_GID |
3138                         ATTR_ATIME_SET | ATTR_MTIME_SET | ATTR_TIMES_SET))
3139                 return dentry_has_perm(cred, dentry, FILE__SETATTR);
3140
3141         if (selinux_policycap_openperm &&
3142             inode->i_sb->s_magic != SOCKFS_MAGIC &&
3143             (ia_valid & ATTR_SIZE) &&
3144             !(ia_valid & ATTR_FILE))
3145                 av |= FILE__OPEN;
3146
3147         return dentry_has_perm(cred, dentry, av);
3148 }
3149
3150 static int selinux_inode_getattr(const struct path *path)
3151 {
3152         return path_has_perm(current_cred(), path, FILE__GETATTR);
3153 }
3154
3155 static int selinux_inode_setotherxattr(struct dentry *dentry, const char *name)
3156 {
3157         const struct cred *cred = current_cred();
3158
3159         if (!strncmp(name, XATTR_SECURITY_PREFIX,
3160                      sizeof XATTR_SECURITY_PREFIX - 1)) {
3161                 if (!strcmp(name, XATTR_NAME_CAPS)) {
3162                         if (!capable(CAP_SETFCAP))
3163                                 return -EPERM;
3164                 } else if (!capable(CAP_SYS_ADMIN)) {
3165                         /* A different attribute in the security namespace.
3166                            Restrict to administrator. */
3167                         return -EPERM;
3168                 }
3169         }
3170
3171         /* Not an attribute we recognize, so just check the
3172            ordinary setattr permission. */
3173         return dentry_has_perm(cred, dentry, FILE__SETATTR);
3174 }
3175
3176 static bool has_cap_mac_admin(bool audit)
3177 {
3178         const struct cred *cred = current_cred();
3179         int cap_audit = audit ? SECURITY_CAP_AUDIT : SECURITY_CAP_NOAUDIT;
3180
3181         if (cap_capable(cred, &init_user_ns, CAP_MAC_ADMIN, cap_audit))
3182                 return false;
3183         if (cred_has_capability(cred, CAP_MAC_ADMIN, cap_audit, true))
3184                 return false;
3185         return true;
3186 }
3187
3188 static int selinux_inode_setxattr(struct dentry *dentry, const char *name,
3189                                   const void *value, size_t size, int flags)
3190 {
3191         struct inode *inode = d_backing_inode(dentry);
3192         struct inode_security_struct *isec;
3193         struct superblock_security_struct *sbsec;
3194         struct common_audit_data ad;
3195         u32 newsid, sid = current_sid();
3196         int rc = 0;
3197
3198         if (strcmp(name, XATTR_NAME_SELINUX))
3199                 return selinux_inode_setotherxattr(dentry, name);
3200
3201         sbsec = inode->i_sb->s_security;
3202         if (!(sbsec->flags & SBLABEL_MNT))
3203                 return -EOPNOTSUPP;
3204
3205         if (!inode_owner_or_capable(inode))
3206                 return -EPERM;
3207
3208         ad.type = LSM_AUDIT_DATA_DENTRY;
3209         ad.u.dentry = dentry;
3210
3211         isec = backing_inode_security(dentry);
3212         rc = avc_has_perm(sid, isec->sid, isec->sclass,
3213                           FILE__RELABELFROM, &ad);
3214         if (rc)
3215                 return rc;
3216
3217         rc = security_context_to_sid(value, size, &newsid, GFP_KERNEL);
3218         if (rc == -EINVAL) {
3219                 if (!has_cap_mac_admin(true)) {
3220                         struct audit_buffer *ab;
3221                         size_t audit_size;
3222                         const char *str;
3223
3224                         /* We strip a nul only if it is at the end, otherwise the
3225                          * context contains a nul and we should audit that */
3226                         if (value) {
3227                                 str = value;
3228                                 if (str[size - 1] == '\0')
3229                                         audit_size = size - 1;
3230                                 else
3231                                         audit_size = size;
3232                         } else {
3233                                 str = "";
3234                                 audit_size = 0;
3235                         }
3236                         ab = audit_log_start(current->audit_context, GFP_ATOMIC, AUDIT_SELINUX_ERR);
3237                         audit_log_format(ab, "op=setxattr invalid_context=");
3238                         audit_log_n_untrustedstring(ab, value, audit_size);
3239                         audit_log_end(ab);
3240
3241                         return rc;
3242                 }
3243                 rc = security_context_to_sid_force(value, size, &newsid);
3244         }
3245         if (rc)
3246                 return rc;
3247
3248         rc = avc_has_perm(sid, newsid, isec->sclass,
3249                           FILE__RELABELTO, &ad);
3250         if (rc)
3251                 return rc;
3252
3253         rc = security_validate_transition(isec->sid, newsid, sid,
3254                                           isec->sclass);
3255         if (rc)
3256                 return rc;
3257
3258         return avc_has_perm(newsid,
3259                             sbsec->sid,
3260                             SECCLASS_FILESYSTEM,
3261                             FILESYSTEM__ASSOCIATE,
3262                             &ad);
3263 }
3264
3265 static void selinux_inode_post_setxattr(struct dentry *dentry, const char *name,
3266                                         const void *value, size_t size,
3267                                         int flags)
3268 {
3269         struct inode *inode = d_backing_inode(dentry);
3270         struct inode_security_struct *isec;
3271         u32 newsid;
3272         int rc;
3273
3274         if (strcmp(name, XATTR_NAME_SELINUX)) {
3275                 /* Not an attribute we recognize, so nothing to do. */
3276                 return;
3277         }
3278
3279         rc = security_context_to_sid_force(value, size, &newsid);
3280         if (rc) {
3281                 printk(KERN_ERR "SELinux:  unable to map context to SID"
3282                        "for (%s, %lu), rc=%d\n",
3283                        inode->i_sb->s_id, inode->i_ino, -rc);
3284                 return;
3285         }
3286
3287         isec = backing_inode_security(dentry);
3288         spin_lock(&isec->lock);
3289         isec->sclass = inode_mode_to_security_class(inode->i_mode);
3290         isec->sid = newsid;
3291         isec->initialized = LABEL_INITIALIZED;
3292         spin_unlock(&isec->lock);
3293
3294         return;
3295 }
3296
3297 static int selinux_inode_getxattr(struct dentry *dentry, const char *name)
3298 {
3299         const struct cred *cred = current_cred();
3300
3301         return dentry_has_perm(cred, dentry, FILE__GETATTR);
3302 }
3303
3304 static int selinux_inode_listxattr(struct dentry *dentry)
3305 {
3306         const struct cred *cred = current_cred();
3307
3308         return dentry_has_perm(cred, dentry, FILE__GETATTR);
3309 }
3310
3311 static int selinux_inode_removexattr(struct dentry *dentry, const char *name)
3312 {
3313         if (strcmp(name, XATTR_NAME_SELINUX))
3314                 return selinux_inode_setotherxattr(dentry, name);
3315
3316         /* No one is allowed to remove a SELinux security label.
3317            You can change the label, but all data must be labeled. */
3318         return -EACCES;
3319 }
3320
3321 /*
3322  * Copy the inode security context value to the user.
3323  *
3324  * Permission check is handled by selinux_inode_getxattr hook.
3325  */
3326 static int selinux_inode_getsecurity(struct inode *inode, const char *name, void **buffer, bool alloc)
3327 {
3328         u32 size;
3329         int error;
3330         char *context = NULL;
3331         struct inode_security_struct *isec;
3332
3333         if (strcmp(name, XATTR_SELINUX_SUFFIX))
3334                 return -EOPNOTSUPP;
3335
3336         /*
3337          * If the caller has CAP_MAC_ADMIN, then get the raw context
3338          * value even if it is not defined by current policy; otherwise,
3339          * use the in-core value under current policy.
3340          * Use the non-auditing forms of the permission checks since
3341          * getxattr may be called by unprivileged processes commonly
3342          * and lack of permission just means that we fall back to the
3343          * in-core context value, not a denial.
3344          */
3345         isec = inode_security(inode);
3346         if (has_cap_mac_admin(false))
3347                 error = security_sid_to_context_force(isec->sid, &context,
3348                                                       &size);
3349         else
3350                 error = security_sid_to_context(isec->sid, &context, &size);
3351         if (error)
3352                 return error;
3353         error = size;
3354         if (alloc) {
3355                 *buffer = context;
3356                 goto out_nofree;
3357         }
3358         kfree(context);
3359 out_nofree:
3360         return error;
3361 }
3362
3363 static int selinux_inode_setsecurity(struct inode *inode, const char *name,
3364                                      const void *value, size_t size, int flags)
3365 {
3366         struct inode_security_struct *isec = inode_security_novalidate(inode);
3367         struct superblock_security_struct *sbsec = inode->i_sb->s_security;
3368         u32 newsid;
3369         int rc;
3370
3371         if (strcmp(name, XATTR_SELINUX_SUFFIX))
3372                 return -EOPNOTSUPP;
3373
3374         if (!(sbsec->flags & SBLABEL_MNT))
3375                 return -EOPNOTSUPP;
3376
3377         if (!value || !size)
3378                 return -EACCES;
3379
3380         rc = security_context_to_sid(value, size, &newsid, GFP_KERNEL);
3381         if (rc)
3382                 return rc;
3383
3384         spin_lock(&isec->lock);
3385         isec->sclass = inode_mode_to_security_class(inode->i_mode);
3386         isec->sid = newsid;
3387         isec->initialized = LABEL_INITIALIZED;
3388         spin_unlock(&isec->lock);
3389         return 0;
3390 }
3391
3392 static int selinux_inode_listsecurity(struct inode *inode, char *buffer, size_t buffer_size)
3393 {
3394         const int len = sizeof(XATTR_NAME_SELINUX);
3395         if (buffer && len <= buffer_size)
3396                 memcpy(buffer, XATTR_NAME_SELINUX, len);
3397         return len;
3398 }
3399
3400 static void selinux_inode_getsecid(struct inode *inode, u32 *secid)
3401 {
3402         struct inode_security_struct *isec = inode_security_novalidate(inode);
3403         *secid = isec->sid;
3404 }
3405
3406 static int selinux_inode_copy_up(struct dentry *src, struct cred **new)
3407 {
3408         u32 sid;
3409         struct task_security_struct *tsec;
3410         struct cred *new_creds = *new;
3411
3412         if (new_creds == NULL) {
3413                 new_creds = prepare_creds();
3414                 if (!new_creds)
3415                         return -ENOMEM;
3416         }
3417
3418         tsec = new_creds->security;
3419         /* Get label from overlay inode and set it in create_sid */
3420         selinux_inode_getsecid(d_inode(src), &sid);
3421         tsec->create_sid = sid;
3422         *new = new_creds;
3423         return 0;
3424 }
3425
3426 static int selinux_inode_copy_up_xattr(const char *name)
3427 {
3428         /* The copy_up hook above sets the initial context on an inode, but we
3429          * don't then want to overwrite it by blindly copying all the lower
3430          * xattrs up.  Instead, we have to filter out SELinux-related xattrs.
3431          */
3432         if (strcmp(name, XATTR_NAME_SELINUX) == 0)
3433                 return 1; /* Discard */
3434         /*
3435          * Any other attribute apart from SELINUX is not claimed, supported
3436          * by selinux.
3437          */
3438         return -EOPNOTSUPP;
3439 }
3440
3441 /* file security operations */
3442
3443 static int selinux_revalidate_file_permission(struct file *file, int mask)
3444 {
3445         const struct cred *cred = current_cred();
3446         struct inode *inode = file_inode(file);
3447
3448         /* file_mask_to_av won't add FILE__WRITE if MAY_APPEND is set */
3449         if ((file->f_flags & O_APPEND) && (mask & MAY_WRITE))
3450                 mask |= MAY_APPEND;
3451
3452         return file_has_perm(cred, file,
3453                              file_mask_to_av(inode->i_mode, mask));
3454 }
3455
3456 static int selinux_file_permission(struct file *file, int mask)
3457 {
3458         struct inode *inode = file_inode(file);
3459         struct file_security_struct *fsec = file->f_security;
3460         struct inode_security_struct *isec;
3461         u32 sid = current_sid();
3462
3463         if (!mask)
3464                 /* No permission to check.  Existence test. */
3465                 return 0;
3466
3467         isec = inode_security(inode);
3468         if (sid == fsec->sid && fsec->isid == isec->sid &&
3469             fsec->pseqno == avc_policy_seqno())
3470                 /* No change since file_open check. */
3471                 return 0;
3472
3473         return selinux_revalidate_file_permission(file, mask);
3474 }
3475
3476 static int selinux_file_alloc_security(struct file *file)
3477 {
3478         return file_alloc_security(file);
3479 }
3480
3481 static void selinux_file_free_security(struct file *file)
3482 {
3483         file_free_security(file);
3484 }
3485
3486 /*
3487  * Check whether a task has the ioctl permission and cmd
3488  * operation to an inode.
3489  */
3490 static int ioctl_has_perm(const struct cred *cred, struct file *file,
3491                 u32 requested, u16 cmd)
3492 {
3493         struct common_audit_data ad;
3494         struct file_security_struct *fsec = file->f_security;
3495         struct inode *inode = file_inode(file);
3496         struct inode_security_struct *isec;
3497         struct lsm_ioctlop_audit ioctl;
3498         u32 ssid = cred_sid(cred);
3499         int rc;
3500         u8 driver = cmd >> 8;
3501         u8 xperm = cmd & 0xff;
3502
3503         ad.type = LSM_AUDIT_DATA_IOCTL_OP;
3504         ad.u.op = &ioctl;
3505         ad.u.op->cmd = cmd;
3506         ad.u.op->path = file->f_path;
3507
3508         if (ssid != fsec->sid) {
3509                 rc = avc_has_perm(ssid, fsec->sid,
3510                                 SECCLASS_FD,
3511                                 FD__USE,
3512                                 &ad);
3513                 if (rc)
3514                         goto out;
3515         }
3516
3517         if (unlikely(IS_PRIVATE(inode)))
3518                 return 0;
3519
3520         isec = inode_security(inode);
3521         rc = avc_has_extended_perms(ssid, isec->sid, isec->sclass,
3522                         requested, driver, xperm, &ad);
3523 out:
3524         return rc;
3525 }
3526
3527 static int selinux_file_ioctl(struct file *file, unsigned int cmd,
3528                               unsigned long arg)
3529 {
3530         const struct cred *cred = current_cred();
3531         int error = 0;
3532
3533         switch (cmd) {
3534         case FIONREAD:
3535         /* fall through */
3536         case FIBMAP:
3537         /* fall through */
3538         case FIGETBSZ:
3539         /* fall through */
3540         case FS_IOC_GETFLAGS:
3541         /* fall through */
3542         case FS_IOC_GETVERSION:
3543                 error = file_has_perm(cred, file, FILE__GETATTR);
3544                 break;
3545
3546         case FS_IOC_SETFLAGS:
3547         /* fall through */
3548         case FS_IOC_SETVERSION:
3549                 error = file_has_perm(cred, file, FILE__SETATTR);
3550                 break;
3551
3552         /* sys_ioctl() checks */
3553         case FIONBIO:
3554         /* fall through */
3555         case FIOASYNC:
3556                 error = file_has_perm(cred, file, 0);
3557                 break;
3558
3559         case KDSKBENT:
3560         case KDSKBSENT:
3561                 error = cred_has_capability(cred, CAP_SYS_TTY_CONFIG,
3562                                             SECURITY_CAP_AUDIT, true);
3563                 break;
3564
3565         /* default case assumes that the command will go
3566          * to the file's ioctl() function.
3567          */
3568         default:
3569                 error = ioctl_has_perm(cred, file, FILE__IOCTL, (u16) cmd);
3570         }
3571         return error;
3572 }
3573
3574 static int default_noexec;
3575
3576 static int file_map_prot_check(struct file *file, unsigned long prot, int shared)
3577 {
3578         const struct cred *cred = current_cred();
3579         u32 sid = cred_sid(cred);
3580         int rc = 0;
3581
3582         if (default_noexec &&
3583             (prot & PROT_EXEC) && (!file || IS_PRIVATE(file_inode(file)) ||
3584                                    (!shared && (prot & PROT_WRITE)))) {
3585                 /*
3586                  * We are making executable an anonymous mapping or a
3587                  * private file mapping that will also be writable.
3588                  * This has an additional check.
3589                  */
3590                 rc = avc_has_perm(sid, sid, SECCLASS_PROCESS,
3591                                   PROCESS__EXECMEM, NULL);
3592                 if (rc)
3593                         goto error;
3594         }
3595
3596         if (file) {
3597                 /* read access is always possible with a mapping */
3598                 u32 av = FILE__READ;
3599
3600                 /* write access only matters if the mapping is shared */
3601                 if (shared && (prot & PROT_WRITE))
3602                         av |= FILE__WRITE;
3603
3604                 if (prot & PROT_EXEC)
3605                         av |= FILE__EXECUTE;
3606
3607                 return file_has_perm(cred, file, av);
3608         }
3609
3610 error:
3611         return rc;
3612 }
3613
3614 static int selinux_mmap_addr(unsigned long addr)
3615 {
3616         int rc = 0;
3617
3618         if (addr < CONFIG_LSM_MMAP_MIN_ADDR) {
3619                 u32 sid = current_sid();
3620                 rc = avc_has_perm(sid, sid, SECCLASS_MEMPROTECT,
3621                                   MEMPROTECT__MMAP_ZERO, NULL);
3622         }
3623
3624         return rc;
3625 }
3626
3627 static int selinux_mmap_file(struct file *file, unsigned long reqprot,
3628                              unsigned long prot, unsigned long flags)
3629 {
3630         struct common_audit_data ad;
3631         int rc;
3632
3633         if (file) {
3634                 ad.type = LSM_AUDIT_DATA_FILE;
3635                 ad.u.file = file;
3636                 rc = inode_has_perm(current_cred(), file_inode(file),
3637                                     FILE__MAP, &ad);
3638                 if (rc)
3639                         return rc;
3640         }
3641
3642         if (selinux_checkreqprot)
3643                 prot = reqprot;
3644
3645         return file_map_prot_check(file, prot,
3646                                    (flags & MAP_TYPE) == MAP_SHARED);
3647 }
3648
3649 static int selinux_file_mprotect(struct vm_area_struct *vma,
3650                                  unsigned long reqprot,
3651                                  unsigned long prot)
3652 {
3653         const struct cred *cred = current_cred();
3654         u32 sid = cred_sid(cred);
3655
3656         if (selinux_checkreqprot)
3657                 prot = reqprot;
3658
3659         if (default_noexec &&
3660             (prot & PROT_EXEC) && !(vma->vm_flags & VM_EXEC)) {
3661                 int rc = 0;
3662                 if (vma->vm_start >= vma->vm_mm->start_brk &&
3663                     vma->vm_end <= vma->vm_mm->brk) {
3664                         rc = avc_has_perm(sid, sid, SECCLASS_PROCESS,
3665                                           PROCESS__EXECHEAP, NULL);
3666                 } else if (!vma->vm_file &&
3667                            ((vma->vm_start <= vma->vm_mm->start_stack &&
3668                              vma->vm_end >= vma->vm_mm->start_stack) ||
3669                             vma_is_stack_for_current(vma))) {
3670                         rc = avc_has_perm(sid, sid, SECCLASS_PROCESS,
3671                                           PROCESS__EXECSTACK, NULL);
3672                 } else if (vma->vm_file && vma->anon_vma) {
3673                         /*
3674                          * We are making executable a file mapping that has
3675                          * had some COW done. Since pages might have been
3676                          * written, check ability to execute the possibly
3677                          * modified content.  This typically should only
3678                          * occur for text relocations.
3679                          */
3680                         rc = file_has_perm(cred, vma->vm_file, FILE__EXECMOD);
3681                 }
3682                 if (rc)
3683                         return rc;
3684         }
3685
3686         return file_map_prot_check(vma->vm_file, prot, vma->vm_flags&VM_SHARED);
3687 }
3688
3689 static int selinux_file_lock(struct file *file, unsigned int cmd)
3690 {
3691         const struct cred *cred = current_cred();
3692
3693         return file_has_perm(cred, file, FILE__LOCK);
3694 }
3695
3696 static int selinux_file_fcntl(struct file *file, unsigned int cmd,
3697                               unsigned long arg)
3698 {
3699         const struct cred *cred = current_cred();
3700         int err = 0;
3701
3702         switch (cmd) {
3703         case F_SETFL:
3704                 if ((file->f_flags & O_APPEND) && !(arg & O_APPEND)) {
3705                         err = file_has_perm(cred, file, FILE__WRITE);
3706                         break;
3707                 }
3708                 /* fall through */
3709         case F_SETOWN:
3710         case F_SETSIG:
3711         case F_GETFL:
3712         case F_GETOWN:
3713         case F_GETSIG:
3714         case F_GETOWNER_UIDS:
3715                 /* Just check FD__USE permission */
3716                 err = file_has_perm(cred, file, 0);
3717                 break;
3718         case F_GETLK:
3719         case F_SETLK:
3720         case F_SETLKW:
3721         case F_OFD_GETLK:
3722         case F_OFD_SETLK:
3723         case F_OFD_SETLKW:
3724 #if BITS_PER_LONG == 32
3725         case F_GETLK64:
3726         case F_SETLK64:
3727         case F_SETLKW64:
3728 #endif
3729                 err = file_has_perm(cred, file, FILE__LOCK);
3730                 break;
3731         }
3732
3733         return err;
3734 }
3735
3736 static void selinux_file_set_fowner(struct file *file)
3737 {
3738         struct file_security_struct *fsec;
3739
3740         fsec = file->f_security;
3741         fsec->fown_sid = current_sid();
3742 }
3743
3744 static int selinux_file_send_sigiotask(struct task_struct *tsk,
3745                                        struct fown_struct *fown, int signum)
3746 {
3747         struct file *file;
3748         u32 sid = task_sid(tsk);
3749         u32 perm;
3750         struct file_security_struct *fsec;
3751
3752         /* struct fown_struct is never outside the context of a struct file */
3753         file = container_of(fown, struct file, f_owner);
3754
3755         fsec = file->f_security;
3756
3757         if (!signum)
3758                 perm = signal_to_av(SIGIO); /* as per send_sigio_to_task */
3759         else
3760                 perm = signal_to_av(signum);
3761
3762         return avc_has_perm(fsec->fown_sid, sid,
3763                             SECCLASS_PROCESS, perm, NULL);
3764 }
3765
3766 static int selinux_file_receive(struct file *file)
3767 {
3768         const struct cred *cred = current_cred();
3769
3770         return file_has_perm(cred, file, file_to_av(file));
3771 }
3772
3773 static int selinux_file_open(struct file *file, const struct cred *cred)
3774 {
3775         struct file_security_struct *fsec;
3776         struct inode_security_struct *isec;
3777
3778         fsec = file->f_security;
3779         isec = inode_security(file_inode(file));
3780         /*
3781          * Save inode label and policy sequence number
3782          * at open-time so that selinux_file_permission
3783          * can determine whether revalidation is necessary.
3784          * Task label is already saved in the file security
3785          * struct as its SID.
3786          */
3787         fsec->isid = isec->sid;
3788         fsec->pseqno = avc_policy_seqno();
3789         /*
3790          * Since the inode label or policy seqno may have changed
3791          * between the selinux_inode_permission check and the saving
3792          * of state above, recheck that access is still permitted.
3793          * Otherwise, access might never be revalidated against the
3794          * new inode label or new policy.
3795          * This check is not redundant - do not remove.
3796          */
3797         return file_path_has_perm(cred, file, open_file_to_av(file));
3798 }
3799
3800 /* task security operations */
3801
3802 static int selinux_task_alloc(struct task_struct *task,
3803                               unsigned long clone_flags)
3804 {
3805         u32 sid = current_sid();
3806
3807         return avc_has_perm(sid, sid, SECCLASS_PROCESS, PROCESS__FORK, NULL);
3808 }
3809
3810 /*
3811  * allocate the SELinux part of blank credentials
3812  */
3813 static int selinux_cred_alloc_blank(struct cred *cred, gfp_t gfp)
3814 {
3815         struct task_security_struct *tsec;
3816
3817         tsec = kzalloc(sizeof(struct task_security_struct), gfp);
3818         if (!tsec)
3819                 return -ENOMEM;
3820
3821         cred->security = tsec;
3822         return 0;
3823 }
3824
3825 /*
3826  * detach and free the LSM part of a set of credentials
3827  */
3828 static void selinux_cred_free(struct cred *cred)
3829 {
3830         struct task_security_struct *tsec = cred->security;
3831
3832         /*
3833          * cred->security == NULL if security_cred_alloc_blank() or
3834          * security_prepare_creds() returned an error.
3835          */
3836         BUG_ON(cred->security && (unsigned long) cred->security < PAGE_SIZE);
3837         cred->security = (void *) 0x7UL;
3838         kfree(tsec);
3839 }
3840
3841 /*
3842  * prepare a new set of credentials for modification
3843  */
3844 static int selinux_cred_prepare(struct cred *new, const struct cred *old,
3845                                 gfp_t gfp)
3846 {
3847         const struct task_security_struct *old_tsec;
3848         struct task_security_struct *tsec;
3849
3850         old_tsec = old->security;
3851
3852         tsec = kmemdup(old_tsec, sizeof(struct task_security_struct), gfp);
3853         if (!tsec)
3854                 return -ENOMEM;
3855
3856         new->security = tsec;
3857         return 0;
3858 }
3859
3860 /*
3861  * transfer the SELinux data to a blank set of creds
3862  */
3863 static void selinux_cred_transfer(struct cred *new, const struct cred *old)
3864 {
3865         const struct task_security_struct *old_tsec = old->security;
3866         struct task_security_struct *tsec = new->security;
3867
3868         *tsec = *old_tsec;
3869 }
3870
3871 /*
3872  * set the security data for a kernel service
3873  * - all the creation contexts are set to unlabelled
3874  */
3875 static int selinux_kernel_act_as(struct cred *new, u32 secid)
3876 {
3877         struct task_security_struct *tsec = new->security;
3878         u32 sid = current_sid();
3879         int ret;
3880
3881         ret = avc_has_perm(sid, secid,
3882                            SECCLASS_KERNEL_SERVICE,
3883                            KERNEL_SERVICE__USE_AS_OVERRIDE,
3884                            NULL);
3885         if (ret == 0) {
3886                 tsec->sid = secid;
3887                 tsec->create_sid = 0;
3888                 tsec->keycreate_sid = 0;
3889                 tsec->sockcreate_sid = 0;
3890         }
3891         return ret;
3892 }
3893
3894 /*
3895  * set the file creation context in a security record to the same as the
3896  * objective context of the specified inode
3897  */
3898 static int selinux_kernel_create_files_as(struct cred *new, struct inode *inode)
3899 {
3900         struct inode_security_struct *isec = inode_security(inode);
3901         struct task_security_struct *tsec = new->security;
3902         u32 sid = current_sid();
3903         int ret;
3904
3905         ret = avc_has_perm(sid, isec->sid,
3906                            SECCLASS_KERNEL_SERVICE,
3907                            KERNEL_SERVICE__CREATE_FILES_AS,
3908                            NULL);
3909
3910         if (ret == 0)
3911                 tsec->create_sid = isec->sid;
3912         return ret;
3913 }
3914
3915 static int selinux_kernel_module_request(char *kmod_name)
3916 {
3917         struct common_audit_data ad;
3918
3919         ad.type = LSM_AUDIT_DATA_KMOD;
3920         ad.u.kmod_name = kmod_name;
3921
3922         return avc_has_perm(current_sid(), SECINITSID_KERNEL, SECCLASS_SYSTEM,
3923                             SYSTEM__MODULE_REQUEST, &ad);
3924 }
3925
3926 static int selinux_kernel_module_from_file(struct file *file)
3927 {
3928         struct common_audit_data ad;
3929         struct inode_security_struct *isec;
3930         struct file_security_struct *fsec;
3931         u32 sid = current_sid();
3932         int rc;
3933
3934         /* init_module */
3935         if (file == NULL)
3936                 return avc_has_perm(sid, sid, SECCLASS_SYSTEM,
3937                                         SYSTEM__MODULE_LOAD, NULL);
3938
3939         /* finit_module */
3940
3941         ad.type = LSM_AUDIT_DATA_FILE;
3942         ad.u.file = file;
3943
3944         fsec = file->f_security;
3945         if (sid != fsec->sid) {
3946                 rc = avc_has_perm(sid, fsec->sid, SECCLASS_FD, FD__USE, &ad);
3947                 if (rc)
3948                         return rc;
3949         }
3950
3951         isec = inode_security(file_inode(file));
3952         return avc_has_perm(sid, isec->sid, SECCLASS_SYSTEM,
3953                                 SYSTEM__MODULE_LOAD, &ad);
3954 }
3955
3956 static int selinux_kernel_read_file(struct file *file,
3957                                     enum kernel_read_file_id id)
3958 {
3959         int rc = 0;
3960
3961         switch (id) {
3962         case READING_MODULE:
3963                 rc = selinux_kernel_module_from_file(file);
3964                 break;
3965         default:
3966                 break;
3967         }
3968
3969         return rc;
3970 }
3971
3972 static int selinux_task_setpgid(struct task_struct *p, pid_t pgid)
3973 {
3974         return avc_has_perm(current_sid(), task_sid(p), SECCLASS_PROCESS,
3975                             PROCESS__SETPGID, NULL);
3976 }
3977
3978 static int selinux_task_getpgid(struct task_struct *p)
3979 {
3980         return avc_has_perm(current_sid(), task_sid(p), SECCLASS_PROCESS,
3981                             PROCESS__GETPGID, NULL);
3982 }
3983
3984 static int selinux_task_getsid(struct task_struct *p)
3985 {
3986         return avc_has_perm(current_sid(), task_sid(p), SECCLASS_PROCESS,
3987                             PROCESS__GETSESSION, NULL);
3988 }
3989
3990 static void selinux_task_getsecid(struct task_struct *p, u32 *secid)
3991 {
3992         *secid = task_sid(p);
3993 }
3994
3995 static int selinux_task_setnice(struct task_struct *p, int nice)
3996 {
3997         return avc_has_perm(current_sid(), task_sid(p), SECCLASS_PROCESS,
3998                             PROCESS__SETSCHED, NULL);
3999 }
4000
4001 static int selinux_task_setioprio(struct task_struct *p, int ioprio)
4002 {
4003         return avc_has_perm(current_sid(), task_sid(p), SECCLASS_PROCESS,
4004                             PROCESS__SETSCHED, NULL);
4005 }
4006
4007 static int selinux_task_getioprio(struct task_struct *p)
4008 {
4009         return avc_has_perm(current_sid(), task_sid(p), SECCLASS_PROCESS,
4010                             PROCESS__GETSCHED, NULL);
4011 }
4012
4013 int selinux_task_prlimit(const struct cred *cred, const struct cred *tcred,
4014                          unsigned int flags)
4015 {
4016         u32 av = 0;
4017
4018         if (!flags)
4019                 return 0;
4020         if (flags & LSM_PRLIMIT_WRITE)
4021                 av |= PROCESS__SETRLIMIT;
4022         if (flags & LSM_PRLIMIT_READ)
4023                 av |= PROCESS__GETRLIMIT;
4024         return avc_has_perm(cred_sid(cred), cred_sid(tcred),
4025                             SECCLASS_PROCESS, av, NULL);
4026 }
4027
4028 static int selinux_task_setrlimit(struct task_struct *p, unsigned int resource,
4029                 struct rlimit *new_rlim)
4030 {
4031         struct rlimit *old_rlim = p->signal->rlim + resource;
4032
4033         /* Control the ability to change the hard limit (whether
4034            lowering or raising it), so that the hard limit can
4035            later be used as a safe reset point for the soft limit
4036            upon context transitions.  See selinux_bprm_committing_creds. */
4037         if (old_rlim->rlim_max != new_rlim->rlim_max)
4038                 return avc_has_perm(current_sid(), task_sid(p),
4039                                     SECCLASS_PROCESS, PROCESS__SETRLIMIT, NULL);
4040
4041         return 0;
4042 }
4043
4044 static int selinux_task_setscheduler(struct task_struct *p)
4045 {
4046         return avc_has_perm(current_sid(), task_sid(p), SECCLASS_PROCESS,
4047                             PROCESS__SETSCHED, NULL);
4048 }
4049
4050 static int selinux_task_getscheduler(struct task_struct *p)
4051 {
4052         return avc_has_perm(current_sid(), task_sid(p), SECCLASS_PROCESS,
4053                             PROCESS__GETSCHED, NULL);
4054 }
4055
4056 static int selinux_task_movememory(struct task_struct *p)
4057 {
4058         return avc_has_perm(current_sid(), task_sid(p), SECCLASS_PROCESS,
4059                             PROCESS__SETSCHED, NULL);
4060 }
4061
4062 static int selinux_task_kill(struct task_struct *p, struct siginfo *info,
4063                                 int sig, u32 secid)
4064 {
4065         u32 perm;
4066
4067         if (!sig)
4068                 perm = PROCESS__SIGNULL; /* null signal; existence test */
4069         else
4070                 perm = signal_to_av(sig);
4071         if (!secid)
4072                 secid = current_sid();
4073         return avc_has_perm(secid, task_sid(p), SECCLASS_PROCESS, perm, NULL);
4074 }
4075
4076 static void selinux_task_to_inode(struct task_struct *p,
4077                                   struct inode *inode)
4078 {
4079         struct inode_security_struct *isec = inode->i_security;
4080         u32 sid = task_sid(p);
4081
4082         spin_lock(&isec->lock);
4083         isec->sclass = inode_mode_to_security_class(inode->i_mode);
4084         isec->sid = sid;
4085         isec->initialized = LABEL_INITIALIZED;
4086         spin_unlock(&isec->lock);
4087 }
4088
4089 /* Returns error only if unable to parse addresses */
4090 static int selinux_parse_skb_ipv4(struct sk_buff *skb,
4091                         struct common_audit_data *ad, u8 *proto)
4092 {
4093         int offset, ihlen, ret = -EINVAL;
4094         struct iphdr _iph, *ih;
4095
4096         offset = skb_network_offset(skb);
4097         ih = skb_header_pointer(skb, offset, sizeof(_iph), &_iph);
4098         if (ih == NULL)
4099                 goto out;
4100
4101         ihlen = ih->ihl * 4;
4102         if (ihlen < sizeof(_iph))
4103                 goto out;
4104
4105         ad->u.net->v4info.saddr = ih->saddr;
4106         ad->u.net->v4info.daddr = ih->daddr;
4107         ret = 0;
4108
4109         if (proto)
4110                 *proto = ih->protocol;
4111
4112         switch (ih->protocol) {
4113         case IPPROTO_TCP: {
4114                 struct tcphdr _tcph, *th;
4115
4116                 if (ntohs(ih->frag_off) & IP_OFFSET)
4117                         break;
4118
4119                 offset += ihlen;
4120                 th = skb_header_pointer(skb, offset, sizeof(_tcph), &_tcph);
4121                 if (th == NULL)
4122                         break;
4123
4124                 ad->u.net->sport = th->source;
4125                 ad->u.net->dport = th->dest;
4126                 break;
4127         }
4128
4129         case IPPROTO_UDP: {
4130                 struct udphdr _udph, *uh;
4131
4132                 if (ntohs(ih->frag_off) & IP_OFFSET)
4133                         break;
4134
4135                 offset += ihlen;
4136                 uh = skb_header_pointer(skb, offset, sizeof(_udph), &_udph);
4137                 if (uh == NULL)
4138                         break;
4139
4140                 ad->u.net->sport = uh->source;
4141                 ad->u.net->dport = uh->dest;
4142                 break;
4143         }
4144
4145         case IPPROTO_DCCP: {
4146                 struct dccp_hdr _dccph, *dh;
4147
4148                 if (ntohs(ih->frag_off) & IP_OFFSET)
4149                         break;
4150
4151                 offset += ihlen;
4152                 dh = skb_header_pointer(skb, offset, sizeof(_dccph), &_dccph);
4153                 if (dh == NULL)
4154                         break;
4155
4156                 ad->u.net->sport = dh->dccph_sport;
4157                 ad->u.net->dport = dh->dccph_dport;
4158                 break;
4159         }
4160
4161         default:
4162                 break;
4163         }
4164 out:
4165         return ret;
4166 }
4167
4168 #if IS_ENABLED(CONFIG_IPV6)
4169
4170 /* Returns error only if unable to parse addresses */
4171 static int selinux_parse_skb_ipv6(struct sk_buff *skb,
4172                         struct common_audit_data *ad, u8 *proto)
4173 {
4174         u8 nexthdr;
4175         int ret = -EINVAL, offset;
4176         struct ipv6hdr _ipv6h, *ip6;
4177         __be16 frag_off;
4178
4179         offset = skb_network_offset(skb);
4180         ip6 = skb_header_pointer(skb, offset, sizeof(_ipv6h), &_ipv6h);
4181         if (ip6 == NULL)
4182                 goto out;
4183
4184         ad->u.net->v6info.saddr = ip6->saddr;
4185         ad->u.net->v6info.daddr = ip6->daddr;
4186         ret = 0;
4187
4188         nexthdr = ip6->nexthdr;
4189         offset += sizeof(_ipv6h);
4190         offset = ipv6_skip_exthdr(skb, offset, &nexthdr, &frag_off);
4191         if (offset < 0)
4192                 goto out;
4193
4194         if (proto)
4195                 *proto = nexthdr;
4196
4197         switch (nexthdr) {
4198         case IPPROTO_TCP: {
4199                 struct tcphdr _tcph, *th;
4200
4201                 th = skb_header_pointer(skb, offset, sizeof(_tcph), &_tcph);
4202                 if (th == NULL)
4203                         break;
4204
4205                 ad->u.net->sport = th->source;
4206                 ad->u.net->dport = th->dest;
4207                 break;
4208         }
4209
4210         case IPPROTO_UDP: {
4211                 struct udphdr _udph, *uh;
4212
4213                 uh = skb_header_pointer(skb, offset, sizeof(_udph), &_udph);
4214                 if (uh == NULL)
4215                         break;
4216
4217                 ad->u.net->sport = uh->source;
4218                 ad->u.net->dport = uh->dest;
4219                 break;
4220         }
4221
4222         case IPPROTO_DCCP: {
4223                 struct dccp_hdr _dccph, *dh;
4224
4225                 dh = skb_header_pointer(skb, offset, sizeof(_dccph), &_dccph);
4226                 if (dh == NULL)
4227                         break;
4228
4229                 ad->u.net->sport = dh->dccph_sport;
4230                 ad->u.net->dport = dh->dccph_dport;
4231                 break;
4232         }
4233
4234         /* includes fragments */
4235         default:
4236                 break;
4237         }
4238 out:
4239         return ret;
4240 }
4241
4242 #endif /* IPV6 */
4243
4244 static int selinux_parse_skb(struct sk_buff *skb, struct common_audit_data *ad,
4245                              char **_addrp, int src, u8 *proto)
4246 {
4247         char *addrp;
4248         int ret;
4249
4250         switch (ad->u.net->family) {
4251         case PF_INET:
4252                 ret = selinux_parse_skb_ipv4(skb, ad, proto);
4253                 if (ret)
4254                         goto parse_error;
4255                 addrp = (char *)(src ? &ad->u.net->v4info.saddr :
4256                                        &ad->u.net->v4info.daddr);
4257                 goto okay;
4258
4259 #if IS_ENABLED(CONFIG_IPV6)
4260         case PF_INET6:
4261                 ret = selinux_parse_skb_ipv6(skb, ad, proto);
4262                 if (ret)
4263                         goto parse_error;
4264                 addrp = (char *)(src ? &ad->u.net->v6info.saddr :
4265                                        &ad->u.net->v6info.daddr);
4266                 goto okay;
4267 #endif  /* IPV6 */
4268         default:
4269                 addrp = NULL;
4270                 goto okay;
4271         }
4272
4273 parse_error:
4274         printk(KERN_WARNING
4275                "SELinux: failure in selinux_parse_skb(),"
4276                " unable to parse packet\n");
4277         return ret;
4278
4279 okay:
4280         if (_addrp)
4281                 *_addrp = addrp;
4282         return 0;
4283 }
4284
4285 /**
4286  * selinux_skb_peerlbl_sid - Determine the peer label of a packet
4287  * @skb: the packet
4288  * @family: protocol family
4289  * @sid: the packet's peer label SID
4290  *
4291  * Description:
4292  * Check the various different forms of network peer labeling and determine
4293  * the peer label/SID for the packet; most of the magic actually occurs in
4294  * the security server function security_net_peersid_cmp().  The function
4295  * returns zero if the value in @sid is valid (although it may be SECSID_NULL)
4296  * or -EACCES if @sid is invalid due to inconsistencies with the different
4297  * peer labels.
4298  *
4299  */
4300 static int selinux_skb_peerlbl_sid(struct sk_buff *skb, u16 family, u32 *sid)
4301 {
4302         int err;
4303         u32 xfrm_sid;
4304         u32 nlbl_sid;
4305         u32 nlbl_type;
4306
4307         err = selinux_xfrm_skb_sid(skb, &xfrm_sid);
4308         if (unlikely(err))
4309                 return -EACCES;
4310         err = selinux_netlbl_skbuff_getsid(skb, family, &nlbl_type, &nlbl_sid);
4311         if (unlikely(err))
4312                 return -EACCES;
4313
4314         err = security_net_peersid_resolve(nlbl_sid, nlbl_type, xfrm_sid, sid);
4315         if (unlikely(err)) {
4316                 printk(KERN_WARNING
4317                        "SELinux: failure in selinux_skb_peerlbl_sid(),"
4318                        " unable to determine packet's peer label\n");
4319                 return -EACCES;
4320         }
4321
4322         return 0;
4323 }
4324
4325 /**
4326  * selinux_conn_sid - Determine the child socket label for a connection
4327  * @sk_sid: the parent socket's SID
4328  * @skb_sid: the packet's SID
4329  * @conn_sid: the resulting connection SID
4330  *
4331  * If @skb_sid is valid then the user:role:type information from @sk_sid is
4332  * combined with the MLS information from @skb_sid in order to create
4333  * @conn_sid.  If @skb_sid is not valid then then @conn_sid is simply a copy
4334  * of @sk_sid.  Returns zero on success, negative values on failure.
4335  *
4336  */
4337 static int selinux_conn_sid(u32 sk_sid, u32 skb_sid, u32 *conn_sid)
4338 {
4339         int err = 0;
4340
4341         if (skb_sid != SECSID_NULL)
4342                 err = security_sid_mls_copy(sk_sid, skb_sid, conn_sid);
4343         else
4344                 *conn_sid = sk_sid;
4345
4346         return err;
4347 }
4348
4349 /* socket security operations */
4350
4351 static int socket_sockcreate_sid(const struct task_security_struct *tsec,
4352                                  u16 secclass, u32 *socksid)
4353 {
4354         if (tsec->sockcreate_sid > SECSID_NULL) {
4355                 *socksid = tsec->sockcreate_sid;
4356                 return 0;
4357         }
4358
4359         return security_transition_sid(tsec->sid, tsec->sid, secclass, NULL,
4360                                        socksid);
4361 }
4362
4363 static int sock_has_perm(struct sock *sk, u32 perms)
4364 {
4365         struct sk_security_struct *sksec = sk->sk_security;
4366         struct common_audit_data ad;
4367         struct lsm_network_audit net = {0,};
4368
4369         if (sksec->sid == SECINITSID_KERNEL)
4370                 return 0;
4371
4372         ad.type = LSM_AUDIT_DATA_NET;
4373         ad.u.net = &net;
4374         ad.u.net->sk = sk;
4375
4376         return avc_has_perm(current_sid(), sksec->sid, sksec->sclass, perms,
4377                             &ad);
4378 }
4379
4380 static int selinux_socket_create(int family, int type,
4381                                  int protocol, int kern)
4382 {
4383         const struct task_security_struct *tsec = current_security();
4384         u32 newsid;
4385         u16 secclass;
4386         int rc;
4387
4388         if (kern)
4389                 return 0;
4390
4391         secclass = socket_type_to_security_class(family, type, protocol);
4392         rc = socket_sockcreate_sid(tsec, secclass, &newsid);
4393         if (rc)
4394                 return rc;
4395
4396         return avc_has_perm(tsec->sid, newsid, secclass, SOCKET__CREATE, NULL);
4397 }
4398
4399 static int selinux_socket_post_create(struct socket *sock, int family,
4400                                       int type, int protocol, int kern)
4401 {
4402         const struct task_security_struct *tsec = current_security();
4403         struct inode_security_struct *isec = inode_security_novalidate(SOCK_INODE(sock));
4404         struct sk_security_struct *sksec;
4405         u16 sclass = socket_type_to_security_class(family, type, protocol);
4406         u32 sid = SECINITSID_KERNEL;
4407         int err = 0;
4408
4409         if (!kern) {
4410                 err = socket_sockcreate_sid(tsec, sclass, &sid);
4411                 if (err)
4412                         return err;
4413         }
4414
4415         isec->sclass = sclass;
4416         isec->sid = sid;
4417         isec->initialized = LABEL_INITIALIZED;
4418
4419         if (sock->sk) {
4420                 sksec = sock->sk->sk_security;
4421                 sksec->sclass = sclass;
4422                 sksec->sid = sid;
4423                 err = selinux_netlbl_socket_post_create(sock->sk, family);
4424         }
4425
4426         return err;
4427 }
4428
4429 /* Range of port numbers used to automatically bind.
4430    Need to determine whether we should perform a name_bind
4431    permission check between the socket and the port number. */
4432
4433 static int selinux_socket_bind(struct socket *sock, struct sockaddr *address, int addrlen)
4434 {
4435         struct sock *sk = sock->sk;
4436         u16 family;
4437         int err;
4438
4439         err = sock_has_perm(sk, SOCKET__BIND);
4440         if (err)
4441                 goto out;
4442
4443         /*
4444          * If PF_INET or PF_INET6, check name_bind permission for the port.
4445          * Multiple address binding for SCTP is not supported yet: we just
4446          * check the first address now.
4447          */
4448         family = sk->sk_family;
4449         if (family == PF_INET || family == PF_INET6) {
4450                 char *addrp;
4451                 struct sk_security_struct *sksec = sk->sk_security;
4452                 struct common_audit_data ad;
4453                 struct lsm_network_audit net = {0,};
4454                 struct sockaddr_in *addr4 = NULL;
4455                 struct sockaddr_in6 *addr6 = NULL;
4456                 unsigned short snum;
4457                 u32 sid, node_perm;
4458
4459                 if (family == PF_INET) {
4460                         if (addrlen < sizeof(struct sockaddr_in)) {
4461                                 err = -EINVAL;
4462                                 goto out;
4463                         }
4464                         addr4 = (struct sockaddr_in *)address;
4465                         snum = ntohs(addr4->sin_port);
4466                         addrp = (char *)&addr4->sin_addr.s_addr;
4467                 } else {
4468                         if (addrlen < SIN6_LEN_RFC2133) {
4469                                 err = -EINVAL;
4470                                 goto out;
4471                         }
4472                         addr6 = (struct sockaddr_in6 *)address;
4473                         snum = ntohs(addr6->sin6_port);
4474                         addrp = (char *)&addr6->sin6_addr.s6_addr;
4475                 }
4476
4477                 if (snum) {
4478                         int low, high;
4479
4480                         inet_get_local_port_range(sock_net(sk), &low, &high);
4481
4482                         if (snum < max(inet_prot_sock(sock_net(sk)), low) ||
4483                             snum > high) {
4484                                 err = sel_netport_sid(sk->sk_protocol,
4485                                                       snum, &sid);
4486                                 if (err)
4487                                         goto out;
4488                                 ad.type = LSM_AUDIT_DATA_NET;
4489                                 ad.u.net = &net;
4490                                 ad.u.net->sport = htons(snum);
4491                                 ad.u.net->family = family;
4492                                 err = avc_has_perm(sksec->sid, sid,
4493                                                    sksec->sclass,
4494                                                    SOCKET__NAME_BIND, &ad);
4495                                 if (err)
4496                                         goto out;
4497                         }
4498                 }
4499
4500                 switch (sksec->sclass) {
4501                 case SECCLASS_TCP_SOCKET:
4502                         node_perm = TCP_SOCKET__NODE_BIND;
4503                         break;
4504
4505                 case SECCLASS_UDP_SOCKET:
4506                         node_perm = UDP_SOCKET__NODE_BIND;
4507                         break;
4508
4509                 case SECCLASS_DCCP_SOCKET:
4510                         node_perm = DCCP_SOCKET__NODE_BIND;
4511                         break;
4512
4513                 default:
4514                         node_perm = RAWIP_SOCKET__NODE_BIND;
4515                         break;
4516                 }
4517
4518                 err = sel_netnode_sid(addrp, family, &sid);
4519                 if (err)
4520                         goto out;
4521
4522                 ad.type = LSM_AUDIT_DATA_NET;
4523                 ad.u.net = &net;
4524                 ad.u.net->sport = htons(snum);
4525                 ad.u.net->family = family;
4526
4527                 if (family == PF_INET)
4528                         ad.u.net->v4info.saddr = addr4->sin_addr.s_addr;
4529                 else
4530                         ad.u.net->v6info.saddr = addr6->sin6_addr;
4531
4532                 err = avc_has_perm(sksec->sid, sid,
4533                                    sksec->sclass, node_perm, &ad);
4534                 if (err)
4535                         goto out;
4536         }
4537 out:
4538         return err;
4539 }
4540
4541 static int selinux_socket_connect(struct socket *sock, struct sockaddr *address, int addrlen)
4542 {
4543         struct sock *sk = sock->sk;
4544         struct sk_security_struct *sksec = sk->sk_security;
4545         int err;
4546
4547         err = sock_has_perm(sk, SOCKET__CONNECT);
4548         if (err)
4549                 return err;
4550
4551         /*
4552          * If a TCP or DCCP socket, check name_connect permission for the port.
4553          */
4554         if (sksec->sclass == SECCLASS_TCP_SOCKET ||
4555             sksec->sclass == SECCLASS_DCCP_SOCKET) {
4556                 struct common_audit_data ad;
4557                 struct lsm_network_audit net = {0,};
4558                 struct sockaddr_in *addr4 = NULL;
4559                 struct sockaddr_in6 *addr6 = NULL;
4560                 unsigned short snum;
4561                 u32 sid, perm;
4562
4563                 if (sk->sk_family == PF_INET) {
4564                         addr4 = (struct sockaddr_in *)address;
4565                         if (addrlen < sizeof(struct sockaddr_in))
4566                                 return -EINVAL;
4567                         snum = ntohs(addr4->sin_port);
4568                 } else {
4569                         addr6 = (struct sockaddr_in6 *)address;
4570                         if (addrlen < SIN6_LEN_RFC2133)
4571                                 return -EINVAL;
4572                         snum = ntohs(addr6->sin6_port);
4573                 }
4574
4575                 err = sel_netport_sid(sk->sk_protocol, snum, &sid);
4576                 if (err)
4577                         goto out;
4578
4579                 perm = (sksec->sclass == SECCLASS_TCP_SOCKET) ?
4580                        TCP_SOCKET__NAME_CONNECT : DCCP_SOCKET__NAME_CONNECT;
4581
4582                 ad.type = LSM_AUDIT_DATA_NET;
4583                 ad.u.net = &net;
4584                 ad.u.net->dport = htons(snum);
4585                 ad.u.net->family = sk->sk_family;
4586                 err = avc_has_perm(sksec->sid, sid, sksec->sclass, perm, &ad);
4587                 if (err)
4588                         goto out;
4589         }
4590
4591         err = selinux_netlbl_socket_connect(sk, address);
4592
4593 out:
4594         return err;
4595 }
4596
4597 static int selinux_socket_listen(struct socket *sock, int backlog)
4598 {
4599         return sock_has_perm(sock->sk, SOCKET__LISTEN);
4600 }
4601
4602 static int selinux_socket_accept(struct socket *sock, struct socket *newsock)
4603 {
4604         int err;
4605         struct inode_security_struct *isec;
4606         struct inode_security_struct *newisec;
4607         u16 sclass;
4608         u32 sid;
4609
4610         err = sock_has_perm(sock->sk, SOCKET__ACCEPT);
4611         if (err)
4612                 return err;
4613
4614         isec = inode_security_novalidate(SOCK_INODE(sock));
4615         spin_lock(&isec->lock);
4616         sclass = isec->sclass;
4617         sid = isec->sid;
4618         spin_unlock(&isec->lock);
4619
4620         newisec = inode_security_novalidate(SOCK_INODE(newsock));
4621         newisec->sclass = sclass;
4622         newisec->sid = sid;
4623         newisec->initialized = LABEL_INITIALIZED;
4624
4625         return 0;
4626 }
4627
4628 static int selinux_socket_sendmsg(struct socket *sock, struct msghdr *msg,
4629                                   int size)
4630 {
4631         return sock_has_perm(sock->sk, SOCKET__WRITE);
4632 }
4633
4634 static int selinux_socket_recvmsg(struct socket *sock, struct msghdr *msg,
4635                                   int size, int flags)
4636 {
4637         return sock_has_perm(sock->sk, SOCKET__READ);
4638 }
4639
4640 static int selinux_socket_getsockname(struct socket *sock)
4641 {
4642         return sock_has_perm(sock->sk, SOCKET__GETATTR);
4643 }
4644
4645 static int selinux_socket_getpeername(struct socket *sock)
4646 {
4647         return sock_has_perm(sock->sk, SOCKET__GETATTR);
4648 }
4649
4650 static int selinux_socket_setsockopt(struct socket *sock, int level, int optname)
4651 {
4652         int err;
4653
4654         err = sock_has_perm(sock->sk, SOCKET__SETOPT);
4655         if (err)
4656                 return err;
4657
4658         return selinux_netlbl_socket_setsockopt(sock, level, optname);
4659 }
4660
4661 static int selinux_socket_getsockopt(struct socket *sock, int level,
4662                                      int optname)
4663 {
4664         return sock_has_perm(sock->sk, SOCKET__GETOPT);
4665 }
4666
4667 static int selinux_socket_shutdown(struct socket *sock, int how)
4668 {
4669         return sock_has_perm(sock->sk, SOCKET__SHUTDOWN);
4670 }
4671
4672 static int selinux_socket_unix_stream_connect(struct sock *sock,
4673                                               struct sock *other,
4674                                               struct sock *newsk)
4675 {
4676         struct sk_security_struct *sksec_sock = sock->sk_security;
4677         struct sk_security_struct *sksec_other = other->sk_security;
4678         struct sk_security_struct *sksec_new = newsk->sk_security;
4679         struct common_audit_data ad;
4680         struct lsm_network_audit net = {0,};
4681         int err;
4682
4683         ad.type = LSM_AUDIT_DATA_NET;
4684         ad.u.net = &net;
4685         ad.u.net->sk = other;
4686
4687         err = avc_has_perm(sksec_sock->sid, sksec_other->sid,
4688                            sksec_other->sclass,
4689                            UNIX_STREAM_SOCKET__CONNECTTO, &ad);
4690         if (err)
4691                 return err;
4692
4693         /* server child socket */
4694         sksec_new->peer_sid = sksec_sock->sid;
4695         err = security_sid_mls_copy(sksec_other->sid, sksec_sock->sid,
4696                                     &sksec_new->sid);
4697         if (err)
4698                 return err;
4699
4700         /* connecting socket */
4701         sksec_sock->peer_sid = sksec_new->sid;
4702
4703         return 0;
4704 }
4705
4706 static int selinux_socket_unix_may_send(struct socket *sock,
4707                                         struct socket *other)
4708 {
4709         struct sk_security_struct *ssec = sock->sk->sk_security;
4710         struct sk_security_struct *osec = other->sk->sk_security;
4711         struct common_audit_data ad;
4712         struct lsm_network_audit net = {0,};
4713
4714         ad.type = LSM_AUDIT_DATA_NET;
4715         ad.u.net = &net;
4716         ad.u.net->sk = other->sk;
4717
4718         return avc_has_perm(ssec->sid, osec->sid, osec->sclass, SOCKET__SENDTO,
4719                             &ad);
4720 }
4721
4722 static int selinux_inet_sys_rcv_skb(struct net *ns, int ifindex,
4723                                     char *addrp, u16 family, u32 peer_sid,
4724                                     struct common_audit_data *ad)
4725 {
4726         int err;
4727         u32 if_sid;
4728         u32 node_sid;
4729
4730         err = sel_netif_sid(ns, ifindex, &if_sid);
4731         if (err)
4732                 return err;
4733         err = avc_has_perm(peer_sid, if_sid,
4734                            SECCLASS_NETIF, NETIF__INGRESS, ad);
4735         if (err)
4736                 return err;
4737
4738         err = sel_netnode_sid(addrp, family, &node_sid);
4739         if (err)
4740                 return err;
4741         return avc_has_perm(peer_sid, node_sid,
4742                             SECCLASS_NODE, NODE__RECVFROM, ad);
4743 }
4744
4745 static int selinux_sock_rcv_skb_compat(struct sock *sk, struct sk_buff *skb,
4746                                        u16 family)
4747 {
4748         int err = 0;
4749         struct sk_security_struct *sksec = sk->sk_security;
4750         u32 sk_sid = sksec->sid;
4751         struct common_audit_data ad;
4752         struct lsm_network_audit net = {0,};
4753         char *addrp;
4754
4755         ad.type = LSM_AUDIT_DATA_NET;
4756         ad.u.net = &net;
4757         ad.u.net->netif = skb->skb_iif;
4758         ad.u.net->family = family;
4759         err = selinux_parse_skb(skb, &ad, &addrp, 1, NULL);
4760         if (err)
4761                 return err;
4762
4763         if (selinux_secmark_enabled()) {
4764                 err = avc_has_perm(sk_sid, skb->secmark, SECCLASS_PACKET,
4765                                    PACKET__RECV, &ad);
4766                 if (err)
4767                         return err;
4768         }
4769
4770         err = selinux_netlbl_sock_rcv_skb(sksec, skb, family, &ad);
4771         if (err)
4772                 return err;
4773         err = selinux_xfrm_sock_rcv_skb(sksec->sid, skb, &ad);
4774
4775         return err;
4776 }
4777
4778 static int selinux_socket_sock_rcv_skb(struct sock *sk, struct sk_buff *skb)
4779 {
4780         int err;
4781         struct sk_security_struct *sksec = sk->sk_security;
4782         u16 family = sk->sk_family;
4783         u32 sk_sid = sksec->sid;
4784         struct common_audit_data ad;
4785         struct lsm_network_audit net = {0,};
4786         char *addrp;
4787         u8 secmark_active;
4788         u8 peerlbl_active;
4789
4790         if (family != PF_INET && family != PF_INET6)
4791                 return 0;
4792
4793         /* Handle mapped IPv4 packets arriving via IPv6 sockets */
4794         if (family == PF_INET6 && skb->protocol == htons(ETH_P_IP))
4795                 family = PF_INET;
4796
4797         /* If any sort of compatibility mode is enabled then handoff processing
4798          * to the selinux_sock_rcv_skb_compat() function to deal with the
4799          * special handling.  We do this in an attempt to keep this function
4800          * as fast and as clean as possible. */
4801         if (!selinux_policycap_netpeer)
4802                 return selinux_sock_rcv_skb_compat(sk, skb, family);
4803
4804         secmark_active = selinux_secmark_enabled();
4805         peerlbl_active = selinux_peerlbl_enabled();
4806         if (!secmark_active && !peerlbl_active)
4807                 return 0;
4808
4809         ad.type = LSM_AUDIT_DATA_NET;
4810         ad.u.net = &net;
4811         ad.u.net->netif = skb->skb_iif;
4812         ad.u.net->family = family;
4813         err = selinux_parse_skb(skb, &ad, &addrp, 1, NULL);
4814         if (err)
4815                 return err;
4816
4817         if (peerlbl_active) {
4818                 u32 peer_sid;
4819
4820                 err = selinux_skb_peerlbl_sid(skb, family, &peer_sid);
4821                 if (err)
4822                         return err;
4823                 err = selinux_inet_sys_rcv_skb(sock_net(sk), skb->skb_iif,
4824                                                addrp, family, peer_sid, &ad);
4825                 if (err) {
4826                         selinux_netlbl_err(skb, family, err, 0);
4827                         return err;
4828                 }
4829                 err = avc_has_perm(sk_sid, peer_sid, SECCLASS_PEER,
4830                                    PEER__RECV, &ad);
4831                 if (err) {
4832                         selinux_netlbl_err(skb, family, err, 0);
4833                         return err;
4834                 }
4835         }
4836
4837         if (secmark_active) {
4838                 err = avc_has_perm(sk_sid, skb->secmark, SECCLASS_PACKET,
4839                                    PACKET__RECV, &ad);
4840                 if (err)
4841                         return err;
4842         }
4843
4844         return err;
4845 }
4846
4847 static int selinux_socket_getpeersec_stream(struct socket *sock, char __user *optval,
4848                                             int __user *optlen, unsigned len)
4849 {
4850         int err = 0;
4851         char *scontext;
4852         u32 scontext_len;
4853         struct sk_security_struct *sksec = sock->sk->sk_security;
4854         u32 peer_sid = SECSID_NULL;
4855
4856         if (sksec->sclass == SECCLASS_UNIX_STREAM_SOCKET ||
4857             sksec->sclass == SECCLASS_TCP_SOCKET)
4858                 peer_sid = sksec->peer_sid;
4859         if (peer_sid == SECSID_NULL)
4860                 return -ENOPROTOOPT;
4861
4862         err = security_sid_to_context(peer_sid, &scontext, &scontext_len);
4863         if (err)
4864                 return err;
4865
4866         if (scontext_len > len) {
4867                 err = -ERANGE;
4868                 goto out_len;
4869         }
4870
4871         if (copy_to_user(optval, scontext, scontext_len))
4872                 err = -EFAULT;
4873
4874 out_len:
4875         if (put_user(scontext_len, optlen))
4876                 err = -EFAULT;
4877         kfree(scontext);
4878         return err;
4879 }
4880
4881 static int selinux_socket_getpeersec_dgram(struct socket *sock, struct sk_buff *skb, u32 *secid)
4882 {
4883         u32 peer_secid = SECSID_NULL;
4884         u16 family;
4885         struct inode_security_struct *isec;
4886
4887         if (skb && skb->protocol == htons(ETH_P_IP))
4888                 family = PF_INET;
4889         else if (skb && skb->protocol == htons(ETH_P_IPV6))
4890                 family = PF_INET6;
4891         else if (sock)
4892                 family = sock->sk->sk_family;
4893         else
4894                 goto out;
4895
4896         if (sock && family == PF_UNIX) {
4897                 isec = inode_security_novalidate(SOCK_INODE(sock));
4898                 peer_secid = isec->sid;
4899         } else if (skb)
4900                 selinux_skb_peerlbl_sid(skb, family, &peer_secid);
4901
4902 out:
4903         *secid = peer_secid;
4904         if (peer_secid == SECSID_NULL)
4905                 return -EINVAL;
4906         return 0;
4907 }
4908
4909 static int selinux_sk_alloc_security(struct sock *sk, int family, gfp_t priority)
4910 {
4911         struct sk_security_struct *sksec;
4912
4913         sksec = kzalloc(sizeof(*sksec), priority);
4914         if (!sksec)
4915                 return -ENOMEM;
4916
4917         sksec->peer_sid = SECINITSID_UNLABELED;
4918         sksec->sid = SECINITSID_UNLABELED;
4919         sksec->sclass = SECCLASS_SOCKET;
4920         selinux_netlbl_sk_security_reset(sksec);
4921         sk->sk_security = sksec;
4922
4923         return 0;
4924 }
4925
4926 static void selinux_sk_free_security(struct sock *sk)
4927 {
4928         struct sk_security_struct *sksec = sk->sk_security;
4929
4930         sk->sk_security = NULL;
4931         selinux_netlbl_sk_security_free(sksec);
4932         kfree(sksec);
4933 }
4934
4935 static void selinux_sk_clone_security(const struct sock *sk, struct sock *newsk)
4936 {
4937         struct sk_security_struct *sksec = sk->sk_security;
4938         struct sk_security_struct *newsksec = newsk->sk_security;
4939
4940         newsksec->sid = sksec->sid;
4941         newsksec->peer_sid = sksec->peer_sid;
4942         newsksec->sclass = sksec->sclass;
4943
4944         selinux_netlbl_sk_security_reset(newsksec);
4945 }
4946
4947 static void selinux_sk_getsecid(struct sock *sk, u32 *secid)
4948 {
4949         if (!sk)
4950                 *secid = SECINITSID_ANY_SOCKET;
4951         else {
4952                 struct sk_security_struct *sksec = sk->sk_security;
4953
4954                 *secid = sksec->sid;
4955         }
4956 }
4957
4958 static void selinux_sock_graft(struct sock *sk, struct socket *parent)
4959 {
4960         struct inode_security_struct *isec =
4961                 inode_security_novalidate(SOCK_INODE(parent));
4962         struct sk_security_struct *sksec = sk->sk_security;
4963
4964         if (sk->sk_family == PF_INET || sk->sk_family == PF_INET6 ||
4965             sk->sk_family == PF_UNIX)
4966                 isec->sid = sksec->sid;
4967         sksec->sclass = isec->sclass;
4968 }
4969
4970 static int selinux_inet_conn_request(struct sock *sk, struct sk_buff *skb,
4971                                      struct request_sock *req)
4972 {
4973         struct sk_security_struct *sksec = sk->sk_security;
4974         int err;
4975         u16 family = req->rsk_ops->family;
4976         u32 connsid;
4977         u32 peersid;
4978
4979         err = selinux_skb_peerlbl_sid(skb, family, &peersid);
4980         if (err)
4981                 return err;
4982         err = selinux_conn_sid(sksec->sid, peersid, &connsid);
4983         if (err)
4984                 return err;
4985         req->secid = connsid;
4986         req->peer_secid = peersid;
4987
4988         return selinux_netlbl_inet_conn_request(req, family);
4989 }
4990
4991 static void selinux_inet_csk_clone(struct sock *newsk,
4992                                    const struct request_sock *req)
4993 {
4994         struct sk_security_struct *newsksec = newsk->sk_security;
4995
4996         newsksec->sid = req->secid;
4997         newsksec->peer_sid = req->peer_secid;
4998         /* NOTE: Ideally, we should also get the isec->sid for the
4999            new socket in sync, but we don't have the isec available yet.
5000            So we will wait until sock_graft to do it, by which
5001            time it will have been created and available. */
5002
5003         /* We don't need to take any sort of lock here as we are the only
5004          * thread with access to newsksec */
5005         selinux_netlbl_inet_csk_clone(newsk, req->rsk_ops->family);
5006 }
5007
5008 static void selinux_inet_conn_established(struct sock *sk, struct sk_buff *skb)
5009 {
5010         u16 family = sk->sk_family;
5011         struct sk_security_struct *sksec = sk->sk_security;
5012
5013         /* handle mapped IPv4 packets arriving via IPv6 sockets */
5014         if (family == PF_INET6 && skb->protocol == htons(ETH_P_IP))
5015                 family = PF_INET;
5016
5017         selinux_skb_peerlbl_sid(skb, family, &sksec->peer_sid);
5018 }
5019
5020 static int selinux_secmark_relabel_packet(u32 sid)
5021 {
5022         const struct task_security_struct *__tsec;
5023         u32 tsid;
5024
5025         __tsec = current_security();
5026         tsid = __tsec->sid;
5027
5028         return avc_has_perm(tsid, sid, SECCLASS_PACKET, PACKET__RELABELTO, NULL);
5029 }
5030
5031 static void selinux_secmark_refcount_inc(void)
5032 {
5033         atomic_inc(&selinux_secmark_refcount);
5034 }
5035
5036 static void selinux_secmark_refcount_dec(void)
5037 {
5038         atomic_dec(&selinux_secmark_refcount);
5039 }
5040
5041 static void selinux_req_classify_flow(const struct request_sock *req,
5042                                       struct flowi *fl)
5043 {
5044         fl->flowi_secid = req->secid;
5045 }
5046
5047 static int selinux_tun_dev_alloc_security(void **security)
5048 {
5049         struct tun_security_struct *tunsec;
5050
5051         tunsec = kzalloc(sizeof(*tunsec), GFP_KERNEL);
5052         if (!tunsec)
5053                 return -ENOMEM;
5054         tunsec->sid = current_sid();
5055
5056         *security = tunsec;
5057         return 0;
5058 }
5059
5060 static void selinux_tun_dev_free_security(void *security)
5061 {
5062         kfree(security);
5063 }
5064
5065 static int selinux_tun_dev_create(void)
5066 {
5067         u32 sid = current_sid();
5068
5069         /* we aren't taking into account the "sockcreate" SID since the socket
5070          * that is being created here is not a socket in the traditional sense,
5071          * instead it is a private sock, accessible only to the kernel, and
5072          * representing a wide range of network traffic spanning multiple
5073          * connections unlike traditional sockets - check the TUN driver to
5074          * get a better understanding of why this socket is special */
5075
5076         return avc_has_perm(sid, sid, SECCLASS_TUN_SOCKET, TUN_SOCKET__CREATE,
5077                             NULL);
5078 }
5079
5080 static int selinux_tun_dev_attach_queue(void *security)
5081 {
5082         struct tun_security_struct *tunsec = security;
5083
5084         return avc_has_perm(current_sid(), tunsec->sid, SECCLASS_TUN_SOCKET,
5085                             TUN_SOCKET__ATTACH_QUEUE, NULL);
5086 }
5087
5088 static int selinux_tun_dev_attach(struct sock *sk, void *security)
5089 {
5090         struct tun_security_struct *tunsec = security;
5091         struct sk_security_struct *sksec = sk->sk_security;
5092
5093         /* we don't currently perform any NetLabel based labeling here and it
5094          * isn't clear that we would want to do so anyway; while we could apply
5095          * labeling without the support of the TUN user the resulting labeled
5096          * traffic from the other end of the connection would almost certainly
5097          * cause confusion to the TUN user that had no idea network labeling
5098          * protocols were being used */
5099
5100         sksec->sid = tunsec->sid;
5101         sksec->sclass = SECCLASS_TUN_SOCKET;
5102
5103         return 0;
5104 }
5105
5106 static int selinux_tun_dev_open(void *security)
5107 {
5108         struct tun_security_struct *tunsec = security;
5109         u32 sid = current_sid();
5110         int err;
5111
5112         err = avc_has_perm(sid, tunsec->sid, SECCLASS_TUN_SOCKET,
5113                            TUN_SOCKET__RELABELFROM, NULL);
5114         if (err)
5115                 return err;
5116         err = avc_has_perm(sid, sid, SECCLASS_TUN_SOCKET,
5117                            TUN_SOCKET__RELABELTO, NULL);
5118         if (err)
5119                 return err;
5120         tunsec->sid = sid;
5121
5122         return 0;
5123 }
5124
5125 static int selinux_nlmsg_perm(struct sock *sk, struct sk_buff *skb)
5126 {
5127         int rc = 0;
5128         unsigned int msg_len;
5129         unsigned int data_len = skb->len;
5130         unsigned char *data = skb->data;
5131         struct nlmsghdr *nlh;
5132         struct sk_security_struct *sksec = sk->sk_security;
5133         u16 sclass = sksec->sclass;
5134         u32 perm;
5135
5136         while (data_len >= nlmsg_total_size(0)) {
5137                 nlh = (struct nlmsghdr *)data;
5138
5139                 /* NOTE: the nlmsg_len field isn't reliably set by some netlink
5140                  *       users which means we can't reject skb's with bogus
5141                  *       length fields; our solution is to follow what
5142                  *       netlink_rcv_skb() does and simply skip processing at
5143                  *       messages with length fields that are clearly junk
5144                  */
5145                 if (nlh->nlmsg_len < NLMSG_HDRLEN || nlh->nlmsg_len > data_len)
5146                         return 0;
5147
5148                 rc = selinux_nlmsg_lookup(sclass, nlh->nlmsg_type, &perm);
5149                 if (rc == 0) {
5150                         rc = sock_has_perm(sk, perm);
5151                         if (rc)
5152                                 return rc;
5153                 } else if (rc == -EINVAL) {
5154                         /* -EINVAL is a missing msg/perm mapping */
5155                         pr_warn_ratelimited("SELinux: unrecognized netlink"
5156                                 " message: protocol=%hu nlmsg_type=%hu sclass=%s"
5157                                 " pid=%d comm=%s\n",
5158                                 sk->sk_protocol, nlh->nlmsg_type,
5159                                 secclass_map[sclass - 1].name,
5160                                 task_pid_nr(current), current->comm);
5161                         if (selinux_enforcing && !security_get_allow_unknown())
5162                                 return rc;
5163                         rc = 0;
5164                 } else if (rc == -ENOENT) {
5165                         /* -ENOENT is a missing socket/class mapping, ignore */
5166                         rc = 0;
5167                 } else {
5168                         return rc;
5169                 }
5170
5171                 /* move to the next message after applying netlink padding */
5172                 msg_len = NLMSG_ALIGN(nlh->nlmsg_len);
5173                 if (msg_len >= data_len)
5174                         return 0;
5175                 data_len -= msg_len;
5176                 data += msg_len;
5177         }
5178
5179         return rc;
5180 }
5181
5182 #ifdef CONFIG_NETFILTER
5183
5184 static unsigned int selinux_ip_forward(struct sk_buff *skb,
5185                                        const struct net_device *indev,
5186                                        u16 family)
5187 {
5188         int err;
5189         char *addrp;
5190         u32 peer_sid;
5191         struct common_audit_data ad;
5192         struct lsm_network_audit net = {0,};
5193         u8 secmark_active;
5194         u8 netlbl_active;
5195         u8 peerlbl_active;
5196
5197         if (!selinux_policycap_netpeer)
5198                 return NF_ACCEPT;
5199
5200         secmark_active = selinux_secmark_enabled();
5201         netlbl_active = netlbl_enabled();
5202         peerlbl_active = selinux_peerlbl_enabled();
5203         if (!secmark_active && !peerlbl_active)
5204                 return NF_ACCEPT;
5205
5206         if (selinux_skb_peerlbl_sid(skb, family, &peer_sid) != 0)
5207                 return NF_DROP;
5208
5209         ad.type = LSM_AUDIT_DATA_NET;
5210         ad.u.net = &net;
5211         ad.u.net->netif = indev->ifindex;
5212         ad.u.net->family = family;
5213         if (selinux_parse_skb(skb, &ad, &addrp, 1, NULL) != 0)
5214                 return NF_DROP;
5215
5216         if (peerlbl_active) {
5217                 err = selinux_inet_sys_rcv_skb(dev_net(indev), indev->ifindex,
5218                                                addrp, family, peer_sid, &ad);
5219                 if (err) {
5220                         selinux_netlbl_err(skb, family, err, 1);
5221                         return NF_DROP;
5222                 }
5223         }
5224
5225         if (secmark_active)
5226                 if (avc_has_perm(peer_sid, skb->secmark,
5227                                  SECCLASS_PACKET, PACKET__FORWARD_IN, &ad))
5228                         return NF_DROP;
5229
5230         if (netlbl_active)
5231                 /* we do this in the FORWARD path and not the POST_ROUTING
5232                  * path because we want to make sure we apply the necessary
5233                  * labeling before IPsec is applied so we can leverage AH
5234                  * protection */
5235                 if (selinux_netlbl_skbuff_setsid(skb, family, peer_sid) != 0)
5236                         return NF_DROP;
5237
5238         return NF_ACCEPT;
5239 }
5240
5241 static unsigned int selinux_ipv4_forward(void *priv,
5242                                          struct sk_buff *skb,
5243                                          const struct nf_hook_state *state)
5244 {
5245         return selinux_ip_forward(skb, state->in, PF_INET);
5246 }
5247
5248 #if IS_ENABLED(CONFIG_IPV6)
5249 static unsigned int selinux_ipv6_forward(void *priv,
5250                                          struct sk_buff *skb,
5251                                          const struct nf_hook_state *state)
5252 {
5253         return selinux_ip_forward(skb, state->in, PF_INET6);
5254 }
5255 #endif  /* IPV6 */
5256
5257 static unsigned int selinux_ip_output(struct sk_buff *skb,
5258                                       u16 family)
5259 {
5260         struct sock *sk;
5261         u32 sid;
5262
5263         if (!netlbl_enabled())
5264                 return NF_ACCEPT;
5265
5266         /* we do this in the LOCAL_OUT path and not the POST_ROUTING path
5267          * because we want to make sure we apply the necessary labeling
5268          * before IPsec is applied so we can leverage AH protection */
5269         sk = skb->sk;
5270         if (sk) {
5271                 struct sk_security_struct *sksec;
5272
5273                 if (sk_listener(sk))
5274                         /* if the socket is the listening state then this
5275                          * packet is a SYN-ACK packet which means it needs to
5276                          * be labeled based on the connection/request_sock and
5277                          * not the parent socket.  unfortunately, we can't
5278                          * lookup the request_sock yet as it isn't queued on
5279                          * the parent socket until after the SYN-ACK is sent.
5280                          * the "solution" is to simply pass the packet as-is
5281                          * as any IP option based labeling should be copied
5282                          * from the initial connection request (in the IP
5283                          * layer).  it is far from ideal, but until we get a
5284                          * security label in the packet itself this is the
5285                          * best we can do. */
5286                         return NF_ACCEPT;
5287
5288                 /* standard practice, label using the parent socket */
5289                 sksec = sk->sk_security;
5290                 sid = sksec->sid;
5291         } else
5292                 sid = SECINITSID_KERNEL;
5293         if (selinux_netlbl_skbuff_setsid(skb, family, sid) != 0)
5294                 return NF_DROP;
5295
5296         return NF_ACCEPT;
5297 }
5298
5299 static unsigned int selinux_ipv4_output(void *priv,
5300                                         struct sk_buff *skb,
5301                                         const struct nf_hook_state *state)
5302 {
5303         return selinux_ip_output(skb, PF_INET);
5304 }
5305
5306 #if IS_ENABLED(CONFIG_IPV6)
5307 static unsigned int selinux_ipv6_output(void *priv,
5308                                         struct sk_buff *skb,
5309                                         const struct nf_hook_state *state)
5310 {
5311         return selinux_ip_output(skb, PF_INET6);
5312 }
5313 #endif  /* IPV6 */
5314
5315 static unsigned int selinux_ip_postroute_compat(struct sk_buff *skb,
5316                                                 int ifindex,
5317                                                 u16 family)
5318 {
5319         struct sock *sk = skb_to_full_sk(skb);
5320         struct sk_security_struct *sksec;
5321         struct common_audit_data ad;
5322         struct lsm_network_audit net = {0,};
5323         char *addrp;
5324         u8 proto = 0;
5325
5326         if (sk == NULL)
5327                 return NF_ACCEPT;
5328         sksec = sk->sk_security;
5329
5330         ad.type = LSM_AUDIT_DATA_NET;
5331         ad.u.net = &net;
5332         ad.u.net->netif = ifindex;
5333         ad.u.net->family = family;
5334         if (selinux_parse_skb(skb, &ad, &addrp, 0, &proto))
5335                 return NF_DROP;
5336
5337         if (selinux_secmark_enabled())
5338                 if (avc_has_perm(sksec->sid, skb->secmark,
5339                                  SECCLASS_PACKET, PACKET__SEND, &ad))
5340                         return NF_DROP_ERR(-ECONNREFUSED);
5341
5342         if (selinux_xfrm_postroute_last(sksec->sid, skb, &ad, proto))
5343                 return NF_DROP_ERR(-ECONNREFUSED);
5344
5345         return NF_ACCEPT;
5346 }
5347
5348 static unsigned int selinux_ip_postroute(struct sk_buff *skb,
5349                                          const struct net_device *outdev,
5350                                          u16 family)
5351 {
5352         u32 secmark_perm;
5353         u32 peer_sid;
5354         int ifindex = outdev->ifindex;
5355         struct sock *sk;
5356         struct common_audit_data ad;
5357         struct lsm_network_audit net = {0,};
5358         char *addrp;
5359         u8 secmark_active;
5360         u8 peerlbl_active;
5361
5362         /* If any sort of compatibility mode is enabled then handoff processing
5363          * to the selinux_ip_postroute_compat() function to deal with the
5364          * special handling.  We do this in an attempt to keep this function
5365          * as fast and as clean as possible. */
5366         if (!selinux_policycap_netpeer)
5367                 return selinux_ip_postroute_compat(skb, ifindex, family);
5368
5369         secmark_active = selinux_secmark_enabled();
5370         peerlbl_active = selinux_peerlbl_enabled();
5371         if (!secmark_active && !peerlbl_active)
5372                 return NF_ACCEPT;
5373
5374         sk = skb_to_full_sk(skb);
5375
5376 #ifdef CONFIG_XFRM
5377         /* If skb->dst->xfrm is non-NULL then the packet is undergoing an IPsec
5378          * packet transformation so allow the packet to pass without any checks
5379          * since we'll have another chance to perform access control checks
5380          * when the packet is on it's final way out.
5381          * NOTE: there appear to be some IPv6 multicast cases where skb->dst
5382          *       is NULL, in this case go ahead and apply access control.
5383          * NOTE: if this is a local socket (skb->sk != NULL) that is in the
5384          *       TCP listening state we cannot wait until the XFRM processing
5385          *       is done as we will miss out on the SA label if we do;
5386          *       unfortunately, this means more work, but it is only once per
5387          *       connection. */
5388         if (skb_dst(skb) != NULL && skb_dst(skb)->xfrm != NULL &&
5389             !(sk && sk_listener(sk)))
5390                 return NF_ACCEPT;
5391 #endif
5392
5393         if (sk == NULL) {
5394                 /* Without an associated socket the packet is either coming
5395                  * from the kernel or it is being forwarded; check the packet
5396                  * to determine which and if the packet is being forwarded
5397                  * query the packet directly to determine the security label. */
5398                 if (skb->skb_iif) {
5399                         secmark_perm = PACKET__FORWARD_OUT;
5400                         if (selinux_skb_peerlbl_sid(skb, family, &peer_sid))
5401                                 return NF_DROP;
5402                 } else {
5403                         secmark_perm = PACKET__SEND;
5404                         peer_sid = SECINITSID_KERNEL;
5405                 }
5406         } else if (sk_listener(sk)) {
5407                 /* Locally generated packet but the associated socket is in the
5408                  * listening state which means this is a SYN-ACK packet.  In
5409                  * this particular case the correct security label is assigned
5410                  * to the connection/request_sock but unfortunately we can't
5411                  * query the request_sock as it isn't queued on the parent
5412                  * socket until after the SYN-ACK packet is sent; the only
5413                  * viable choice is to regenerate the label like we do in
5414                  * selinux_inet_conn_request().  See also selinux_ip_output()
5415                  * for similar problems. */
5416                 u32 skb_sid;
5417                 struct sk_security_struct *sksec;
5418
5419                 sksec = sk->sk_security;
5420                 if (selinux_skb_peerlbl_sid(skb, family, &skb_sid))
5421                         return NF_DROP;
5422                 /* At this point, if the returned skb peerlbl is SECSID_NULL
5423                  * and the packet has been through at least one XFRM
5424                  * transformation then we must be dealing with the "final"
5425                  * form of labeled IPsec packet; since we've already applied
5426                  * all of our access controls on this packet we can safely
5427                  * pass the packet. */
5428                 if (skb_sid == SECSID_NULL) {
5429                         switch (family) {
5430                         case PF_INET:
5431                                 if (IPCB(skb)->flags & IPSKB_XFRM_TRANSFORMED)
5432                                         return NF_ACCEPT;
5433                                 break;
5434                         case PF_INET6:
5435                                 if (IP6CB(skb)->flags & IP6SKB_XFRM_TRANSFORMED)
5436                                         return NF_ACCEPT;
5437                                 break;
5438                         default:
5439                                 return NF_DROP_ERR(-ECONNREFUSED);
5440                         }
5441                 }
5442                 if (selinux_conn_sid(sksec->sid, skb_sid, &peer_sid))
5443                         return NF_DROP;
5444                 secmark_perm = PACKET__SEND;
5445         } else {
5446                 /* Locally generated packet, fetch the security label from the
5447                  * associated socket. */
5448                 struct sk_security_struct *sksec = sk->sk_security;
5449                 peer_sid = sksec->sid;
5450                 secmark_perm = PACKET__SEND;
5451         }
5452
5453         ad.type = LSM_AUDIT_DATA_NET;
5454         ad.u.net = &net;
5455         ad.u.net->netif = ifindex;
5456         ad.u.net->family = family;
5457         if (selinux_parse_skb(skb, &ad, &addrp, 0, NULL))
5458                 return NF_DROP;
5459
5460         if (secmark_active)
5461                 if (avc_has_perm(peer_sid, skb->secmark,
5462                                  SECCLASS_PACKET, secmark_perm, &ad))
5463                         return NF_DROP_ERR(-ECONNREFUSED);
5464
5465         if (peerlbl_active) {
5466                 u32 if_sid;
5467                 u32 node_sid;
5468
5469                 if (sel_netif_sid(dev_net(outdev), ifindex, &if_sid))
5470                         return NF_DROP;
5471                 if (avc_has_perm(peer_sid, if_sid,
5472                                  SECCLASS_NETIF, NETIF__EGRESS, &ad))
5473                         return NF_DROP_ERR(-ECONNREFUSED);
5474
5475                 if (sel_netnode_sid(addrp, family, &node_sid))
5476                         return NF_DROP;
5477                 if (avc_has_perm(peer_sid, node_sid,
5478                                  SECCLASS_NODE, NODE__SENDTO, &ad))
5479                         return NF_DROP_ERR(-ECONNREFUSED);
5480         }
5481
5482         return NF_ACCEPT;
5483 }
5484
5485 static unsigned int selinux_ipv4_postroute(void *priv,
5486                                            struct sk_buff *skb,
5487                                            const struct nf_hook_state *state)
5488 {
5489         return selinux_ip_postroute(skb, state->out, PF_INET);
5490 }
5491
5492 #if IS_ENABLED(CONFIG_IPV6)
5493 static unsigned int selinux_ipv6_postroute(void *priv,
5494                                            struct sk_buff *skb,
5495                                            const struct nf_hook_state *state)
5496 {
5497         return selinux_ip_postroute(skb, state->out, PF_INET6);
5498 }
5499 #endif  /* IPV6 */
5500
5501 #endif  /* CONFIG_NETFILTER */
5502
5503 static int selinux_netlink_send(struct sock *sk, struct sk_buff *skb)
5504 {
5505         return selinux_nlmsg_perm(sk, skb);
5506 }
5507
5508 static int ipc_alloc_security(struct kern_ipc_perm *perm,
5509                               u16 sclass)
5510 {
5511         struct ipc_security_struct *isec;
5512
5513         isec = kzalloc(sizeof(struct ipc_security_struct), GFP_KERNEL);
5514         if (!isec)
5515                 return -ENOMEM;
5516
5517         isec->sclass = sclass;
5518         isec->sid = current_sid();
5519         perm->security = isec;
5520
5521         return 0;
5522 }
5523
5524 static void ipc_free_security(struct kern_ipc_perm *perm)
5525 {
5526         struct ipc_security_struct *isec = perm->security;
5527         perm->security = NULL;
5528         kfree(isec);
5529 }
5530
5531 static int msg_msg_alloc_security(struct msg_msg *msg)
5532 {
5533         struct msg_security_struct *msec;
5534
5535         msec = kzalloc(sizeof(struct msg_security_struct), GFP_KERNEL);
5536         if (!msec)
5537                 return -ENOMEM;
5538
5539         msec->sid = SECINITSID_UNLABELED;
5540         msg->security = msec;
5541
5542         return 0;
5543 }
5544
5545 static void msg_msg_free_security(struct msg_msg *msg)
5546 {
5547         struct msg_security_struct *msec = msg->security;
5548
5549         msg->security = NULL;
5550         kfree(msec);
5551 }
5552
5553 static int ipc_has_perm(struct kern_ipc_perm *ipc_perms,
5554                         u32 perms)
5555 {
5556         struct ipc_security_struct *isec;
5557         struct common_audit_data ad;
5558         u32 sid = current_sid();
5559
5560         isec = ipc_perms->security;
5561
5562         ad.type = LSM_AUDIT_DATA_IPC;
5563         ad.u.ipc_id = ipc_perms->key;
5564
5565         return avc_has_perm(sid, isec->sid, isec->sclass, perms, &ad);
5566 }
5567
5568 static int selinux_msg_msg_alloc_security(struct msg_msg *msg)
5569 {
5570         return msg_msg_alloc_security(msg);
5571 }
5572
5573 static void selinux_msg_msg_free_security(struct msg_msg *msg)
5574 {
5575         msg_msg_free_security(msg);
5576 }
5577
5578 /* message queue security operations */
5579 static int selinux_msg_queue_alloc_security(struct msg_queue *msq)
5580 {
5581         struct ipc_security_struct *isec;
5582         struct common_audit_data ad;
5583         u32 sid = current_sid();
5584         int rc;
5585
5586         rc = ipc_alloc_security(&msq->q_perm, SECCLASS_MSGQ);
5587         if (rc)
5588                 return rc;
5589
5590         isec = msq->q_perm.security;
5591
5592         ad.type = LSM_AUDIT_DATA_IPC;
5593         ad.u.ipc_id = msq->q_perm.key;
5594
5595         rc = avc_has_perm(sid, isec->sid, SECCLASS_MSGQ,
5596                           MSGQ__CREATE, &ad);
5597         if (rc) {
5598                 ipc_free_security(&msq->q_perm);
5599                 return rc;
5600         }
5601         return 0;
5602 }
5603
5604 static void selinux_msg_queue_free_security(struct msg_queue *msq)
5605 {
5606         ipc_free_security(&msq->q_perm);
5607 }
5608
5609 static int selinux_msg_queue_associate(struct msg_queue *msq, int msqflg)
5610 {
5611         struct ipc_security_struct *isec;
5612         struct common_audit_data ad;
5613         u32 sid = current_sid();
5614
5615         isec = msq->q_perm.security;
5616
5617         ad.type = LSM_AUDIT_DATA_IPC;
5618         ad.u.ipc_id = msq->q_perm.key;
5619
5620         return avc_has_perm(sid, isec->sid, SECCLASS_MSGQ,
5621                             MSGQ__ASSOCIATE, &ad);
5622 }
5623
5624 static int selinux_msg_queue_msgctl(struct msg_queue *msq, int cmd)
5625 {
5626         int err;
5627         int perms;
5628
5629         switch (cmd) {
5630         case IPC_INFO:
5631         case MSG_INFO:
5632                 /* No specific object, just general system-wide information. */
5633                 return avc_has_perm(current_sid(), SECINITSID_KERNEL,
5634                                     SECCLASS_SYSTEM, SYSTEM__IPC_INFO, NULL);
5635         case IPC_STAT:
5636         case MSG_STAT:
5637                 perms = MSGQ__GETATTR | MSGQ__ASSOCIATE;
5638                 break;
5639         case IPC_SET:
5640                 perms = MSGQ__SETATTR;
5641                 break;
5642         case IPC_RMID:
5643                 perms = MSGQ__DESTROY;
5644                 break;
5645         default:
5646                 return 0;
5647         }
5648
5649         err = ipc_has_perm(&msq->q_perm, perms);
5650         return err;
5651 }
5652
5653 static int selinux_msg_queue_msgsnd(struct msg_queue *msq, struct msg_msg *msg, int msqflg)
5654 {
5655         struct ipc_security_struct *isec;
5656         struct msg_security_struct *msec;
5657         struct common_audit_data ad;
5658         u32 sid = current_sid();
5659         int rc;
5660
5661         isec = msq->q_perm.security;
5662         msec = msg->security;
5663
5664         /*
5665          * First time through, need to assign label to the message
5666          */
5667         if (msec->sid == SECINITSID_UNLABELED) {
5668                 /*
5669                  * Compute new sid based on current process and
5670                  * message queue this message will be stored in
5671                  */
5672                 rc = security_transition_sid(sid, isec->sid, SECCLASS_MSG,
5673                                              NULL, &msec->sid);
5674                 if (rc)
5675                         return rc;
5676         }
5677
5678         ad.type = LSM_AUDIT_DATA_IPC;
5679         ad.u.ipc_id = msq->q_perm.key;
5680
5681         /* Can this process write to the queue? */
5682         rc = avc_has_perm(sid, isec->sid, SECCLASS_MSGQ,
5683                           MSGQ__WRITE, &ad);
5684         if (!rc)
5685                 /* Can this process send the message */
5686                 rc = avc_has_perm(sid, msec->sid, SECCLASS_MSG,
5687                                   MSG__SEND, &ad);
5688         if (!rc)
5689                 /* Can the message be put in the queue? */
5690                 rc = avc_has_perm(msec->sid, isec->sid, SECCLASS_MSGQ,
5691                                   MSGQ__ENQUEUE, &ad);
5692
5693         return rc;
5694 }
5695
5696 static int selinux_msg_queue_msgrcv(struct msg_queue *msq, struct msg_msg *msg,
5697                                     struct task_struct *target,
5698                                     long type, int mode)
5699 {
5700         struct ipc_security_struct *isec;
5701         struct msg_security_struct *msec;
5702         struct common_audit_data ad;
5703         u32 sid = task_sid(target);
5704         int rc;
5705
5706         isec = msq->q_perm.security;
5707         msec = msg->security;
5708
5709         ad.type = LSM_AUDIT_DATA_IPC;
5710         ad.u.ipc_id = msq->q_perm.key;
5711
5712         rc = avc_has_perm(sid, isec->sid,
5713                           SECCLASS_MSGQ, MSGQ__READ, &ad);
5714         if (!rc)
5715                 rc = avc_has_perm(sid, msec->sid,
5716                                   SECCLASS_MSG, MSG__RECEIVE, &ad);
5717         return rc;
5718 }
5719
5720 /* Shared Memory security operations */
5721 static int selinux_shm_alloc_security(struct shmid_kernel *shp)
5722 {
5723         struct ipc_security_struct *isec;
5724         struct common_audit_data ad;
5725         u32 sid = current_sid();
5726         int rc;
5727
5728         rc = ipc_alloc_security(&shp->shm_perm, SECCLASS_SHM);
5729         if (rc)
5730                 return rc;
5731
5732         isec = shp->shm_perm.security;
5733
5734         ad.type = LSM_AUDIT_DATA_IPC;
5735         ad.u.ipc_id = shp->shm_perm.key;
5736
5737         rc = avc_has_perm(sid, isec->sid, SECCLASS_SHM,
5738                           SHM__CREATE, &ad);
5739         if (rc) {
5740                 ipc_free_security(&shp->shm_perm);
5741                 return rc;
5742         }
5743         return 0;
5744 }
5745
5746 static void selinux_shm_free_security(struct shmid_kernel *shp)
5747 {
5748         ipc_free_security(&shp->shm_perm);
5749 }
5750
5751 static int selinux_shm_associate(struct shmid_kernel *shp, int shmflg)
5752 {
5753         struct ipc_security_struct *isec;
5754         struct common_audit_data ad;
5755         u32 sid = current_sid();
5756
5757         isec = shp->shm_perm.security;
5758
5759         ad.type = LSM_AUDIT_DATA_IPC;
5760         ad.u.ipc_id = shp->shm_perm.key;
5761
5762         return avc_has_perm(sid, isec->sid, SECCLASS_SHM,
5763                             SHM__ASSOCIATE, &ad);
5764 }
5765
5766 /* Note, at this point, shp is locked down */
5767 static int selinux_shm_shmctl(struct shmid_kernel *shp, int cmd)
5768 {
5769         int perms;
5770         int err;
5771
5772         switch (cmd) {
5773         case IPC_INFO:
5774         case SHM_INFO:
5775                 /* No specific object, just general system-wide information. */
5776                 return avc_has_perm(current_sid(), SECINITSID_KERNEL,
5777                                     SECCLASS_SYSTEM, SYSTEM__IPC_INFO, NULL);
5778         case IPC_STAT:
5779         case SHM_STAT:
5780                 perms = SHM__GETATTR | SHM__ASSOCIATE;
5781                 break;
5782         case IPC_SET:
5783                 perms = SHM__SETATTR;
5784                 break;
5785         case SHM_LOCK:
5786         case SHM_UNLOCK:
5787                 perms = SHM__LOCK;
5788                 break;
5789         case IPC_RMID:
5790                 perms = SHM__DESTROY;
5791                 break;
5792         default:
5793                 return 0;
5794         }
5795
5796         err = ipc_has_perm(&shp->shm_perm, perms);
5797         return err;
5798 }
5799
5800 static int selinux_shm_shmat(struct shmid_kernel *shp,
5801                              char __user *shmaddr, int shmflg)
5802 {
5803         u32 perms;
5804
5805         if (shmflg & SHM_RDONLY)
5806                 perms = SHM__READ;
5807         else
5808                 perms = SHM__READ | SHM__WRITE;
5809
5810         return ipc_has_perm(&shp->shm_perm, perms);
5811 }
5812
5813 /* Semaphore security operations */
5814 static int selinux_sem_alloc_security(struct sem_array *sma)
5815 {
5816         struct ipc_security_struct *isec;
5817         struct common_audit_data ad;
5818         u32 sid = current_sid();
5819         int rc;
5820
5821         rc = ipc_alloc_security(&sma->sem_perm, SECCLASS_SEM);
5822         if (rc)
5823                 return rc;
5824
5825         isec = sma->sem_perm.security;
5826
5827         ad.type = LSM_AUDIT_DATA_IPC;
5828         ad.u.ipc_id = sma->sem_perm.key;
5829
5830         rc = avc_has_perm(sid, isec->sid, SECCLASS_SEM,
5831                           SEM__CREATE, &ad);
5832         if (rc) {
5833                 ipc_free_security(&sma->sem_perm);
5834                 return rc;
5835         }
5836         return 0;
5837 }
5838
5839 static void selinux_sem_free_security(struct sem_array *sma)
5840 {
5841         ipc_free_security(&sma->sem_perm);
5842 }
5843
5844 static int selinux_sem_associate(struct sem_array *sma, int semflg)
5845 {
5846         struct ipc_security_struct *isec;
5847         struct common_audit_data ad;
5848         u32 sid = current_sid();
5849
5850         isec = sma->sem_perm.security;
5851
5852         ad.type = LSM_AUDIT_DATA_IPC;
5853         ad.u.ipc_id = sma->sem_perm.key;
5854
5855         return avc_has_perm(sid, isec->sid, SECCLASS_SEM,
5856                             SEM__ASSOCIATE, &ad);
5857 }
5858
5859 /* Note, at this point, sma is locked down */
5860 static int selinux_sem_semctl(struct sem_array *sma, int cmd)
5861 {
5862         int err;
5863         u32 perms;
5864
5865         switch (cmd) {
5866         case IPC_INFO:
5867         case SEM_INFO:
5868                 /* No specific object, just general system-wide information. */
5869                 return avc_has_perm(current_sid(), SECINITSID_KERNEL,
5870                                     SECCLASS_SYSTEM, SYSTEM__IPC_INFO, NULL);
5871         case GETPID:
5872         case GETNCNT:
5873         case GETZCNT:
5874                 perms = SEM__GETATTR;
5875                 break;
5876         case GETVAL:
5877         case GETALL:
5878                 perms = SEM__READ;
5879                 break;
5880         case SETVAL:
5881         case SETALL:
5882                 perms = SEM__WRITE;
5883                 break;
5884         case IPC_RMID:
5885                 perms = SEM__DESTROY;
5886                 break;
5887         case IPC_SET:
5888                 perms = SEM__SETATTR;
5889                 break;
5890         case IPC_STAT:
5891         case SEM_STAT:
5892                 perms = SEM__GETATTR | SEM__ASSOCIATE;
5893                 break;
5894         default:
5895                 return 0;
5896         }
5897
5898         err = ipc_has_perm(&sma->sem_perm, perms);
5899         return err;
5900 }
5901
5902 static int selinux_sem_semop(struct sem_array *sma,
5903                              struct sembuf *sops, unsigned nsops, int alter)
5904 {
5905         u32 perms;
5906
5907         if (alter)
5908                 perms = SEM__READ | SEM__WRITE;
5909         else
5910                 perms = SEM__READ;
5911
5912         return ipc_has_perm(&sma->sem_perm, perms);
5913 }
5914
5915 static int selinux_ipc_permission(struct kern_ipc_perm *ipcp, short flag)
5916 {
5917         u32 av = 0;
5918
5919         av = 0;
5920         if (flag & S_IRUGO)
5921                 av |= IPC__UNIX_READ;
5922         if (flag & S_IWUGO)
5923                 av |= IPC__UNIX_WRITE;
5924
5925         if (av == 0)
5926                 return 0;
5927
5928         return ipc_has_perm(ipcp, av);
5929 }
5930
5931 static void selinux_ipc_getsecid(struct kern_ipc_perm *ipcp, u32 *secid)
5932 {
5933         struct ipc_security_struct *isec = ipcp->security;
5934         *secid = isec->sid;
5935 }
5936
5937 static void selinux_d_instantiate(struct dentry *dentry, struct inode *inode)
5938 {
5939         if (inode)
5940                 inode_doinit_with_dentry(inode, dentry);
5941 }
5942
5943 static int selinux_getprocattr(struct task_struct *p,
5944                                char *name, char **value)
5945 {
5946         const struct task_security_struct *__tsec;
5947         u32 sid;
5948         int error;
5949         unsigned len;
5950
5951         rcu_read_lock();
5952         __tsec = __task_cred(p)->security;
5953
5954         if (current != p) {
5955                 error = avc_has_perm(current_sid(), __tsec->sid,
5956                                      SECCLASS_PROCESS, PROCESS__GETATTR, NULL);
5957                 if (error)
5958                         goto bad;
5959         }
5960
5961         if (!strcmp(name, "current"))
5962                 sid = __tsec->sid;
5963         else if (!strcmp(name, "prev"))
5964                 sid = __tsec->osid;
5965         else if (!strcmp(name, "exec"))
5966                 sid = __tsec->exec_sid;
5967         else if (!strcmp(name, "fscreate"))
5968                 sid = __tsec->create_sid;
5969         else if (!strcmp(name, "keycreate"))
5970                 sid = __tsec->keycreate_sid;
5971         else if (!strcmp(name, "sockcreate"))
5972                 sid = __tsec->sockcreate_sid;
5973         else {
5974                 error = -EINVAL;
5975                 goto bad;
5976         }
5977         rcu_read_unlock();
5978
5979         if (!sid)
5980                 return 0;
5981
5982         error = security_sid_to_context(sid, value, &len);
5983         if (error)
5984                 return error;
5985         return len;
5986
5987 bad:
5988         rcu_read_unlock();
5989         return error;
5990 }
5991
5992 static int selinux_setprocattr(const char *name, void *value, size_t size)
5993 {
5994         struct task_security_struct *tsec;
5995         struct cred *new;
5996         u32 mysid = current_sid(), sid = 0, ptsid;
5997         int error;
5998         char *str = value;
5999
6000         /*
6001          * Basic control over ability to set these attributes at all.
6002          */
6003         if (!strcmp(name, "exec"))
6004                 error = avc_has_perm(mysid, mysid, SECCLASS_PROCESS,
6005                                      PROCESS__SETEXEC, NULL);
6006         else if (!strcmp(name, "fscreate"))
6007                 error = avc_has_perm(mysid, mysid, SECCLASS_PROCESS,
6008                                      PROCESS__SETFSCREATE, NULL);
6009         else if (!strcmp(name, "keycreate"))
6010                 error = avc_has_perm(mysid, mysid, SECCLASS_PROCESS,
6011                                      PROCESS__SETKEYCREATE, NULL);
6012         else if (!strcmp(name, "sockcreate"))
6013                 error = avc_has_perm(mysid, mysid, SECCLASS_PROCESS,
6014                                      PROCESS__SETSOCKCREATE, NULL);
6015         else if (!strcmp(name, "current"))
6016                 error = avc_has_perm(mysid, mysid, SECCLASS_PROCESS,
6017                                      PROCESS__SETCURRENT, NULL);
6018         else
6019                 error = -EINVAL;
6020         if (error)
6021                 return error;
6022
6023         /* Obtain a SID for the context, if one was specified. */
6024         if (size && str[0] && str[0] != '\n') {
6025                 if (str[size-1] == '\n') {
6026                         str[size-1] = 0;
6027                         size--;
6028                 }
6029                 error = security_context_to_sid(value, size, &sid, GFP_KERNEL);
6030                 if (error == -EINVAL && !strcmp(name, "fscreate")) {
6031                         if (!has_cap_mac_admin(true)) {
6032                                 struct audit_buffer *ab;
6033                                 size_t audit_size;
6034
6035                                 /* We strip a nul only if it is at the end, otherwise the
6036                                  * context contains a nul and we should audit that */
6037                                 if (str[size - 1] == '\0')
6038                                         audit_size = size - 1;
6039                                 else
6040                                         audit_size = size;
6041                                 ab = audit_log_start(current->audit_context, GFP_ATOMIC, AUDIT_SELINUX_ERR);
6042                                 audit_log_format(ab, "op=fscreate invalid_context=");
6043                                 audit_log_n_untrustedstring(ab, value, audit_size);
6044                                 audit_log_end(ab);
6045
6046                                 return error;
6047                         }
6048                         error = security_context_to_sid_force(value, size,
6049                                                               &sid);
6050                 }
6051                 if (error)
6052                         return error;
6053         }
6054
6055         new = prepare_creds();
6056         if (!new)
6057                 return -ENOMEM;
6058
6059         /* Permission checking based on the specified context is
6060            performed during the actual operation (execve,
6061            open/mkdir/...), when we know the full context of the
6062            operation.  See selinux_bprm_set_creds for the execve
6063            checks and may_create for the file creation checks. The
6064            operation will then fail if the context is not permitted. */
6065         tsec = new->security;
6066         if (!strcmp(name, "exec")) {
6067                 tsec->exec_sid = sid;
6068         } else if (!strcmp(name, "fscreate")) {
6069                 tsec->create_sid = sid;
6070         } else if (!strcmp(name, "keycreate")) {
6071                 error = avc_has_perm(mysid, sid, SECCLASS_KEY, KEY__CREATE,
6072                                      NULL);
6073                 if (error)
6074                         goto abort_change;
6075                 tsec->keycreate_sid = sid;
6076         } else if (!strcmp(name, "sockcreate")) {
6077                 tsec->sockcreate_sid = sid;
6078         } else if (!strcmp(name, "current")) {
6079                 error = -EINVAL;
6080                 if (sid == 0)
6081                         goto abort_change;
6082
6083                 /* Only allow single threaded processes to change context */
6084                 error = -EPERM;
6085                 if (!current_is_single_threaded()) {
6086                         error = security_bounded_transition(tsec->sid, sid);
6087                         if (error)
6088                                 goto abort_change;
6089                 }
6090
6091                 /* Check permissions for the transition. */
6092                 error = avc_has_perm(tsec->sid, sid, SECCLASS_PROCESS,
6093                                      PROCESS__DYNTRANSITION, NULL);
6094                 if (error)
6095                         goto abort_change;
6096
6097                 /* Check for ptracing, and update the task SID if ok.
6098                    Otherwise, leave SID unchanged and fail. */
6099                 ptsid = ptrace_parent_sid();
6100                 if (ptsid != 0) {
6101                         error = avc_has_perm(ptsid, sid, SECCLASS_PROCESS,
6102                                              PROCESS__PTRACE, NULL);
6103                         if (error)
6104                                 goto abort_change;
6105                 }
6106
6107                 tsec->sid = sid;
6108         } else {
6109                 error = -EINVAL;
6110                 goto abort_change;
6111         }
6112
6113         commit_creds(new);
6114         return size;
6115
6116 abort_change:
6117         abort_creds(new);
6118         return error;
6119 }
6120
6121 static int selinux_ismaclabel(const char *name)
6122 {
6123         return (strcmp(name, XATTR_SELINUX_SUFFIX) == 0);
6124 }
6125
6126 static int selinux_secid_to_secctx(u32 secid, char **secdata, u32 *seclen)
6127 {
6128         return security_sid_to_context(secid, secdata, seclen);
6129 }
6130
6131 static int selinux_secctx_to_secid(const char *secdata, u32 seclen, u32 *secid)
6132 {
6133         return security_context_to_sid(secdata, seclen, secid, GFP_KERNEL);
6134 }
6135
6136 static void selinux_release_secctx(char *secdata, u32 seclen)
6137 {
6138         kfree(secdata);
6139 }
6140
6141 static void selinux_inode_invalidate_secctx(struct inode *inode)
6142 {
6143         struct inode_security_struct *isec = inode->i_security;
6144
6145         spin_lock(&isec->lock);
6146         isec->initialized = LABEL_INVALID;
6147         spin_unlock(&isec->lock);
6148 }
6149
6150 /*
6151  *      called with inode->i_mutex locked
6152  */
6153 static int selinux_inode_notifysecctx(struct inode *inode, void *ctx, u32 ctxlen)
6154 {
6155         int rc = selinux_inode_setsecurity(inode, XATTR_SELINUX_SUFFIX,
6156                                            ctx, ctxlen, 0);
6157         /* Do not return error when suppressing label (SBLABEL_MNT not set). */
6158         return rc == -EOPNOTSUPP ? 0 : rc;
6159 }
6160
6161 /*
6162  *      called with inode->i_mutex locked
6163  */
6164 static int selinux_inode_setsecctx(struct dentry *dentry, void *ctx, u32 ctxlen)
6165 {
6166         return __vfs_setxattr_noperm(dentry, XATTR_NAME_SELINUX, ctx, ctxlen, 0);
6167 }
6168
6169 static int selinux_inode_getsecctx(struct inode *inode, void **ctx, u32 *ctxlen)
6170 {
6171         int len = 0;
6172         len = selinux_inode_getsecurity(inode, XATTR_SELINUX_SUFFIX,
6173                                                 ctx, true);
6174         if (len < 0)
6175                 return len;
6176         *ctxlen = len;
6177         return 0;
6178 }
6179 #ifdef CONFIG_KEYS
6180
6181 static int selinux_key_alloc(struct key *k, const struct cred *cred,
6182                              unsigned long flags)
6183 {
6184         const struct task_security_struct *tsec;
6185         struct key_security_struct *ksec;
6186
6187         ksec = kzalloc(sizeof(struct key_security_struct), GFP_KERNEL);
6188         if (!ksec)
6189                 return -ENOMEM;
6190
6191         tsec = cred->security;
6192         if (tsec->keycreate_sid)
6193                 ksec->sid = tsec->keycreate_sid;
6194         else
6195                 ksec->sid = tsec->sid;
6196
6197         k->security = ksec;
6198         return 0;
6199 }
6200
6201 static void selinux_key_free(struct key *k)
6202 {
6203         struct key_security_struct *ksec = k->security;
6204
6205         k->security = NULL;
6206         kfree(ksec);
6207 }
6208
6209 static int selinux_key_permission(key_ref_t key_ref,
6210                                   const struct cred *cred,
6211                                   unsigned perm)
6212 {
6213         struct key *key;
6214         struct key_security_struct *ksec;
6215         u32 sid;
6216
6217         /* if no specific permissions are requested, we skip the
6218            permission check. No serious, additional covert channels
6219            appear to be created. */
6220         if (perm == 0)
6221                 return 0;
6222
6223         sid = cred_sid(cred);
6224
6225         key = key_ref_to_ptr(key_ref);
6226         ksec = key->security;
6227
6228         return avc_has_perm(sid, ksec->sid, SECCLASS_KEY, perm, NULL);
6229 }
6230
6231 static int selinux_key_getsecurity(struct key *key, char **_buffer)
6232 {
6233         struct key_security_struct *ksec = key->security;
6234         char *context = NULL;
6235         unsigned len;
6236         int rc;
6237
6238         rc = security_sid_to_context(ksec->sid, &context, &len);
6239         if (!rc)
6240                 rc = len;
6241         *_buffer = context;
6242         return rc;
6243 }
6244 #endif
6245
6246 #ifdef CONFIG_SECURITY_INFINIBAND
6247 static int selinux_ib_pkey_access(void *ib_sec, u64 subnet_prefix, u16 pkey_val)
6248 {
6249         struct common_audit_data ad;
6250         int err;
6251         u32 sid = 0;
6252         struct ib_security_struct *sec = ib_sec;
6253         struct lsm_ibpkey_audit ibpkey;
6254
6255         err = sel_ib_pkey_sid(subnet_prefix, pkey_val, &sid);
6256         if (err)
6257                 return err;
6258
6259         ad.type = LSM_AUDIT_DATA_IBPKEY;
6260         ibpkey.subnet_prefix = subnet_prefix;
6261         ibpkey.pkey = pkey_val;
6262         ad.u.ibpkey = &ibpkey;
6263         return avc_has_perm(sec->sid, sid,
6264                             SECCLASS_INFINIBAND_PKEY,
6265                             INFINIBAND_PKEY__ACCESS, &ad);
6266 }
6267
6268 static int selinux_ib_endport_manage_subnet(void *ib_sec, const char *dev_name,
6269                                             u8 port_num)
6270 {
6271         struct common_audit_data ad;
6272         int err;
6273         u32 sid = 0;
6274         struct ib_security_struct *sec = ib_sec;
6275         struct lsm_ibendport_audit ibendport;
6276
6277         err = security_ib_endport_sid(dev_name, port_num, &sid);
6278
6279         if (err)
6280                 return err;
6281
6282         ad.type = LSM_AUDIT_DATA_IBENDPORT;
6283         strncpy(ibendport.dev_name, dev_name, sizeof(ibendport.dev_name));
6284         ibendport.port = port_num;
6285         ad.u.ibendport = &ibendport;
6286         return avc_has_perm(sec->sid, sid,
6287                             SECCLASS_INFINIBAND_ENDPORT,
6288                             INFINIBAND_ENDPORT__MANAGE_SUBNET, &ad);
6289 }
6290
6291 static int selinux_ib_alloc_security(void **ib_sec)
6292 {
6293         struct ib_security_struct *sec;
6294
6295         sec = kzalloc(sizeof(*sec), GFP_KERNEL);
6296         if (!sec)
6297                 return -ENOMEM;
6298         sec->sid = current_sid();
6299
6300         *ib_sec = sec;
6301         return 0;
6302 }
6303
6304 static void selinux_ib_free_security(void *ib_sec)
6305 {
6306         kfree(ib_sec);
6307 }
6308 #endif
6309
6310 static struct security_hook_list selinux_hooks[] __lsm_ro_after_init = {
6311         LSM_HOOK_INIT(binder_set_context_mgr, selinux_binder_set_context_mgr),
6312         LSM_HOOK_INIT(binder_transaction, selinux_binder_transaction),
6313         LSM_HOOK_INIT(binder_transfer_binder, selinux_binder_transfer_binder),
6314         LSM_HOOK_INIT(binder_transfer_file, selinux_binder_transfer_file),
6315
6316         LSM_HOOK_INIT(ptrace_access_check, selinux_ptrace_access_check),
6317         LSM_HOOK_INIT(ptrace_traceme, selinux_ptrace_traceme),
6318         LSM_HOOK_INIT(capget, selinux_capget),
6319         LSM_HOOK_INIT(capset, selinux_capset),
6320         LSM_HOOK_INIT(capable, selinux_capable),
6321         LSM_HOOK_INIT(quotactl, selinux_quotactl),
6322         LSM_HOOK_INIT(quota_on, selinux_quota_on),
6323         LSM_HOOK_INIT(syslog, selinux_syslog),
6324         LSM_HOOK_INIT(vm_enough_memory, selinux_vm_enough_memory),
6325
6326         LSM_HOOK_INIT(netlink_send, selinux_netlink_send),
6327
6328         LSM_HOOK_INIT(bprm_set_creds, selinux_bprm_set_creds),
6329         LSM_HOOK_INIT(bprm_committing_creds, selinux_bprm_committing_creds),
6330         LSM_HOOK_INIT(bprm_committed_creds, selinux_bprm_committed_creds),
6331
6332         LSM_HOOK_INIT(sb_alloc_security, selinux_sb_alloc_security),
6333         LSM_HOOK_INIT(sb_free_security, selinux_sb_free_security),
6334         LSM_HOOK_INIT(sb_copy_data, selinux_sb_copy_data),
6335         LSM_HOOK_INIT(sb_remount, selinux_sb_remount),
6336         LSM_HOOK_INIT(sb_kern_mount, selinux_sb_kern_mount),
6337         LSM_HOOK_INIT(sb_show_options, selinux_sb_show_options),
6338         LSM_HOOK_INIT(sb_statfs, selinux_sb_statfs),
6339         LSM_HOOK_INIT(sb_mount, selinux_mount),
6340         LSM_HOOK_INIT(sb_umount, selinux_umount),
6341         LSM_HOOK_INIT(sb_set_mnt_opts, selinux_set_mnt_opts),
6342         LSM_HOOK_INIT(sb_clone_mnt_opts, selinux_sb_clone_mnt_opts),
6343         LSM_HOOK_INIT(sb_parse_opts_str, selinux_parse_opts_str),
6344
6345         LSM_HOOK_INIT(dentry_init_security, selinux_dentry_init_security),
6346         LSM_HOOK_INIT(dentry_create_files_as, selinux_dentry_create_files_as),
6347
6348         LSM_HOOK_INIT(inode_alloc_security, selinux_inode_alloc_security),
6349         LSM_HOOK_INIT(inode_free_security, selinux_inode_free_security),
6350         LSM_HOOK_INIT(inode_init_security, selinux_inode_init_security),
6351         LSM_HOOK_INIT(inode_create, selinux_inode_create),
6352         LSM_HOOK_INIT(inode_link, selinux_inode_link),
6353         LSM_HOOK_INIT(inode_unlink, selinux_inode_unlink),
6354         LSM_HOOK_INIT(inode_symlink, selinux_inode_symlink),
6355         LSM_HOOK_INIT(inode_mkdir, selinux_inode_mkdir),
6356         LSM_HOOK_INIT(inode_rmdir, selinux_inode_rmdir),
6357         LSM_HOOK_INIT(inode_mknod, selinux_inode_mknod),
6358         LSM_HOOK_INIT(inode_rename, selinux_inode_rename),
6359         LSM_HOOK_INIT(inode_readlink, selinux_inode_readlink),
6360         LSM_HOOK_INIT(inode_follow_link, selinux_inode_follow_link),
6361         LSM_HOOK_INIT(inode_permission, selinux_inode_permission),
6362         LSM_HOOK_INIT(inode_setattr, selinux_inode_setattr),
6363         LSM_HOOK_INIT(inode_getattr, selinux_inode_getattr),
6364         LSM_HOOK_INIT(inode_setxattr, selinux_inode_setxattr),
6365         LSM_HOOK_INIT(inode_post_setxattr, selinux_inode_post_setxattr),
6366         LSM_HOOK_INIT(inode_getxattr, selinux_inode_getxattr),
6367         LSM_HOOK_INIT(inode_listxattr, selinux_inode_listxattr),
6368         LSM_HOOK_INIT(inode_removexattr, selinux_inode_removexattr),
6369         LSM_HOOK_INIT(inode_getsecurity, selinux_inode_getsecurity),
6370         LSM_HOOK_INIT(inode_setsecurity, selinux_inode_setsecurity),
6371         LSM_HOOK_INIT(inode_listsecurity, selinux_inode_listsecurity),
6372         LSM_HOOK_INIT(inode_getsecid, selinux_inode_getsecid),
6373         LSM_HOOK_INIT(inode_copy_up, selinux_inode_copy_up),
6374         LSM_HOOK_INIT(inode_copy_up_xattr, selinux_inode_copy_up_xattr),
6375
6376         LSM_HOOK_INIT(file_permission, selinux_file_permission),
6377         LSM_HOOK_INIT(file_alloc_security, selinux_file_alloc_security),
6378         LSM_HOOK_INIT(file_free_security, selinux_file_free_security),
6379         LSM_HOOK_INIT(file_ioctl, selinux_file_ioctl),
6380         LSM_HOOK_INIT(mmap_file, selinux_mmap_file),
6381         LSM_HOOK_INIT(mmap_addr, selinux_mmap_addr),
6382         LSM_HOOK_INIT(file_mprotect, selinux_file_mprotect),
6383         LSM_HOOK_INIT(file_lock, selinux_file_lock),
6384         LSM_HOOK_INIT(file_fcntl, selinux_file_fcntl),
6385         LSM_HOOK_INIT(file_set_fowner, selinux_file_set_fowner),
6386         LSM_HOOK_INIT(file_send_sigiotask, selinux_file_send_sigiotask),
6387         LSM_HOOK_INIT(file_receive, selinux_file_receive),
6388
6389         LSM_HOOK_INIT(file_open, selinux_file_open),
6390
6391         LSM_HOOK_INIT(task_alloc, selinux_task_alloc),
6392         LSM_HOOK_INIT(cred_alloc_blank, selinux_cred_alloc_blank),
6393         LSM_HOOK_INIT(cred_free, selinux_cred_free),
6394         LSM_HOOK_INIT(cred_prepare, selinux_cred_prepare),
6395         LSM_HOOK_INIT(cred_transfer, selinux_cred_transfer),
6396         LSM_HOOK_INIT(kernel_act_as, selinux_kernel_act_as),
6397         LSM_HOOK_INIT(kernel_create_files_as, selinux_kernel_create_files_as),
6398         LSM_HOOK_INIT(kernel_module_request, selinux_kernel_module_request),
6399         LSM_HOOK_INIT(kernel_read_file, selinux_kernel_read_file),
6400         LSM_HOOK_INIT(task_setpgid, selinux_task_setpgid),
6401         LSM_HOOK_INIT(task_getpgid, selinux_task_getpgid),
6402         LSM_HOOK_INIT(task_getsid, selinux_task_getsid),
6403         LSM_HOOK_INIT(task_getsecid, selinux_task_getsecid),
6404         LSM_HOOK_INIT(task_setnice, selinux_task_setnice),
6405         LSM_HOOK_INIT(task_setioprio, selinux_task_setioprio),
6406         LSM_HOOK_INIT(task_getioprio, selinux_task_getioprio),
6407         LSM_HOOK_INIT(task_prlimit, selinux_task_prlimit),
6408         LSM_HOOK_INIT(task_setrlimit, selinux_task_setrlimit),
6409         LSM_HOOK_INIT(task_setscheduler, selinux_task_setscheduler),
6410         LSM_HOOK_INIT(task_getscheduler, selinux_task_getscheduler),
6411         LSM_HOOK_INIT(task_movememory, selinux_task_movememory),
6412         LSM_HOOK_INIT(task_kill, selinux_task_kill),
6413         LSM_HOOK_INIT(task_to_inode, selinux_task_to_inode),
6414
6415         LSM_HOOK_INIT(ipc_permission, selinux_ipc_permission),
6416         LSM_HOOK_INIT(ipc_getsecid, selinux_ipc_getsecid),
6417
6418         LSM_HOOK_INIT(msg_msg_alloc_security, selinux_msg_msg_alloc_security),
6419         LSM_HOOK_INIT(msg_msg_free_security, selinux_msg_msg_free_security),
6420
6421         LSM_HOOK_INIT(msg_queue_alloc_security,
6422                         selinux_msg_queue_alloc_security),
6423         LSM_HOOK_INIT(msg_queue_free_security, selinux_msg_queue_free_security),
6424         LSM_HOOK_INIT(msg_queue_associate, selinux_msg_queue_associate),
6425         LSM_HOOK_INIT(msg_queue_msgctl, selinux_msg_queue_msgctl),
6426         LSM_HOOK_INIT(msg_queue_msgsnd, selinux_msg_queue_msgsnd),
6427         LSM_HOOK_INIT(msg_queue_msgrcv, selinux_msg_queue_msgrcv),
6428
6429         LSM_HOOK_INIT(shm_alloc_security, selinux_shm_alloc_security),
6430         LSM_HOOK_INIT(shm_free_security, selinux_shm_free_security),
6431         LSM_HOOK_INIT(shm_associate, selinux_shm_associate),
6432         LSM_HOOK_INIT(shm_shmctl, selinux_shm_shmctl),
6433         LSM_HOOK_INIT(shm_shmat, selinux_shm_shmat),
6434
6435         LSM_HOOK_INIT(sem_alloc_security, selinux_sem_alloc_security),
6436         LSM_HOOK_INIT(sem_free_security, selinux_sem_free_security),
6437         LSM_HOOK_INIT(sem_associate, selinux_sem_associate),
6438         LSM_HOOK_INIT(sem_semctl, selinux_sem_semctl),
6439         LSM_HOOK_INIT(sem_semop, selinux_sem_semop),
6440
6441         LSM_HOOK_INIT(d_instantiate, selinux_d_instantiate),
6442
6443         LSM_HOOK_INIT(getprocattr, selinux_getprocattr),
6444         LSM_HOOK_INIT(setprocattr, selinux_setprocattr),
6445
6446         LSM_HOOK_INIT(ismaclabel, selinux_ismaclabel),
6447         LSM_HOOK_INIT(secid_to_secctx, selinux_secid_to_secctx),
6448         LSM_HOOK_INIT(secctx_to_secid, selinux_secctx_to_secid),
6449         LSM_HOOK_INIT(release_secctx, selinux_release_secctx),
6450         LSM_HOOK_INIT(inode_invalidate_secctx, selinux_inode_invalidate_secctx),
6451         LSM_HOOK_INIT(inode_notifysecctx, selinux_inode_notifysecctx),
6452         LSM_HOOK_INIT(inode_setsecctx, selinux_inode_setsecctx),
6453         LSM_HOOK_INIT(inode_getsecctx, selinux_inode_getsecctx),
6454
6455         LSM_HOOK_INIT(unix_stream_connect, selinux_socket_unix_stream_connect),
6456         LSM_HOOK_INIT(unix_may_send, selinux_socket_unix_may_send),
6457
6458         LSM_HOOK_INIT(socket_create, selinux_socket_create),
6459         LSM_HOOK_INIT(socket_post_create, selinux_socket_post_create),
6460         LSM_HOOK_INIT(socket_bind, selinux_socket_bind),
6461         LSM_HOOK_INIT(socket_connect, selinux_socket_connect),
6462         LSM_HOOK_INIT(socket_listen, selinux_socket_listen),
6463         LSM_HOOK_INIT(socket_accept, selinux_socket_accept),
6464         LSM_HOOK_INIT(socket_sendmsg, selinux_socket_sendmsg),
6465         LSM_HOOK_INIT(socket_recvmsg, selinux_socket_recvmsg),
6466         LSM_HOOK_INIT(socket_getsockname, selinux_socket_getsockname),
6467         LSM_HOOK_INIT(socket_getpeername, selinux_socket_getpeername),
6468         LSM_HOOK_INIT(socket_getsockopt, selinux_socket_getsockopt),
6469         LSM_HOOK_INIT(socket_setsockopt, selinux_socket_setsockopt),
6470         LSM_HOOK_INIT(socket_shutdown, selinux_socket_shutdown),
6471         LSM_HOOK_INIT(socket_sock_rcv_skb, selinux_socket_sock_rcv_skb),
6472         LSM_HOOK_INIT(socket_getpeersec_stream,
6473                         selinux_socket_getpeersec_stream),
6474         LSM_HOOK_INIT(socket_getpeersec_dgram, selinux_socket_getpeersec_dgram),
6475         LSM_HOOK_INIT(sk_alloc_security, selinux_sk_alloc_security),
6476         LSM_HOOK_INIT(sk_free_security, selinux_sk_free_security),
6477         LSM_HOOK_INIT(sk_clone_security, selinux_sk_clone_security),
6478         LSM_HOOK_INIT(sk_getsecid, selinux_sk_getsecid),
6479         LSM_HOOK_INIT(sock_graft, selinux_sock_graft),
6480         LSM_HOOK_INIT(inet_conn_request, selinux_inet_conn_request),
6481         LSM_HOOK_INIT(inet_csk_clone, selinux_inet_csk_clone),
6482         LSM_HOOK_INIT(inet_conn_established, selinux_inet_conn_established),
6483         LSM_HOOK_INIT(secmark_relabel_packet, selinux_secmark_relabel_packet),
6484         LSM_HOOK_INIT(secmark_refcount_inc, selinux_secmark_refcount_inc),
6485         LSM_HOOK_INIT(secmark_refcount_dec, selinux_secmark_refcount_dec),
6486         LSM_HOOK_INIT(req_classify_flow, selinux_req_classify_flow),
6487         LSM_HOOK_INIT(tun_dev_alloc_security, selinux_tun_dev_alloc_security),
6488         LSM_HOOK_INIT(tun_dev_free_security, selinux_tun_dev_free_security),
6489         LSM_HOOK_INIT(tun_dev_create, selinux_tun_dev_create),
6490         LSM_HOOK_INIT(tun_dev_attach_queue, selinux_tun_dev_attach_queue),
6491         LSM_HOOK_INIT(tun_dev_attach, selinux_tun_dev_attach),
6492         LSM_HOOK_INIT(tun_dev_open, selinux_tun_dev_open),
6493 #ifdef CONFIG_SECURITY_INFINIBAND
6494         LSM_HOOK_INIT(ib_pkey_access, selinux_ib_pkey_access),
6495         LSM_HOOK_INIT(ib_endport_manage_subnet,
6496                       selinux_ib_endport_manage_subnet),
6497         LSM_HOOK_INIT(ib_alloc_security, selinux_ib_alloc_security),
6498         LSM_HOOK_INIT(ib_free_security, selinux_ib_free_security),
6499 #endif
6500 #ifdef CONFIG_SECURITY_NETWORK_XFRM
6501         LSM_HOOK_INIT(xfrm_policy_alloc_security, selinux_xfrm_policy_alloc),
6502         LSM_HOOK_INIT(xfrm_policy_clone_security, selinux_xfrm_policy_clone),
6503         LSM_HOOK_INIT(xfrm_policy_free_security, selinux_xfrm_policy_free),
6504         LSM_HOOK_INIT(xfrm_policy_delete_security, selinux_xfrm_policy_delete),
6505         LSM_HOOK_INIT(xfrm_state_alloc, selinux_xfrm_state_alloc),
6506         LSM_HOOK_INIT(xfrm_state_alloc_acquire,
6507                         selinux_xfrm_state_alloc_acquire),
6508         LSM_HOOK_INIT(xfrm_state_free_security, selinux_xfrm_state_free),
6509         LSM_HOOK_INIT(xfrm_state_delete_security, selinux_xfrm_state_delete),
6510         LSM_HOOK_INIT(xfrm_policy_lookup, selinux_xfrm_policy_lookup),
6511         LSM_HOOK_INIT(xfrm_state_pol_flow_match,
6512                         selinux_xfrm_state_pol_flow_match),
6513         LSM_HOOK_INIT(xfrm_decode_session, selinux_xfrm_decode_session),
6514 #endif
6515
6516 #ifdef CONFIG_KEYS
6517         LSM_HOOK_INIT(key_alloc, selinux_key_alloc),
6518         LSM_HOOK_INIT(key_free, selinux_key_free),
6519         LSM_HOOK_INIT(key_permission, selinux_key_permission),
6520         LSM_HOOK_INIT(key_getsecurity, selinux_key_getsecurity),
6521 #endif
6522
6523 #ifdef CONFIG_AUDIT
6524         LSM_HOOK_INIT(audit_rule_init, selinux_audit_rule_init),
6525         LSM_HOOK_INIT(audit_rule_known, selinux_audit_rule_known),
6526         LSM_HOOK_INIT(audit_rule_match, selinux_audit_rule_match),
6527         LSM_HOOK_INIT(audit_rule_free, selinux_audit_rule_free),
6528 #endif
6529 };
6530
6531 static __init int selinux_init(void)
6532 {
6533         if (!security_module_enable("selinux")) {
6534                 selinux_enabled = 0;
6535                 return 0;
6536         }
6537
6538         if (!selinux_enabled) {
6539                 printk(KERN_INFO "SELinux:  Disabled at boot.\n");
6540                 return 0;
6541         }
6542
6543         printk(KERN_INFO "SELinux:  Initializing.\n");
6544
6545         /* Set the security state for the initial task. */
6546         cred_init_security();
6547
6548         default_noexec = !(VM_DATA_DEFAULT_FLAGS & VM_EXEC);
6549
6550         sel_inode_cache = kmem_cache_create("selinux_inode_security",
6551                                             sizeof(struct inode_security_struct),
6552                                             0, SLAB_PANIC, NULL);
6553         file_security_cache = kmem_cache_create("selinux_file_security",
6554                                             sizeof(struct file_security_struct),
6555                                             0, SLAB_PANIC, NULL);
6556         avc_init();
6557
6558         security_add_hooks(selinux_hooks, ARRAY_SIZE(selinux_hooks), "selinux");
6559
6560         if (avc_add_callback(selinux_netcache_avc_callback, AVC_CALLBACK_RESET))
6561                 panic("SELinux: Unable to register AVC netcache callback\n");
6562
6563         if (avc_add_callback(selinux_lsm_notifier_avc_callback, AVC_CALLBACK_RESET))
6564                 panic("SELinux: Unable to register AVC LSM notifier callback\n");
6565
6566         if (selinux_enforcing)
6567                 printk(KERN_DEBUG "SELinux:  Starting in enforcing mode\n");
6568         else
6569                 printk(KERN_DEBUG "SELinux:  Starting in permissive mode\n");
6570
6571         return 0;
6572 }
6573
6574 static void delayed_superblock_init(struct super_block *sb, void *unused)
6575 {
6576         superblock_doinit(sb, NULL);
6577 }
6578
6579 void selinux_complete_init(void)
6580 {
6581         printk(KERN_DEBUG "SELinux:  Completing initialization.\n");
6582
6583         /* Set up any superblocks initialized prior to the policy load. */
6584         printk(KERN_DEBUG "SELinux:  Setting up existing superblocks.\n");
6585         iterate_supers(delayed_superblock_init, NULL);
6586 }
6587
6588 /* SELinux requires early initialization in order to label
6589    all processes and objects when they are created. */
6590 security_initcall(selinux_init);
6591
6592 #if defined(CONFIG_NETFILTER)
6593
6594 static const struct nf_hook_ops selinux_nf_ops[] = {
6595         {
6596                 .hook =         selinux_ipv4_postroute,
6597                 .pf =           NFPROTO_IPV4,
6598                 .hooknum =      NF_INET_POST_ROUTING,
6599                 .priority =     NF_IP_PRI_SELINUX_LAST,
6600         },
6601         {
6602                 .hook =         selinux_ipv4_forward,
6603                 .pf =           NFPROTO_IPV4,
6604                 .hooknum =      NF_INET_FORWARD,
6605                 .priority =     NF_IP_PRI_SELINUX_FIRST,
6606         },
6607         {
6608                 .hook =         selinux_ipv4_output,
6609                 .pf =           NFPROTO_IPV4,
6610                 .hooknum =      NF_INET_LOCAL_OUT,
6611                 .priority =     NF_IP_PRI_SELINUX_FIRST,
6612         },
6613 #if IS_ENABLED(CONFIG_IPV6)
6614         {
6615                 .hook =         selinux_ipv6_postroute,
6616                 .pf =           NFPROTO_IPV6,
6617                 .hooknum =      NF_INET_POST_ROUTING,
6618                 .priority =     NF_IP6_PRI_SELINUX_LAST,
6619         },
6620         {
6621                 .hook =         selinux_ipv6_forward,
6622                 .pf =           NFPROTO_IPV6,
6623                 .hooknum =      NF_INET_FORWARD,
6624                 .priority =     NF_IP6_PRI_SELINUX_FIRST,
6625         },
6626         {
6627                 .hook =         selinux_ipv6_output,
6628                 .pf =           NFPROTO_IPV6,
6629                 .hooknum =      NF_INET_LOCAL_OUT,
6630                 .priority =     NF_IP6_PRI_SELINUX_FIRST,
6631         },
6632 #endif  /* IPV6 */
6633 };
6634
6635 static int __net_init selinux_nf_register(struct net *net)
6636 {
6637         return nf_register_net_hooks(net, selinux_nf_ops,
6638                                      ARRAY_SIZE(selinux_nf_ops));
6639 }
6640
6641 static void __net_exit selinux_nf_unregister(struct net *net)
6642 {
6643         nf_unregister_net_hooks(net, selinux_nf_ops,
6644                                 ARRAY_SIZE(selinux_nf_ops));
6645 }
6646
6647 static struct pernet_operations selinux_net_ops = {
6648         .init = selinux_nf_register,
6649         .exit = selinux_nf_unregister,
6650 };
6651
6652 static int __init selinux_nf_ip_init(void)
6653 {
6654         int err;
6655
6656         if (!selinux_enabled)
6657                 return 0;
6658
6659         printk(KERN_DEBUG "SELinux:  Registering netfilter hooks\n");
6660
6661         err = register_pernet_subsys(&selinux_net_ops);
6662         if (err)
6663                 panic("SELinux: register_pernet_subsys: error %d\n", err);
6664
6665         return 0;
6666 }
6667 __initcall(selinux_nf_ip_init);
6668
6669 #ifdef CONFIG_SECURITY_SELINUX_DISABLE
6670 static void selinux_nf_ip_exit(void)
6671 {
6672         printk(KERN_DEBUG "SELinux:  Unregistering netfilter hooks\n");
6673
6674         unregister_pernet_subsys(&selinux_net_ops);
6675 }
6676 #endif
6677
6678 #else /* CONFIG_NETFILTER */
6679
6680 #ifdef CONFIG_SECURITY_SELINUX_DISABLE
6681 #define selinux_nf_ip_exit()
6682 #endif
6683
6684 #endif /* CONFIG_NETFILTER */
6685
6686 #ifdef CONFIG_SECURITY_SELINUX_DISABLE
6687 static int selinux_disabled;
6688
6689 int selinux_disable(void)
6690 {
6691         if (ss_initialized) {
6692                 /* Not permitted after initial policy load. */
6693                 return -EINVAL;
6694         }
6695
6696         if (selinux_disabled) {
6697                 /* Only do this once. */
6698                 return -EINVAL;
6699         }
6700
6701         printk(KERN_INFO "SELinux:  Disabled at runtime.\n");
6702
6703         selinux_disabled = 1;
6704         selinux_enabled = 0;
6705
6706         security_delete_hooks(selinux_hooks, ARRAY_SIZE(selinux_hooks));
6707
6708         /* Try to destroy the avc node cache */
6709         avc_disable();
6710
6711         /* Unregister netfilter hooks. */
6712         selinux_nf_ip_exit();
6713
6714         /* Unregister selinuxfs. */
6715         exit_sel_fs();
6716
6717         return 0;
6718 }
6719 #endif