patch-2_6_7-vs1_9_1_12
[linux-2.6.git] / security / selinux / hooks.c
1 /*
2  *  NSA Security-Enhanced Linux (SELinux) security module
3  *
4  *  This file contains the SELinux hook function implementations.
5  *
6  *  Authors:  Stephen Smalley, <sds@epoch.ncsc.mil>
7  *            Chris Vance, <cvance@nai.com>
8  *            Wayne Salamon, <wsalamon@nai.com>
9  *            James Morris <jmorris@redhat.com>
10  *
11  *  Copyright (C) 2001,2002 Networks Associates Technology, Inc.
12  *  Copyright (C) 2003 Red Hat, Inc., James Morris <jmorris@redhat.com>
13  *
14  *      This program is free software; you can redistribute it and/or modify
15  *      it under the terms of the GNU General Public License version 2,
16  *      as published by the Free Software Foundation.
17  */
18
19 #include <linux/config.h>
20 #include <linux/module.h>
21 #include <linux/init.h>
22 #include <linux/kernel.h>
23 #include <linux/ptrace.h>
24 #include <linux/errno.h>
25 #include <linux/sched.h>
26 #include <linux/security.h>
27 #include <linux/xattr.h>
28 #include <linux/capability.h>
29 #include <linux/unistd.h>
30 #include <linux/mm.h>
31 #include <linux/mman.h>
32 #include <linux/slab.h>
33 #include <linux/pagemap.h>
34 #include <linux/swap.h>
35 #include <linux/smp_lock.h>
36 #include <linux/spinlock.h>
37 #include <linux/syscalls.h>
38 #include <linux/file.h>
39 #include <linux/namei.h>
40 #include <linux/mount.h>
41 #include <linux/ext2_fs.h>
42 #include <linux/proc_fs.h>
43 #include <linux/kd.h>
44 #include <linux/netfilter_ipv4.h>
45 #include <linux/netfilter_ipv6.h>
46 #include <net/icmp.h>
47 #include <net/ip.h>             /* for sysctl_local_port_range[] */
48 #include <net/tcp.h>            /* struct or_callable used in sock_rcv_skb */
49 #include <asm/uaccess.h>
50 #include <asm/semaphore.h>
51 #include <asm/ioctls.h>
52 #include <linux/bitops.h>
53 #include <linux/interrupt.h>
54 #include <linux/netdevice.h>    /* for network interface checks */
55 #include <linux/netlink.h>
56 #include <linux/tcp.h>
57 #include <linux/udp.h>
58 #include <linux/quota.h>
59 #include <linux/un.h>           /* for Unix socket types */
60 #include <net/af_unix.h>        /* for Unix socket types */
61 #include <linux/parser.h>
62 #include <linux/nfs_mount.h>
63 #include <net/ipv6.h>
64 #include <linux/hugetlb.h>
65 #include <linux/major.h>
66
67 #include "avc.h"
68 #include "objsec.h"
69 #include "netif.h"
70
71 #define XATTR_SELINUX_SUFFIX "selinux"
72 #define XATTR_NAME_SELINUX XATTR_SECURITY_PREFIX XATTR_SELINUX_SUFFIX
73
74 #ifdef CONFIG_SECURITY_SELINUX_DEVELOP
75 int selinux_enforcing = 0;
76
77 static int __init enforcing_setup(char *str)
78 {
79         selinux_enforcing = simple_strtol(str,NULL,0);
80         return 1;
81 }
82 __setup("enforcing=", enforcing_setup);
83 #endif
84
85 #ifdef CONFIG_SECURITY_SELINUX_BOOTPARAM
86 int selinux_enabled = 1;
87
88 static int __init selinux_enabled_setup(char *str)
89 {
90         selinux_enabled = simple_strtol(str, NULL, 0);
91         return 1;
92 }
93 __setup("selinux=", selinux_enabled_setup);
94 #endif
95
96 /* Original (dummy) security module. */
97 static struct security_operations *original_ops = NULL;
98
99 /* Minimal support for a secondary security module,
100    just to allow the use of the dummy or capability modules.
101    The owlsm module can alternatively be used as a secondary
102    module as long as CONFIG_OWLSM_FD is not enabled. */
103 static struct security_operations *secondary_ops = NULL;
104
105 /* Lists of inode and superblock security structures initialized
106    before the policy was loaded. */
107 static LIST_HEAD(superblock_security_head);
108 static spinlock_t sb_security_lock = SPIN_LOCK_UNLOCKED;
109
110 /* Allocate and free functions for each kind of security blob. */
111
112 static int task_alloc_security(struct task_struct *task)
113 {
114         struct task_security_struct *tsec;
115
116         tsec = kmalloc(sizeof(struct task_security_struct), GFP_KERNEL);
117         if (!tsec)
118                 return -ENOMEM;
119
120         memset(tsec, 0, sizeof(struct task_security_struct));
121         tsec->magic = SELINUX_MAGIC;
122         tsec->task = task;
123         tsec->osid = tsec->sid = tsec->ptrace_sid = SECINITSID_UNLABELED;
124         task->security = tsec;
125
126         return 0;
127 }
128
129 static void task_free_security(struct task_struct *task)
130 {
131         struct task_security_struct *tsec = task->security;
132
133         if (!tsec || tsec->magic != SELINUX_MAGIC)
134                 return;
135
136         task->security = NULL;
137         kfree(tsec);
138 }
139
140 static int inode_alloc_security(struct inode *inode)
141 {
142         struct task_security_struct *tsec = current->security;
143         struct inode_security_struct *isec;
144
145         isec = kmalloc(sizeof(struct inode_security_struct), GFP_KERNEL);
146         if (!isec)
147                 return -ENOMEM;
148
149         memset(isec, 0, sizeof(struct inode_security_struct));
150         init_MUTEX(&isec->sem);
151         INIT_LIST_HEAD(&isec->list);
152         isec->magic = SELINUX_MAGIC;
153         isec->inode = inode;
154         isec->sid = SECINITSID_UNLABELED;
155         isec->sclass = SECCLASS_FILE;
156         if (tsec && tsec->magic == SELINUX_MAGIC)
157                 isec->task_sid = tsec->sid;
158         else
159                 isec->task_sid = SECINITSID_UNLABELED;
160         inode->i_security = isec;
161
162         return 0;
163 }
164
165 static void inode_free_security(struct inode *inode)
166 {
167         struct inode_security_struct *isec = inode->i_security;
168         struct superblock_security_struct *sbsec = inode->i_sb->s_security;
169
170         if (!isec || isec->magic != SELINUX_MAGIC)
171                 return;
172
173         spin_lock(&sbsec->isec_lock);
174         if (!list_empty(&isec->list))
175                 list_del_init(&isec->list);
176         spin_unlock(&sbsec->isec_lock);
177
178         inode->i_security = NULL;
179         kfree(isec);
180 }
181
182 static int file_alloc_security(struct file *file)
183 {
184         struct task_security_struct *tsec = current->security;
185         struct file_security_struct *fsec;
186
187         fsec = kmalloc(sizeof(struct file_security_struct), GFP_ATOMIC);
188         if (!fsec)
189                 return -ENOMEM;
190
191         memset(fsec, 0, sizeof(struct file_security_struct));
192         fsec->magic = SELINUX_MAGIC;
193         fsec->file = file;
194         if (tsec && tsec->magic == SELINUX_MAGIC) {
195                 fsec->sid = tsec->sid;
196                 fsec->fown_sid = tsec->sid;
197         } else {
198                 fsec->sid = SECINITSID_UNLABELED;
199                 fsec->fown_sid = SECINITSID_UNLABELED;
200         }
201         file->f_security = fsec;
202
203         return 0;
204 }
205
206 static void file_free_security(struct file *file)
207 {
208         struct file_security_struct *fsec = file->f_security;
209
210         if (!fsec || fsec->magic != SELINUX_MAGIC)
211                 return;
212
213         file->f_security = NULL;
214         kfree(fsec);
215 }
216
217 static int superblock_alloc_security(struct super_block *sb)
218 {
219         struct superblock_security_struct *sbsec;
220
221         sbsec = kmalloc(sizeof(struct superblock_security_struct), GFP_KERNEL);
222         if (!sbsec)
223                 return -ENOMEM;
224
225         memset(sbsec, 0, sizeof(struct superblock_security_struct));
226         init_MUTEX(&sbsec->sem);
227         INIT_LIST_HEAD(&sbsec->list);
228         INIT_LIST_HEAD(&sbsec->isec_head);
229         spin_lock_init(&sbsec->isec_lock);
230         sbsec->magic = SELINUX_MAGIC;
231         sbsec->sb = sb;
232         sbsec->sid = SECINITSID_UNLABELED;
233         sbsec->def_sid = SECINITSID_FILE;
234         sb->s_security = sbsec;
235
236         return 0;
237 }
238
239 static void superblock_free_security(struct super_block *sb)
240 {
241         struct superblock_security_struct *sbsec = sb->s_security;
242
243         if (!sbsec || sbsec->magic != SELINUX_MAGIC)
244                 return;
245
246         spin_lock(&sb_security_lock);
247         if (!list_empty(&sbsec->list))
248                 list_del_init(&sbsec->list);
249         spin_unlock(&sb_security_lock);
250
251         sb->s_security = NULL;
252         kfree(sbsec);
253 }
254
255 #ifdef CONFIG_SECURITY_NETWORK
256 static int sk_alloc_security(struct sock *sk, int family, int priority)
257 {
258         struct sk_security_struct *ssec;
259
260         if (family != PF_UNIX)
261                 return 0;
262
263         ssec = kmalloc(sizeof(*ssec), priority);
264         if (!ssec)
265                 return -ENOMEM;
266
267         memset(ssec, 0, sizeof(*ssec));
268         ssec->magic = SELINUX_MAGIC;
269         ssec->sk = sk;
270         ssec->peer_sid = SECINITSID_UNLABELED;
271         sk->sk_security = ssec;
272
273         return 0;
274 }
275
276 static void sk_free_security(struct sock *sk)
277 {
278         struct sk_security_struct *ssec = sk->sk_security;
279
280         if (sk->sk_family != PF_UNIX || ssec->magic != SELINUX_MAGIC)
281                 return;
282
283         sk->sk_security = NULL;
284         kfree(ssec);
285 }
286 #endif  /* CONFIG_SECURITY_NETWORK */
287
288 /* The security server must be initialized before
289    any labeling or access decisions can be provided. */
290 extern int ss_initialized;
291
292 /* The file system's label must be initialized prior to use. */
293
294 static char *labeling_behaviors[6] = {
295         "uses xattr",
296         "uses transition SIDs",
297         "uses task SIDs",
298         "uses genfs_contexts",
299         "not configured for labeling",
300         "uses mountpoint labeling",
301 };
302
303 static int inode_doinit_with_dentry(struct inode *inode, struct dentry *opt_dentry);
304
305 static inline int inode_doinit(struct inode *inode)
306 {
307         return inode_doinit_with_dentry(inode, NULL);
308 }
309
310 enum {
311         Opt_context = 1,
312         Opt_fscontext = 2,
313         Opt_defcontext = 4,
314 };
315
316 static match_table_t tokens = {
317         {Opt_context, "context=%s"},
318         {Opt_fscontext, "fscontext=%s"},
319         {Opt_defcontext, "defcontext=%s"},
320 };
321
322 #define SEL_MOUNT_FAIL_MSG "SELinux:  duplicate or incompatible mount options\n"
323
324 static int try_context_mount(struct super_block *sb, void *data)
325 {
326         char *context = NULL, *defcontext = NULL;
327         const char *name;
328         u32 sid;
329         int alloc = 0, rc = 0, seen = 0;
330         struct task_security_struct *tsec = current->security;
331         struct superblock_security_struct *sbsec = sb->s_security;
332
333         if (!data)
334                 goto out;
335
336         name = sb->s_type->name;
337
338         if (sb->s_type->fs_flags & FS_BINARY_MOUNTDATA) {
339
340                 /* NFS we understand. */
341                 if (!strcmp(name, "nfs")) {
342                         struct nfs_mount_data *d = data;
343
344                         if (d->version <  NFS_MOUNT_VERSION)
345                                 goto out;
346
347                         if (d->context[0]) {
348                                 context = d->context;
349                                 seen |= Opt_context;
350                         }
351                 } else
352                         goto out;
353
354         } else {
355                 /* Standard string-based options. */
356                 char *p, *options = data;
357
358                 while ((p = strsep(&options, ",")) != NULL) {
359                         int token;
360                         substring_t args[MAX_OPT_ARGS];
361
362                         if (!*p)
363                                 continue;
364
365                         token = match_token(p, tokens, args);
366
367                         switch (token) {
368                         case Opt_context:
369                                 if (seen) {
370                                         rc = -EINVAL;
371                                         printk(KERN_WARNING SEL_MOUNT_FAIL_MSG);
372                                         goto out_free;
373                                 }
374                                 context = match_strdup(&args[0]);
375                                 if (!context) {
376                                         rc = -ENOMEM;
377                                         goto out_free;
378                                 }
379                                 if (!alloc)
380                                         alloc = 1;
381                                 seen |= Opt_context;
382                                 break;
383
384                         case Opt_fscontext:
385                                 if (sbsec->behavior != SECURITY_FS_USE_XATTR) {
386                                         rc = -EINVAL;
387                                         printk(KERN_WARNING "SELinux:  "
388                                                "fscontext option is invalid for"
389                                                " this filesystem type\n");
390                                         goto out_free;
391                                 }
392                                 if (seen & (Opt_context|Opt_fscontext)) {
393                                         rc = -EINVAL;
394                                         printk(KERN_WARNING SEL_MOUNT_FAIL_MSG);
395                                         goto out_free;
396                                 }
397                                 context = match_strdup(&args[0]);
398                                 if (!context) {
399                                         rc = -ENOMEM;
400                                         goto out_free;
401                                 }
402                                 if (!alloc)
403                                         alloc = 1;
404                                 seen |= Opt_fscontext;
405                                 break;
406
407                         case Opt_defcontext:
408                                 if (sbsec->behavior != SECURITY_FS_USE_XATTR) {
409                                         rc = -EINVAL;
410                                         printk(KERN_WARNING "SELinux:  "
411                                                "defcontext option is invalid "
412                                                "for this filesystem type\n");
413                                         goto out_free;
414                                 }
415                                 if (seen & (Opt_context|Opt_defcontext)) {
416                                         rc = -EINVAL;
417                                         printk(KERN_WARNING SEL_MOUNT_FAIL_MSG);
418                                         goto out_free;
419                                 }
420                                 defcontext = match_strdup(&args[0]);
421                                 if (!defcontext) {
422                                         rc = -ENOMEM;
423                                         goto out_free;
424                                 }
425                                 if (!alloc)
426                                         alloc = 1;
427                                 seen |= Opt_defcontext;
428                                 break;
429
430                         default:
431                                 rc = -EINVAL;
432                                 printk(KERN_WARNING "SELinux:  unknown mount "
433                                        "option\n");
434                                 goto out_free;
435
436                         }
437                 }
438         }
439
440         if (!seen)
441                 goto out;
442
443         if (context) {
444                 rc = security_context_to_sid(context, strlen(context), &sid);
445                 if (rc) {
446                         printk(KERN_WARNING "SELinux: security_context_to_sid"
447                                "(%s) failed for (dev %s, type %s) errno=%d\n",
448                                context, sb->s_id, name, rc);
449                         goto out_free;
450                 }
451
452                 rc = avc_has_perm(tsec->sid, sbsec->sid, SECCLASS_FILESYSTEM,
453                                   FILESYSTEM__RELABELFROM, NULL, NULL);
454                 if (rc)
455                         goto out_free;
456
457                 rc = avc_has_perm(tsec->sid, sid, SECCLASS_FILESYSTEM,
458                                   FILESYSTEM__RELABELTO, NULL, NULL);
459                 if (rc)
460                         goto out_free;
461
462                 sbsec->sid = sid;
463
464                 if (seen & Opt_context)
465                         sbsec->behavior = SECURITY_FS_USE_MNTPOINT;
466         }
467
468         if (defcontext) {
469                 rc = security_context_to_sid(defcontext, strlen(defcontext), &sid);
470                 if (rc) {
471                         printk(KERN_WARNING "SELinux: security_context_to_sid"
472                                "(%s) failed for (dev %s, type %s) errno=%d\n",
473                                defcontext, sb->s_id, name, rc);
474                         goto out_free;
475                 }
476
477                 if (sid == sbsec->def_sid)
478                         goto out_free;
479
480                 rc = avc_has_perm(tsec->sid, sbsec->sid, SECCLASS_FILESYSTEM,
481                                   FILESYSTEM__RELABELFROM, NULL, NULL);
482                 if (rc)
483                         goto out_free;
484
485                 rc = avc_has_perm(sid, sbsec->sid, SECCLASS_FILESYSTEM,
486                                   FILESYSTEM__ASSOCIATE, NULL, NULL);
487                 if (rc)
488                         goto out_free;
489
490                 sbsec->def_sid = sid;
491         }
492
493 out_free:
494         if (alloc) {
495                 kfree(context);
496                 kfree(defcontext);
497         }
498 out:
499         return rc;
500 }
501
502 static int superblock_doinit(struct super_block *sb, void *data)
503 {
504         struct superblock_security_struct *sbsec = sb->s_security;
505         struct dentry *root = sb->s_root;
506         struct inode *inode = root->d_inode;
507         int rc = 0;
508
509         down(&sbsec->sem);
510         if (sbsec->initialized)
511                 goto out;
512
513         if (!ss_initialized) {
514                 /* Defer initialization until selinux_complete_init,
515                    after the initial policy is loaded and the security
516                    server is ready to handle calls. */
517                 spin_lock(&sb_security_lock);
518                 if (list_empty(&sbsec->list))
519                         list_add(&sbsec->list, &superblock_security_head);
520                 spin_unlock(&sb_security_lock);
521                 goto out;
522         }
523
524         /* Determine the labeling behavior to use for this filesystem type. */
525         rc = security_fs_use(sb->s_type->name, &sbsec->behavior, &sbsec->sid);
526         if (rc) {
527                 printk(KERN_WARNING "%s:  security_fs_use(%s) returned %d\n",
528                        __FUNCTION__, sb->s_type->name, rc);
529                 goto out;
530         }
531
532         rc = try_context_mount(sb, data);
533         if (rc)
534                 goto out;
535
536         if (sbsec->behavior == SECURITY_FS_USE_XATTR) {
537                 /* Make sure that the xattr handler exists and that no
538                    error other than -ENODATA is returned by getxattr on
539                    the root directory.  -ENODATA is ok, as this may be
540                    the first boot of the SELinux kernel before we have
541                    assigned xattr values to the filesystem. */
542                 if (!inode->i_op->getxattr) {
543                         printk(KERN_WARNING "SELinux: (dev %s, type %s) has no "
544                                "xattr support\n", sb->s_id, sb->s_type->name);
545                         rc = -EOPNOTSUPP;
546                         goto out;
547                 }
548                 rc = inode->i_op->getxattr(root, XATTR_NAME_SELINUX, NULL, 0);
549                 if (rc < 0 && rc != -ENODATA) {
550                         if (rc == -EOPNOTSUPP)
551                                 printk(KERN_WARNING "SELinux: (dev %s, type "
552                                        "%s) has no security xattr handler\n",
553                                        sb->s_id, sb->s_type->name);
554                         else
555                                 printk(KERN_WARNING "SELinux: (dev %s, type "
556                                        "%s) getxattr errno %d\n", sb->s_id,
557                                        sb->s_type->name, -rc);
558                         goto out;
559                 }
560         }
561
562         if (strcmp(sb->s_type->name, "proc") == 0)
563                 sbsec->proc = 1;
564
565         sbsec->initialized = 1;
566
567         if (sbsec->behavior > ARRAY_SIZE(labeling_behaviors)) {
568                 printk(KERN_INFO "SELinux: initialized (dev %s, type %s), unknown behavior\n",
569                        sb->s_id, sb->s_type->name);
570         }
571         else {
572                 printk(KERN_INFO "SELinux: initialized (dev %s, type %s), %s\n",
573                        sb->s_id, sb->s_type->name,
574                        labeling_behaviors[sbsec->behavior-1]);
575         }
576
577         /* Initialize the root inode. */
578         rc = inode_doinit_with_dentry(sb->s_root->d_inode, sb->s_root);
579
580         /* Initialize any other inodes associated with the superblock, e.g.
581            inodes created prior to initial policy load or inodes created
582            during get_sb by a pseudo filesystem that directly
583            populates itself. */
584         spin_lock(&sbsec->isec_lock);
585 next_inode:
586         if (!list_empty(&sbsec->isec_head)) {
587                 struct inode_security_struct *isec =
588                                 list_entry(sbsec->isec_head.next,
589                                            struct inode_security_struct, list);
590                 struct inode *inode = isec->inode;
591                 spin_unlock(&sbsec->isec_lock);
592                 inode = igrab(inode);
593                 if (inode) {
594                         inode_doinit(inode);
595                         iput(inode);
596                 }
597                 spin_lock(&sbsec->isec_lock);
598                 list_del_init(&isec->list);
599                 goto next_inode;
600         }
601         spin_unlock(&sbsec->isec_lock);
602 out:
603         up(&sbsec->sem);
604         return rc;
605 }
606
607 static inline u16 inode_mode_to_security_class(umode_t mode)
608 {
609         switch (mode & S_IFMT) {
610         case S_IFSOCK:
611                 return SECCLASS_SOCK_FILE;
612         case S_IFLNK:
613                 return SECCLASS_LNK_FILE;
614         case S_IFREG:
615                 return SECCLASS_FILE;
616         case S_IFBLK:
617                 return SECCLASS_BLK_FILE;
618         case S_IFDIR:
619                 return SECCLASS_DIR;
620         case S_IFCHR:
621                 return SECCLASS_CHR_FILE;
622         case S_IFIFO:
623                 return SECCLASS_FIFO_FILE;
624
625         }
626
627         return SECCLASS_FILE;
628 }
629
630 static inline u16 socket_type_to_security_class(int family, int type)
631 {
632         switch (family) {
633         case PF_UNIX:
634                 switch (type) {
635                 case SOCK_STREAM:
636                         return SECCLASS_UNIX_STREAM_SOCKET;
637                 case SOCK_DGRAM:
638                         return SECCLASS_UNIX_DGRAM_SOCKET;
639                 }
640         case PF_INET:
641         case PF_INET6:
642                 switch (type) {
643                 case SOCK_STREAM:
644                         return SECCLASS_TCP_SOCKET;
645                 case SOCK_DGRAM:
646                         return SECCLASS_UDP_SOCKET;
647                 case SOCK_RAW:
648                         return SECCLASS_RAWIP_SOCKET;
649                 }
650         case PF_NETLINK:
651                 return SECCLASS_NETLINK_SOCKET;
652         case PF_PACKET:
653                 return SECCLASS_PACKET_SOCKET;
654         case PF_KEY:
655                 return SECCLASS_KEY_SOCKET;
656         }
657
658         return SECCLASS_SOCKET;
659 }
660
661 #ifdef CONFIG_PROC_FS
662 static int selinux_proc_get_sid(struct proc_dir_entry *de,
663                                 u16 tclass,
664                                 u32 *sid)
665 {
666         int buflen, rc;
667         char *buffer, *path, *end;
668
669         buffer = (char*)__get_free_page(GFP_KERNEL);
670         if (!buffer)
671                 return -ENOMEM;
672
673         buflen = PAGE_SIZE;
674         end = buffer+buflen;
675         *--end = '\0';
676         buflen--;
677         path = end-1;
678         *path = '/';
679         while (de && de != de->parent) {
680                 buflen -= de->namelen + 1;
681                 if (buflen < 0)
682                         break;
683                 end -= de->namelen;
684                 memcpy(end, de->name, de->namelen);
685                 *--end = '/';
686                 path = end;
687                 de = de->parent;
688         }
689         rc = security_genfs_sid("proc", path, tclass, sid);
690         free_page((unsigned long)buffer);
691         return rc;
692 }
693 #else
694 static int selinux_proc_get_sid(struct proc_dir_entry *de,
695                                 u16 tclass,
696                                 u32 *sid)
697 {
698         return -EINVAL;
699 }
700 #endif
701
702 /* The inode's security attributes must be initialized before first use. */
703 static int inode_doinit_with_dentry(struct inode *inode, struct dentry *opt_dentry)
704 {
705         struct superblock_security_struct *sbsec = NULL;
706         struct inode_security_struct *isec = inode->i_security;
707         u32 sid;
708         struct dentry *dentry;
709 #define INITCONTEXTLEN 255
710         char *context = NULL;
711         unsigned len = 0;
712         int rc = 0;
713         int hold_sem = 0;
714
715         if (isec->initialized)
716                 goto out;
717
718         down(&isec->sem);
719         hold_sem = 1;
720         if (isec->initialized)
721                 goto out;
722
723         sbsec = inode->i_sb->s_security;
724         if (!sbsec->initialized) {
725                 /* Defer initialization until selinux_complete_init,
726                    after the initial policy is loaded and the security
727                    server is ready to handle calls. */
728                 spin_lock(&sbsec->isec_lock);
729                 if (list_empty(&isec->list))
730                         list_add(&isec->list, &sbsec->isec_head);
731                 spin_unlock(&sbsec->isec_lock);
732                 goto out;
733         }
734
735         switch (sbsec->behavior) {
736         case SECURITY_FS_USE_XATTR:
737                 if (!inode->i_op->getxattr) {
738                         isec->sid = sbsec->def_sid;
739                         break;
740                 }
741
742                 /* Need a dentry, since the xattr API requires one.
743                    Life would be simpler if we could just pass the inode. */
744                 if (opt_dentry) {
745                         /* Called from d_instantiate or d_splice_alias. */
746                         dentry = dget(opt_dentry);
747                 } else {
748                         /* Called from selinux_complete_init, try to find a dentry. */
749                         dentry = d_find_alias(inode);
750                 }
751                 if (!dentry) {
752                         printk(KERN_WARNING "%s:  no dentry for dev=%s "
753                                "ino=%ld\n", __FUNCTION__, inode->i_sb->s_id,
754                                inode->i_ino);
755                         goto out;
756                 }
757
758                 len = INITCONTEXTLEN;
759                 context = kmalloc(len, GFP_KERNEL);
760                 if (!context) {
761                         rc = -ENOMEM;
762                         dput(dentry);
763                         goto out;
764                 }
765                 rc = inode->i_op->getxattr(dentry, XATTR_NAME_SELINUX,
766                                            context, len);
767                 if (rc == -ERANGE) {
768                         /* Need a larger buffer.  Query for the right size. */
769                         rc = inode->i_op->getxattr(dentry, XATTR_NAME_SELINUX,
770                                                    NULL, 0);
771                         if (rc < 0) {
772                                 dput(dentry);
773                                 goto out;
774                         }
775                         kfree(context);
776                         len = rc;
777                         context = kmalloc(len, GFP_KERNEL);
778                         if (!context) {
779                                 rc = -ENOMEM;
780                                 dput(dentry);
781                                 goto out;
782                         }
783                         rc = inode->i_op->getxattr(dentry,
784                                                    XATTR_NAME_SELINUX,
785                                                    context, len);
786                 }
787                 dput(dentry);
788                 if (rc < 0) {
789                         if (rc != -ENODATA) {
790                                 printk(KERN_WARNING "%s:  getxattr returned "
791                                        "%d for dev=%s ino=%ld\n", __FUNCTION__,
792                                        -rc, inode->i_sb->s_id, inode->i_ino);
793                                 kfree(context);
794                                 goto out;
795                         }
796                         /* Map ENODATA to the default file SID */
797                         sid = sbsec->def_sid;
798                         rc = 0;
799                 } else {
800                         rc = security_context_to_sid(context, rc, &sid);
801                         if (rc) {
802                                 printk(KERN_WARNING "%s:  context_to_sid(%s) "
803                                        "returned %d for dev=%s ino=%ld\n",
804                                        __FUNCTION__, context, -rc,
805                                        inode->i_sb->s_id, inode->i_ino);
806                                 kfree(context);
807                                 goto out;
808                         }
809                 }
810                 kfree(context);
811                 isec->sid = sid;
812                 break;
813         case SECURITY_FS_USE_TASK:
814                 isec->sid = isec->task_sid;
815                 break;
816         case SECURITY_FS_USE_TRANS:
817                 /* Default to the fs SID. */
818                 isec->sid = sbsec->sid;
819
820                 /* Try to obtain a transition SID. */
821                 isec->sclass = inode_mode_to_security_class(inode->i_mode);
822                 rc = security_transition_sid(isec->task_sid,
823                                              sbsec->sid,
824                                              isec->sclass,
825                                              &sid);
826                 if (rc)
827                         goto out;
828                 isec->sid = sid;
829                 break;
830         default:
831                 /* Default to the fs SID. */
832                 isec->sid = sbsec->sid;
833
834                 if (sbsec->proc) {
835                         struct proc_inode *proci = PROC_I(inode);
836                         if (proci->pde) {
837                                 isec->sclass = inode_mode_to_security_class(inode->i_mode);
838                                 rc = selinux_proc_get_sid(proci->pde,
839                                                           isec->sclass,
840                                                           &sid);
841                                 if (rc)
842                                         goto out;
843                                 isec->sid = sid;
844                         }
845                 }
846                 break;
847         }
848
849         isec->initialized = 1;
850
851 out:
852         if (inode->i_sock) {
853                 struct socket *sock = SOCKET_I(inode);
854                 if (sock->sk) {
855                         isec->sclass = socket_type_to_security_class(sock->sk->sk_family,
856                                                                      sock->sk->sk_type);
857                 } else {
858                         isec->sclass = SECCLASS_SOCKET;
859                 }
860         } else {
861                 isec->sclass = inode_mode_to_security_class(inode->i_mode);
862         }
863
864         if (hold_sem)
865                 up(&isec->sem);
866         return rc;
867 }
868
869 /* Convert a Linux signal to an access vector. */
870 static inline u32 signal_to_av(int sig)
871 {
872         u32 perm = 0;
873
874         switch (sig) {
875         case SIGCHLD:
876                 /* Commonly granted from child to parent. */
877                 perm = PROCESS__SIGCHLD;
878                 break;
879         case SIGKILL:
880                 /* Cannot be caught or ignored */
881                 perm = PROCESS__SIGKILL;
882                 break;
883         case SIGSTOP:
884                 /* Cannot be caught or ignored */
885                 perm = PROCESS__SIGSTOP;
886                 break;
887         default:
888                 /* All other signals. */
889                 perm = PROCESS__SIGNAL;
890                 break;
891         }
892
893         return perm;
894 }
895
896 /* Check permission betweeen a pair of tasks, e.g. signal checks,
897    fork check, ptrace check, etc. */
898 int task_has_perm(struct task_struct *tsk1,
899                   struct task_struct *tsk2,
900                   u32 perms)
901 {
902         struct task_security_struct *tsec1, *tsec2;
903
904         tsec1 = tsk1->security;
905         tsec2 = tsk2->security;
906         return avc_has_perm(tsec1->sid, tsec2->sid,
907                             SECCLASS_PROCESS, perms, &tsec2->avcr, NULL);
908 }
909
910 /* Check whether a task is allowed to use a capability. */
911 int task_has_capability(struct task_struct *tsk,
912                         int cap)
913 {
914         struct task_security_struct *tsec;
915         struct avc_audit_data ad;
916
917         tsec = tsk->security;
918
919         AVC_AUDIT_DATA_INIT(&ad,CAP);
920         ad.tsk = tsk;
921         ad.u.cap = cap;
922
923         return avc_has_perm(tsec->sid, tsec->sid,
924                             SECCLASS_CAPABILITY, CAP_TO_MASK(cap), NULL, &ad);
925 }
926
927 /* Check whether a task is allowed to use a system operation. */
928 int task_has_system(struct task_struct *tsk,
929                     u32 perms)
930 {
931         struct task_security_struct *tsec;
932
933         tsec = tsk->security;
934
935         return avc_has_perm(tsec->sid, SECINITSID_KERNEL,
936                             SECCLASS_SYSTEM, perms, NULL, NULL);
937 }
938
939 /* Check whether a task has a particular permission to an inode.
940    The 'aeref' parameter is optional and allows other AVC
941    entry references to be passed (e.g. the one in the struct file).
942    The 'adp' parameter is optional and allows other audit
943    data to be passed (e.g. the dentry). */
944 int inode_has_perm(struct task_struct *tsk,
945                    struct inode *inode,
946                    u32 perms,
947                    struct avc_entry_ref *aeref,
948                    struct avc_audit_data *adp)
949 {
950         struct task_security_struct *tsec;
951         struct inode_security_struct *isec;
952         struct avc_audit_data ad;
953
954         tsec = tsk->security;
955         isec = inode->i_security;
956
957         if (!adp) {
958                 adp = &ad;
959                 AVC_AUDIT_DATA_INIT(&ad, FS);
960                 ad.u.fs.inode = inode;
961         }
962
963         return avc_has_perm(tsec->sid, isec->sid, isec->sclass,
964                             perms, aeref ? aeref : &isec->avcr, adp);
965 }
966
967 /* Same as inode_has_perm, but pass explicit audit data containing
968    the dentry to help the auditing code to more easily generate the
969    pathname if needed. */
970 static inline int dentry_has_perm(struct task_struct *tsk,
971                                   struct vfsmount *mnt,
972                                   struct dentry *dentry,
973                                   u32 av)
974 {
975         struct inode *inode = dentry->d_inode;
976         struct avc_audit_data ad;
977         AVC_AUDIT_DATA_INIT(&ad,FS);
978         ad.u.fs.mnt = mnt;
979         ad.u.fs.dentry = dentry;
980         return inode_has_perm(tsk, inode, av, NULL, &ad);
981 }
982
983 /* Check whether a task can use an open file descriptor to
984    access an inode in a given way.  Check access to the
985    descriptor itself, and then use dentry_has_perm to
986    check a particular permission to the file.
987    Access to the descriptor is implicitly granted if it
988    has the same SID as the process.  If av is zero, then
989    access to the file is not checked, e.g. for cases
990    where only the descriptor is affected like seek. */
991 static inline int file_has_perm(struct task_struct *tsk,
992                                 struct file *file,
993                                 u32 av)
994 {
995         struct task_security_struct *tsec = tsk->security;
996         struct file_security_struct *fsec = file->f_security;
997         struct vfsmount *mnt = file->f_vfsmnt;
998         struct dentry *dentry = file->f_dentry;
999         struct inode *inode = dentry->d_inode;
1000         struct avc_audit_data ad;
1001         int rc;
1002
1003         AVC_AUDIT_DATA_INIT(&ad, FS);
1004         ad.u.fs.mnt = mnt;
1005         ad.u.fs.dentry = dentry;
1006
1007         if (tsec->sid != fsec->sid) {
1008                 rc = avc_has_perm(tsec->sid, fsec->sid,
1009                                   SECCLASS_FD,
1010                                   FD__USE,
1011                                   &fsec->avcr, &ad);
1012                 if (rc)
1013                         return rc;
1014         }
1015
1016         /* av is zero if only checking access to the descriptor. */
1017         if (av)
1018                 return inode_has_perm(tsk, inode, av, &fsec->inode_avcr, &ad);
1019
1020         return 0;
1021 }
1022
1023 /* Check whether a task can create a file. */
1024 static int may_create(struct inode *dir,
1025                       struct dentry *dentry,
1026                       u16 tclass)
1027 {
1028         struct task_security_struct *tsec;
1029         struct inode_security_struct *dsec;
1030         struct superblock_security_struct *sbsec;
1031         u32 newsid;
1032         struct avc_audit_data ad;
1033         int rc;
1034
1035         tsec = current->security;
1036         dsec = dir->i_security;
1037         sbsec = dir->i_sb->s_security;
1038
1039         AVC_AUDIT_DATA_INIT(&ad, FS);
1040         ad.u.fs.dentry = dentry;
1041
1042         rc = avc_has_perm(tsec->sid, dsec->sid, SECCLASS_DIR,
1043                           DIR__ADD_NAME | DIR__SEARCH,
1044                           &dsec->avcr, &ad);
1045         if (rc)
1046                 return rc;
1047
1048         if (tsec->create_sid && sbsec->behavior != SECURITY_FS_USE_MNTPOINT) {
1049                 newsid = tsec->create_sid;
1050         } else {
1051                 rc = security_transition_sid(tsec->sid, dsec->sid, tclass,
1052                                              &newsid);
1053                 if (rc)
1054                         return rc;
1055         }
1056
1057         rc = avc_has_perm(tsec->sid, newsid, tclass, FILE__CREATE, NULL, &ad);
1058         if (rc)
1059                 return rc;
1060
1061         return avc_has_perm(newsid, sbsec->sid,
1062                             SECCLASS_FILESYSTEM,
1063                             FILESYSTEM__ASSOCIATE, NULL, &ad);
1064 }
1065
1066 #define MAY_LINK   0
1067 #define MAY_UNLINK 1
1068 #define MAY_RMDIR  2
1069
1070 /* Check whether a task can link, unlink, or rmdir a file/directory. */
1071 static int may_link(struct inode *dir,
1072                     struct dentry *dentry,
1073                     int kind)
1074
1075 {
1076         struct task_security_struct *tsec;
1077         struct inode_security_struct *dsec, *isec;
1078         struct avc_audit_data ad;
1079         u32 av;
1080         int rc;
1081
1082         tsec = current->security;
1083         dsec = dir->i_security;
1084         isec = dentry->d_inode->i_security;
1085
1086         AVC_AUDIT_DATA_INIT(&ad, FS);
1087         ad.u.fs.dentry = dentry;
1088
1089         av = DIR__SEARCH;
1090         av |= (kind ? DIR__REMOVE_NAME : DIR__ADD_NAME);
1091         rc = avc_has_perm(tsec->sid, dsec->sid, SECCLASS_DIR,
1092                           av, &dsec->avcr, &ad);
1093         if (rc)
1094                 return rc;
1095
1096         switch (kind) {
1097         case MAY_LINK:
1098                 av = FILE__LINK;
1099                 break;
1100         case MAY_UNLINK:
1101                 av = FILE__UNLINK;
1102                 break;
1103         case MAY_RMDIR:
1104                 av = DIR__RMDIR;
1105                 break;
1106         default:
1107                 printk(KERN_WARNING "may_link:  unrecognized kind %d\n", kind);
1108                 return 0;
1109         }
1110
1111         rc = avc_has_perm(tsec->sid, isec->sid, isec->sclass,
1112                           av, &isec->avcr, &ad);
1113         return rc;
1114 }
1115
1116 static inline int may_rename(struct inode *old_dir,
1117                              struct dentry *old_dentry,
1118                              struct inode *new_dir,
1119                              struct dentry *new_dentry)
1120 {
1121         struct task_security_struct *tsec;
1122         struct inode_security_struct *old_dsec, *new_dsec, *old_isec, *new_isec;
1123         struct avc_audit_data ad;
1124         u32 av;
1125         int old_is_dir, new_is_dir;
1126         int rc;
1127
1128         tsec = current->security;
1129         old_dsec = old_dir->i_security;
1130         old_isec = old_dentry->d_inode->i_security;
1131         old_is_dir = S_ISDIR(old_dentry->d_inode->i_mode);
1132         new_dsec = new_dir->i_security;
1133
1134         AVC_AUDIT_DATA_INIT(&ad, FS);
1135
1136         ad.u.fs.dentry = old_dentry;
1137         rc = avc_has_perm(tsec->sid, old_dsec->sid, SECCLASS_DIR,
1138                           DIR__REMOVE_NAME | DIR__SEARCH,
1139                           &old_dsec->avcr, &ad);
1140         if (rc)
1141                 return rc;
1142         rc = avc_has_perm(tsec->sid, old_isec->sid,
1143                           old_isec->sclass,
1144                           FILE__RENAME,
1145                           &old_isec->avcr, &ad);
1146         if (rc)
1147                 return rc;
1148         if (old_is_dir && new_dir != old_dir) {
1149                 rc = avc_has_perm(tsec->sid, old_isec->sid,
1150                                   old_isec->sclass,
1151                                   DIR__REPARENT,
1152                                   &old_isec->avcr, &ad);
1153                 if (rc)
1154                         return rc;
1155         }
1156
1157         ad.u.fs.dentry = new_dentry;
1158         av = DIR__ADD_NAME | DIR__SEARCH;
1159         if (new_dentry->d_inode)
1160                 av |= DIR__REMOVE_NAME;
1161         rc = avc_has_perm(tsec->sid, new_dsec->sid, SECCLASS_DIR,
1162                           av,&new_dsec->avcr, &ad);
1163         if (rc)
1164                 return rc;
1165         if (new_dentry->d_inode) {
1166                 new_isec = new_dentry->d_inode->i_security;
1167                 new_is_dir = S_ISDIR(new_dentry->d_inode->i_mode);
1168                 rc = avc_has_perm(tsec->sid, new_isec->sid,
1169                                   new_isec->sclass,
1170                                   (new_is_dir ? DIR__RMDIR : FILE__UNLINK),
1171                                   &new_isec->avcr, &ad);
1172                 if (rc)
1173                         return rc;
1174         }
1175
1176         return 0;
1177 }
1178
1179 /* Check whether a task can perform a filesystem operation. */
1180 int superblock_has_perm(struct task_struct *tsk,
1181                         struct super_block *sb,
1182                         u32 perms,
1183                         struct avc_audit_data *ad)
1184 {
1185         struct task_security_struct *tsec;
1186         struct superblock_security_struct *sbsec;
1187
1188         tsec = tsk->security;
1189         sbsec = sb->s_security;
1190         return avc_has_perm(tsec->sid, sbsec->sid, SECCLASS_FILESYSTEM,
1191                             perms, NULL, ad);
1192 }
1193
1194 /* Convert a Linux mode and permission mask to an access vector. */
1195 static inline u32 file_mask_to_av(int mode, int mask)
1196 {
1197         u32 av = 0;
1198
1199         if ((mode & S_IFMT) != S_IFDIR) {
1200                 if (mask & MAY_EXEC)
1201                         av |= FILE__EXECUTE;
1202                 if (mask & MAY_READ)
1203                         av |= FILE__READ;
1204
1205                 if (mask & MAY_APPEND)
1206                         av |= FILE__APPEND;
1207                 else if (mask & MAY_WRITE)
1208                         av |= FILE__WRITE;
1209
1210         } else {
1211                 if (mask & MAY_EXEC)
1212                         av |= DIR__SEARCH;
1213                 if (mask & MAY_WRITE)
1214                         av |= DIR__WRITE;
1215                 if (mask & MAY_READ)
1216                         av |= DIR__READ;
1217         }
1218
1219         return av;
1220 }
1221
1222 /* Convert a Linux file to an access vector. */
1223 static inline u32 file_to_av(struct file *file)
1224 {
1225         u32 av = 0;
1226
1227         if (file->f_mode & FMODE_READ)
1228                 av |= FILE__READ;
1229         if (file->f_mode & FMODE_WRITE) {
1230                 if (file->f_flags & O_APPEND)
1231                         av |= FILE__APPEND;
1232                 else
1233                         av |= FILE__WRITE;
1234         }
1235
1236         return av;
1237 }
1238
1239 /* Set an inode's SID to a specified value. */
1240 int inode_security_set_sid(struct inode *inode, u32 sid)
1241 {
1242         struct inode_security_struct *isec = inode->i_security;
1243
1244         down(&isec->sem);
1245         isec->sclass = inode_mode_to_security_class(inode->i_mode);
1246         isec->sid = sid;
1247         isec->initialized = 1;
1248         up(&isec->sem);
1249         return 0;
1250 }
1251
1252 /* Set the security attributes on a newly created file. */
1253 static int post_create(struct inode *dir,
1254                        struct dentry *dentry)
1255 {
1256
1257         struct task_security_struct *tsec;
1258         struct inode *inode;
1259         struct inode_security_struct *dsec;
1260         struct superblock_security_struct *sbsec;
1261         u32 newsid;
1262         char *context;
1263         unsigned int len;
1264         int rc;
1265
1266         tsec = current->security;
1267         dsec = dir->i_security;
1268         sbsec = dir->i_sb->s_security;
1269
1270         inode = dentry->d_inode;
1271         if (!inode) {
1272                 /* Some file system types (e.g. NFS) may not instantiate
1273                    a dentry for all create operations (e.g. symlink),
1274                    so we have to check to see if the inode is non-NULL. */
1275                 printk(KERN_WARNING "post_create:  no inode, dir (dev=%s, "
1276                        "ino=%ld)\n", dir->i_sb->s_id, dir->i_ino);
1277                 return 0;
1278         }
1279
1280         if (tsec->create_sid && sbsec->behavior != SECURITY_FS_USE_MNTPOINT) {
1281                 newsid = tsec->create_sid;
1282         } else {
1283                 rc = security_transition_sid(tsec->sid, dsec->sid,
1284                                              inode_mode_to_security_class(inode->i_mode),
1285                                              &newsid);
1286                 if (rc) {
1287                         printk(KERN_WARNING "post_create:  "
1288                                "security_transition_sid failed, rc=%d (dev=%s "
1289                                "ino=%ld)\n",
1290                                -rc, inode->i_sb->s_id, inode->i_ino);
1291                         return rc;
1292                 }
1293         }
1294
1295         rc = inode_security_set_sid(inode, newsid);
1296         if (rc) {
1297                 printk(KERN_WARNING "post_create:  inode_security_set_sid "
1298                        "failed, rc=%d (dev=%s ino=%ld)\n",
1299                        -rc, inode->i_sb->s_id, inode->i_ino);
1300                 return rc;
1301         }
1302
1303         if (sbsec->behavior == SECURITY_FS_USE_XATTR &&
1304             inode->i_op->setxattr) {
1305                 /* Use extended attributes. */
1306                 rc = security_sid_to_context(newsid, &context, &len);
1307                 if (rc) {
1308                         printk(KERN_WARNING "post_create:  sid_to_context "
1309                                "failed, rc=%d (dev=%s ino=%ld)\n",
1310                                -rc, inode->i_sb->s_id, inode->i_ino);
1311                         return rc;
1312                 }
1313                 down(&inode->i_sem);
1314                 rc = inode->i_op->setxattr(dentry,
1315                                            XATTR_NAME_SELINUX,
1316                                            context, len, 0);
1317                 up(&inode->i_sem);
1318                 kfree(context);
1319                 if (rc < 0) {
1320                         printk(KERN_WARNING "post_create:  setxattr failed, "
1321                                "rc=%d (dev=%s ino=%ld)\n",
1322                                -rc, inode->i_sb->s_id, inode->i_ino);
1323                         return rc;
1324                 }
1325         }
1326
1327         return 0;
1328 }
1329
1330
1331 /* Hook functions begin here. */
1332
1333 static int selinux_ptrace(struct task_struct *parent, struct task_struct *child)
1334 {
1335         struct task_security_struct *psec = parent->security;
1336         struct task_security_struct *csec = child->security;
1337         int rc;
1338
1339         rc = secondary_ops->ptrace(parent,child);
1340         if (rc)
1341                 return rc;
1342
1343         rc = task_has_perm(parent, child, PROCESS__PTRACE);
1344         /* Save the SID of the tracing process for later use in apply_creds. */
1345         if (!rc)
1346                 csec->ptrace_sid = psec->sid;
1347         return rc;
1348 }
1349
1350 static int selinux_capget(struct task_struct *target, kernel_cap_t *effective,
1351                           kernel_cap_t *inheritable, kernel_cap_t *permitted)
1352 {
1353         int error;
1354
1355         error = task_has_perm(current, target, PROCESS__GETCAP);
1356         if (error)
1357                 return error;
1358
1359         return secondary_ops->capget(target, effective, inheritable, permitted);
1360 }
1361
1362 static int selinux_capset_check(struct task_struct *target, kernel_cap_t *effective,
1363                                 kernel_cap_t *inheritable, kernel_cap_t *permitted)
1364 {
1365         int error;
1366
1367         error = task_has_perm(current, target, PROCESS__SETCAP);
1368         if (error)
1369                 return error;
1370
1371         return secondary_ops->capset_check(target, effective, inheritable, permitted);
1372 }
1373
1374 static void selinux_capset_set(struct task_struct *target, kernel_cap_t *effective,
1375                                kernel_cap_t *inheritable, kernel_cap_t *permitted)
1376 {
1377         int error;
1378
1379         error = task_has_perm(current, target, PROCESS__SETCAP);
1380         if (error)
1381                 return;
1382
1383         secondary_ops->capset_set(target, effective, inheritable, permitted);
1384 }
1385
1386 static int selinux_capable(struct task_struct *tsk, int cap)
1387 {
1388         int rc;
1389
1390         rc = secondary_ops->capable(tsk, cap);
1391         if (rc)
1392                 return rc;
1393
1394         return task_has_capability(tsk,cap);
1395 }
1396
1397 static int selinux_sysctl(ctl_table *table, int op)
1398 {
1399         int error = 0;
1400         u32 av;
1401         struct task_security_struct *tsec;
1402         u32 tsid;
1403         int rc;
1404
1405         tsec = current->security;
1406
1407         rc = selinux_proc_get_sid(table->de, (op == 001) ?
1408                                   SECCLASS_DIR : SECCLASS_FILE, &tsid);
1409         if (rc) {
1410                 /* Default to the well-defined sysctl SID. */
1411                 tsid = SECINITSID_SYSCTL;
1412         }
1413
1414         /* The op values are "defined" in sysctl.c, thereby creating
1415          * a bad coupling between this module and sysctl.c */
1416         if(op == 001) {
1417                 error = avc_has_perm(tsec->sid, tsid,
1418                                      SECCLASS_DIR, DIR__SEARCH, NULL, NULL);
1419         } else {
1420                 av = 0;
1421                 if (op & 004)
1422                         av |= FILE__READ;
1423                 if (op & 002)
1424                         av |= FILE__WRITE;
1425                 if (av)
1426                         error = avc_has_perm(tsec->sid, tsid,
1427                                              SECCLASS_FILE, av, NULL, NULL);
1428         }
1429
1430         return error;
1431 }
1432
1433 static int selinux_quotactl(int cmds, int type, int id, struct super_block *sb)
1434 {
1435         int rc = 0;
1436
1437         if (!sb)
1438                 return 0;
1439
1440         switch (cmds) {
1441                 case Q_SYNC:
1442                 case Q_QUOTAON:
1443                 case Q_QUOTAOFF:
1444                 case Q_SETINFO:
1445                 case Q_SETQUOTA:
1446                         rc = superblock_has_perm(current,
1447                                                  sb,
1448                                                  FILESYSTEM__QUOTAMOD, NULL);
1449                         break;
1450                 case Q_GETFMT:
1451                 case Q_GETINFO:
1452                 case Q_GETQUOTA:
1453                         rc = superblock_has_perm(current,
1454                                                  sb,
1455                                                  FILESYSTEM__QUOTAGET, NULL);
1456                         break;
1457                 default:
1458                         rc = 0;  /* let the kernel handle invalid cmds */
1459                         break;
1460         }
1461         return rc;
1462 }
1463
1464 static int selinux_quota_on(struct file *f)
1465 {
1466         return file_has_perm(current, f, FILE__QUOTAON);
1467 }
1468
1469 static int selinux_syslog(int type)
1470 {
1471         int rc;
1472
1473         rc = secondary_ops->syslog(type);
1474         if (rc)
1475                 return rc;
1476
1477         switch (type) {
1478                 case 3:         /* Read last kernel messages */
1479                 case 10:        /* Return size of the log buffer */
1480                         rc = task_has_system(current, SYSTEM__SYSLOG_READ);
1481                         break;
1482                 case 6:         /* Disable logging to console */
1483                 case 7:         /* Enable logging to console */
1484                 case 8:         /* Set level of messages printed to console */
1485                         rc = task_has_system(current, SYSTEM__SYSLOG_CONSOLE);
1486                         break;
1487                 case 0:         /* Close log */
1488                 case 1:         /* Open log */
1489                 case 2:         /* Read from log */
1490                 case 4:         /* Read/clear last kernel messages */
1491                 case 5:         /* Clear ring buffer */
1492                 default:
1493                         rc = task_has_system(current, SYSTEM__SYSLOG_MOD);
1494                         break;
1495         }
1496         return rc;
1497 }
1498
1499 /*
1500  * Check that a process has enough memory to allocate a new virtual
1501  * mapping. 0 means there is enough memory for the allocation to
1502  * succeed and -ENOMEM implies there is not.
1503  *
1504  * We currently support three overcommit policies, which are set via the
1505  * vm.overcommit_memory sysctl.  See Documentation/vm/overcommit-accounting
1506  *
1507  * Strict overcommit modes added 2002 Feb 26 by Alan Cox.
1508  * Additional code 2002 Jul 20 by Robert Love.
1509  */
1510 static int selinux_vm_enough_memory(long pages)
1511 {
1512         unsigned long free, allowed;
1513         int rc;
1514         struct task_security_struct *tsec = current->security;
1515
1516         vm_acct_memory(pages);
1517
1518         /*
1519          * Sometimes we want to use more memory than we have
1520          */
1521         if (sysctl_overcommit_memory == 1)
1522                 return 0;
1523
1524         if (sysctl_overcommit_memory == 0) {
1525                 free = get_page_cache_size();
1526                 free += nr_free_pages();
1527                 free += nr_swap_pages;
1528
1529                 /*
1530                  * Any slabs which are created with the
1531                  * SLAB_RECLAIM_ACCOUNT flag claim to have contents
1532                  * which are reclaimable, under pressure.  The dentry
1533                  * cache and most inode caches should fall into this
1534                  */
1535                 free += atomic_read(&slab_reclaim_pages);
1536
1537                 /*
1538                  * Leave the last 3% for privileged processes.
1539                  * Don't audit the check, as it is applied to all processes
1540                  * that allocate mappings.
1541                  */
1542                 rc = secondary_ops->capable(current, CAP_SYS_ADMIN);
1543                 if (!rc) {
1544                         rc = avc_has_perm_noaudit(tsec->sid, tsec->sid,
1545                                                   SECCLASS_CAPABILITY,
1546                                                   CAP_TO_MASK(CAP_SYS_ADMIN),
1547                                                   NULL, NULL);
1548                 }
1549                 if (rc)
1550                         free -= free / 32;
1551
1552                 if (free > pages)
1553                         return 0;
1554                 vm_unacct_memory(pages);
1555                 return -ENOMEM;
1556         }
1557
1558         allowed = (totalram_pages - hugetlb_total_pages())
1559                 * sysctl_overcommit_ratio / 100;
1560         allowed += total_swap_pages;
1561
1562         if (atomic_read(&vm_committed_space) < allowed)
1563                 return 0;
1564
1565         vm_unacct_memory(pages);
1566
1567         return -ENOMEM;
1568 }
1569
1570 static int selinux_netlink_send(struct sk_buff *skb)
1571 {
1572         if (capable(CAP_NET_ADMIN))
1573                 cap_raise (NETLINK_CB (skb).eff_cap, CAP_NET_ADMIN);
1574         else
1575                 NETLINK_CB(skb).eff_cap = 0;
1576         return 0;
1577 }
1578
1579 static int selinux_netlink_recv(struct sk_buff *skb)
1580 {
1581         if (!cap_raised(NETLINK_CB(skb).eff_cap, CAP_NET_ADMIN))
1582                 return -EPERM;
1583         return 0;
1584 }
1585
1586 /* binprm security operations */
1587
1588 static int selinux_bprm_alloc_security(struct linux_binprm *bprm)
1589 {
1590         struct bprm_security_struct *bsec;
1591
1592         bsec = kmalloc(sizeof(struct bprm_security_struct), GFP_KERNEL);
1593         if (!bsec)
1594                 return -ENOMEM;
1595
1596         memset(bsec, 0, sizeof *bsec);
1597         bsec->magic = SELINUX_MAGIC;
1598         bsec->bprm = bprm;
1599         bsec->sid = SECINITSID_UNLABELED;
1600         bsec->set = 0;
1601
1602         bprm->security = bsec;
1603         return 0;
1604 }
1605
1606 static int selinux_bprm_set_security(struct linux_binprm *bprm)
1607 {
1608         struct task_security_struct *tsec;
1609         struct inode *inode = bprm->file->f_dentry->d_inode;
1610         struct inode_security_struct *isec;
1611         struct bprm_security_struct *bsec;
1612         u32 newsid;
1613         struct avc_audit_data ad;
1614         int rc;
1615
1616         rc = secondary_ops->bprm_set_security(bprm);
1617         if (rc)
1618                 return rc;
1619
1620         bsec = bprm->security;
1621
1622         if (bsec->set)
1623                 return 0;
1624
1625         tsec = current->security;
1626         isec = inode->i_security;
1627
1628         /* Default to the current task SID. */
1629         bsec->sid = tsec->sid;
1630
1631         /* Reset create SID on execve. */
1632         tsec->create_sid = 0;
1633
1634         if (tsec->exec_sid) {
1635                 newsid = tsec->exec_sid;
1636                 /* Reset exec SID on execve. */
1637                 tsec->exec_sid = 0;
1638         } else {
1639                 /* Check for a default transition on this program. */
1640                 rc = security_transition_sid(tsec->sid, isec->sid,
1641                                              SECCLASS_PROCESS, &newsid);
1642                 if (rc)
1643                         return rc;
1644         }
1645
1646         AVC_AUDIT_DATA_INIT(&ad, FS);
1647         ad.u.fs.mnt = bprm->file->f_vfsmnt;
1648         ad.u.fs.dentry = bprm->file->f_dentry;
1649
1650         if (bprm->file->f_vfsmnt->mnt_flags & MNT_NOSUID)
1651                 newsid = tsec->sid;
1652
1653         if (tsec->sid == newsid) {
1654                 rc = avc_has_perm(tsec->sid, isec->sid,
1655                                   SECCLASS_FILE, FILE__EXECUTE_NO_TRANS,
1656                                   &isec->avcr, &ad);
1657                 if (rc)
1658                         return rc;
1659         } else {
1660                 /* Check permissions for the transition. */
1661                 rc = avc_has_perm(tsec->sid, newsid,
1662                                   SECCLASS_PROCESS, PROCESS__TRANSITION,
1663                                   NULL,
1664                                   &ad);
1665                 if (rc)
1666                         return rc;
1667
1668                 rc = avc_has_perm(newsid, isec->sid,
1669                                   SECCLASS_FILE, FILE__ENTRYPOINT,
1670                                   &isec->avcr, &ad);
1671                 if (rc)
1672                         return rc;
1673
1674                 /* Set the security field to the new SID. */
1675                 bsec->sid = newsid;
1676         }
1677
1678         bsec->set = 1;
1679         return 0;
1680 }
1681
1682 static int selinux_bprm_check_security (struct linux_binprm *bprm)
1683 {
1684         return 0;
1685 }
1686
1687
1688 static int selinux_bprm_secureexec (struct linux_binprm *bprm)
1689 {
1690         struct task_security_struct *tsec = current->security;
1691         int atsecure = 0;
1692
1693         if (tsec->osid != tsec->sid) {
1694                 /* Enable secure mode for SIDs transitions unless
1695                    the noatsecure permission is granted between
1696                    the two SIDs, i.e. ahp returns 0. */
1697                 atsecure = avc_has_perm(tsec->osid, tsec->sid,
1698                                          SECCLASS_PROCESS,
1699                                          PROCESS__NOATSECURE, NULL, NULL);
1700         }
1701
1702         /* Note that we must include the legacy uid/gid test below
1703            to retain it, as the new userland will simply use the
1704            value passed by AT_SECURE to decide whether to enable
1705            secure mode. */
1706         return ( atsecure || current->euid != current->uid ||
1707                 current->egid != current->gid);
1708 }
1709
1710 static void selinux_bprm_free_security(struct linux_binprm *bprm)
1711 {
1712         struct bprm_security_struct *bsec = bprm->security;
1713         bprm->security = NULL;
1714         kfree(bsec);
1715 }
1716
1717 /* Create an open file that refers to the null device.
1718    Derived from the OpenWall LSM. */
1719 struct file *open_devnull(void)
1720 {
1721         struct inode *inode;
1722         struct dentry *dentry;
1723         struct file *file = NULL;
1724         struct inode_security_struct *isec;
1725         dev_t dev;
1726
1727         inode = new_inode(current->fs->rootmnt->mnt_sb);
1728         if (!inode)
1729                 goto out;
1730
1731         dentry = dget(d_alloc_root(inode));
1732         if (!dentry)
1733                 goto out_iput;
1734
1735         file = get_empty_filp();
1736         if (!file)
1737                 goto out_dput;
1738
1739         dev = MKDEV(MEM_MAJOR, 3); /* null device */
1740
1741         inode->i_uid = current->fsuid;
1742         inode->i_gid = current->fsgid;
1743         inode->i_blksize = PAGE_SIZE;
1744         inode->i_blocks = 0;
1745         inode->i_atime = inode->i_mtime = inode->i_ctime = CURRENT_TIME;
1746         inode->i_state = I_DIRTY; /* so that mark_inode_dirty won't touch us */
1747
1748         isec = inode->i_security;
1749         isec->sid = SECINITSID_DEVNULL;
1750         isec->sclass = SECCLASS_CHR_FILE;
1751         isec->initialized = 1;
1752
1753         file->f_flags = O_RDWR;
1754         file->f_mode = FMODE_READ | FMODE_WRITE;
1755         file->f_dentry = dentry;
1756         file->f_vfsmnt = mntget(current->fs->rootmnt);
1757         file->f_pos = 0;
1758
1759         init_special_inode(inode, S_IFCHR | S_IRUGO | S_IWUGO, dev);
1760         if (inode->i_fop->open(inode, file))
1761                 goto out_fput;
1762
1763 out:
1764         return file;
1765 out_fput:
1766         mntput(file->f_vfsmnt);
1767         put_filp(file);
1768 out_dput:
1769         dput(dentry);
1770 out_iput:
1771         iput(inode);
1772         file = NULL;
1773         goto out;
1774 }
1775
1776 /* Derived from fs/exec.c:flush_old_files. */
1777 static inline void flush_unauthorized_files(struct files_struct * files)
1778 {
1779         struct avc_audit_data ad;
1780         struct file *file, *devnull = NULL;
1781         long j = -1;
1782
1783         AVC_AUDIT_DATA_INIT(&ad,FS);
1784
1785         spin_lock(&files->file_lock);
1786         for (;;) {
1787                 unsigned long set, i, fd;
1788
1789                 j++;
1790                 i = j * __NFDBITS;
1791                 if (i >= files->max_fds || i >= files->max_fdset)
1792                         break;
1793                 set = files->open_fds->fds_bits[j];
1794                 if (!set)
1795                         continue;
1796                 spin_unlock(&files->file_lock);
1797                 for ( ; set ; i++,set >>= 1) {
1798                         if (set & 1) {
1799                                 file = fget(i);
1800                                 if (!file)
1801                                         continue;
1802                                 if (file_has_perm(current,
1803                                                   file,
1804                                                   file_to_av(file))) {
1805                                         sys_close(i);
1806                                         fd = get_unused_fd();
1807                                         if (fd != i) {
1808                                                 if (fd >= 0)
1809                                                         put_unused_fd(fd);
1810                                                 fput(file);
1811                                                 continue;
1812                                         }
1813                                         if (devnull) {
1814                                                 atomic_inc(&devnull->f_count);
1815                                         } else {
1816                                                 devnull = open_devnull();
1817                                                 if (!devnull) {
1818                                                         put_unused_fd(fd);
1819                                                         fput(file);
1820                                                         continue;
1821                                                 }
1822                                         }
1823                                         fd_install(fd, devnull);
1824                                 }
1825                                 fput(file);
1826                         }
1827                 }
1828                 spin_lock(&files->file_lock);
1829
1830         }
1831         spin_unlock(&files->file_lock);
1832 }
1833
1834 static void selinux_bprm_apply_creds(struct linux_binprm *bprm, int unsafe)
1835 {
1836         struct task_security_struct *tsec;
1837         struct bprm_security_struct *bsec;
1838         u32 sid;
1839         struct av_decision avd;
1840         struct itimerval itimer;
1841         struct rlimit *rlim, *initrlim;
1842         int rc, i;
1843
1844         secondary_ops->bprm_apply_creds(bprm, unsafe);
1845
1846         tsec = current->security;
1847
1848         bsec = bprm->security;
1849         sid = bsec->sid;
1850
1851         tsec->osid = tsec->sid;
1852         if (tsec->sid != sid) {
1853                 /* Check for shared state.  If not ok, leave SID
1854                    unchanged and kill. */
1855                 if (unsafe & LSM_UNSAFE_SHARE) {
1856                         rc = avc_has_perm_noaudit(tsec->sid, sid,
1857                                           SECCLASS_PROCESS, PROCESS__SHARE,
1858                                           NULL, &avd);
1859                         if (rc) {
1860                                 task_unlock(current);
1861                                 avc_audit(tsec->sid, sid, SECCLASS_PROCESS,
1862                                     PROCESS__SHARE, &avd, rc, NULL);
1863                                 force_sig_specific(SIGKILL, current);
1864                                 goto lock_out;
1865                         }
1866                 }
1867
1868                 /* Check for ptracing, and update the task SID if ok.
1869                    Otherwise, leave SID unchanged and kill. */
1870                 if (unsafe & (LSM_UNSAFE_PTRACE | LSM_UNSAFE_PTRACE_CAP)) {
1871                         rc = avc_has_perm_noaudit(tsec->ptrace_sid, sid,
1872                                           SECCLASS_PROCESS, PROCESS__PTRACE,
1873                                           NULL, &avd);
1874                         if (!rc)
1875                                 tsec->sid = sid;
1876                         task_unlock(current);
1877                         avc_audit(tsec->ptrace_sid, sid, SECCLASS_PROCESS,
1878                                   PROCESS__PTRACE, &avd, rc, NULL);
1879                         if (rc) {
1880                                 force_sig_specific(SIGKILL, current);
1881                                 goto lock_out;
1882                         }
1883                 } else {
1884                         tsec->sid = sid;
1885                         task_unlock(current);
1886                 }
1887
1888                 /* Close files for which the new task SID is not authorized. */
1889                 flush_unauthorized_files(current->files);
1890
1891                 /* Check whether the new SID can inherit signal state
1892                    from the old SID.  If not, clear itimers to avoid
1893                    subsequent signal generation and flush and unblock
1894                    signals. This must occur _after_ the task SID has
1895                   been updated so that any kill done after the flush
1896                   will be checked against the new SID. */
1897                 rc = avc_has_perm(tsec->osid, tsec->sid, SECCLASS_PROCESS,
1898                                   PROCESS__SIGINH, NULL, NULL);
1899                 if (rc) {
1900                         memset(&itimer, 0, sizeof itimer);
1901                         for (i = 0; i < 3; i++)
1902                                 do_setitimer(i, &itimer, NULL);
1903                         flush_signals(current);
1904                         spin_lock_irq(&current->sighand->siglock);
1905                         flush_signal_handlers(current, 1);
1906                         sigemptyset(&current->blocked);
1907                         recalc_sigpending();
1908                         spin_unlock_irq(&current->sighand->siglock);
1909                 }
1910
1911                 /* Check whether the new SID can inherit resource limits
1912                    from the old SID.  If not, reset all soft limits to
1913                    the lower of the current task's hard limit and the init
1914                    task's soft limit.  Note that the setting of hard limits 
1915                    (even to lower them) can be controlled by the setrlimit 
1916                    check. The inclusion of the init task's soft limit into
1917                    the computation is to avoid resetting soft limits higher
1918                    than the default soft limit for cases where the default
1919                    is lower than the hard limit, e.g. RLIMIT_CORE or 
1920                    RLIMIT_STACK.*/
1921                 rc = avc_has_perm(tsec->osid, tsec->sid, SECCLASS_PROCESS,
1922                                   PROCESS__RLIMITINH, NULL, NULL);
1923                 if (rc) {
1924                         for (i = 0; i < RLIM_NLIMITS; i++) {
1925                                 rlim = current->rlim + i;
1926                                 initrlim = init_task.rlim+i;
1927                                 rlim->rlim_cur = min(rlim->rlim_max,initrlim->rlim_cur);
1928                         }
1929                 }
1930
1931                 /* Wake up the parent if it is waiting so that it can
1932                    recheck wait permission to the new task SID. */
1933                 wake_up_interruptible(&current->parent->wait_chldexit);
1934
1935 lock_out:
1936                 task_lock(current);
1937                 return;
1938         }
1939 }
1940
1941 /* superblock security operations */
1942
1943 static int selinux_sb_alloc_security(struct super_block *sb)
1944 {
1945         return superblock_alloc_security(sb);
1946 }
1947
1948 static void selinux_sb_free_security(struct super_block *sb)
1949 {
1950         superblock_free_security(sb);
1951 }
1952
1953 static inline int match_prefix(char *prefix, int plen, char *option, int olen)
1954 {
1955         if (plen > olen)
1956                 return 0;
1957
1958         return !memcmp(prefix, option, plen);
1959 }
1960
1961 static inline int selinux_option(char *option, int len)
1962 {
1963         return (match_prefix("context=", sizeof("context=")-1, option, len) ||
1964                 match_prefix("fscontext=", sizeof("fscontext=")-1, option, len) ||
1965                 match_prefix("defcontext=", sizeof("defcontext=")-1, option, len));
1966 }
1967
1968 static inline void take_option(char **to, char *from, int *first, int len)
1969 {
1970         if (!*first) {
1971                 **to = ',';
1972                 *to += 1;
1973         }
1974         else
1975                 *first = 0;
1976         memcpy(*to, from, len);
1977         *to += len;
1978 }
1979
1980 static int selinux_sb_copy_data(struct file_system_type *type, void *orig, void *copy)
1981 {
1982         int fnosec, fsec, rc = 0;
1983         char *in_save, *in_curr, *in_end;
1984         char *sec_curr, *nosec_save, *nosec;
1985
1986         in_curr = orig;
1987         sec_curr = copy;
1988
1989         /* Binary mount data: just copy */
1990         if (type->fs_flags & FS_BINARY_MOUNTDATA) {
1991                 copy_page(sec_curr, in_curr);
1992                 goto out;
1993         }
1994
1995         nosec = (char *)get_zeroed_page(GFP_KERNEL);
1996         if (!nosec) {
1997                 rc = -ENOMEM;
1998                 goto out;
1999         }
2000
2001         nosec_save = nosec;
2002         fnosec = fsec = 1;
2003         in_save = in_end = orig;
2004
2005         do {
2006                 if (*in_end == ',' || *in_end == '\0') {
2007                         int len = in_end - in_curr;
2008
2009                         if (selinux_option(in_curr, len))
2010                                 take_option(&sec_curr, in_curr, &fsec, len);
2011                         else
2012                                 take_option(&nosec, in_curr, &fnosec, len);
2013
2014                         in_curr = in_end + 1;
2015                 }
2016         } while (*in_end++);
2017
2018         copy_page(in_save, nosec_save);
2019 out:
2020         return rc;
2021 }
2022
2023 static int selinux_sb_kern_mount(struct super_block *sb, void *data)
2024 {
2025         struct avc_audit_data ad;
2026         int rc;
2027
2028         rc = superblock_doinit(sb, data);
2029         if (rc)
2030                 return rc;
2031
2032         AVC_AUDIT_DATA_INIT(&ad,FS);
2033         ad.u.fs.dentry = sb->s_root;
2034         return superblock_has_perm(current, sb, FILESYSTEM__MOUNT, &ad);
2035 }
2036
2037 static int selinux_sb_statfs(struct super_block *sb)
2038 {
2039         struct avc_audit_data ad;
2040
2041         AVC_AUDIT_DATA_INIT(&ad,FS);
2042         ad.u.fs.dentry = sb->s_root;
2043         return superblock_has_perm(current, sb, FILESYSTEM__GETATTR, &ad);
2044 }
2045
2046 static int selinux_mount(char * dev_name,
2047                          struct nameidata *nd,
2048                          char * type,
2049                          unsigned long flags,
2050                          void * data)
2051 {
2052         if (flags & MS_REMOUNT)
2053                 return superblock_has_perm(current, nd->mnt->mnt_sb,
2054                                            FILESYSTEM__REMOUNT, NULL);
2055         else
2056                 return dentry_has_perm(current, nd->mnt, nd->dentry,
2057                                        FILE__MOUNTON);
2058 }
2059
2060 static int selinux_umount(struct vfsmount *mnt, int flags)
2061 {
2062         return superblock_has_perm(current,mnt->mnt_sb,
2063                                    FILESYSTEM__UNMOUNT,NULL);
2064 }
2065
2066 /* inode security operations */
2067
2068 static int selinux_inode_alloc_security(struct inode *inode)
2069 {
2070         return inode_alloc_security(inode);
2071 }
2072
2073 static void selinux_inode_free_security(struct inode *inode)
2074 {
2075         inode_free_security(inode);
2076 }
2077
2078 static int selinux_inode_create(struct inode *dir, struct dentry *dentry, int mask)
2079 {
2080         return may_create(dir, dentry, SECCLASS_FILE);
2081 }
2082
2083 static void selinux_inode_post_create(struct inode *dir, struct dentry *dentry, int mask)
2084 {
2085         post_create(dir, dentry);
2086 }
2087
2088 static int selinux_inode_link(struct dentry *old_dentry, struct inode *dir, struct dentry *new_dentry)
2089 {
2090         int rc;
2091
2092         rc = secondary_ops->inode_link(old_dentry,dir,new_dentry);
2093         if (rc)
2094                 return rc;
2095         return may_link(dir, old_dentry, MAY_LINK);
2096 }
2097
2098 static void selinux_inode_post_link(struct dentry *old_dentry, struct inode *inode, struct dentry *new_dentry)
2099 {
2100         return;
2101 }
2102
2103 static int selinux_inode_unlink(struct inode *dir, struct dentry *dentry)
2104 {
2105         return may_link(dir, dentry, MAY_UNLINK);
2106 }
2107
2108 static int selinux_inode_symlink(struct inode *dir, struct dentry *dentry, const char *name)
2109 {
2110         return may_create(dir, dentry, SECCLASS_LNK_FILE);
2111 }
2112
2113 static void selinux_inode_post_symlink(struct inode *dir, struct dentry *dentry, const char *name)
2114 {
2115         post_create(dir, dentry);
2116 }
2117
2118 static int selinux_inode_mkdir(struct inode *dir, struct dentry *dentry, int mask)
2119 {
2120         return may_create(dir, dentry, SECCLASS_DIR);
2121 }
2122
2123 static void selinux_inode_post_mkdir(struct inode *dir, struct dentry *dentry, int mask)
2124 {
2125         post_create(dir, dentry);
2126 }
2127
2128 static int selinux_inode_rmdir(struct inode *dir, struct dentry *dentry)
2129 {
2130         return may_link(dir, dentry, MAY_RMDIR);
2131 }
2132
2133 static int selinux_inode_mknod(struct inode *dir, struct dentry *dentry, int mode, dev_t dev)
2134 {
2135         return may_create(dir, dentry, inode_mode_to_security_class(mode));
2136 }
2137
2138 static void selinux_inode_post_mknod(struct inode *dir, struct dentry *dentry, int mode, dev_t dev)
2139 {
2140         post_create(dir, dentry);
2141 }
2142
2143 static int selinux_inode_rename(struct inode *old_inode, struct dentry *old_dentry,
2144                                 struct inode *new_inode, struct dentry *new_dentry)
2145 {
2146         return may_rename(old_inode, old_dentry, new_inode, new_dentry);
2147 }
2148
2149 static void selinux_inode_post_rename(struct inode *old_inode, struct dentry *old_dentry,
2150                                       struct inode *new_inode, struct dentry *new_dentry)
2151 {
2152         return;
2153 }
2154
2155 static int selinux_inode_readlink(struct dentry *dentry)
2156 {
2157         return dentry_has_perm(current, NULL, dentry, FILE__READ);
2158 }
2159
2160 static int selinux_inode_follow_link(struct dentry *dentry, struct nameidata *nameidata)
2161 {
2162         int rc;
2163
2164         rc = secondary_ops->inode_follow_link(dentry,nameidata);
2165         if (rc)
2166                 return rc;
2167         return dentry_has_perm(current, NULL, dentry, FILE__READ);
2168 }
2169
2170 static int selinux_inode_permission(struct inode *inode, int mask,
2171                                     struct nameidata *nd)
2172 {
2173         if (!mask) {
2174                 /* No permission to check.  Existence test. */
2175                 return 0;
2176         }
2177
2178         return inode_has_perm(current, inode,
2179                                file_mask_to_av(inode->i_mode, mask), NULL, NULL);
2180 }
2181
2182 static int selinux_inode_setattr(struct dentry *dentry, struct iattr *iattr)
2183 {
2184         if (iattr->ia_valid & (ATTR_MODE | ATTR_UID | ATTR_GID |
2185                                ATTR_ATIME_SET | ATTR_MTIME_SET))
2186                 return dentry_has_perm(current, NULL, dentry, FILE__SETATTR);
2187
2188         return dentry_has_perm(current, NULL, dentry, FILE__WRITE);
2189 }
2190
2191 static int selinux_inode_getattr(struct vfsmount *mnt, struct dentry *dentry)
2192 {
2193         return dentry_has_perm(current, mnt, dentry, FILE__GETATTR);
2194 }
2195
2196 static int selinux_inode_setxattr(struct dentry *dentry, char *name, void *value, size_t size, int flags)
2197 {
2198         struct task_security_struct *tsec = current->security;
2199         struct inode *inode = dentry->d_inode;
2200         struct inode_security_struct *isec = inode->i_security;
2201         struct superblock_security_struct *sbsec;
2202         struct avc_audit_data ad;
2203         u32 newsid;
2204         int rc = 0;
2205
2206         if (strcmp(name, XATTR_NAME_SELINUX)) {
2207                 if (!strncmp(name, XATTR_SECURITY_PREFIX,
2208                              sizeof XATTR_SECURITY_PREFIX - 1) &&
2209                     !capable(CAP_SYS_ADMIN)) {
2210                         /* A different attribute in the security namespace.
2211                            Restrict to administrator. */
2212                         return -EPERM;
2213                 }
2214
2215                 /* Not an attribute we recognize, so just check the
2216                    ordinary setattr permission. */
2217                 return dentry_has_perm(current, NULL, dentry, FILE__SETATTR);
2218         }
2219
2220         sbsec = inode->i_sb->s_security;
2221         if (sbsec->behavior == SECURITY_FS_USE_MNTPOINT)
2222                 return -EOPNOTSUPP;
2223
2224         AVC_AUDIT_DATA_INIT(&ad,FS);
2225         ad.u.fs.dentry = dentry;
2226
2227         rc = avc_has_perm(tsec->sid, isec->sid, isec->sclass,
2228                           FILE__RELABELFROM,
2229                           &isec->avcr, &ad);
2230         if (rc)
2231                 return rc;
2232
2233         rc = security_context_to_sid(value, size, &newsid);
2234         if (rc)
2235                 return rc;
2236
2237         rc = avc_has_perm(tsec->sid, newsid, isec->sclass,
2238                           FILE__RELABELTO, NULL, &ad);
2239         if (rc)
2240                 return rc;
2241
2242         return avc_has_perm(newsid,
2243                             sbsec->sid,
2244                             SECCLASS_FILESYSTEM,
2245                             FILESYSTEM__ASSOCIATE,
2246                             NULL,
2247                             &ad);
2248 }
2249
2250 static void selinux_inode_post_setxattr(struct dentry *dentry, char *name,
2251                                         void *value, size_t size, int flags)
2252 {
2253         struct inode *inode = dentry->d_inode;
2254         struct inode_security_struct *isec = inode->i_security;
2255         u32 newsid;
2256         int rc;
2257
2258         if (strcmp(name, XATTR_NAME_SELINUX)) {
2259                 /* Not an attribute we recognize, so nothing to do. */
2260                 return;
2261         }
2262
2263         rc = security_context_to_sid(value, size, &newsid);
2264         if (rc) {
2265                 printk(KERN_WARNING "%s:  unable to obtain SID for context "
2266                        "%s, rc=%d\n", __FUNCTION__, (char*)value, -rc);
2267                 return;
2268         }
2269
2270         isec->sid = newsid;
2271         return;
2272 }
2273
2274 static int selinux_inode_getxattr (struct dentry *dentry, char *name)
2275 {
2276         struct inode *inode = dentry->d_inode;
2277         struct superblock_security_struct *sbsec = inode->i_sb->s_security;
2278
2279         if (sbsec->behavior == SECURITY_FS_USE_MNTPOINT)
2280                 return -EOPNOTSUPP;
2281
2282         return dentry_has_perm(current, NULL, dentry, FILE__GETATTR);
2283 }
2284
2285 static int selinux_inode_listxattr (struct dentry *dentry)
2286 {
2287         return dentry_has_perm(current, NULL, dentry, FILE__GETATTR);
2288 }
2289
2290 static int selinux_inode_removexattr (struct dentry *dentry, char *name)
2291 {
2292         if (strcmp(name, XATTR_NAME_SELINUX)) {
2293                 if (!strncmp(name, XATTR_SECURITY_PREFIX,
2294                              sizeof XATTR_SECURITY_PREFIX - 1) &&
2295                     !capable(CAP_SYS_ADMIN)) {
2296                         /* A different attribute in the security namespace.
2297                            Restrict to administrator. */
2298                         return -EPERM;
2299                 }
2300
2301                 /* Not an attribute we recognize, so just check the
2302                    ordinary setattr permission. Might want a separate
2303                    permission for removexattr. */
2304                 return dentry_has_perm(current, NULL, dentry, FILE__SETATTR);
2305         }
2306
2307         /* No one is allowed to remove a SELinux security label.
2308            You can change the label, but all data must be labeled. */
2309         return -EACCES;
2310 }
2311
2312 static int selinux_inode_getsecurity(struct dentry *dentry, const char *name, void *buffer, size_t size)
2313 {
2314         struct inode *inode = dentry->d_inode;
2315         struct inode_security_struct *isec = inode->i_security;
2316         char *context;
2317         unsigned len;
2318         int rc;
2319
2320         /* Permission check handled by selinux_inode_getxattr hook.*/
2321
2322         if (strcmp(name, XATTR_SELINUX_SUFFIX))
2323                 return -EOPNOTSUPP;
2324
2325         rc = security_sid_to_context(isec->sid, &context, &len);
2326         if (rc)
2327                 return rc;
2328
2329         if (!buffer || !size) {
2330                 kfree(context);
2331                 return len;
2332         }
2333         if (size < len) {
2334                 kfree(context);
2335                 return -ERANGE;
2336         }
2337         memcpy(buffer, context, len);
2338         kfree(context);
2339         return len;
2340 }
2341
2342 static int selinux_inode_setsecurity(struct dentry *dentry, const char *name,
2343                                      const void *value, size_t size, int flags)
2344 {
2345         struct inode *inode = dentry->d_inode;
2346         struct inode_security_struct *isec = inode->i_security;
2347         u32 newsid;
2348         int rc;
2349
2350         if (strcmp(name, XATTR_SELINUX_SUFFIX))
2351                 return -EOPNOTSUPP;
2352
2353         if (!value || !size)
2354                 return -EACCES;
2355
2356         rc = security_context_to_sid((void*)value, size, &newsid);
2357         if (rc)
2358                 return rc;
2359
2360         isec->sid = newsid;
2361         return 0;
2362 }
2363
2364 static int selinux_inode_listsecurity(struct dentry *dentry, char *buffer)
2365 {
2366         const int len = sizeof(XATTR_NAME_SELINUX);
2367         if (buffer)
2368                 memcpy(buffer, XATTR_NAME_SELINUX, len);
2369         return len;
2370 }
2371
2372 /* file security operations */
2373
2374 static int selinux_file_permission(struct file *file, int mask)
2375 {
2376         struct inode *inode = file->f_dentry->d_inode;
2377
2378         if (!mask) {
2379                 /* No permission to check.  Existence test. */
2380                 return 0;
2381         }
2382
2383         /* file_mask_to_av won't add FILE__WRITE if MAY_APPEND is set */
2384         if ((file->f_flags & O_APPEND) && (mask & MAY_WRITE))
2385                 mask |= MAY_APPEND;
2386
2387         return file_has_perm(current, file,
2388                              file_mask_to_av(inode->i_mode, mask));
2389 }
2390
2391 static int selinux_file_alloc_security(struct file *file)
2392 {
2393         return file_alloc_security(file);
2394 }
2395
2396 static void selinux_file_free_security(struct file *file)
2397 {
2398         file_free_security(file);
2399 }
2400
2401 static int selinux_file_ioctl(struct file *file, unsigned int cmd,
2402                               unsigned long arg)
2403 {
2404         int error = 0;
2405
2406         switch (cmd) {
2407                 case FIONREAD:
2408                 /* fall through */
2409                 case FIBMAP:
2410                 /* fall through */
2411                 case FIGETBSZ:
2412                 /* fall through */
2413                 case EXT2_IOC_GETFLAGS:
2414                 /* fall through */
2415                 case EXT2_IOC_GETVERSION:
2416                         error = file_has_perm(current, file, FILE__GETATTR);
2417                         break;
2418
2419                 case EXT2_IOC_SETFLAGS:
2420                 /* fall through */
2421                 case EXT2_IOC_SETVERSION:
2422                         error = file_has_perm(current, file, FILE__SETATTR);
2423                         break;
2424
2425                 /* sys_ioctl() checks */
2426                 case FIONBIO:
2427                 /* fall through */
2428                 case FIOASYNC:
2429                         error = file_has_perm(current, file, 0);
2430                         break;
2431
2432                 case KDSKBENT:
2433                 case KDSKBSENT:
2434                         error = task_has_capability(current,CAP_SYS_TTY_CONFIG);
2435                         break;
2436
2437                 /* default case assumes that the command will go
2438                  * to the file's ioctl() function.
2439                  */
2440                 default:
2441                         error = file_has_perm(current, file, FILE__IOCTL);
2442
2443         }
2444         return error;
2445 }
2446
2447 static int selinux_file_mmap(struct file *file, unsigned long prot, unsigned long flags)
2448 {
2449         u32 av;
2450
2451         if (file) {
2452                 /* read access is always possible with a mapping */
2453                 av = FILE__READ;
2454
2455                 /* write access only matters if the mapping is shared */
2456                 if ((flags & MAP_TYPE) == MAP_SHARED && (prot & PROT_WRITE))
2457                         av |= FILE__WRITE;
2458
2459                 if (prot & PROT_EXEC)
2460                         av |= FILE__EXECUTE;
2461
2462                 return file_has_perm(current, file, av);
2463         }
2464         return 0;
2465 }
2466
2467 static int selinux_file_mprotect(struct vm_area_struct *vma,
2468                                  unsigned long prot)
2469 {
2470         return selinux_file_mmap(vma->vm_file, prot, vma->vm_flags);
2471 }
2472
2473 static int selinux_file_lock(struct file *file, unsigned int cmd)
2474 {
2475         return file_has_perm(current, file, FILE__LOCK);
2476 }
2477
2478 static int selinux_file_fcntl(struct file *file, unsigned int cmd,
2479                               unsigned long arg)
2480 {
2481         int err = 0;
2482
2483         switch (cmd) {
2484                 case F_SETFL:
2485                         if (!file->f_dentry || !file->f_dentry->d_inode) {
2486                                 err = -EINVAL;
2487                                 break;
2488                         }
2489
2490                         if ((file->f_flags & O_APPEND) && !(arg & O_APPEND)) {
2491                                 err = file_has_perm(current, file,FILE__WRITE);
2492                                 break;
2493                         }
2494                         /* fall through */
2495                 case F_SETOWN:
2496                 case F_SETSIG:
2497                 case F_GETFL:
2498                 case F_GETOWN:
2499                 case F_GETSIG:
2500                         /* Just check FD__USE permission */
2501                         err = file_has_perm(current, file, 0);
2502                         break;
2503                 case F_GETLK:
2504                 case F_SETLK:
2505                 case F_SETLKW:
2506 #if BITS_PER_LONG == 32
2507                 case F_GETLK64:
2508                 case F_SETLK64:
2509                 case F_SETLKW64:
2510 #endif
2511                         if (!file->f_dentry || !file->f_dentry->d_inode) {
2512                                 err = -EINVAL;
2513                                 break;
2514                         }
2515                         err = file_has_perm(current, file, FILE__LOCK);
2516                         break;
2517         }
2518
2519         return err;
2520 }
2521
2522 static int selinux_file_set_fowner(struct file *file)
2523 {
2524         struct task_security_struct *tsec;
2525         struct file_security_struct *fsec;
2526
2527         tsec = current->security;
2528         fsec = file->f_security;
2529         fsec->fown_sid = tsec->sid;
2530
2531         return 0;
2532 }
2533
2534 static int selinux_file_send_sigiotask(struct task_struct *tsk,
2535                                        struct fown_struct *fown,
2536                                        int fd, int reason)
2537 {
2538         struct file *file;
2539         u32 perm;
2540         struct task_security_struct *tsec;
2541         struct file_security_struct *fsec;
2542
2543         /* struct fown_struct is never outside the context of a struct file */
2544         file = (struct file *)((long)fown - offsetof(struct file,f_owner));
2545
2546         tsec = tsk->security;
2547         fsec = file->f_security;
2548
2549         if (!fown->signum)
2550                 perm = signal_to_av(SIGIO); /* as per send_sigio_to_task */
2551         else
2552                 perm = signal_to_av(fown->signum);
2553
2554         return avc_has_perm(fsec->fown_sid, tsec->sid,
2555                             SECCLASS_PROCESS, perm, NULL, NULL);
2556 }
2557
2558 static int selinux_file_receive(struct file *file)
2559 {
2560         return file_has_perm(current, file, file_to_av(file));
2561 }
2562
2563 /* task security operations */
2564
2565 static int selinux_task_create(unsigned long clone_flags)
2566 {
2567         return task_has_perm(current, current, PROCESS__FORK);
2568 }
2569
2570 static int selinux_task_alloc_security(struct task_struct *tsk)
2571 {
2572         struct task_security_struct *tsec1, *tsec2;
2573         int rc;
2574
2575         tsec1 = current->security;
2576
2577         rc = task_alloc_security(tsk);
2578         if (rc)
2579                 return rc;
2580         tsec2 = tsk->security;
2581
2582         tsec2->osid = tsec1->osid;
2583         tsec2->sid = tsec1->sid;
2584
2585         /* Retain the exec and create SIDs across fork */
2586         tsec2->exec_sid = tsec1->exec_sid;
2587         tsec2->create_sid = tsec1->create_sid;
2588
2589         return 0;
2590 }
2591
2592 static void selinux_task_free_security(struct task_struct *tsk)
2593 {
2594         task_free_security(tsk);
2595 }
2596
2597 static int selinux_task_setuid(uid_t id0, uid_t id1, uid_t id2, int flags)
2598 {
2599         /* Since setuid only affects the current process, and
2600            since the SELinux controls are not based on the Linux
2601            identity attributes, SELinux does not need to control
2602            this operation.  However, SELinux does control the use
2603            of the CAP_SETUID and CAP_SETGID capabilities using the
2604            capable hook. */
2605         return 0;
2606 }
2607
2608 static int selinux_task_post_setuid(uid_t id0, uid_t id1, uid_t id2, int flags)
2609 {
2610         return secondary_ops->task_post_setuid(id0,id1,id2,flags);
2611 }
2612
2613 static int selinux_task_setgid(gid_t id0, gid_t id1, gid_t id2, int flags)
2614 {
2615         /* See the comment for setuid above. */
2616         return 0;
2617 }
2618
2619 static int selinux_task_setpgid(struct task_struct *p, pid_t pgid)
2620 {
2621         return task_has_perm(current, p, PROCESS__SETPGID);
2622 }
2623
2624 static int selinux_task_getpgid(struct task_struct *p)
2625 {
2626         return task_has_perm(current, p, PROCESS__GETPGID);
2627 }
2628
2629 static int selinux_task_getsid(struct task_struct *p)
2630 {
2631         return task_has_perm(current, p, PROCESS__GETSESSION);
2632 }
2633
2634 static int selinux_task_setgroups(struct group_info *group_info)
2635 {
2636         /* See the comment for setuid above. */
2637         return 0;
2638 }
2639
2640 static int selinux_task_setnice(struct task_struct *p, int nice)
2641 {
2642         return task_has_perm(current,p, PROCESS__SETSCHED);
2643 }
2644
2645 static int selinux_task_setrlimit(unsigned int resource, struct rlimit *new_rlim)
2646 {
2647         struct rlimit *old_rlim = current->rlim + resource;
2648
2649         /* Control the ability to change the hard limit (whether
2650            lowering or raising it), so that the hard limit can
2651            later be used as a safe reset point for the soft limit
2652            upon context transitions. See selinux_bprm_apply_creds. */
2653         if (old_rlim->rlim_max != new_rlim->rlim_max)
2654                 return task_has_perm(current, current, PROCESS__SETRLIMIT);
2655
2656         return 0;
2657 }
2658
2659 static int selinux_task_setscheduler(struct task_struct *p, int policy, struct sched_param *lp)
2660 {
2661         struct task_security_struct *tsec1, *tsec2;
2662
2663         tsec1 = current->security;
2664         tsec2 = p->security;
2665
2666         /* No auditing from the setscheduler hook, since the runqueue lock
2667            is held and the system will deadlock if we try to log an audit
2668            message. */
2669         return avc_has_perm_noaudit(tsec1->sid, tsec2->sid,
2670                                     SECCLASS_PROCESS, PROCESS__SETSCHED,
2671                                     &tsec2->avcr, NULL);
2672 }
2673
2674 static int selinux_task_getscheduler(struct task_struct *p)
2675 {
2676         return task_has_perm(current, p, PROCESS__GETSCHED);
2677 }
2678
2679 static int selinux_task_kill(struct task_struct *p, struct siginfo *info, int sig)
2680 {
2681         u32 perm;
2682
2683         if (info && ((unsigned long)info == 1 ||
2684                      (unsigned long)info == 2 || SI_FROMKERNEL(info)))
2685                 return 0;
2686
2687         if (!sig)
2688                 perm = PROCESS__SIGNULL; /* null signal; existence test */
2689         else
2690                 perm = signal_to_av(sig);
2691
2692         return task_has_perm(current, p, perm);
2693 }
2694
2695 static int selinux_task_prctl(int option,
2696                               unsigned long arg2,
2697                               unsigned long arg3,
2698                               unsigned long arg4,
2699                               unsigned long arg5)
2700 {
2701         /* The current prctl operations do not appear to require
2702            any SELinux controls since they merely observe or modify
2703            the state of the current process. */
2704         return 0;
2705 }
2706
2707 static int selinux_task_wait(struct task_struct *p)
2708 {
2709         u32 perm;
2710
2711         perm = signal_to_av(p->exit_signal);
2712
2713         return task_has_perm(p, current, perm);
2714 }
2715
2716 static void selinux_task_reparent_to_init(struct task_struct *p)
2717 {
2718         struct task_security_struct *tsec;
2719
2720         secondary_ops->task_reparent_to_init(p);
2721
2722         tsec = p->security;
2723         tsec->osid = tsec->sid;
2724         tsec->sid = SECINITSID_KERNEL;
2725         return;
2726 }
2727
2728 static void selinux_task_to_inode(struct task_struct *p,
2729                                   struct inode *inode)
2730 {
2731         struct task_security_struct *tsec = p->security;
2732         struct inode_security_struct *isec = inode->i_security;
2733
2734         isec->sid = tsec->sid;
2735         isec->initialized = 1;
2736         return;
2737 }
2738
2739 #ifdef CONFIG_SECURITY_NETWORK
2740
2741 /* Returns error only if unable to parse addresses */
2742 static int selinux_parse_skb_ipv4(struct sk_buff *skb, struct avc_audit_data *ad)
2743 {
2744         int offset, ihlen, ret;
2745         struct iphdr iph;
2746
2747         offset = skb->nh.raw - skb->data;
2748         ret = skb_copy_bits(skb, offset, &iph, sizeof(iph));
2749         if (ret)
2750                 goto out;
2751
2752         ihlen = iph.ihl * 4;
2753         if (ihlen < sizeof(iph))
2754                 goto out;
2755
2756         ad->u.net.v4info.saddr = iph.saddr;
2757         ad->u.net.v4info.daddr = iph.daddr;
2758
2759         switch (iph.protocol) {
2760         case IPPROTO_TCP: {
2761                 struct tcphdr tcph;
2762
2763                 if (ntohs(iph.frag_off) & IP_OFFSET)
2764                         break;
2765
2766                 offset += ihlen;
2767                 if (skb_copy_bits(skb, offset, &tcph, sizeof(tcph)) < 0)
2768                         break;
2769
2770                 ad->u.net.sport = tcph.source;
2771                 ad->u.net.dport = tcph.dest;
2772                 break;
2773         }
2774         
2775         case IPPROTO_UDP: {
2776                 struct udphdr udph;
2777                 
2778                 if (ntohs(iph.frag_off) & IP_OFFSET)
2779                         break;
2780                         
2781                 offset += ihlen;
2782                 if (skb_copy_bits(skb, offset, &udph, sizeof(udph)) < 0)
2783                         break;  
2784
2785                 ad->u.net.sport = udph.source;
2786                 ad->u.net.dport = udph.dest;
2787                 break;
2788         }
2789
2790         default:
2791                 break;
2792         }
2793 out:
2794         return ret;
2795 }
2796
2797 #if defined(CONFIG_IPV6) || defined(CONFIG_IPV6_MODULE)
2798
2799 /* Returns error only if unable to parse addresses */
2800 static int selinux_parse_skb_ipv6(struct sk_buff *skb, struct avc_audit_data *ad)
2801 {
2802         u8 nexthdr;
2803         int ret, offset;
2804         struct ipv6hdr ipv6h;
2805
2806         offset = skb->nh.raw - skb->data;
2807         ret = skb_copy_bits(skb, offset, &ipv6h, sizeof(ipv6h));
2808         if (ret)
2809                 goto out;
2810
2811         ipv6_addr_copy(&ad->u.net.v6info.saddr, &ipv6h.saddr);
2812         ipv6_addr_copy(&ad->u.net.v6info.daddr, &ipv6h.daddr);
2813
2814         nexthdr = ipv6h.nexthdr;
2815         offset += sizeof(ipv6h);
2816         offset = ipv6_skip_exthdr(skb, offset, &nexthdr,
2817                                   skb->tail - skb->head - offset);
2818         if (offset < 0)
2819                 goto out;
2820
2821         switch (nexthdr) {
2822         case IPPROTO_TCP: {
2823                 struct tcphdr tcph;
2824
2825                 if (skb_copy_bits(skb, offset, &tcph, sizeof(tcph)) < 0)
2826                         break;
2827
2828                 ad->u.net.sport = tcph.source;
2829                 ad->u.net.dport = tcph.dest;
2830                 break;
2831         }
2832
2833         case IPPROTO_UDP: {
2834                 struct udphdr udph;
2835
2836                 if (skb_copy_bits(skb, offset, &udph, sizeof(udph)) < 0)
2837                         break;
2838
2839                 ad->u.net.sport = udph.source;
2840                 ad->u.net.dport = udph.dest;
2841                 break;
2842         }
2843
2844         /* includes fragments */
2845         default:
2846                 break;
2847         }
2848 out:
2849         return ret;
2850 }
2851
2852 #endif /* IPV6 */
2853
2854 static int selinux_parse_skb(struct sk_buff *skb, struct avc_audit_data *ad,
2855                              char **addrp, int *len, int src)
2856 {
2857         int ret = 0;
2858
2859         switch (ad->u.net.family) {
2860         case PF_INET:
2861                 ret = selinux_parse_skb_ipv4(skb, ad);
2862                 if (ret || !addrp)
2863                         break;
2864                 *len = 4;
2865                 *addrp = (char *)(src ? &ad->u.net.v4info.saddr :
2866                                         &ad->u.net.v4info.daddr);
2867                 break;
2868
2869 #if defined(CONFIG_IPV6) || defined(CONFIG_IPV6_MODULE)
2870         case PF_INET6:
2871                 ret = selinux_parse_skb_ipv6(skb, ad);
2872                 if (ret || !addrp)
2873                         break;
2874                 *len = 16;
2875                 *addrp = (char *)(src ? &ad->u.net.v6info.saddr :
2876                                         &ad->u.net.v6info.daddr);
2877                 break;
2878 #endif  /* IPV6 */
2879         default:
2880                 break;
2881         }
2882
2883         return ret;
2884 }
2885
2886 /* socket security operations */
2887 static int socket_has_perm(struct task_struct *task, struct socket *sock,
2888                            u32 perms)
2889 {
2890         struct inode_security_struct *isec;
2891         struct task_security_struct *tsec;
2892         struct avc_audit_data ad;
2893         int err = 0;
2894
2895         tsec = task->security;
2896         isec = SOCK_INODE(sock)->i_security;
2897
2898         if (isec->sid == SECINITSID_KERNEL)
2899                 goto out;
2900
2901         AVC_AUDIT_DATA_INIT(&ad,NET);
2902         ad.u.net.sk = sock->sk;
2903         err = avc_has_perm(tsec->sid, isec->sid, isec->sclass,
2904                            perms, &isec->avcr, &ad);
2905
2906 out:
2907         return err;
2908 }
2909
2910 static int selinux_socket_create(int family, int type,
2911                                  int protocol, int kern)
2912 {
2913         int err = 0;
2914         struct task_security_struct *tsec;
2915
2916         if (kern)
2917                 goto out;
2918
2919         tsec = current->security;
2920         err = avc_has_perm(tsec->sid, tsec->sid,
2921                            socket_type_to_security_class(family, type),
2922                            SOCKET__CREATE, NULL, NULL);
2923
2924 out:
2925         return err;
2926 }
2927
2928 static void selinux_socket_post_create(struct socket *sock, int family,
2929                                        int type, int protocol, int kern)
2930 {
2931         int err;
2932         struct inode_security_struct *isec;
2933         struct task_security_struct *tsec;
2934
2935         err = inode_doinit(SOCK_INODE(sock));
2936         if (err < 0)
2937                 return;
2938         isec = SOCK_INODE(sock)->i_security;
2939
2940         tsec = current->security;
2941         isec->sclass = socket_type_to_security_class(family, type);
2942         isec->sid = kern ? SECINITSID_KERNEL : tsec->sid;
2943
2944         return;
2945 }
2946
2947 /* Range of port numbers used to automatically bind.
2948    Need to determine whether we should perform a name_bind
2949    permission check between the socket and the port number. */
2950 #define ip_local_port_range_0 sysctl_local_port_range[0]
2951 #define ip_local_port_range_1 sysctl_local_port_range[1]
2952
2953 static int selinux_socket_bind(struct socket *sock, struct sockaddr *address, int addrlen)
2954 {
2955         u16 family;
2956         int err;
2957
2958         err = socket_has_perm(current, sock, SOCKET__BIND);
2959         if (err)
2960                 goto out;
2961
2962         /*
2963          * If PF_INET or PF_INET6, check name_bind permission for the port.
2964          */
2965         family = sock->sk->sk_family;
2966         if (family == PF_INET || family == PF_INET6) {
2967                 char *addrp;
2968                 struct inode_security_struct *isec;
2969                 struct task_security_struct *tsec;
2970                 struct avc_audit_data ad;
2971                 struct sockaddr_in *addr4 = NULL;
2972                 struct sockaddr_in6 *addr6 = NULL;
2973                 unsigned short snum;
2974                 struct sock *sk = sock->sk;
2975                 u32 sid, node_perm, addrlen;
2976
2977                 tsec = current->security;
2978                 isec = SOCK_INODE(sock)->i_security;
2979
2980                 if (family == PF_INET) {
2981                         addr4 = (struct sockaddr_in *)address;
2982                         snum = ntohs(addr4->sin_port);
2983                         addrlen = sizeof(addr4->sin_addr.s_addr);
2984                         addrp = (char *)&addr4->sin_addr.s_addr;
2985                 } else {
2986                         addr6 = (struct sockaddr_in6 *)address;
2987                         snum = ntohs(addr6->sin6_port);
2988                         addrlen = sizeof(addr6->sin6_addr.s6_addr);
2989                         addrp = (char *)&addr6->sin6_addr.s6_addr;
2990                 }
2991
2992                 if (snum&&(snum < max(PROT_SOCK,ip_local_port_range_0) ||
2993                            snum > ip_local_port_range_1)) {
2994                         err = security_port_sid(sk->sk_family, sk->sk_type,
2995                                                 sk->sk_protocol, snum, &sid);
2996                         if (err)
2997                                 goto out;
2998                         AVC_AUDIT_DATA_INIT(&ad,NET);
2999                         ad.u.net.sport = htons(snum);
3000                         err = avc_has_perm(isec->sid, sid,
3001                                            isec->sclass,
3002                                            SOCKET__NAME_BIND, NULL, &ad);
3003                         if (err)
3004                                 goto out;
3005                 }
3006                 
3007                 switch(sk->sk_protocol) {
3008                 case IPPROTO_TCP:
3009                         node_perm = TCP_SOCKET__NODE_BIND;
3010                         break;
3011                         
3012                 case IPPROTO_UDP:
3013                         node_perm = UDP_SOCKET__NODE_BIND;
3014                         break;
3015                         
3016                 default:
3017                         node_perm = RAWIP_SOCKET__NODE_BIND;
3018                         break;
3019                 }
3020                 
3021                 err = security_node_sid(family, addrp, addrlen, &sid);
3022                 if (err)
3023                         goto out;
3024                 
3025                 AVC_AUDIT_DATA_INIT(&ad,NET);
3026                 ad.u.net.sport = htons(snum);
3027                 ad.u.net.family = family;
3028
3029                 if (family == PF_INET)
3030                         ad.u.net.v4info.saddr = addr4->sin_addr.s_addr;
3031                 else
3032                         ipv6_addr_copy(&ad.u.net.v6info.saddr, &addr6->sin6_addr);
3033
3034                 err = avc_has_perm(isec->sid, sid,
3035                                    isec->sclass, node_perm, NULL, &ad);
3036                 if (err)
3037                         goto out;
3038         }
3039 out:
3040         return err;
3041 }
3042
3043 static int selinux_socket_connect(struct socket *sock, struct sockaddr *address, int addrlen)
3044 {
3045         return socket_has_perm(current, sock, SOCKET__CONNECT);
3046 }
3047
3048 static int selinux_socket_listen(struct socket *sock, int backlog)
3049 {
3050         return socket_has_perm(current, sock, SOCKET__LISTEN);
3051 }
3052
3053 static int selinux_socket_accept(struct socket *sock, struct socket *newsock)
3054 {
3055         int err;
3056         struct inode_security_struct *isec;
3057         struct inode_security_struct *newisec;
3058
3059         err = socket_has_perm(current, sock, SOCKET__ACCEPT);
3060         if (err)
3061                 return err;
3062
3063         err = inode_doinit(SOCK_INODE(newsock));
3064         if (err < 0)
3065                 return err;
3066         newisec = SOCK_INODE(newsock)->i_security;
3067
3068         isec = SOCK_INODE(sock)->i_security;
3069         newisec->sclass = isec->sclass;
3070         newisec->sid = isec->sid;
3071
3072         return 0;
3073 }
3074
3075 static int selinux_socket_sendmsg(struct socket *sock, struct msghdr *msg,
3076                                   int size)
3077 {
3078         return socket_has_perm(current, sock, SOCKET__WRITE);
3079 }
3080
3081 static int selinux_socket_recvmsg(struct socket *sock, struct msghdr *msg,
3082                                   int size, int flags)
3083 {
3084         return socket_has_perm(current, sock, SOCKET__READ);
3085 }
3086
3087 static int selinux_socket_getsockname(struct socket *sock)
3088 {
3089         return socket_has_perm(current, sock, SOCKET__GETATTR);
3090 }
3091
3092 static int selinux_socket_getpeername(struct socket *sock)
3093 {
3094         return socket_has_perm(current, sock, SOCKET__GETATTR);
3095 }
3096
3097 static int selinux_socket_setsockopt(struct socket *sock,int level,int optname)
3098 {
3099         return socket_has_perm(current, sock, SOCKET__SETOPT);
3100 }
3101
3102 static int selinux_socket_getsockopt(struct socket *sock, int level,
3103                                      int optname)
3104 {
3105         return socket_has_perm(current, sock, SOCKET__GETOPT);
3106 }
3107
3108 static int selinux_socket_shutdown(struct socket *sock, int how)
3109 {
3110         return socket_has_perm(current, sock, SOCKET__SHUTDOWN);
3111 }
3112
3113 static int selinux_socket_unix_stream_connect(struct socket *sock,
3114                                               struct socket *other,
3115                                               struct sock *newsk)
3116 {
3117         struct sk_security_struct *ssec;
3118         struct inode_security_struct *isec;
3119         struct inode_security_struct *other_isec;
3120         struct avc_audit_data ad;
3121         int err;
3122
3123         isec = SOCK_INODE(sock)->i_security;
3124         other_isec = SOCK_INODE(other)->i_security;
3125
3126         AVC_AUDIT_DATA_INIT(&ad,NET);
3127         ad.u.net.sk = other->sk;
3128
3129         err = avc_has_perm(isec->sid, other_isec->sid,
3130                            isec->sclass,
3131                            UNIX_STREAM_SOCKET__CONNECTTO,
3132                            &other_isec->avcr, &ad);
3133         if (err)
3134                 return err;
3135
3136         /* connecting socket */
3137         ssec = sock->sk->sk_security;
3138         ssec->peer_sid = other_isec->sid;
3139         
3140         /* server child socket */
3141         ssec = newsk->sk_security;
3142         ssec->peer_sid = isec->sid;
3143         
3144         return 0;
3145 }
3146
3147 static int selinux_socket_unix_may_send(struct socket *sock,
3148                                         struct socket *other)
3149 {
3150         struct inode_security_struct *isec;
3151         struct inode_security_struct *other_isec;
3152         struct avc_audit_data ad;
3153         int err;
3154
3155         isec = SOCK_INODE(sock)->i_security;
3156         other_isec = SOCK_INODE(other)->i_security;
3157
3158         AVC_AUDIT_DATA_INIT(&ad,NET);
3159         ad.u.net.sk = other->sk;
3160
3161         err = avc_has_perm(isec->sid, other_isec->sid,
3162                            isec->sclass,
3163                            SOCKET__SENDTO,
3164                            &other_isec->avcr, &ad);
3165         if (err)
3166                 return err;
3167
3168         return 0;
3169 }
3170
3171 static int selinux_socket_sock_rcv_skb(struct sock *sk, struct sk_buff *skb)
3172 {
3173         u16 family;
3174         char *addrp;
3175         int len, err = 0;
3176         u32 netif_perm, node_perm, node_sid, recv_perm = 0;
3177         struct socket *sock;
3178         struct inode *inode;
3179         struct net_device *dev;
3180         struct sel_netif *netif;
3181         struct netif_security_struct *nsec;
3182         struct inode_security_struct *isec;
3183         struct avc_audit_data ad;
3184
3185         family = sk->sk_family;
3186         if (family != PF_INET && family != PF_INET6)
3187                 goto out;
3188
3189         /* Handle mapped IPv4 packets arriving via IPv6 sockets */
3190         if (family == PF_INET6 && skb->protocol == ntohs(ETH_P_IP))
3191                 family = PF_INET;
3192
3193         sock = sk->sk_socket;
3194         
3195         /* TCP control messages don't always have a socket. */
3196         if (!sock)
3197                 goto out;
3198
3199         inode = SOCK_INODE(sock);
3200         if (!inode)
3201                 goto out;
3202
3203         dev = skb->dev;
3204         if (!dev)
3205                 goto out;
3206
3207         netif = sel_netif_lookup(dev);
3208         if (IS_ERR(netif)) {
3209                 err = PTR_ERR(netif);
3210                 goto out;
3211         }
3212         
3213         nsec = &netif->nsec;
3214         isec = inode->i_security;
3215
3216         switch (isec->sclass) {
3217         case SECCLASS_UDP_SOCKET:
3218                 netif_perm = NETIF__UDP_RECV;
3219                 node_perm = NODE__UDP_RECV;
3220                 recv_perm = UDP_SOCKET__RECV_MSG;
3221                 break;
3222         
3223         case SECCLASS_TCP_SOCKET:
3224                 netif_perm = NETIF__TCP_RECV;
3225                 node_perm = NODE__TCP_RECV;
3226                 recv_perm = TCP_SOCKET__RECV_MSG;
3227                 break;
3228         
3229         default:
3230                 netif_perm = NETIF__RAWIP_RECV;
3231                 node_perm = NODE__RAWIP_RECV;
3232                 break;
3233         }
3234
3235         AVC_AUDIT_DATA_INIT(&ad, NET);
3236         ad.u.net.netif = dev->name;
3237         ad.u.net.family = family;
3238
3239         err = selinux_parse_skb(skb, &ad, &addrp, &len, 1);
3240         if (err) {
3241                 sel_netif_put(netif);
3242                 goto out;
3243         }
3244
3245         err = avc_has_perm(isec->sid, nsec->if_sid, SECCLASS_NETIF,
3246                            netif_perm, &nsec->avcr, &ad);
3247         sel_netif_put(netif);
3248         if (err)
3249                 goto out;
3250         
3251         /* Fixme: this lookup is inefficient */
3252         err = security_node_sid(family, addrp, len, &node_sid);
3253         if (err)
3254                 goto out;
3255         
3256         err = avc_has_perm(isec->sid, node_sid, SECCLASS_NODE, node_perm, NULL, &ad);
3257         if (err)
3258                 goto out;
3259
3260         if (recv_perm) {
3261                 u32 port_sid;
3262
3263                 /* Fixme: make this more efficient */
3264                 err = security_port_sid(sk->sk_family, sk->sk_type,
3265                                         sk->sk_protocol, ntohs(ad.u.net.sport),
3266                                         &port_sid);
3267                 if (err)
3268                         goto out;
3269
3270                 err = avc_has_perm(isec->sid, port_sid, isec->sclass,
3271                                    recv_perm, NULL, &ad);
3272         }
3273 out:    
3274         return err;
3275 }
3276
3277 static int selinux_socket_getpeersec(struct socket *sock, char __user *optval,
3278                                      int __user *optlen, unsigned len)
3279 {
3280         int err = 0;
3281         char *scontext;
3282         u32 scontext_len;
3283         struct sk_security_struct *ssec;
3284         struct inode_security_struct *isec;
3285
3286         isec = SOCK_INODE(sock)->i_security;
3287         if (isec->sclass != SECCLASS_UNIX_STREAM_SOCKET) {
3288                 err = -ENOPROTOOPT;
3289                 goto out;
3290         }
3291
3292         ssec = sock->sk->sk_security;
3293         
3294         err = security_sid_to_context(ssec->peer_sid, &scontext, &scontext_len);
3295         if (err)
3296                 goto out;
3297
3298         if (scontext_len > len) {
3299                 err = -ERANGE;
3300                 goto out_len;
3301         }
3302
3303         if (copy_to_user(optval, scontext, scontext_len))
3304                 err = -EFAULT;
3305
3306 out_len:
3307         if (put_user(scontext_len, optlen))
3308                 err = -EFAULT;
3309
3310         kfree(scontext);
3311 out:    
3312         return err;
3313 }
3314
3315 static int selinux_sk_alloc_security(struct sock *sk, int family, int priority)
3316 {
3317         return sk_alloc_security(sk, family, priority);
3318 }
3319
3320 static void selinux_sk_free_security(struct sock *sk)
3321 {
3322         sk_free_security(sk);
3323 }
3324
3325 #ifdef CONFIG_NETFILTER
3326
3327 static unsigned int selinux_ip_postroute_last(unsigned int hooknum,
3328                                               struct sk_buff **pskb,
3329                                               const struct net_device *in,
3330                                               const struct net_device *out,
3331                                               int (*okfn)(struct sk_buff *),
3332                                               u16 family)
3333 {
3334         char *addrp;
3335         int len, err = NF_ACCEPT;
3336         u32 netif_perm, node_perm, node_sid, send_perm = 0;
3337         struct sock *sk;
3338         struct socket *sock;
3339         struct inode *inode;
3340         struct sel_netif *netif;
3341         struct sk_buff *skb = *pskb;
3342         struct netif_security_struct *nsec;
3343         struct inode_security_struct *isec;
3344         struct avc_audit_data ad;
3345         struct net_device *dev = (struct net_device *)out;
3346         
3347         sk = skb->sk;
3348         if (!sk)
3349                 goto out;
3350                 
3351         sock = sk->sk_socket;
3352         if (!sock)
3353                 goto out;
3354                 
3355         inode = SOCK_INODE(sock);
3356         if (!inode)
3357                 goto out;
3358
3359         netif = sel_netif_lookup(dev);
3360         if (IS_ERR(netif)) {
3361                 err = NF_DROP;
3362                 goto out;
3363         }
3364         
3365         nsec = &netif->nsec;
3366         isec = inode->i_security;
3367         
3368         switch (isec->sclass) {
3369         case SECCLASS_UDP_SOCKET:
3370                 netif_perm = NETIF__UDP_SEND;
3371                 node_perm = NODE__UDP_SEND;
3372                 send_perm = UDP_SOCKET__SEND_MSG;
3373                 break;
3374         
3375         case SECCLASS_TCP_SOCKET:
3376                 netif_perm = NETIF__TCP_SEND;
3377                 node_perm = NODE__TCP_SEND;
3378                 send_perm = TCP_SOCKET__SEND_MSG;
3379                 break;
3380         
3381         default:
3382                 netif_perm = NETIF__RAWIP_SEND;
3383                 node_perm = NODE__RAWIP_SEND;
3384                 break;
3385         }
3386
3387
3388         AVC_AUDIT_DATA_INIT(&ad, NET);
3389         ad.u.net.netif = dev->name;
3390         ad.u.net.family = family;
3391
3392         err = selinux_parse_skb(skb, &ad, &addrp,
3393                                 &len, 0) ? NF_DROP : NF_ACCEPT;
3394         if (err != NF_ACCEPT) {
3395                 sel_netif_put(netif);
3396                 goto out;
3397         }
3398
3399         err = avc_has_perm(isec->sid, nsec->if_sid, SECCLASS_NETIF,
3400                            netif_perm, &nsec->avcr, &ad) ? NF_DROP : NF_ACCEPT;
3401         sel_netif_put(netif);
3402         if (err != NF_ACCEPT)
3403                 goto out;
3404                 
3405         /* Fixme: this lookup is inefficient */
3406         err = security_node_sid(family, addrp, len,
3407                                 &node_sid) ? NF_DROP : NF_ACCEPT;
3408         if (err != NF_ACCEPT)
3409                 goto out;
3410         
3411         err = avc_has_perm(isec->sid, node_sid, SECCLASS_NODE,
3412                            node_perm, NULL, &ad) ? NF_DROP : NF_ACCEPT;
3413         if (err != NF_ACCEPT)
3414                 goto out;
3415
3416         if (send_perm) {
3417                 u32 port_sid;
3418                 
3419                 /* Fixme: make this more efficient */
3420                 err = security_port_sid(sk->sk_family,
3421                                         sk->sk_type,
3422                                         sk->sk_protocol,
3423                                         ntohs(ad.u.net.dport),
3424                                         &port_sid) ? NF_DROP : NF_ACCEPT;
3425                 if (err != NF_ACCEPT)
3426                         goto out;
3427
3428                 err = avc_has_perm(isec->sid, port_sid, isec->sclass,
3429                                    send_perm, NULL, &ad) ? NF_DROP : NF_ACCEPT;
3430         }
3431
3432 out:
3433         return err;
3434 }
3435
3436 static unsigned int selinux_ipv4_postroute_last(unsigned int hooknum,
3437                                                 struct sk_buff **pskb,
3438                                                 const struct net_device *in,
3439                                                 const struct net_device *out,
3440                                                 int (*okfn)(struct sk_buff *))
3441 {
3442         return selinux_ip_postroute_last(hooknum, pskb, in, out, okfn, PF_INET);
3443 }
3444
3445 #if defined(CONFIG_IPV6) || defined(CONFIG_IPV6_MODULE)
3446
3447 static unsigned int selinux_ipv6_postroute_last(unsigned int hooknum,
3448                                                 struct sk_buff **pskb,
3449                                                 const struct net_device *in,
3450                                                 const struct net_device *out,
3451                                                 int (*okfn)(struct sk_buff *))
3452 {
3453         return selinux_ip_postroute_last(hooknum, pskb, in, out, okfn, PF_INET6);
3454 }
3455
3456 #endif  /* IPV6 */
3457
3458 #endif  /* CONFIG_NETFILTER */
3459
3460 #endif  /* CONFIG_SECURITY_NETWORK */
3461
3462 static int ipc_alloc_security(struct task_struct *task,
3463                               struct kern_ipc_perm *perm,
3464                               u16 sclass)
3465 {
3466         struct task_security_struct *tsec = task->security;
3467         struct ipc_security_struct *isec;
3468
3469         isec = kmalloc(sizeof(struct ipc_security_struct), GFP_KERNEL);
3470         if (!isec)
3471                 return -ENOMEM;
3472
3473         memset(isec, 0, sizeof(struct ipc_security_struct));
3474         isec->magic = SELINUX_MAGIC;
3475         isec->sclass = sclass;
3476         isec->ipc_perm = perm;
3477         if (tsec) {
3478                 isec->sid = tsec->sid;
3479         } else {
3480                 isec->sid = SECINITSID_UNLABELED;
3481         }
3482         perm->security = isec;
3483
3484         return 0;
3485 }
3486
3487 static void ipc_free_security(struct kern_ipc_perm *perm)
3488 {
3489         struct ipc_security_struct *isec = perm->security;
3490         if (!isec || isec->magic != SELINUX_MAGIC)
3491                 return;
3492
3493         perm->security = NULL;
3494         kfree(isec);
3495 }
3496
3497 static int msg_msg_alloc_security(struct msg_msg *msg)
3498 {
3499         struct msg_security_struct *msec;
3500
3501         msec = kmalloc(sizeof(struct msg_security_struct), GFP_KERNEL);
3502         if (!msec)
3503                 return -ENOMEM;
3504
3505         memset(msec, 0, sizeof(struct msg_security_struct));
3506         msec->magic = SELINUX_MAGIC;
3507         msec->msg = msg;
3508         msec->sid = SECINITSID_UNLABELED;
3509         msg->security = msec;
3510
3511         return 0;
3512 }
3513
3514 static void msg_msg_free_security(struct msg_msg *msg)
3515 {
3516         struct msg_security_struct *msec = msg->security;
3517         if (!msec || msec->magic != SELINUX_MAGIC)
3518                 return;
3519
3520         msg->security = NULL;
3521         kfree(msec);
3522 }
3523
3524 static int ipc_has_perm(struct kern_ipc_perm *ipc_perms,
3525                         u16 sclass, u32 perms)
3526 {
3527         struct task_security_struct *tsec;
3528         struct ipc_security_struct *isec;
3529         struct avc_audit_data ad;
3530
3531         tsec = current->security;
3532         isec = ipc_perms->security;
3533
3534         AVC_AUDIT_DATA_INIT(&ad, IPC);
3535         ad.u.ipc_id = ipc_perms->key;
3536
3537         return avc_has_perm(tsec->sid, isec->sid, sclass,
3538                             perms, &isec->avcr, &ad);
3539 }
3540
3541 static int selinux_msg_msg_alloc_security(struct msg_msg *msg)
3542 {
3543         return msg_msg_alloc_security(msg);
3544 }
3545
3546 static void selinux_msg_msg_free_security(struct msg_msg *msg)
3547 {
3548         msg_msg_free_security(msg);
3549 }
3550
3551 /* message queue security operations */
3552 static int selinux_msg_queue_alloc_security(struct msg_queue *msq)
3553 {
3554         struct task_security_struct *tsec;
3555         struct ipc_security_struct *isec;
3556         struct avc_audit_data ad;
3557         int rc;
3558
3559         rc = ipc_alloc_security(current, &msq->q_perm, SECCLASS_MSGQ);
3560         if (rc)
3561                 return rc;
3562
3563         tsec = current->security;
3564         isec = msq->q_perm.security;
3565
3566         AVC_AUDIT_DATA_INIT(&ad, IPC);
3567         ad.u.ipc_id = msq->q_perm.key;
3568
3569         rc = avc_has_perm(tsec->sid, isec->sid, SECCLASS_MSGQ,
3570                           MSGQ__CREATE, &isec->avcr, &ad);
3571         if (rc) {
3572                 ipc_free_security(&msq->q_perm);
3573                 return rc;
3574         }
3575         return 0;
3576 }
3577
3578 static void selinux_msg_queue_free_security(struct msg_queue *msq)
3579 {
3580         ipc_free_security(&msq->q_perm);
3581 }
3582
3583 static int selinux_msg_queue_associate(struct msg_queue *msq, int msqflg)
3584 {
3585         struct task_security_struct *tsec;
3586         struct ipc_security_struct *isec;
3587         struct avc_audit_data ad;
3588
3589         tsec = current->security;
3590         isec = msq->q_perm.security;
3591
3592         AVC_AUDIT_DATA_INIT(&ad, IPC);
3593         ad.u.ipc_id = msq->q_perm.key;
3594
3595         return avc_has_perm(tsec->sid, isec->sid, SECCLASS_MSGQ,
3596                             MSGQ__ASSOCIATE, &isec->avcr, &ad);
3597 }
3598
3599 static int selinux_msg_queue_msgctl(struct msg_queue *msq, int cmd)
3600 {
3601         int err;
3602         int perms;
3603
3604         switch(cmd) {
3605         case IPC_INFO:
3606         case MSG_INFO:
3607                 /* No specific object, just general system-wide information. */
3608                 return task_has_system(current, SYSTEM__IPC_INFO);
3609         case IPC_STAT:
3610         case MSG_STAT:
3611                 perms = MSGQ__GETATTR | MSGQ__ASSOCIATE;
3612                 break;
3613         case IPC_SET:
3614                 perms = MSGQ__SETATTR;
3615                 break;
3616         case IPC_RMID:
3617                 perms = MSGQ__DESTROY;
3618                 break;
3619         default:
3620                 return 0;
3621         }
3622
3623         err = ipc_has_perm(&msq->q_perm, SECCLASS_MSGQ, perms);
3624         return err;
3625 }
3626
3627 static int selinux_msg_queue_msgsnd(struct msg_queue *msq, struct msg_msg *msg, int msqflg)
3628 {
3629         struct task_security_struct *tsec;
3630         struct ipc_security_struct *isec;
3631         struct msg_security_struct *msec;
3632         struct avc_audit_data ad;
3633         int rc;
3634
3635         tsec = current->security;
3636         isec = msq->q_perm.security;
3637         msec = msg->security;
3638
3639         /*
3640          * First time through, need to assign label to the message
3641          */
3642         if (msec->sid == SECINITSID_UNLABELED) {
3643                 /*
3644                  * Compute new sid based on current process and
3645                  * message queue this message will be stored in
3646                  */
3647                 rc = security_transition_sid(tsec->sid,
3648                                              isec->sid,
3649                                              SECCLASS_MSG,
3650                                              &msec->sid);
3651                 if (rc)
3652                         return rc;
3653         }
3654
3655         AVC_AUDIT_DATA_INIT(&ad, IPC);
3656         ad.u.ipc_id = msq->q_perm.key;
3657
3658         /* Can this process write to the queue? */
3659         rc = avc_has_perm(tsec->sid, isec->sid, SECCLASS_MSGQ,
3660                           MSGQ__WRITE, &isec->avcr, &ad);
3661         if (!rc)
3662                 /* Can this process send the message */
3663                 rc = avc_has_perm(tsec->sid, msec->sid,
3664                                   SECCLASS_MSG, MSG__SEND,
3665                                   &msec->avcr, &ad);
3666         if (!rc)
3667                 /* Can the message be put in the queue? */
3668                 rc = avc_has_perm(msec->sid, isec->sid,
3669                                   SECCLASS_MSGQ, MSGQ__ENQUEUE,
3670                                   &isec->avcr, &ad);
3671
3672         return rc;
3673 }
3674
3675 static int selinux_msg_queue_msgrcv(struct msg_queue *msq, struct msg_msg *msg,
3676                                     struct task_struct *target,
3677                                     long type, int mode)
3678 {
3679         struct task_security_struct *tsec;
3680         struct ipc_security_struct *isec;
3681         struct msg_security_struct *msec;
3682         struct avc_audit_data ad;
3683         int rc;
3684
3685         tsec = target->security;
3686         isec = msq->q_perm.security;
3687         msec = msg->security;
3688
3689         AVC_AUDIT_DATA_INIT(&ad, IPC);
3690         ad.u.ipc_id = msq->q_perm.key;
3691
3692         rc = avc_has_perm(tsec->sid, isec->sid,
3693                           SECCLASS_MSGQ, MSGQ__READ,
3694                           &isec->avcr, &ad);
3695         if (!rc)
3696                 rc = avc_has_perm(tsec->sid, msec->sid,
3697                                   SECCLASS_MSG, MSG__RECEIVE,
3698                                   &msec->avcr, &ad);
3699         return rc;
3700 }
3701
3702 /* Shared Memory security operations */
3703 static int selinux_shm_alloc_security(struct shmid_kernel *shp)
3704 {
3705         struct task_security_struct *tsec;
3706         struct ipc_security_struct *isec;
3707         struct avc_audit_data ad;
3708         int rc;
3709
3710         rc = ipc_alloc_security(current, &shp->shm_perm, SECCLASS_SHM);
3711         if (rc)
3712                 return rc;
3713
3714         tsec = current->security;
3715         isec = shp->shm_perm.security;
3716
3717         AVC_AUDIT_DATA_INIT(&ad, IPC);
3718         ad.u.ipc_id = shp->shm_perm.key;
3719
3720         rc = avc_has_perm(tsec->sid, isec->sid, SECCLASS_SHM,
3721                           SHM__CREATE, &isec->avcr, &ad);
3722         if (rc) {
3723                 ipc_free_security(&shp->shm_perm);
3724                 return rc;
3725         }
3726         return 0;
3727 }
3728
3729 static void selinux_shm_free_security(struct shmid_kernel *shp)
3730 {
3731         ipc_free_security(&shp->shm_perm);
3732 }
3733
3734 static int selinux_shm_associate(struct shmid_kernel *shp, int shmflg)
3735 {
3736         struct task_security_struct *tsec;
3737         struct ipc_security_struct *isec;
3738         struct avc_audit_data ad;
3739
3740         tsec = current->security;
3741         isec = shp->shm_perm.security;
3742
3743         AVC_AUDIT_DATA_INIT(&ad, IPC);
3744         ad.u.ipc_id = shp->shm_perm.key;
3745
3746         return avc_has_perm(tsec->sid, isec->sid, SECCLASS_SHM,
3747                             SHM__ASSOCIATE, &isec->avcr, &ad);
3748 }
3749
3750 /* Note, at this point, shp is locked down */
3751 static int selinux_shm_shmctl(struct shmid_kernel *shp, int cmd)
3752 {
3753         int perms;
3754         int err;
3755
3756         switch(cmd) {
3757         case IPC_INFO:
3758         case SHM_INFO:
3759                 /* No specific object, just general system-wide information. */
3760                 return task_has_system(current, SYSTEM__IPC_INFO);
3761         case IPC_STAT:
3762         case SHM_STAT:
3763                 perms = SHM__GETATTR | SHM__ASSOCIATE;
3764                 break;
3765         case IPC_SET:
3766                 perms = SHM__SETATTR;
3767                 break;
3768         case SHM_LOCK:
3769         case SHM_UNLOCK:
3770                 perms = SHM__LOCK;
3771                 break;
3772         case IPC_RMID:
3773                 perms = SHM__DESTROY;
3774                 break;
3775         default:
3776                 return 0;
3777         }
3778
3779         err = ipc_has_perm(&shp->shm_perm, SECCLASS_SHM, perms);
3780         return err;
3781 }
3782
3783 static int selinux_shm_shmat(struct shmid_kernel *shp,
3784                              char __user *shmaddr, int shmflg)
3785 {
3786         u32 perms;
3787
3788         if (shmflg & SHM_RDONLY)
3789                 perms = SHM__READ;
3790         else
3791                 perms = SHM__READ | SHM__WRITE;
3792
3793         return ipc_has_perm(&shp->shm_perm, SECCLASS_SHM, perms);
3794 }
3795
3796 /* Semaphore security operations */
3797 static int selinux_sem_alloc_security(struct sem_array *sma)
3798 {
3799         struct task_security_struct *tsec;
3800         struct ipc_security_struct *isec;
3801         struct avc_audit_data ad;
3802         int rc;
3803
3804         rc = ipc_alloc_security(current, &sma->sem_perm, SECCLASS_SEM);
3805         if (rc)
3806                 return rc;
3807
3808         tsec = current->security;
3809         isec = sma->sem_perm.security;
3810
3811         AVC_AUDIT_DATA_INIT(&ad, IPC);
3812         ad.u.ipc_id = sma->sem_perm.key;
3813
3814         rc = avc_has_perm(tsec->sid, isec->sid, SECCLASS_SEM,
3815                           SEM__CREATE, &isec->avcr, &ad);
3816         if (rc) {
3817                 ipc_free_security(&sma->sem_perm);
3818                 return rc;
3819         }
3820         return 0;
3821 }
3822
3823 static void selinux_sem_free_security(struct sem_array *sma)
3824 {
3825         ipc_free_security(&sma->sem_perm);
3826 }
3827
3828 static int selinux_sem_associate(struct sem_array *sma, int semflg)
3829 {
3830         struct task_security_struct *tsec;
3831         struct ipc_security_struct *isec;
3832         struct avc_audit_data ad;
3833
3834         tsec = current->security;
3835         isec = sma->sem_perm.security;
3836
3837         AVC_AUDIT_DATA_INIT(&ad, IPC);
3838         ad.u.ipc_id = sma->sem_perm.key;
3839
3840         return avc_has_perm(tsec->sid, isec->sid, SECCLASS_SEM,
3841                             SEM__ASSOCIATE, &isec->avcr, &ad);
3842 }
3843
3844 /* Note, at this point, sma is locked down */
3845 static int selinux_sem_semctl(struct sem_array *sma, int cmd)
3846 {
3847         int err;
3848         u32 perms;
3849
3850         switch(cmd) {
3851         case IPC_INFO:
3852         case SEM_INFO:
3853                 /* No specific object, just general system-wide information. */
3854                 return task_has_system(current, SYSTEM__IPC_INFO);
3855         case GETPID:
3856         case GETNCNT:
3857         case GETZCNT:
3858                 perms = SEM__GETATTR;
3859                 break;
3860         case GETVAL:
3861         case GETALL:
3862                 perms = SEM__READ;
3863                 break;
3864         case SETVAL:
3865         case SETALL:
3866                 perms = SEM__WRITE;
3867                 break;
3868         case IPC_RMID:
3869                 perms = SEM__DESTROY;
3870                 break;
3871         case IPC_SET:
3872                 perms = SEM__SETATTR;
3873                 break;
3874         case IPC_STAT:
3875         case SEM_STAT:
3876                 perms = SEM__GETATTR | SEM__ASSOCIATE;
3877                 break;
3878         default:
3879                 return 0;
3880         }
3881
3882         err = ipc_has_perm(&sma->sem_perm, SECCLASS_SEM, perms);
3883         return err;
3884 }
3885
3886 static int selinux_sem_semop(struct sem_array *sma,
3887                              struct sembuf *sops, unsigned nsops, int alter)
3888 {
3889         u32 perms;
3890
3891         if (alter)
3892                 perms = SEM__READ | SEM__WRITE;
3893         else
3894                 perms = SEM__READ;
3895
3896         return ipc_has_perm(&sma->sem_perm, SECCLASS_SEM, perms);
3897 }
3898
3899 static int selinux_ipc_permission(struct kern_ipc_perm *ipcp, short flag)
3900 {
3901         struct ipc_security_struct *isec = ipcp->security;
3902         u16 sclass = SECCLASS_IPC;
3903         u32 av = 0;
3904
3905         if (isec && isec->magic == SELINUX_MAGIC)
3906                 sclass = isec->sclass;
3907
3908         av = 0;
3909         if (flag & S_IRUGO)
3910                 av |= IPC__UNIX_READ;
3911         if (flag & S_IWUGO)
3912                 av |= IPC__UNIX_WRITE;
3913
3914         if (av == 0)
3915                 return 0;
3916
3917         return ipc_has_perm(ipcp, sclass, av);
3918 }
3919
3920 /* module stacking operations */
3921 int selinux_register_security (const char *name, struct security_operations *ops)
3922 {
3923         if (secondary_ops != original_ops) {
3924                 printk(KERN_INFO "%s:  There is already a secondary security "
3925                        "module registered.\n", __FUNCTION__);
3926                 return -EINVAL;
3927         }
3928
3929         secondary_ops = ops;
3930
3931         printk(KERN_INFO "%s:  Registering secondary module %s\n",
3932                __FUNCTION__,
3933                name);
3934
3935         return 0;
3936 }
3937
3938 int selinux_unregister_security (const char *name, struct security_operations *ops)
3939 {
3940         if (ops != secondary_ops) {
3941                 printk (KERN_INFO "%s:  trying to unregister a security module "
3942                         "that is not registered.\n", __FUNCTION__);
3943                 return -EINVAL;
3944         }
3945
3946         secondary_ops = original_ops;
3947
3948         return 0;
3949 }
3950
3951 static void selinux_d_instantiate (struct dentry *dentry, struct inode *inode)
3952 {
3953         if (inode)
3954                 inode_doinit_with_dentry(inode, dentry);
3955 }
3956
3957 static int selinux_getprocattr(struct task_struct *p,
3958                                char *name, void *value, size_t size)
3959 {
3960         struct task_security_struct *tsec;
3961         u32 sid, len;
3962         char *context;
3963         int error;
3964
3965         if (current != p) {
3966                 error = task_has_perm(current, p, PROCESS__GETATTR);
3967                 if (error)
3968                         return error;
3969         }
3970
3971         if (!size)
3972                 return -ERANGE;
3973
3974         tsec = p->security;
3975
3976         if (!strcmp(name, "current"))
3977                 sid = tsec->sid;
3978         else if (!strcmp(name, "prev"))
3979                 sid = tsec->osid;
3980         else if (!strcmp(name, "exec"))
3981                 sid = tsec->exec_sid;
3982         else if (!strcmp(name, "fscreate"))
3983                 sid = tsec->create_sid;
3984         else
3985                 return -EINVAL;
3986
3987         if (!sid)
3988                 return 0;
3989
3990         error = security_sid_to_context(sid, &context, &len);
3991         if (error)
3992                 return error;
3993         if (len > size) {
3994                 kfree(context);
3995                 return -ERANGE;
3996         }
3997         memcpy(value, context, len);
3998         kfree(context);
3999         return len;
4000 }
4001
4002 static int selinux_setprocattr(struct task_struct *p,
4003                                char *name, void *value, size_t size)
4004 {
4005         struct task_security_struct *tsec;
4006         u32 sid = 0;
4007         int error;
4008
4009         if (current != p || !strcmp(name, "current")) {
4010                 /* SELinux only allows a process to change its own
4011                    security attributes, and it only allows the process
4012                    current SID to change via exec. */
4013                 return -EACCES;
4014         }
4015
4016         /*
4017          * Basic control over ability to set these attributes at all.
4018          * current == p, but we'll pass them separately in case the
4019          * above restriction is ever removed.
4020          */
4021         if (!strcmp(name, "exec"))
4022                 error = task_has_perm(current, p, PROCESS__SETEXEC);
4023         else if (!strcmp(name, "fscreate"))
4024                 error = task_has_perm(current, p, PROCESS__SETFSCREATE);
4025         else
4026                 error = -EINVAL;
4027         if (error)
4028                 return error;
4029
4030         /* Obtain a SID for the context, if one was specified. */
4031         if (size) {
4032                 int error;
4033                 error = security_context_to_sid(value, size, &sid);
4034                 if (error)
4035                         return error;
4036         }
4037
4038         /* Permission checking based on the specified context is
4039            performed during the actual operation (execve,
4040            open/mkdir/...), when we know the full context of the
4041            operation.  See selinux_bprm_set_security for the execve
4042            checks and may_create for the file creation checks. The
4043            operation will then fail if the context is not permitted. */
4044         tsec = p->security;
4045         if (!strcmp(name, "exec"))
4046                 tsec->exec_sid = sid;
4047         else if (!strcmp(name, "fscreate"))
4048                 tsec->create_sid = sid;
4049         else
4050                 return -EINVAL;
4051
4052         return size;
4053 }
4054
4055 struct security_operations selinux_ops = {
4056         .ptrace =                       selinux_ptrace,
4057         .capget =                       selinux_capget,
4058         .capset_check =                 selinux_capset_check,
4059         .capset_set =                   selinux_capset_set,
4060         .sysctl =                       selinux_sysctl,
4061         .capable =                      selinux_capable,
4062         .quotactl =                     selinux_quotactl,
4063         .quota_on =                     selinux_quota_on,
4064         .syslog =                       selinux_syslog,
4065         .vm_enough_memory =             selinux_vm_enough_memory,
4066
4067         .netlink_send =                 selinux_netlink_send,
4068         .netlink_recv =                 selinux_netlink_recv,
4069
4070         .bprm_alloc_security =          selinux_bprm_alloc_security,
4071         .bprm_free_security =           selinux_bprm_free_security,
4072         .bprm_apply_creds =             selinux_bprm_apply_creds,
4073         .bprm_set_security =            selinux_bprm_set_security,
4074         .bprm_check_security =          selinux_bprm_check_security,
4075         .bprm_secureexec =              selinux_bprm_secureexec,
4076
4077         .sb_alloc_security =            selinux_sb_alloc_security,
4078         .sb_free_security =             selinux_sb_free_security,
4079         .sb_copy_data =                 selinux_sb_copy_data,
4080         .sb_kern_mount =                selinux_sb_kern_mount,
4081         .sb_statfs =                    selinux_sb_statfs,
4082         .sb_mount =                     selinux_mount,
4083         .sb_umount =                    selinux_umount,
4084
4085         .inode_alloc_security =         selinux_inode_alloc_security,
4086         .inode_free_security =          selinux_inode_free_security,
4087         .inode_create =                 selinux_inode_create,
4088         .inode_post_create =            selinux_inode_post_create,
4089         .inode_link =                   selinux_inode_link,
4090         .inode_post_link =              selinux_inode_post_link,
4091         .inode_unlink =                 selinux_inode_unlink,
4092         .inode_symlink =                selinux_inode_symlink,
4093         .inode_post_symlink =           selinux_inode_post_symlink,
4094         .inode_mkdir =                  selinux_inode_mkdir,
4095         .inode_post_mkdir =             selinux_inode_post_mkdir,
4096         .inode_rmdir =                  selinux_inode_rmdir,
4097         .inode_mknod =                  selinux_inode_mknod,
4098         .inode_post_mknod =             selinux_inode_post_mknod,
4099         .inode_rename =                 selinux_inode_rename,
4100         .inode_post_rename =            selinux_inode_post_rename,
4101         .inode_readlink =               selinux_inode_readlink,
4102         .inode_follow_link =            selinux_inode_follow_link,
4103         .inode_permission =             selinux_inode_permission,
4104         .inode_setattr =                selinux_inode_setattr,
4105         .inode_getattr =                selinux_inode_getattr,
4106         .inode_setxattr =               selinux_inode_setxattr,
4107         .inode_post_setxattr =          selinux_inode_post_setxattr,
4108         .inode_getxattr =               selinux_inode_getxattr,
4109         .inode_listxattr =              selinux_inode_listxattr,
4110         .inode_removexattr =            selinux_inode_removexattr,
4111         .inode_getsecurity =            selinux_inode_getsecurity,
4112         .inode_setsecurity =            selinux_inode_setsecurity,
4113         .inode_listsecurity =           selinux_inode_listsecurity,
4114
4115         .file_permission =              selinux_file_permission,
4116         .file_alloc_security =          selinux_file_alloc_security,
4117         .file_free_security =           selinux_file_free_security,
4118         .file_ioctl =                   selinux_file_ioctl,
4119         .file_mmap =                    selinux_file_mmap,
4120         .file_mprotect =                selinux_file_mprotect,
4121         .file_lock =                    selinux_file_lock,
4122         .file_fcntl =                   selinux_file_fcntl,
4123         .file_set_fowner =              selinux_file_set_fowner,
4124         .file_send_sigiotask =          selinux_file_send_sigiotask,
4125         .file_receive =                 selinux_file_receive,
4126
4127         .task_create =                  selinux_task_create,
4128         .task_alloc_security =          selinux_task_alloc_security,
4129         .task_free_security =           selinux_task_free_security,
4130         .task_setuid =                  selinux_task_setuid,
4131         .task_post_setuid =             selinux_task_post_setuid,
4132         .task_setgid =                  selinux_task_setgid,
4133         .task_setpgid =                 selinux_task_setpgid,
4134         .task_getpgid =                 selinux_task_getpgid,
4135         .task_getsid =                  selinux_task_getsid,
4136         .task_setgroups =               selinux_task_setgroups,
4137         .task_setnice =                 selinux_task_setnice,
4138         .task_setrlimit =               selinux_task_setrlimit,
4139         .task_setscheduler =            selinux_task_setscheduler,
4140         .task_getscheduler =            selinux_task_getscheduler,
4141         .task_kill =                    selinux_task_kill,
4142         .task_wait =                    selinux_task_wait,
4143         .task_prctl =                   selinux_task_prctl,
4144         .task_reparent_to_init =        selinux_task_reparent_to_init,
4145         .task_to_inode =                selinux_task_to_inode,
4146
4147         .ipc_permission =               selinux_ipc_permission,
4148
4149         .msg_msg_alloc_security =       selinux_msg_msg_alloc_security,
4150         .msg_msg_free_security =        selinux_msg_msg_free_security,
4151
4152         .msg_queue_alloc_security =     selinux_msg_queue_alloc_security,
4153         .msg_queue_free_security =      selinux_msg_queue_free_security,
4154         .msg_queue_associate =          selinux_msg_queue_associate,
4155         .msg_queue_msgctl =             selinux_msg_queue_msgctl,
4156         .msg_queue_msgsnd =             selinux_msg_queue_msgsnd,
4157         .msg_queue_msgrcv =             selinux_msg_queue_msgrcv,
4158
4159         .shm_alloc_security =           selinux_shm_alloc_security,
4160         .shm_free_security =            selinux_shm_free_security,
4161         .shm_associate =                selinux_shm_associate,
4162         .shm_shmctl =                   selinux_shm_shmctl,
4163         .shm_shmat =                    selinux_shm_shmat,
4164
4165         .sem_alloc_security =           selinux_sem_alloc_security,
4166         .sem_free_security =            selinux_sem_free_security,
4167         .sem_associate =                selinux_sem_associate,
4168         .sem_semctl =                   selinux_sem_semctl,
4169         .sem_semop =                    selinux_sem_semop,
4170
4171         .register_security =            selinux_register_security,
4172         .unregister_security =          selinux_unregister_security,
4173
4174         .d_instantiate =                selinux_d_instantiate,
4175
4176         .getprocattr =                  selinux_getprocattr,
4177         .setprocattr =                  selinux_setprocattr,
4178
4179 #ifdef CONFIG_SECURITY_NETWORK
4180         .unix_stream_connect =          selinux_socket_unix_stream_connect,
4181         .unix_may_send =                selinux_socket_unix_may_send,
4182
4183         .socket_create =                selinux_socket_create,
4184         .socket_post_create =           selinux_socket_post_create,
4185         .socket_bind =                  selinux_socket_bind,
4186         .socket_connect =               selinux_socket_connect,
4187         .socket_listen =                selinux_socket_listen,
4188         .socket_accept =                selinux_socket_accept,
4189         .socket_sendmsg =               selinux_socket_sendmsg,
4190         .socket_recvmsg =               selinux_socket_recvmsg,
4191         .socket_getsockname =           selinux_socket_getsockname,
4192         .socket_getpeername =           selinux_socket_getpeername,
4193         .socket_getsockopt =            selinux_socket_getsockopt,
4194         .socket_setsockopt =            selinux_socket_setsockopt,
4195         .socket_shutdown =              selinux_socket_shutdown,
4196         .socket_sock_rcv_skb =          selinux_socket_sock_rcv_skb,
4197         .socket_getpeersec =            selinux_socket_getpeersec,
4198         .sk_alloc_security =            selinux_sk_alloc_security,
4199         .sk_free_security =             selinux_sk_free_security,
4200 #endif
4201 };
4202
4203 __init int selinux_init(void)
4204 {
4205         struct task_security_struct *tsec;
4206
4207         if (!selinux_enabled) {
4208                 printk(KERN_INFO "SELinux:  Disabled at boot.\n");
4209                 return 0;
4210         }
4211
4212         printk(KERN_INFO "SELinux:  Initializing.\n");
4213
4214         /* Set the security state for the initial task. */
4215         if (task_alloc_security(current))
4216                 panic("SELinux:  Failed to initialize initial task.\n");
4217         tsec = current->security;
4218         tsec->osid = tsec->sid = SECINITSID_KERNEL;
4219
4220         avc_init();
4221
4222         original_ops = secondary_ops = security_ops;
4223         if (!secondary_ops)
4224                 panic ("SELinux: No initial security operations\n");
4225         if (register_security (&selinux_ops))
4226                 panic("SELinux: Unable to register with kernel.\n");
4227
4228         if (selinux_enforcing) {
4229                 printk(KERN_INFO "SELinux:  Starting in enforcing mode\n");
4230         } else {
4231                 printk(KERN_INFO "SELinux:  Starting in permissive mode\n");
4232         }
4233         return 0;
4234 }
4235
4236 void selinux_complete_init(void)
4237 {
4238         printk(KERN_INFO "SELinux:  Completing initialization.\n");
4239
4240         /* Set up any superblocks initialized prior to the policy load. */
4241         printk(KERN_INFO "SELinux:  Setting up existing superblocks.\n");
4242         spin_lock(&sb_security_lock);
4243 next_sb:
4244         if (!list_empty(&superblock_security_head)) {
4245                 struct superblock_security_struct *sbsec =
4246                                 list_entry(superblock_security_head.next,
4247                                            struct superblock_security_struct,
4248                                            list);
4249                 struct super_block *sb = sbsec->sb;
4250                 spin_lock(&sb_lock);
4251                 sb->s_count++;
4252                 spin_unlock(&sb_lock);
4253                 spin_unlock(&sb_security_lock);
4254                 down_read(&sb->s_umount);
4255                 if (sb->s_root)
4256                         superblock_doinit(sb, NULL);
4257                 drop_super(sb);
4258                 spin_lock(&sb_security_lock);
4259                 list_del_init(&sbsec->list);
4260                 goto next_sb;
4261         }
4262         spin_unlock(&sb_security_lock);
4263 }
4264
4265 /* SELinux requires early initialization in order to label
4266    all processes and objects when they are created. */
4267 security_initcall(selinux_init);
4268
4269 #if defined(CONFIG_SECURITY_NETWORK) && defined(CONFIG_NETFILTER)
4270
4271 static struct nf_hook_ops selinux_ipv4_op = {
4272         .hook =         selinux_ipv4_postroute_last,
4273         .owner =        THIS_MODULE,
4274         .pf =           PF_INET,
4275         .hooknum =      NF_IP_POST_ROUTING,
4276         .priority =     NF_IP_PRI_SELINUX_LAST,
4277 };
4278
4279 #if defined(CONFIG_IPV6) || defined(CONFIG_IPV6_MODULE)
4280
4281 static struct nf_hook_ops selinux_ipv6_op = {
4282         .hook =         selinux_ipv6_postroute_last,
4283         .owner =        THIS_MODULE,
4284         .pf =           PF_INET6,
4285         .hooknum =      NF_IP6_POST_ROUTING,
4286         .priority =     NF_IP6_PRI_SELINUX_LAST,
4287 };
4288
4289 #endif  /* IPV6 */
4290
4291 static int __init selinux_nf_ip_init(void)
4292 {
4293         int err = 0;
4294
4295         if (!selinux_enabled)
4296                 goto out;
4297                 
4298         printk(KERN_INFO "SELinux:  Registering netfilter hooks\n");
4299         
4300         err = nf_register_hook(&selinux_ipv4_op);
4301         if (err)
4302                 panic("SELinux: nf_register_hook for IPv4: error %d\n", err);
4303
4304 #if defined(CONFIG_IPV6) || defined(CONFIG_IPV6_MODULE)
4305
4306         err = nf_register_hook(&selinux_ipv6_op);
4307         if (err)
4308                 panic("SELinux: nf_register_hook for IPv6: error %d\n", err);
4309
4310 #endif  /* IPV6 */
4311 out:
4312         return err;
4313 }
4314
4315 __initcall(selinux_nf_ip_init);
4316
4317 #ifdef CONFIG_SECURITY_SELINUX_DISABLE
4318 static void selinux_nf_ip_exit(void)
4319 {
4320         printk(KERN_INFO "SELinux:  Unregistering netfilter hooks\n");
4321
4322         nf_unregister_hook(&selinux_ipv4_op);
4323 #if defined(CONFIG_IPV6) || defined(CONFIG_IPV6_MODULE)
4324         nf_unregister_hook(&selinux_ipv6_op);
4325 #endif  /* IPV6 */
4326 }
4327 #endif
4328
4329 #else /* CONFIG_SECURITY_NETWORK && CONFIG_NETFILTER */
4330
4331 #ifdef CONFIG_SECURITY_SELINUX_DISABLE
4332 #define selinux_nf_ip_exit()
4333 #endif
4334
4335 #endif /* CONFIG_SECURITY_NETWORK && CONFIG_NETFILTER */
4336
4337 #ifdef CONFIG_SECURITY_SELINUX_DISABLE
4338 int selinux_disable(void)
4339 {
4340         extern void exit_sel_fs(void);
4341         static int selinux_disabled = 0;
4342
4343         if (ss_initialized) {
4344                 /* Not permitted after initial policy load. */
4345                 return -EINVAL;
4346         }
4347
4348         if (selinux_disabled) {
4349                 /* Only do this once. */
4350                 return -EINVAL;
4351         }
4352
4353         printk(KERN_INFO "SELinux:  Disabled at runtime.\n");
4354
4355         selinux_disabled = 1;
4356
4357         /* Reset security_ops to the secondary module, dummy or capability. */
4358         security_ops = secondary_ops;
4359
4360         /* Unregister netfilter hooks. */
4361         selinux_nf_ip_exit();
4362
4363         /* Unregister selinuxfs. */
4364         exit_sel_fs();
4365
4366         return 0;
4367 }
4368 #endif
4369
4370