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