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