SELinux: Add a network node caching mechanism similar to the sel_netif_*() functions
[linux-2.6.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 Red Hat, Inc., James Morris <jmorris@redhat.com>
13  *  Copyright (C) 2004-2005 Trusted Computer Solutions, Inc.
14  *                          <dgoeddel@trustedcs.com>
15  *  Copyright (C) 2006 Hewlett-Packard Development Company, L.P.
16  *                     Paul Moore, <paul.moore@hp.com>
17  *  Copyright (C) 2007 Hitachi Software Engineering Co., Ltd.
18  *                     Yuichi Nakamura <ynakam@hitachisoft.jp>
19  *
20  *      This program is free software; you can redistribute it and/or modify
21  *      it under the terms of the GNU General Public License version 2,
22  *      as published by the Free Software Foundation.
23  */
24
25 #include <linux/init.h>
26 #include <linux/kernel.h>
27 #include <linux/ptrace.h>
28 #include <linux/errno.h>
29 #include <linux/sched.h>
30 #include <linux/security.h>
31 #include <linux/xattr.h>
32 #include <linux/capability.h>
33 #include <linux/unistd.h>
34 #include <linux/mm.h>
35 #include <linux/mman.h>
36 #include <linux/slab.h>
37 #include <linux/pagemap.h>
38 #include <linux/swap.h>
39 #include <linux/spinlock.h>
40 #include <linux/syscalls.h>
41 #include <linux/file.h>
42 #include <linux/namei.h>
43 #include <linux/mount.h>
44 #include <linux/ext2_fs.h>
45 #include <linux/proc_fs.h>
46 #include <linux/kd.h>
47 #include <linux/netfilter_ipv4.h>
48 #include <linux/netfilter_ipv6.h>
49 #include <linux/tty.h>
50 #include <net/icmp.h>
51 #include <net/ip.h>             /* for local_port_range[] */
52 #include <net/tcp.h>            /* struct or_callable used in sock_rcv_skb */
53 #include <asm/uaccess.h>
54 #include <asm/ioctls.h>
55 #include <linux/bitops.h>
56 #include <linux/interrupt.h>
57 #include <linux/netdevice.h>    /* for network interface checks */
58 #include <linux/netlink.h>
59 #include <linux/tcp.h>
60 #include <linux/udp.h>
61 #include <linux/dccp.h>
62 #include <linux/quota.h>
63 #include <linux/un.h>           /* for Unix socket types */
64 #include <net/af_unix.h>        /* for Unix socket types */
65 #include <linux/parser.h>
66 #include <linux/nfs_mount.h>
67 #include <net/ipv6.h>
68 #include <linux/hugetlb.h>
69 #include <linux/personality.h>
70 #include <linux/sysctl.h>
71 #include <linux/audit.h>
72 #include <linux/string.h>
73 #include <linux/selinux.h>
74 #include <linux/mutex.h>
75
76 #include "avc.h"
77 #include "objsec.h"
78 #include "netif.h"
79 #include "netnode.h"
80 #include "xfrm.h"
81 #include "netlabel.h"
82
83 #define XATTR_SELINUX_SUFFIX "selinux"
84 #define XATTR_NAME_SELINUX XATTR_SECURITY_PREFIX XATTR_SELINUX_SUFFIX
85
86 #define NUM_SEL_MNT_OPTS 4
87
88 extern unsigned int policydb_loaded_version;
89 extern int selinux_nlmsg_lookup(u16 sclass, u16 nlmsg_type, u32 *perm);
90 extern int selinux_compat_net;
91 extern struct security_operations *security_ops;
92
93 #ifdef CONFIG_SECURITY_SELINUX_DEVELOP
94 int selinux_enforcing = 0;
95
96 static int __init enforcing_setup(char *str)
97 {
98         selinux_enforcing = simple_strtol(str,NULL,0);
99         return 1;
100 }
101 __setup("enforcing=", enforcing_setup);
102 #endif
103
104 #ifdef CONFIG_SECURITY_SELINUX_BOOTPARAM
105 int selinux_enabled = CONFIG_SECURITY_SELINUX_BOOTPARAM_VALUE;
106
107 static int __init selinux_enabled_setup(char *str)
108 {
109         selinux_enabled = simple_strtol(str, NULL, 0);
110         return 1;
111 }
112 __setup("selinux=", selinux_enabled_setup);
113 #else
114 int selinux_enabled = 1;
115 #endif
116
117 /* Original (dummy) security module. */
118 static struct security_operations *original_ops = NULL;
119
120 /* Minimal support for a secondary security module,
121    just to allow the use of the dummy or capability modules.
122    The owlsm module can alternatively be used as a secondary
123    module as long as CONFIG_OWLSM_FD is not enabled. */
124 static struct security_operations *secondary_ops = NULL;
125
126 /* Lists of inode and superblock security structures initialized
127    before the policy was loaded. */
128 static LIST_HEAD(superblock_security_head);
129 static DEFINE_SPINLOCK(sb_security_lock);
130
131 static struct kmem_cache *sel_inode_cache;
132
133 /* Return security context for a given sid or just the context 
134    length if the buffer is null or length is 0 */
135 static int selinux_getsecurity(u32 sid, void *buffer, size_t size)
136 {
137         char *context;
138         unsigned len;
139         int rc;
140
141         rc = security_sid_to_context(sid, &context, &len);
142         if (rc)
143                 return rc;
144
145         if (!buffer || !size)
146                 goto getsecurity_exit;
147
148         if (size < len) {
149                 len = -ERANGE;
150                 goto getsecurity_exit;
151         }
152         memcpy(buffer, context, len);
153
154 getsecurity_exit:
155         kfree(context);
156         return len;
157 }
158
159 /* Allocate and free functions for each kind of security blob. */
160
161 static int task_alloc_security(struct task_struct *task)
162 {
163         struct task_security_struct *tsec;
164
165         tsec = kzalloc(sizeof(struct task_security_struct), GFP_KERNEL);
166         if (!tsec)
167                 return -ENOMEM;
168
169         tsec->task = task;
170         tsec->osid = tsec->sid = tsec->ptrace_sid = SECINITSID_UNLABELED;
171         task->security = tsec;
172
173         return 0;
174 }
175
176 static void task_free_security(struct task_struct *task)
177 {
178         struct task_security_struct *tsec = task->security;
179         task->security = NULL;
180         kfree(tsec);
181 }
182
183 static int inode_alloc_security(struct inode *inode)
184 {
185         struct task_security_struct *tsec = current->security;
186         struct inode_security_struct *isec;
187
188         isec = kmem_cache_zalloc(sel_inode_cache, GFP_KERNEL);
189         if (!isec)
190                 return -ENOMEM;
191
192         mutex_init(&isec->lock);
193         INIT_LIST_HEAD(&isec->list);
194         isec->inode = inode;
195         isec->sid = SECINITSID_UNLABELED;
196         isec->sclass = SECCLASS_FILE;
197         isec->task_sid = tsec->sid;
198         inode->i_security = isec;
199
200         return 0;
201 }
202
203 static void inode_free_security(struct inode *inode)
204 {
205         struct inode_security_struct *isec = inode->i_security;
206         struct superblock_security_struct *sbsec = inode->i_sb->s_security;
207
208         spin_lock(&sbsec->isec_lock);
209         if (!list_empty(&isec->list))
210                 list_del_init(&isec->list);
211         spin_unlock(&sbsec->isec_lock);
212
213         inode->i_security = NULL;
214         kmem_cache_free(sel_inode_cache, isec);
215 }
216
217 static int file_alloc_security(struct file *file)
218 {
219         struct task_security_struct *tsec = current->security;
220         struct file_security_struct *fsec;
221
222         fsec = kzalloc(sizeof(struct file_security_struct), GFP_KERNEL);
223         if (!fsec)
224                 return -ENOMEM;
225
226         fsec->file = file;
227         fsec->sid = tsec->sid;
228         fsec->fown_sid = tsec->sid;
229         file->f_security = fsec;
230
231         return 0;
232 }
233
234 static void file_free_security(struct file *file)
235 {
236         struct file_security_struct *fsec = file->f_security;
237         file->f_security = NULL;
238         kfree(fsec);
239 }
240
241 static int superblock_alloc_security(struct super_block *sb)
242 {
243         struct superblock_security_struct *sbsec;
244
245         sbsec = kzalloc(sizeof(struct superblock_security_struct), GFP_KERNEL);
246         if (!sbsec)
247                 return -ENOMEM;
248
249         mutex_init(&sbsec->lock);
250         INIT_LIST_HEAD(&sbsec->list);
251         INIT_LIST_HEAD(&sbsec->isec_head);
252         spin_lock_init(&sbsec->isec_lock);
253         sbsec->sb = sb;
254         sbsec->sid = SECINITSID_UNLABELED;
255         sbsec->def_sid = SECINITSID_FILE;
256         sbsec->mntpoint_sid = SECINITSID_UNLABELED;
257         sb->s_security = sbsec;
258
259         return 0;
260 }
261
262 static void superblock_free_security(struct super_block *sb)
263 {
264         struct superblock_security_struct *sbsec = sb->s_security;
265
266         spin_lock(&sb_security_lock);
267         if (!list_empty(&sbsec->list))
268                 list_del_init(&sbsec->list);
269         spin_unlock(&sb_security_lock);
270
271         sb->s_security = NULL;
272         kfree(sbsec);
273 }
274
275 static int sk_alloc_security(struct sock *sk, int family, gfp_t priority)
276 {
277         struct sk_security_struct *ssec;
278
279         ssec = kzalloc(sizeof(*ssec), priority);
280         if (!ssec)
281                 return -ENOMEM;
282
283         ssec->sk = sk;
284         ssec->peer_sid = SECINITSID_UNLABELED;
285         ssec->sid = SECINITSID_UNLABELED;
286         sk->sk_security = ssec;
287
288         selinux_netlbl_sk_security_init(ssec, family);
289
290         return 0;
291 }
292
293 static void sk_free_security(struct sock *sk)
294 {
295         struct sk_security_struct *ssec = sk->sk_security;
296
297         sk->sk_security = NULL;
298         kfree(ssec);
299 }
300
301 /* The security server must be initialized before
302    any labeling or access decisions can be provided. */
303 extern int ss_initialized;
304
305 /* The file system's label must be initialized prior to use. */
306
307 static char *labeling_behaviors[6] = {
308         "uses xattr",
309         "uses transition SIDs",
310         "uses task SIDs",
311         "uses genfs_contexts",
312         "not configured for labeling",
313         "uses mountpoint labeling",
314 };
315
316 static int inode_doinit_with_dentry(struct inode *inode, struct dentry *opt_dentry);
317
318 static inline int inode_doinit(struct inode *inode)
319 {
320         return inode_doinit_with_dentry(inode, NULL);
321 }
322
323 enum {
324         Opt_error = -1,
325         Opt_context = 1,
326         Opt_fscontext = 2,
327         Opt_defcontext = 3,
328         Opt_rootcontext = 4,
329 };
330
331 static match_table_t tokens = {
332         {Opt_context, "context=%s"},
333         {Opt_fscontext, "fscontext=%s"},
334         {Opt_defcontext, "defcontext=%s"},
335         {Opt_rootcontext, "rootcontext=%s"},
336         {Opt_error, NULL},
337 };
338
339 #define SEL_MOUNT_FAIL_MSG "SELinux:  duplicate or incompatible mount options\n"
340
341 static int may_context_mount_sb_relabel(u32 sid,
342                         struct superblock_security_struct *sbsec,
343                         struct task_security_struct *tsec)
344 {
345         int rc;
346
347         rc = avc_has_perm(tsec->sid, sbsec->sid, SECCLASS_FILESYSTEM,
348                           FILESYSTEM__RELABELFROM, NULL);
349         if (rc)
350                 return rc;
351
352         rc = avc_has_perm(tsec->sid, sid, SECCLASS_FILESYSTEM,
353                           FILESYSTEM__RELABELTO, NULL);
354         return rc;
355 }
356
357 static int may_context_mount_inode_relabel(u32 sid,
358                         struct superblock_security_struct *sbsec,
359                         struct task_security_struct *tsec)
360 {
361         int rc;
362         rc = avc_has_perm(tsec->sid, sbsec->sid, SECCLASS_FILESYSTEM,
363                           FILESYSTEM__RELABELFROM, NULL);
364         if (rc)
365                 return rc;
366
367         rc = avc_has_perm(sid, sbsec->sid, SECCLASS_FILESYSTEM,
368                           FILESYSTEM__ASSOCIATE, NULL);
369         return rc;
370 }
371
372 static int sb_finish_set_opts(struct super_block *sb)
373 {
374         struct superblock_security_struct *sbsec = sb->s_security;
375         struct dentry *root = sb->s_root;
376         struct inode *root_inode = root->d_inode;
377         int rc = 0;
378
379         if (sbsec->behavior == SECURITY_FS_USE_XATTR) {
380                 /* Make sure that the xattr handler exists and that no
381                    error other than -ENODATA is returned by getxattr on
382                    the root directory.  -ENODATA is ok, as this may be
383                    the first boot of the SELinux kernel before we have
384                    assigned xattr values to the filesystem. */
385                 if (!root_inode->i_op->getxattr) {
386                         printk(KERN_WARNING "SELinux: (dev %s, type %s) has no "
387                                "xattr support\n", sb->s_id, sb->s_type->name);
388                         rc = -EOPNOTSUPP;
389                         goto out;
390                 }
391                 rc = root_inode->i_op->getxattr(root, XATTR_NAME_SELINUX, NULL, 0);
392                 if (rc < 0 && rc != -ENODATA) {
393                         if (rc == -EOPNOTSUPP)
394                                 printk(KERN_WARNING "SELinux: (dev %s, type "
395                                        "%s) has no security xattr handler\n",
396                                        sb->s_id, sb->s_type->name);
397                         else
398                                 printk(KERN_WARNING "SELinux: (dev %s, type "
399                                        "%s) getxattr errno %d\n", sb->s_id,
400                                        sb->s_type->name, -rc);
401                         goto out;
402                 }
403         }
404
405         sbsec->initialized = 1;
406
407         if (sbsec->behavior > ARRAY_SIZE(labeling_behaviors))
408                 printk(KERN_ERR "SELinux: initialized (dev %s, type %s), unknown behavior\n",
409                        sb->s_id, sb->s_type->name);
410         else
411                 printk(KERN_DEBUG "SELinux: initialized (dev %s, type %s), %s\n",
412                        sb->s_id, sb->s_type->name,
413                        labeling_behaviors[sbsec->behavior-1]);
414
415         /* Initialize the root inode. */
416         rc = inode_doinit_with_dentry(root_inode, root);
417
418         /* Initialize any other inodes associated with the superblock, e.g.
419            inodes created prior to initial policy load or inodes created
420            during get_sb by a pseudo filesystem that directly
421            populates itself. */
422         spin_lock(&sbsec->isec_lock);
423 next_inode:
424         if (!list_empty(&sbsec->isec_head)) {
425                 struct inode_security_struct *isec =
426                                 list_entry(sbsec->isec_head.next,
427                                            struct inode_security_struct, list);
428                 struct inode *inode = isec->inode;
429                 spin_unlock(&sbsec->isec_lock);
430                 inode = igrab(inode);
431                 if (inode) {
432                         if (!IS_PRIVATE(inode))
433                                 inode_doinit(inode);
434                         iput(inode);
435                 }
436                 spin_lock(&sbsec->isec_lock);
437                 list_del_init(&isec->list);
438                 goto next_inode;
439         }
440         spin_unlock(&sbsec->isec_lock);
441 out:
442         return rc;
443 }
444
445 /*
446  * This function should allow an FS to ask what it's mount security
447  * options were so it can use those later for submounts, displaying
448  * mount options, or whatever.
449  */
450 static int selinux_get_mnt_opts(const struct super_block *sb,
451                                 char ***mount_options, int **mnt_opts_flags,
452                                 int *num_opts)
453 {
454         int rc = 0, i;
455         struct superblock_security_struct *sbsec = sb->s_security;
456         char *context = NULL;
457         u32 len;
458         char tmp;
459
460         *num_opts = 0;
461         *mount_options = NULL;
462         *mnt_opts_flags = NULL;
463
464         if (!sbsec->initialized)
465                 return -EINVAL;
466
467         if (!ss_initialized)
468                 return -EINVAL;
469
470         /*
471          * if we ever use sbsec flags for anything other than tracking mount
472          * settings this is going to need a mask
473          */
474         tmp = sbsec->flags;
475         /* count the number of mount options for this sb */
476         for (i = 0; i < 8; i++) {
477                 if (tmp & 0x01)
478                         (*num_opts)++;
479                 tmp >>= 1;
480         }
481
482         *mount_options = kcalloc(*num_opts, sizeof(char *), GFP_ATOMIC);
483         if (!*mount_options) {
484                 rc = -ENOMEM;
485                 goto out_free;
486         }
487
488         *mnt_opts_flags = kcalloc(*num_opts, sizeof(int), GFP_ATOMIC);
489         if (!*mnt_opts_flags) {
490                 rc = -ENOMEM;
491                 goto out_free;
492         }
493
494         i = 0;
495         if (sbsec->flags & FSCONTEXT_MNT) {
496                 rc = security_sid_to_context(sbsec->sid, &context, &len);
497                 if (rc)
498                         goto out_free;
499                 (*mount_options)[i] = context;
500                 (*mnt_opts_flags)[i++] = FSCONTEXT_MNT;
501         }
502         if (sbsec->flags & CONTEXT_MNT) {
503                 rc = security_sid_to_context(sbsec->mntpoint_sid, &context, &len);
504                 if (rc)
505                         goto out_free;
506                 (*mount_options)[i] = context;
507                 (*mnt_opts_flags)[i++] = CONTEXT_MNT;
508         }
509         if (sbsec->flags & DEFCONTEXT_MNT) {
510                 rc = security_sid_to_context(sbsec->def_sid, &context, &len);
511                 if (rc)
512                         goto out_free;
513                 (*mount_options)[i] = context;
514                 (*mnt_opts_flags)[i++] = DEFCONTEXT_MNT;
515         }
516         if (sbsec->flags & ROOTCONTEXT_MNT) {
517                 struct inode *root = sbsec->sb->s_root->d_inode;
518                 struct inode_security_struct *isec = root->i_security;
519
520                 rc = security_sid_to_context(isec->sid, &context, &len);
521                 if (rc)
522                         goto out_free;
523                 (*mount_options)[i] = context;
524                 (*mnt_opts_flags)[i++] = ROOTCONTEXT_MNT;
525         }
526
527         BUG_ON(i != *num_opts);
528
529         return 0;
530
531 out_free:
532         /* don't leak context string if security_sid_to_context had an error */
533         if (*mount_options && i)
534                 for (; i > 0; i--)
535                         kfree((*mount_options)[i-1]);
536         kfree(*mount_options);
537         *mount_options = NULL;
538         kfree(*mnt_opts_flags);
539         *mnt_opts_flags = NULL;
540         *num_opts = 0;
541         return rc;
542 }
543
544 static int bad_option(struct superblock_security_struct *sbsec, char flag,
545                       u32 old_sid, u32 new_sid)
546 {
547         /* check if the old mount command had the same options */
548         if (sbsec->initialized)
549                 if (!(sbsec->flags & flag) ||
550                     (old_sid != new_sid))
551                         return 1;
552
553         /* check if we were passed the same options twice,
554          * aka someone passed context=a,context=b
555          */
556         if (!sbsec->initialized)
557                 if (sbsec->flags & flag)
558                         return 1;
559         return 0;
560 }
561 /*
562  * Allow filesystems with binary mount data to explicitly set mount point
563  * labeling information.
564  */
565 int selinux_set_mnt_opts(struct super_block *sb, char **mount_options,
566                                  int *flags, int num_opts)
567 {
568         int rc = 0, i;
569         struct task_security_struct *tsec = current->security;
570         struct superblock_security_struct *sbsec = sb->s_security;
571         const char *name = sb->s_type->name;
572         struct inode *inode = sbsec->sb->s_root->d_inode;
573         struct inode_security_struct *root_isec = inode->i_security;
574         u32 fscontext_sid = 0, context_sid = 0, rootcontext_sid = 0;
575         u32 defcontext_sid = 0;
576
577         mutex_lock(&sbsec->lock);
578
579         if (!ss_initialized) {
580                 if (!num_opts) {
581                         /* Defer initialization until selinux_complete_init,
582                            after the initial policy is loaded and the security
583                            server is ready to handle calls. */
584                         spin_lock(&sb_security_lock);
585                         if (list_empty(&sbsec->list))
586                                 list_add(&sbsec->list, &superblock_security_head);
587                         spin_unlock(&sb_security_lock);
588                         goto out;
589                 }
590                 rc = -EINVAL;
591                 printk(KERN_WARNING "Unable to set superblock options before "
592                        "the security server is initialized\n");
593                 goto out;
594         }
595
596         /*
597          * parse the mount options, check if they are valid sids.
598          * also check if someone is trying to mount the same sb more
599          * than once with different security options.
600          */
601         for (i = 0; i < num_opts; i++) {
602                 u32 sid;
603                 rc = security_context_to_sid(mount_options[i],
604                                              strlen(mount_options[i]), &sid);
605                 if (rc) {
606                         printk(KERN_WARNING "SELinux: security_context_to_sid"
607                                "(%s) failed for (dev %s, type %s) errno=%d\n",
608                                mount_options[i], sb->s_id, name, rc);
609                         goto out;
610                 }
611                 switch (flags[i]) {
612                 case FSCONTEXT_MNT:
613                         fscontext_sid = sid;
614
615                         if (bad_option(sbsec, FSCONTEXT_MNT, sbsec->sid,
616                                         fscontext_sid))
617                                 goto out_double_mount;
618
619                         sbsec->flags |= FSCONTEXT_MNT;
620                         break;
621                 case CONTEXT_MNT:
622                         context_sid = sid;
623
624                         if (bad_option(sbsec, CONTEXT_MNT, sbsec->mntpoint_sid,
625                                         context_sid))
626                                 goto out_double_mount;
627
628                         sbsec->flags |= CONTEXT_MNT;
629                         break;
630                 case ROOTCONTEXT_MNT:
631                         rootcontext_sid = sid;
632
633                         if (bad_option(sbsec, ROOTCONTEXT_MNT, root_isec->sid,
634                                         rootcontext_sid))
635                                 goto out_double_mount;
636
637                         sbsec->flags |= ROOTCONTEXT_MNT;
638
639                         break;
640                 case DEFCONTEXT_MNT:
641                         defcontext_sid = sid;
642
643                         if (bad_option(sbsec, DEFCONTEXT_MNT, sbsec->def_sid,
644                                         defcontext_sid))
645                                 goto out_double_mount;
646
647                         sbsec->flags |= DEFCONTEXT_MNT;
648
649                         break;
650                 default:
651                         rc = -EINVAL;
652                         goto out;
653                 }
654         }
655
656         if (sbsec->initialized) {
657                 /* previously mounted with options, but not on this attempt? */
658                 if (sbsec->flags && !num_opts)
659                         goto out_double_mount;
660                 rc = 0;
661                 goto out;
662         }
663
664         if (strcmp(sb->s_type->name, "proc") == 0)
665                 sbsec->proc = 1;
666
667         /* Determine the labeling behavior to use for this filesystem type. */
668         rc = security_fs_use(sb->s_type->name, &sbsec->behavior, &sbsec->sid);
669         if (rc) {
670                 printk(KERN_WARNING "%s: security_fs_use(%s) returned %d\n",
671                        __FUNCTION__, sb->s_type->name, rc);
672                 goto out;
673         }
674
675         /* sets the context of the superblock for the fs being mounted. */
676         if (fscontext_sid) {
677
678                 rc = may_context_mount_sb_relabel(fscontext_sid, sbsec, tsec);
679                 if (rc)
680                         goto out;
681
682                 sbsec->sid = fscontext_sid;
683         }
684
685         /*
686          * Switch to using mount point labeling behavior.
687          * sets the label used on all file below the mountpoint, and will set
688          * the superblock context if not already set.
689          */
690         if (context_sid) {
691                 if (!fscontext_sid) {
692                         rc = may_context_mount_sb_relabel(context_sid, sbsec, tsec);
693                         if (rc)
694                                 goto out;
695                         sbsec->sid = context_sid;
696                 } else {
697                         rc = may_context_mount_inode_relabel(context_sid, sbsec, tsec);
698                         if (rc)
699                                 goto out;
700                 }
701                 if (!rootcontext_sid)
702                         rootcontext_sid = context_sid;
703
704                 sbsec->mntpoint_sid = context_sid;
705                 sbsec->behavior = SECURITY_FS_USE_MNTPOINT;
706         }
707
708         if (rootcontext_sid) {
709                 rc = may_context_mount_inode_relabel(rootcontext_sid, sbsec, tsec);
710                 if (rc)
711                         goto out;
712
713                 root_isec->sid = rootcontext_sid;
714                 root_isec->initialized = 1;
715         }
716
717         if (defcontext_sid) {
718                 if (sbsec->behavior != SECURITY_FS_USE_XATTR) {
719                         rc = -EINVAL;
720                         printk(KERN_WARNING "SELinux: defcontext option is "
721                                "invalid for this filesystem type\n");
722                         goto out;
723                 }
724
725                 if (defcontext_sid != sbsec->def_sid) {
726                         rc = may_context_mount_inode_relabel(defcontext_sid,
727                                                              sbsec, tsec);
728                         if (rc)
729                                 goto out;
730                 }
731
732                 sbsec->def_sid = defcontext_sid;
733         }
734
735         rc = sb_finish_set_opts(sb);
736 out:
737         mutex_unlock(&sbsec->lock);
738         return rc;
739 out_double_mount:
740         rc = -EINVAL;
741         printk(KERN_WARNING "SELinux: mount invalid.  Same superblock, different "
742                "security settings for (dev %s, type %s)\n", sb->s_id, name);
743         goto out;
744 }
745
746 static void selinux_sb_clone_mnt_opts(const struct super_block *oldsb,
747                                         struct super_block *newsb)
748 {
749         const struct superblock_security_struct *oldsbsec = oldsb->s_security;
750         struct superblock_security_struct *newsbsec = newsb->s_security;
751
752         int set_fscontext =     (oldsbsec->flags & FSCONTEXT_MNT);
753         int set_context =       (oldsbsec->flags & CONTEXT_MNT);
754         int set_rootcontext =   (oldsbsec->flags & ROOTCONTEXT_MNT);
755
756         /* we can't error, we can't save the info, this shouldn't get called
757          * this early in the boot process. */
758         BUG_ON(!ss_initialized);
759
760         /* this might go away sometime down the line if there is a new user
761          * of clone, but for now, nfs better not get here... */
762         BUG_ON(newsbsec->initialized);
763
764         /* how can we clone if the old one wasn't set up?? */
765         BUG_ON(!oldsbsec->initialized);
766
767         mutex_lock(&newsbsec->lock);
768
769         newsbsec->flags = oldsbsec->flags;
770
771         newsbsec->sid = oldsbsec->sid;
772         newsbsec->def_sid = oldsbsec->def_sid;
773         newsbsec->behavior = oldsbsec->behavior;
774
775         if (set_context) {
776                 u32 sid = oldsbsec->mntpoint_sid;
777
778                 if (!set_fscontext)
779                         newsbsec->sid = sid;
780                 if (!set_rootcontext) {
781                         struct inode *newinode = newsb->s_root->d_inode;
782                         struct inode_security_struct *newisec = newinode->i_security;
783                         newisec->sid = sid;
784                 }
785                 newsbsec->mntpoint_sid = sid;
786         }
787         if (set_rootcontext) {
788                 const struct inode *oldinode = oldsb->s_root->d_inode;
789                 const struct inode_security_struct *oldisec = oldinode->i_security;
790                 struct inode *newinode = newsb->s_root->d_inode;
791                 struct inode_security_struct *newisec = newinode->i_security;
792
793                 newisec->sid = oldisec->sid;
794         }
795
796         sb_finish_set_opts(newsb);
797         mutex_unlock(&newsbsec->lock);
798 }
799
800 /*
801  * string mount options parsing and call set the sbsec
802  */
803 static int superblock_doinit(struct super_block *sb, void *data)
804 {
805         char *context = NULL, *defcontext = NULL;
806         char *fscontext = NULL, *rootcontext = NULL;
807         int rc = 0;
808         char *p, *options = data;
809         /* selinux only know about a fixed number of mount options */
810         char *mnt_opts[NUM_SEL_MNT_OPTS];
811         int mnt_opts_flags[NUM_SEL_MNT_OPTS], num_mnt_opts = 0;
812
813         if (!data)
814                 goto out;
815
816         /* with the nfs patch this will become a goto out; */
817         if (sb->s_type->fs_flags & FS_BINARY_MOUNTDATA) {
818                 const char *name = sb->s_type->name;
819                 /* NFS we understand. */
820                 if (!strcmp(name, "nfs")) {
821                         struct nfs_mount_data *d = data;
822
823                         if (d->version !=  NFS_MOUNT_VERSION)
824                                 goto out;
825
826                         if (d->context[0]) {
827                                 context = kstrdup(d->context, GFP_KERNEL);
828                                 if (!context) {
829                                         rc = -ENOMEM;
830                                         goto out;
831                                 }
832                         }
833                         goto build_flags;
834                 } else
835                         goto out;
836         }
837
838         /* Standard string-based options. */
839         while ((p = strsep(&options, "|")) != NULL) {
840                 int token;
841                 substring_t args[MAX_OPT_ARGS];
842
843                 if (!*p)
844                         continue;
845
846                 token = match_token(p, tokens, args);
847
848                 switch (token) {
849                 case Opt_context:
850                         if (context || defcontext) {
851                                 rc = -EINVAL;
852                                 printk(KERN_WARNING SEL_MOUNT_FAIL_MSG);
853                                 goto out_err;
854                         }
855                         context = match_strdup(&args[0]);
856                         if (!context) {
857                                 rc = -ENOMEM;
858                                 goto out_err;
859                         }
860                         break;
861
862                 case Opt_fscontext:
863                         if (fscontext) {
864                                 rc = -EINVAL;
865                                 printk(KERN_WARNING SEL_MOUNT_FAIL_MSG);
866                                 goto out_err;
867                         }
868                         fscontext = match_strdup(&args[0]);
869                         if (!fscontext) {
870                                 rc = -ENOMEM;
871                                 goto out_err;
872                         }
873                         break;
874
875                 case Opt_rootcontext:
876                         if (rootcontext) {
877                                 rc = -EINVAL;
878                                 printk(KERN_WARNING SEL_MOUNT_FAIL_MSG);
879                                 goto out_err;
880                         }
881                         rootcontext = match_strdup(&args[0]);
882                         if (!rootcontext) {
883                                 rc = -ENOMEM;
884                                 goto out_err;
885                         }
886                         break;
887
888                 case Opt_defcontext:
889                         if (context || defcontext) {
890                                 rc = -EINVAL;
891                                 printk(KERN_WARNING SEL_MOUNT_FAIL_MSG);
892                                 goto out_err;
893                         }
894                         defcontext = match_strdup(&args[0]);
895                         if (!defcontext) {
896                                 rc = -ENOMEM;
897                                 goto out_err;
898                         }
899                         break;
900
901                 default:
902                         rc = -EINVAL;
903                         printk(KERN_WARNING "SELinux:  unknown mount option\n");
904                         goto out_err;
905
906                 }
907         }
908
909 build_flags:
910         if (fscontext) {
911                 mnt_opts[num_mnt_opts] = fscontext;
912                 mnt_opts_flags[num_mnt_opts++] = FSCONTEXT_MNT;
913         }
914         if (context) {
915                 mnt_opts[num_mnt_opts] = context;
916                 mnt_opts_flags[num_mnt_opts++] = CONTEXT_MNT;
917         }
918         if (rootcontext) {
919                 mnt_opts[num_mnt_opts] = rootcontext;
920                 mnt_opts_flags[num_mnt_opts++] = ROOTCONTEXT_MNT;
921         }
922         if (defcontext) {
923                 mnt_opts[num_mnt_opts] = defcontext;
924                 mnt_opts_flags[num_mnt_opts++] = DEFCONTEXT_MNT;
925         }
926
927 out:
928         rc = selinux_set_mnt_opts(sb, mnt_opts, mnt_opts_flags, num_mnt_opts);
929 out_err:
930         kfree(context);
931         kfree(defcontext);
932         kfree(fscontext);
933         kfree(rootcontext);
934         return rc;
935 }
936
937 static inline u16 inode_mode_to_security_class(umode_t mode)
938 {
939         switch (mode & S_IFMT) {
940         case S_IFSOCK:
941                 return SECCLASS_SOCK_FILE;
942         case S_IFLNK:
943                 return SECCLASS_LNK_FILE;
944         case S_IFREG:
945                 return SECCLASS_FILE;
946         case S_IFBLK:
947                 return SECCLASS_BLK_FILE;
948         case S_IFDIR:
949                 return SECCLASS_DIR;
950         case S_IFCHR:
951                 return SECCLASS_CHR_FILE;
952         case S_IFIFO:
953                 return SECCLASS_FIFO_FILE;
954
955         }
956
957         return SECCLASS_FILE;
958 }
959
960 static inline int default_protocol_stream(int protocol)
961 {
962         return (protocol == IPPROTO_IP || protocol == IPPROTO_TCP);
963 }
964
965 static inline int default_protocol_dgram(int protocol)
966 {
967         return (protocol == IPPROTO_IP || protocol == IPPROTO_UDP);
968 }
969
970 static inline u16 socket_type_to_security_class(int family, int type, int protocol)
971 {
972         switch (family) {
973         case PF_UNIX:
974                 switch (type) {
975                 case SOCK_STREAM:
976                 case SOCK_SEQPACKET:
977                         return SECCLASS_UNIX_STREAM_SOCKET;
978                 case SOCK_DGRAM:
979                         return SECCLASS_UNIX_DGRAM_SOCKET;
980                 }
981                 break;
982         case PF_INET:
983         case PF_INET6:
984                 switch (type) {
985                 case SOCK_STREAM:
986                         if (default_protocol_stream(protocol))
987                                 return SECCLASS_TCP_SOCKET;
988                         else
989                                 return SECCLASS_RAWIP_SOCKET;
990                 case SOCK_DGRAM:
991                         if (default_protocol_dgram(protocol))
992                                 return SECCLASS_UDP_SOCKET;
993                         else
994                                 return SECCLASS_RAWIP_SOCKET;
995                 case SOCK_DCCP:
996                         return SECCLASS_DCCP_SOCKET;
997                 default:
998                         return SECCLASS_RAWIP_SOCKET;
999                 }
1000                 break;
1001         case PF_NETLINK:
1002                 switch (protocol) {
1003                 case NETLINK_ROUTE:
1004                         return SECCLASS_NETLINK_ROUTE_SOCKET;
1005                 case NETLINK_FIREWALL:
1006                         return SECCLASS_NETLINK_FIREWALL_SOCKET;
1007                 case NETLINK_INET_DIAG:
1008                         return SECCLASS_NETLINK_TCPDIAG_SOCKET;
1009                 case NETLINK_NFLOG:
1010                         return SECCLASS_NETLINK_NFLOG_SOCKET;
1011                 case NETLINK_XFRM:
1012                         return SECCLASS_NETLINK_XFRM_SOCKET;
1013                 case NETLINK_SELINUX:
1014                         return SECCLASS_NETLINK_SELINUX_SOCKET;
1015                 case NETLINK_AUDIT:
1016                         return SECCLASS_NETLINK_AUDIT_SOCKET;
1017                 case NETLINK_IP6_FW:
1018                         return SECCLASS_NETLINK_IP6FW_SOCKET;
1019                 case NETLINK_DNRTMSG:
1020                         return SECCLASS_NETLINK_DNRT_SOCKET;
1021                 case NETLINK_KOBJECT_UEVENT:
1022                         return SECCLASS_NETLINK_KOBJECT_UEVENT_SOCKET;
1023                 default:
1024                         return SECCLASS_NETLINK_SOCKET;
1025                 }
1026         case PF_PACKET:
1027                 return SECCLASS_PACKET_SOCKET;
1028         case PF_KEY:
1029                 return SECCLASS_KEY_SOCKET;
1030         case PF_APPLETALK:
1031                 return SECCLASS_APPLETALK_SOCKET;
1032         }
1033
1034         return SECCLASS_SOCKET;
1035 }
1036
1037 #ifdef CONFIG_PROC_FS
1038 static int selinux_proc_get_sid(struct proc_dir_entry *de,
1039                                 u16 tclass,
1040                                 u32 *sid)
1041 {
1042         int buflen, rc;
1043         char *buffer, *path, *end;
1044
1045         buffer = (char*)__get_free_page(GFP_KERNEL);
1046         if (!buffer)
1047                 return -ENOMEM;
1048
1049         buflen = PAGE_SIZE;
1050         end = buffer+buflen;
1051         *--end = '\0';
1052         buflen--;
1053         path = end-1;
1054         *path = '/';
1055         while (de && de != de->parent) {
1056                 buflen -= de->namelen + 1;
1057                 if (buflen < 0)
1058                         break;
1059                 end -= de->namelen;
1060                 memcpy(end, de->name, de->namelen);
1061                 *--end = '/';
1062                 path = end;
1063                 de = de->parent;
1064         }
1065         rc = security_genfs_sid("proc", path, tclass, sid);
1066         free_page((unsigned long)buffer);
1067         return rc;
1068 }
1069 #else
1070 static int selinux_proc_get_sid(struct proc_dir_entry *de,
1071                                 u16 tclass,
1072                                 u32 *sid)
1073 {
1074         return -EINVAL;
1075 }
1076 #endif
1077
1078 /* The inode's security attributes must be initialized before first use. */
1079 static int inode_doinit_with_dentry(struct inode *inode, struct dentry *opt_dentry)
1080 {
1081         struct superblock_security_struct *sbsec = NULL;
1082         struct inode_security_struct *isec = inode->i_security;
1083         u32 sid;
1084         struct dentry *dentry;
1085 #define INITCONTEXTLEN 255
1086         char *context = NULL;
1087         unsigned len = 0;
1088         int rc = 0;
1089
1090         if (isec->initialized)
1091                 goto out;
1092
1093         mutex_lock(&isec->lock);
1094         if (isec->initialized)
1095                 goto out_unlock;
1096
1097         sbsec = inode->i_sb->s_security;
1098         if (!sbsec->initialized) {
1099                 /* Defer initialization until selinux_complete_init,
1100                    after the initial policy is loaded and the security
1101                    server is ready to handle calls. */
1102                 spin_lock(&sbsec->isec_lock);
1103                 if (list_empty(&isec->list))
1104                         list_add(&isec->list, &sbsec->isec_head);
1105                 spin_unlock(&sbsec->isec_lock);
1106                 goto out_unlock;
1107         }
1108
1109         switch (sbsec->behavior) {
1110         case SECURITY_FS_USE_XATTR:
1111                 if (!inode->i_op->getxattr) {
1112                         isec->sid = sbsec->def_sid;
1113                         break;
1114                 }
1115
1116                 /* Need a dentry, since the xattr API requires one.
1117                    Life would be simpler if we could just pass the inode. */
1118                 if (opt_dentry) {
1119                         /* Called from d_instantiate or d_splice_alias. */
1120                         dentry = dget(opt_dentry);
1121                 } else {
1122                         /* Called from selinux_complete_init, try to find a dentry. */
1123                         dentry = d_find_alias(inode);
1124                 }
1125                 if (!dentry) {
1126                         printk(KERN_WARNING "%s:  no dentry for dev=%s "
1127                                "ino=%ld\n", __FUNCTION__, inode->i_sb->s_id,
1128                                inode->i_ino);
1129                         goto out_unlock;
1130                 }
1131
1132                 len = INITCONTEXTLEN;
1133                 context = kmalloc(len, GFP_KERNEL);
1134                 if (!context) {
1135                         rc = -ENOMEM;
1136                         dput(dentry);
1137                         goto out_unlock;
1138                 }
1139                 rc = inode->i_op->getxattr(dentry, XATTR_NAME_SELINUX,
1140                                            context, len);
1141                 if (rc == -ERANGE) {
1142                         /* Need a larger buffer.  Query for the right size. */
1143                         rc = inode->i_op->getxattr(dentry, XATTR_NAME_SELINUX,
1144                                                    NULL, 0);
1145                         if (rc < 0) {
1146                                 dput(dentry);
1147                                 goto out_unlock;
1148                         }
1149                         kfree(context);
1150                         len = rc;
1151                         context = kmalloc(len, GFP_KERNEL);
1152                         if (!context) {
1153                                 rc = -ENOMEM;
1154                                 dput(dentry);
1155                                 goto out_unlock;
1156                         }
1157                         rc = inode->i_op->getxattr(dentry,
1158                                                    XATTR_NAME_SELINUX,
1159                                                    context, len);
1160                 }
1161                 dput(dentry);
1162                 if (rc < 0) {
1163                         if (rc != -ENODATA) {
1164                                 printk(KERN_WARNING "%s:  getxattr returned "
1165                                        "%d for dev=%s ino=%ld\n", __FUNCTION__,
1166                                        -rc, inode->i_sb->s_id, inode->i_ino);
1167                                 kfree(context);
1168                                 goto out_unlock;
1169                         }
1170                         /* Map ENODATA to the default file SID */
1171                         sid = sbsec->def_sid;
1172                         rc = 0;
1173                 } else {
1174                         rc = security_context_to_sid_default(context, rc, &sid,
1175                                                              sbsec->def_sid);
1176                         if (rc) {
1177                                 printk(KERN_WARNING "%s:  context_to_sid(%s) "
1178                                        "returned %d for dev=%s ino=%ld\n",
1179                                        __FUNCTION__, context, -rc,
1180                                        inode->i_sb->s_id, inode->i_ino);
1181                                 kfree(context);
1182                                 /* Leave with the unlabeled SID */
1183                                 rc = 0;
1184                                 break;
1185                         }
1186                 }
1187                 kfree(context);
1188                 isec->sid = sid;
1189                 break;
1190         case SECURITY_FS_USE_TASK:
1191                 isec->sid = isec->task_sid;
1192                 break;
1193         case SECURITY_FS_USE_TRANS:
1194                 /* Default to the fs SID. */
1195                 isec->sid = sbsec->sid;
1196
1197                 /* Try to obtain a transition SID. */
1198                 isec->sclass = inode_mode_to_security_class(inode->i_mode);
1199                 rc = security_transition_sid(isec->task_sid,
1200                                              sbsec->sid,
1201                                              isec->sclass,
1202                                              &sid);
1203                 if (rc)
1204                         goto out_unlock;
1205                 isec->sid = sid;
1206                 break;
1207         case SECURITY_FS_USE_MNTPOINT:
1208                 isec->sid = sbsec->mntpoint_sid;
1209                 break;
1210         default:
1211                 /* Default to the fs superblock SID. */
1212                 isec->sid = sbsec->sid;
1213
1214                 if (sbsec->proc) {
1215                         struct proc_inode *proci = PROC_I(inode);
1216                         if (proci->pde) {
1217                                 isec->sclass = inode_mode_to_security_class(inode->i_mode);
1218                                 rc = selinux_proc_get_sid(proci->pde,
1219                                                           isec->sclass,
1220                                                           &sid);
1221                                 if (rc)
1222                                         goto out_unlock;
1223                                 isec->sid = sid;
1224                         }
1225                 }
1226                 break;
1227         }
1228
1229         isec->initialized = 1;
1230
1231 out_unlock:
1232         mutex_unlock(&isec->lock);
1233 out:
1234         if (isec->sclass == SECCLASS_FILE)
1235                 isec->sclass = inode_mode_to_security_class(inode->i_mode);
1236         return rc;
1237 }
1238
1239 /* Convert a Linux signal to an access vector. */
1240 static inline u32 signal_to_av(int sig)
1241 {
1242         u32 perm = 0;
1243
1244         switch (sig) {
1245         case SIGCHLD:
1246                 /* Commonly granted from child to parent. */
1247                 perm = PROCESS__SIGCHLD;
1248                 break;
1249         case SIGKILL:
1250                 /* Cannot be caught or ignored */
1251                 perm = PROCESS__SIGKILL;
1252                 break;
1253         case SIGSTOP:
1254                 /* Cannot be caught or ignored */
1255                 perm = PROCESS__SIGSTOP;
1256                 break;
1257         default:
1258                 /* All other signals. */
1259                 perm = PROCESS__SIGNAL;
1260                 break;
1261         }
1262
1263         return perm;
1264 }
1265
1266 /* Check permission betweeen a pair of tasks, e.g. signal checks,
1267    fork check, ptrace check, etc. */
1268 static int task_has_perm(struct task_struct *tsk1,
1269                          struct task_struct *tsk2,
1270                          u32 perms)
1271 {
1272         struct task_security_struct *tsec1, *tsec2;
1273
1274         tsec1 = tsk1->security;
1275         tsec2 = tsk2->security;
1276         return avc_has_perm(tsec1->sid, tsec2->sid,
1277                             SECCLASS_PROCESS, perms, NULL);
1278 }
1279
1280 /* Check whether a task is allowed to use a capability. */
1281 static int task_has_capability(struct task_struct *tsk,
1282                                int cap)
1283 {
1284         struct task_security_struct *tsec;
1285         struct avc_audit_data ad;
1286
1287         tsec = tsk->security;
1288
1289         AVC_AUDIT_DATA_INIT(&ad,CAP);
1290         ad.tsk = tsk;
1291         ad.u.cap = cap;
1292
1293         return avc_has_perm(tsec->sid, tsec->sid,
1294                             SECCLASS_CAPABILITY, CAP_TO_MASK(cap), &ad);
1295 }
1296
1297 /* Check whether a task is allowed to use a system operation. */
1298 static int task_has_system(struct task_struct *tsk,
1299                            u32 perms)
1300 {
1301         struct task_security_struct *tsec;
1302
1303         tsec = tsk->security;
1304
1305         return avc_has_perm(tsec->sid, SECINITSID_KERNEL,
1306                             SECCLASS_SYSTEM, perms, NULL);
1307 }
1308
1309 /* Check whether a task has a particular permission to an inode.
1310    The 'adp' parameter is optional and allows other audit
1311    data to be passed (e.g. the dentry). */
1312 static int inode_has_perm(struct task_struct *tsk,
1313                           struct inode *inode,
1314                           u32 perms,
1315                           struct avc_audit_data *adp)
1316 {
1317         struct task_security_struct *tsec;
1318         struct inode_security_struct *isec;
1319         struct avc_audit_data ad;
1320
1321         if (unlikely (IS_PRIVATE (inode)))
1322                 return 0;
1323
1324         tsec = tsk->security;
1325         isec = inode->i_security;
1326
1327         if (!adp) {
1328                 adp = &ad;
1329                 AVC_AUDIT_DATA_INIT(&ad, FS);
1330                 ad.u.fs.inode = inode;
1331         }
1332
1333         return avc_has_perm(tsec->sid, isec->sid, isec->sclass, perms, adp);
1334 }
1335
1336 /* Same as inode_has_perm, but pass explicit audit data containing
1337    the dentry to help the auditing code to more easily generate the
1338    pathname if needed. */
1339 static inline int dentry_has_perm(struct task_struct *tsk,
1340                                   struct vfsmount *mnt,
1341                                   struct dentry *dentry,
1342                                   u32 av)
1343 {
1344         struct inode *inode = dentry->d_inode;
1345         struct avc_audit_data ad;
1346         AVC_AUDIT_DATA_INIT(&ad,FS);
1347         ad.u.fs.mnt = mnt;
1348         ad.u.fs.dentry = dentry;
1349         return inode_has_perm(tsk, inode, av, &ad);
1350 }
1351
1352 /* Check whether a task can use an open file descriptor to
1353    access an inode in a given way.  Check access to the
1354    descriptor itself, and then use dentry_has_perm to
1355    check a particular permission to the file.
1356    Access to the descriptor is implicitly granted if it
1357    has the same SID as the process.  If av is zero, then
1358    access to the file is not checked, e.g. for cases
1359    where only the descriptor is affected like seek. */
1360 static int file_has_perm(struct task_struct *tsk,
1361                                 struct file *file,
1362                                 u32 av)
1363 {
1364         struct task_security_struct *tsec = tsk->security;
1365         struct file_security_struct *fsec = file->f_security;
1366         struct vfsmount *mnt = file->f_path.mnt;
1367         struct dentry *dentry = file->f_path.dentry;
1368         struct inode *inode = dentry->d_inode;
1369         struct avc_audit_data ad;
1370         int rc;
1371
1372         AVC_AUDIT_DATA_INIT(&ad, FS);
1373         ad.u.fs.mnt = mnt;
1374         ad.u.fs.dentry = dentry;
1375
1376         if (tsec->sid != fsec->sid) {
1377                 rc = avc_has_perm(tsec->sid, fsec->sid,
1378                                   SECCLASS_FD,
1379                                   FD__USE,
1380                                   &ad);
1381                 if (rc)
1382                         return rc;
1383         }
1384
1385         /* av is zero if only checking access to the descriptor. */
1386         if (av)
1387                 return inode_has_perm(tsk, inode, av, &ad);
1388
1389         return 0;
1390 }
1391
1392 /* Check whether a task can create a file. */
1393 static int may_create(struct inode *dir,
1394                       struct dentry *dentry,
1395                       u16 tclass)
1396 {
1397         struct task_security_struct *tsec;
1398         struct inode_security_struct *dsec;
1399         struct superblock_security_struct *sbsec;
1400         u32 newsid;
1401         struct avc_audit_data ad;
1402         int rc;
1403
1404         tsec = current->security;
1405         dsec = dir->i_security;
1406         sbsec = dir->i_sb->s_security;
1407
1408         AVC_AUDIT_DATA_INIT(&ad, FS);
1409         ad.u.fs.dentry = dentry;
1410
1411         rc = avc_has_perm(tsec->sid, dsec->sid, SECCLASS_DIR,
1412                           DIR__ADD_NAME | DIR__SEARCH,
1413                           &ad);
1414         if (rc)
1415                 return rc;
1416
1417         if (tsec->create_sid && sbsec->behavior != SECURITY_FS_USE_MNTPOINT) {
1418                 newsid = tsec->create_sid;
1419         } else {
1420                 rc = security_transition_sid(tsec->sid, dsec->sid, tclass,
1421                                              &newsid);
1422                 if (rc)
1423                         return rc;
1424         }
1425
1426         rc = avc_has_perm(tsec->sid, newsid, tclass, FILE__CREATE, &ad);
1427         if (rc)
1428                 return rc;
1429
1430         return avc_has_perm(newsid, sbsec->sid,
1431                             SECCLASS_FILESYSTEM,
1432                             FILESYSTEM__ASSOCIATE, &ad);
1433 }
1434
1435 /* Check whether a task can create a key. */
1436 static int may_create_key(u32 ksid,
1437                           struct task_struct *ctx)
1438 {
1439         struct task_security_struct *tsec;
1440
1441         tsec = ctx->security;
1442
1443         return avc_has_perm(tsec->sid, ksid, SECCLASS_KEY, KEY__CREATE, NULL);
1444 }
1445
1446 #define MAY_LINK   0
1447 #define MAY_UNLINK 1
1448 #define MAY_RMDIR  2
1449
1450 /* Check whether a task can link, unlink, or rmdir a file/directory. */
1451 static int may_link(struct inode *dir,
1452                     struct dentry *dentry,
1453                     int kind)
1454
1455 {
1456         struct task_security_struct *tsec;
1457         struct inode_security_struct *dsec, *isec;
1458         struct avc_audit_data ad;
1459         u32 av;
1460         int rc;
1461
1462         tsec = current->security;
1463         dsec = dir->i_security;
1464         isec = dentry->d_inode->i_security;
1465
1466         AVC_AUDIT_DATA_INIT(&ad, FS);
1467         ad.u.fs.dentry = dentry;
1468
1469         av = DIR__SEARCH;
1470         av |= (kind ? DIR__REMOVE_NAME : DIR__ADD_NAME);
1471         rc = avc_has_perm(tsec->sid, dsec->sid, SECCLASS_DIR, av, &ad);
1472         if (rc)
1473                 return rc;
1474
1475         switch (kind) {
1476         case MAY_LINK:
1477                 av = FILE__LINK;
1478                 break;
1479         case MAY_UNLINK:
1480                 av = FILE__UNLINK;
1481                 break;
1482         case MAY_RMDIR:
1483                 av = DIR__RMDIR;
1484                 break;
1485         default:
1486                 printk(KERN_WARNING "may_link:  unrecognized kind %d\n", kind);
1487                 return 0;
1488         }
1489
1490         rc = avc_has_perm(tsec->sid, isec->sid, isec->sclass, av, &ad);
1491         return rc;
1492 }
1493
1494 static inline int may_rename(struct inode *old_dir,
1495                              struct dentry *old_dentry,
1496                              struct inode *new_dir,
1497                              struct dentry *new_dentry)
1498 {
1499         struct task_security_struct *tsec;
1500         struct inode_security_struct *old_dsec, *new_dsec, *old_isec, *new_isec;
1501         struct avc_audit_data ad;
1502         u32 av;
1503         int old_is_dir, new_is_dir;
1504         int rc;
1505
1506         tsec = current->security;
1507         old_dsec = old_dir->i_security;
1508         old_isec = old_dentry->d_inode->i_security;
1509         old_is_dir = S_ISDIR(old_dentry->d_inode->i_mode);
1510         new_dsec = new_dir->i_security;
1511
1512         AVC_AUDIT_DATA_INIT(&ad, FS);
1513
1514         ad.u.fs.dentry = old_dentry;
1515         rc = avc_has_perm(tsec->sid, old_dsec->sid, SECCLASS_DIR,
1516                           DIR__REMOVE_NAME | DIR__SEARCH, &ad);
1517         if (rc)
1518                 return rc;
1519         rc = avc_has_perm(tsec->sid, old_isec->sid,
1520                           old_isec->sclass, FILE__RENAME, &ad);
1521         if (rc)
1522                 return rc;
1523         if (old_is_dir && new_dir != old_dir) {
1524                 rc = avc_has_perm(tsec->sid, old_isec->sid,
1525                                   old_isec->sclass, DIR__REPARENT, &ad);
1526                 if (rc)
1527                         return rc;
1528         }
1529
1530         ad.u.fs.dentry = new_dentry;
1531         av = DIR__ADD_NAME | DIR__SEARCH;
1532         if (new_dentry->d_inode)
1533                 av |= DIR__REMOVE_NAME;
1534         rc = avc_has_perm(tsec->sid, new_dsec->sid, SECCLASS_DIR, av, &ad);
1535         if (rc)
1536                 return rc;
1537         if (new_dentry->d_inode) {
1538                 new_isec = new_dentry->d_inode->i_security;
1539                 new_is_dir = S_ISDIR(new_dentry->d_inode->i_mode);
1540                 rc = avc_has_perm(tsec->sid, new_isec->sid,
1541                                   new_isec->sclass,
1542                                   (new_is_dir ? DIR__RMDIR : FILE__UNLINK), &ad);
1543                 if (rc)
1544                         return rc;
1545         }
1546
1547         return 0;
1548 }
1549
1550 /* Check whether a task can perform a filesystem operation. */
1551 static int superblock_has_perm(struct task_struct *tsk,
1552                                struct super_block *sb,
1553                                u32 perms,
1554                                struct avc_audit_data *ad)
1555 {
1556         struct task_security_struct *tsec;
1557         struct superblock_security_struct *sbsec;
1558
1559         tsec = tsk->security;
1560         sbsec = sb->s_security;
1561         return avc_has_perm(tsec->sid, sbsec->sid, SECCLASS_FILESYSTEM,
1562                             perms, ad);
1563 }
1564
1565 /* Convert a Linux mode and permission mask to an access vector. */
1566 static inline u32 file_mask_to_av(int mode, int mask)
1567 {
1568         u32 av = 0;
1569
1570         if ((mode & S_IFMT) != S_IFDIR) {
1571                 if (mask & MAY_EXEC)
1572                         av |= FILE__EXECUTE;
1573                 if (mask & MAY_READ)
1574                         av |= FILE__READ;
1575
1576                 if (mask & MAY_APPEND)
1577                         av |= FILE__APPEND;
1578                 else if (mask & MAY_WRITE)
1579                         av |= FILE__WRITE;
1580
1581         } else {
1582                 if (mask & MAY_EXEC)
1583                         av |= DIR__SEARCH;
1584                 if (mask & MAY_WRITE)
1585                         av |= DIR__WRITE;
1586                 if (mask & MAY_READ)
1587                         av |= DIR__READ;
1588         }
1589
1590         return av;
1591 }
1592
1593 /* Convert a Linux file to an access vector. */
1594 static inline u32 file_to_av(struct file *file)
1595 {
1596         u32 av = 0;
1597
1598         if (file->f_mode & FMODE_READ)
1599                 av |= FILE__READ;
1600         if (file->f_mode & FMODE_WRITE) {
1601                 if (file->f_flags & O_APPEND)
1602                         av |= FILE__APPEND;
1603                 else
1604                         av |= FILE__WRITE;
1605         }
1606
1607         return av;
1608 }
1609
1610 /* Hook functions begin here. */
1611
1612 static int selinux_ptrace(struct task_struct *parent, struct task_struct *child)
1613 {
1614         struct task_security_struct *psec = parent->security;
1615         struct task_security_struct *csec = child->security;
1616         int rc;
1617
1618         rc = secondary_ops->ptrace(parent,child);
1619         if (rc)
1620                 return rc;
1621
1622         rc = task_has_perm(parent, child, PROCESS__PTRACE);
1623         /* Save the SID of the tracing process for later use in apply_creds. */
1624         if (!(child->ptrace & PT_PTRACED) && !rc)
1625                 csec->ptrace_sid = psec->sid;
1626         return rc;
1627 }
1628
1629 static int selinux_capget(struct task_struct *target, kernel_cap_t *effective,
1630                           kernel_cap_t *inheritable, kernel_cap_t *permitted)
1631 {
1632         int error;
1633
1634         error = task_has_perm(current, target, PROCESS__GETCAP);
1635         if (error)
1636                 return error;
1637
1638         return secondary_ops->capget(target, effective, inheritable, permitted);
1639 }
1640
1641 static int selinux_capset_check(struct task_struct *target, kernel_cap_t *effective,
1642                                 kernel_cap_t *inheritable, kernel_cap_t *permitted)
1643 {
1644         int error;
1645
1646         error = secondary_ops->capset_check(target, effective, inheritable, permitted);
1647         if (error)
1648                 return error;
1649
1650         return task_has_perm(current, target, PROCESS__SETCAP);
1651 }
1652
1653 static void selinux_capset_set(struct task_struct *target, kernel_cap_t *effective,
1654                                kernel_cap_t *inheritable, kernel_cap_t *permitted)
1655 {
1656         secondary_ops->capset_set(target, effective, inheritable, permitted);
1657 }
1658
1659 static int selinux_capable(struct task_struct *tsk, int cap)
1660 {
1661         int rc;
1662
1663         rc = secondary_ops->capable(tsk, cap);
1664         if (rc)
1665                 return rc;
1666
1667         return task_has_capability(tsk,cap);
1668 }
1669
1670 static int selinux_sysctl_get_sid(ctl_table *table, u16 tclass, u32 *sid)
1671 {
1672         int buflen, rc;
1673         char *buffer, *path, *end;
1674
1675         rc = -ENOMEM;
1676         buffer = (char*)__get_free_page(GFP_KERNEL);
1677         if (!buffer)
1678                 goto out;
1679
1680         buflen = PAGE_SIZE;
1681         end = buffer+buflen;
1682         *--end = '\0';
1683         buflen--;
1684         path = end-1;
1685         *path = '/';
1686         while (table) {
1687                 const char *name = table->procname;
1688                 size_t namelen = strlen(name);
1689                 buflen -= namelen + 1;
1690                 if (buflen < 0)
1691                         goto out_free;
1692                 end -= namelen;
1693                 memcpy(end, name, namelen);
1694                 *--end = '/';
1695                 path = end;
1696                 table = table->parent;
1697         }
1698         buflen -= 4;
1699         if (buflen < 0)
1700                 goto out_free;
1701         end -= 4;
1702         memcpy(end, "/sys", 4);
1703         path = end;
1704         rc = security_genfs_sid("proc", path, tclass, sid);
1705 out_free:
1706         free_page((unsigned long)buffer);
1707 out:
1708         return rc;
1709 }
1710
1711 static int selinux_sysctl(ctl_table *table, int op)
1712 {
1713         int error = 0;
1714         u32 av;
1715         struct task_security_struct *tsec;
1716         u32 tsid;
1717         int rc;
1718
1719         rc = secondary_ops->sysctl(table, op);
1720         if (rc)
1721                 return rc;
1722
1723         tsec = current->security;
1724
1725         rc = selinux_sysctl_get_sid(table, (op == 0001) ?
1726                                     SECCLASS_DIR : SECCLASS_FILE, &tsid);
1727         if (rc) {
1728                 /* Default to the well-defined sysctl SID. */
1729                 tsid = SECINITSID_SYSCTL;
1730         }
1731
1732         /* The op values are "defined" in sysctl.c, thereby creating
1733          * a bad coupling between this module and sysctl.c */
1734         if(op == 001) {
1735                 error = avc_has_perm(tsec->sid, tsid,
1736                                      SECCLASS_DIR, DIR__SEARCH, NULL);
1737         } else {
1738                 av = 0;
1739                 if (op & 004)
1740                         av |= FILE__READ;
1741                 if (op & 002)
1742                         av |= FILE__WRITE;
1743                 if (av)
1744                         error = avc_has_perm(tsec->sid, tsid,
1745                                              SECCLASS_FILE, av, NULL);
1746         }
1747
1748         return error;
1749 }
1750
1751 static int selinux_quotactl(int cmds, int type, int id, struct super_block *sb)
1752 {
1753         int rc = 0;
1754
1755         if (!sb)
1756                 return 0;
1757
1758         switch (cmds) {
1759                 case Q_SYNC:
1760                 case Q_QUOTAON:
1761                 case Q_QUOTAOFF:
1762                 case Q_SETINFO:
1763                 case Q_SETQUOTA:
1764                         rc = superblock_has_perm(current,
1765                                                  sb,
1766                                                  FILESYSTEM__QUOTAMOD, NULL);
1767                         break;
1768                 case Q_GETFMT:
1769                 case Q_GETINFO:
1770                 case Q_GETQUOTA:
1771                         rc = superblock_has_perm(current,
1772                                                  sb,
1773                                                  FILESYSTEM__QUOTAGET, NULL);
1774                         break;
1775                 default:
1776                         rc = 0;  /* let the kernel handle invalid cmds */
1777                         break;
1778         }
1779         return rc;
1780 }
1781
1782 static int selinux_quota_on(struct dentry *dentry)
1783 {
1784         return dentry_has_perm(current, NULL, dentry, FILE__QUOTAON);
1785 }
1786
1787 static int selinux_syslog(int type)
1788 {
1789         int rc;
1790
1791         rc = secondary_ops->syslog(type);
1792         if (rc)
1793                 return rc;
1794
1795         switch (type) {
1796                 case 3:         /* Read last kernel messages */
1797                 case 10:        /* Return size of the log buffer */
1798                         rc = task_has_system(current, SYSTEM__SYSLOG_READ);
1799                         break;
1800                 case 6:         /* Disable logging to console */
1801                 case 7:         /* Enable logging to console */
1802                 case 8:         /* Set level of messages printed to console */
1803                         rc = task_has_system(current, SYSTEM__SYSLOG_CONSOLE);
1804                         break;
1805                 case 0:         /* Close log */
1806                 case 1:         /* Open log */
1807                 case 2:         /* Read from log */
1808                 case 4:         /* Read/clear last kernel messages */
1809                 case 5:         /* Clear ring buffer */
1810                 default:
1811                         rc = task_has_system(current, SYSTEM__SYSLOG_MOD);
1812                         break;
1813         }
1814         return rc;
1815 }
1816
1817 /*
1818  * Check that a process has enough memory to allocate a new virtual
1819  * mapping. 0 means there is enough memory for the allocation to
1820  * succeed and -ENOMEM implies there is not.
1821  *
1822  * Note that secondary_ops->capable and task_has_perm_noaudit return 0
1823  * if the capability is granted, but __vm_enough_memory requires 1 if
1824  * the capability is granted.
1825  *
1826  * Do not audit the selinux permission check, as this is applied to all
1827  * processes that allocate mappings.
1828  */
1829 static int selinux_vm_enough_memory(struct mm_struct *mm, long pages)
1830 {
1831         int rc, cap_sys_admin = 0;
1832         struct task_security_struct *tsec = current->security;
1833
1834         rc = secondary_ops->capable(current, CAP_SYS_ADMIN);
1835         if (rc == 0)
1836                 rc = avc_has_perm_noaudit(tsec->sid, tsec->sid,
1837                                           SECCLASS_CAPABILITY,
1838                                           CAP_TO_MASK(CAP_SYS_ADMIN),
1839                                           0,
1840                                           NULL);
1841
1842         if (rc == 0)
1843                 cap_sys_admin = 1;
1844
1845         return __vm_enough_memory(mm, pages, cap_sys_admin);
1846 }
1847
1848 /* binprm security operations */
1849
1850 static int selinux_bprm_alloc_security(struct linux_binprm *bprm)
1851 {
1852         struct bprm_security_struct *bsec;
1853
1854         bsec = kzalloc(sizeof(struct bprm_security_struct), GFP_KERNEL);
1855         if (!bsec)
1856                 return -ENOMEM;
1857
1858         bsec->bprm = bprm;
1859         bsec->sid = SECINITSID_UNLABELED;
1860         bsec->set = 0;
1861
1862         bprm->security = bsec;
1863         return 0;
1864 }
1865
1866 static int selinux_bprm_set_security(struct linux_binprm *bprm)
1867 {
1868         struct task_security_struct *tsec;
1869         struct inode *inode = bprm->file->f_path.dentry->d_inode;
1870         struct inode_security_struct *isec;
1871         struct bprm_security_struct *bsec;
1872         u32 newsid;
1873         struct avc_audit_data ad;
1874         int rc;
1875
1876         rc = secondary_ops->bprm_set_security(bprm);
1877         if (rc)
1878                 return rc;
1879
1880         bsec = bprm->security;
1881
1882         if (bsec->set)
1883                 return 0;
1884
1885         tsec = current->security;
1886         isec = inode->i_security;
1887
1888         /* Default to the current task SID. */
1889         bsec->sid = tsec->sid;
1890
1891         /* Reset fs, key, and sock SIDs on execve. */
1892         tsec->create_sid = 0;
1893         tsec->keycreate_sid = 0;
1894         tsec->sockcreate_sid = 0;
1895
1896         if (tsec->exec_sid) {
1897                 newsid = tsec->exec_sid;
1898                 /* Reset exec SID on execve. */
1899                 tsec->exec_sid = 0;
1900         } else {
1901                 /* Check for a default transition on this program. */
1902                 rc = security_transition_sid(tsec->sid, isec->sid,
1903                                              SECCLASS_PROCESS, &newsid);
1904                 if (rc)
1905                         return rc;
1906         }
1907
1908         AVC_AUDIT_DATA_INIT(&ad, FS);
1909         ad.u.fs.mnt = bprm->file->f_path.mnt;
1910         ad.u.fs.dentry = bprm->file->f_path.dentry;
1911
1912         if (bprm->file->f_path.mnt->mnt_flags & MNT_NOSUID)
1913                 newsid = tsec->sid;
1914
1915         if (tsec->sid == newsid) {
1916                 rc = avc_has_perm(tsec->sid, isec->sid,
1917                                   SECCLASS_FILE, FILE__EXECUTE_NO_TRANS, &ad);
1918                 if (rc)
1919                         return rc;
1920         } else {
1921                 /* Check permissions for the transition. */
1922                 rc = avc_has_perm(tsec->sid, newsid,
1923                                   SECCLASS_PROCESS, PROCESS__TRANSITION, &ad);
1924                 if (rc)
1925                         return rc;
1926
1927                 rc = avc_has_perm(newsid, isec->sid,
1928                                   SECCLASS_FILE, FILE__ENTRYPOINT, &ad);
1929                 if (rc)
1930                         return rc;
1931
1932                 /* Clear any possibly unsafe personality bits on exec: */
1933                 current->personality &= ~PER_CLEAR_ON_SETID;
1934
1935                 /* Set the security field to the new SID. */
1936                 bsec->sid = newsid;
1937         }
1938
1939         bsec->set = 1;
1940         return 0;
1941 }
1942
1943 static int selinux_bprm_check_security (struct linux_binprm *bprm)
1944 {
1945         return secondary_ops->bprm_check_security(bprm);
1946 }
1947
1948
1949 static int selinux_bprm_secureexec (struct linux_binprm *bprm)
1950 {
1951         struct task_security_struct *tsec = current->security;
1952         int atsecure = 0;
1953
1954         if (tsec->osid != tsec->sid) {
1955                 /* Enable secure mode for SIDs transitions unless
1956                    the noatsecure permission is granted between
1957                    the two SIDs, i.e. ahp returns 0. */
1958                 atsecure = avc_has_perm(tsec->osid, tsec->sid,
1959                                          SECCLASS_PROCESS,
1960                                          PROCESS__NOATSECURE, NULL);
1961         }
1962
1963         return (atsecure || secondary_ops->bprm_secureexec(bprm));
1964 }
1965
1966 static void selinux_bprm_free_security(struct linux_binprm *bprm)
1967 {
1968         kfree(bprm->security);
1969         bprm->security = NULL;
1970 }
1971
1972 extern struct vfsmount *selinuxfs_mount;
1973 extern struct dentry *selinux_null;
1974
1975 /* Derived from fs/exec.c:flush_old_files. */
1976 static inline void flush_unauthorized_files(struct files_struct * files)
1977 {
1978         struct avc_audit_data ad;
1979         struct file *file, *devnull = NULL;
1980         struct tty_struct *tty;
1981         struct fdtable *fdt;
1982         long j = -1;
1983         int drop_tty = 0;
1984
1985         mutex_lock(&tty_mutex);
1986         tty = get_current_tty();
1987         if (tty) {
1988                 file_list_lock();
1989                 file = list_entry(tty->tty_files.next, typeof(*file), f_u.fu_list);
1990                 if (file) {
1991                         /* Revalidate access to controlling tty.
1992                            Use inode_has_perm on the tty inode directly rather
1993                            than using file_has_perm, as this particular open
1994                            file may belong to another process and we are only
1995                            interested in the inode-based check here. */
1996                         struct inode *inode = file->f_path.dentry->d_inode;
1997                         if (inode_has_perm(current, inode,
1998                                            FILE__READ | FILE__WRITE, NULL)) {
1999                                 drop_tty = 1;
2000                         }
2001                 }
2002                 file_list_unlock();
2003         }
2004         mutex_unlock(&tty_mutex);
2005         /* Reset controlling tty. */
2006         if (drop_tty)
2007                 no_tty();
2008
2009         /* Revalidate access to inherited open files. */
2010
2011         AVC_AUDIT_DATA_INIT(&ad,FS);
2012
2013         spin_lock(&files->file_lock);
2014         for (;;) {
2015                 unsigned long set, i;
2016                 int fd;
2017
2018                 j++;
2019                 i = j * __NFDBITS;
2020                 fdt = files_fdtable(files);
2021                 if (i >= fdt->max_fds)
2022                         break;
2023                 set = fdt->open_fds->fds_bits[j];
2024                 if (!set)
2025                         continue;
2026                 spin_unlock(&files->file_lock);
2027                 for ( ; set ; i++,set >>= 1) {
2028                         if (set & 1) {
2029                                 file = fget(i);
2030                                 if (!file)
2031                                         continue;
2032                                 if (file_has_perm(current,
2033                                                   file,
2034                                                   file_to_av(file))) {
2035                                         sys_close(i);
2036                                         fd = get_unused_fd();
2037                                         if (fd != i) {
2038                                                 if (fd >= 0)
2039                                                         put_unused_fd(fd);
2040                                                 fput(file);
2041                                                 continue;
2042                                         }
2043                                         if (devnull) {
2044                                                 get_file(devnull);
2045                                         } else {
2046                                                 devnull = dentry_open(dget(selinux_null), mntget(selinuxfs_mount), O_RDWR);
2047                                                 if (IS_ERR(devnull)) {
2048                                                         devnull = NULL;
2049                                                         put_unused_fd(fd);
2050                                                         fput(file);
2051                                                         continue;
2052                                                 }
2053                                         }
2054                                         fd_install(fd, devnull);
2055                                 }
2056                                 fput(file);
2057                         }
2058                 }
2059                 spin_lock(&files->file_lock);
2060
2061         }
2062         spin_unlock(&files->file_lock);
2063 }
2064
2065 static void selinux_bprm_apply_creds(struct linux_binprm *bprm, int unsafe)
2066 {
2067         struct task_security_struct *tsec;
2068         struct bprm_security_struct *bsec;
2069         u32 sid;
2070         int rc;
2071
2072         secondary_ops->bprm_apply_creds(bprm, unsafe);
2073
2074         tsec = current->security;
2075
2076         bsec = bprm->security;
2077         sid = bsec->sid;
2078
2079         tsec->osid = tsec->sid;
2080         bsec->unsafe = 0;
2081         if (tsec->sid != sid) {
2082                 /* Check for shared state.  If not ok, leave SID
2083                    unchanged and kill. */
2084                 if (unsafe & LSM_UNSAFE_SHARE) {
2085                         rc = avc_has_perm(tsec->sid, sid, SECCLASS_PROCESS,
2086                                         PROCESS__SHARE, NULL);
2087                         if (rc) {
2088                                 bsec->unsafe = 1;
2089                                 return;
2090                         }
2091                 }
2092
2093                 /* Check for ptracing, and update the task SID if ok.
2094                    Otherwise, leave SID unchanged and kill. */
2095                 if (unsafe & (LSM_UNSAFE_PTRACE | LSM_UNSAFE_PTRACE_CAP)) {
2096                         rc = avc_has_perm(tsec->ptrace_sid, sid,
2097                                           SECCLASS_PROCESS, PROCESS__PTRACE,
2098                                           NULL);
2099                         if (rc) {
2100                                 bsec->unsafe = 1;
2101                                 return;
2102                         }
2103                 }
2104                 tsec->sid = sid;
2105         }
2106 }
2107
2108 /*
2109  * called after apply_creds without the task lock held
2110  */
2111 static void selinux_bprm_post_apply_creds(struct linux_binprm *bprm)
2112 {
2113         struct task_security_struct *tsec;
2114         struct rlimit *rlim, *initrlim;
2115         struct itimerval itimer;
2116         struct bprm_security_struct *bsec;
2117         int rc, i;
2118
2119         tsec = current->security;
2120         bsec = bprm->security;
2121
2122         if (bsec->unsafe) {
2123                 force_sig_specific(SIGKILL, current);
2124                 return;
2125         }
2126         if (tsec->osid == tsec->sid)
2127                 return;
2128
2129         /* Close files for which the new task SID is not authorized. */
2130         flush_unauthorized_files(current->files);
2131
2132         /* Check whether the new SID can inherit signal state
2133            from the old SID.  If not, clear itimers to avoid
2134            subsequent signal generation and flush and unblock
2135            signals. This must occur _after_ the task SID has
2136           been updated so that any kill done after the flush
2137           will be checked against the new SID. */
2138         rc = avc_has_perm(tsec->osid, tsec->sid, SECCLASS_PROCESS,
2139                           PROCESS__SIGINH, NULL);
2140         if (rc) {
2141                 memset(&itimer, 0, sizeof itimer);
2142                 for (i = 0; i < 3; i++)
2143                         do_setitimer(i, &itimer, NULL);
2144                 flush_signals(current);
2145                 spin_lock_irq(&current->sighand->siglock);
2146                 flush_signal_handlers(current, 1);
2147                 sigemptyset(&current->blocked);
2148                 recalc_sigpending();
2149                 spin_unlock_irq(&current->sighand->siglock);
2150         }
2151
2152         /* Always clear parent death signal on SID transitions. */
2153         current->pdeath_signal = 0;
2154
2155         /* Check whether the new SID can inherit resource limits
2156            from the old SID.  If not, reset all soft limits to
2157            the lower of the current task's hard limit and the init
2158            task's soft limit.  Note that the setting of hard limits
2159            (even to lower them) can be controlled by the setrlimit
2160            check. The inclusion of the init task's soft limit into
2161            the computation is to avoid resetting soft limits higher
2162            than the default soft limit for cases where the default
2163            is lower than the hard limit, e.g. RLIMIT_CORE or
2164            RLIMIT_STACK.*/
2165         rc = avc_has_perm(tsec->osid, tsec->sid, SECCLASS_PROCESS,
2166                           PROCESS__RLIMITINH, NULL);
2167         if (rc) {
2168                 for (i = 0; i < RLIM_NLIMITS; i++) {
2169                         rlim = current->signal->rlim + i;
2170                         initrlim = init_task.signal->rlim+i;
2171                         rlim->rlim_cur = min(rlim->rlim_max,initrlim->rlim_cur);
2172                 }
2173                 if (current->signal->rlim[RLIMIT_CPU].rlim_cur != RLIM_INFINITY) {
2174                         /*
2175                          * This will cause RLIMIT_CPU calculations
2176                          * to be refigured.
2177                          */
2178                         current->it_prof_expires = jiffies_to_cputime(1);
2179                 }
2180         }
2181
2182         /* Wake up the parent if it is waiting so that it can
2183            recheck wait permission to the new task SID. */
2184         wake_up_interruptible(&current->parent->signal->wait_chldexit);
2185 }
2186
2187 /* superblock security operations */
2188
2189 static int selinux_sb_alloc_security(struct super_block *sb)
2190 {
2191         return superblock_alloc_security(sb);
2192 }
2193
2194 static void selinux_sb_free_security(struct super_block *sb)
2195 {
2196         superblock_free_security(sb);
2197 }
2198
2199 static inline int match_prefix(char *prefix, int plen, char *option, int olen)
2200 {
2201         if (plen > olen)
2202                 return 0;
2203
2204         return !memcmp(prefix, option, plen);
2205 }
2206
2207 static inline int selinux_option(char *option, int len)
2208 {
2209         return (match_prefix("context=", sizeof("context=")-1, option, len) ||
2210                 match_prefix("fscontext=", sizeof("fscontext=")-1, option, len) ||
2211                 match_prefix("defcontext=", sizeof("defcontext=")-1, option, len) ||
2212                 match_prefix("rootcontext=", sizeof("rootcontext=")-1, option, len));
2213 }
2214
2215 static inline void take_option(char **to, char *from, int *first, int len)
2216 {
2217         if (!*first) {
2218                 **to = ',';
2219                 *to += 1;
2220         } else
2221                 *first = 0;
2222         memcpy(*to, from, len);
2223         *to += len;
2224 }
2225
2226 static inline void take_selinux_option(char **to, char *from, int *first, 
2227                                        int len)
2228 {
2229         int current_size = 0;
2230
2231         if (!*first) {
2232                 **to = '|';
2233                 *to += 1;
2234         }
2235         else
2236                 *first = 0;
2237
2238         while (current_size < len) {
2239                 if (*from != '"') {
2240                         **to = *from;
2241                         *to += 1;
2242                 }
2243                 from += 1;
2244                 current_size += 1;
2245         }
2246 }
2247
2248 static int selinux_sb_copy_data(struct file_system_type *type, void *orig, void *copy)
2249 {
2250         int fnosec, fsec, rc = 0;
2251         char *in_save, *in_curr, *in_end;
2252         char *sec_curr, *nosec_save, *nosec;
2253         int open_quote = 0;
2254
2255         in_curr = orig;
2256         sec_curr = copy;
2257
2258         /* Binary mount data: just copy */
2259         if (type->fs_flags & FS_BINARY_MOUNTDATA) {
2260                 copy_page(sec_curr, in_curr);
2261                 goto out;
2262         }
2263
2264         nosec = (char *)get_zeroed_page(GFP_KERNEL);
2265         if (!nosec) {
2266                 rc = -ENOMEM;
2267                 goto out;
2268         }
2269
2270         nosec_save = nosec;
2271         fnosec = fsec = 1;
2272         in_save = in_end = orig;
2273
2274         do {
2275                 if (*in_end == '"')
2276                         open_quote = !open_quote;
2277                 if ((*in_end == ',' && open_quote == 0) ||
2278                                 *in_end == '\0') {
2279                         int len = in_end - in_curr;
2280
2281                         if (selinux_option(in_curr, len))
2282                                 take_selinux_option(&sec_curr, in_curr, &fsec, len);
2283                         else
2284                                 take_option(&nosec, in_curr, &fnosec, len);
2285
2286                         in_curr = in_end + 1;
2287                 }
2288         } while (*in_end++);
2289
2290         strcpy(in_save, nosec_save);
2291         free_page((unsigned long)nosec_save);
2292 out:
2293         return rc;
2294 }
2295
2296 static int selinux_sb_kern_mount(struct super_block *sb, void *data)
2297 {
2298         struct avc_audit_data ad;
2299         int rc;
2300
2301         rc = superblock_doinit(sb, data);
2302         if (rc)
2303                 return rc;
2304
2305         AVC_AUDIT_DATA_INIT(&ad,FS);
2306         ad.u.fs.dentry = sb->s_root;
2307         return superblock_has_perm(current, sb, FILESYSTEM__MOUNT, &ad);
2308 }
2309
2310 static int selinux_sb_statfs(struct dentry *dentry)
2311 {
2312         struct avc_audit_data ad;
2313
2314         AVC_AUDIT_DATA_INIT(&ad,FS);
2315         ad.u.fs.dentry = dentry->d_sb->s_root;
2316         return superblock_has_perm(current, dentry->d_sb, FILESYSTEM__GETATTR, &ad);
2317 }
2318
2319 static int selinux_mount(char * dev_name,
2320                          struct nameidata *nd,
2321                          char * type,
2322                          unsigned long flags,
2323                          void * data)
2324 {
2325         int rc;
2326
2327         rc = secondary_ops->sb_mount(dev_name, nd, type, flags, data);
2328         if (rc)
2329                 return rc;
2330
2331         if (flags & MS_REMOUNT)
2332                 return superblock_has_perm(current, nd->mnt->mnt_sb,
2333                                            FILESYSTEM__REMOUNT, NULL);
2334         else
2335                 return dentry_has_perm(current, nd->mnt, nd->dentry,
2336                                        FILE__MOUNTON);
2337 }
2338
2339 static int selinux_umount(struct vfsmount *mnt, int flags)
2340 {
2341         int rc;
2342
2343         rc = secondary_ops->sb_umount(mnt, flags);
2344         if (rc)
2345                 return rc;
2346
2347         return superblock_has_perm(current,mnt->mnt_sb,
2348                                    FILESYSTEM__UNMOUNT,NULL);
2349 }
2350
2351 /* inode security operations */
2352
2353 static int selinux_inode_alloc_security(struct inode *inode)
2354 {
2355         return inode_alloc_security(inode);
2356 }
2357
2358 static void selinux_inode_free_security(struct inode *inode)
2359 {
2360         inode_free_security(inode);
2361 }
2362
2363 static int selinux_inode_init_security(struct inode *inode, struct inode *dir,
2364                                        char **name, void **value,
2365                                        size_t *len)
2366 {
2367         struct task_security_struct *tsec;
2368         struct inode_security_struct *dsec;
2369         struct superblock_security_struct *sbsec;
2370         u32 newsid, clen;
2371         int rc;
2372         char *namep = NULL, *context;
2373
2374         tsec = current->security;
2375         dsec = dir->i_security;
2376         sbsec = dir->i_sb->s_security;
2377
2378         if (tsec->create_sid && sbsec->behavior != SECURITY_FS_USE_MNTPOINT) {
2379                 newsid = tsec->create_sid;
2380         } else {
2381                 rc = security_transition_sid(tsec->sid, dsec->sid,
2382                                              inode_mode_to_security_class(inode->i_mode),
2383                                              &newsid);
2384                 if (rc) {
2385                         printk(KERN_WARNING "%s:  "
2386                                "security_transition_sid failed, rc=%d (dev=%s "
2387                                "ino=%ld)\n",
2388                                __FUNCTION__,
2389                                -rc, inode->i_sb->s_id, inode->i_ino);
2390                         return rc;
2391                 }
2392         }
2393
2394         /* Possibly defer initialization to selinux_complete_init. */
2395         if (sbsec->initialized) {
2396                 struct inode_security_struct *isec = inode->i_security;
2397                 isec->sclass = inode_mode_to_security_class(inode->i_mode);
2398                 isec->sid = newsid;
2399                 isec->initialized = 1;
2400         }
2401
2402         if (!ss_initialized || sbsec->behavior == SECURITY_FS_USE_MNTPOINT)
2403                 return -EOPNOTSUPP;
2404
2405         if (name) {
2406                 namep = kstrdup(XATTR_SELINUX_SUFFIX, GFP_KERNEL);
2407                 if (!namep)
2408                         return -ENOMEM;
2409                 *name = namep;
2410         }
2411
2412         if (value && len) {
2413                 rc = security_sid_to_context(newsid, &context, &clen);
2414                 if (rc) {
2415                         kfree(namep);
2416                         return rc;
2417                 }
2418                 *value = context;
2419                 *len = clen;
2420         }
2421
2422         return 0;
2423 }
2424
2425 static int selinux_inode_create(struct inode *dir, struct dentry *dentry, int mask)
2426 {
2427         return may_create(dir, dentry, SECCLASS_FILE);
2428 }
2429
2430 static int selinux_inode_link(struct dentry *old_dentry, struct inode *dir, struct dentry *new_dentry)
2431 {
2432         int rc;
2433
2434         rc = secondary_ops->inode_link(old_dentry,dir,new_dentry);
2435         if (rc)
2436                 return rc;
2437         return may_link(dir, old_dentry, MAY_LINK);
2438 }
2439
2440 static int selinux_inode_unlink(struct inode *dir, struct dentry *dentry)
2441 {
2442         int rc;
2443
2444         rc = secondary_ops->inode_unlink(dir, dentry);
2445         if (rc)
2446                 return rc;
2447         return may_link(dir, dentry, MAY_UNLINK);
2448 }
2449
2450 static int selinux_inode_symlink(struct inode *dir, struct dentry *dentry, const char *name)
2451 {
2452         return may_create(dir, dentry, SECCLASS_LNK_FILE);
2453 }
2454
2455 static int selinux_inode_mkdir(struct inode *dir, struct dentry *dentry, int mask)
2456 {
2457         return may_create(dir, dentry, SECCLASS_DIR);
2458 }
2459
2460 static int selinux_inode_rmdir(struct inode *dir, struct dentry *dentry)
2461 {
2462         return may_link(dir, dentry, MAY_RMDIR);
2463 }
2464
2465 static int selinux_inode_mknod(struct inode *dir, struct dentry *dentry, int mode, dev_t dev)
2466 {
2467         int rc;
2468
2469         rc = secondary_ops->inode_mknod(dir, dentry, mode, dev);
2470         if (rc)
2471                 return rc;
2472
2473         return may_create(dir, dentry, inode_mode_to_security_class(mode));
2474 }
2475
2476 static int selinux_inode_rename(struct inode *old_inode, struct dentry *old_dentry,
2477                                 struct inode *new_inode, struct dentry *new_dentry)
2478 {
2479         return may_rename(old_inode, old_dentry, new_inode, new_dentry);
2480 }
2481
2482 static int selinux_inode_readlink(struct dentry *dentry)
2483 {
2484         return dentry_has_perm(current, NULL, dentry, FILE__READ);
2485 }
2486
2487 static int selinux_inode_follow_link(struct dentry *dentry, struct nameidata *nameidata)
2488 {
2489         int rc;
2490
2491         rc = secondary_ops->inode_follow_link(dentry,nameidata);
2492         if (rc)
2493                 return rc;
2494         return dentry_has_perm(current, NULL, dentry, FILE__READ);
2495 }
2496
2497 static int selinux_inode_permission(struct inode *inode, int mask,
2498                                     struct nameidata *nd)
2499 {
2500         int rc;
2501
2502         rc = secondary_ops->inode_permission(inode, mask, nd);
2503         if (rc)
2504                 return rc;
2505
2506         if (!mask) {
2507                 /* No permission to check.  Existence test. */
2508                 return 0;
2509         }
2510
2511         return inode_has_perm(current, inode,
2512                                file_mask_to_av(inode->i_mode, mask), NULL);
2513 }
2514
2515 static int selinux_inode_setattr(struct dentry *dentry, struct iattr *iattr)
2516 {
2517         int rc;
2518
2519         rc = secondary_ops->inode_setattr(dentry, iattr);
2520         if (rc)
2521                 return rc;
2522
2523         if (iattr->ia_valid & ATTR_FORCE)
2524                 return 0;
2525
2526         if (iattr->ia_valid & (ATTR_MODE | ATTR_UID | ATTR_GID |
2527                                ATTR_ATIME_SET | ATTR_MTIME_SET))
2528                 return dentry_has_perm(current, NULL, dentry, FILE__SETATTR);
2529
2530         return dentry_has_perm(current, NULL, dentry, FILE__WRITE);
2531 }
2532
2533 static int selinux_inode_getattr(struct vfsmount *mnt, struct dentry *dentry)
2534 {
2535         return dentry_has_perm(current, mnt, dentry, FILE__GETATTR);
2536 }
2537
2538 static int selinux_inode_setotherxattr(struct dentry *dentry, char *name)
2539 {
2540         if (!strncmp(name, XATTR_SECURITY_PREFIX,
2541                      sizeof XATTR_SECURITY_PREFIX - 1)) {
2542                 if (!strcmp(name, XATTR_NAME_CAPS)) {
2543                         if (!capable(CAP_SETFCAP))
2544                                 return -EPERM;
2545                 } else if (!capable(CAP_SYS_ADMIN)) {
2546                         /* A different attribute in the security namespace.
2547                            Restrict to administrator. */
2548                         return -EPERM;
2549                 }
2550         }
2551
2552         /* Not an attribute we recognize, so just check the
2553            ordinary setattr permission. */
2554         return dentry_has_perm(current, NULL, dentry, FILE__SETATTR);
2555 }
2556
2557 static int selinux_inode_setxattr(struct dentry *dentry, char *name, void *value, size_t size, int flags)
2558 {
2559         struct task_security_struct *tsec = current->security;
2560         struct inode *inode = dentry->d_inode;
2561         struct inode_security_struct *isec = inode->i_security;
2562         struct superblock_security_struct *sbsec;
2563         struct avc_audit_data ad;
2564         u32 newsid;
2565         int rc = 0;
2566
2567         if (strcmp(name, XATTR_NAME_SELINUX))
2568                 return selinux_inode_setotherxattr(dentry, name);
2569
2570         sbsec = inode->i_sb->s_security;
2571         if (sbsec->behavior == SECURITY_FS_USE_MNTPOINT)
2572                 return -EOPNOTSUPP;
2573
2574         if (!is_owner_or_cap(inode))
2575                 return -EPERM;
2576
2577         AVC_AUDIT_DATA_INIT(&ad,FS);
2578         ad.u.fs.dentry = dentry;
2579
2580         rc = avc_has_perm(tsec->sid, isec->sid, isec->sclass,
2581                           FILE__RELABELFROM, &ad);
2582         if (rc)
2583                 return rc;
2584
2585         rc = security_context_to_sid(value, size, &newsid);
2586         if (rc)
2587                 return rc;
2588
2589         rc = avc_has_perm(tsec->sid, newsid, isec->sclass,
2590                           FILE__RELABELTO, &ad);
2591         if (rc)
2592                 return rc;
2593
2594         rc = security_validate_transition(isec->sid, newsid, tsec->sid,
2595                                           isec->sclass);
2596         if (rc)
2597                 return rc;
2598
2599         return avc_has_perm(newsid,
2600                             sbsec->sid,
2601                             SECCLASS_FILESYSTEM,
2602                             FILESYSTEM__ASSOCIATE,
2603                             &ad);
2604 }
2605
2606 static void selinux_inode_post_setxattr(struct dentry *dentry, char *name,
2607                                         void *value, size_t size, int flags)
2608 {
2609         struct inode *inode = dentry->d_inode;
2610         struct inode_security_struct *isec = inode->i_security;
2611         u32 newsid;
2612         int rc;
2613
2614         if (strcmp(name, XATTR_NAME_SELINUX)) {
2615                 /* Not an attribute we recognize, so nothing to do. */
2616                 return;
2617         }
2618
2619         rc = security_context_to_sid(value, size, &newsid);
2620         if (rc) {
2621                 printk(KERN_WARNING "%s:  unable to obtain SID for context "
2622                        "%s, rc=%d\n", __FUNCTION__, (char*)value, -rc);
2623                 return;
2624         }
2625
2626         isec->sid = newsid;
2627         return;
2628 }
2629
2630 static int selinux_inode_getxattr (struct dentry *dentry, char *name)
2631 {
2632         return dentry_has_perm(current, NULL, dentry, FILE__GETATTR);
2633 }
2634
2635 static int selinux_inode_listxattr (struct dentry *dentry)
2636 {
2637         return dentry_has_perm(current, NULL, dentry, FILE__GETATTR);
2638 }
2639
2640 static int selinux_inode_removexattr (struct dentry *dentry, char *name)
2641 {
2642         if (strcmp(name, XATTR_NAME_SELINUX))
2643                 return selinux_inode_setotherxattr(dentry, name);
2644
2645         /* No one is allowed to remove a SELinux security label.
2646            You can change the label, but all data must be labeled. */
2647         return -EACCES;
2648 }
2649
2650 /*
2651  * Copy the in-core inode security context value to the user.  If the
2652  * getxattr() prior to this succeeded, check to see if we need to
2653  * canonicalize the value to be finally returned to the user.
2654  *
2655  * Permission check is handled by selinux_inode_getxattr hook.
2656  */
2657 static int selinux_inode_getsecurity(const struct inode *inode, const char *name, void *buffer, size_t size, int err)
2658 {
2659         struct inode_security_struct *isec = inode->i_security;
2660
2661         if (strcmp(name, XATTR_SELINUX_SUFFIX))
2662                 return -EOPNOTSUPP;
2663
2664         return selinux_getsecurity(isec->sid, buffer, size);
2665 }
2666
2667 static int selinux_inode_setsecurity(struct inode *inode, const char *name,
2668                                      const void *value, size_t size, int flags)
2669 {
2670         struct inode_security_struct *isec = inode->i_security;
2671         u32 newsid;
2672         int rc;
2673
2674         if (strcmp(name, XATTR_SELINUX_SUFFIX))
2675                 return -EOPNOTSUPP;
2676
2677         if (!value || !size)
2678                 return -EACCES;
2679
2680         rc = security_context_to_sid((void*)value, size, &newsid);
2681         if (rc)
2682                 return rc;
2683
2684         isec->sid = newsid;
2685         return 0;
2686 }
2687
2688 static int selinux_inode_listsecurity(struct inode *inode, char *buffer, size_t buffer_size)
2689 {
2690         const int len = sizeof(XATTR_NAME_SELINUX);
2691         if (buffer && len <= buffer_size)
2692                 memcpy(buffer, XATTR_NAME_SELINUX, len);
2693         return len;
2694 }
2695
2696 static int selinux_inode_need_killpriv(struct dentry *dentry)
2697 {
2698         return secondary_ops->inode_need_killpriv(dentry);
2699 }
2700
2701 static int selinux_inode_killpriv(struct dentry *dentry)
2702 {
2703         return secondary_ops->inode_killpriv(dentry);
2704 }
2705
2706 /* file security operations */
2707
2708 static int selinux_revalidate_file_permission(struct file *file, int mask)
2709 {
2710         int rc;
2711         struct inode *inode = file->f_path.dentry->d_inode;
2712
2713         if (!mask) {
2714                 /* No permission to check.  Existence test. */
2715                 return 0;
2716         }
2717
2718         /* file_mask_to_av won't add FILE__WRITE if MAY_APPEND is set */
2719         if ((file->f_flags & O_APPEND) && (mask & MAY_WRITE))
2720                 mask |= MAY_APPEND;
2721
2722         rc = file_has_perm(current, file,
2723                            file_mask_to_av(inode->i_mode, mask));
2724         if (rc)
2725                 return rc;
2726
2727         return selinux_netlbl_inode_permission(inode, mask);
2728 }
2729
2730 static int selinux_file_permission(struct file *file, int mask)
2731 {
2732         struct inode *inode = file->f_path.dentry->d_inode;
2733         struct task_security_struct *tsec = current->security;
2734         struct file_security_struct *fsec = file->f_security;
2735         struct inode_security_struct *isec = inode->i_security;
2736
2737         if (!mask) {
2738                 /* No permission to check.  Existence test. */
2739                 return 0;
2740         }
2741
2742         if (tsec->sid == fsec->sid && fsec->isid == isec->sid
2743             && fsec->pseqno == avc_policy_seqno())
2744                 return selinux_netlbl_inode_permission(inode, mask);
2745
2746         return selinux_revalidate_file_permission(file, mask);
2747 }
2748
2749 static int selinux_file_alloc_security(struct file *file)
2750 {
2751         return file_alloc_security(file);
2752 }
2753
2754 static void selinux_file_free_security(struct file *file)
2755 {
2756         file_free_security(file);
2757 }
2758
2759 static int selinux_file_ioctl(struct file *file, unsigned int cmd,
2760                               unsigned long arg)
2761 {
2762         int error = 0;
2763
2764         switch (cmd) {
2765                 case FIONREAD:
2766                 /* fall through */
2767                 case FIBMAP:
2768                 /* fall through */
2769                 case FIGETBSZ:
2770                 /* fall through */
2771                 case EXT2_IOC_GETFLAGS:
2772                 /* fall through */
2773                 case EXT2_IOC_GETVERSION:
2774                         error = file_has_perm(current, file, FILE__GETATTR);
2775                         break;
2776
2777                 case EXT2_IOC_SETFLAGS:
2778                 /* fall through */
2779                 case EXT2_IOC_SETVERSION:
2780                         error = file_has_perm(current, file, FILE__SETATTR);
2781                         break;
2782
2783                 /* sys_ioctl() checks */
2784                 case FIONBIO:
2785                 /* fall through */
2786                 case FIOASYNC:
2787                         error = file_has_perm(current, file, 0);
2788                         break;
2789
2790                 case KDSKBENT:
2791                 case KDSKBSENT:
2792                         error = task_has_capability(current,CAP_SYS_TTY_CONFIG);
2793                         break;
2794
2795                 /* default case assumes that the command will go
2796                  * to the file's ioctl() function.
2797                  */
2798                 default:
2799                         error = file_has_perm(current, file, FILE__IOCTL);
2800
2801         }
2802         return error;
2803 }
2804
2805 static int file_map_prot_check(struct file *file, unsigned long prot, int shared)
2806 {
2807 #ifndef CONFIG_PPC32
2808         if ((prot & PROT_EXEC) && (!file || (!shared && (prot & PROT_WRITE)))) {
2809                 /*
2810                  * We are making executable an anonymous mapping or a
2811                  * private file mapping that will also be writable.
2812                  * This has an additional check.
2813                  */
2814                 int rc = task_has_perm(current, current, PROCESS__EXECMEM);
2815                 if (rc)
2816                         return rc;
2817         }
2818 #endif
2819
2820         if (file) {
2821                 /* read access is always possible with a mapping */
2822                 u32 av = FILE__READ;
2823
2824                 /* write access only matters if the mapping is shared */
2825                 if (shared && (prot & PROT_WRITE))
2826                         av |= FILE__WRITE;
2827
2828                 if (prot & PROT_EXEC)
2829                         av |= FILE__EXECUTE;
2830
2831                 return file_has_perm(current, file, av);
2832         }
2833         return 0;
2834 }
2835
2836 static int selinux_file_mmap(struct file *file, unsigned long reqprot,
2837                              unsigned long prot, unsigned long flags,
2838                              unsigned long addr, unsigned long addr_only)
2839 {
2840         int rc = 0;
2841         u32 sid = ((struct task_security_struct*)(current->security))->sid;
2842
2843         if (addr < mmap_min_addr)
2844                 rc = avc_has_perm(sid, sid, SECCLASS_MEMPROTECT,
2845                                   MEMPROTECT__MMAP_ZERO, NULL);
2846         if (rc || addr_only)
2847                 return rc;
2848
2849         if (selinux_checkreqprot)
2850                 prot = reqprot;
2851
2852         return file_map_prot_check(file, prot,
2853                                    (flags & MAP_TYPE) == MAP_SHARED);
2854 }
2855
2856 static int selinux_file_mprotect(struct vm_area_struct *vma,
2857                                  unsigned long reqprot,
2858                                  unsigned long prot)
2859 {
2860         int rc;
2861
2862         rc = secondary_ops->file_mprotect(vma, reqprot, prot);
2863         if (rc)
2864                 return rc;
2865
2866         if (selinux_checkreqprot)
2867                 prot = reqprot;
2868
2869 #ifndef CONFIG_PPC32
2870         if ((prot & PROT_EXEC) && !(vma->vm_flags & VM_EXEC)) {
2871                 rc = 0;
2872                 if (vma->vm_start >= vma->vm_mm->start_brk &&
2873                     vma->vm_end <= vma->vm_mm->brk) {
2874                         rc = task_has_perm(current, current,
2875                                            PROCESS__EXECHEAP);
2876                 } else if (!vma->vm_file &&
2877                            vma->vm_start <= vma->vm_mm->start_stack &&
2878                            vma->vm_end >= vma->vm_mm->start_stack) {
2879                         rc = task_has_perm(current, current, PROCESS__EXECSTACK);
2880                 } else if (vma->vm_file && vma->anon_vma) {
2881                         /*
2882                          * We are making executable a file mapping that has
2883                          * had some COW done. Since pages might have been
2884                          * written, check ability to execute the possibly
2885                          * modified content.  This typically should only
2886                          * occur for text relocations.
2887                          */
2888                         rc = file_has_perm(current, vma->vm_file,
2889                                            FILE__EXECMOD);
2890                 }
2891                 if (rc)
2892                         return rc;
2893         }
2894 #endif
2895
2896         return file_map_prot_check(vma->vm_file, prot, vma->vm_flags&VM_SHARED);
2897 }
2898
2899 static int selinux_file_lock(struct file *file, unsigned int cmd)
2900 {
2901         return file_has_perm(current, file, FILE__LOCK);
2902 }
2903
2904 static int selinux_file_fcntl(struct file *file, unsigned int cmd,
2905                               unsigned long arg)
2906 {
2907         int err = 0;
2908
2909         switch (cmd) {
2910                 case F_SETFL:
2911                         if (!file->f_path.dentry || !file->f_path.dentry->d_inode) {
2912                                 err = -EINVAL;
2913                                 break;
2914                         }
2915
2916                         if ((file->f_flags & O_APPEND) && !(arg & O_APPEND)) {
2917                                 err = file_has_perm(current, file,FILE__WRITE);
2918                                 break;
2919                         }
2920                         /* fall through */
2921                 case F_SETOWN:
2922                 case F_SETSIG:
2923                 case F_GETFL:
2924                 case F_GETOWN:
2925                 case F_GETSIG:
2926                         /* Just check FD__USE permission */
2927                         err = file_has_perm(current, file, 0);
2928                         break;
2929                 case F_GETLK:
2930                 case F_SETLK:
2931                 case F_SETLKW:
2932 #if BITS_PER_LONG == 32
2933                 case F_GETLK64:
2934                 case F_SETLK64:
2935                 case F_SETLKW64:
2936 #endif
2937                         if (!file->f_path.dentry || !file->f_path.dentry->d_inode) {
2938                                 err = -EINVAL;
2939                                 break;
2940                         }
2941                         err = file_has_perm(current, file, FILE__LOCK);
2942                         break;
2943         }
2944
2945         return err;
2946 }
2947
2948 static int selinux_file_set_fowner(struct file *file)
2949 {
2950         struct task_security_struct *tsec;
2951         struct file_security_struct *fsec;
2952
2953         tsec = current->security;
2954         fsec = file->f_security;
2955         fsec->fown_sid = tsec->sid;
2956
2957         return 0;
2958 }
2959
2960 static int selinux_file_send_sigiotask(struct task_struct *tsk,
2961                                        struct fown_struct *fown, int signum)
2962 {
2963         struct file *file;
2964         u32 perm;
2965         struct task_security_struct *tsec;
2966         struct file_security_struct *fsec;
2967
2968         /* struct fown_struct is never outside the context of a struct file */
2969         file = container_of(fown, struct file, f_owner);
2970
2971         tsec = tsk->security;
2972         fsec = file->f_security;
2973
2974         if (!signum)
2975                 perm = signal_to_av(SIGIO); /* as per send_sigio_to_task */
2976         else
2977                 perm = signal_to_av(signum);
2978
2979         return avc_has_perm(fsec->fown_sid, tsec->sid,
2980                             SECCLASS_PROCESS, perm, NULL);
2981 }
2982
2983 static int selinux_file_receive(struct file *file)
2984 {
2985         return file_has_perm(current, file, file_to_av(file));
2986 }
2987
2988 static int selinux_dentry_open(struct file *file)
2989 {
2990         struct file_security_struct *fsec;
2991         struct inode *inode;
2992         struct inode_security_struct *isec;
2993         inode = file->f_path.dentry->d_inode;
2994         fsec = file->f_security;
2995         isec = inode->i_security;
2996         /*
2997          * Save inode label and policy sequence number
2998          * at open-time so that selinux_file_permission
2999          * can determine whether revalidation is necessary.
3000          * Task label is already saved in the file security
3001          * struct as its SID.
3002          */
3003         fsec->isid = isec->sid;
3004         fsec->pseqno = avc_policy_seqno();
3005         /*
3006          * Since the inode label or policy seqno may have changed
3007          * between the selinux_inode_permission check and the saving
3008          * of state above, recheck that access is still permitted.
3009          * Otherwise, access might never be revalidated against the
3010          * new inode label or new policy.
3011          * This check is not redundant - do not remove.
3012          */
3013         return inode_has_perm(current, inode, file_to_av(file), NULL);
3014 }
3015
3016 /* task security operations */
3017
3018 static int selinux_task_create(unsigned long clone_flags)
3019 {
3020         int rc;
3021
3022         rc = secondary_ops->task_create(clone_flags);
3023         if (rc)
3024                 return rc;
3025
3026         return task_has_perm(current, current, PROCESS__FORK);
3027 }
3028
3029 static int selinux_task_alloc_security(struct task_struct *tsk)
3030 {
3031         struct task_security_struct *tsec1, *tsec2;
3032         int rc;
3033
3034         tsec1 = current->security;
3035
3036         rc = task_alloc_security(tsk);
3037         if (rc)
3038                 return rc;
3039         tsec2 = tsk->security;
3040
3041         tsec2->osid = tsec1->osid;
3042         tsec2->sid = tsec1->sid;
3043
3044         /* Retain the exec, fs, key, and sock SIDs across fork */
3045         tsec2->exec_sid = tsec1->exec_sid;
3046         tsec2->create_sid = tsec1->create_sid;
3047         tsec2->keycreate_sid = tsec1->keycreate_sid;
3048         tsec2->sockcreate_sid = tsec1->sockcreate_sid;
3049
3050         /* Retain ptracer SID across fork, if any.
3051            This will be reset by the ptrace hook upon any
3052            subsequent ptrace_attach operations. */
3053         tsec2->ptrace_sid = tsec1->ptrace_sid;
3054
3055         return 0;
3056 }
3057
3058 static void selinux_task_free_security(struct task_struct *tsk)
3059 {
3060         task_free_security(tsk);
3061 }
3062
3063 static int selinux_task_setuid(uid_t id0, uid_t id1, uid_t id2, int flags)
3064 {
3065         /* Since setuid only affects the current process, and
3066            since the SELinux controls are not based on the Linux
3067            identity attributes, SELinux does not need to control
3068            this operation.  However, SELinux does control the use
3069            of the CAP_SETUID and CAP_SETGID capabilities using the
3070            capable hook. */
3071         return 0;
3072 }
3073
3074 static int selinux_task_post_setuid(uid_t id0, uid_t id1, uid_t id2, int flags)
3075 {
3076         return secondary_ops->task_post_setuid(id0,id1,id2,flags);
3077 }
3078
3079 static int selinux_task_setgid(gid_t id0, gid_t id1, gid_t id2, int flags)
3080 {
3081         /* See the comment for setuid above. */
3082         return 0;
3083 }
3084
3085 static int selinux_task_setpgid(struct task_struct *p, pid_t pgid)
3086 {
3087         return task_has_perm(current, p, PROCESS__SETPGID);
3088 }
3089
3090 static int selinux_task_getpgid(struct task_struct *p)
3091 {
3092         return task_has_perm(current, p, PROCESS__GETPGID);
3093 }
3094
3095 static int selinux_task_getsid(struct task_struct *p)
3096 {
3097         return task_has_perm(current, p, PROCESS__GETSESSION);
3098 }
3099
3100 static void selinux_task_getsecid(struct task_struct *p, u32 *secid)
3101 {
3102         selinux_get_task_sid(p, secid);
3103 }
3104
3105 static int selinux_task_setgroups(struct group_info *group_info)
3106 {
3107         /* See the comment for setuid above. */
3108         return 0;
3109 }
3110
3111 static int selinux_task_setnice(struct task_struct *p, int nice)
3112 {
3113         int rc;
3114
3115         rc = secondary_ops->task_setnice(p, nice);
3116         if (rc)
3117                 return rc;
3118
3119         return task_has_perm(current,p, PROCESS__SETSCHED);
3120 }
3121
3122 static int selinux_task_setioprio(struct task_struct *p, int ioprio)
3123 {
3124         int rc;
3125
3126         rc = secondary_ops->task_setioprio(p, ioprio);
3127         if (rc)
3128                 return rc;
3129
3130         return task_has_perm(current, p, PROCESS__SETSCHED);
3131 }
3132
3133 static int selinux_task_getioprio(struct task_struct *p)
3134 {
3135         return task_has_perm(current, p, PROCESS__GETSCHED);
3136 }
3137
3138 static int selinux_task_setrlimit(unsigned int resource, struct rlimit *new_rlim)
3139 {
3140         struct rlimit *old_rlim = current->signal->rlim + resource;
3141         int rc;
3142
3143         rc = secondary_ops->task_setrlimit(resource, new_rlim);
3144         if (rc)
3145                 return rc;
3146
3147         /* Control the ability to change the hard limit (whether
3148            lowering or raising it), so that the hard limit can
3149            later be used as a safe reset point for the soft limit
3150            upon context transitions. See selinux_bprm_apply_creds. */
3151         if (old_rlim->rlim_max != new_rlim->rlim_max)
3152                 return task_has_perm(current, current, PROCESS__SETRLIMIT);
3153
3154         return 0;
3155 }
3156
3157 static int selinux_task_setscheduler(struct task_struct *p, int policy, struct sched_param *lp)
3158 {
3159         int rc;
3160
3161         rc = secondary_ops->task_setscheduler(p, policy, lp);
3162         if (rc)
3163                 return rc;
3164
3165         return task_has_perm(current, p, PROCESS__SETSCHED);
3166 }
3167
3168 static int selinux_task_getscheduler(struct task_struct *p)
3169 {
3170         return task_has_perm(current, p, PROCESS__GETSCHED);
3171 }
3172
3173 static int selinux_task_movememory(struct task_struct *p)
3174 {
3175         return task_has_perm(current, p, PROCESS__SETSCHED);
3176 }
3177
3178 static int selinux_task_kill(struct task_struct *p, struct siginfo *info,
3179                                 int sig, u32 secid)
3180 {
3181         u32 perm;
3182         int rc;
3183         struct task_security_struct *tsec;
3184
3185         rc = secondary_ops->task_kill(p, info, sig, secid);
3186         if (rc)
3187                 return rc;
3188
3189         if (info != SEND_SIG_NOINFO && (is_si_special(info) || SI_FROMKERNEL(info)))
3190                 return 0;
3191
3192         if (!sig)
3193                 perm = PROCESS__SIGNULL; /* null signal; existence test */
3194         else
3195                 perm = signal_to_av(sig);
3196         tsec = p->security;
3197         if (secid)
3198                 rc = avc_has_perm(secid, tsec->sid, SECCLASS_PROCESS, perm, NULL);
3199         else
3200                 rc = task_has_perm(current, p, perm);
3201         return rc;
3202 }
3203
3204 static int selinux_task_prctl(int option,
3205                               unsigned long arg2,
3206                               unsigned long arg3,
3207                               unsigned long arg4,
3208                               unsigned long arg5)
3209 {
3210         /* The current prctl operations do not appear to require
3211            any SELinux controls since they merely observe or modify
3212            the state of the current process. */
3213         return 0;
3214 }
3215
3216 static int selinux_task_wait(struct task_struct *p)
3217 {
3218         return task_has_perm(p, current, PROCESS__SIGCHLD);
3219 }
3220
3221 static void selinux_task_reparent_to_init(struct task_struct *p)
3222 {
3223         struct task_security_struct *tsec;
3224
3225         secondary_ops->task_reparent_to_init(p);
3226
3227         tsec = p->security;
3228         tsec->osid = tsec->sid;
3229         tsec->sid = SECINITSID_KERNEL;
3230         return;
3231 }
3232
3233 static void selinux_task_to_inode(struct task_struct *p,
3234                                   struct inode *inode)
3235 {
3236         struct task_security_struct *tsec = p->security;
3237         struct inode_security_struct *isec = inode->i_security;
3238
3239         isec->sid = tsec->sid;
3240         isec->initialized = 1;
3241         return;
3242 }
3243
3244 /* Returns error only if unable to parse addresses */
3245 static int selinux_parse_skb_ipv4(struct sk_buff *skb,
3246                         struct avc_audit_data *ad, u8 *proto)
3247 {
3248         int offset, ihlen, ret = -EINVAL;
3249         struct iphdr _iph, *ih;
3250
3251         offset = skb_network_offset(skb);
3252         ih = skb_header_pointer(skb, offset, sizeof(_iph), &_iph);
3253         if (ih == NULL)
3254                 goto out;
3255
3256         ihlen = ih->ihl * 4;
3257         if (ihlen < sizeof(_iph))
3258                 goto out;
3259
3260         ad->u.net.v4info.saddr = ih->saddr;
3261         ad->u.net.v4info.daddr = ih->daddr;
3262         ret = 0;
3263
3264         if (proto)
3265                 *proto = ih->protocol;
3266
3267         switch (ih->protocol) {
3268         case IPPROTO_TCP: {
3269                 struct tcphdr _tcph, *th;
3270
3271                 if (ntohs(ih->frag_off) & IP_OFFSET)
3272                         break;
3273
3274                 offset += ihlen;
3275                 th = skb_header_pointer(skb, offset, sizeof(_tcph), &_tcph);
3276                 if (th == NULL)
3277                         break;
3278
3279                 ad->u.net.sport = th->source;
3280                 ad->u.net.dport = th->dest;
3281                 break;
3282         }
3283         
3284         case IPPROTO_UDP: {
3285                 struct udphdr _udph, *uh;
3286                 
3287                 if (ntohs(ih->frag_off) & IP_OFFSET)
3288                         break;
3289                         
3290                 offset += ihlen;
3291                 uh = skb_header_pointer(skb, offset, sizeof(_udph), &_udph);
3292                 if (uh == NULL)
3293                         break;  
3294
3295                 ad->u.net.sport = uh->source;
3296                 ad->u.net.dport = uh->dest;
3297                 break;
3298         }
3299
3300         case IPPROTO_DCCP: {
3301                 struct dccp_hdr _dccph, *dh;
3302