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