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