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