[PATCH] selinux: remove security struct magic number fields and tests
[linux-2.6.git] / security / selinux / hooks.c
1 /*
2  *  NSA Security-Enhanced Linux (SELinux) security module
3  *
4  *  This file contains the SELinux hook function implementations.
5  *
6  *  Authors:  Stephen Smalley, <sds@epoch.ncsc.mil>
7  *            Chris Vance, <cvance@nai.com>
8  *            Wayne Salamon, <wsalamon@nai.com>
9  *            James Morris <jmorris@redhat.com>
10  *
11  *  Copyright (C) 2001,2002 Networks Associates Technology, Inc.
12  *  Copyright (C) 2003 Red Hat, Inc., James Morris <jmorris@redhat.com>
13  *  Copyright (C) 2004-2005 Trusted Computer Solutions, Inc.
14  *                          <dgoeddel@trustedcs.com>
15  *
16  *      This program is free software; you can redistribute it and/or modify
17  *      it under the terms of the GNU General Public License version 2,
18  *      as published by the Free Software Foundation.
19  */
20
21 #include <linux/config.h>
22 #include <linux/module.h>
23 #include <linux/init.h>
24 #include <linux/kernel.h>
25 #include <linux/ptrace.h>
26 #include <linux/errno.h>
27 #include <linux/sched.h>
28 #include <linux/security.h>
29 #include <linux/xattr.h>
30 #include <linux/capability.h>
31 #include <linux/unistd.h>
32 #include <linux/mm.h>
33 #include <linux/mman.h>
34 #include <linux/slab.h>
35 #include <linux/pagemap.h>
36 #include <linux/swap.h>
37 #include <linux/smp_lock.h>
38 #include <linux/spinlock.h>
39 #include <linux/syscalls.h>
40 #include <linux/file.h>
41 #include <linux/namei.h>
42 #include <linux/mount.h>
43 #include <linux/ext2_fs.h>
44 #include <linux/proc_fs.h>
45 #include <linux/kd.h>
46 #include <linux/netfilter_ipv4.h>
47 #include <linux/netfilter_ipv6.h>
48 #include <linux/tty.h>
49 #include <net/icmp.h>
50 #include <net/ip.h>             /* for sysctl_local_port_range[] */
51 #include <net/tcp.h>            /* struct or_callable used in sock_rcv_skb */
52 #include <asm/uaccess.h>
53 #include <asm/semaphore.h>
54 #include <asm/ioctls.h>
55 #include <linux/bitops.h>
56 #include <linux/interrupt.h>
57 #include <linux/netdevice.h>    /* for network interface checks */
58 #include <linux/netlink.h>
59 #include <linux/tcp.h>
60 #include <linux/udp.h>
61 #include <linux/quota.h>
62 #include <linux/un.h>           /* for Unix socket types */
63 #include <net/af_unix.h>        /* for Unix socket types */
64 #include <linux/parser.h>
65 #include <linux/nfs_mount.h>
66 #include <net/ipv6.h>
67 #include <linux/hugetlb.h>
68 #include <linux/personality.h>
69 #include <linux/sysctl.h>
70 #include <linux/audit.h>
71 #include <linux/string.h>
72
73 #include "avc.h"
74 #include "objsec.h"
75 #include "netif.h"
76 #include "xfrm.h"
77
78 #define XATTR_SELINUX_SUFFIX "selinux"
79 #define XATTR_NAME_SELINUX XATTR_SECURITY_PREFIX XATTR_SELINUX_SUFFIX
80
81 extern unsigned int policydb_loaded_version;
82 extern int selinux_nlmsg_lookup(u16 sclass, u16 nlmsg_type, u32 *perm);
83
84 #ifdef CONFIG_SECURITY_SELINUX_DEVELOP
85 int selinux_enforcing = 0;
86
87 static int __init enforcing_setup(char *str)
88 {
89         selinux_enforcing = simple_strtol(str,NULL,0);
90         return 1;
91 }
92 __setup("enforcing=", enforcing_setup);
93 #endif
94
95 #ifdef CONFIG_SECURITY_SELINUX_BOOTPARAM
96 int selinux_enabled = CONFIG_SECURITY_SELINUX_BOOTPARAM_VALUE;
97
98 static int __init selinux_enabled_setup(char *str)
99 {
100         selinux_enabled = simple_strtol(str, NULL, 0);
101         return 1;
102 }
103 __setup("selinux=", selinux_enabled_setup);
104 #endif
105
106 /* Original (dummy) security module. */
107 static struct security_operations *original_ops = NULL;
108
109 /* Minimal support for a secondary security module,
110    just to allow the use of the dummy or capability modules.
111    The owlsm module can alternatively be used as a secondary
112    module as long as CONFIG_OWLSM_FD is not enabled. */
113 static struct security_operations *secondary_ops = NULL;
114
115 /* Lists of inode and superblock security structures initialized
116    before the policy was loaded. */
117 static LIST_HEAD(superblock_security_head);
118 static DEFINE_SPINLOCK(sb_security_lock);
119
120 /* Allocate and free functions for each kind of security blob. */
121
122 static int task_alloc_security(struct task_struct *task)
123 {
124         struct task_security_struct *tsec;
125
126         tsec = kzalloc(sizeof(struct task_security_struct), GFP_KERNEL);
127         if (!tsec)
128                 return -ENOMEM;
129
130         tsec->task = task;
131         tsec->osid = tsec->sid = tsec->ptrace_sid = SECINITSID_UNLABELED;
132         task->security = tsec;
133
134         return 0;
135 }
136
137 static void task_free_security(struct task_struct *task)
138 {
139         struct task_security_struct *tsec = task->security;
140         task->security = NULL;
141         kfree(tsec);
142 }
143
144 static int inode_alloc_security(struct inode *inode)
145 {
146         struct task_security_struct *tsec = current->security;
147         struct inode_security_struct *isec;
148
149         isec = kzalloc(sizeof(struct inode_security_struct), GFP_KERNEL);
150         if (!isec)
151                 return -ENOMEM;
152
153         init_MUTEX(&isec->sem);
154         INIT_LIST_HEAD(&isec->list);
155         isec->inode = inode;
156         isec->sid = SECINITSID_UNLABELED;
157         isec->sclass = SECCLASS_FILE;
158         isec->task_sid = tsec->sid;
159         inode->i_security = isec;
160
161         return 0;
162 }
163
164 static void inode_free_security(struct inode *inode)
165 {
166         struct inode_security_struct *isec = inode->i_security;
167         struct superblock_security_struct *sbsec = inode->i_sb->s_security;
168
169         spin_lock(&sbsec->isec_lock);
170         if (!list_empty(&isec->list))
171                 list_del_init(&isec->list);
172         spin_unlock(&sbsec->isec_lock);
173
174         inode->i_security = NULL;
175         kfree(isec);
176 }
177
178 static int file_alloc_security(struct file *file)
179 {
180         struct task_security_struct *tsec = current->security;
181         struct file_security_struct *fsec;
182
183         fsec = kzalloc(sizeof(struct file_security_struct), GFP_KERNEL);
184         if (!fsec)
185                 return -ENOMEM;
186
187         fsec->file = file;
188         fsec->sid = tsec->sid;
189         fsec->fown_sid = tsec->sid;
190         file->f_security = fsec;
191
192         return 0;
193 }
194
195 static void file_free_security(struct file *file)
196 {
197         struct file_security_struct *fsec = file->f_security;
198         file->f_security = NULL;
199         kfree(fsec);
200 }
201
202 static int superblock_alloc_security(struct super_block *sb)
203 {
204         struct superblock_security_struct *sbsec;
205
206         sbsec = kzalloc(sizeof(struct superblock_security_struct), GFP_KERNEL);
207         if (!sbsec)
208                 return -ENOMEM;
209
210         init_MUTEX(&sbsec->sem);
211         INIT_LIST_HEAD(&sbsec->list);
212         INIT_LIST_HEAD(&sbsec->isec_head);
213         spin_lock_init(&sbsec->isec_lock);
214         sbsec->sb = sb;
215         sbsec->sid = SECINITSID_UNLABELED;
216         sbsec->def_sid = SECINITSID_FILE;
217         sb->s_security = sbsec;
218
219         return 0;
220 }
221
222 static void superblock_free_security(struct super_block *sb)
223 {
224         struct superblock_security_struct *sbsec = sb->s_security;
225
226         spin_lock(&sb_security_lock);
227         if (!list_empty(&sbsec->list))
228                 list_del_init(&sbsec->list);
229         spin_unlock(&sb_security_lock);
230
231         sb->s_security = NULL;
232         kfree(sbsec);
233 }
234
235 #ifdef CONFIG_SECURITY_NETWORK
236 static int sk_alloc_security(struct sock *sk, int family, gfp_t priority)
237 {
238         struct sk_security_struct *ssec;
239
240         if (family != PF_UNIX)
241                 return 0;
242
243         ssec = kzalloc(sizeof(*ssec), priority);
244         if (!ssec)
245                 return -ENOMEM;
246
247         ssec->sk = sk;
248         ssec->peer_sid = SECINITSID_UNLABELED;
249         sk->sk_security = ssec;
250
251         return 0;
252 }
253
254 static void sk_free_security(struct sock *sk)
255 {
256         struct sk_security_struct *ssec = sk->sk_security;
257
258         if (sk->sk_family != PF_UNIX)
259                 return;
260
261         sk->sk_security = NULL;
262         kfree(ssec);
263 }
264 #endif  /* CONFIG_SECURITY_NETWORK */
265
266 /* The security server must be initialized before
267    any labeling or access decisions can be provided. */
268 extern int ss_initialized;
269
270 /* The file system's label must be initialized prior to use. */
271
272 static char *labeling_behaviors[6] = {
273         "uses xattr",
274         "uses transition SIDs",
275         "uses task SIDs",
276         "uses genfs_contexts",
277         "not configured for labeling",
278         "uses mountpoint labeling",
279 };
280
281 static int inode_doinit_with_dentry(struct inode *inode, struct dentry *opt_dentry);
282
283 static inline int inode_doinit(struct inode *inode)
284 {
285         return inode_doinit_with_dentry(inode, NULL);
286 }
287
288 enum {
289         Opt_context = 1,
290         Opt_fscontext = 2,
291         Opt_defcontext = 4,
292 };
293
294 static match_table_t tokens = {
295         {Opt_context, "context=%s"},
296         {Opt_fscontext, "fscontext=%s"},
297         {Opt_defcontext, "defcontext=%s"},
298 };
299
300 #define SEL_MOUNT_FAIL_MSG "SELinux:  duplicate or incompatible mount options\n"
301
302 static int try_context_mount(struct super_block *sb, void *data)
303 {
304         char *context = NULL, *defcontext = NULL;
305         const char *name;
306         u32 sid;
307         int alloc = 0, rc = 0, seen = 0;
308         struct task_security_struct *tsec = current->security;
309         struct superblock_security_struct *sbsec = sb->s_security;
310
311         if (!data)
312                 goto out;
313
314         name = sb->s_type->name;
315
316         if (sb->s_type->fs_flags & FS_BINARY_MOUNTDATA) {
317
318                 /* NFS we understand. */
319                 if (!strcmp(name, "nfs")) {
320                         struct nfs_mount_data *d = data;
321
322                         if (d->version <  NFS_MOUNT_VERSION)
323                                 goto out;
324
325                         if (d->context[0]) {
326                                 context = d->context;
327                                 seen |= Opt_context;
328                         }
329                 } else
330                         goto out;
331
332         } else {
333                 /* Standard string-based options. */
334                 char *p, *options = data;
335
336                 while ((p = strsep(&options, ",")) != NULL) {
337                         int token;
338                         substring_t args[MAX_OPT_ARGS];
339
340                         if (!*p)
341                                 continue;
342
343                         token = match_token(p, tokens, args);
344
345                         switch (token) {
346                         case Opt_context:
347                                 if (seen) {
348                                         rc = -EINVAL;
349                                         printk(KERN_WARNING SEL_MOUNT_FAIL_MSG);
350                                         goto out_free;
351                                 }
352                                 context = match_strdup(&args[0]);
353                                 if (!context) {
354                                         rc = -ENOMEM;
355                                         goto out_free;
356                                 }
357                                 if (!alloc)
358                                         alloc = 1;
359                                 seen |= Opt_context;
360                                 break;
361
362                         case Opt_fscontext:
363                                 if (seen & (Opt_context|Opt_fscontext)) {
364                                         rc = -EINVAL;
365                                         printk(KERN_WARNING SEL_MOUNT_FAIL_MSG);
366                                         goto out_free;
367                                 }
368                                 context = match_strdup(&args[0]);
369                                 if (!context) {
370                                         rc = -ENOMEM;
371                                         goto out_free;
372                                 }
373                                 if (!alloc)
374                                         alloc = 1;
375                                 seen |= Opt_fscontext;
376                                 break;
377
378                         case Opt_defcontext:
379                                 if (sbsec->behavior != SECURITY_FS_USE_XATTR) {
380                                         rc = -EINVAL;
381                                         printk(KERN_WARNING "SELinux:  "
382                                                "defcontext option is invalid "
383                                                "for this filesystem type\n");
384                                         goto out_free;
385                                 }
386                                 if (seen & (Opt_context|Opt_defcontext)) {
387                                         rc = -EINVAL;
388                                         printk(KERN_WARNING SEL_MOUNT_FAIL_MSG);
389                                         goto out_free;
390                                 }
391                                 defcontext = match_strdup(&args[0]);
392                                 if (!defcontext) {
393                                         rc = -ENOMEM;
394                                         goto out_free;
395                                 }
396                                 if (!alloc)
397                                         alloc = 1;
398                                 seen |= Opt_defcontext;
399                                 break;
400
401                         default:
402                                 rc = -EINVAL;
403                                 printk(KERN_WARNING "SELinux:  unknown mount "
404                                        "option\n");
405                                 goto out_free;
406
407                         }
408                 }
409         }
410
411         if (!seen)
412                 goto out;
413
414         if (context) {
415                 rc = security_context_to_sid(context, strlen(context), &sid);
416                 if (rc) {
417                         printk(KERN_WARNING "SELinux: security_context_to_sid"
418                                "(%s) failed for (dev %s, type %s) errno=%d\n",
419                                context, sb->s_id, name, rc);
420                         goto out_free;
421                 }
422
423                 rc = avc_has_perm(tsec->sid, sbsec->sid, SECCLASS_FILESYSTEM,
424                                   FILESYSTEM__RELABELFROM, NULL);
425                 if (rc)
426                         goto out_free;
427
428                 rc = avc_has_perm(tsec->sid, sid, SECCLASS_FILESYSTEM,
429                                   FILESYSTEM__RELABELTO, NULL);
430                 if (rc)
431                         goto out_free;
432
433                 sbsec->sid = sid;
434
435                 if (seen & Opt_context)
436                         sbsec->behavior = SECURITY_FS_USE_MNTPOINT;
437         }
438
439         if (defcontext) {
440                 rc = security_context_to_sid(defcontext, strlen(defcontext), &sid);
441                 if (rc) {
442                         printk(KERN_WARNING "SELinux: security_context_to_sid"
443                                "(%s) failed for (dev %s, type %s) errno=%d\n",
444                                defcontext, sb->s_id, name, rc);
445                         goto out_free;
446                 }
447
448                 if (sid == sbsec->def_sid)
449                         goto out_free;
450
451                 rc = avc_has_perm(tsec->sid, sbsec->sid, SECCLASS_FILESYSTEM,
452                                   FILESYSTEM__RELABELFROM, NULL);
453                 if (rc)
454                         goto out_free;
455
456                 rc = avc_has_perm(sid, sbsec->sid, SECCLASS_FILESYSTEM,
457                                   FILESYSTEM__ASSOCIATE, NULL);
458                 if (rc)
459                         goto out_free;
460
461                 sbsec->def_sid = sid;
462         }
463
464 out_free:
465         if (alloc) {
466                 kfree(context);
467                 kfree(defcontext);
468         }
469 out:
470         return rc;
471 }
472
473 static int superblock_doinit(struct super_block *sb, void *data)
474 {
475         struct superblock_security_struct *sbsec = sb->s_security;
476         struct dentry *root = sb->s_root;
477         struct inode *inode = root->d_inode;
478         int rc = 0;
479
480         down(&sbsec->sem);
481         if (sbsec->initialized)
482                 goto out;
483
484         if (!ss_initialized) {
485                 /* Defer initialization until selinux_complete_init,
486                    after the initial policy is loaded and the security
487                    server is ready to handle calls. */
488                 spin_lock(&sb_security_lock);
489                 if (list_empty(&sbsec->list))
490                         list_add(&sbsec->list, &superblock_security_head);
491                 spin_unlock(&sb_security_lock);
492                 goto out;
493         }
494
495         /* Determine the labeling behavior to use for this filesystem type. */
496         rc = security_fs_use(sb->s_type->name, &sbsec->behavior, &sbsec->sid);
497         if (rc) {
498                 printk(KERN_WARNING "%s:  security_fs_use(%s) returned %d\n",
499                        __FUNCTION__, sb->s_type->name, rc);
500                 goto out;
501         }
502
503         rc = try_context_mount(sb, data);
504         if (rc)
505                 goto out;
506
507         if (sbsec->behavior == SECURITY_FS_USE_XATTR) {
508                 /* Make sure that the xattr handler exists and that no
509                    error other than -ENODATA is returned by getxattr on
510                    the root directory.  -ENODATA is ok, as this may be
511                    the first boot of the SELinux kernel before we have
512                    assigned xattr values to the filesystem. */
513                 if (!inode->i_op->getxattr) {
514                         printk(KERN_WARNING "SELinux: (dev %s, type %s) has no "
515                                "xattr support\n", sb->s_id, sb->s_type->name);
516                         rc = -EOPNOTSUPP;
517                         goto out;
518                 }
519                 rc = inode->i_op->getxattr(root, XATTR_NAME_SELINUX, NULL, 0);
520                 if (rc < 0 && rc != -ENODATA) {
521                         if (rc == -EOPNOTSUPP)
522                                 printk(KERN_WARNING "SELinux: (dev %s, type "
523                                        "%s) has no security xattr handler\n",
524                                        sb->s_id, sb->s_type->name);
525                         else
526                                 printk(KERN_WARNING "SELinux: (dev %s, type "
527                                        "%s) getxattr errno %d\n", sb->s_id,
528                                        sb->s_type->name, -rc);
529                         goto out;
530                 }
531         }
532
533         if (strcmp(sb->s_type->name, "proc") == 0)
534                 sbsec->proc = 1;
535
536         sbsec->initialized = 1;
537
538         if (sbsec->behavior > ARRAY_SIZE(labeling_behaviors)) {
539                 printk(KERN_INFO "SELinux: initialized (dev %s, type %s), unknown behavior\n",
540                        sb->s_id, sb->s_type->name);
541         }
542         else {
543                 printk(KERN_INFO "SELinux: initialized (dev %s, type %s), %s\n",
544                        sb->s_id, sb->s_type->name,
545                        labeling_behaviors[sbsec->behavior-1]);
546         }
547
548         /* Initialize the root inode. */
549         rc = inode_doinit_with_dentry(sb->s_root->d_inode, sb->s_root);
550
551         /* Initialize any other inodes associated with the superblock, e.g.
552            inodes created prior to initial policy load or inodes created
553            during get_sb by a pseudo filesystem that directly
554            populates itself. */
555         spin_lock(&sbsec->isec_lock);
556 next_inode:
557         if (!list_empty(&sbsec->isec_head)) {
558                 struct inode_security_struct *isec =
559                                 list_entry(sbsec->isec_head.next,
560                                            struct inode_security_struct, list);
561                 struct inode *inode = isec->inode;
562                 spin_unlock(&sbsec->isec_lock);
563                 inode = igrab(inode);
564                 if (inode) {
565                         if (!IS_PRIVATE (inode))
566                                 inode_doinit(inode);
567                         iput(inode);
568                 }
569                 spin_lock(&sbsec->isec_lock);
570                 list_del_init(&isec->list);
571                 goto next_inode;
572         }
573         spin_unlock(&sbsec->isec_lock);
574 out:
575         up(&sbsec->sem);
576         return rc;
577 }
578
579 static inline u16 inode_mode_to_security_class(umode_t mode)
580 {
581         switch (mode & S_IFMT) {
582         case S_IFSOCK:
583                 return SECCLASS_SOCK_FILE;
584         case S_IFLNK:
585                 return SECCLASS_LNK_FILE;
586         case S_IFREG:
587                 return SECCLASS_FILE;
588         case S_IFBLK:
589                 return SECCLASS_BLK_FILE;
590         case S_IFDIR:
591                 return SECCLASS_DIR;
592         case S_IFCHR:
593                 return SECCLASS_CHR_FILE;
594         case S_IFIFO:
595                 return SECCLASS_FIFO_FILE;
596
597         }
598
599         return SECCLASS_FILE;
600 }
601
602 static inline int default_protocol_stream(int protocol)
603 {
604         return (protocol == IPPROTO_IP || protocol == IPPROTO_TCP);
605 }
606
607 static inline int default_protocol_dgram(int protocol)
608 {
609         return (protocol == IPPROTO_IP || protocol == IPPROTO_UDP);
610 }
611
612 static inline u16 socket_type_to_security_class(int family, int type, int protocol)
613 {
614         switch (family) {
615         case PF_UNIX:
616                 switch (type) {
617                 case SOCK_STREAM:
618                 case SOCK_SEQPACKET:
619                         return SECCLASS_UNIX_STREAM_SOCKET;
620                 case SOCK_DGRAM:
621                         return SECCLASS_UNIX_DGRAM_SOCKET;
622                 }
623                 break;
624         case PF_INET:
625         case PF_INET6:
626                 switch (type) {
627                 case SOCK_STREAM:
628                         if (default_protocol_stream(protocol))
629                                 return SECCLASS_TCP_SOCKET;
630                         else
631                                 return SECCLASS_RAWIP_SOCKET;
632                 case SOCK_DGRAM:
633                         if (default_protocol_dgram(protocol))
634                                 return SECCLASS_UDP_SOCKET;
635                         else
636                                 return SECCLASS_RAWIP_SOCKET;
637                 default:
638                         return SECCLASS_RAWIP_SOCKET;
639                 }
640                 break;
641         case PF_NETLINK:
642                 switch (protocol) {
643                 case NETLINK_ROUTE:
644                         return SECCLASS_NETLINK_ROUTE_SOCKET;
645                 case NETLINK_FIREWALL:
646                         return SECCLASS_NETLINK_FIREWALL_SOCKET;
647                 case NETLINK_INET_DIAG:
648                         return SECCLASS_NETLINK_TCPDIAG_SOCKET;
649                 case NETLINK_NFLOG:
650                         return SECCLASS_NETLINK_NFLOG_SOCKET;
651                 case NETLINK_XFRM:
652                         return SECCLASS_NETLINK_XFRM_SOCKET;
653                 case NETLINK_SELINUX:
654                         return SECCLASS_NETLINK_SELINUX_SOCKET;
655                 case NETLINK_AUDIT:
656                         return SECCLASS_NETLINK_AUDIT_SOCKET;
657                 case NETLINK_IP6_FW:
658                         return SECCLASS_NETLINK_IP6FW_SOCKET;
659                 case NETLINK_DNRTMSG:
660                         return SECCLASS_NETLINK_DNRT_SOCKET;
661                 case NETLINK_KOBJECT_UEVENT:
662                         return SECCLASS_NETLINK_KOBJECT_UEVENT_SOCKET;
663                 default:
664                         return SECCLASS_NETLINK_SOCKET;
665                 }
666         case PF_PACKET:
667                 return SECCLASS_PACKET_SOCKET;
668         case PF_KEY:
669                 return SECCLASS_KEY_SOCKET;
670         }
671
672         return SECCLASS_SOCKET;
673 }
674
675 #ifdef CONFIG_PROC_FS
676 static int selinux_proc_get_sid(struct proc_dir_entry *de,
677                                 u16 tclass,
678                                 u32 *sid)
679 {
680         int buflen, rc;
681         char *buffer, *path, *end;
682
683         buffer = (char*)__get_free_page(GFP_KERNEL);
684         if (!buffer)
685                 return -ENOMEM;
686
687         buflen = PAGE_SIZE;
688         end = buffer+buflen;
689         *--end = '\0';
690         buflen--;
691         path = end-1;
692         *path = '/';
693         while (de && de != de->parent) {
694                 buflen -= de->namelen + 1;
695                 if (buflen < 0)
696                         break;
697                 end -= de->namelen;
698                 memcpy(end, de->name, de->namelen);
699                 *--end = '/';
700                 path = end;
701                 de = de->parent;
702         }
703         rc = security_genfs_sid("proc", path, tclass, sid);
704         free_page((unsigned long)buffer);
705         return rc;
706 }
707 #else
708 static int selinux_proc_get_sid(struct proc_dir_entry *de,
709                                 u16 tclass,
710                                 u32 *sid)
711 {
712         return -EINVAL;
713 }
714 #endif
715
716 /* The inode's security attributes must be initialized before first use. */
717 static int inode_doinit_with_dentry(struct inode *inode, struct dentry *opt_dentry)
718 {
719         struct superblock_security_struct *sbsec = NULL;
720         struct inode_security_struct *isec = inode->i_security;
721         u32 sid;
722         struct dentry *dentry;
723 #define INITCONTEXTLEN 255
724         char *context = NULL;
725         unsigned len = 0;
726         int rc = 0;
727         int hold_sem = 0;
728
729         if (isec->initialized)
730                 goto out;
731
732         down(&isec->sem);
733         hold_sem = 1;
734         if (isec->initialized)
735                 goto out;
736
737         sbsec = inode->i_sb->s_security;
738         if (!sbsec->initialized) {
739                 /* Defer initialization until selinux_complete_init,
740                    after the initial policy is loaded and the security
741                    server is ready to handle calls. */
742                 spin_lock(&sbsec->isec_lock);
743                 if (list_empty(&isec->list))
744                         list_add(&isec->list, &sbsec->isec_head);
745                 spin_unlock(&sbsec->isec_lock);
746                 goto out;
747         }
748
749         switch (sbsec->behavior) {
750         case SECURITY_FS_USE_XATTR:
751                 if (!inode->i_op->getxattr) {
752                         isec->sid = sbsec->def_sid;
753                         break;
754                 }
755
756                 /* Need a dentry, since the xattr API requires one.
757                    Life would be simpler if we could just pass the inode. */
758                 if (opt_dentry) {
759                         /* Called from d_instantiate or d_splice_alias. */
760                         dentry = dget(opt_dentry);
761                 } else {
762                         /* Called from selinux_complete_init, try to find a dentry. */
763                         dentry = d_find_alias(inode);
764                 }
765                 if (!dentry) {
766                         printk(KERN_WARNING "%s:  no dentry for dev=%s "
767                                "ino=%ld\n", __FUNCTION__, inode->i_sb->s_id,
768                                inode->i_ino);
769                         goto out;
770                 }
771
772                 len = INITCONTEXTLEN;
773                 context = kmalloc(len, GFP_KERNEL);
774                 if (!context) {
775                         rc = -ENOMEM;
776                         dput(dentry);
777                         goto out;
778                 }
779                 rc = inode->i_op->getxattr(dentry, XATTR_NAME_SELINUX,
780                                            context, len);
781                 if (rc == -ERANGE) {
782                         /* Need a larger buffer.  Query for the right size. */
783                         rc = inode->i_op->getxattr(dentry, XATTR_NAME_SELINUX,
784                                                    NULL, 0);
785                         if (rc < 0) {
786                                 dput(dentry);
787                                 goto out;
788                         }
789                         kfree(context);
790                         len = rc;
791                         context = kmalloc(len, GFP_KERNEL);
792                         if (!context) {
793                                 rc = -ENOMEM;
794                                 dput(dentry);
795                                 goto out;
796                         }
797                         rc = inode->i_op->getxattr(dentry,
798                                                    XATTR_NAME_SELINUX,
799                                                    context, len);
800                 }
801                 dput(dentry);
802                 if (rc < 0) {
803                         if (rc != -ENODATA) {
804                                 printk(KERN_WARNING "%s:  getxattr returned "
805                                        "%d for dev=%s ino=%ld\n", __FUNCTION__,
806                                        -rc, inode->i_sb->s_id, inode->i_ino);
807                                 kfree(context);
808                                 goto out;
809                         }
810                         /* Map ENODATA to the default file SID */
811                         sid = sbsec->def_sid;
812                         rc = 0;
813                 } else {
814                         rc = security_context_to_sid_default(context, rc, &sid,
815                                                              sbsec->def_sid);
816                         if (rc) {
817                                 printk(KERN_WARNING "%s:  context_to_sid(%s) "
818                                        "returned %d for dev=%s ino=%ld\n",
819                                        __FUNCTION__, context, -rc,
820                                        inode->i_sb->s_id, inode->i_ino);
821                                 kfree(context);
822                                 /* Leave with the unlabeled SID */
823                                 rc = 0;
824                                 break;
825                         }
826                 }
827                 kfree(context);
828                 isec->sid = sid;
829                 break;
830         case SECURITY_FS_USE_TASK:
831                 isec->sid = isec->task_sid;
832                 break;
833         case SECURITY_FS_USE_TRANS:
834                 /* Default to the fs SID. */
835                 isec->sid = sbsec->sid;
836
837                 /* Try to obtain a transition SID. */
838                 isec->sclass = inode_mode_to_security_class(inode->i_mode);
839                 rc = security_transition_sid(isec->task_sid,
840                                              sbsec->sid,
841                                              isec->sclass,
842                                              &sid);
843                 if (rc)
844                         goto out;
845                 isec->sid = sid;
846                 break;
847         default:
848                 /* Default to the fs SID. */
849                 isec->sid = sbsec->sid;
850
851                 if (sbsec->proc) {
852                         struct proc_inode *proci = PROC_I(inode);
853                         if (proci->pde) {
854                                 isec->sclass = inode_mode_to_security_class(inode->i_mode);
855                                 rc = selinux_proc_get_sid(proci->pde,
856                                                           isec->sclass,
857                                                           &sid);
858                                 if (rc)
859                                         goto out;
860                                 isec->sid = sid;
861                         }
862                 }
863                 break;
864         }
865
866         isec->initialized = 1;
867
868 out:
869         if (isec->sclass == SECCLASS_FILE)
870                 isec->sclass = inode_mode_to_security_class(inode->i_mode);
871
872         if (hold_sem)
873                 up(&isec->sem);
874         return rc;
875 }
876
877 /* Convert a Linux signal to an access vector. */
878 static inline u32 signal_to_av(int sig)
879 {
880         u32 perm = 0;
881
882         switch (sig) {
883         case SIGCHLD:
884                 /* Commonly granted from child to parent. */
885                 perm = PROCESS__SIGCHLD;
886                 break;
887         case SIGKILL:
888                 /* Cannot be caught or ignored */
889                 perm = PROCESS__SIGKILL;
890                 break;
891         case SIGSTOP:
892                 /* Cannot be caught or ignored */
893                 perm = PROCESS__SIGSTOP;
894                 break;
895         default:
896                 /* All other signals. */
897                 perm = PROCESS__SIGNAL;
898                 break;
899         }
900
901         return perm;
902 }
903
904 /* Check permission betweeen a pair of tasks, e.g. signal checks,
905    fork check, ptrace check, etc. */
906 static int task_has_perm(struct task_struct *tsk1,
907                          struct task_struct *tsk2,
908                          u32 perms)
909 {
910         struct task_security_struct *tsec1, *tsec2;
911
912         tsec1 = tsk1->security;
913         tsec2 = tsk2->security;
914         return avc_has_perm(tsec1->sid, tsec2->sid,
915                             SECCLASS_PROCESS, perms, NULL);
916 }
917
918 /* Check whether a task is allowed to use a capability. */
919 static int task_has_capability(struct task_struct *tsk,
920                                int cap)
921 {
922         struct task_security_struct *tsec;
923         struct avc_audit_data ad;
924
925         tsec = tsk->security;
926
927         AVC_AUDIT_DATA_INIT(&ad,CAP);
928         ad.tsk = tsk;
929         ad.u.cap = cap;
930
931         return avc_has_perm(tsec->sid, tsec->sid,
932                             SECCLASS_CAPABILITY, CAP_TO_MASK(cap), &ad);
933 }
934
935 /* Check whether a task is allowed to use a system operation. */
936 static int task_has_system(struct task_struct *tsk,
937                            u32 perms)
938 {
939         struct task_security_struct *tsec;
940
941         tsec = tsk->security;
942
943         return avc_has_perm(tsec->sid, SECINITSID_KERNEL,
944                             SECCLASS_SYSTEM, perms, NULL);
945 }
946
947 /* Check whether a task has a particular permission to an inode.
948    The 'adp' parameter is optional and allows other audit
949    data to be passed (e.g. the dentry). */
950 static int inode_has_perm(struct task_struct *tsk,
951                           struct inode *inode,
952                           u32 perms,
953                           struct avc_audit_data *adp)
954 {
955         struct task_security_struct *tsec;
956         struct inode_security_struct *isec;
957         struct avc_audit_data ad;
958
959         tsec = tsk->security;
960         isec = inode->i_security;
961
962         if (!adp) {
963                 adp = &ad;
964                 AVC_AUDIT_DATA_INIT(&ad, FS);
965                 ad.u.fs.inode = inode;
966         }
967
968         return avc_has_perm(tsec->sid, isec->sid, isec->sclass, perms, adp);
969 }
970
971 /* Same as inode_has_perm, but pass explicit audit data containing
972    the dentry to help the auditing code to more easily generate the
973    pathname if needed. */
974 static inline int dentry_has_perm(struct task_struct *tsk,
975                                   struct vfsmount *mnt,
976                                   struct dentry *dentry,
977                                   u32 av)
978 {
979         struct inode *inode = dentry->d_inode;
980         struct avc_audit_data ad;
981         AVC_AUDIT_DATA_INIT(&ad,FS);
982         ad.u.fs.mnt = mnt;
983         ad.u.fs.dentry = dentry;
984         return inode_has_perm(tsk, inode, av, &ad);
985 }
986
987 /* Check whether a task can use an open file descriptor to
988    access an inode in a given way.  Check access to the
989    descriptor itself, and then use dentry_has_perm to
990    check a particular permission to the file.
991    Access to the descriptor is implicitly granted if it
992    has the same SID as the process.  If av is zero, then
993    access to the file is not checked, e.g. for cases
994    where only the descriptor is affected like seek. */
995 static int file_has_perm(struct task_struct *tsk,
996                                 struct file *file,
997                                 u32 av)
998 {
999         struct task_security_struct *tsec = tsk->security;
1000         struct file_security_struct *fsec = file->f_security;
1001         struct vfsmount *mnt = file->f_vfsmnt;
1002         struct dentry *dentry = file->f_dentry;
1003         struct inode *inode = dentry->d_inode;
1004         struct avc_audit_data ad;
1005         int rc;
1006
1007         AVC_AUDIT_DATA_INIT(&ad, FS);
1008         ad.u.fs.mnt = mnt;
1009         ad.u.fs.dentry = dentry;
1010
1011         if (tsec->sid != fsec->sid) {
1012                 rc = avc_has_perm(tsec->sid, fsec->sid,
1013                                   SECCLASS_FD,
1014                                   FD__USE,
1015                                   &ad);
1016                 if (rc)
1017                         return rc;
1018         }
1019
1020         /* av is zero if only checking access to the descriptor. */
1021         if (av)
1022                 return inode_has_perm(tsk, inode, av, &ad);
1023
1024         return 0;
1025 }
1026
1027 /* Check whether a task can create a file. */
1028 static int may_create(struct inode *dir,
1029                       struct dentry *dentry,
1030                       u16 tclass)
1031 {
1032         struct task_security_struct *tsec;
1033         struct inode_security_struct *dsec;
1034         struct superblock_security_struct *sbsec;
1035         u32 newsid;
1036         struct avc_audit_data ad;
1037         int rc;
1038
1039         tsec = current->security;
1040         dsec = dir->i_security;
1041         sbsec = dir->i_sb->s_security;
1042
1043         AVC_AUDIT_DATA_INIT(&ad, FS);
1044         ad.u.fs.dentry = dentry;
1045
1046         rc = avc_has_perm(tsec->sid, dsec->sid, SECCLASS_DIR,
1047                           DIR__ADD_NAME | DIR__SEARCH,
1048                           &ad);
1049         if (rc)
1050                 return rc;
1051
1052         if (tsec->create_sid && sbsec->behavior != SECURITY_FS_USE_MNTPOINT) {
1053                 newsid = tsec->create_sid;
1054         } else {
1055                 rc = security_transition_sid(tsec->sid, dsec->sid, tclass,
1056                                              &newsid);
1057                 if (rc)
1058                         return rc;
1059         }
1060
1061         rc = avc_has_perm(tsec->sid, newsid, tclass, FILE__CREATE, &ad);
1062         if (rc)
1063                 return rc;
1064
1065         return avc_has_perm(newsid, sbsec->sid,
1066                             SECCLASS_FILESYSTEM,
1067                             FILESYSTEM__ASSOCIATE, &ad);
1068 }
1069
1070 #define MAY_LINK   0
1071 #define MAY_UNLINK 1
1072 #define MAY_RMDIR  2
1073
1074 /* Check whether a task can link, unlink, or rmdir a file/directory. */
1075 static int may_link(struct inode *dir,
1076                     struct dentry *dentry,
1077                     int kind)
1078
1079 {
1080         struct task_security_struct *tsec;
1081         struct inode_security_struct *dsec, *isec;
1082         struct avc_audit_data ad;
1083         u32 av;
1084         int rc;
1085
1086         tsec = current->security;
1087         dsec = dir->i_security;
1088         isec = dentry->d_inode->i_security;
1089
1090         AVC_AUDIT_DATA_INIT(&ad, FS);
1091         ad.u.fs.dentry = dentry;
1092
1093         av = DIR__SEARCH;
1094         av |= (kind ? DIR__REMOVE_NAME : DIR__ADD_NAME);
1095         rc = avc_has_perm(tsec->sid, dsec->sid, SECCLASS_DIR, av, &ad);
1096         if (rc)
1097                 return rc;
1098
1099         switch (kind) {
1100         case MAY_LINK:
1101                 av = FILE__LINK;
1102                 break;
1103         case MAY_UNLINK:
1104                 av = FILE__UNLINK;
1105                 break;
1106         case MAY_RMDIR:
1107                 av = DIR__RMDIR;
1108                 break;
1109         default:
1110                 printk(KERN_WARNING "may_link:  unrecognized kind %d\n", kind);
1111                 return 0;
1112         }
1113
1114         rc = avc_has_perm(tsec->sid, isec->sid, isec->sclass, av, &ad);
1115         return rc;
1116 }
1117
1118 static inline int may_rename(struct inode *old_dir,
1119                              struct dentry *old_dentry,
1120                              struct inode *new_dir,
1121                              struct dentry *new_dentry)
1122 {
1123         struct task_security_struct *tsec;
1124         struct inode_security_struct *old_dsec, *new_dsec, *old_isec, *new_isec;
1125         struct avc_audit_data ad;
1126         u32 av;
1127         int old_is_dir, new_is_dir;
1128         int rc;
1129
1130         tsec = current->security;
1131         old_dsec = old_dir->i_security;
1132         old_isec = old_dentry->d_inode->i_security;
1133         old_is_dir = S_ISDIR(old_dentry->d_inode->i_mode);
1134         new_dsec = new_dir->i_security;
1135
1136         AVC_AUDIT_DATA_INIT(&ad, FS);
1137
1138         ad.u.fs.dentry = old_dentry;
1139         rc = avc_has_perm(tsec->sid, old_dsec->sid, SECCLASS_DIR,
1140                           DIR__REMOVE_NAME | DIR__SEARCH, &ad);
1141         if (rc)
1142                 return rc;
1143         rc = avc_has_perm(tsec->sid, old_isec->sid,
1144                           old_isec->sclass, FILE__RENAME, &ad);
1145         if (rc)
1146                 return rc;
1147         if (old_is_dir && new_dir != old_dir) {
1148                 rc = avc_has_perm(tsec->sid, old_isec->sid,
1149                                   old_isec->sclass, DIR__REPARENT, &ad);
1150                 if (rc)
1151                         return rc;
1152         }
1153
1154         ad.u.fs.dentry = new_dentry;
1155         av = DIR__ADD_NAME | DIR__SEARCH;
1156         if (new_dentry->d_inode)
1157                 av |= DIR__REMOVE_NAME;
1158         rc = avc_has_perm(tsec->sid, new_dsec->sid, SECCLASS_DIR, av, &ad);
1159         if (rc)
1160                 return rc;
1161         if (new_dentry->d_inode) {
1162                 new_isec = new_dentry->d_inode->i_security;
1163                 new_is_dir = S_ISDIR(new_dentry->d_inode->i_mode);
1164                 rc = avc_has_perm(tsec->sid, new_isec->sid,
1165                                   new_isec->sclass,
1166                                   (new_is_dir ? DIR__RMDIR : FILE__UNLINK), &ad);
1167                 if (rc)
1168                         return rc;
1169         }
1170
1171         return 0;
1172 }
1173
1174 /* Check whether a task can perform a filesystem operation. */
1175 static int superblock_has_perm(struct task_struct *tsk,
1176                                struct super_block *sb,
1177                                u32 perms,
1178                                struct avc_audit_data *ad)
1179 {
1180         struct task_security_struct *tsec;
1181         struct superblock_security_struct *sbsec;
1182
1183         tsec = tsk->security;
1184         sbsec = sb->s_security;
1185         return avc_has_perm(tsec->sid, sbsec->sid, SECCLASS_FILESYSTEM,
1186                             perms, ad);
1187 }
1188
1189 /* Convert a Linux mode and permission mask to an access vector. */
1190 static inline u32 file_mask_to_av(int mode, int mask)
1191 {
1192         u32 av = 0;
1193
1194         if ((mode & S_IFMT) != S_IFDIR) {
1195                 if (mask & MAY_EXEC)
1196                         av |= FILE__EXECUTE;
1197                 if (mask & MAY_READ)
1198                         av |= FILE__READ;
1199
1200                 if (mask & MAY_APPEND)
1201                         av |= FILE__APPEND;
1202                 else if (mask & MAY_WRITE)
1203                         av |= FILE__WRITE;
1204
1205         } else {
1206                 if (mask & MAY_EXEC)
1207                         av |= DIR__SEARCH;
1208                 if (mask & MAY_WRITE)
1209                         av |= DIR__WRITE;
1210                 if (mask & MAY_READ)
1211                         av |= DIR__READ;
1212         }
1213
1214         return av;
1215 }
1216
1217 /* Convert a Linux file to an access vector. */
1218 static inline u32 file_to_av(struct file *file)
1219 {
1220         u32 av = 0;
1221
1222         if (file->f_mode & FMODE_READ)
1223                 av |= FILE__READ;
1224         if (file->f_mode & FMODE_WRITE) {
1225                 if (file->f_flags & O_APPEND)
1226                         av |= FILE__APPEND;
1227                 else
1228                         av |= FILE__WRITE;
1229         }
1230
1231         return av;
1232 }
1233
1234 /* Set an inode's SID to a specified value. */
1235 static int inode_security_set_sid(struct inode *inode, u32 sid)
1236 {
1237         struct inode_security_struct *isec = inode->i_security;
1238         struct superblock_security_struct *sbsec = inode->i_sb->s_security;
1239
1240         if (!sbsec->initialized) {
1241                 /* Defer initialization to selinux_complete_init. */
1242                 return 0;
1243         }
1244
1245         down(&isec->sem);
1246         isec->sclass = inode_mode_to_security_class(inode->i_mode);
1247         isec->sid = sid;
1248         isec->initialized = 1;
1249         up(&isec->sem);
1250         return 0;
1251 }
1252
1253 /* Hook functions begin here. */
1254
1255 static int selinux_ptrace(struct task_struct *parent, struct task_struct *child)
1256 {
1257         struct task_security_struct *psec = parent->security;
1258         struct task_security_struct *csec = child->security;
1259         int rc;
1260
1261         rc = secondary_ops->ptrace(parent,child);
1262         if (rc)
1263                 return rc;
1264
1265         rc = task_has_perm(parent, child, PROCESS__PTRACE);
1266         /* Save the SID of the tracing process for later use in apply_creds. */
1267         if (!rc)
1268                 csec->ptrace_sid = psec->sid;
1269         return rc;
1270 }
1271
1272 static int selinux_capget(struct task_struct *target, kernel_cap_t *effective,
1273                           kernel_cap_t *inheritable, kernel_cap_t *permitted)
1274 {
1275         int error;
1276
1277         error = task_has_perm(current, target, PROCESS__GETCAP);
1278         if (error)
1279                 return error;
1280
1281         return secondary_ops->capget(target, effective, inheritable, permitted);
1282 }
1283
1284 static int selinux_capset_check(struct task_struct *target, kernel_cap_t *effective,
1285                                 kernel_cap_t *inheritable, kernel_cap_t *permitted)
1286 {
1287         int error;
1288
1289         error = secondary_ops->capset_check(target, effective, inheritable, permitted);
1290         if (error)
1291                 return error;
1292
1293         return task_has_perm(current, target, PROCESS__SETCAP);
1294 }
1295
1296 static void selinux_capset_set(struct task_struct *target, kernel_cap_t *effective,
1297                                kernel_cap_t *inheritable, kernel_cap_t *permitted)
1298 {
1299         secondary_ops->capset_set(target, effective, inheritable, permitted);
1300 }
1301
1302 static int selinux_capable(struct task_struct *tsk, int cap)
1303 {
1304         int rc;
1305
1306         rc = secondary_ops->capable(tsk, cap);
1307         if (rc)
1308                 return rc;
1309
1310         return task_has_capability(tsk,cap);
1311 }
1312
1313 static int selinux_sysctl(ctl_table *table, int op)
1314 {
1315         int error = 0;
1316         u32 av;
1317         struct task_security_struct *tsec;
1318         u32 tsid;
1319         int rc;
1320
1321         rc = secondary_ops->sysctl(table, op);
1322         if (rc)
1323                 return rc;
1324
1325         tsec = current->security;
1326
1327         rc = selinux_proc_get_sid(table->de, (op == 001) ?
1328                                   SECCLASS_DIR : SECCLASS_FILE, &tsid);
1329         if (rc) {
1330                 /* Default to the well-defined sysctl SID. */
1331                 tsid = SECINITSID_SYSCTL;
1332         }
1333
1334         /* The op values are "defined" in sysctl.c, thereby creating
1335          * a bad coupling between this module and sysctl.c */
1336         if(op == 001) {
1337                 error = avc_has_perm(tsec->sid, tsid,
1338                                      SECCLASS_DIR, DIR__SEARCH, NULL);
1339         } else {
1340                 av = 0;
1341                 if (op & 004)
1342                         av |= FILE__READ;
1343                 if (op & 002)
1344                         av |= FILE__WRITE;
1345                 if (av)
1346                         error = avc_has_perm(tsec->sid, tsid,
1347                                              SECCLASS_FILE, av, NULL);
1348         }
1349
1350         return error;
1351 }
1352
1353 static int selinux_quotactl(int cmds, int type, int id, struct super_block *sb)
1354 {
1355         int rc = 0;
1356
1357         if (!sb)
1358                 return 0;
1359
1360         switch (cmds) {
1361                 case Q_SYNC:
1362                 case Q_QUOTAON:
1363                 case Q_QUOTAOFF:
1364                 case Q_SETINFO:
1365                 case Q_SETQUOTA:
1366                         rc = superblock_has_perm(current,
1367                                                  sb,
1368                                                  FILESYSTEM__QUOTAMOD, NULL);
1369                         break;
1370                 case Q_GETFMT:
1371                 case Q_GETINFO:
1372                 case Q_GETQUOTA:
1373                         rc = superblock_has_perm(current,
1374                                                  sb,
1375                                                  FILESYSTEM__QUOTAGET, NULL);
1376                         break;
1377                 default:
1378                         rc = 0;  /* let the kernel handle invalid cmds */
1379                         break;
1380         }
1381         return rc;
1382 }
1383
1384 static int selinux_quota_on(struct dentry *dentry)
1385 {
1386         return dentry_has_perm(current, NULL, dentry, FILE__QUOTAON);
1387 }
1388
1389 static int selinux_syslog(int type)
1390 {
1391         int rc;
1392
1393         rc = secondary_ops->syslog(type);
1394         if (rc)
1395                 return rc;
1396
1397         switch (type) {
1398                 case 3:         /* Read last kernel messages */
1399                 case 10:        /* Return size of the log buffer */
1400                         rc = task_has_system(current, SYSTEM__SYSLOG_READ);
1401                         break;
1402                 case 6:         /* Disable logging to console */
1403                 case 7:         /* Enable logging to console */
1404                 case 8:         /* Set level of messages printed to console */
1405                         rc = task_has_system(current, SYSTEM__SYSLOG_CONSOLE);
1406                         break;
1407                 case 0:         /* Close log */
1408                 case 1:         /* Open log */
1409                 case 2:         /* Read from log */
1410                 case 4:         /* Read/clear last kernel messages */
1411                 case 5:         /* Clear ring buffer */
1412                 default:
1413                         rc = task_has_system(current, SYSTEM__SYSLOG_MOD);
1414                         break;
1415         }
1416         return rc;
1417 }
1418
1419 /*
1420  * Check that a process has enough memory to allocate a new virtual
1421  * mapping. 0 means there is enough memory for the allocation to
1422  * succeed and -ENOMEM implies there is not.
1423  *
1424  * Note that secondary_ops->capable and task_has_perm_noaudit return 0
1425  * if the capability is granted, but __vm_enough_memory requires 1 if
1426  * the capability is granted.
1427  *
1428  * Do not audit the selinux permission check, as this is applied to all
1429  * processes that allocate mappings.
1430  */
1431 static int selinux_vm_enough_memory(long pages)
1432 {
1433         int rc, cap_sys_admin = 0;
1434         struct task_security_struct *tsec = current->security;
1435
1436         rc = secondary_ops->capable(current, CAP_SYS_ADMIN);
1437         if (rc == 0)
1438                 rc = avc_has_perm_noaudit(tsec->sid, tsec->sid,
1439                                         SECCLASS_CAPABILITY,
1440                                         CAP_TO_MASK(CAP_SYS_ADMIN),
1441                                         NULL);
1442
1443         if (rc == 0)
1444                 cap_sys_admin = 1;
1445
1446         return __vm_enough_memory(pages, cap_sys_admin);
1447 }
1448
1449 /* binprm security operations */
1450
1451 static int selinux_bprm_alloc_security(struct linux_binprm *bprm)
1452 {
1453         struct bprm_security_struct *bsec;
1454
1455         bsec = kzalloc(sizeof(struct bprm_security_struct), GFP_KERNEL);
1456         if (!bsec)
1457                 return -ENOMEM;
1458
1459         bsec->bprm = bprm;
1460         bsec->sid = SECINITSID_UNLABELED;
1461         bsec->set = 0;
1462
1463         bprm->security = bsec;
1464         return 0;
1465 }
1466
1467 static int selinux_bprm_set_security(struct linux_binprm *bprm)
1468 {
1469         struct task_security_struct *tsec;
1470         struct inode *inode = bprm->file->f_dentry->d_inode;
1471         struct inode_security_struct *isec;
1472         struct bprm_security_struct *bsec;
1473         u32 newsid;
1474         struct avc_audit_data ad;
1475         int rc;
1476
1477         rc = secondary_ops->bprm_set_security(bprm);
1478         if (rc)
1479                 return rc;
1480
1481         bsec = bprm->security;
1482
1483         if (bsec->set)
1484                 return 0;
1485
1486         tsec = current->security;
1487         isec = inode->i_security;
1488
1489         /* Default to the current task SID. */
1490         bsec->sid = tsec->sid;
1491
1492         /* Reset create SID on execve. */
1493         tsec->create_sid = 0;
1494
1495         if (tsec->exec_sid) {
1496                 newsid = tsec->exec_sid;
1497                 /* Reset exec SID on execve. */
1498                 tsec->exec_sid = 0;
1499         } else {
1500                 /* Check for a default transition on this program. */
1501                 rc = security_transition_sid(tsec->sid, isec->sid,
1502                                              SECCLASS_PROCESS, &newsid);
1503                 if (rc)
1504                         return rc;
1505         }
1506
1507         AVC_AUDIT_DATA_INIT(&ad, FS);
1508         ad.u.fs.mnt = bprm->file->f_vfsmnt;
1509         ad.u.fs.dentry = bprm->file->f_dentry;
1510
1511         if (bprm->file->f_vfsmnt->mnt_flags & MNT_NOSUID)
1512                 newsid = tsec->sid;
1513
1514         if (tsec->sid == newsid) {
1515                 rc = avc_has_perm(tsec->sid, isec->sid,
1516                                   SECCLASS_FILE, FILE__EXECUTE_NO_TRANS, &ad);
1517                 if (rc)
1518                         return rc;
1519         } else {
1520                 /* Check permissions for the transition. */
1521                 rc = avc_has_perm(tsec->sid, newsid,
1522                                   SECCLASS_PROCESS, PROCESS__TRANSITION, &ad);
1523                 if (rc)
1524                         return rc;
1525
1526                 rc = avc_has_perm(newsid, isec->sid,
1527                                   SECCLASS_FILE, FILE__ENTRYPOINT, &ad);
1528                 if (rc)
1529                         return rc;
1530
1531                 /* Clear any possibly unsafe personality bits on exec: */
1532                 current->personality &= ~PER_CLEAR_ON_SETID;
1533
1534                 /* Set the security field to the new SID. */
1535                 bsec->sid = newsid;
1536         }
1537
1538         bsec->set = 1;
1539         return 0;
1540 }
1541
1542 static int selinux_bprm_check_security (struct linux_binprm *bprm)
1543 {
1544         return secondary_ops->bprm_check_security(bprm);
1545 }
1546
1547
1548 static int selinux_bprm_secureexec (struct linux_binprm *bprm)
1549 {
1550         struct task_security_struct *tsec = current->security;
1551         int atsecure = 0;
1552
1553         if (tsec->osid != tsec->sid) {
1554                 /* Enable secure mode for SIDs transitions unless
1555                    the noatsecure permission is granted between
1556                    the two SIDs, i.e. ahp returns 0. */
1557                 atsecure = avc_has_perm(tsec->osid, tsec->sid,
1558                                          SECCLASS_PROCESS,
1559                                          PROCESS__NOATSECURE, NULL);
1560         }
1561
1562         return (atsecure || secondary_ops->bprm_secureexec(bprm));
1563 }
1564
1565 static void selinux_bprm_free_security(struct linux_binprm *bprm)
1566 {
1567         kfree(bprm->security);
1568         bprm->security = NULL;
1569 }
1570
1571 extern struct vfsmount *selinuxfs_mount;
1572 extern struct dentry *selinux_null;
1573
1574 /* Derived from fs/exec.c:flush_old_files. */
1575 static inline void flush_unauthorized_files(struct files_struct * files)
1576 {
1577         struct avc_audit_data ad;
1578         struct file *file, *devnull = NULL;
1579         struct tty_struct *tty = current->signal->tty;
1580         struct fdtable *fdt;
1581         long j = -1;
1582
1583         if (tty) {
1584                 file_list_lock();
1585                 file = list_entry(tty->tty_files.next, typeof(*file), f_u.fu_list);
1586                 if (file) {
1587                         /* Revalidate access to controlling tty.
1588                            Use inode_has_perm on the tty inode directly rather
1589                            than using file_has_perm, as this particular open
1590                            file may belong to another process and we are only
1591                            interested in the inode-based check here. */
1592                         struct inode *inode = file->f_dentry->d_inode;
1593                         if (inode_has_perm(current, inode,
1594                                            FILE__READ | FILE__WRITE, NULL)) {
1595                                 /* Reset controlling tty. */
1596                                 current->signal->tty = NULL;
1597                                 current->signal->tty_old_pgrp = 0;
1598                         }
1599                 }
1600                 file_list_unlock();
1601         }
1602
1603         /* Revalidate access to inherited open files. */
1604
1605         AVC_AUDIT_DATA_INIT(&ad,FS);
1606
1607         spin_lock(&files->file_lock);
1608         for (;;) {
1609                 unsigned long set, i;
1610                 int fd;
1611
1612                 j++;
1613                 i = j * __NFDBITS;
1614                 fdt = files_fdtable(files);
1615                 if (i >= fdt->max_fds || i >= fdt->max_fdset)
1616                         break;
1617                 set = fdt->open_fds->fds_bits[j];
1618                 if (!set)
1619                         continue;
1620                 spin_unlock(&files->file_lock);
1621                 for ( ; set ; i++,set >>= 1) {
1622                         if (set & 1) {
1623                                 file = fget(i);
1624                                 if (!file)
1625                                         continue;
1626                                 if (file_has_perm(current,
1627                                                   file,
1628                                                   file_to_av(file))) {
1629                                         sys_close(i);
1630                                         fd = get_unused_fd();
1631                                         if (fd != i) {
1632                                                 if (fd >= 0)
1633                                                         put_unused_fd(fd);
1634                                                 fput(file);
1635                                                 continue;
1636                                         }
1637                                         if (devnull) {
1638                                                 get_file(devnull);
1639                                         } else {
1640                                                 devnull = dentry_open(dget(selinux_null), mntget(selinuxfs_mount), O_RDWR);
1641                                                 if (!devnull) {
1642                                                         put_unused_fd(fd);
1643                                                         fput(file);
1644                                                         continue;
1645                                                 }
1646                                         }
1647                                         fd_install(fd, devnull);
1648                                 }
1649                                 fput(file);
1650                         }
1651                 }
1652                 spin_lock(&files->file_lock);
1653
1654         }
1655         spin_unlock(&files->file_lock);
1656 }
1657
1658 static void selinux_bprm_apply_creds(struct linux_binprm *bprm, int unsafe)
1659 {
1660         struct task_security_struct *tsec;
1661         struct bprm_security_struct *bsec;
1662         u32 sid;
1663         int rc;
1664
1665         secondary_ops->bprm_apply_creds(bprm, unsafe);
1666
1667         tsec = current->security;
1668
1669         bsec = bprm->security;
1670         sid = bsec->sid;
1671
1672         tsec->osid = tsec->sid;
1673         bsec->unsafe = 0;
1674         if (tsec->sid != sid) {
1675                 /* Check for shared state.  If not ok, leave SID
1676                    unchanged and kill. */
1677                 if (unsafe & LSM_UNSAFE_SHARE) {
1678                         rc = avc_has_perm(tsec->sid, sid, SECCLASS_PROCESS,
1679                                         PROCESS__SHARE, NULL);
1680                         if (rc) {
1681                                 bsec->unsafe = 1;
1682                                 return;
1683                         }
1684                 }
1685
1686                 /* Check for ptracing, and update the task SID if ok.
1687                    Otherwise, leave SID unchanged and kill. */
1688                 if (unsafe & (LSM_UNSAFE_PTRACE | LSM_UNSAFE_PTRACE_CAP)) {
1689                         rc = avc_has_perm(tsec->ptrace_sid, sid,
1690                                           SECCLASS_PROCESS, PROCESS__PTRACE,
1691                                           NULL);
1692                         if (rc) {
1693                                 bsec->unsafe = 1;
1694                                 return;
1695                         }
1696                 }
1697                 tsec->sid = sid;
1698         }
1699 }
1700
1701 /*
1702  * called after apply_creds without the task lock held
1703  */
1704 static void selinux_bprm_post_apply_creds(struct linux_binprm *bprm)
1705 {
1706         struct task_security_struct *tsec;
1707         struct rlimit *rlim, *initrlim;
1708         struct itimerval itimer;
1709         struct bprm_security_struct *bsec;
1710         int rc, i;
1711
1712         tsec = current->security;
1713         bsec = bprm->security;
1714
1715         if (bsec->unsafe) {
1716                 force_sig_specific(SIGKILL, current);
1717                 return;
1718         }
1719         if (tsec->osid == tsec->sid)
1720                 return;
1721
1722         /* Close files for which the new task SID is not authorized. */
1723         flush_unauthorized_files(current->files);
1724
1725         /* Check whether the new SID can inherit signal state
1726            from the old SID.  If not, clear itimers to avoid
1727            subsequent signal generation and flush and unblock
1728            signals. This must occur _after_ the task SID has
1729           been updated so that any kill done after the flush
1730           will be checked against the new SID. */
1731         rc = avc_has_perm(tsec->osid, tsec->sid, SECCLASS_PROCESS,
1732                           PROCESS__SIGINH, NULL);
1733         if (rc) {
1734                 memset(&itimer, 0, sizeof itimer);
1735                 for (i = 0; i < 3; i++)
1736                         do_setitimer(i, &itimer, NULL);
1737                 flush_signals(current);
1738                 spin_lock_irq(&current->sighand->siglock);
1739                 flush_signal_handlers(current, 1);
1740                 sigemptyset(&current->blocked);
1741                 recalc_sigpending();
1742                 spin_unlock_irq(&current->sighand->siglock);
1743         }
1744
1745         /* Check whether the new SID can inherit resource limits
1746            from the old SID.  If not, reset all soft limits to
1747            the lower of the current task's hard limit and the init
1748            task's soft limit.  Note that the setting of hard limits
1749            (even to lower them) can be controlled by the setrlimit
1750            check. The inclusion of the init task's soft limit into
1751            the computation is to avoid resetting soft limits higher
1752            than the default soft limit for cases where the default
1753            is lower than the hard limit, e.g. RLIMIT_CORE or
1754            RLIMIT_STACK.*/
1755         rc = avc_has_perm(tsec->osid, tsec->sid, SECCLASS_PROCESS,
1756                           PROCESS__RLIMITINH, NULL);
1757         if (rc) {
1758                 for (i = 0; i < RLIM_NLIMITS; i++) {
1759                         rlim = current->signal->rlim + i;
1760                         initrlim = init_task.signal->rlim+i;
1761                         rlim->rlim_cur = min(rlim->rlim_max,initrlim->rlim_cur);
1762                 }
1763                 if (current->signal->rlim[RLIMIT_CPU].rlim_cur != RLIM_INFINITY) {
1764                         /*
1765                          * This will cause RLIMIT_CPU calculations
1766                          * to be refigured.
1767                          */
1768                         current->it_prof_expires = jiffies_to_cputime(1);
1769                 }
1770         }
1771
1772         /* Wake up the parent if it is waiting so that it can
1773            recheck wait permission to the new task SID. */
1774         wake_up_interruptible(&current->parent->signal->wait_chldexit);
1775 }
1776
1777 /* superblock security operations */
1778
1779 static int selinux_sb_alloc_security(struct super_block *sb)
1780 {
1781         return superblock_alloc_security(sb);
1782 }
1783
1784 static void selinux_sb_free_security(struct super_block *sb)
1785 {
1786         superblock_free_security(sb);
1787 }
1788
1789 static inline int match_prefix(char *prefix, int plen, char *option, int olen)
1790 {
1791         if (plen > olen)
1792                 return 0;
1793
1794         return !memcmp(prefix, option, plen);
1795 }
1796
1797 static inline int selinux_option(char *option, int len)
1798 {
1799         return (match_prefix("context=", sizeof("context=")-1, option, len) ||
1800                 match_prefix("fscontext=", sizeof("fscontext=")-1, option, len) ||
1801                 match_prefix("defcontext=", sizeof("defcontext=")-1, option, len));
1802 }
1803
1804 static inline void take_option(char **to, char *from, int *first, int len)
1805 {
1806         if (!*first) {
1807                 **to = ',';
1808                 *to += 1;
1809         }
1810         else
1811                 *first = 0;
1812         memcpy(*to, from, len);
1813         *to += len;
1814 }
1815
1816 static int selinux_sb_copy_data(struct file_system_type *type, void *orig, void *copy)
1817 {
1818         int fnosec, fsec, rc = 0;
1819         char *in_save, *in_curr, *in_end;
1820         char *sec_curr, *nosec_save, *nosec;
1821
1822         in_curr = orig;
1823         sec_curr = copy;
1824
1825         /* Binary mount data: just copy */
1826         if (type->fs_flags & FS_BINARY_MOUNTDATA) {
1827                 copy_page(sec_curr, in_curr);
1828                 goto out;
1829         }
1830
1831         nosec = (char *)get_zeroed_page(GFP_KERNEL);
1832         if (!nosec) {
1833                 rc = -ENOMEM;
1834                 goto out;
1835         }
1836
1837         nosec_save = nosec;
1838         fnosec = fsec = 1;
1839         in_save = in_end = orig;
1840
1841         do {
1842                 if (*in_end == ',' || *in_end == '\0') {
1843                         int len = in_end - in_curr;
1844
1845                         if (selinux_option(in_curr, len))
1846                                 take_option(&sec_curr, in_curr, &fsec, len);
1847                         else
1848                                 take_option(&nosec, in_curr, &fnosec, len);
1849
1850                         in_curr = in_end + 1;
1851                 }
1852         } while (*in_end++);
1853
1854         strcpy(in_save, nosec_save);
1855         free_page((unsigned long)nosec_save);
1856 out:
1857         return rc;
1858 }
1859
1860 static int selinux_sb_kern_mount(struct super_block *sb, void *data)
1861 {
1862         struct avc_audit_data ad;
1863         int rc;
1864
1865         rc = superblock_doinit(sb, data);
1866         if (rc)
1867                 return rc;
1868
1869         AVC_AUDIT_DATA_INIT(&ad,FS);
1870         ad.u.fs.dentry = sb->s_root;
1871         return superblock_has_perm(current, sb, FILESYSTEM__MOUNT, &ad);
1872 }
1873
1874 static int selinux_sb_statfs(struct super_block *sb)
1875 {
1876         struct avc_audit_data ad;
1877
1878         AVC_AUDIT_DATA_INIT(&ad,FS);
1879         ad.u.fs.dentry = sb->s_root;
1880         return superblock_has_perm(current, sb, FILESYSTEM__GETATTR, &ad);
1881 }
1882
1883 static int selinux_mount(char * dev_name,
1884                          struct nameidata *nd,
1885                          char * type,
1886                          unsigned long flags,
1887                          void * data)
1888 {
1889         int rc;
1890
1891         rc = secondary_ops->sb_mount(dev_name, nd, type, flags, data);
1892         if (rc)
1893                 return rc;
1894
1895         if (flags & MS_REMOUNT)
1896                 return superblock_has_perm(current, nd->mnt->mnt_sb,
1897                                            FILESYSTEM__REMOUNT, NULL);
1898         else
1899                 return dentry_has_perm(current, nd->mnt, nd->dentry,
1900                                        FILE__MOUNTON);
1901 }
1902
1903 static int selinux_umount(struct vfsmount *mnt, int flags)
1904 {
1905         int rc;
1906
1907         rc = secondary_ops->sb_umount(mnt, flags);
1908         if (rc)
1909                 return rc;
1910
1911         return superblock_has_perm(current,mnt->mnt_sb,
1912                                    FILESYSTEM__UNMOUNT,NULL);
1913 }
1914
1915 /* inode security operations */
1916
1917 static int selinux_inode_alloc_security(struct inode *inode)
1918 {
1919         return inode_alloc_security(inode);
1920 }
1921
1922 static void selinux_inode_free_security(struct inode *inode)
1923 {
1924         inode_free_security(inode);
1925 }
1926
1927 static int selinux_inode_init_security(struct inode *inode, struct inode *dir,
1928                                        char **name, void **value,
1929                                        size_t *len)
1930 {
1931         struct task_security_struct *tsec;
1932         struct inode_security_struct *dsec;
1933         struct superblock_security_struct *sbsec;
1934         struct inode_security_struct *isec;
1935         u32 newsid, clen;
1936         int rc;
1937         char *namep = NULL, *context;
1938
1939         tsec = current->security;
1940         dsec = dir->i_security;
1941         sbsec = dir->i_sb->s_security;
1942         isec = inode->i_security;
1943
1944         if (tsec->create_sid && sbsec->behavior != SECURITY_FS_USE_MNTPOINT) {
1945                 newsid = tsec->create_sid;
1946         } else {
1947                 rc = security_transition_sid(tsec->sid, dsec->sid,
1948                                              inode_mode_to_security_class(inode->i_mode),
1949                                              &newsid);
1950                 if (rc) {
1951                         printk(KERN_WARNING "%s:  "
1952                                "security_transition_sid failed, rc=%d (dev=%s "
1953                                "ino=%ld)\n",
1954                                __FUNCTION__,
1955                                -rc, inode->i_sb->s_id, inode->i_ino);
1956                         return rc;
1957                 }
1958         }
1959
1960         inode_security_set_sid(inode, newsid);
1961
1962         if (sbsec->behavior == SECURITY_FS_USE_MNTPOINT)
1963                 return -EOPNOTSUPP;
1964
1965         if (name) {
1966                 namep = kstrdup(XATTR_SELINUX_SUFFIX, GFP_KERNEL);
1967                 if (!namep)
1968                         return -ENOMEM;
1969                 *name = namep;
1970         }
1971
1972         if (value && len) {
1973                 rc = security_sid_to_context(newsid, &context, &clen);
1974                 if (rc) {
1975                         kfree(namep);
1976                         return rc;
1977                 }
1978                 *value = context;
1979                 *len = clen;
1980         }
1981
1982         return 0;
1983 }
1984
1985 static int selinux_inode_create(struct inode *dir, struct dentry *dentry, int mask)
1986 {
1987         return may_create(dir, dentry, SECCLASS_FILE);
1988 }
1989
1990 static int selinux_inode_link(struct dentry *old_dentry, struct inode *dir, struct dentry *new_dentry)
1991 {
1992         int rc;
1993
1994         rc = secondary_ops->inode_link(old_dentry,dir,new_dentry);
1995         if (rc)
1996                 return rc;
1997         return may_link(dir, old_dentry, MAY_LINK);
1998 }
1999
2000 static int selinux_inode_unlink(struct inode *dir, struct dentry *dentry)
2001 {
2002         int rc;
2003
2004         rc = secondary_ops->inode_unlink(dir, dentry);
2005         if (rc)
2006                 return rc;
2007         return may_link(dir, dentry, MAY_UNLINK);
2008 }
2009
2010 static int selinux_inode_symlink(struct inode *dir, struct dentry *dentry, const char *name)
2011 {
2012         return may_create(dir, dentry, SECCLASS_LNK_FILE);
2013 }
2014
2015 static int selinux_inode_mkdir(struct inode *dir, struct dentry *dentry, int mask)
2016 {
2017         return may_create(dir, dentry, SECCLASS_DIR);
2018 }
2019
2020 static int selinux_inode_rmdir(struct inode *dir, struct dentry *dentry)
2021 {
2022         return may_link(dir, dentry, MAY_RMDIR);
2023 }
2024
2025 static int selinux_inode_mknod(struct inode *dir, struct dentry *dentry, int mode, dev_t dev)
2026 {
2027         int rc;
2028
2029         rc = secondary_ops->inode_mknod(dir, dentry, mode, dev);
2030         if (rc)
2031                 return rc;
2032
2033         return may_create(dir, dentry, inode_mode_to_security_class(mode));
2034 }
2035
2036 static int selinux_inode_rename(struct inode *old_inode, struct dentry *old_dentry,
2037                                 struct inode *new_inode, struct dentry *new_dentry)
2038 {
2039         return may_rename(old_inode, old_dentry, new_inode, new_dentry);
2040 }
2041
2042 static int selinux_inode_readlink(struct dentry *dentry)
2043 {
2044         return dentry_has_perm(current, NULL, dentry, FILE__READ);
2045 }
2046
2047 static int selinux_inode_follow_link(struct dentry *dentry, struct nameidata *nameidata)
2048 {
2049         int rc;
2050
2051         rc = secondary_ops->inode_follow_link(dentry,nameidata);
2052         if (rc)
2053                 return rc;
2054         return dentry_has_perm(current, NULL, dentry, FILE__READ);
2055 }
2056
2057 static int selinux_inode_permission(struct inode *inode, int mask,
2058                                     struct nameidata *nd)
2059 {
2060         int rc;
2061
2062         rc = secondary_ops->inode_permission(inode, mask, nd);
2063         if (rc)
2064                 return rc;
2065
2066         if (!mask) {
2067                 /* No permission to check.  Existence test. */
2068                 return 0;
2069         }
2070
2071         return inode_has_perm(current, inode,
2072                                file_mask_to_av(inode->i_mode, mask), NULL);
2073 }
2074
2075 static int selinux_inode_setattr(struct dentry *dentry, struct iattr *iattr)
2076 {
2077         int rc;
2078
2079         rc = secondary_ops->inode_setattr(dentry, iattr);
2080         if (rc)
2081                 return rc;
2082
2083         if (iattr->ia_valid & ATTR_FORCE)
2084                 return 0;
2085
2086         if (iattr->ia_valid & (ATTR_MODE | ATTR_UID | ATTR_GID |
2087                                ATTR_ATIME_SET | ATTR_MTIME_SET))
2088                 return dentry_has_perm(current, NULL, dentry, FILE__SETATTR);
2089
2090         return dentry_has_perm(current, NULL, dentry, FILE__WRITE);
2091 }
2092
2093 static int selinux_inode_getattr(struct vfsmount *mnt, struct dentry *dentry)
2094 {
2095         return dentry_has_perm(current, mnt, dentry, FILE__GETATTR);
2096 }
2097
2098 static int selinux_inode_setxattr(struct dentry *dentry, char *name, void *value, size_t size, int flags)
2099 {
2100         struct task_security_struct *tsec = current->security;
2101         struct inode *inode = dentry->d_inode;
2102         struct inode_security_struct *isec = inode->i_security;
2103         struct superblock_security_struct *sbsec;
2104         struct avc_audit_data ad;
2105         u32 newsid;
2106         int rc = 0;
2107
2108         if (strcmp(name, XATTR_NAME_SELINUX)) {
2109                 if (!strncmp(name, XATTR_SECURITY_PREFIX,
2110                              sizeof XATTR_SECURITY_PREFIX - 1) &&
2111                     !capable(CAP_SYS_ADMIN)) {
2112                         /* A different attribute in the security namespace.
2113                            Restrict to administrator. */
2114                         return -EPERM;
2115                 }
2116
2117                 /* Not an attribute we recognize, so just check the
2118                    ordinary setattr permission. */
2119                 return dentry_has_perm(current, NULL, dentry, FILE__SETATTR);
2120         }
2121
2122         sbsec = inode->i_sb->s_security;
2123         if (sbsec->behavior == SECURITY_FS_USE_MNTPOINT)
2124                 return -EOPNOTSUPP;
2125
2126         if ((current->fsuid != inode->i_uid) && !capable(CAP_FOWNER))
2127                 return -EPERM;
2128
2129         AVC_AUDIT_DATA_INIT(&ad,FS);
2130         ad.u.fs.dentry = dentry;
2131
2132         rc = avc_has_perm(tsec->sid, isec->sid, isec->sclass,
2133                           FILE__RELABELFROM, &ad);
2134         if (rc)
2135                 return rc;
2136
2137         rc = security_context_to_sid(value, size, &newsid);
2138         if (rc)
2139                 return rc;
2140
2141         rc = avc_has_perm(tsec->sid, newsid, isec->sclass,
2142                           FILE__RELABELTO, &ad);
2143         if (rc)
2144                 return rc;
2145
2146         rc = security_validate_transition(isec->sid, newsid, tsec->sid,
2147                                           isec->sclass);
2148         if (rc)
2149                 return rc;
2150
2151         return avc_has_perm(newsid,
2152                             sbsec->sid,
2153                             SECCLASS_FILESYSTEM,
2154                             FILESYSTEM__ASSOCIATE,
2155                             &ad);
2156 }
2157
2158 static void selinux_inode_post_setxattr(struct dentry *dentry, char *name,
2159                                         void *value, size_t size, int flags)
2160 {
2161         struct inode *inode = dentry->d_inode;
2162         struct inode_security_struct *isec = inode->i_security;
2163         u32 newsid;
2164         int rc;
2165
2166         if (strcmp(name, XATTR_NAME_SELINUX)) {
2167                 /* Not an attribute we recognize, so nothing to do. */
2168                 return;
2169         }
2170
2171         rc = security_context_to_sid(value, size, &newsid);
2172         if (rc) {
2173                 printk(KERN_WARNING "%s:  unable to obtain SID for context "
2174                        "%s, rc=%d\n", __FUNCTION__, (char*)value, -rc);
2175                 return;
2176         }
2177
2178         isec->sid = newsid;
2179         return;
2180 }
2181
2182 static int selinux_inode_getxattr (struct dentry *dentry, char *name)
2183 {
2184         return dentry_has_perm(current, NULL, dentry, FILE__GETATTR);
2185 }
2186
2187 static int selinux_inode_listxattr (struct dentry *dentry)
2188 {
2189         return dentry_has_perm(current, NULL, dentry, FILE__GETATTR);
2190 }
2191
2192 static int selinux_inode_removexattr (struct dentry *dentry, char *name)
2193 {
2194         if (strcmp(name, XATTR_NAME_SELINUX)) {
2195                 if (!strncmp(name, XATTR_SECURITY_PREFIX,
2196                              sizeof XATTR_SECURITY_PREFIX - 1) &&
2197                     !capable(CAP_SYS_ADMIN)) {
2198                         /* A different attribute in the security namespace.
2199                            Restrict to administrator. */
2200                         return -EPERM;
2201                 }
2202
2203                 /* Not an attribute we recognize, so just check the
2204                    ordinary setattr permission. Might want a separate
2205                    permission for removexattr. */
2206                 return dentry_has_perm(current, NULL, dentry, FILE__SETATTR);
2207         }
2208
2209         /* No one is allowed to remove a SELinux security label.
2210            You can change the label, but all data must be labeled. */
2211         return -EACCES;
2212 }
2213
2214 /*
2215  * Copy the in-core inode security context value to the user.  If the
2216  * getxattr() prior to this succeeded, check to see if we need to
2217  * canonicalize the value to be finally returned to the user.
2218  *
2219  * Permission check is handled by selinux_inode_getxattr hook.
2220  */
2221 static int selinux_inode_getsecurity(struct inode *inode, const char *name, void *buffer, size_t size, int err)
2222 {
2223         struct inode_security_struct *isec = inode->i_security;
2224         char *context;
2225         unsigned len;
2226         int rc;
2227
2228         if (strcmp(name, XATTR_SELINUX_SUFFIX)) {
2229                 rc = -EOPNOTSUPP;
2230                 goto out;
2231         }
2232
2233         rc = security_sid_to_context(isec->sid, &context, &len);
2234         if (rc)
2235                 goto out;
2236
2237         /* Probe for required buffer size */
2238         if (!buffer || !size) {
2239                 rc = len;
2240                 goto out_free;
2241         }
2242
2243         if (size < len) {
2244                 rc = -ERANGE;
2245                 goto out_free;
2246         }
2247
2248         if (err > 0) {
2249                 if ((len == err) && !(memcmp(context, buffer, len))) {
2250                         /* Don't need to canonicalize value */
2251                         rc = err;
2252                         goto out_free;
2253                 }
2254                 memset(buffer, 0, size);
2255         }
2256         memcpy(buffer, context, len);
2257         rc = len;
2258 out_free:
2259         kfree(context);
2260 out:
2261         return rc;
2262 }
2263
2264 static int selinux_inode_setsecurity(struct inode *inode, const char *name,
2265                                      const void *value, size_t size, int flags)
2266 {
2267         struct inode_security_struct *isec = inode->i_security;
2268         u32 newsid;
2269         int rc;
2270
2271         if (strcmp(name, XATTR_SELINUX_SUFFIX))
2272                 return -EOPNOTSUPP;
2273
2274         if (!value || !size)
2275                 return -EACCES;
2276
2277         rc = security_context_to_sid((void*)value, size, &newsid);
2278         if (rc)
2279                 return rc;
2280
2281         isec->sid = newsid;
2282         return 0;
2283 }
2284
2285 static int selinux_inode_listsecurity(struct inode *inode, char *buffer, size_t buffer_size)
2286 {
2287         const int len = sizeof(XATTR_NAME_SELINUX);
2288         if (buffer && len <= buffer_size)
2289                 memcpy(buffer, XATTR_NAME_SELINUX, len);
2290         return len;
2291 }
2292
2293 /* file security operations */
2294
2295 static int selinux_file_permission(struct file *file, int mask)
2296 {
2297         struct inode *inode = file->f_dentry->d_inode;
2298
2299         if (!mask) {
2300                 /* No permission to check.  Existence test. */
2301                 return 0;
2302         }
2303
2304         /* file_mask_to_av won't add FILE__WRITE if MAY_APPEND is set */
2305         if ((file->f_flags & O_APPEND) && (mask & MAY_WRITE))
2306                 mask |= MAY_APPEND;
2307
2308         return file_has_perm(current, file,
2309                              file_mask_to_av(inode->i_mode, mask));
2310 }
2311
2312 static int selinux_file_alloc_security(struct file *file)
2313 {
2314         return file_alloc_security(file);
2315 }
2316
2317 static void selinux_file_free_security(struct file *file)
2318 {
2319         file_free_security(file);
2320 }
2321
2322 static int selinux_file_ioctl(struct file *file, unsigned int cmd,
2323                               unsigned long arg)
2324 {
2325         int error = 0;
2326
2327         switch (cmd) {
2328                 case FIONREAD:
2329                 /* fall through */
2330                 case FIBMAP:
2331                 /* fall through */
2332                 case FIGETBSZ:
2333                 /* fall through */
2334                 case EXT2_IOC_GETFLAGS:
2335                 /* fall through */
2336                 case EXT2_IOC_GETVERSION:
2337                         error = file_has_perm(current, file, FILE__GETATTR);
2338                         break;
2339
2340                 case EXT2_IOC_SETFLAGS:
2341                 /* fall through */
2342                 case EXT2_IOC_SETVERSION:
2343                         error = file_has_perm(current, file, FILE__SETATTR);
2344                         break;
2345
2346                 /* sys_ioctl() checks */
2347                 case FIONBIO:
2348                 /* fall through */
2349                 case FIOASYNC:
2350                         error = file_has_perm(current, file, 0);
2351                         break;
2352
2353                 case KDSKBENT:
2354                 case KDSKBSENT:
2355                         error = task_has_capability(current,CAP_SYS_TTY_CONFIG);
2356                         break;
2357
2358                 /* default case assumes that the command will go
2359                  * to the file's ioctl() function.
2360                  */
2361                 default:
2362                         error = file_has_perm(current, file, FILE__IOCTL);
2363
2364         }
2365         return error;
2366 }
2367
2368 static int file_map_prot_check(struct file *file, unsigned long prot, int shared)
2369 {
2370 #ifndef CONFIG_PPC32
2371         if ((prot & PROT_EXEC) && (!file || (!shared && (prot & PROT_WRITE)))) {
2372                 /*
2373                  * We are making executable an anonymous mapping or a
2374                  * private file mapping that will also be writable.
2375                  * This has an additional check.
2376                  */
2377                 int rc = task_has_perm(current, current, PROCESS__EXECMEM);
2378                 if (rc)
2379                         return rc;
2380         }
2381 #endif
2382
2383         if (file) {
2384                 /* read access is always possible with a mapping */
2385                 u32 av = FILE__READ;
2386
2387                 /* write access only matters if the mapping is shared */
2388                 if (shared && (prot & PROT_WRITE))
2389                         av |= FILE__WRITE;
2390
2391                 if (prot & PROT_EXEC)
2392                         av |= FILE__EXECUTE;
2393
2394                 return file_has_perm(current, file, av);
2395         }
2396         return 0;
2397 }
2398
2399 static int selinux_file_mmap(struct file *file, unsigned long reqprot,
2400                              unsigned long prot, unsigned long flags)
2401 {
2402         int rc;
2403
2404         rc = secondary_ops->file_mmap(file, reqprot, prot, flags);
2405         if (rc)
2406                 return rc;
2407
2408         if (selinux_checkreqprot)
2409                 prot = reqprot;
2410
2411         return file_map_prot_check(file, prot,
2412                                    (flags & MAP_TYPE) == MAP_SHARED);
2413 }
2414
2415 static int selinux_file_mprotect(struct vm_area_struct *vma,
2416                                  unsigned long reqprot,
2417                                  unsigned long prot)
2418 {
2419         int rc;
2420
2421         rc = secondary_ops->file_mprotect(vma, reqprot, prot);
2422         if (rc)
2423                 return rc;
2424
2425         if (selinux_checkreqprot)
2426                 prot = reqprot;
2427
2428 #ifndef CONFIG_PPC32
2429         if ((prot & PROT_EXEC) && !(vma->vm_flags & VM_EXEC)) {
2430                 rc = 0;
2431                 if (vma->vm_start >= vma->vm_mm->start_brk &&
2432                     vma->vm_end <= vma->vm_mm->brk) {
2433                         rc = task_has_perm(current, current,
2434                                            PROCESS__EXECHEAP);
2435                 } else if (!vma->vm_file &&
2436                            vma->vm_start <= vma->vm_mm->start_stack &&
2437                            vma->vm_end >= vma->vm_mm->start_stack) {
2438                         rc = task_has_perm(current, current, PROCESS__EXECSTACK);
2439                 } else if (vma->vm_file && vma->anon_vma) {
2440                         /*
2441                          * We are making executable a file mapping that has
2442                          * had some COW done. Since pages might have been
2443                          * written, check ability to execute the possibly
2444                          * modified content.  This typically should only
2445                          * occur for text relocations.
2446                          */
2447                         rc = file_has_perm(current, vma->vm_file,
2448                                            FILE__EXECMOD);
2449                 }
2450                 if (rc)
2451                         return rc;
2452         }
2453 #endif
2454
2455         return file_map_prot_check(vma->vm_file, prot, vma->vm_flags&VM_SHARED);
2456 }
2457
2458 static int selinux_file_lock(struct file *file, unsigned int cmd)
2459 {
2460         return file_has_perm(current, file, FILE__LOCK);
2461 }
2462
2463 static int selinux_file_fcntl(struct file *file, unsigned int cmd,
2464                               unsigned long arg)
2465 {
2466         int err = 0;
2467
2468         switch (cmd) {
2469                 case F_SETFL:
2470                         if (!file->f_dentry || !file->f_dentry->d_inode) {
2471                                 err = -EINVAL;
2472                                 break;
2473                         }
2474
2475                         if ((file->f_flags & O_APPEND) && !(arg & O_APPEND)) {
2476                                 err = file_has_perm(current, file,FILE__WRITE);
2477                                 break;
2478                         }
2479                         /* fall through */
2480                 case F_SETOWN:
2481                 case F_SETSIG:
2482                 case F_GETFL:
2483                 case F_GETOWN:
2484                 case F_GETSIG:
2485                         /* Just check FD__USE permission */
2486                         err = file_has_perm(current, file, 0);
2487                         break;
2488                 case F_GETLK:
2489                 case F_SETLK:
2490                 case F_SETLKW:
2491 #if BITS_PER_LONG == 32
2492                 case F_GETLK64:
2493                 case F_SETLK64:
2494                 case F_SETLKW64:
2495 #endif
2496                         if (!file->f_dentry || !file->f_dentry->d_inode) {
2497                                 err = -EINVAL;
2498                                 break;
2499                         }
2500                         err = file_has_perm(current, file, FILE__LOCK);
2501                         break;
2502         }
2503
2504         return err;
2505 }
2506
2507 static int selinux_file_set_fowner(struct file *file)
2508 {
2509         struct task_security_struct *tsec;
2510         struct file_security_struct *fsec;
2511
2512         tsec = current->security;
2513         fsec = file->f_security;
2514         fsec->fown_sid = tsec->sid;
2515
2516         return 0;
2517 }
2518
2519 static int selinux_file_send_sigiotask(struct task_struct *tsk,
2520                                        struct fown_struct *fown, int signum)
2521 {
2522         struct file *file;
2523         u32 perm;
2524         struct task_security_struct *tsec;
2525         struct file_security_struct *fsec;
2526
2527         /* struct fown_struct is never outside the context of a struct file */
2528         file = (struct file *)((long)fown - offsetof(struct file,f_owner));
2529
2530         tsec = tsk->security;
2531         fsec = file->f_security;
2532
2533         if (!signum)
2534                 perm = signal_to_av(SIGIO); /* as per send_sigio_to_task */
2535         else
2536                 perm = signal_to_av(signum);
2537
2538         return avc_has_perm(fsec->fown_sid, tsec->sid,
2539                             SECCLASS_PROCESS, perm, NULL);
2540 }
2541
2542 static int selinux_file_receive(struct file *file)
2543 {
2544         return file_has_perm(current, file, file_to_av(file));
2545 }
2546
2547 /* task security operations */
2548
2549 static int selinux_task_create(unsigned long clone_flags)
2550 {
2551         int rc;
2552
2553         rc = secondary_ops->task_create(clone_flags);
2554         if (rc)
2555                 return rc;
2556
2557         return task_has_perm(current, current, PROCESS__FORK);
2558 }
2559
2560 static int selinux_task_alloc_security(struct task_struct *tsk)
2561 {
2562         struct task_security_struct *tsec1, *tsec2;
2563         int rc;
2564
2565         tsec1 = current->security;
2566
2567         rc = task_alloc_security(tsk);
2568         if (rc)
2569                 return rc;
2570         tsec2 = tsk->security;
2571
2572         tsec2->osid = tsec1->osid;
2573         tsec2->sid = tsec1->sid;
2574
2575         /* Retain the exec and create SIDs across fork */
2576         tsec2->exec_sid = tsec1->exec_sid;
2577         tsec2->create_sid = tsec1->create_sid;
2578
2579         /* Retain ptracer SID across fork, if any.
2580            This will be reset by the ptrace hook upon any
2581            subsequent ptrace_attach operations. */
2582         tsec2->ptrace_sid = tsec1->ptrace_sid;
2583
2584         return 0;
2585 }
2586
2587 static void selinux_task_free_security(struct task_struct *tsk)
2588 {
2589         task_free_security(tsk);
2590 }
2591
2592 static int selinux_task_setuid(uid_t id0, uid_t id1, uid_t id2, int flags)
2593 {
2594         /* Since setuid only affects the current process, and
2595            since the SELinux controls are not based on the Linux
2596            identity attributes, SELinux does not need to control
2597            this operation.  However, SELinux does control the use
2598            of the CAP_SETUID and CAP_SETGID capabilities using the
2599            capable hook. */
2600         return 0;
2601 }
2602
2603 static int selinux_task_post_setuid(uid_t id0, uid_t id1, uid_t id2, int flags)
2604 {
2605         return secondary_ops->task_post_setuid(id0,id1,id2,flags);
2606 }
2607
2608 static int selinux_task_setgid(gid_t id0, gid_t id1, gid_t id2, int flags)
2609 {
2610         /* See the comment for setuid above. */
2611         return 0;
2612 }
2613
2614 static int selinux_task_setpgid(struct task_struct *p, pid_t pgid)
2615 {
2616         return task_has_perm(current, p, PROCESS__SETPGID);
2617 }
2618
2619 static int selinux_task_getpgid(struct task_struct *p)
2620 {
2621         return task_has_perm(current, p, PROCESS__GETPGID);
2622 }
2623
2624 static int selinux_task_getsid(struct task_struct *p)
2625 {
2626         return task_has_perm(current, p, PROCESS__GETSESSION);
2627 }
2628
2629 static int selinux_task_setgroups(struct group_info *group_info)
2630 {
2631         /* See the comment for setuid above. */
2632         return 0;
2633 }
2634
2635 static int selinux_task_setnice(struct task_struct *p, int nice)
2636 {
2637         int rc;
2638
2639         rc = secondary_ops->task_setnice(p, nice);
2640         if (rc)
2641                 return rc;
2642
2643         return task_has_perm(current,p, PROCESS__SETSCHED);
2644 }
2645
2646 static int selinux_task_setrlimit(unsigned int resource, struct rlimit *new_rlim)
2647 {
2648         struct rlimit *old_rlim = current->signal->rlim + resource;
2649         int rc;
2650
2651         rc = secondary_ops->task_setrlimit(resource, new_rlim);
2652         if (rc)
2653                 return rc;
2654
2655         /* Control the ability to change the hard limit (whether
2656            lowering or raising it), so that the hard limit can
2657            later be used as a safe reset point for the soft limit
2658            upon context transitions. See selinux_bprm_apply_creds. */
2659         if (old_rlim->rlim_max != new_rlim->rlim_max)
2660                 return task_has_perm(current, current, PROCESS__SETRLIMIT);
2661
2662         return 0;
2663 }
2664
2665 static int selinux_task_setscheduler(struct task_struct *p, int policy, struct sched_param *lp)
2666 {
2667         return task_has_perm(current, p, PROCESS__SETSCHED);
2668 }
2669
2670 static int selinux_task_getscheduler(struct task_struct *p)
2671 {
2672         return task_has_perm(current, p, PROCESS__GETSCHED);
2673 }
2674
2675 static int selinux_task_kill(struct task_struct *p, struct siginfo *info, int sig)
2676 {
2677         u32 perm;
2678         int rc;
2679
2680         rc = secondary_ops->task_kill(p, info, sig);
2681         if (rc)
2682                 return rc;
2683
2684         if (info != SEND_SIG_NOINFO && (is_si_special(info) || SI_FROMKERNEL(info)))
2685                 return 0;
2686
2687         if (!sig)
2688                 perm = PROCESS__SIGNULL; /* null signal; existence test */
2689         else
2690                 perm = signal_to_av(sig);
2691
2692         return task_has_perm(current, p, perm);
2693 }
2694
2695 static int selinux_task_prctl(int option,
2696                               unsigned long arg2,
2697                               unsigned long arg3,
2698                               unsigned long arg4,
2699                               unsigned long arg5)
2700 {
2701         /* The current prctl operations do not appear to require
2702            any SELinux controls since they merely observe or modify
2703            the state of the current process. */
2704         return 0;
2705 }
2706
2707 static int selinux_task_wait(struct task_struct *p)
2708 {
2709         u32 perm;
2710
2711         perm = signal_to_av(p->exit_signal);
2712
2713         return task_has_perm(p, current, perm);
2714 }
2715
2716 static void selinux_task_reparent_to_init(struct task_struct *p)
2717 {
2718         struct task_security_struct *tsec;
2719
2720         secondary_ops->task_reparent_to_init(p);
2721
2722         tsec = p->security;
2723         tsec->osid = tsec->sid;
2724         tsec->sid = SECINITSID_KERNEL;
2725         return;
2726 }
2727
2728 static void selinux_task_to_inode(struct task_struct *p,
2729                                   struct inode *inode)
2730 {
2731         struct task_security_struct *tsec = p->security;
2732         struct inode_security_struct *isec = inode->i_security;
2733
2734         isec->sid = tsec->sid;
2735         isec->initialized = 1;
2736         return;
2737 }
2738
2739 #ifdef CONFIG_SECURITY_NETWORK
2740
2741 /* Returns error only if unable to parse addresses */
2742 static int selinux_parse_skb_ipv4(struct sk_buff *skb, struct avc_audit_data *ad)
2743 {
2744         int offset, ihlen, ret = -EINVAL;
2745         struct iphdr _iph, *ih;
2746
2747         offset = skb->nh.raw - skb->data;
2748         ih = skb_header_pointer(skb, offset, sizeof(_iph), &_iph);
2749         if (ih == NULL)
2750                 goto out;
2751
2752         ihlen = ih->ihl * 4;
2753         if (ihlen < sizeof(_iph))
2754                 goto out;
2755
2756         ad->u.net.v4info.saddr = ih->saddr;
2757         ad->u.net.v4info.daddr = ih->daddr;
2758         ret = 0;
2759
2760         switch (ih->protocol) {
2761         case IPPROTO_TCP: {
2762                 struct tcphdr _tcph, *th;
2763
2764                 if (ntohs(ih->frag_off) & IP_OFFSET)
2765                         break;
2766
2767                 offset += ihlen;
2768                 th = skb_header_pointer(skb, offset, sizeof(_tcph), &_tcph);
2769                 if (th == NULL)
2770                         break;
2771
2772                 ad->u.net.sport = th->source;
2773                 ad->u.net.dport = th->dest;
2774                 break;
2775         }
2776         
2777         case IPPROTO_UDP: {
2778                 struct udphdr _udph, *uh;
2779                 
2780                 if (ntohs(ih->frag_off) & IP_OFFSET)
2781                         break;
2782                         
2783                 offset += ihlen;
2784                 uh = skb_header_pointer(skb, offset, sizeof(_udph), &_udph);
2785                 if (uh == NULL)
2786                         break;  
2787
2788                 ad->u.net.sport = uh->source;
2789                 ad->u.net.dport = uh->dest;
2790                 break;
2791         }
2792
2793         default:
2794                 break;
2795         }
2796 out:
2797         return ret;
2798 }
2799
2800 #if defined(CONFIG_IPV6) || defined(CONFIG_IPV6_MODULE)
2801
2802 /* Returns error only if unable to parse addresses */
2803 static int selinux_parse_skb_ipv6(struct sk_buff *skb, struct avc_audit_data *ad)
2804 {
2805         u8 nexthdr;
2806         int ret = -EINVAL, offset;
2807         struct ipv6hdr _ipv6h, *ip6;
2808
2809         offset = skb->nh.raw - skb->data;
2810         ip6 = skb_header_pointer(skb, offset, sizeof(_ipv6h), &_ipv6h);
2811         if (ip6 == NULL)
2812                 goto out;
2813
2814         ipv6_addr_copy(&ad->u.net.v6info.saddr, &ip6->saddr);
2815         ipv6_addr_copy(&ad->u.net.v6info.daddr, &ip6->daddr);
2816         ret = 0;
2817
2818         nexthdr = ip6->nexthdr;
2819         offset += sizeof(_ipv6h);
2820         offset = ipv6_skip_exthdr(skb, offset, &nexthdr);
2821         if (offset < 0)
2822                 goto out;
2823
2824         switch (nexthdr) {
2825         case IPPROTO_TCP: {
2826                 struct tcphdr _tcph, *th;
2827
2828                 th = skb_header_pointer(skb, offset, sizeof(_tcph), &_tcph);
2829                 if (th == NULL)
2830                         break;
2831
2832                 ad->u.net.sport = th->source;
2833                 ad->u.net.dport = th->dest;
2834                 break;
2835         }
2836
2837         case IPPROTO_UDP: {
2838                 struct udphdr _udph, *uh;
2839
2840                 uh = skb_header_pointer(skb, offset, sizeof(_udph), &_udph);
2841                 if (uh == NULL)
2842                         break;
2843
2844                 ad->u.net.sport = uh->source;
2845                 ad->u.net.dport = uh->dest;
2846                 break;
2847         }
2848
2849         /* includes fragments */
2850         default:
2851                 break;
2852         }
2853 out:
2854         return ret;
2855 }
2856
2857 #endif /* IPV6 */
2858
2859 static int selinux_parse_skb(struct sk_buff *skb, struct avc_audit_data *ad,
2860                              char **addrp, int *len, int src)
2861 {
2862         int ret = 0;
2863
2864         switch (ad->u.net.family) {
2865         case PF_INET:
2866                 ret = selinux_parse_skb_ipv4(skb, ad);
2867                 if (ret || !addrp)
2868                         break;
2869                 *len = 4;
2870                 *addrp = (char *)(src ? &ad->u.net.v4info.saddr :
2871                                         &ad->u.net.v4info.daddr);
2872                 break;
2873
2874 #if defined(CONFIG_IPV6) || defined(CONFIG_IPV6_MODULE)
2875         case PF_INET6:
2876                 ret = selinux_parse_skb_ipv6(skb, ad);
2877                 if (ret || !addrp)
2878                         break;
2879                 *len = 16;
2880                 *addrp = (char *)(src ? &ad->u.net.v6info.saddr :
2881                                         &ad->u.net.v6info.daddr);
2882                 break;
2883 #endif  /* IPV6 */
2884         default:
2885                 break;
2886         }
2887
2888         return ret;
2889 }
2890
2891 /* socket security operations */
2892 static int socket_has_perm(struct task_struct *task, struct socket *sock,
2893                            u32 perms)
2894 {
2895         struct inode_security_struct *isec;
2896         struct task_security_struct *tsec;
2897         struct avc_audit_data ad;
2898         int err = 0;
2899
2900         tsec = task->security;
2901         isec = SOCK_INODE(sock)->i_security;
2902
2903         if (isec->sid == SECINITSID_KERNEL)
2904                 goto out;
2905
2906         AVC_AUDIT_DATA_INIT(&ad,NET);
2907         ad.u.net.sk = sock->sk;
2908         err = avc_has_perm(tsec->sid, isec->sid, isec->sclass, perms, &ad);
2909
2910 out:
2911         return err;
2912 }
2913
2914 static int selinux_socket_create(int family, int type,
2915                                  int protocol, int kern)
2916 {
2917         int err = 0;
2918         struct task_security_struct *tsec;
2919
2920         if (kern)
2921                 goto out;
2922
2923         tsec = current->security;
2924         err = avc_has_perm(tsec->sid, tsec->sid,
2925                            socket_type_to_security_class(family, type,
2926                            protocol), SOCKET__CREATE, NULL);
2927
2928 out:
2929         return err;
2930 }
2931
2932 static void selinux_socket_post_create(struct socket *sock, int family,
2933                                        int type, int protocol, int kern)
2934 {
2935         struct inode_security_struct *isec;
2936         struct task_security_struct *tsec;
2937
2938         isec = SOCK_INODE(sock)->i_security;
2939
2940         tsec = current->security;
2941         isec->sclass = socket_type_to_security_class(family, type, protocol);
2942         isec->sid = kern ? SECINITSID_KERNEL : tsec->sid;
2943         isec->initialized = 1;
2944
2945         return;
2946 }
2947
2948 /* Range of port numbers used to automatically bind.
2949    Need to determine whether we should perform a name_bind
2950    permission check between the socket and the port number. */
2951 #define ip_local_port_range_0 sysctl_local_port_range[0]
2952 #define ip_local_port_range_1 sysctl_local_port_range[1]
2953
2954 static int selinux_socket_bind(struct socket *sock, struct sockaddr *address, int addrlen)
2955 {
2956         u16 family;
2957         int err;
2958
2959         err = socket_has_perm(current, sock, SOCKET__BIND);
2960         if (err)
2961                 goto out;
2962
2963         /*
2964          * If PF_INET or PF_INET6, check name_bind permission for the port.
2965          * Multiple address binding for SCTP is not supported yet: we just
2966          * check the first address now.
2967          */
2968         family = sock->sk->sk_family;
2969         if (family == PF_INET || family == PF_INET6) {
2970                 char *addrp;
2971                 struct inode_security_struct *isec;
2972                 struct task_security_struct *tsec;
2973                 struct avc_audit_data ad;
2974                 struct sockaddr_in *addr4 = NULL;
2975                 struct sockaddr_in6 *addr6 = NULL;
2976                 unsigned short snum;
2977                 struct sock *sk = sock->sk;
2978                 u32 sid, node_perm, addrlen;
2979
2980                 tsec = current->security;
2981                 isec = SOCK_INODE(sock)->i_security;
2982
2983                 if (family == PF_INET) {
2984                         addr4 = (struct sockaddr_in *)address;
2985                         snum = ntohs(addr4->sin_port);
2986                         addrlen = sizeof(addr4->sin_addr.s_addr);
2987                         addrp = (char *)&addr4->sin_addr.s_addr;
2988                 } else {
2989                         addr6 = (struct sockaddr_in6 *)address;
2990                         snum = ntohs(addr6->sin6_port);
2991                         addrlen = sizeof(addr6->sin6_addr.s6_addr);
2992                         addrp = (char *)&addr6->sin6_addr.s6_addr;
2993                 }
2994
2995                 if (snum&&(snum < max(PROT_SOCK,ip_local_port_range_0) ||
2996                            snum > ip_local_port_range_1)) {
2997                         err = security_port_sid(sk->sk_family, sk->sk_type,
2998                                                 sk->sk_protocol, snum, &sid);
2999                         if (err)
3000                                 goto out;
3001                         AVC_AUDIT_DATA_INIT(&ad,NET);
3002                         ad.u.net.sport = htons(snum);
3003                         ad.u.net.family = family;
3004                         err = avc_has_perm(isec->sid, sid,
3005                                            isec->sclass,
3006                                            SOCKET__NAME_BIND, &ad);
3007                         if (err)
3008                                 goto out;
3009                 }
3010                 
3011                 switch(isec->sclass) {
3012                 case SECCLASS_TCP_SOCKET:
3013                         node_perm = TCP_SOCKET__NODE_BIND;
3014                         break;
3015                         
3016                 case SECCLASS_UDP_SOCKET:
3017                         node_perm = UDP_SOCKET__NODE_BIND;
3018                         break;
3019                         
3020                 default:
3021                         node_perm = RAWIP_SOCKET__NODE_BIND;
3022                         break;
3023                 }
3024                 
3025                 err = security_node_sid(family, addrp, addrlen, &sid);
3026                 if (err)
3027                         goto out;
3028                 
3029                 AVC_AUDIT_DATA_INIT(&ad,NET);
3030                 ad.u.net.sport = htons(snum);
3031                 ad.u.net.family = family;
3032
3033                 if (family == PF_INET)
3034                         ad.u.net.v4info.saddr = addr4->sin_addr.s_addr;
3035                 else
3036                         ipv6_addr_copy(&ad.u.net.v6info.saddr, &addr6->sin6_addr);
3037
3038                 err = avc_has_perm(isec->sid, sid,
3039                                    isec->sclass, node_perm, &ad);
3040                 if (err)
3041                         goto out;
3042         }
3043 out:
3044         return err;
3045 }
3046
3047 static int selinux_socket_connect(struct socket *sock, struct sockaddr *address, int addrlen)
3048 {
3049         struct inode_security_struct *isec;
3050         int err;
3051
3052         err = socket_has_perm(current, sock, SOCKET__CONNECT);
3053         if (err)
3054                 return err;
3055
3056         /*
3057          * If a TCP socket, check name_connect permission for the port.
3058          */
3059         isec = SOCK_INODE(sock)->i_security;
3060         if (isec->sclass == SECCLASS_TCP_SOCKET) {
3061                 struct sock *sk = sock->sk;
3062                 struct avc_audit_data ad;
3063                 struct sockaddr_in *addr4 = NULL;
3064                 struct sockaddr_in6 *addr6 = NULL;
3065                 unsigned short snum;
3066                 u32 sid;
3067
3068                 if (sk->sk_family == PF_INET) {
3069                         addr4 = (struct sockaddr_in *)address;
3070                         if (addrlen < sizeof(struct sockaddr_in))
3071                                 return -EINVAL;
3072                         snum = ntohs(addr4->sin_port);
3073                 } else {
3074                         addr6 = (struct sockaddr_in6 *)address;
3075                         if (addrlen < SIN6_LEN_RFC2133)
3076                                 return -EINVAL;
3077                         snum = ntohs(addr6->sin6_port);
3078                 }
3079
3080                 err = security_port_sid(sk->sk_family, sk->sk_type,
3081                                         sk->sk_protocol, snum, &sid);
3082                 if (err)
3083                         goto out;
3084
3085                 AVC_AUDIT_DATA_INIT(&ad,NET);
3086                 ad.u.net.dport = htons(snum);
3087                 ad.u.net.family = sk->sk_family;
3088                 err = avc_has_perm(isec->sid, sid, isec->sclass,
3089                                    TCP_SOCKET__NAME_CONNECT, &ad);
3090                 if (err)
3091                         goto out;
3092         }
3093
3094 out:
3095         return err;
3096 }
3097
3098 static int selinux_socket_listen(struct socket *sock, int backlog)
3099 {
3100         return socket_has_perm(current, sock, SOCKET__LISTEN);
3101 }
3102
3103 static int selinux_socket_accept(struct socket *sock, struct socket *newsock)
3104 {
3105         int err;
3106         struct inode_security_struct *isec;
3107         struct inode_security_struct *newisec;
3108
3109         err = socket_has_perm(current, sock, SOCKET__ACCEPT);
3110         if (err)
3111                 return err;
3112
3113         newisec = SOCK_INODE(newsock)->i_security;
3114
3115         isec = SOCK_INODE(sock)->i_security;
3116         newisec->sclass = isec->sclass;
3117         newisec->sid = isec->sid;
3118         newisec->initialized = 1;
3119
3120         return 0;
3121 }
3122
3123 static int selinux_socket_sendmsg(struct socket *sock, struct msghdr *msg,
3124                                   int size)
3125 {
3126         return socket_has_perm(current, sock, SOCKET__WRITE);
3127 }
3128
3129 static int selinux_socket_recvmsg(struct socket *sock, struct msghdr *msg,
3130                                   int size, int flags)
3131 {
3132         return socket_has_perm(current, sock, SOCKET__READ);
3133 }
3134
3135 static int selinux_socket_getsockname(struct socket *sock)
3136 {
3137         return socket_has_perm(current, sock, SOCKET__GETATTR);
3138 }
3139
3140 static int selinux_socket_getpeername(struct socket *sock)
3141 {
3142         return socket_has_perm(current, sock, SOCKET__GETATTR);
3143 }
3144
3145 static int selinux_socket_setsockopt(struct socket *sock,int level,int optname)
3146 {
3147         return socket_has_perm(current, sock, SOCKET__SETOPT);
3148 }
3149
3150 static int selinux_socket_getsockopt(struct socket *sock, int level,
3151                                      int optname)
3152 {
3153         return socket_has_perm(current, sock, SOCKET__GETOPT);
3154 }
3155
3156 static int selinux_socket_shutdown(struct socket *sock, int how)
3157 {
3158         return socket_has_perm(current, sock, SOCKET__SHUTDOWN);
3159 }
3160
3161 static int selinux_socket_unix_stream_connect(struct socket *sock,
3162                                               struct socket *other,
3163                                               struct sock *newsk)
3164 {
3165         struct sk_security_struct *ssec;
3166         struct inode_security_struct *isec;
3167         struct inode_security_struct *other_isec;
3168         struct avc_audit_data ad;
3169         int err;
3170
3171         err = secondary_ops->unix_stream_connect(sock, other, newsk);
3172         if (err)
3173                 return err;
3174
3175         isec = SOCK_INODE(sock)->i_security;
3176         other_isec = SOCK_INODE(other)->i_security;
3177
3178         AVC_AUDIT_DATA_INIT(&ad,NET);
3179         ad.u.net.sk = other->sk;
3180
3181         err = avc_has_perm(isec->sid, other_isec->sid,
3182                            isec->sclass,
3183                            UNIX_STREAM_SOCKET__CONNECTTO, &ad);
3184         if (err)
3185                 return err;
3186
3187         /* connecting socket */
3188         ssec = sock->sk->sk_security;
3189         ssec->peer_sid = other_isec->sid;
3190         
3191         /* server child socket */
3192         ssec = newsk->sk_security;
3193         ssec->peer_sid = isec->sid;
3194         
3195         return 0;
3196 }
3197
3198 static int selinux_socket_unix_may_send(struct socket *sock,
3199                                         struct socket *other)
3200 {
3201         struct inode_security_struct *isec;
3202         struct inode_security_struct *other_isec;
3203         struct avc_audit_data ad;
3204         int err;
3205
3206         isec = SOCK_INODE(sock)->i_security;
3207         other_isec = SOCK_INODE(other)->i_security;
3208
3209         AVC_AUDIT_DATA_INIT(&ad,NET);
3210         ad.u.net.sk = other->sk;
3211
3212         err = avc_has_perm(isec->sid, other_isec->sid,
3213                            isec->sclass, SOCKET__SENDTO, &ad);
3214         if (err)
3215                 return err;
3216
3217         return 0;
3218 }
3219
3220 static int selinux_socket_sock_rcv_skb(struct sock *sk, struct sk_buff *skb)
3221 {
3222         u16 family;
3223         char *addrp;
3224         int len, err = 0;
3225         u32 netif_perm, node_perm, node_sid, if_sid, recv_perm = 0;
3226         u32 sock_sid = 0;
3227         u16 sock_class = 0;
3228         struct socket *sock;
3229         struct net_device *dev;
3230         struct avc_audit_data ad;
3231
3232         family = sk->sk_family;
3233         if (family != PF_INET && family != PF_INET6)
3234                 goto out;
3235
3236         /* Handle mapped IPv4 packets arriving via IPv6 sockets */
3237         if (family == PF_INET6 && skb->protocol == ntohs(ETH_P_IP))
3238                 family = PF_INET;
3239
3240         read_lock_bh(&sk->sk_callback_lock);
3241         sock = sk->sk_socket;
3242         if (sock) {
3243                 struct inode *inode;
3244                 inode = SOCK_INODE(sock);
3245                 if (inode) {
3246                         struct inode_security_struct *isec;
3247                         isec = inode->i_security;
3248                         sock_sid = isec->sid;
3249                         sock_class = isec->sclass;
3250                 }
3251         }
3252         read_unlock_bh(&sk->sk_callback_lock);
3253         if (!sock_sid)
3254                 goto out;
3255
3256         dev = skb->dev;
3257         if (!dev)
3258                 goto out;
3259
3260         err = sel_netif_sids(dev, &if_sid, NULL);
3261         if (err)
3262                 goto out;
3263
3264         switch (sock_class) {
3265         case SECCLASS_UDP_SOCKET:
3266                 netif_perm = NETIF__UDP_RECV;
3267                 node_perm = NODE__UDP_RECV;
3268                 recv_perm = UDP_SOCKET__RECV_MSG;
3269                 break;
3270         
3271         case SECCLASS_TCP_SOCKET:
3272                 netif_perm = NETIF__TCP_RECV;
3273                 node_perm = NODE__TCP_RECV;
3274                 recv_perm = TCP_SOCKET__RECV_MSG;
3275                 break;
3276         
3277         default:
3278                 netif_perm = NETIF__RAWIP_RECV;
3279                 node_perm = NODE__RAWIP_RECV;
3280                 break;
3281         }
3282
3283         AVC_AUDIT_DATA_INIT(&ad, NET);
3284         ad.u.net.netif = dev->name;
3285         ad.u.net.family = family;
3286
3287         err = selinux_parse_skb(skb, &ad, &addrp, &len, 1);
3288         if (err)
3289                 goto out;
3290
3291         err = avc_has_perm(sock_sid, if_sid, SECCLASS_NETIF, netif_perm, &ad);
3292         if (err)
3293                 goto out;
3294         
3295         /* Fixme: this lookup is inefficient */
3296         err = security_node_sid(family, addrp, len, &node_sid);
3297         if (err)
3298                 goto out;
3299