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