SELinux: Add a network node caching mechanism similar to the sel_netif_*() functions
[sfrench/cifs-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
3303                 if (ntohs(ih->frag_off) & IP_OFFSET)
3304                         break;
3305
3306                 offset += ihlen;
3307                 dh = skb_header_pointer(skb, offset, sizeof(_dccph), &_dccph);
3308                 if (dh == NULL)
3309                         break;
3310
3311                 ad->u.net.sport = dh->dccph_sport;
3312                 ad->u.net.dport = dh->dccph_dport;
3313                 break;
3314         }
3315
3316         default:
3317                 break;
3318         }
3319 out:
3320         return ret;
3321 }
3322
3323 #if defined(CONFIG_IPV6) || defined(CONFIG_IPV6_MODULE)
3324
3325 /* Returns error only if unable to parse addresses */
3326 static int selinux_parse_skb_ipv6(struct sk_buff *skb,
3327                         struct avc_audit_data *ad, u8 *proto)
3328 {
3329         u8 nexthdr;
3330         int ret = -EINVAL, offset;
3331         struct ipv6hdr _ipv6h, *ip6;
3332
3333         offset = skb_network_offset(skb);
3334         ip6 = skb_header_pointer(skb, offset, sizeof(_ipv6h), &_ipv6h);
3335         if (ip6 == NULL)
3336                 goto out;
3337
3338         ipv6_addr_copy(&ad->u.net.v6info.saddr, &ip6->saddr);
3339         ipv6_addr_copy(&ad->u.net.v6info.daddr, &ip6->daddr);
3340         ret = 0;
3341
3342         nexthdr = ip6->nexthdr;
3343         offset += sizeof(_ipv6h);
3344         offset = ipv6_skip_exthdr(skb, offset, &nexthdr);
3345         if (offset < 0)
3346                 goto out;
3347
3348         if (proto)
3349                 *proto = nexthdr;
3350
3351         switch (nexthdr) {
3352         case IPPROTO_TCP: {
3353                 struct tcphdr _tcph, *th;
3354
3355                 th = skb_header_pointer(skb, offset, sizeof(_tcph), &_tcph);
3356                 if (th == NULL)
3357                         break;
3358
3359                 ad->u.net.sport = th->source;
3360                 ad->u.net.dport = th->dest;
3361                 break;
3362         }
3363
3364         case IPPROTO_UDP: {
3365                 struct udphdr _udph, *uh;
3366
3367                 uh = skb_header_pointer(skb, offset, sizeof(_udph), &_udph);
3368                 if (uh == NULL)
3369                         break;
3370
3371                 ad->u.net.sport = uh->source;
3372                 ad->u.net.dport = uh->dest;
3373                 break;
3374         }
3375
3376         case IPPROTO_DCCP: {
3377                 struct dccp_hdr _dccph, *dh;
3378
3379                 dh = skb_header_pointer(skb, offset, sizeof(_dccph), &_dccph);
3380                 if (dh == NULL)
3381                         break;
3382
3383                 ad->u.net.sport = dh->dccph_sport;
3384                 ad->u.net.dport = dh->dccph_dport;
3385                 break;
3386         }
3387
3388         /* includes fragments */
3389         default:
3390                 break;
3391         }
3392 out:
3393         return ret;
3394 }
3395
3396 #endif /* IPV6 */
3397
3398 static int selinux_parse_skb(struct sk_buff *skb, struct avc_audit_data *ad,
3399                              char **addrp, int src, u8 *proto)
3400 {
3401         int ret = 0;
3402
3403         switch (ad->u.net.family) {
3404         case PF_INET:
3405                 ret = selinux_parse_skb_ipv4(skb, ad, proto);
3406                 if (ret || !addrp)
3407                         break;
3408                 *addrp = (char *)(src ? &ad->u.net.v4info.saddr :
3409                                         &ad->u.net.v4info.daddr);
3410                 break;
3411
3412 #if defined(CONFIG_IPV6) || defined(CONFIG_IPV6_MODULE)
3413         case PF_INET6:
3414                 ret = selinux_parse_skb_ipv6(skb, ad, proto);
3415                 if (ret || !addrp)
3416                         break;
3417                 *addrp = (char *)(src ? &ad->u.net.v6info.saddr :
3418                                         &ad->u.net.v6info.daddr);
3419                 break;
3420 #endif  /* IPV6 */
3421         default:
3422                 break;
3423         }
3424
3425         return ret;
3426 }
3427
3428 /**
3429  * selinux_skb_extlbl_sid - Determine the external label of a packet
3430  * @skb: the packet
3431  * @family: protocol family
3432  * @sid: the packet's SID
3433  *
3434  * Description:
3435  * Check the various different forms of external packet labeling and determine
3436  * the external SID for the packet.  If only one form of external labeling is
3437  * present then it is used, if both labeled IPsec and NetLabel labels are
3438  * present then the SELinux type information is taken from the labeled IPsec
3439  * SA and the MLS sensitivity label information is taken from the NetLabel
3440  * security attributes.  This bit of "magic" is done in the call to
3441  * selinux_netlbl_skbuff_getsid().
3442  *
3443  */
3444 static void selinux_skb_extlbl_sid(struct sk_buff *skb,
3445                                    u16 family,
3446                                    u32 *sid)
3447 {
3448         u32 xfrm_sid;
3449         u32 nlbl_sid;
3450
3451         selinux_skb_xfrm_sid(skb, &xfrm_sid);
3452         if (selinux_netlbl_skbuff_getsid(skb,
3453                                          family,
3454                                          (xfrm_sid == SECSID_NULL ?
3455                                           SECINITSID_NETMSG : xfrm_sid),
3456                                          &nlbl_sid) != 0)
3457                 nlbl_sid = SECSID_NULL;
3458         *sid = (nlbl_sid == SECSID_NULL ? xfrm_sid : nlbl_sid);
3459 }
3460
3461 /* socket security operations */
3462 static int socket_has_perm(struct task_struct *task, struct socket *sock,
3463                            u32 perms)
3464 {
3465         struct inode_security_struct *isec;
3466         struct task_security_struct *tsec;
3467         struct avc_audit_data ad;
3468         int err = 0;
3469
3470         tsec = task->security;
3471         isec = SOCK_INODE(sock)->i_security;
3472
3473         if (isec->sid == SECINITSID_KERNEL)
3474                 goto out;
3475
3476         AVC_AUDIT_DATA_INIT(&ad,NET);
3477         ad.u.net.sk = sock->sk;
3478         err = avc_has_perm(tsec->sid, isec->sid, isec->sclass, perms, &ad);
3479
3480 out:
3481         return err;
3482 }
3483
3484 static int selinux_socket_create(int family, int type,
3485                                  int protocol, int kern)
3486 {
3487         int err = 0;
3488         struct task_security_struct *tsec;
3489         u32 newsid;
3490
3491         if (kern)
3492                 goto out;
3493
3494         tsec = current->security;
3495         newsid = tsec->sockcreate_sid ? : tsec->sid;
3496         err = avc_has_perm(tsec->sid, newsid,
3497                            socket_type_to_security_class(family, type,
3498                            protocol), SOCKET__CREATE, NULL);
3499
3500 out:
3501         return err;
3502 }
3503
3504 static int selinux_socket_post_create(struct socket *sock, int family,
3505                                       int type, int protocol, int kern)
3506 {
3507         int err = 0;
3508         struct inode_security_struct *isec;
3509         struct task_security_struct *tsec;
3510         struct sk_security_struct *sksec;
3511         u32 newsid;
3512
3513         isec = SOCK_INODE(sock)->i_security;
3514
3515         tsec = current->security;
3516         newsid = tsec->sockcreate_sid ? : tsec->sid;
3517         isec->sclass = socket_type_to_security_class(family, type, protocol);
3518         isec->sid = kern ? SECINITSID_KERNEL : newsid;
3519         isec->initialized = 1;
3520
3521         if (sock->sk) {
3522                 sksec = sock->sk->sk_security;
3523                 sksec->sid = isec->sid;
3524                 err = selinux_netlbl_socket_post_create(sock);
3525         }
3526
3527         return err;
3528 }
3529
3530 /* Range of port numbers used to automatically bind.
3531    Need to determine whether we should perform a name_bind
3532    permission check between the socket and the port number. */
3533
3534 static int selinux_socket_bind(struct socket *sock, struct sockaddr *address, int addrlen)
3535 {
3536         u16 family;
3537         int err;
3538
3539         err = socket_has_perm(current, sock, SOCKET__BIND);
3540         if (err)
3541                 goto out;
3542
3543         /*
3544          * If PF_INET or PF_INET6, check name_bind permission for the port.
3545          * Multiple address binding for SCTP is not supported yet: we just
3546          * check the first address now.
3547          */
3548         family = sock->sk->sk_family;
3549         if (family == PF_INET || family == PF_INET6) {
3550                 char *addrp;
3551                 struct inode_security_struct *isec;
3552                 struct task_security_struct *tsec;
3553                 struct avc_audit_data ad;
3554                 struct sockaddr_in *addr4 = NULL;
3555                 struct sockaddr_in6 *addr6 = NULL;
3556                 unsigned short snum;
3557                 struct sock *sk = sock->sk;
3558                 u32 sid, node_perm, addrlen;
3559
3560                 tsec = current->security;
3561                 isec = SOCK_INODE(sock)->i_security;
3562
3563                 if (family == PF_INET) {
3564                         addr4 = (struct sockaddr_in *)address;
3565                         snum = ntohs(addr4->sin_port);
3566                         addrlen = sizeof(addr4->sin_addr.s_addr);
3567                         addrp = (char *)&addr4->sin_addr.s_addr;
3568                 } else {
3569                         addr6 = (struct sockaddr_in6 *)address;
3570                         snum = ntohs(addr6->sin6_port);
3571                         addrlen = sizeof(addr6->sin6_addr.s6_addr);
3572                         addrp = (char *)&addr6->sin6_addr.s6_addr;
3573                 }
3574
3575                 if (snum) {
3576                         int low, high;
3577
3578                         inet_get_local_port_range(&low, &high);
3579
3580                         if (snum < max(PROT_SOCK, low) || snum > high) {
3581                                 err = security_port_sid(sk->sk_family,
3582                                                         sk->sk_type,
3583                                                         sk->sk_protocol, snum,
3584                                                         &sid);
3585                                 if (err)
3586                                         goto out;
3587                                 AVC_AUDIT_DATA_INIT(&ad,NET);
3588                                 ad.u.net.sport = htons(snum);
3589                                 ad.u.net.family = family;
3590                                 err = avc_has_perm(isec->sid, sid,
3591                                                    isec->sclass,
3592                                                    SOCKET__NAME_BIND, &ad);
3593                                 if (err)
3594                                         goto out;
3595                         }
3596                 }
3597                 
3598                 switch(isec->sclass) {
3599                 case SECCLASS_TCP_SOCKET:
3600                         node_perm = TCP_SOCKET__NODE_BIND;
3601                         break;
3602                         
3603                 case SECCLASS_UDP_SOCKET:
3604                         node_perm = UDP_SOCKET__NODE_BIND;
3605                         break;
3606
3607                 case SECCLASS_DCCP_SOCKET:
3608                         node_perm = DCCP_SOCKET__NODE_BIND;
3609                         break;
3610
3611                 default:
3612                         node_perm = RAWIP_SOCKET__NODE_BIND;
3613                         break;
3614                 }
3615                 
3616                 err = sel_netnode_sid(addrp, family, &sid);
3617                 if (err)
3618                         goto out;
3619                 
3620                 AVC_AUDIT_DATA_INIT(&ad,NET);
3621                 ad.u.net.sport = htons(snum);
3622                 ad.u.net.family = family;
3623
3624                 if (family == PF_INET)
3625                         ad.u.net.v4info.saddr = addr4->sin_addr.s_addr;
3626                 else
3627                         ipv6_addr_copy(&ad.u.net.v6info.saddr, &addr6->sin6_addr);
3628
3629                 err = avc_has_perm(isec->sid, sid,
3630                                    isec->sclass, node_perm, &ad);
3631                 if (err)
3632                         goto out;
3633         }
3634 out:
3635         return err;
3636 }
3637
3638 static int selinux_socket_connect(struct socket *sock, struct sockaddr *address, int addrlen)
3639 {
3640         struct inode_security_struct *isec;
3641         int err;
3642
3643         err = socket_has_perm(current, sock, SOCKET__CONNECT);
3644         if (err)
3645                 return err;
3646
3647         /*
3648          * If a TCP or DCCP socket, check name_connect permission for the port.
3649          */
3650         isec = SOCK_INODE(sock)->i_security;
3651         if (isec->sclass == SECCLASS_TCP_SOCKET ||
3652             isec->sclass == SECCLASS_DCCP_SOCKET) {
3653                 struct sock *sk = sock->sk;
3654                 struct avc_audit_data ad;
3655                 struct sockaddr_in *addr4 = NULL;
3656                 struct sockaddr_in6 *addr6 = NULL;
3657                 unsigned short snum;
3658                 u32 sid, perm;
3659
3660                 if (sk->sk_family == PF_INET) {
3661                         addr4 = (struct sockaddr_in *)address;
3662                         if (addrlen < sizeof(struct sockaddr_in))
3663                                 return -EINVAL;
3664                         snum = ntohs(addr4->sin_port);
3665                 } else {
3666                         addr6 = (struct sockaddr_in6 *)address;
3667                         if (addrlen < SIN6_LEN_RFC2133)
3668                                 return -EINVAL;
3669                         snum = ntohs(addr6->sin6_port);
3670                 }
3671
3672                 err = security_port_sid(sk->sk_family, sk->sk_type,
3673                                         sk->sk_protocol, snum, &sid);
3674                 if (err)
3675                         goto out;
3676
3677                 perm = (isec->sclass == SECCLASS_TCP_SOCKET) ?
3678                        TCP_SOCKET__NAME_CONNECT : DCCP_SOCKET__NAME_CONNECT;
3679
3680                 AVC_AUDIT_DATA_INIT(&ad,NET);
3681                 ad.u.net.dport = htons(snum);
3682                 ad.u.net.family = sk->sk_family;
3683                 err = avc_has_perm(isec->sid, sid, isec->sclass, perm, &ad);
3684                 if (err)
3685                         goto out;
3686         }
3687
3688 out:
3689         return err;
3690 }
3691
3692 static int selinux_socket_listen(struct socket *sock, int backlog)
3693 {
3694         return socket_has_perm(current, sock, SOCKET__LISTEN);
3695 }
3696
3697 static int selinux_socket_accept(struct socket *sock, struct socket *newsock)
3698 {
3699         int err;
3700         struct inode_security_struct *isec;
3701         struct inode_security_struct *newisec;
3702
3703         err = socket_has_perm(current, sock, SOCKET__ACCEPT);
3704         if (err)
3705                 return err;
3706
3707         newisec = SOCK_INODE(newsock)->i_security;
3708
3709         isec = SOCK_INODE(sock)->i_security;
3710         newisec->sclass = isec->sclass;
3711         newisec->sid = isec->sid;
3712         newisec->initialized = 1;
3713
3714         return 0;
3715 }
3716
3717 static int selinux_socket_sendmsg(struct socket *sock, struct msghdr *msg,
3718                                   int size)
3719 {
3720         int rc;
3721
3722         rc = socket_has_perm(current, sock, SOCKET__WRITE);
3723         if (rc)
3724                 return rc;
3725
3726         return selinux_netlbl_inode_permission(SOCK_INODE(sock), MAY_WRITE);
3727 }
3728
3729 static int selinux_socket_recvmsg(struct socket *sock, struct msghdr *msg,
3730                                   int size, int flags)
3731 {
3732         return socket_has_perm(current, sock, SOCKET__READ);
3733 }
3734
3735 static int selinux_socket_getsockname(struct socket *sock)
3736 {
3737         return socket_has_perm(current, sock, SOCKET__GETATTR);
3738 }
3739
3740 static int selinux_socket_getpeername(struct socket *sock)
3741 {
3742         return socket_has_perm(current, sock, SOCKET__GETATTR);
3743 }
3744
3745 static int selinux_socket_setsockopt(struct socket *sock,int level,int optname)
3746 {
3747         int err;
3748
3749         err = socket_has_perm(current, sock, SOCKET__SETOPT);
3750         if (err)
3751                 return err;
3752
3753         return selinux_netlbl_socket_setsockopt(sock, level, optname);
3754 }
3755
3756 static int selinux_socket_getsockopt(struct socket *sock, int level,
3757                                      int optname)
3758 {
3759         return socket_has_perm(current, sock, SOCKET__GETOPT);
3760 }
3761
3762 static int selinux_socket_shutdown(struct socket *sock, int how)
3763 {
3764         return socket_has_perm(current, sock, SOCKET__SHUTDOWN);
3765 }
3766
3767 static int selinux_socket_unix_stream_connect(struct socket *sock,
3768                                               struct socket *other,
3769                                               struct sock *newsk)
3770 {
3771         struct sk_security_struct *ssec;
3772         struct inode_security_struct *isec;
3773         struct inode_security_struct *other_isec;
3774         struct avc_audit_data ad;
3775         int err;
3776
3777         err = secondary_ops->unix_stream_connect(sock, other, newsk);
3778         if (err)
3779                 return err;
3780
3781         isec = SOCK_INODE(sock)->i_security;
3782         other_isec = SOCK_INODE(other)->i_security;
3783
3784         AVC_AUDIT_DATA_INIT(&ad,NET);
3785         ad.u.net.sk = other->sk;
3786
3787         err = avc_has_perm(isec->sid, other_isec->sid,
3788                            isec->sclass,
3789                            UNIX_STREAM_SOCKET__CONNECTTO, &ad);
3790         if (err)
3791                 return err;
3792
3793         /* connecting socket */
3794         ssec = sock->sk->sk_security;
3795         ssec->peer_sid = other_isec->sid;
3796         
3797         /* server child socket */
3798         ssec = newsk->sk_security;
3799         ssec->peer_sid = isec->sid;
3800         err = security_sid_mls_copy(other_isec->sid, ssec->peer_sid, &ssec->sid);
3801
3802         return err;
3803 }
3804
3805 static int selinux_socket_unix_may_send(struct socket *sock,
3806                                         struct socket *other)
3807 {
3808         struct inode_security_struct *isec;
3809         struct inode_security_struct *other_isec;
3810         struct avc_audit_data ad;
3811         int err;
3812
3813         isec = SOCK_INODE(sock)->i_security;
3814         other_isec = SOCK_INODE(other)->i_security;
3815
3816         AVC_AUDIT_DATA_INIT(&ad,NET);
3817         ad.u.net.sk = other->sk;
3818
3819         err = avc_has_perm(isec->sid, other_isec->sid,
3820                            isec->sclass, SOCKET__SENDTO, &ad);
3821         if (err)
3822                 return err;
3823
3824         return 0;
3825 }
3826
3827 static int selinux_sock_rcv_skb_compat(struct sock *sk, struct sk_buff *skb,
3828                                        struct avc_audit_data *ad,
3829                                        u16 family, char *addrp)
3830 {
3831         int err = 0;
3832         u32 netif_perm, node_perm, node_sid, if_sid, recv_perm = 0;
3833         struct socket *sock;
3834         u16 sock_class = 0;
3835         u32 sock_sid = 0;
3836
3837         read_lock_bh(&sk->sk_callback_lock);
3838         sock = sk->sk_socket;
3839         if (sock) {
3840                 struct inode *inode;
3841                 inode = SOCK_INODE(sock);
3842                 if (inode) {
3843                         struct inode_security_struct *isec;
3844                         isec = inode->i_security;
3845                         sock_sid = isec->sid;
3846                         sock_class = isec->sclass;
3847                 }
3848         }
3849         read_unlock_bh(&sk->sk_callback_lock);
3850         if (!sock_sid)
3851                 goto out;
3852
3853         if (!skb->dev)
3854                 goto out;
3855
3856         err = sel_netif_sid(skb->iif, &if_sid);
3857         if (err)
3858                 goto out;
3859
3860         switch (sock_class) {
3861         case SECCLASS_UDP_SOCKET:
3862                 netif_perm = NETIF__UDP_RECV;
3863                 node_perm = NODE__UDP_RECV;
3864                 recv_perm = UDP_SOCKET__RECV_MSG;
3865                 break;
3866         
3867         case SECCLASS_TCP_SOCKET:
3868                 netif_perm = NETIF__TCP_RECV;
3869                 node_perm = NODE__TCP_RECV;
3870                 recv_perm = TCP_SOCKET__RECV_MSG;
3871                 break;
3872
3873         case SECCLASS_DCCP_SOCKET:
3874                 netif_perm = NETIF__DCCP_RECV;
3875                 node_perm = NODE__DCCP_RECV;
3876                 recv_perm = DCCP_SOCKET__RECV_MSG;
3877                 break;
3878
3879         default:
3880                 netif_perm = NETIF__RAWIP_RECV;
3881                 node_perm = NODE__RAWIP_RECV;
3882                 break;
3883         }
3884
3885         err = avc_has_perm(sock_sid, if_sid, SECCLASS_NETIF, netif_perm, ad);
3886         if (err)
3887                 goto out;
3888         
3889         err = sel_netnode_sid(addrp, family, &node_sid);
3890         if (err)
3891                 goto out;
3892         
3893         err = avc_has_perm(sock_sid, node_sid, SECCLASS_NODE, node_perm, ad);
3894         if (err)
3895                 goto out;
3896
3897         if (recv_perm) {
3898                 u32 port_sid;
3899
3900                 err = security_port_sid(sk->sk_family, sk->sk_type,
3901                                         sk->sk_protocol, ntohs(ad->u.net.sport),
3902                                         &port_sid);
3903                 if (err)
3904                         goto out;
3905
3906                 err = avc_has_perm(sock_sid, port_sid,
3907                                    sock_class, recv_perm, ad);
3908         }
3909
3910 out:
3911         return err;
3912 }
3913
3914 static int selinux_socket_sock_rcv_skb(struct sock *sk, struct sk_buff *skb)
3915 {
3916         u16 family;
3917         char *addrp;
3918         int err = 0;
3919         struct avc_audit_data ad;
3920         struct sk_security_struct *sksec = sk->sk_security;
3921
3922         family = sk->sk_family;
3923         if (family != PF_INET && family != PF_INET6)
3924                 goto out;
3925
3926         /* Handle mapped IPv4 packets arriving via IPv6 sockets */
3927         if (family == PF_INET6 && skb->protocol == htons(ETH_P_IP))
3928                 family = PF_INET;
3929
3930         AVC_AUDIT_DATA_INIT(&ad, NET);
3931         ad.u.net.netif = skb->iif;
3932         ad.u.net.family = family;
3933
3934         err = selinux_parse_skb(skb, &ad, &addrp, 1, NULL);
3935         if (err)
3936                 goto out;
3937
3938         if (selinux_compat_net)
3939                 err = selinux_sock_rcv_skb_compat(sk, skb, &ad, family, addrp);
3940         else
3941                 err = avc_has_perm(sksec->sid, skb->secmark, SECCLASS_PACKET,
3942                                    PACKET__RECV, &ad);
3943         if (err)
3944                 goto out;
3945
3946         err = selinux_netlbl_sock_rcv_skb(sksec, skb, family, &ad);
3947         if (err)
3948                 goto out;
3949
3950         err = selinux_xfrm_sock_rcv_skb(sksec->sid, skb, &ad);
3951 out:    
3952         return err;
3953 }
3954
3955 static int selinux_socket_getpeersec_stream(struct socket *sock, char __user *optval,
3956                                             int __user *optlen, unsigned len)
3957 {
3958         int err = 0;
3959         char *scontext;
3960         u32 scontext_len;
3961         struct sk_security_struct *ssec;
3962         struct inode_security_struct *isec;
3963         u32 peer_sid = SECSID_NULL;
3964
3965         isec = SOCK_INODE(sock)->i_security;
3966
3967         if (isec->sclass == SECCLASS_UNIX_STREAM_SOCKET ||
3968             isec->sclass == SECCLASS_TCP_SOCKET) {
3969                 ssec = sock->sk->sk_security;
3970                 peer_sid = ssec->peer_sid;
3971         }
3972         if (peer_sid == SECSID_NULL) {
3973                 err = -ENOPROTOOPT;
3974                 goto out;
3975         }
3976
3977         err = security_sid_to_context(peer_sid, &scontext, &scontext_len);
3978
3979         if (err)
3980                 goto out;
3981
3982         if (scontext_len > len) {
3983                 err = -ERANGE;
3984                 goto out_len;
3985         }
3986
3987         if (copy_to_user(optval, scontext, scontext_len))
3988                 err = -EFAULT;
3989
3990 out_len:
3991         if (put_user(scontext_len, optlen))
3992                 err = -EFAULT;
3993
3994         kfree(scontext);
3995 out:    
3996         return err;
3997 }
3998
3999 static int selinux_socket_getpeersec_dgram(struct socket *sock, struct sk_buff *skb, u32 *secid)
4000 {
4001         u32 peer_secid = SECSID_NULL;
4002         u16 family;
4003
4004         if (sock)
4005                 family = sock->sk->sk_family;
4006         else if (skb && skb->sk)
4007                 family = skb->sk->sk_family;
4008         else
4009                 goto out;
4010
4011         if (sock && family == PF_UNIX)
4012                 selinux_get_inode_sid(SOCK_INODE(sock), &peer_secid);
4013         else if (skb)
4014                 selinux_skb_extlbl_sid(skb, family, &peer_secid);
4015
4016 out:
4017         *secid = peer_secid;
4018         if (peer_secid == SECSID_NULL)
4019                 return -EINVAL;
4020         return 0;
4021 }
4022
4023 static int selinux_sk_alloc_security(struct sock *sk, int family, gfp_t priority)
4024 {
4025         return sk_alloc_security(sk, family, priority);
4026 }
4027
4028 static void selinux_sk_free_security(struct sock *sk)
4029 {
4030         sk_free_security(sk);
4031 }
4032
4033 static void selinux_sk_clone_security(const struct sock *sk, struct sock *newsk)
4034 {
4035         struct sk_security_struct *ssec = sk->sk_security;
4036         struct sk_security_struct *newssec = newsk->sk_security;
4037
4038         newssec->sid = ssec->sid;
4039         newssec->peer_sid = ssec->peer_sid;
4040
4041         selinux_netlbl_sk_security_clone(ssec, newssec);
4042 }
4043
4044 static void selinux_sk_getsecid(struct sock *sk, u32 *secid)
4045 {
4046         if (!sk)
4047                 *secid = SECINITSID_ANY_SOCKET;
4048         else {
4049                 struct sk_security_struct *sksec = sk->sk_security;
4050
4051                 *secid = sksec->sid;
4052         }
4053 }
4054
4055 static void selinux_sock_graft(struct sock* sk, struct socket *parent)
4056 {
4057         struct inode_security_struct *isec = SOCK_INODE(parent)->i_security;
4058         struct sk_security_struct *sksec = sk->sk_security;
4059
4060         if (sk->sk_family == PF_INET || sk->sk_family == PF_INET6 ||
4061             sk->sk_family == PF_UNIX)
4062                 isec->sid = sksec->sid;
4063
4064         selinux_netlbl_sock_graft(sk, parent);
4065 }
4066
4067 static int selinux_inet_conn_request(struct sock *sk, struct sk_buff *skb,
4068                                      struct request_sock *req)
4069 {
4070         struct sk_security_struct *sksec = sk->sk_security;
4071         int err;
4072         u32 newsid;
4073         u32 peersid;
4074
4075         selinux_skb_extlbl_sid(skb, sk->sk_family, &peersid);
4076         if (peersid == SECSID_NULL) {
4077                 req->secid = sksec->sid;
4078                 req->peer_secid = SECSID_NULL;
4079                 return 0;
4080         }
4081
4082         err = security_sid_mls_copy(sksec->sid, peersid, &newsid);
4083         if (err)
4084                 return err;
4085
4086         req->secid = newsid;
4087         req->peer_secid = peersid;
4088         return 0;
4089 }
4090
4091 static void selinux_inet_csk_clone(struct sock *newsk,
4092                                    const struct request_sock *req)
4093 {
4094         struct sk_security_struct *newsksec = newsk->sk_security;
4095
4096         newsksec->sid = req->secid;
4097         newsksec->peer_sid = req->peer_secid;
4098         /* NOTE: Ideally, we should also get the isec->sid for the
4099            new socket in sync, but we don't have the isec available yet.
4100            So we will wait until sock_graft to do it, by which
4101            time it will have been created and available. */
4102
4103         /* We don't need to take any sort of lock here as we are the only
4104          * thread with access to newsksec */
4105         selinux_netlbl_sk_security_reset(newsksec, req->rsk_ops->family);
4106 }
4107
4108 static void selinux_inet_conn_established(struct sock *sk,
4109                                 struct sk_buff *skb)
4110 {
4111         struct sk_security_struct *sksec = sk->sk_security;
4112
4113         selinux_skb_extlbl_sid(skb, sk->sk_family, &sksec->peer_sid);
4114 }
4115
4116 static void selinux_req_classify_flow(const struct request_sock *req,
4117                                       struct flowi *fl)
4118 {
4119         fl->secid = req->secid;
4120 }
4121
4122 static int selinux_nlmsg_perm(struct sock *sk, struct sk_buff *skb)
4123 {
4124         int err = 0;
4125         u32 perm;
4126         struct nlmsghdr *nlh;
4127         struct socket *sock = sk->sk_socket;
4128         struct inode_security_struct *isec = SOCK_INODE(sock)->i_security;
4129         
4130         if (skb->len < NLMSG_SPACE(0)) {
4131                 err = -EINVAL;
4132                 goto out;
4133         }
4134         nlh = nlmsg_hdr(skb);
4135         
4136         err = selinux_nlmsg_lookup(isec->sclass, nlh->nlmsg_type, &perm);
4137         if (err) {
4138                 if (err == -EINVAL) {
4139                         audit_log(current->audit_context, GFP_KERNEL, AUDIT_SELINUX_ERR,
4140                                   "SELinux:  unrecognized netlink message"
4141                                   " type=%hu for sclass=%hu\n",
4142                                   nlh->nlmsg_type, isec->sclass);
4143                         if (!selinux_enforcing)
4144                                 err = 0;
4145                 }
4146
4147                 /* Ignore */
4148                 if (err == -ENOENT)
4149                         err = 0;
4150                 goto out;
4151         }
4152
4153         err = socket_has_perm(current, sock, perm);
4154 out:
4155         return err;
4156 }
4157
4158 #ifdef CONFIG_NETFILTER
4159
4160 static int selinux_ip_postroute_last_compat(struct sock *sk,
4161                                             struct net_device *dev,
4162                                             struct avc_audit_data *ad,
4163                                             u16 family,
4164                                             char *addrp)
4165 {
4166         int err = 0;
4167         u32 netif_perm, node_perm, node_sid, if_sid, send_perm = 0;
4168         struct socket *sock;
4169         struct inode *inode;
4170         struct inode_security_struct *isec;
4171
4172         sock = sk->sk_socket;
4173         if (!sock)
4174                 goto out;
4175
4176         inode = SOCK_INODE(sock);
4177         if (!inode)
4178                 goto out;
4179
4180         isec = inode->i_security;
4181         
4182         err = sel_netif_sid(dev->ifindex, &if_sid);
4183         if (err)
4184                 goto out;
4185
4186         switch (isec->sclass) {
4187         case SECCLASS_UDP_SOCKET:
4188                 netif_perm = NETIF__UDP_SEND;
4189                 node_perm = NODE__UDP_SEND;
4190                 send_perm = UDP_SOCKET__SEND_MSG;
4191                 break;
4192         
4193         case SECCLASS_TCP_SOCKET:
4194                 netif_perm = NETIF__TCP_SEND;
4195                 node_perm = NODE__TCP_SEND;
4196                 send_perm = TCP_SOCKET__SEND_MSG;
4197                 break;
4198
4199         case SECCLASS_DCCP_SOCKET:
4200                 netif_perm = NETIF__DCCP_SEND;
4201                 node_perm = NODE__DCCP_SEND;
4202                 send_perm = DCCP_SOCKET__SEND_MSG;
4203                 break;
4204
4205         default:
4206                 netif_perm = NETIF__RAWIP_SEND;
4207                 node_perm = NODE__RAWIP_SEND;
4208                 break;
4209         }
4210
4211         err = avc_has_perm(isec->sid, if_sid, SECCLASS_NETIF, netif_perm, ad);
4212         if (err)
4213                 goto out;
4214                 
4215         err = sel_netnode_sid(addrp, family, &node_sid);
4216         if (err)
4217                 goto out;
4218         
4219         err = avc_has_perm(isec->sid, node_sid, SECCLASS_NODE, node_perm, ad);
4220         if (err)
4221                 goto out;
4222
4223         if (send_perm) {
4224                 u32 port_sid;
4225                 
4226                 err = security_port_sid(sk->sk_family,
4227                                         sk->sk_type,
4228                                         sk->sk_protocol,
4229                                         ntohs(ad->u.net.dport),
4230                                         &port_sid);
4231                 if (err)
4232                         goto out;
4233
4234                 err = avc_has_perm(isec->sid, port_sid, isec->sclass,
4235                                    send_perm, ad);
4236         }
4237 out:
4238         return err;
4239 }
4240
4241 static unsigned int selinux_ip_postroute_last(unsigned int hooknum,
4242                                               struct sk_buff *skb,
4243                                               const struct net_device *in,
4244                                               const struct net_device *out,
4245                                               int (*okfn)(struct sk_buff *),
4246                                               u16 family)
4247 {
4248         char *addrp;
4249         int err = 0;
4250         struct sock *sk;
4251         struct avc_audit_data ad;
4252         struct net_device *dev = (struct net_device *)out;
4253         struct sk_security_struct *sksec;
4254         u8 proto;
4255
4256         sk = skb->sk;
4257         if (!sk)
4258                 goto out;
4259
4260         sksec = sk->sk_security;
4261
4262         AVC_AUDIT_DATA_INIT(&ad, NET);
4263         ad.u.net.netif = dev->ifindex;
4264         ad.u.net.family = family;
4265
4266         err = selinux_parse_skb(skb, &ad, &addrp, 0, &proto);
4267         if (err)
4268                 goto out;
4269
4270         if (selinux_compat_net)
4271                 err = selinux_ip_postroute_last_compat(sk, dev, &ad,
4272                                                        family, addrp);
4273         else
4274                 err = avc_has_perm(sksec->sid, skb->secmark, SECCLASS_PACKET,
4275                                    PACKET__SEND, &ad);
4276
4277         if (err)
4278                 goto out;
4279
4280         err = selinux_xfrm_postroute_last(sksec->sid, skb, &ad, proto);
4281 out:
4282         return err ? NF_DROP : NF_ACCEPT;
4283 }
4284
4285 static unsigned int selinux_ipv4_postroute_last(unsigned int hooknum,
4286                                                 struct sk_buff *skb,
4287                                                 const struct net_device *in,
4288                                                 const struct net_device *out,
4289                                                 int (*okfn)(struct sk_buff *))
4290 {
4291         return selinux_ip_postroute_last(hooknum, skb, in, out, okfn, PF_INET);
4292 }
4293
4294 #if defined(CONFIG_IPV6) || defined(CONFIG_IPV6_MODULE)
4295
4296 static unsigned int selinux_ipv6_postroute_last(unsigned int hooknum,
4297                                                 struct sk_buff *skb,
4298                                                 const struct net_device *in,
4299                                                 const struct net_device *out,
4300                                                 int (*okfn)(struct sk_buff *))
4301 {
4302         return selinux_ip_postroute_last(hooknum, skb, in, out, okfn, PF_INET6);
4303 }
4304
4305 #endif  /* IPV6 */
4306
4307 #endif  /* CONFIG_NETFILTER */
4308
4309 static int selinux_netlink_send(struct sock *sk, struct sk_buff *skb)
4310 {
4311         int err;
4312
4313         err = secondary_ops->netlink_send(sk, skb);
4314         if (err)
4315                 return err;
4316
4317         if (policydb_loaded_version >= POLICYDB_VERSION_NLCLASS)
4318                 err = selinux_nlmsg_perm(sk, skb);
4319
4320         return err;
4321 }
4322
4323 static int selinux_netlink_recv(struct sk_buff *skb, int capability)
4324 {
4325         int err;
4326         struct avc_audit_data ad;
4327
4328         err = secondary_ops->netlink_recv(skb, capability);
4329         if (err)
4330                 return err;
4331
4332         AVC_AUDIT_DATA_INIT(&ad, CAP);
4333         ad.u.cap = capability;
4334
4335         return avc_has_perm(NETLINK_CB(skb).sid, NETLINK_CB(skb).sid,
4336                             SECCLASS_CAPABILITY, CAP_TO_MASK(capability), &ad);
4337 }
4338
4339 static int ipc_alloc_security(struct task_struct *task,
4340                               struct kern_ipc_perm *perm,
4341                               u16 sclass)
4342 {
4343         struct task_security_struct *tsec = task->security;
4344         struct ipc_security_struct *isec;
4345
4346         isec = kzalloc(sizeof(struct ipc_security_struct), GFP_KERNEL);
4347         if (!isec)
4348                 return -ENOMEM;
4349
4350         isec->sclass = sclass;
4351         isec->ipc_perm = perm;
4352         isec->sid = tsec->sid;
4353         perm->security = isec;
4354
4355         return 0;
4356 }
4357
4358 static void ipc_free_security(struct kern_ipc_perm *perm)
4359 {
4360         struct ipc_security_struct *isec = perm->security;
4361         perm->security = NULL;
4362         kfree(isec);
4363 }
4364
4365 static int msg_msg_alloc_security(struct msg_msg *msg)
4366 {
4367         struct msg_security_struct *msec;
4368
4369         msec = kzalloc(sizeof(struct msg_security_struct), GFP_KERNEL);
4370         if (!msec)
4371                 return -ENOMEM;
4372
4373         msec->msg = msg;
4374         msec->sid = SECINITSID_UNLABELED;
4375         msg->security = msec;
4376
4377         return 0;
4378 }
4379
4380 static void msg_msg_free_security(struct msg_msg *msg)
4381 {
4382         struct msg_security_struct *msec = msg->security;
4383
4384         msg->security = NULL;
4385         kfree(msec);
4386 }
4387
4388 static int ipc_has_perm(struct kern_ipc_perm *ipc_perms,
4389                         u32 perms)
4390 {
4391         struct task_security_struct *tsec;
4392         struct ipc_security_struct *isec;
4393         struct avc_audit_data ad;
4394
4395         tsec = current->security;
4396         isec = ipc_perms->security;
4397
4398         AVC_AUDIT_DATA_INIT(&ad, IPC);
4399         ad.u.ipc_id = ipc_perms->key;
4400
4401         return avc_has_perm(tsec->sid, isec->sid, isec->sclass, perms, &ad);
4402 }
4403
4404 static int selinux_msg_msg_alloc_security(struct msg_msg *msg)
4405 {
4406         return msg_msg_alloc_security(msg);
4407 }
4408
4409 static void selinux_msg_msg_free_security(struct msg_msg *msg)
4410 {
4411         msg_msg_free_security(msg);
4412 }
4413
4414 /* message queue security operations */
4415 static int selinux_msg_queue_alloc_security(struct msg_queue *msq)
4416 {
4417         struct task_security_struct *tsec;
4418         struct ipc_security_struct *isec;
4419         struct avc_audit_data ad;
4420         int rc;
4421
4422         rc = ipc_alloc_security(current, &msq->q_perm, SECCLASS_MSGQ);
4423         if (rc)
4424                 return rc;
4425
4426         tsec = current->security;
4427         isec = msq->q_perm.security;
4428
4429         AVC_AUDIT_DATA_INIT(&ad, IPC);
4430         ad.u.ipc_id = msq->q_perm.key;
4431
4432         rc = avc_has_perm(tsec->sid, isec->sid, SECCLASS_MSGQ,
4433                           MSGQ__CREATE, &ad);
4434         if (rc) {
4435                 ipc_free_security(&msq->q_perm);
4436                 return rc;
4437         }
4438         return 0;
4439 }
4440
4441 static void selinux_msg_queue_free_security(struct msg_queue *msq)
4442 {
4443         ipc_free_security(&msq->q_perm);
4444 }
4445
4446 static int selinux_msg_queue_associate(struct msg_queue *msq, int msqflg)
4447 {
4448         struct task_security_struct *tsec;
4449         struct ipc_security_struct *isec;
4450         struct avc_audit_data ad;
4451
4452         tsec = current->security;
4453         isec = msq->q_perm.security;
4454
4455         AVC_AUDIT_DATA_INIT(&ad, IPC);
4456         ad.u.ipc_id = msq->q_perm.key;
4457
4458         return avc_has_perm(tsec->sid, isec->sid, SECCLASS_MSGQ,
4459                             MSGQ__ASSOCIATE, &ad);
4460 }
4461
4462 static int selinux_msg_queue_msgctl(struct msg_queue *msq, int cmd)
4463 {
4464         int err;
4465         int perms;
4466
4467         switch(cmd) {
4468         case IPC_INFO:
4469         case MSG_INFO:
4470                 /* No specific object, just general system-wide information. */
4471                 return task_has_system(current, SYSTEM__IPC_INFO);
4472         case IPC_STAT:
4473         case MSG_STAT:
4474                 perms = MSGQ__GETATTR | MSGQ__ASSOCIATE;
4475                 break;
4476         case IPC_SET:
4477                 perms = MSGQ__SETATTR;
4478                 break;
4479         case IPC_RMID:
4480                 perms = MSGQ__DESTROY;
4481                 break;
4482         default:
4483                 return 0;
4484         }
4485
4486         err = ipc_has_perm(&msq->q_perm, perms);
4487         return err;
4488 }
4489
4490 static int selinux_msg_queue_msgsnd(struct msg_queue *msq, struct msg_msg *msg, int msqflg)
4491 {
4492         struct task_security_struct *tsec;
4493         struct ipc_security_struct *isec;
4494         struct msg_security_struct *msec;
4495         struct avc_audit_data ad;
4496         int rc;
4497
4498         tsec = current->security;
4499         isec = msq->q_perm.security;
4500         msec = msg->security;
4501
4502         /*
4503          * First time through, need to assign label to the message
4504          */
4505         if (msec->sid == SECINITSID_UNLABELED) {
4506                 /*
4507                  * Compute new sid based on current process and
4508                  * message queue this message will be stored in
4509                  */
4510                 rc = security_transition_sid(tsec->sid,
4511                                              isec->sid,
4512                                              SECCLASS_MSG,
4513                                              &msec->sid);
4514                 if (rc)
4515                         return rc;
4516         }
4517
4518         AVC_AUDIT_DATA_INIT(&ad, IPC);
4519         ad.u.ipc_id = msq->q_perm.key;
4520
4521         /* Can this process write to the queue? */
4522         rc = avc_has_perm(tsec->sid, isec->sid, SECCLASS_MSGQ,
4523                           MSGQ__WRITE, &ad);
4524         if (!rc)
4525                 /* Can this process send the message */
4526                 rc = avc_has_perm(tsec->sid, msec->sid,
4527                                   SECCLASS_MSG, MSG__SEND, &ad);
4528         if (!rc)
4529                 /* Can the message be put in the queue? */
4530                 rc = avc_has_perm(msec->sid, isec->sid,
4531                                   SECCLASS_MSGQ, MSGQ__ENQUEUE, &ad);
4532
4533         return rc;
4534 }
4535
4536 static int selinux_msg_queue_msgrcv(struct msg_queue *msq, struct msg_msg *msg,
4537                                     struct task_struct *target,
4538                                     long type, int mode)
4539 {
4540         struct task_security_struct *tsec;
4541         struct ipc_security_struct *isec;
4542         struct msg_security_struct *msec;
4543         struct avc_audit_data ad;
4544         int rc;
4545
4546         tsec = target->security;
4547         isec = msq->q_perm.security;
4548         msec = msg->security;
4549
4550         AVC_AUDIT_DATA_INIT(&ad, IPC);
4551         ad.u.ipc_id = msq->q_perm.key;
4552
4553         rc = avc_has_perm(tsec->sid, isec->sid,
4554                           SECCLASS_MSGQ, MSGQ__READ, &ad);
4555         if (!rc)
4556                 rc = avc_has_perm(tsec->sid, msec->sid,
4557                                   SECCLASS_MSG, MSG__RECEIVE, &ad);
4558         return rc;
4559 }
4560
4561 /* Shared Memory security operations */
4562 static int selinux_shm_alloc_security(struct shmid_kernel *shp)
4563 {
4564         struct task_security_struct *tsec;
4565         struct ipc_security_struct *isec;
4566         struct avc_audit_data ad;
4567         int rc;
4568
4569         rc = ipc_alloc_security(current, &shp->shm_perm, SECCLASS_SHM);
4570         if (rc)
4571                 return rc;
4572
4573         tsec = current->security;
4574         isec = shp->shm_perm.security;
4575
4576         AVC_AUDIT_DATA_INIT(&ad, IPC);
4577         ad.u.ipc_id = shp->shm_perm.key;
4578
4579         rc = avc_has_perm(tsec->sid, isec->sid, SECCLASS_SHM,
4580                           SHM__CREATE, &ad);
4581         if (rc) {
4582                 ipc_free_security(&shp->shm_perm);
4583                 return rc;
4584         }
4585         return 0;
4586 }
4587
4588 static void selinux_shm_free_security(struct shmid_kernel *shp)
4589 {
4590         ipc_free_security(&shp->shm_perm);
4591 }
4592
4593 static int selinux_shm_associate(struct shmid_kernel *shp, int shmflg)
4594 {
4595         struct task_security_struct *tsec;
4596         struct ipc_security_struct *isec;
4597         struct avc_audit_data ad;
4598
4599         tsec = current->security;
4600         isec = shp->shm_perm.security;
4601
4602         AVC_AUDIT_DATA_INIT(&ad, IPC);
4603         ad.u.ipc_id = shp->shm_perm.key;
4604
4605         return avc_has_perm(tsec->sid, isec->sid, SECCLASS_SHM,
4606                             SHM__ASSOCIATE, &ad);
4607 }
4608
4609 /* Note, at this point, shp is locked down */
4610 static int selinux_shm_shmctl(struct shmid_kernel *shp, int cmd)
4611 {
4612         int perms;
4613         int err;
4614
4615         switch(cmd) {
4616         case IPC_INFO:
4617         case SHM_INFO:
4618                 /* No specific object, just general system-wide information. */
4619                 return task_has_system(current, SYSTEM__IPC_INFO);
4620         case IPC_STAT:
4621         case SHM_STAT:
4622                 perms = SHM__GETATTR | SHM__ASSOCIATE;
4623                 break;
4624         case IPC_SET:
4625                 perms = SHM__SETATTR;
4626                 break;
4627         case SHM_LOCK:
4628         case SHM_UNLOCK:
4629                 perms = SHM__LOCK;
4630                 break;
4631         case IPC_RMID:
4632                 perms = SHM__DESTROY;
4633                 break;
4634         default:
4635                 return 0;
4636         }
4637
4638         err = ipc_has_perm(&shp->shm_perm, perms);
4639         return err;
4640 }
4641
4642 static int selinux_shm_shmat(struct shmid_kernel *shp,
4643                              char __user *shmaddr, int shmflg)
4644 {
4645         u32 perms;
4646         int rc;
4647
4648         rc = secondary_ops->shm_shmat(shp, shmaddr, shmflg);
4649         if (rc)
4650                 return rc;
4651
4652         if (shmflg & SHM_RDONLY)
4653                 perms = SHM__READ;
4654         else
4655                 perms = SHM__READ | SHM__WRITE;
4656
4657         return ipc_has_perm(&shp->shm_perm, perms);
4658 }
4659
4660 /* Semaphore security operations */
4661 static int selinux_sem_alloc_security(struct sem_array *sma)
4662 {
4663         struct task_security_struct *tsec;
4664         struct ipc_security_struct *isec;
4665         struct avc_audit_data ad;
4666         int rc;
4667
4668         rc = ipc_alloc_security(current, &sma->sem_perm, SECCLASS_SEM);
4669         if (rc)
4670                 return rc;
4671
4672         tsec = current->security;
4673         isec = sma->sem_perm.security;
4674
4675         AVC_AUDIT_DATA_INIT(&ad, IPC);
4676         ad.u.ipc_id = sma->sem_perm.key;
4677
4678         rc = avc_has_perm(tsec->sid, isec->sid, SECCLASS_SEM,
4679                           SEM__CREATE, &ad);
4680         if (rc) {
4681                 ipc_free_security(&sma->sem_perm);
4682                 return rc;
4683         }
4684         return 0;
4685 }
4686
4687 static void selinux_sem_free_security(struct sem_array *sma)
4688 {
4689         ipc_free_security(&sma->sem_perm);
4690 }
4691
4692 static int selinux_sem_associate(struct sem_array *sma, int semflg)
4693 {
4694         struct task_security_struct *tsec;
4695         struct ipc_security_struct *isec;
4696         struct avc_audit_data ad;
4697
4698         tsec = current->security;
4699         isec = sma->sem_perm.security;
4700
4701         AVC_AUDIT_DATA_INIT(&ad, IPC);
4702         ad.u.ipc_id = sma->sem_perm.key;
4703
4704         return avc_has_perm(tsec->sid, isec->sid, SECCLASS_SEM,
4705                             SEM__ASSOCIATE, &ad);
4706 }
4707
4708 /* Note, at this point, sma is locked down */
4709 static int selinux_sem_semctl(struct sem_array *sma, int cmd)
4710 {
4711         int err;
4712         u32 perms;
4713
4714         switch(cmd) {
4715         case IPC_INFO:
4716         case SEM_INFO:
4717                 /* No specific object, just general system-wide information. */
4718                 return task_has_system(current, SYSTEM__IPC_INFO);
4719         case GETPID:
4720         case GETNCNT:
4721         case GETZCNT:
4722                 perms = SEM__GETATTR;
4723                 break;
4724         case GETVAL:
4725         case GETALL:
4726                 perms = SEM__READ;
4727                 break;
4728         case SETVAL:
4729         case SETALL:
4730                 perms = SEM__WRITE;
4731                 break;
4732         case IPC_RMID:
4733                 perms = SEM__DESTROY;
4734                 break;
4735         case IPC_SET:
4736                 perms = SEM__SETATTR;
4737                 break;
4738         case IPC_STAT:
4739         case SEM_STAT:
4740                 perms = SEM__GETATTR | SEM__ASSOCIATE;
4741                 break;
4742         default:
4743                 return 0;
4744         }
4745
4746         err = ipc_has_perm(&sma->sem_perm, perms);
4747         return err;
4748 }
4749
4750 static int selinux_sem_semop(struct sem_array *sma,
4751                              struct sembuf *sops, unsigned nsops, int alter)
4752 {
4753         u32 perms;
4754
4755         if (alter)
4756                 perms = SEM__READ | SEM__WRITE;
4757         else
4758                 perms = SEM__READ;
4759
4760         return ipc_has_perm(&sma->sem_perm, perms);
4761 }
4762
4763 static int selinux_ipc_permission(struct kern_ipc_perm *ipcp, short flag)
4764 {
4765         u32 av = 0;
4766
4767         av = 0;
4768         if (flag & S_IRUGO)
4769                 av |= IPC__UNIX_READ;
4770         if (flag & S_IWUGO)
4771                 av |= IPC__UNIX_WRITE;
4772
4773         if (av == 0)
4774                 return 0;
4775
4776         return ipc_has_perm(ipcp, av);
4777 }
4778
4779 /* module stacking operations */
4780 static int selinux_register_security (const char *name, struct security_operations *ops)
4781 {
4782         if (secondary_ops != original_ops) {
4783                 printk(KERN_ERR "%s:  There is already a secondary security "
4784                        "module registered.\n", __FUNCTION__);
4785                 return -EINVAL;
4786         }
4787
4788         secondary_ops = ops;
4789
4790         printk(KERN_INFO "%s:  Registering secondary module %s\n",
4791                __FUNCTION__,
4792                name);
4793
4794         return 0;
4795 }
4796
4797 static void selinux_d_instantiate (struct dentry *dentry, struct inode *inode)
4798 {
4799         if (inode)
4800                 inode_doinit_with_dentry(inode, dentry);
4801 }
4802
4803 static int selinux_getprocattr(struct task_struct *p,
4804                                char *name, char **value)
4805 {
4806         struct task_security_struct *tsec;
4807         u32 sid;
4808         int error;
4809         unsigned len;
4810
4811         if (current != p) {
4812                 error = task_has_perm(current, p, PROCESS__GETATTR);
4813                 if (error)
4814                         return error;
4815         }
4816
4817         tsec = p->security;
4818
4819         if (!strcmp(name, "current"))
4820                 sid = tsec->sid;
4821         else if (!strcmp(name, "prev"))
4822                 sid = tsec->osid;
4823         else if (!strcmp(name, "exec"))
4824                 sid = tsec->exec_sid;
4825         else if (!strcmp(name, "fscreate"))
4826                 sid = tsec->create_sid;
4827         else if (!strcmp(name, "keycreate"))
4828                 sid = tsec->keycreate_sid;
4829         else if (!strcmp(name, "sockcreate"))
4830                 sid = tsec->sockcreate_sid;
4831         else
4832                 return -EINVAL;
4833
4834         if (!sid)
4835                 return 0;
4836
4837         error = security_sid_to_context(sid, value, &len);
4838         if (error)
4839                 return error;
4840         return len;
4841 }
4842
4843 static int selinux_setprocattr(struct task_struct *p,
4844                                char *name, void *value, size_t size)
4845 {
4846         struct task_security_struct *tsec;
4847         u32 sid = 0;
4848         int error;
4849         char *str = value;
4850
4851         if (current != p) {
4852                 /* SELinux only allows a process to change its own
4853                    security attributes. */
4854                 return -EACCES;
4855         }
4856
4857         /*
4858          * Basic control over ability to set these attributes at all.
4859          * current == p, but we'll pass them separately in case the
4860          * above restriction is ever removed.
4861          */
4862         if (!strcmp(name, "exec"))
4863                 error = task_has_perm(current, p, PROCESS__SETEXEC);
4864         else if (!strcmp(name, "fscreate"))
4865                 error = task_has_perm(current, p, PROCESS__SETFSCREATE);
4866         else if (!strcmp(name, "keycreate"))
4867                 error = task_has_perm(current, p, PROCESS__SETKEYCREATE);
4868         else if (!strcmp(name, "sockcreate"))
4869                 error = task_has_perm(current, p, PROCESS__SETSOCKCREATE);
4870         else if (!strcmp(name, "current"))
4871                 error = task_has_perm(current, p, PROCESS__SETCURRENT);
4872         else
4873                 error = -EINVAL;
4874         if (error)
4875                 return error;
4876
4877         /* Obtain a SID for the context, if one was specified. */
4878         if (size && str[1] && str[1] != '\n') {
4879                 if (str[size-1] == '\n') {
4880                         str[size-1] = 0;
4881                         size--;
4882                 }
4883                 error = security_context_to_sid(value, size, &sid);
4884                 if (error)
4885                         return error;
4886         }
4887
4888         /* Permission checking based on the specified context is
4889            performed during the actual operation (execve,
4890            open/mkdir/...), when we know the full context of the
4891            operation.  See selinux_bprm_set_security for the execve
4892            checks and may_create for the file creation checks. The
4893            operation will then fail if the context is not permitted. */
4894         tsec = p->security;
4895         if (!strcmp(name, "exec"))
4896                 tsec->exec_sid = sid;
4897         else if (!strcmp(name, "fscreate"))
4898                 tsec->create_sid = sid;
4899         else if (!strcmp(name, "keycreate")) {
4900                 error = may_create_key(sid, p);
4901                 if (error)
4902                         return error;
4903                 tsec->keycreate_sid = sid;
4904         } else if (!strcmp(name, "sockcreate"))
4905                 tsec->sockcreate_sid = sid;
4906         else if (!strcmp(name, "current")) {
4907                 struct av_decision avd;
4908
4909                 if (sid == 0)
4910                         return -EINVAL;
4911
4912                 /* Only allow single threaded processes to change context */
4913                 if (atomic_read(&p->mm->mm_users) != 1) {
4914                         struct task_struct *g, *t;
4915                         struct mm_struct *mm = p->mm;
4916                         read_lock(&tasklist_lock);
4917                         do_each_thread(g, t)
4918                                 if (t->mm == mm && t != p) {
4919                                         read_unlock(&tasklist_lock);
4920                                         return -EPERM;
4921                                 }
4922                         while_each_thread(g, t);
4923                         read_unlock(&tasklist_lock);
4924                 }
4925
4926                 /* Check permissions for the transition. */
4927                 error = avc_has_perm(tsec->sid, sid, SECCLASS_PROCESS,
4928                                      PROCESS__DYNTRANSITION, NULL);
4929                 if (error)
4930                         return error;
4931
4932                 /* Check for ptracing, and update the task SID if ok.
4933                    Otherwise, leave SID unchanged and fail. */
4934                 task_lock(p);
4935                 if (p->ptrace & PT_PTRACED) {
4936                         error = avc_has_perm_noaudit(tsec->ptrace_sid, sid,
4937                                                      SECCLASS_PROCESS,
4938                                                      PROCESS__PTRACE, 0, &avd);
4939                         if (!error)
4940                                 tsec->sid = sid;
4941                         task_unlock(p);
4942                         avc_audit(tsec->ptrace_sid, sid, SECCLASS_PROCESS,
4943                                   PROCESS__PTRACE, &avd, error, NULL);
4944                         if (error)
4945                                 return error;
4946                 } else {
4947                         tsec->sid = sid;
4948                         task_unlock(p);
4949                 }
4950         }
4951         else
4952                 return -EINVAL;
4953
4954         return size;
4955 }
4956
4957 static int selinux_secid_to_secctx(u32 secid, char **secdata, u32 *seclen)
4958 {
4959         return security_sid_to_context(secid, secdata, seclen);
4960 }
4961
4962 static int selinux_secctx_to_secid(char *secdata, u32 seclen, u32 *secid)
4963 {
4964         return security_context_to_sid(secdata, seclen, secid);
4965 }
4966
4967 static void selinux_release_secctx(char *secdata, u32 seclen)
4968 {
4969         kfree(secdata);
4970 }
4971
4972 #ifdef CONFIG_KEYS
4973
4974 static int selinux_key_alloc(struct key *k, struct task_struct *tsk,
4975                              unsigned long flags)
4976 {
4977         struct task_security_struct *tsec = tsk->security;
4978         struct key_security_struct *ksec;
4979
4980         ksec = kzalloc(sizeof(struct key_security_struct), GFP_KERNEL);
4981         if (!ksec)
4982                 return -ENOMEM;
4983
4984         ksec->obj = k;
4985         if (tsec->keycreate_sid)
4986                 ksec->sid = tsec->keycreate_sid;
4987         else
4988                 ksec->sid = tsec->sid;
4989         k->security = ksec;
4990
4991         return 0;
4992 }
4993
4994 static void selinux_key_free(struct key *k)
4995 {
4996         struct key_security_struct *ksec = k->security;
4997
4998         k->security = NULL;
4999         kfree(ksec);
5000 }
5001
5002 static int selinux_key_permission(key_ref_t key_ref,
5003                             struct task_struct *ctx,
5004                             key_perm_t perm)
5005 {
5006         struct key *key;
5007         struct task_security_struct *tsec;
5008         struct key_security_struct *ksec;
5009
5010         key = key_ref_to_ptr(key_ref);
5011
5012         tsec = ctx->security;
5013         ksec = key->security;
5014
5015         /* if no specific permissions are requested, we skip the
5016            permission check. No serious, additional covert channels
5017            appear to be created. */
5018         if (perm == 0)
5019                 return 0;
5020
5021         return avc_has_perm(tsec->sid, ksec->sid,
5022                             SECCLASS_KEY, perm, NULL);
5023 }
5024
5025 #endif
5026
5027 static struct security_operations selinux_ops = {
5028         .ptrace =                       selinux_ptrace,
5029         .capget =                       selinux_capget,
5030         .capset_check =                 selinux_capset_check,
5031         .capset_set =                   selinux_capset_set,
5032         .sysctl =                       selinux_sysctl,
5033         .capable =                      selinux_capable,
5034         .quotactl =                     selinux_quotactl,
5035         .quota_on =                     selinux_quota_on,
5036         .syslog =                       selinux_syslog,
5037         .vm_enough_memory =             selinux_vm_enough_memory,
5038
5039         .netlink_send =                 selinux_netlink_send,
5040         .netlink_recv =                 selinux_netlink_recv,
5041
5042         .bprm_alloc_security =          selinux_bprm_alloc_security,
5043         .bprm_free_security =           selinux_bprm_free_security,
5044         .bprm_apply_creds =             selinux_bprm_apply_creds,
5045         .bprm_post_apply_creds =        selinux_bprm_post_apply_creds,
5046         .bprm_set_security =            selinux_bprm_set_security,
5047         .bprm_check_security =          selinux_bprm_check_security,
5048         .bprm_secureexec =              selinux_bprm_secureexec,
5049
5050         .sb_alloc_security =            selinux_sb_alloc_security,
5051         .sb_free_security =             selinux_sb_free_security,
5052         .sb_copy_data =                 selinux_sb_copy_data,
5053         .sb_kern_mount =                selinux_sb_kern_mount,
5054         .sb_statfs =                    selinux_sb_statfs,
5055         .sb_mount =                     selinux_mount,
5056         .sb_umount =                    selinux_umount,
5057         .sb_get_mnt_opts =              selinux_get_mnt_opts,
5058         .sb_set_mnt_opts =              selinux_set_mnt_opts,
5059         .sb_clone_mnt_opts =            selinux_sb_clone_mnt_opts,
5060
5061         .inode_alloc_security =         selinux_inode_alloc_security,
5062         .inode_free_security =          selinux_inode_free_security,
5063         .inode_init_security =          selinux_inode_init_security,
5064         .inode_create =                 selinux_inode_create,
5065         .inode_link =                   selinux_inode_link,
5066         .inode_unlink =                 selinux_inode_unlink,
5067         .inode_symlink =                selinux_inode_symlink,
5068         .inode_mkdir =                  selinux_inode_mkdir,
5069         .inode_rmdir =                  selinux_inode_rmdir,
5070         .inode_mknod =                  selinux_inode_mknod,
5071         .inode_rename =                 selinux_inode_rename,
5072         .inode_readlink =               selinux_inode_readlink,
5073         .inode_follow_link =            selinux_inode_follow_link,
5074         .inode_permission =             selinux_inode_permission,
5075         .inode_setattr =                selinux_inode_setattr,
5076         .inode_getattr =                selinux_inode_getattr,
5077         .inode_setxattr =               selinux_inode_setxattr,
5078         .inode_post_setxattr =          selinux_inode_post_setxattr,
5079         .inode_getxattr =               selinux_inode_getxattr,
5080         .inode_listxattr =              selinux_inode_listxattr,
5081         .inode_removexattr =            selinux_inode_removexattr,
5082         .inode_getsecurity =            selinux_inode_getsecurity,
5083         .inode_setsecurity =            selinux_inode_setsecurity,
5084         .inode_listsecurity =           selinux_inode_listsecurity,
5085         .inode_need_killpriv =          selinux_inode_need_killpriv,
5086         .inode_killpriv =               selinux_inode_killpriv,
5087
5088         .file_permission =              selinux_file_permission,
5089         .file_alloc_security =          selinux_file_alloc_security,
5090         .file_free_security =           selinux_file_free_security,
5091         .file_ioctl =                   selinux_file_ioctl,
5092         .file_mmap =                    selinux_file_mmap,
5093         .file_mprotect =                selinux_file_mprotect,
5094         .file_lock =                    selinux_file_lock,
5095         .file_fcntl =                   selinux_file_fcntl,
5096         .file_set_fowner =              selinux_file_set_fowner,
5097         .file_send_sigiotask =          selinux_file_send_sigiotask,
5098         .file_receive =                 selinux_file_receive,
5099
5100         .dentry_open =                  selinux_dentry_open,
5101
5102         .task_create =                  selinux_task_create,
5103         .task_alloc_security =          selinux_task_alloc_security,
5104         .task_free_security =           selinux_task_free_security,
5105         .task_setuid =                  selinux_task_setuid,
5106         .task_post_setuid =             selinux_task_post_setuid,
5107         .task_setgid =                  selinux_task_setgid,
5108         .task_setpgid =                 selinux_task_setpgid,
5109         .task_getpgid =                 selinux_task_getpgid,
5110         .task_getsid =                  selinux_task_getsid,
5111         .task_getsecid =                selinux_task_getsecid,
5112         .task_setgroups =               selinux_task_setgroups,
5113         .task_setnice =                 selinux_task_setnice,
5114         .task_setioprio =               selinux_task_setioprio,
5115         .task_getioprio =               selinux_task_getioprio,
5116         .task_setrlimit =               selinux_task_setrlimit,
5117         .task_setscheduler =            selinux_task_setscheduler,
5118         .task_getscheduler =            selinux_task_getscheduler,
5119         .task_movememory =              selinux_task_movememory,
5120         .task_kill =                    selinux_task_kill,
5121         .task_wait =                    selinux_task_wait,
5122         .task_prctl =                   selinux_task_prctl,
5123         .task_reparent_to_init =        selinux_task_reparent_to_init,
5124         .task_to_inode =                selinux_task_to_inode,
5125
5126         .ipc_permission =               selinux_ipc_permission,
5127
5128         .msg_msg_alloc_security =       selinux_msg_msg_alloc_security,
5129         .msg_msg_free_security =        selinux_msg_msg_free_security,
5130
5131         .msg_queue_alloc_security =     selinux_msg_queue_alloc_security,
5132         .msg_queue_free_security =      selinux_msg_queue_free_security,
5133         .msg_queue_associate =          selinux_msg_queue_associate,
5134         .msg_queue_msgctl =             selinux_msg_queue_msgctl,
5135         .msg_queue_msgsnd =             selinux_msg_queue_msgsnd,
5136         .msg_queue_msgrcv =             selinux_msg_queue_msgrcv,
5137
5138         .shm_alloc_security =           selinux_shm_alloc_security,
5139         .shm_free_security =            selinux_shm_free_security,
5140         .shm_associate =                selinux_shm_associate,
5141         .shm_shmctl =                   selinux_shm_shmctl,
5142         .shm_shmat =                    selinux_shm_shmat,
5143
5144         .sem_alloc_security =           selinux_sem_alloc_security,
5145         .sem_free_security =            selinux_sem_free_security,
5146         .sem_associate =                selinux_sem_associate,
5147         .sem_semctl =                   selinux_sem_semctl,
5148         .sem_semop =                    selinux_sem_semop,
5149
5150         .register_security =            selinux_register_security,
5151
5152         .d_instantiate =                selinux_d_instantiate,
5153
5154         .getprocattr =                  selinux_getprocattr,
5155         .setprocattr =                  selinux_setprocattr,
5156
5157         .secid_to_secctx =              selinux_secid_to_secctx,
5158         .secctx_to_secid =              selinux_secctx_to_secid,
5159         .release_secctx =               selinux_release_secctx,
5160
5161         .unix_stream_connect =          selinux_socket_unix_stream_connect,
5162         .unix_may_send =                selinux_socket_unix_may_send,
5163
5164         .socket_create =                selinux_socket_create,
5165         .socket_post_create =           selinux_socket_post_create,
5166         .socket_bind =                  selinux_socket_bind,
5167         .socket_connect =               selinux_socket_connect,
5168         .socket_listen =                selinux_socket_listen,
5169         .socket_accept =                selinux_socket_accept,
5170         .socket_sendmsg =               selinux_socket_sendmsg,
5171         .socket_recvmsg =               selinux_socket_recvmsg,
5172         .socket_getsockname =           selinux_socket_getsockname,
5173         .socket_getpeername =           selinux_socket_getpeername,
5174         .socket_getsockopt =            selinux_socket_getsockopt,
5175         .socket_setsockopt =            selinux_socket_setsockopt,
5176         .socket_shutdown =              selinux_socket_shutdown,
5177         .socket_sock_rcv_skb =          selinux_socket_sock_rcv_skb,
5178         .socket_getpeersec_stream =     selinux_socket_getpeersec_stream,
5179         .socket_getpeersec_dgram =      selinux_socket_getpeersec_dgram,
5180         .sk_alloc_security =            selinux_sk_alloc_security,
5181         .sk_free_security =             selinux_sk_free_security,
5182         .sk_clone_security =            selinux_sk_clone_security,
5183         .sk_getsecid =                  selinux_sk_getsecid,
5184         .sock_graft =                   selinux_sock_graft,
5185         .inet_conn_request =            selinux_inet_conn_request,
5186         .inet_csk_clone =               selinux_inet_csk_clone,
5187         .inet_conn_established =        selinux_inet_conn_established,
5188         .req_classify_flow =            selinux_req_classify_flow,
5189
5190 #ifdef CONFIG_SECURITY_NETWORK_XFRM
5191         .xfrm_policy_alloc_security =   selinux_xfrm_policy_alloc,
5192         .xfrm_policy_clone_security =   selinux_xfrm_policy_clone,
5193         .xfrm_policy_free_security =    selinux_xfrm_policy_free,
5194         .xfrm_policy_delete_security =  selinux_xfrm_policy_delete,
5195         .xfrm_state_alloc_security =    selinux_xfrm_state_alloc,
5196         .xfrm_state_free_security =     selinux_xfrm_state_free,
5197         .xfrm_state_delete_security =   selinux_xfrm_state_delete,
5198         .xfrm_policy_lookup =           selinux_xfrm_policy_lookup,
5199         .xfrm_state_pol_flow_match =    selinux_xfrm_state_pol_flow_match,
5200         .xfrm_decode_session =          selinux_xfrm_decode_session,
5201 #endif
5202
5203 #ifdef CONFIG_KEYS
5204         .key_alloc =                    selinux_key_alloc,
5205         .key_free =                     selinux_key_free,
5206         .key_permission =               selinux_key_permission,
5207 #endif
5208 };
5209
5210 static __init int selinux_init(void)
5211 {
5212         struct task_security_struct *tsec;
5213
5214         if (!selinux_enabled) {
5215                 printk(KERN_INFO "SELinux:  Disabled at boot.\n");
5216                 return 0;
5217         }
5218
5219         printk(KERN_INFO "SELinux:  Initializing.\n");
5220
5221         /* Set the security state for the initial task. */
5222         if (task_alloc_security(current))
5223                 panic("SELinux:  Failed to initialize initial task.\n");
5224         tsec = current->security;
5225         tsec->osid = tsec->sid = SECINITSID_KERNEL;
5226
5227         sel_inode_cache = kmem_cache_create("selinux_inode_security",
5228                                             sizeof(struct inode_security_struct),
5229                                             0, SLAB_PANIC, NULL);
5230         avc_init();
5231
5232         original_ops = secondary_ops = security_ops;
5233         if (!secondary_ops)
5234                 panic ("SELinux: No initial security operations\n");
5235         if (register_security (&selinux_ops))
5236                 panic("SELinux: Unable to register with kernel.\n");
5237
5238         if (selinux_enforcing) {
5239                 printk(KERN_DEBUG "SELinux:  Starting in enforcing mode\n");
5240         } else {
5241                 printk(KERN_DEBUG "SELinux:  Starting in permissive mode\n");
5242         }
5243
5244 #ifdef CONFIG_KEYS
5245         /* Add security information to initial keyrings */
5246         selinux_key_alloc(&root_user_keyring, current,
5247                           KEY_ALLOC_NOT_IN_QUOTA);
5248         selinux_key_alloc(&root_session_keyring, current,
5249                           KEY_ALLOC_NOT_IN_QUOTA);
5250 #endif
5251
5252         return 0;
5253 }
5254
5255 void selinux_complete_init(void)
5256 {
5257         printk(KERN_DEBUG "SELinux:  Completing initialization.\n");
5258
5259         /* Set up any superblocks initialized prior to the policy load. */
5260         printk(KERN_DEBUG "SELinux:  Setting up existing superblocks.\n");
5261         spin_lock(&sb_lock);
5262         spin_lock(&sb_security_lock);
5263 next_sb:
5264         if (!list_empty(&superblock_security_head)) {
5265                 struct superblock_security_struct *sbsec =
5266                                 list_entry(superblock_security_head.next,
5267                                            struct superblock_security_struct,
5268                                            list);
5269                 struct super_block *sb = sbsec->sb;
5270                 sb->s_count++;
5271                 spin_unlock(&sb_security_lock);
5272                 spin_unlock(&sb_lock);
5273                 down_read(&sb->s_umount);
5274                 if (sb->s_root)
5275                         superblock_doinit(sb, NULL);
5276                 drop_super(sb);
5277                 spin_lock(&sb_lock);
5278                 spin_lock(&sb_security_lock);
5279                 list_del_init(&sbsec->list);
5280                 goto next_sb;
5281         }
5282         spin_unlock(&sb_security_lock);
5283         spin_unlock(&sb_lock);
5284 }
5285
5286 /* SELinux requires early initialization in order to label
5287    all processes and objects when they are created. */
5288 security_initcall(selinux_init);
5289
5290 #if defined(CONFIG_NETFILTER)
5291
5292 static struct nf_hook_ops selinux_ipv4_op = {
5293         .hook =         selinux_ipv4_postroute_last,
5294         .owner =        THIS_MODULE,
5295         .pf =           PF_INET,
5296         .hooknum =      NF_INET_POST_ROUTING,
5297         .priority =     NF_IP_PRI_SELINUX_LAST,
5298 };
5299
5300 #if defined(CONFIG_IPV6) || defined(CONFIG_IPV6_MODULE)
5301
5302 static struct nf_hook_ops selinux_ipv6_op = {
5303         .hook =         selinux_ipv6_postroute_last,
5304         .owner =        THIS_MODULE,
5305         .pf =           PF_INET6,
5306         .hooknum =      NF_INET_POST_ROUTING,
5307         .priority =     NF_IP6_PRI_SELINUX_LAST,
5308 };
5309
5310 #endif  /* IPV6 */
5311
5312 static int __init selinux_nf_ip_init(void)
5313 {
5314         int err = 0;
5315
5316         if (!selinux_enabled)
5317                 goto out;
5318
5319         printk(KERN_DEBUG "SELinux:  Registering netfilter hooks\n");
5320
5321         err = nf_register_hook(&selinux_ipv4_op);
5322         if (err)
5323                 panic("SELinux: nf_register_hook for IPv4: error %d\n", err);
5324
5325 #if defined(CONFIG_IPV6) || defined(CONFIG_IPV6_MODULE)
5326
5327         err = nf_register_hook(&selinux_ipv6_op);
5328         if (err)
5329                 panic("SELinux: nf_register_hook for IPv6: error %d\n", err);
5330
5331 #endif  /* IPV6 */
5332
5333 out:
5334         return err;
5335 }
5336
5337 __initcall(selinux_nf_ip_init);
5338
5339 #ifdef CONFIG_SECURITY_SELINUX_DISABLE
5340 static void selinux_nf_ip_exit(void)
5341 {
5342         printk(KERN_DEBUG "SELinux:  Unregistering netfilter hooks\n");
5343
5344         nf_unregister_hook(&selinux_ipv4_op);
5345 #if defined(CONFIG_IPV6) || defined(CONFIG_IPV6_MODULE)
5346         nf_unregister_hook(&selinux_ipv6_op);
5347 #endif  /* IPV6 */
5348 }
5349 #endif
5350
5351 #else /* CONFIG_NETFILTER */
5352
5353 #ifdef CONFIG_SECURITY_SELINUX_DISABLE
5354 #define selinux_nf_ip_exit()
5355 #endif
5356
5357 #endif /* CONFIG_NETFILTER */
5358
5359 #ifdef CONFIG_SECURITY_SELINUX_DISABLE
5360 int selinux_disable(void)
5361 {
5362         extern void exit_sel_fs(void);
5363         static int selinux_disabled = 0;
5364
5365         if (ss_initialized) {
5366                 /* Not permitted after initial policy load. */
5367                 return -EINVAL;
5368         }
5369
5370         if (selinux_disabled) {
5371                 /* Only do this once. */
5372                 return -EINVAL;
5373         }
5374
5375         printk(KERN_INFO "SELinux:  Disabled at runtime.\n");
5376
5377         selinux_disabled = 1;
5378         selinux_enabled = 0;
5379
5380         /* Reset security_ops to the secondary module, dummy or capability. */
5381         security_ops = secondary_ops;
5382
5383         /* Unregister netfilter hooks. */
5384         selinux_nf_ip_exit();
5385
5386         /* Unregister selinuxfs. */
5387         exit_sel_fs();
5388
5389         return 0;
5390 }
5391 #endif
5392
5393