selinux: selinux_setprocattr()->ptrace_parent() needs rcu_read_lock()
[platform/adaptation/renesas_rcar/renesas_kernel.git] / security / selinux / hooks.c
1 /*
2  *  NSA Security-Enhanced Linux (SELinux) security module
3  *
4  *  This file contains the SELinux hook function implementations.
5  *
6  *  Authors:  Stephen Smalley, <sds@epoch.ncsc.mil>
7  *            Chris Vance, <cvance@nai.com>
8  *            Wayne Salamon, <wsalamon@nai.com>
9  *            James Morris <jmorris@redhat.com>
10  *
11  *  Copyright (C) 2001,2002 Networks Associates Technology, Inc.
12  *  Copyright (C) 2003-2008 Red Hat, Inc., James Morris <jmorris@redhat.com>
13  *                                         Eric Paris <eparis@redhat.com>
14  *  Copyright (C) 2004-2005 Trusted Computer Solutions, Inc.
15  *                          <dgoeddel@trustedcs.com>
16  *  Copyright (C) 2006, 2007, 2009 Hewlett-Packard Development Company, L.P.
17  *      Paul Moore <paul@paul-moore.com>
18  *  Copyright (C) 2007 Hitachi Software Engineering Co., Ltd.
19  *                     Yuichi Nakamura <ynakam@hitachisoft.jp>
20  *
21  *      This program is free software; you can redistribute it and/or modify
22  *      it under the terms of the GNU General Public License version 2,
23  *      as published by the Free Software Foundation.
24  */
25
26 #include <linux/init.h>
27 #include <linux/kd.h>
28 #include <linux/kernel.h>
29 #include <linux/tracehook.h>
30 #include <linux/errno.h>
31 #include <linux/sched.h>
32 #include <linux/security.h>
33 #include <linux/xattr.h>
34 #include <linux/capability.h>
35 #include <linux/unistd.h>
36 #include <linux/mm.h>
37 #include <linux/mman.h>
38 #include <linux/slab.h>
39 #include <linux/pagemap.h>
40 #include <linux/proc_fs.h>
41 #include <linux/swap.h>
42 #include <linux/spinlock.h>
43 #include <linux/syscalls.h>
44 #include <linux/dcache.h>
45 #include <linux/file.h>
46 #include <linux/fdtable.h>
47 #include <linux/namei.h>
48 #include <linux/mount.h>
49 #include <linux/netfilter_ipv4.h>
50 #include <linux/netfilter_ipv6.h>
51 #include <linux/tty.h>
52 #include <net/icmp.h>
53 #include <net/ip.h>             /* for local_port_range[] */
54 #include <net/sock.h>
55 #include <net/tcp.h>            /* struct or_callable used in sock_rcv_skb */
56 #include <net/inet_connection_sock.h>
57 #include <net/net_namespace.h>
58 #include <net/netlabel.h>
59 #include <linux/uaccess.h>
60 #include <asm/ioctls.h>
61 #include <linux/atomic.h>
62 #include <linux/bitops.h>
63 #include <linux/interrupt.h>
64 #include <linux/netdevice.h>    /* for network interface checks */
65 #include <net/netlink.h>
66 #include <linux/tcp.h>
67 #include <linux/udp.h>
68 #include <linux/dccp.h>
69 #include <linux/quota.h>
70 #include <linux/un.h>           /* for Unix socket types */
71 #include <net/af_unix.h>        /* for Unix socket types */
72 #include <linux/parser.h>
73 #include <linux/nfs_mount.h>
74 #include <net/ipv6.h>
75 #include <linux/hugetlb.h>
76 #include <linux/personality.h>
77 #include <linux/audit.h>
78 #include <linux/string.h>
79 #include <linux/selinux.h>
80 #include <linux/mutex.h>
81 #include <linux/posix-timers.h>
82 #include <linux/syslog.h>
83 #include <linux/user_namespace.h>
84 #include <linux/export.h>
85 #include <linux/security.h>
86 #include <linux/msg.h>
87 #include <linux/shm.h>
88
89 #include "avc.h"
90 #include "objsec.h"
91 #include "netif.h"
92 #include "netnode.h"
93 #include "netport.h"
94 #include "xfrm.h"
95 #include "netlabel.h"
96 #include "audit.h"
97 #include "avc_ss.h"
98
99 extern struct security_operations *security_ops;
100
101 /* SECMARK reference count */
102 static atomic_t selinux_secmark_refcount = ATOMIC_INIT(0);
103
104 #ifdef CONFIG_SECURITY_SELINUX_DEVELOP
105 int selinux_enforcing;
106
107 static int __init enforcing_setup(char *str)
108 {
109         unsigned long enforcing;
110         if (!strict_strtoul(str, 0, &enforcing))
111                 selinux_enforcing = enforcing ? 1 : 0;
112         return 1;
113 }
114 __setup("enforcing=", enforcing_setup);
115 #endif
116
117 #ifdef CONFIG_SECURITY_SELINUX_BOOTPARAM
118 int selinux_enabled = CONFIG_SECURITY_SELINUX_BOOTPARAM_VALUE;
119
120 static int __init selinux_enabled_setup(char *str)
121 {
122         unsigned long enabled;
123         if (!strict_strtoul(str, 0, &enabled))
124                 selinux_enabled = enabled ? 1 : 0;
125         return 1;
126 }
127 __setup("selinux=", selinux_enabled_setup);
128 #else
129 int selinux_enabled = 1;
130 #endif
131
132 static struct kmem_cache *sel_inode_cache;
133
134 /**
135  * selinux_secmark_enabled - Check to see if SECMARK is currently enabled
136  *
137  * Description:
138  * This function checks the SECMARK reference counter to see if any SECMARK
139  * targets are currently configured, if the reference counter is greater than
140  * zero SECMARK is considered to be enabled.  Returns true (1) if SECMARK is
141  * enabled, false (0) if SECMARK is disabled.  If the always_check_network
142  * policy capability is enabled, SECMARK is always considered enabled.
143  *
144  */
145 static int selinux_secmark_enabled(void)
146 {
147         return (selinux_policycap_alwaysnetwork || atomic_read(&selinux_secmark_refcount));
148 }
149
150 /**
151  * selinux_peerlbl_enabled - Check to see if peer labeling is currently enabled
152  *
153  * Description:
154  * This function checks if NetLabel or labeled IPSEC is enabled.  Returns true
155  * (1) if any are enabled or false (0) if neither are enabled.  If the
156  * always_check_network policy capability is enabled, peer labeling
157  * is always considered enabled.
158  *
159  */
160 static int selinux_peerlbl_enabled(void)
161 {
162         return (selinux_policycap_alwaysnetwork || netlbl_enabled() || selinux_xfrm_enabled());
163 }
164
165 /*
166  * initialise the security for the init task
167  */
168 static void cred_init_security(void)
169 {
170         struct cred *cred = (struct cred *) current->real_cred;
171         struct task_security_struct *tsec;
172
173         tsec = kzalloc(sizeof(struct task_security_struct), GFP_KERNEL);
174         if (!tsec)
175                 panic("SELinux:  Failed to initialize initial task.\n");
176
177         tsec->osid = tsec->sid = SECINITSID_KERNEL;
178         cred->security = tsec;
179 }
180
181 /*
182  * get the security ID of a set of credentials
183  */
184 static inline u32 cred_sid(const struct cred *cred)
185 {
186         const struct task_security_struct *tsec;
187
188         tsec = cred->security;
189         return tsec->sid;
190 }
191
192 /*
193  * get the objective security ID of a task
194  */
195 static inline u32 task_sid(const struct task_struct *task)
196 {
197         u32 sid;
198
199         rcu_read_lock();
200         sid = cred_sid(__task_cred(task));
201         rcu_read_unlock();
202         return sid;
203 }
204
205 /*
206  * get the subjective security ID of the current task
207  */
208 static inline u32 current_sid(void)
209 {
210         const struct task_security_struct *tsec = current_security();
211
212         return tsec->sid;
213 }
214
215 /* Allocate and free functions for each kind of security blob. */
216
217 static int inode_alloc_security(struct inode *inode)
218 {
219         struct inode_security_struct *isec;
220         u32 sid = current_sid();
221
222         isec = kmem_cache_zalloc(sel_inode_cache, GFP_NOFS);
223         if (!isec)
224                 return -ENOMEM;
225
226         mutex_init(&isec->lock);
227         INIT_LIST_HEAD(&isec->list);
228         isec->inode = inode;
229         isec->sid = SECINITSID_UNLABELED;
230         isec->sclass = SECCLASS_FILE;
231         isec->task_sid = sid;
232         inode->i_security = isec;
233
234         return 0;
235 }
236
237 static void inode_free_security(struct inode *inode)
238 {
239         struct inode_security_struct *isec = inode->i_security;
240         struct superblock_security_struct *sbsec = inode->i_sb->s_security;
241
242         spin_lock(&sbsec->isec_lock);
243         if (!list_empty(&isec->list))
244                 list_del_init(&isec->list);
245         spin_unlock(&sbsec->isec_lock);
246
247         inode->i_security = NULL;
248         kmem_cache_free(sel_inode_cache, isec);
249 }
250
251 static int file_alloc_security(struct file *file)
252 {
253         struct file_security_struct *fsec;
254         u32 sid = current_sid();
255
256         fsec = kzalloc(sizeof(struct file_security_struct), GFP_KERNEL);
257         if (!fsec)
258                 return -ENOMEM;
259
260         fsec->sid = sid;
261         fsec->fown_sid = sid;
262         file->f_security = fsec;
263
264         return 0;
265 }
266
267 static void file_free_security(struct file *file)
268 {
269         struct file_security_struct *fsec = file->f_security;
270         file->f_security = NULL;
271         kfree(fsec);
272 }
273
274 static int superblock_alloc_security(struct super_block *sb)
275 {
276         struct superblock_security_struct *sbsec;
277
278         sbsec = kzalloc(sizeof(struct superblock_security_struct), GFP_KERNEL);
279         if (!sbsec)
280                 return -ENOMEM;
281
282         mutex_init(&sbsec->lock);
283         INIT_LIST_HEAD(&sbsec->isec_head);
284         spin_lock_init(&sbsec->isec_lock);
285         sbsec->sb = sb;
286         sbsec->sid = SECINITSID_UNLABELED;
287         sbsec->def_sid = SECINITSID_FILE;
288         sbsec->mntpoint_sid = SECINITSID_UNLABELED;
289         sb->s_security = sbsec;
290
291         return 0;
292 }
293
294 static void superblock_free_security(struct super_block *sb)
295 {
296         struct superblock_security_struct *sbsec = sb->s_security;
297         sb->s_security = NULL;
298         kfree(sbsec);
299 }
300
301 /* The file system's label must be initialized prior to use. */
302
303 static const char *labeling_behaviors[7] = {
304         "uses xattr",
305         "uses transition SIDs",
306         "uses task SIDs",
307         "uses genfs_contexts",
308         "not configured for labeling",
309         "uses mountpoint labeling",
310         "uses native labeling",
311 };
312
313 static int inode_doinit_with_dentry(struct inode *inode, struct dentry *opt_dentry);
314
315 static inline int inode_doinit(struct inode *inode)
316 {
317         return inode_doinit_with_dentry(inode, NULL);
318 }
319
320 enum {
321         Opt_error = -1,
322         Opt_context = 1,
323         Opt_fscontext = 2,
324         Opt_defcontext = 3,
325         Opt_rootcontext = 4,
326         Opt_labelsupport = 5,
327         Opt_nextmntopt = 6,
328 };
329
330 #define NUM_SEL_MNT_OPTS        (Opt_nextmntopt - 1)
331
332 static const match_table_t tokens = {
333         {Opt_context, CONTEXT_STR "%s"},
334         {Opt_fscontext, FSCONTEXT_STR "%s"},
335         {Opt_defcontext, DEFCONTEXT_STR "%s"},
336         {Opt_rootcontext, ROOTCONTEXT_STR "%s"},
337         {Opt_labelsupport, LABELSUPP_STR},
338         {Opt_error, NULL},
339 };
340
341 #define SEL_MOUNT_FAIL_MSG "SELinux:  duplicate or incompatible mount options\n"
342
343 static int may_context_mount_sb_relabel(u32 sid,
344                         struct superblock_security_struct *sbsec,
345                         const struct cred *cred)
346 {
347         const struct task_security_struct *tsec = cred->security;
348         int rc;
349
350         rc = avc_has_perm(tsec->sid, sbsec->sid, SECCLASS_FILESYSTEM,
351                           FILESYSTEM__RELABELFROM, NULL);
352         if (rc)
353                 return rc;
354
355         rc = avc_has_perm(tsec->sid, sid, SECCLASS_FILESYSTEM,
356                           FILESYSTEM__RELABELTO, NULL);
357         return rc;
358 }
359
360 static int may_context_mount_inode_relabel(u32 sid,
361                         struct superblock_security_struct *sbsec,
362                         const struct cred *cred)
363 {
364         const struct task_security_struct *tsec = cred->security;
365         int rc;
366         rc = avc_has_perm(tsec->sid, sbsec->sid, SECCLASS_FILESYSTEM,
367                           FILESYSTEM__RELABELFROM, NULL);
368         if (rc)
369                 return rc;
370
371         rc = avc_has_perm(sid, sbsec->sid, SECCLASS_FILESYSTEM,
372                           FILESYSTEM__ASSOCIATE, NULL);
373         return rc;
374 }
375
376 static int selinux_is_sblabel_mnt(struct super_block *sb)
377 {
378         struct superblock_security_struct *sbsec = sb->s_security;
379
380         if (sbsec->behavior == SECURITY_FS_USE_XATTR ||
381             sbsec->behavior == SECURITY_FS_USE_TRANS ||
382             sbsec->behavior == SECURITY_FS_USE_TASK)
383                 return 1;
384
385         /* Special handling for sysfs. Is genfs but also has setxattr handler*/
386         if (strncmp(sb->s_type->name, "sysfs", sizeof("sysfs")) == 0)
387                 return 1;
388
389         /*
390          * Special handling for rootfs. Is genfs but supports
391          * setting SELinux context on in-core inodes.
392          */
393         if (strncmp(sb->s_type->name, "rootfs", sizeof("rootfs")) == 0)
394                 return 1;
395
396         return 0;
397 }
398
399 static int sb_finish_set_opts(struct super_block *sb)
400 {
401         struct superblock_security_struct *sbsec = sb->s_security;
402         struct dentry *root = sb->s_root;
403         struct inode *root_inode = root->d_inode;
404         int rc = 0;
405
406         if (sbsec->behavior == SECURITY_FS_USE_XATTR) {
407                 /* Make sure that the xattr handler exists and that no
408                    error other than -ENODATA is returned by getxattr on
409                    the root directory.  -ENODATA is ok, as this may be
410                    the first boot of the SELinux kernel before we have
411                    assigned xattr values to the filesystem. */
412                 if (!root_inode->i_op->getxattr) {
413                         printk(KERN_WARNING "SELinux: (dev %s, type %s) has no "
414                                "xattr support\n", sb->s_id, sb->s_type->name);
415                         rc = -EOPNOTSUPP;
416                         goto out;
417                 }
418                 rc = root_inode->i_op->getxattr(root, XATTR_NAME_SELINUX, NULL, 0);
419                 if (rc < 0 && rc != -ENODATA) {
420                         if (rc == -EOPNOTSUPP)
421                                 printk(KERN_WARNING "SELinux: (dev %s, type "
422                                        "%s) has no security xattr handler\n",
423                                        sb->s_id, sb->s_type->name);
424                         else
425                                 printk(KERN_WARNING "SELinux: (dev %s, type "
426                                        "%s) getxattr errno %d\n", sb->s_id,
427                                        sb->s_type->name, -rc);
428                         goto out;
429                 }
430         }
431
432         if (sbsec->behavior > ARRAY_SIZE(labeling_behaviors))
433                 printk(KERN_ERR "SELinux: initialized (dev %s, type %s), unknown behavior\n",
434                        sb->s_id, sb->s_type->name);
435         else
436                 printk(KERN_DEBUG "SELinux: initialized (dev %s, type %s), %s\n",
437                        sb->s_id, sb->s_type->name,
438                        labeling_behaviors[sbsec->behavior-1]);
439
440         sbsec->flags |= SE_SBINITIALIZED;
441         if (selinux_is_sblabel_mnt(sb))
442                 sbsec->flags |= SBLABEL_MNT;
443
444         /* Initialize the root inode. */
445         rc = inode_doinit_with_dentry(root_inode, root);
446
447         /* Initialize any other inodes associated with the superblock, e.g.
448            inodes created prior to initial policy load or inodes created
449            during get_sb by a pseudo filesystem that directly
450            populates itself. */
451         spin_lock(&sbsec->isec_lock);
452 next_inode:
453         if (!list_empty(&sbsec->isec_head)) {
454                 struct inode_security_struct *isec =
455                                 list_entry(sbsec->isec_head.next,
456                                            struct inode_security_struct, list);
457                 struct inode *inode = isec->inode;
458                 spin_unlock(&sbsec->isec_lock);
459                 inode = igrab(inode);
460                 if (inode) {
461                         if (!IS_PRIVATE(inode))
462                                 inode_doinit(inode);
463                         iput(inode);
464                 }
465                 spin_lock(&sbsec->isec_lock);
466                 list_del_init(&isec->list);
467                 goto next_inode;
468         }
469         spin_unlock(&sbsec->isec_lock);
470 out:
471         return rc;
472 }
473
474 /*
475  * This function should allow an FS to ask what it's mount security
476  * options were so it can use those later for submounts, displaying
477  * mount options, or whatever.
478  */
479 static int selinux_get_mnt_opts(const struct super_block *sb,
480                                 struct security_mnt_opts *opts)
481 {
482         int rc = 0, i;
483         struct superblock_security_struct *sbsec = sb->s_security;
484         char *context = NULL;
485         u32 len;
486         char tmp;
487
488         security_init_mnt_opts(opts);
489
490         if (!(sbsec->flags & SE_SBINITIALIZED))
491                 return -EINVAL;
492
493         if (!ss_initialized)
494                 return -EINVAL;
495
496         /* make sure we always check enough bits to cover the mask */
497         BUILD_BUG_ON(SE_MNTMASK >= (1 << NUM_SEL_MNT_OPTS));
498
499         tmp = sbsec->flags & SE_MNTMASK;
500         /* count the number of mount options for this sb */
501         for (i = 0; i < NUM_SEL_MNT_OPTS; i++) {
502                 if (tmp & 0x01)
503                         opts->num_mnt_opts++;
504                 tmp >>= 1;
505         }
506         /* Check if the Label support flag is set */
507         if (sbsec->flags & SBLABEL_MNT)
508                 opts->num_mnt_opts++;
509
510         opts->mnt_opts = kcalloc(opts->num_mnt_opts, sizeof(char *), GFP_ATOMIC);
511         if (!opts->mnt_opts) {
512                 rc = -ENOMEM;
513                 goto out_free;
514         }
515
516         opts->mnt_opts_flags = kcalloc(opts->num_mnt_opts, sizeof(int), GFP_ATOMIC);
517         if (!opts->mnt_opts_flags) {
518                 rc = -ENOMEM;
519                 goto out_free;
520         }
521
522         i = 0;
523         if (sbsec->flags & FSCONTEXT_MNT) {
524                 rc = security_sid_to_context(sbsec->sid, &context, &len);
525                 if (rc)
526                         goto out_free;
527                 opts->mnt_opts[i] = context;
528                 opts->mnt_opts_flags[i++] = FSCONTEXT_MNT;
529         }
530         if (sbsec->flags & CONTEXT_MNT) {
531                 rc = security_sid_to_context(sbsec->mntpoint_sid, &context, &len);
532                 if (rc)
533                         goto out_free;
534                 opts->mnt_opts[i] = context;
535                 opts->mnt_opts_flags[i++] = CONTEXT_MNT;
536         }
537         if (sbsec->flags & DEFCONTEXT_MNT) {
538                 rc = security_sid_to_context(sbsec->def_sid, &context, &len);
539                 if (rc)
540                         goto out_free;
541                 opts->mnt_opts[i] = context;
542                 opts->mnt_opts_flags[i++] = DEFCONTEXT_MNT;
543         }
544         if (sbsec->flags & ROOTCONTEXT_MNT) {
545                 struct inode *root = sbsec->sb->s_root->d_inode;
546                 struct inode_security_struct *isec = root->i_security;
547
548                 rc = security_sid_to_context(isec->sid, &context, &len);
549                 if (rc)
550                         goto out_free;
551                 opts->mnt_opts[i] = context;
552                 opts->mnt_opts_flags[i++] = ROOTCONTEXT_MNT;
553         }
554         if (sbsec->flags & SBLABEL_MNT) {
555                 opts->mnt_opts[i] = NULL;
556                 opts->mnt_opts_flags[i++] = SBLABEL_MNT;
557         }
558
559         BUG_ON(i != opts->num_mnt_opts);
560
561         return 0;
562
563 out_free:
564         security_free_mnt_opts(opts);
565         return rc;
566 }
567
568 static int bad_option(struct superblock_security_struct *sbsec, char flag,
569                       u32 old_sid, u32 new_sid)
570 {
571         char mnt_flags = sbsec->flags & SE_MNTMASK;
572
573         /* check if the old mount command had the same options */
574         if (sbsec->flags & SE_SBINITIALIZED)
575                 if (!(sbsec->flags & flag) ||
576                     (old_sid != new_sid))
577                         return 1;
578
579         /* check if we were passed the same options twice,
580          * aka someone passed context=a,context=b
581          */
582         if (!(sbsec->flags & SE_SBINITIALIZED))
583                 if (mnt_flags & flag)
584                         return 1;
585         return 0;
586 }
587
588 /*
589  * Allow filesystems with binary mount data to explicitly set mount point
590  * labeling information.
591  */
592 static int selinux_set_mnt_opts(struct super_block *sb,
593                                 struct security_mnt_opts *opts,
594                                 unsigned long kern_flags,
595                                 unsigned long *set_kern_flags)
596 {
597         const struct cred *cred = current_cred();
598         int rc = 0, i;
599         struct superblock_security_struct *sbsec = sb->s_security;
600         const char *name = sb->s_type->name;
601         struct inode *inode = sbsec->sb->s_root->d_inode;
602         struct inode_security_struct *root_isec = inode->i_security;
603         u32 fscontext_sid = 0, context_sid = 0, rootcontext_sid = 0;
604         u32 defcontext_sid = 0;
605         char **mount_options = opts->mnt_opts;
606         int *flags = opts->mnt_opts_flags;
607         int num_opts = opts->num_mnt_opts;
608
609         mutex_lock(&sbsec->lock);
610
611         if (!ss_initialized) {
612                 if (!num_opts) {
613                         /* Defer initialization until selinux_complete_init,
614                            after the initial policy is loaded and the security
615                            server is ready to handle calls. */
616                         goto out;
617                 }
618                 rc = -EINVAL;
619                 printk(KERN_WARNING "SELinux: Unable to set superblock options "
620                         "before the security server is initialized\n");
621                 goto out;
622         }
623         if (kern_flags && !set_kern_flags) {
624                 /* Specifying internal flags without providing a place to
625                  * place the results is not allowed */
626                 rc = -EINVAL;
627                 goto out;
628         }
629
630         /*
631          * Binary mount data FS will come through this function twice.  Once
632          * from an explicit call and once from the generic calls from the vfs.
633          * Since the generic VFS calls will not contain any security mount data
634          * we need to skip the double mount verification.
635          *
636          * This does open a hole in which we will not notice if the first
637          * mount using this sb set explict options and a second mount using
638          * this sb does not set any security options.  (The first options
639          * will be used for both mounts)
640          */
641         if ((sbsec->flags & SE_SBINITIALIZED) && (sb->s_type->fs_flags & FS_BINARY_MOUNTDATA)
642             && (num_opts == 0))
643                 goto out;
644
645         /*
646          * parse the mount options, check if they are valid sids.
647          * also check if someone is trying to mount the same sb more
648          * than once with different security options.
649          */
650         for (i = 0; i < num_opts; i++) {
651                 u32 sid;
652
653                 if (flags[i] == SBLABEL_MNT)
654                         continue;
655                 rc = security_context_to_sid(mount_options[i],
656                                              strlen(mount_options[i]), &sid);
657                 if (rc) {
658                         printk(KERN_WARNING "SELinux: security_context_to_sid"
659                                "(%s) failed for (dev %s, type %s) errno=%d\n",
660                                mount_options[i], sb->s_id, name, rc);
661                         goto out;
662                 }
663                 switch (flags[i]) {
664                 case FSCONTEXT_MNT:
665                         fscontext_sid = sid;
666
667                         if (bad_option(sbsec, FSCONTEXT_MNT, sbsec->sid,
668                                         fscontext_sid))
669                                 goto out_double_mount;
670
671                         sbsec->flags |= FSCONTEXT_MNT;
672                         break;
673                 case CONTEXT_MNT:
674                         context_sid = sid;
675
676                         if (bad_option(sbsec, CONTEXT_MNT, sbsec->mntpoint_sid,
677                                         context_sid))
678                                 goto out_double_mount;
679
680                         sbsec->flags |= CONTEXT_MNT;
681                         break;
682                 case ROOTCONTEXT_MNT:
683                         rootcontext_sid = sid;
684
685                         if (bad_option(sbsec, ROOTCONTEXT_MNT, root_isec->sid,
686                                         rootcontext_sid))
687                                 goto out_double_mount;
688
689                         sbsec->flags |= ROOTCONTEXT_MNT;
690
691                         break;
692                 case DEFCONTEXT_MNT:
693                         defcontext_sid = sid;
694
695                         if (bad_option(sbsec, DEFCONTEXT_MNT, sbsec->def_sid,
696                                         defcontext_sid))
697                                 goto out_double_mount;
698
699                         sbsec->flags |= DEFCONTEXT_MNT;
700
701                         break;
702                 default:
703                         rc = -EINVAL;
704                         goto out;
705                 }
706         }
707
708         if (sbsec->flags & SE_SBINITIALIZED) {
709                 /* previously mounted with options, but not on this attempt? */
710                 if ((sbsec->flags & SE_MNTMASK) && !num_opts)
711                         goto out_double_mount;
712                 rc = 0;
713                 goto out;
714         }
715
716         if (strcmp(sb->s_type->name, "proc") == 0)
717                 sbsec->flags |= SE_SBPROC;
718
719         if (!sbsec->behavior) {
720                 /*
721                  * Determine the labeling behavior to use for this
722                  * filesystem type.
723                  */
724                 rc = security_fs_use(sb);
725                 if (rc) {
726                         printk(KERN_WARNING
727                                 "%s: security_fs_use(%s) returned %d\n",
728                                         __func__, sb->s_type->name, rc);
729                         goto out;
730                 }
731         }
732         /* sets the context of the superblock for the fs being mounted. */
733         if (fscontext_sid) {
734                 rc = may_context_mount_sb_relabel(fscontext_sid, sbsec, cred);
735                 if (rc)
736                         goto out;
737
738                 sbsec->sid = fscontext_sid;
739         }
740
741         /*
742          * Switch to using mount point labeling behavior.
743          * sets the label used on all file below the mountpoint, and will set
744          * the superblock context if not already set.
745          */
746         if (kern_flags & SECURITY_LSM_NATIVE_LABELS && !context_sid) {
747                 sbsec->behavior = SECURITY_FS_USE_NATIVE;
748                 *set_kern_flags |= SECURITY_LSM_NATIVE_LABELS;
749         }
750
751         if (context_sid) {
752                 if (!fscontext_sid) {
753                         rc = may_context_mount_sb_relabel(context_sid, sbsec,
754                                                           cred);
755                         if (rc)
756                                 goto out;
757                         sbsec->sid = context_sid;
758                 } else {
759                         rc = may_context_mount_inode_relabel(context_sid, sbsec,
760                                                              cred);
761                         if (rc)
762                                 goto out;
763                 }
764                 if (!rootcontext_sid)
765                         rootcontext_sid = context_sid;
766
767                 sbsec->mntpoint_sid = context_sid;
768                 sbsec->behavior = SECURITY_FS_USE_MNTPOINT;
769         }
770
771         if (rootcontext_sid) {
772                 rc = may_context_mount_inode_relabel(rootcontext_sid, sbsec,
773                                                      cred);
774                 if (rc)
775                         goto out;
776
777                 root_isec->sid = rootcontext_sid;
778                 root_isec->initialized = 1;
779         }
780
781         if (defcontext_sid) {
782                 if (sbsec->behavior != SECURITY_FS_USE_XATTR &&
783                         sbsec->behavior != SECURITY_FS_USE_NATIVE) {
784                         rc = -EINVAL;
785                         printk(KERN_WARNING "SELinux: defcontext option is "
786                                "invalid for this filesystem type\n");
787                         goto out;
788                 }
789
790                 if (defcontext_sid != sbsec->def_sid) {
791                         rc = may_context_mount_inode_relabel(defcontext_sid,
792                                                              sbsec, cred);
793                         if (rc)
794                                 goto out;
795                 }
796
797                 sbsec->def_sid = defcontext_sid;
798         }
799
800         rc = sb_finish_set_opts(sb);
801 out:
802         mutex_unlock(&sbsec->lock);
803         return rc;
804 out_double_mount:
805         rc = -EINVAL;
806         printk(KERN_WARNING "SELinux: mount invalid.  Same superblock, different "
807                "security settings for (dev %s, type %s)\n", sb->s_id, name);
808         goto out;
809 }
810
811 static int selinux_cmp_sb_context(const struct super_block *oldsb,
812                                     const struct super_block *newsb)
813 {
814         struct superblock_security_struct *old = oldsb->s_security;
815         struct superblock_security_struct *new = newsb->s_security;
816         char oldflags = old->flags & SE_MNTMASK;
817         char newflags = new->flags & SE_MNTMASK;
818
819         if (oldflags != newflags)
820                 goto mismatch;
821         if ((oldflags & FSCONTEXT_MNT) && old->sid != new->sid)
822                 goto mismatch;
823         if ((oldflags & CONTEXT_MNT) && old->mntpoint_sid != new->mntpoint_sid)
824                 goto mismatch;
825         if ((oldflags & DEFCONTEXT_MNT) && old->def_sid != new->def_sid)
826                 goto mismatch;
827         if (oldflags & ROOTCONTEXT_MNT) {
828                 struct inode_security_struct *oldroot = oldsb->s_root->d_inode->i_security;
829                 struct inode_security_struct *newroot = newsb->s_root->d_inode->i_security;
830                 if (oldroot->sid != newroot->sid)
831                         goto mismatch;
832         }
833         return 0;
834 mismatch:
835         printk(KERN_WARNING "SELinux: mount invalid.  Same superblock, "
836                             "different security settings for (dev %s, "
837                             "type %s)\n", newsb->s_id, newsb->s_type->name);
838         return -EBUSY;
839 }
840
841 static int selinux_sb_clone_mnt_opts(const struct super_block *oldsb,
842                                         struct super_block *newsb)
843 {
844         const struct superblock_security_struct *oldsbsec = oldsb->s_security;
845         struct superblock_security_struct *newsbsec = newsb->s_security;
846
847         int set_fscontext =     (oldsbsec->flags & FSCONTEXT_MNT);
848         int set_context =       (oldsbsec->flags & CONTEXT_MNT);
849         int set_rootcontext =   (oldsbsec->flags & ROOTCONTEXT_MNT);
850
851         /*
852          * if the parent was able to be mounted it clearly had no special lsm
853          * mount options.  thus we can safely deal with this superblock later
854          */
855         if (!ss_initialized)
856                 return 0;
857
858         /* how can we clone if the old one wasn't set up?? */
859         BUG_ON(!(oldsbsec->flags & SE_SBINITIALIZED));
860
861         /* if fs is reusing a sb, make sure that the contexts match */
862         if (newsbsec->flags & SE_SBINITIALIZED)
863                 return selinux_cmp_sb_context(oldsb, newsb);
864
865         mutex_lock(&newsbsec->lock);
866
867         newsbsec->flags = oldsbsec->flags;
868
869         newsbsec->sid = oldsbsec->sid;
870         newsbsec->def_sid = oldsbsec->def_sid;
871         newsbsec->behavior = oldsbsec->behavior;
872
873         if (set_context) {
874                 u32 sid = oldsbsec->mntpoint_sid;
875
876                 if (!set_fscontext)
877                         newsbsec->sid = sid;
878                 if (!set_rootcontext) {
879                         struct inode *newinode = newsb->s_root->d_inode;
880                         struct inode_security_struct *newisec = newinode->i_security;
881                         newisec->sid = sid;
882                 }
883                 newsbsec->mntpoint_sid = sid;
884         }
885         if (set_rootcontext) {
886                 const struct inode *oldinode = oldsb->s_root->d_inode;
887                 const struct inode_security_struct *oldisec = oldinode->i_security;
888                 struct inode *newinode = newsb->s_root->d_inode;
889                 struct inode_security_struct *newisec = newinode->i_security;
890
891                 newisec->sid = oldisec->sid;
892         }
893
894         sb_finish_set_opts(newsb);
895         mutex_unlock(&newsbsec->lock);
896         return 0;
897 }
898
899 static int selinux_parse_opts_str(char *options,
900                                   struct security_mnt_opts *opts)
901 {
902         char *p;
903         char *context = NULL, *defcontext = NULL;
904         char *fscontext = NULL, *rootcontext = NULL;
905         int rc, num_mnt_opts = 0;
906
907         opts->num_mnt_opts = 0;
908
909         /* Standard string-based options. */
910         while ((p = strsep(&options, "|")) != NULL) {
911                 int token;
912                 substring_t args[MAX_OPT_ARGS];
913
914                 if (!*p)
915                         continue;
916
917                 token = match_token(p, tokens, args);
918
919                 switch (token) {
920                 case Opt_context:
921                         if (context || defcontext) {
922                                 rc = -EINVAL;
923                                 printk(KERN_WARNING SEL_MOUNT_FAIL_MSG);
924                                 goto out_err;
925                         }
926                         context = match_strdup(&args[0]);
927                         if (!context) {
928                                 rc = -ENOMEM;
929                                 goto out_err;
930                         }
931                         break;
932
933                 case Opt_fscontext:
934                         if (fscontext) {
935                                 rc = -EINVAL;
936                                 printk(KERN_WARNING SEL_MOUNT_FAIL_MSG);
937                                 goto out_err;
938                         }
939                         fscontext = match_strdup(&args[0]);
940                         if (!fscontext) {
941                                 rc = -ENOMEM;
942                                 goto out_err;
943                         }
944                         break;
945
946                 case Opt_rootcontext:
947                         if (rootcontext) {
948                                 rc = -EINVAL;
949                                 printk(KERN_WARNING SEL_MOUNT_FAIL_MSG);
950                                 goto out_err;
951                         }
952                         rootcontext = match_strdup(&args[0]);
953                         if (!rootcontext) {
954                                 rc = -ENOMEM;
955                                 goto out_err;
956                         }
957                         break;
958
959                 case Opt_defcontext:
960                         if (context || defcontext) {
961                                 rc = -EINVAL;
962                                 printk(KERN_WARNING SEL_MOUNT_FAIL_MSG);
963                                 goto out_err;
964                         }
965                         defcontext = match_strdup(&args[0]);
966                         if (!defcontext) {
967                                 rc = -ENOMEM;
968                                 goto out_err;
969                         }
970                         break;
971                 case Opt_labelsupport:
972                         break;
973                 default:
974                         rc = -EINVAL;
975                         printk(KERN_WARNING "SELinux:  unknown mount option\n");
976                         goto out_err;
977
978                 }
979         }
980
981         rc = -ENOMEM;
982         opts->mnt_opts = kcalloc(NUM_SEL_MNT_OPTS, sizeof(char *), GFP_ATOMIC);
983         if (!opts->mnt_opts)
984                 goto out_err;
985
986         opts->mnt_opts_flags = kcalloc(NUM_SEL_MNT_OPTS, sizeof(int), GFP_ATOMIC);
987         if (!opts->mnt_opts_flags) {
988                 kfree(opts->mnt_opts);
989                 goto out_err;
990         }
991
992         if (fscontext) {
993                 opts->mnt_opts[num_mnt_opts] = fscontext;
994                 opts->mnt_opts_flags[num_mnt_opts++] = FSCONTEXT_MNT;
995         }
996         if (context) {
997                 opts->mnt_opts[num_mnt_opts] = context;
998                 opts->mnt_opts_flags[num_mnt_opts++] = CONTEXT_MNT;
999         }
1000         if (rootcontext) {
1001                 opts->mnt_opts[num_mnt_opts] = rootcontext;
1002                 opts->mnt_opts_flags[num_mnt_opts++] = ROOTCONTEXT_MNT;
1003         }
1004         if (defcontext) {
1005                 opts->mnt_opts[num_mnt_opts] = defcontext;
1006                 opts->mnt_opts_flags[num_mnt_opts++] = DEFCONTEXT_MNT;
1007         }
1008
1009         opts->num_mnt_opts = num_mnt_opts;
1010         return 0;
1011
1012 out_err:
1013         kfree(context);
1014         kfree(defcontext);
1015         kfree(fscontext);
1016         kfree(rootcontext);
1017         return rc;
1018 }
1019 /*
1020  * string mount options parsing and call set the sbsec
1021  */
1022 static int superblock_doinit(struct super_block *sb, void *data)
1023 {
1024         int rc = 0;
1025         char *options = data;
1026         struct security_mnt_opts opts;
1027
1028         security_init_mnt_opts(&opts);
1029
1030         if (!data)
1031                 goto out;
1032
1033         BUG_ON(sb->s_type->fs_flags & FS_BINARY_MOUNTDATA);
1034
1035         rc = selinux_parse_opts_str(options, &opts);
1036         if (rc)
1037                 goto out_err;
1038
1039 out:
1040         rc = selinux_set_mnt_opts(sb, &opts, 0, NULL);
1041
1042 out_err:
1043         security_free_mnt_opts(&opts);
1044         return rc;
1045 }
1046
1047 static void selinux_write_opts(struct seq_file *m,
1048                                struct security_mnt_opts *opts)
1049 {
1050         int i;
1051         char *prefix;
1052
1053         for (i = 0; i < opts->num_mnt_opts; i++) {
1054                 char *has_comma;
1055
1056                 if (opts->mnt_opts[i])
1057                         has_comma = strchr(opts->mnt_opts[i], ',');
1058                 else
1059                         has_comma = NULL;
1060
1061                 switch (opts->mnt_opts_flags[i]) {
1062                 case CONTEXT_MNT:
1063                         prefix = CONTEXT_STR;
1064                         break;
1065                 case FSCONTEXT_MNT:
1066                         prefix = FSCONTEXT_STR;
1067                         break;
1068                 case ROOTCONTEXT_MNT:
1069                         prefix = ROOTCONTEXT_STR;
1070                         break;
1071                 case DEFCONTEXT_MNT:
1072                         prefix = DEFCONTEXT_STR;
1073                         break;
1074                 case SBLABEL_MNT:
1075                         seq_putc(m, ',');
1076                         seq_puts(m, LABELSUPP_STR);
1077                         continue;
1078                 default:
1079                         BUG();
1080                         return;
1081                 };
1082                 /* we need a comma before each option */
1083                 seq_putc(m, ',');
1084                 seq_puts(m, prefix);
1085                 if (has_comma)
1086                         seq_putc(m, '\"');
1087                 seq_puts(m, opts->mnt_opts[i]);
1088                 if (has_comma)
1089                         seq_putc(m, '\"');
1090         }
1091 }
1092
1093 static int selinux_sb_show_options(struct seq_file *m, struct super_block *sb)
1094 {
1095         struct security_mnt_opts opts;
1096         int rc;
1097
1098         rc = selinux_get_mnt_opts(sb, &opts);
1099         if (rc) {
1100                 /* before policy load we may get EINVAL, don't show anything */
1101                 if (rc == -EINVAL)
1102                         rc = 0;
1103                 return rc;
1104         }
1105
1106         selinux_write_opts(m, &opts);
1107
1108         security_free_mnt_opts(&opts);
1109
1110         return rc;
1111 }
1112
1113 static inline u16 inode_mode_to_security_class(umode_t mode)
1114 {
1115         switch (mode & S_IFMT) {
1116         case S_IFSOCK:
1117                 return SECCLASS_SOCK_FILE;
1118         case S_IFLNK:
1119                 return SECCLASS_LNK_FILE;
1120         case S_IFREG:
1121                 return SECCLASS_FILE;
1122         case S_IFBLK:
1123                 return SECCLASS_BLK_FILE;
1124         case S_IFDIR:
1125                 return SECCLASS_DIR;
1126         case S_IFCHR:
1127                 return SECCLASS_CHR_FILE;
1128         case S_IFIFO:
1129                 return SECCLASS_FIFO_FILE;
1130
1131         }
1132
1133         return SECCLASS_FILE;
1134 }
1135
1136 static inline int default_protocol_stream(int protocol)
1137 {
1138         return (protocol == IPPROTO_IP || protocol == IPPROTO_TCP);
1139 }
1140
1141 static inline int default_protocol_dgram(int protocol)
1142 {
1143         return (protocol == IPPROTO_IP || protocol == IPPROTO_UDP);
1144 }
1145
1146 static inline u16 socket_type_to_security_class(int family, int type, int protocol)
1147 {
1148         switch (family) {
1149         case PF_UNIX:
1150                 switch (type) {
1151                 case SOCK_STREAM:
1152                 case SOCK_SEQPACKET:
1153                         return SECCLASS_UNIX_STREAM_SOCKET;
1154                 case SOCK_DGRAM:
1155                         return SECCLASS_UNIX_DGRAM_SOCKET;
1156                 }
1157                 break;
1158         case PF_INET:
1159         case PF_INET6:
1160                 switch (type) {
1161                 case SOCK_STREAM:
1162                         if (default_protocol_stream(protocol))
1163                                 return SECCLASS_TCP_SOCKET;
1164                         else
1165                                 return SECCLASS_RAWIP_SOCKET;
1166                 case SOCK_DGRAM:
1167                         if (default_protocol_dgram(protocol))
1168                                 return SECCLASS_UDP_SOCKET;
1169                         else
1170                                 return SECCLASS_RAWIP_SOCKET;
1171                 case SOCK_DCCP:
1172                         return SECCLASS_DCCP_SOCKET;
1173                 default:
1174                         return SECCLASS_RAWIP_SOCKET;
1175                 }
1176                 break;
1177         case PF_NETLINK:
1178                 switch (protocol) {
1179                 case NETLINK_ROUTE:
1180                         return SECCLASS_NETLINK_ROUTE_SOCKET;
1181                 case NETLINK_FIREWALL:
1182                         return SECCLASS_NETLINK_FIREWALL_SOCKET;
1183                 case NETLINK_SOCK_DIAG:
1184                         return SECCLASS_NETLINK_TCPDIAG_SOCKET;
1185                 case NETLINK_NFLOG:
1186                         return SECCLASS_NETLINK_NFLOG_SOCKET;
1187                 case NETLINK_XFRM:
1188                         return SECCLASS_NETLINK_XFRM_SOCKET;
1189                 case NETLINK_SELINUX:
1190                         return SECCLASS_NETLINK_SELINUX_SOCKET;
1191                 case NETLINK_AUDIT:
1192                         return SECCLASS_NETLINK_AUDIT_SOCKET;
1193                 case NETLINK_IP6_FW:
1194                         return SECCLASS_NETLINK_IP6FW_SOCKET;
1195                 case NETLINK_DNRTMSG:
1196                         return SECCLASS_NETLINK_DNRT_SOCKET;
1197                 case NETLINK_KOBJECT_UEVENT:
1198                         return SECCLASS_NETLINK_KOBJECT_UEVENT_SOCKET;
1199                 default:
1200                         return SECCLASS_NETLINK_SOCKET;
1201                 }
1202         case PF_PACKET:
1203                 return SECCLASS_PACKET_SOCKET;
1204         case PF_KEY:
1205                 return SECCLASS_KEY_SOCKET;
1206         case PF_APPLETALK:
1207                 return SECCLASS_APPLETALK_SOCKET;
1208         }
1209
1210         return SECCLASS_SOCKET;
1211 }
1212
1213 #ifdef CONFIG_PROC_FS
1214 static int selinux_proc_get_sid(struct dentry *dentry,
1215                                 u16 tclass,
1216                                 u32 *sid)
1217 {
1218         int rc;
1219         char *buffer, *path;
1220
1221         buffer = (char *)__get_free_page(GFP_KERNEL);
1222         if (!buffer)
1223                 return -ENOMEM;
1224
1225         path = dentry_path_raw(dentry, buffer, PAGE_SIZE);
1226         if (IS_ERR(path))
1227                 rc = PTR_ERR(path);
1228         else {
1229                 /* each process gets a /proc/PID/ entry. Strip off the
1230                  * PID part to get a valid selinux labeling.
1231                  * e.g. /proc/1/net/rpc/nfs -> /net/rpc/nfs */
1232                 while (path[1] >= '0' && path[1] <= '9') {
1233                         path[1] = '/';
1234                         path++;
1235                 }
1236                 rc = security_genfs_sid("proc", path, tclass, sid);
1237         }
1238         free_page((unsigned long)buffer);
1239         return rc;
1240 }
1241 #else
1242 static int selinux_proc_get_sid(struct dentry *dentry,
1243                                 u16 tclass,
1244                                 u32 *sid)
1245 {
1246         return -EINVAL;
1247 }
1248 #endif
1249
1250 /* The inode's security attributes must be initialized before first use. */
1251 static int inode_doinit_with_dentry(struct inode *inode, struct dentry *opt_dentry)
1252 {
1253         struct superblock_security_struct *sbsec = NULL;
1254         struct inode_security_struct *isec = inode->i_security;
1255         u32 sid;
1256         struct dentry *dentry;
1257 #define INITCONTEXTLEN 255
1258         char *context = NULL;
1259         unsigned len = 0;
1260         int rc = 0;
1261
1262         if (isec->initialized)
1263                 goto out;
1264
1265         mutex_lock(&isec->lock);
1266         if (isec->initialized)
1267                 goto out_unlock;
1268
1269         sbsec = inode->i_sb->s_security;
1270         if (!(sbsec->flags & SE_SBINITIALIZED)) {
1271                 /* Defer initialization until selinux_complete_init,
1272                    after the initial policy is loaded and the security
1273                    server is ready to handle calls. */
1274                 spin_lock(&sbsec->isec_lock);
1275                 if (list_empty(&isec->list))
1276                         list_add(&isec->list, &sbsec->isec_head);
1277                 spin_unlock(&sbsec->isec_lock);
1278                 goto out_unlock;
1279         }
1280
1281         switch (sbsec->behavior) {
1282         case SECURITY_FS_USE_NATIVE:
1283                 break;
1284         case SECURITY_FS_USE_XATTR:
1285                 if (!inode->i_op->getxattr) {
1286                         isec->sid = sbsec->def_sid;
1287                         break;
1288                 }
1289
1290                 /* Need a dentry, since the xattr API requires one.
1291                    Life would be simpler if we could just pass the inode. */
1292                 if (opt_dentry) {
1293                         /* Called from d_instantiate or d_splice_alias. */
1294                         dentry = dget(opt_dentry);
1295                 } else {
1296                         /* Called from selinux_complete_init, try to find a dentry. */
1297                         dentry = d_find_alias(inode);
1298                 }
1299                 if (!dentry) {
1300                         /*
1301                          * this is can be hit on boot when a file is accessed
1302                          * before the policy is loaded.  When we load policy we
1303                          * may find inodes that have no dentry on the
1304                          * sbsec->isec_head list.  No reason to complain as these
1305                          * will get fixed up the next time we go through
1306                          * inode_doinit with a dentry, before these inodes could
1307                          * be used again by userspace.
1308                          */
1309                         goto out_unlock;
1310                 }
1311
1312                 len = INITCONTEXTLEN;
1313                 context = kmalloc(len+1, GFP_NOFS);
1314                 if (!context) {
1315                         rc = -ENOMEM;
1316                         dput(dentry);
1317                         goto out_unlock;
1318                 }
1319                 context[len] = '\0';
1320                 rc = inode->i_op->getxattr(dentry, XATTR_NAME_SELINUX,
1321                                            context, len);
1322                 if (rc == -ERANGE) {
1323                         kfree(context);
1324
1325                         /* Need a larger buffer.  Query for the right size. */
1326                         rc = inode->i_op->getxattr(dentry, XATTR_NAME_SELINUX,
1327                                                    NULL, 0);
1328                         if (rc < 0) {
1329                                 dput(dentry);
1330                                 goto out_unlock;
1331                         }
1332                         len = rc;
1333                         context = kmalloc(len+1, GFP_NOFS);
1334                         if (!context) {
1335                                 rc = -ENOMEM;
1336                                 dput(dentry);
1337                                 goto out_unlock;
1338                         }
1339                         context[len] = '\0';
1340                         rc = inode->i_op->getxattr(dentry,
1341                                                    XATTR_NAME_SELINUX,
1342                                                    context, len);
1343                 }
1344                 dput(dentry);
1345                 if (rc < 0) {
1346                         if (rc != -ENODATA) {
1347                                 printk(KERN_WARNING "SELinux: %s:  getxattr returned "
1348                                        "%d for dev=%s ino=%ld\n", __func__,
1349                                        -rc, inode->i_sb->s_id, inode->i_ino);
1350                                 kfree(context);
1351                                 goto out_unlock;
1352                         }
1353                         /* Map ENODATA to the default file SID */
1354                         sid = sbsec->def_sid;
1355                         rc = 0;
1356                 } else {
1357                         rc = security_context_to_sid_default(context, rc, &sid,
1358                                                              sbsec->def_sid,
1359                                                              GFP_NOFS);
1360                         if (rc) {
1361                                 char *dev = inode->i_sb->s_id;
1362                                 unsigned long ino = inode->i_ino;
1363
1364                                 if (rc == -EINVAL) {
1365                                         if (printk_ratelimit())
1366                                                 printk(KERN_NOTICE "SELinux: inode=%lu on dev=%s was found to have an invalid "
1367                                                         "context=%s.  This indicates you may need to relabel the inode or the "
1368                                                         "filesystem in question.\n", ino, dev, context);
1369                                 } else {
1370                                         printk(KERN_WARNING "SELinux: %s:  context_to_sid(%s) "
1371                                                "returned %d for dev=%s ino=%ld\n",
1372                                                __func__, context, -rc, dev, ino);
1373                                 }
1374                                 kfree(context);
1375                                 /* Leave with the unlabeled SID */
1376                                 rc = 0;
1377                                 break;
1378                         }
1379                 }
1380                 kfree(context);
1381                 isec->sid = sid;
1382                 break;
1383         case SECURITY_FS_USE_TASK:
1384                 isec->sid = isec->task_sid;
1385                 break;
1386         case SECURITY_FS_USE_TRANS:
1387                 /* Default to the fs SID. */
1388                 isec->sid = sbsec->sid;
1389
1390                 /* Try to obtain a transition SID. */
1391                 isec->sclass = inode_mode_to_security_class(inode->i_mode);
1392                 rc = security_transition_sid(isec->task_sid, sbsec->sid,
1393                                              isec->sclass, NULL, &sid);
1394                 if (rc)
1395                         goto out_unlock;
1396                 isec->sid = sid;
1397                 break;
1398         case SECURITY_FS_USE_MNTPOINT:
1399                 isec->sid = sbsec->mntpoint_sid;
1400                 break;
1401         default:
1402                 /* Default to the fs superblock SID. */
1403                 isec->sid = sbsec->sid;
1404
1405                 if ((sbsec->flags & SE_SBPROC) && !S_ISLNK(inode->i_mode)) {
1406                         if (opt_dentry) {
1407                                 isec->sclass = inode_mode_to_security_class(inode->i_mode);
1408                                 rc = selinux_proc_get_sid(opt_dentry,
1409                                                           isec->sclass,
1410                                                           &sid);
1411                                 if (rc)
1412                                         goto out_unlock;
1413                                 isec->sid = sid;
1414                         }
1415                 }
1416                 break;
1417         }
1418
1419         isec->initialized = 1;
1420
1421 out_unlock:
1422         mutex_unlock(&isec->lock);
1423 out:
1424         if (isec->sclass == SECCLASS_FILE)
1425                 isec->sclass = inode_mode_to_security_class(inode->i_mode);
1426         return rc;
1427 }
1428
1429 /* Convert a Linux signal to an access vector. */
1430 static inline u32 signal_to_av(int sig)
1431 {
1432         u32 perm = 0;
1433
1434         switch (sig) {
1435         case SIGCHLD:
1436                 /* Commonly granted from child to parent. */
1437                 perm = PROCESS__SIGCHLD;
1438                 break;
1439         case SIGKILL:
1440                 /* Cannot be caught or ignored */
1441                 perm = PROCESS__SIGKILL;
1442                 break;
1443         case SIGSTOP:
1444                 /* Cannot be caught or ignored */
1445                 perm = PROCESS__SIGSTOP;
1446                 break;
1447         default:
1448                 /* All other signals. */
1449                 perm = PROCESS__SIGNAL;
1450                 break;
1451         }
1452
1453         return perm;
1454 }
1455
1456 /*
1457  * Check permission between a pair of credentials
1458  * fork check, ptrace check, etc.
1459  */
1460 static int cred_has_perm(const struct cred *actor,
1461                          const struct cred *target,
1462                          u32 perms)
1463 {
1464         u32 asid = cred_sid(actor), tsid = cred_sid(target);
1465
1466         return avc_has_perm(asid, tsid, SECCLASS_PROCESS, perms, NULL);
1467 }
1468
1469 /*
1470  * Check permission between a pair of tasks, e.g. signal checks,
1471  * fork check, ptrace check, etc.
1472  * tsk1 is the actor and tsk2 is the target
1473  * - this uses the default subjective creds of tsk1
1474  */
1475 static int task_has_perm(const struct task_struct *tsk1,
1476                          const struct task_struct *tsk2,
1477                          u32 perms)
1478 {
1479         const struct task_security_struct *__tsec1, *__tsec2;
1480         u32 sid1, sid2;
1481
1482         rcu_read_lock();
1483         __tsec1 = __task_cred(tsk1)->security;  sid1 = __tsec1->sid;
1484         __tsec2 = __task_cred(tsk2)->security;  sid2 = __tsec2->sid;
1485         rcu_read_unlock();
1486         return avc_has_perm(sid1, sid2, SECCLASS_PROCESS, perms, NULL);
1487 }
1488
1489 /*
1490  * Check permission between current and another task, e.g. signal checks,
1491  * fork check, ptrace check, etc.
1492  * current is the actor and tsk2 is the target
1493  * - this uses current's subjective creds
1494  */
1495 static int current_has_perm(const struct task_struct *tsk,
1496                             u32 perms)
1497 {
1498         u32 sid, tsid;
1499
1500         sid = current_sid();
1501         tsid = task_sid(tsk);
1502         return avc_has_perm(sid, tsid, SECCLASS_PROCESS, perms, NULL);
1503 }
1504
1505 #if CAP_LAST_CAP > 63
1506 #error Fix SELinux to handle capabilities > 63.
1507 #endif
1508
1509 /* Check whether a task is allowed to use a capability. */
1510 static int cred_has_capability(const struct cred *cred,
1511                                int cap, int audit)
1512 {
1513         struct common_audit_data ad;
1514         struct av_decision avd;
1515         u16 sclass;
1516         u32 sid = cred_sid(cred);
1517         u32 av = CAP_TO_MASK(cap);
1518         int rc;
1519
1520         ad.type = LSM_AUDIT_DATA_CAP;
1521         ad.u.cap = cap;
1522
1523         switch (CAP_TO_INDEX(cap)) {
1524         case 0:
1525                 sclass = SECCLASS_CAPABILITY;
1526                 break;
1527         case 1:
1528                 sclass = SECCLASS_CAPABILITY2;
1529                 break;
1530         default:
1531                 printk(KERN_ERR
1532                        "SELinux:  out of range capability %d\n", cap);
1533                 BUG();
1534                 return -EINVAL;
1535         }
1536
1537         rc = avc_has_perm_noaudit(sid, sid, sclass, av, 0, &avd);
1538         if (audit == SECURITY_CAP_AUDIT) {
1539                 int rc2 = avc_audit(sid, sid, sclass, av, &avd, rc, &ad);
1540                 if (rc2)
1541                         return rc2;
1542         }
1543         return rc;
1544 }
1545
1546 /* Check whether a task is allowed to use a system operation. */
1547 static int task_has_system(struct task_struct *tsk,
1548                            u32 perms)
1549 {
1550         u32 sid = task_sid(tsk);
1551
1552         return avc_has_perm(sid, SECINITSID_KERNEL,
1553                             SECCLASS_SYSTEM, perms, NULL);
1554 }
1555
1556 /* Check whether a task has a particular permission to an inode.
1557    The 'adp' parameter is optional and allows other audit
1558    data to be passed (e.g. the dentry). */
1559 static int inode_has_perm(const struct cred *cred,
1560                           struct inode *inode,
1561                           u32 perms,
1562                           struct common_audit_data *adp)
1563 {
1564         struct inode_security_struct *isec;
1565         u32 sid;
1566
1567         validate_creds(cred);
1568
1569         if (unlikely(IS_PRIVATE(inode)))
1570                 return 0;
1571
1572         sid = cred_sid(cred);
1573         isec = inode->i_security;
1574
1575         return avc_has_perm(sid, isec->sid, isec->sclass, perms, adp);
1576 }
1577
1578 /* Same as inode_has_perm, but pass explicit audit data containing
1579    the dentry to help the auditing code to more easily generate the
1580    pathname if needed. */
1581 static inline int dentry_has_perm(const struct cred *cred,
1582                                   struct dentry *dentry,
1583                                   u32 av)
1584 {
1585         struct inode *inode = dentry->d_inode;
1586         struct common_audit_data ad;
1587
1588         ad.type = LSM_AUDIT_DATA_DENTRY;
1589         ad.u.dentry = dentry;
1590         return inode_has_perm(cred, inode, av, &ad);
1591 }
1592
1593 /* Same as inode_has_perm, but pass explicit audit data containing
1594    the path to help the auditing code to more easily generate the
1595    pathname if needed. */
1596 static inline int path_has_perm(const struct cred *cred,
1597                                 struct path *path,
1598                                 u32 av)
1599 {
1600         struct inode *inode = path->dentry->d_inode;
1601         struct common_audit_data ad;
1602
1603         ad.type = LSM_AUDIT_DATA_PATH;
1604         ad.u.path = *path;
1605         return inode_has_perm(cred, inode, av, &ad);
1606 }
1607
1608 /* Same as path_has_perm, but uses the inode from the file struct. */
1609 static inline int file_path_has_perm(const struct cred *cred,
1610                                      struct file *file,
1611                                      u32 av)
1612 {
1613         struct common_audit_data ad;
1614
1615         ad.type = LSM_AUDIT_DATA_PATH;
1616         ad.u.path = file->f_path;
1617         return inode_has_perm(cred, file_inode(file), av, &ad);
1618 }
1619
1620 /* Check whether a task can use an open file descriptor to
1621    access an inode in a given way.  Check access to the
1622    descriptor itself, and then use dentry_has_perm to
1623    check a particular permission to the file.
1624    Access to the descriptor is implicitly granted if it
1625    has the same SID as the process.  If av is zero, then
1626    access to the file is not checked, e.g. for cases
1627    where only the descriptor is affected like seek. */
1628 static int file_has_perm(const struct cred *cred,
1629                          struct file *file,
1630                          u32 av)
1631 {
1632         struct file_security_struct *fsec = file->f_security;
1633         struct inode *inode = file_inode(file);
1634         struct common_audit_data ad;
1635         u32 sid = cred_sid(cred);
1636         int rc;
1637
1638         ad.type = LSM_AUDIT_DATA_PATH;
1639         ad.u.path = file->f_path;
1640
1641         if (sid != fsec->sid) {
1642                 rc = avc_has_perm(sid, fsec->sid,
1643                                   SECCLASS_FD,
1644                                   FD__USE,
1645                                   &ad);
1646                 if (rc)
1647                         goto out;
1648         }
1649
1650         /* av is zero if only checking access to the descriptor. */
1651         rc = 0;
1652         if (av)
1653                 rc = inode_has_perm(cred, inode, av, &ad);
1654
1655 out:
1656         return rc;
1657 }
1658
1659 /* Check whether a task can create a file. */
1660 static int may_create(struct inode *dir,
1661                       struct dentry *dentry,
1662                       u16 tclass)
1663 {
1664         const struct task_security_struct *tsec = current_security();
1665         struct inode_security_struct *dsec;
1666         struct superblock_security_struct *sbsec;
1667         u32 sid, newsid;
1668         struct common_audit_data ad;
1669         int rc;
1670
1671         dsec = dir->i_security;
1672         sbsec = dir->i_sb->s_security;
1673
1674         sid = tsec->sid;
1675         newsid = tsec->create_sid;
1676
1677         ad.type = LSM_AUDIT_DATA_DENTRY;
1678         ad.u.dentry = dentry;
1679
1680         rc = avc_has_perm(sid, dsec->sid, SECCLASS_DIR,
1681                           DIR__ADD_NAME | DIR__SEARCH,
1682                           &ad);
1683         if (rc)
1684                 return rc;
1685
1686         if (!newsid || !(sbsec->flags & SBLABEL_MNT)) {
1687                 rc = security_transition_sid(sid, dsec->sid, tclass,
1688                                              &dentry->d_name, &newsid);
1689                 if (rc)
1690                         return rc;
1691         }
1692
1693         rc = avc_has_perm(sid, newsid, tclass, FILE__CREATE, &ad);
1694         if (rc)
1695                 return rc;
1696
1697         return avc_has_perm(newsid, sbsec->sid,
1698                             SECCLASS_FILESYSTEM,
1699                             FILESYSTEM__ASSOCIATE, &ad);
1700 }
1701
1702 /* Check whether a task can create a key. */
1703 static int may_create_key(u32 ksid,
1704                           struct task_struct *ctx)
1705 {
1706         u32 sid = task_sid(ctx);
1707
1708         return avc_has_perm(sid, ksid, SECCLASS_KEY, KEY__CREATE, NULL);
1709 }
1710
1711 #define MAY_LINK        0
1712 #define MAY_UNLINK      1
1713 #define MAY_RMDIR       2
1714
1715 /* Check whether a task can link, unlink, or rmdir a file/directory. */
1716 static int may_link(struct inode *dir,
1717                     struct dentry *dentry,
1718                     int kind)
1719
1720 {
1721         struct inode_security_struct *dsec, *isec;
1722         struct common_audit_data ad;
1723         u32 sid = current_sid();
1724         u32 av;
1725         int rc;
1726
1727         dsec = dir->i_security;
1728         isec = dentry->d_inode->i_security;
1729
1730         ad.type = LSM_AUDIT_DATA_DENTRY;
1731         ad.u.dentry = dentry;
1732
1733         av = DIR__SEARCH;
1734         av |= (kind ? DIR__REMOVE_NAME : DIR__ADD_NAME);
1735         rc = avc_has_perm(sid, dsec->sid, SECCLASS_DIR, av, &ad);
1736         if (rc)
1737                 return rc;
1738
1739         switch (kind) {
1740         case MAY_LINK:
1741                 av = FILE__LINK;
1742                 break;
1743         case MAY_UNLINK:
1744                 av = FILE__UNLINK;
1745                 break;
1746         case MAY_RMDIR:
1747                 av = DIR__RMDIR;
1748                 break;
1749         default:
1750                 printk(KERN_WARNING "SELinux: %s:  unrecognized kind %d\n",
1751                         __func__, kind);
1752                 return 0;
1753         }
1754
1755         rc = avc_has_perm(sid, isec->sid, isec->sclass, av, &ad);
1756         return rc;
1757 }
1758
1759 static inline int may_rename(struct inode *old_dir,
1760                              struct dentry *old_dentry,
1761                              struct inode *new_dir,
1762                              struct dentry *new_dentry)
1763 {
1764         struct inode_security_struct *old_dsec, *new_dsec, *old_isec, *new_isec;
1765         struct common_audit_data ad;
1766         u32 sid = current_sid();
1767         u32 av;
1768         int old_is_dir, new_is_dir;
1769         int rc;
1770
1771         old_dsec = old_dir->i_security;
1772         old_isec = old_dentry->d_inode->i_security;
1773         old_is_dir = S_ISDIR(old_dentry->d_inode->i_mode);
1774         new_dsec = new_dir->i_security;
1775
1776         ad.type = LSM_AUDIT_DATA_DENTRY;
1777
1778         ad.u.dentry = old_dentry;
1779         rc = avc_has_perm(sid, old_dsec->sid, SECCLASS_DIR,
1780                           DIR__REMOVE_NAME | DIR__SEARCH, &ad);
1781         if (rc)
1782                 return rc;
1783         rc = avc_has_perm(sid, old_isec->sid,
1784                           old_isec->sclass, FILE__RENAME, &ad);
1785         if (rc)
1786                 return rc;
1787         if (old_is_dir && new_dir != old_dir) {
1788                 rc = avc_has_perm(sid, old_isec->sid,
1789                                   old_isec->sclass, DIR__REPARENT, &ad);
1790                 if (rc)
1791                         return rc;
1792         }
1793
1794         ad.u.dentry = new_dentry;
1795         av = DIR__ADD_NAME | DIR__SEARCH;
1796         if (new_dentry->d_inode)
1797                 av |= DIR__REMOVE_NAME;
1798         rc = avc_has_perm(sid, new_dsec->sid, SECCLASS_DIR, av, &ad);
1799         if (rc)
1800                 return rc;
1801         if (new_dentry->d_inode) {
1802                 new_isec = new_dentry->d_inode->i_security;
1803                 new_is_dir = S_ISDIR(new_dentry->d_inode->i_mode);
1804                 rc = avc_has_perm(sid, new_isec->sid,
1805                                   new_isec->sclass,
1806                                   (new_is_dir ? DIR__RMDIR : FILE__UNLINK), &ad);
1807                 if (rc)
1808                         return rc;
1809         }
1810
1811         return 0;
1812 }
1813
1814 /* Check whether a task can perform a filesystem operation. */
1815 static int superblock_has_perm(const struct cred *cred,
1816                                struct super_block *sb,
1817                                u32 perms,
1818                                struct common_audit_data *ad)
1819 {
1820         struct superblock_security_struct *sbsec;
1821         u32 sid = cred_sid(cred);
1822
1823         sbsec = sb->s_security;
1824         return avc_has_perm(sid, sbsec->sid, SECCLASS_FILESYSTEM, perms, ad);
1825 }
1826
1827 /* Convert a Linux mode and permission mask to an access vector. */
1828 static inline u32 file_mask_to_av(int mode, int mask)
1829 {
1830         u32 av = 0;
1831
1832         if (!S_ISDIR(mode)) {
1833                 if (mask & MAY_EXEC)
1834                         av |= FILE__EXECUTE;
1835                 if (mask & MAY_READ)
1836                         av |= FILE__READ;
1837
1838                 if (mask & MAY_APPEND)
1839                         av |= FILE__APPEND;
1840                 else if (mask & MAY_WRITE)
1841                         av |= FILE__WRITE;
1842
1843         } else {
1844                 if (mask & MAY_EXEC)
1845                         av |= DIR__SEARCH;
1846                 if (mask & MAY_WRITE)
1847                         av |= DIR__WRITE;
1848                 if (mask & MAY_READ)
1849                         av |= DIR__READ;
1850         }
1851
1852         return av;
1853 }
1854
1855 /* Convert a Linux file to an access vector. */
1856 static inline u32 file_to_av(struct file *file)
1857 {
1858         u32 av = 0;
1859
1860         if (file->f_mode & FMODE_READ)
1861                 av |= FILE__READ;
1862         if (file->f_mode & FMODE_WRITE) {
1863                 if (file->f_flags & O_APPEND)
1864                         av |= FILE__APPEND;
1865                 else
1866                         av |= FILE__WRITE;
1867         }
1868         if (!av) {
1869                 /*
1870                  * Special file opened with flags 3 for ioctl-only use.
1871                  */
1872                 av = FILE__IOCTL;
1873         }
1874
1875         return av;
1876 }
1877
1878 /*
1879  * Convert a file to an access vector and include the correct open
1880  * open permission.
1881  */
1882 static inline u32 open_file_to_av(struct file *file)
1883 {
1884         u32 av = file_to_av(file);
1885
1886         if (selinux_policycap_openperm)
1887                 av |= FILE__OPEN;
1888
1889         return av;
1890 }
1891
1892 /* Hook functions begin here. */
1893
1894 static int selinux_ptrace_access_check(struct task_struct *child,
1895                                      unsigned int mode)
1896 {
1897         int rc;
1898
1899         rc = cap_ptrace_access_check(child, mode);
1900         if (rc)
1901                 return rc;
1902
1903         if (mode & PTRACE_MODE_READ) {
1904                 u32 sid = current_sid();
1905                 u32 csid = task_sid(child);
1906                 return avc_has_perm(sid, csid, SECCLASS_FILE, FILE__READ, NULL);
1907         }
1908
1909         return current_has_perm(child, PROCESS__PTRACE);
1910 }
1911
1912 static int selinux_ptrace_traceme(struct task_struct *parent)
1913 {
1914         int rc;
1915
1916         rc = cap_ptrace_traceme(parent);
1917         if (rc)
1918                 return rc;
1919
1920         return task_has_perm(parent, current, PROCESS__PTRACE);
1921 }
1922
1923 static int selinux_capget(struct task_struct *target, kernel_cap_t *effective,
1924                           kernel_cap_t *inheritable, kernel_cap_t *permitted)
1925 {
1926         int error;
1927
1928         error = current_has_perm(target, PROCESS__GETCAP);
1929         if (error)
1930                 return error;
1931
1932         return cap_capget(target, effective, inheritable, permitted);
1933 }
1934
1935 static int selinux_capset(struct cred *new, const struct cred *old,
1936                           const kernel_cap_t *effective,
1937                           const kernel_cap_t *inheritable,
1938                           const kernel_cap_t *permitted)
1939 {
1940         int error;
1941
1942         error = cap_capset(new, old,
1943                                       effective, inheritable, permitted);
1944         if (error)
1945                 return error;
1946
1947         return cred_has_perm(old, new, PROCESS__SETCAP);
1948 }
1949
1950 /*
1951  * (This comment used to live with the selinux_task_setuid hook,
1952  * which was removed).
1953  *
1954  * Since setuid only affects the current process, and since the SELinux
1955  * controls are not based on the Linux identity attributes, SELinux does not
1956  * need to control this operation.  However, SELinux does control the use of
1957  * the CAP_SETUID and CAP_SETGID capabilities using the capable hook.
1958  */
1959
1960 static int selinux_capable(const struct cred *cred, struct user_namespace *ns,
1961                            int cap, int audit)
1962 {
1963         int rc;
1964
1965         rc = cap_capable(cred, ns, cap, audit);
1966         if (rc)
1967                 return rc;
1968
1969         return cred_has_capability(cred, cap, audit);
1970 }
1971
1972 static int selinux_quotactl(int cmds, int type, int id, struct super_block *sb)
1973 {
1974         const struct cred *cred = current_cred();
1975         int rc = 0;
1976
1977         if (!sb)
1978                 return 0;
1979
1980         switch (cmds) {
1981         case Q_SYNC:
1982         case Q_QUOTAON:
1983         case Q_QUOTAOFF:
1984         case Q_SETINFO:
1985         case Q_SETQUOTA:
1986                 rc = superblock_has_perm(cred, sb, FILESYSTEM__QUOTAMOD, NULL);
1987                 break;
1988         case Q_GETFMT:
1989         case Q_GETINFO:
1990         case Q_GETQUOTA:
1991                 rc = superblock_has_perm(cred, sb, FILESYSTEM__QUOTAGET, NULL);
1992                 break;
1993         default:
1994                 rc = 0;  /* let the kernel handle invalid cmds */
1995                 break;
1996         }
1997         return rc;
1998 }
1999
2000 static int selinux_quota_on(struct dentry *dentry)
2001 {
2002         const struct cred *cred = current_cred();
2003
2004         return dentry_has_perm(cred, dentry, FILE__QUOTAON);
2005 }
2006
2007 static int selinux_syslog(int type)
2008 {
2009         int rc;
2010
2011         switch (type) {
2012         case SYSLOG_ACTION_READ_ALL:    /* Read last kernel messages */
2013         case SYSLOG_ACTION_SIZE_BUFFER: /* Return size of the log buffer */
2014                 rc = task_has_system(current, SYSTEM__SYSLOG_READ);
2015                 break;
2016         case SYSLOG_ACTION_CONSOLE_OFF: /* Disable logging to console */
2017         case SYSLOG_ACTION_CONSOLE_ON:  /* Enable logging to console */
2018         /* Set level of messages printed to console */
2019         case SYSLOG_ACTION_CONSOLE_LEVEL:
2020                 rc = task_has_system(current, SYSTEM__SYSLOG_CONSOLE);
2021                 break;
2022         case SYSLOG_ACTION_CLOSE:       /* Close log */
2023         case SYSLOG_ACTION_OPEN:        /* Open log */
2024         case SYSLOG_ACTION_READ:        /* Read from log */
2025         case SYSLOG_ACTION_READ_CLEAR:  /* Read/clear last kernel messages */
2026         case SYSLOG_ACTION_CLEAR:       /* Clear ring buffer */
2027         default:
2028                 rc = task_has_system(current, SYSTEM__SYSLOG_MOD);
2029                 break;
2030         }
2031         return rc;
2032 }
2033
2034 /*
2035  * Check that a process has enough memory to allocate a new virtual
2036  * mapping. 0 means there is enough memory for the allocation to
2037  * succeed and -ENOMEM implies there is not.
2038  *
2039  * Do not audit the selinux permission check, as this is applied to all
2040  * processes that allocate mappings.
2041  */
2042 static int selinux_vm_enough_memory(struct mm_struct *mm, long pages)
2043 {
2044         int rc, cap_sys_admin = 0;
2045
2046         rc = selinux_capable(current_cred(), &init_user_ns, CAP_SYS_ADMIN,
2047                              SECURITY_CAP_NOAUDIT);
2048         if (rc == 0)
2049                 cap_sys_admin = 1;
2050
2051         return __vm_enough_memory(mm, pages, cap_sys_admin);
2052 }
2053
2054 /* binprm security operations */
2055
2056 static int selinux_bprm_set_creds(struct linux_binprm *bprm)
2057 {
2058         const struct task_security_struct *old_tsec;
2059         struct task_security_struct *new_tsec;
2060         struct inode_security_struct *isec;
2061         struct common_audit_data ad;
2062         struct inode *inode = file_inode(bprm->file);
2063         int rc;
2064
2065         rc = cap_bprm_set_creds(bprm);
2066         if (rc)
2067                 return rc;
2068
2069         /* SELinux context only depends on initial program or script and not
2070          * the script interpreter */
2071         if (bprm->cred_prepared)
2072                 return 0;
2073
2074         old_tsec = current_security();
2075         new_tsec = bprm->cred->security;
2076         isec = inode->i_security;
2077
2078         /* Default to the current task SID. */
2079         new_tsec->sid = old_tsec->sid;
2080         new_tsec->osid = old_tsec->sid;
2081
2082         /* Reset fs, key, and sock SIDs on execve. */
2083         new_tsec->create_sid = 0;
2084         new_tsec->keycreate_sid = 0;
2085         new_tsec->sockcreate_sid = 0;
2086
2087         if (old_tsec->exec_sid) {
2088                 new_tsec->sid = old_tsec->exec_sid;
2089                 /* Reset exec SID on execve. */
2090                 new_tsec->exec_sid = 0;
2091
2092                 /*
2093                  * Minimize confusion: if no_new_privs and a transition is
2094                  * explicitly requested, then fail the exec.
2095                  */
2096                 if (bprm->unsafe & LSM_UNSAFE_NO_NEW_PRIVS)
2097                         return -EPERM;
2098         } else {
2099                 /* Check for a default transition on this program. */
2100                 rc = security_transition_sid(old_tsec->sid, isec->sid,
2101                                              SECCLASS_PROCESS, NULL,
2102                                              &new_tsec->sid);
2103                 if (rc)
2104                         return rc;
2105         }
2106
2107         ad.type = LSM_AUDIT_DATA_PATH;
2108         ad.u.path = bprm->file->f_path;
2109
2110         if ((bprm->file->f_path.mnt->mnt_flags & MNT_NOSUID) ||
2111             (bprm->unsafe & LSM_UNSAFE_NO_NEW_PRIVS))
2112                 new_tsec->sid = old_tsec->sid;
2113
2114         if (new_tsec->sid == old_tsec->sid) {
2115                 rc = avc_has_perm(old_tsec->sid, isec->sid,
2116                                   SECCLASS_FILE, FILE__EXECUTE_NO_TRANS, &ad);
2117                 if (rc)
2118                         return rc;
2119         } else {
2120                 /* Check permissions for the transition. */
2121                 rc = avc_has_perm(old_tsec->sid, new_tsec->sid,
2122                                   SECCLASS_PROCESS, PROCESS__TRANSITION, &ad);
2123                 if (rc)
2124                         return rc;
2125
2126                 rc = avc_has_perm(new_tsec->sid, isec->sid,
2127                                   SECCLASS_FILE, FILE__ENTRYPOINT, &ad);
2128                 if (rc)
2129                         return rc;
2130
2131                 /* Check for shared state */
2132                 if (bprm->unsafe & LSM_UNSAFE_SHARE) {
2133                         rc = avc_has_perm(old_tsec->sid, new_tsec->sid,
2134                                           SECCLASS_PROCESS, PROCESS__SHARE,
2135                                           NULL);
2136                         if (rc)
2137                                 return -EPERM;
2138                 }
2139
2140                 /* Make sure that anyone attempting to ptrace over a task that
2141                  * changes its SID has the appropriate permit */
2142                 if (bprm->unsafe &
2143                     (LSM_UNSAFE_PTRACE | LSM_UNSAFE_PTRACE_CAP)) {
2144                         struct task_struct *tracer;
2145                         struct task_security_struct *sec;
2146                         u32 ptsid = 0;
2147
2148                         rcu_read_lock();
2149                         tracer = ptrace_parent(current);
2150                         if (likely(tracer != NULL)) {
2151                                 sec = __task_cred(tracer)->security;
2152                                 ptsid = sec->sid;
2153                         }
2154                         rcu_read_unlock();
2155
2156                         if (ptsid != 0) {
2157                                 rc = avc_has_perm(ptsid, new_tsec->sid,
2158                                                   SECCLASS_PROCESS,
2159                                                   PROCESS__PTRACE, NULL);
2160                                 if (rc)
2161                                         return -EPERM;
2162                         }
2163                 }
2164
2165                 /* Clear any possibly unsafe personality bits on exec: */
2166                 bprm->per_clear |= PER_CLEAR_ON_SETID;
2167         }
2168
2169         return 0;
2170 }
2171
2172 static int selinux_bprm_secureexec(struct linux_binprm *bprm)
2173 {
2174         const struct task_security_struct *tsec = current_security();
2175         u32 sid, osid;
2176         int atsecure = 0;
2177
2178         sid = tsec->sid;
2179         osid = tsec->osid;
2180
2181         if (osid != sid) {
2182                 /* Enable secure mode for SIDs transitions unless
2183                    the noatsecure permission is granted between
2184                    the two SIDs, i.e. ahp returns 0. */
2185                 atsecure = avc_has_perm(osid, sid,
2186                                         SECCLASS_PROCESS,
2187                                         PROCESS__NOATSECURE, NULL);
2188         }
2189
2190         return (atsecure || cap_bprm_secureexec(bprm));
2191 }
2192
2193 static int match_file(const void *p, struct file *file, unsigned fd)
2194 {
2195         return file_has_perm(p, file, file_to_av(file)) ? fd + 1 : 0;
2196 }
2197
2198 /* Derived from fs/exec.c:flush_old_files. */
2199 static inline void flush_unauthorized_files(const struct cred *cred,
2200                                             struct files_struct *files)
2201 {
2202         struct file *file, *devnull = NULL;
2203         struct tty_struct *tty;
2204         int drop_tty = 0;
2205         unsigned n;
2206
2207         tty = get_current_tty();
2208         if (tty) {
2209                 spin_lock(&tty_files_lock);
2210                 if (!list_empty(&tty->tty_files)) {
2211                         struct tty_file_private *file_priv;
2212
2213                         /* Revalidate access to controlling tty.
2214                            Use file_path_has_perm on the tty path directly
2215                            rather than using file_has_perm, as this particular
2216                            open file may belong to another process and we are
2217                            only interested in the inode-based check here. */
2218                         file_priv = list_first_entry(&tty->tty_files,
2219                                                 struct tty_file_private, list);
2220                         file = file_priv->file;
2221                         if (file_path_has_perm(cred, file, FILE__READ | FILE__WRITE))
2222                                 drop_tty = 1;
2223                 }
2224                 spin_unlock(&tty_files_lock);
2225                 tty_kref_put(tty);
2226         }
2227         /* Reset controlling tty. */
2228         if (drop_tty)
2229                 no_tty();
2230
2231         /* Revalidate access to inherited open files. */
2232         n = iterate_fd(files, 0, match_file, cred);
2233         if (!n) /* none found? */
2234                 return;
2235
2236         devnull = dentry_open(&selinux_null, O_RDWR, cred);
2237         if (IS_ERR(devnull))
2238                 devnull = NULL;
2239         /* replace all the matching ones with this */
2240         do {
2241                 replace_fd(n - 1, devnull, 0);
2242         } while ((n = iterate_fd(files, n, match_file, cred)) != 0);
2243         if (devnull)
2244                 fput(devnull);
2245 }
2246
2247 /*
2248  * Prepare a process for imminent new credential changes due to exec
2249  */
2250 static void selinux_bprm_committing_creds(struct linux_binprm *bprm)
2251 {
2252         struct task_security_struct *new_tsec;
2253         struct rlimit *rlim, *initrlim;
2254         int rc, i;
2255
2256         new_tsec = bprm->cred->security;
2257         if (new_tsec->sid == new_tsec->osid)
2258                 return;
2259
2260         /* Close files for which the new task SID is not authorized. */
2261         flush_unauthorized_files(bprm->cred, current->files);
2262
2263         /* Always clear parent death signal on SID transitions. */
2264         current->pdeath_signal = 0;
2265
2266         /* Check whether the new SID can inherit resource limits from the old
2267          * SID.  If not, reset all soft limits to the lower of the current
2268          * task's hard limit and the init task's soft limit.
2269          *
2270          * Note that the setting of hard limits (even to lower them) can be
2271          * controlled by the setrlimit check.  The inclusion of the init task's
2272          * soft limit into the computation is to avoid resetting soft limits
2273          * higher than the default soft limit for cases where the default is
2274          * lower than the hard limit, e.g. RLIMIT_CORE or RLIMIT_STACK.
2275          */
2276         rc = avc_has_perm(new_tsec->osid, new_tsec->sid, SECCLASS_PROCESS,
2277                           PROCESS__RLIMITINH, NULL);
2278         if (rc) {
2279                 /* protect against do_prlimit() */
2280                 task_lock(current);
2281                 for (i = 0; i < RLIM_NLIMITS; i++) {
2282                         rlim = current->signal->rlim + i;
2283                         initrlim = init_task.signal->rlim + i;
2284                         rlim->rlim_cur = min(rlim->rlim_max, initrlim->rlim_cur);
2285                 }
2286                 task_unlock(current);
2287                 update_rlimit_cpu(current, rlimit(RLIMIT_CPU));
2288         }
2289 }
2290
2291 /*
2292  * Clean up the process immediately after the installation of new credentials
2293  * due to exec
2294  */
2295 static void selinux_bprm_committed_creds(struct linux_binprm *bprm)
2296 {
2297         const struct task_security_struct *tsec = current_security();
2298         struct itimerval itimer;
2299         u32 osid, sid;
2300         int rc, i;
2301
2302         osid = tsec->osid;
2303         sid = tsec->sid;
2304
2305         if (sid == osid)
2306                 return;
2307
2308         /* Check whether the new SID can inherit signal state from the old SID.
2309          * If not, clear itimers to avoid subsequent signal generation and
2310          * flush and unblock signals.
2311          *
2312          * This must occur _after_ the task SID has been updated so that any
2313          * kill done after the flush will be checked against the new SID.
2314          */
2315         rc = avc_has_perm(osid, sid, SECCLASS_PROCESS, PROCESS__SIGINH, NULL);
2316         if (rc) {
2317                 memset(&itimer, 0, sizeof itimer);
2318                 for (i = 0; i < 3; i++)
2319                         do_setitimer(i, &itimer, NULL);
2320                 spin_lock_irq(&current->sighand->siglock);
2321                 if (!(current->signal->flags & SIGNAL_GROUP_EXIT)) {
2322                         __flush_signals(current);
2323                         flush_signal_handlers(current, 1);
2324                         sigemptyset(&current->blocked);
2325                 }
2326                 spin_unlock_irq(&current->sighand->siglock);
2327         }
2328
2329         /* Wake up the parent if it is waiting so that it can recheck
2330          * wait permission to the new task SID. */
2331         read_lock(&tasklist_lock);
2332         __wake_up_parent(current, current->real_parent);
2333         read_unlock(&tasklist_lock);
2334 }
2335
2336 /* superblock security operations */
2337
2338 static int selinux_sb_alloc_security(struct super_block *sb)
2339 {
2340         return superblock_alloc_security(sb);
2341 }
2342
2343 static void selinux_sb_free_security(struct super_block *sb)
2344 {
2345         superblock_free_security(sb);
2346 }
2347
2348 static inline int match_prefix(char *prefix, int plen, char *option, int olen)
2349 {
2350         if (plen > olen)
2351                 return 0;
2352
2353         return !memcmp(prefix, option, plen);
2354 }
2355
2356 static inline int selinux_option(char *option, int len)
2357 {
2358         return (match_prefix(CONTEXT_STR, sizeof(CONTEXT_STR)-1, option, len) ||
2359                 match_prefix(FSCONTEXT_STR, sizeof(FSCONTEXT_STR)-1, option, len) ||
2360                 match_prefix(DEFCONTEXT_STR, sizeof(DEFCONTEXT_STR)-1, option, len) ||
2361                 match_prefix(ROOTCONTEXT_STR, sizeof(ROOTCONTEXT_STR)-1, option, len) ||
2362                 match_prefix(LABELSUPP_STR, sizeof(LABELSUPP_STR)-1, option, len));
2363 }
2364
2365 static inline void take_option(char **to, char *from, int *first, int len)
2366 {
2367         if (!*first) {
2368                 **to = ',';
2369                 *to += 1;
2370         } else
2371                 *first = 0;
2372         memcpy(*to, from, len);
2373         *to += len;
2374 }
2375
2376 static inline void take_selinux_option(char **to, char *from, int *first,
2377                                        int len)
2378 {
2379         int current_size = 0;
2380
2381         if (!*first) {
2382                 **to = '|';
2383                 *to += 1;
2384         } else
2385                 *first = 0;
2386
2387         while (current_size < len) {
2388                 if (*from != '"') {
2389                         **to = *from;
2390                         *to += 1;
2391                 }
2392                 from += 1;
2393                 current_size += 1;
2394         }
2395 }
2396
2397 static int selinux_sb_copy_data(char *orig, char *copy)
2398 {
2399         int fnosec, fsec, rc = 0;
2400         char *in_save, *in_curr, *in_end;
2401         char *sec_curr, *nosec_save, *nosec;
2402         int open_quote = 0;
2403
2404         in_curr = orig;
2405         sec_curr = copy;
2406
2407         nosec = (char *)get_zeroed_page(GFP_KERNEL);
2408         if (!nosec) {
2409                 rc = -ENOMEM;
2410                 goto out;
2411         }
2412
2413         nosec_save = nosec;
2414         fnosec = fsec = 1;
2415         in_save = in_end = orig;
2416
2417         do {
2418                 if (*in_end == '"')
2419                         open_quote = !open_quote;
2420                 if ((*in_end == ',' && open_quote == 0) ||
2421                                 *in_end == '\0') {
2422                         int len = in_end - in_curr;
2423
2424                         if (selinux_option(in_curr, len))
2425                                 take_selinux_option(&sec_curr, in_curr, &fsec, len);
2426                         else
2427                                 take_option(&nosec, in_curr, &fnosec, len);
2428
2429                         in_curr = in_end + 1;
2430                 }
2431         } while (*in_end++);
2432
2433         strcpy(in_save, nosec_save);
2434         free_page((unsigned long)nosec_save);
2435 out:
2436         return rc;
2437 }
2438
2439 static int selinux_sb_remount(struct super_block *sb, void *data)
2440 {
2441         int rc, i, *flags;
2442         struct security_mnt_opts opts;
2443         char *secdata, **mount_options;
2444         struct superblock_security_struct *sbsec = sb->s_security;
2445
2446         if (!(sbsec->flags & SE_SBINITIALIZED))
2447                 return 0;
2448
2449         if (!data)
2450                 return 0;
2451
2452         if (sb->s_type->fs_flags & FS_BINARY_MOUNTDATA)
2453                 return 0;
2454
2455         security_init_mnt_opts(&opts);
2456         secdata = alloc_secdata();
2457         if (!secdata)
2458                 return -ENOMEM;
2459         rc = selinux_sb_copy_data(data, secdata);
2460         if (rc)
2461                 goto out_free_secdata;
2462
2463         rc = selinux_parse_opts_str(secdata, &opts);
2464         if (rc)
2465                 goto out_free_secdata;
2466
2467         mount_options = opts.mnt_opts;
2468         flags = opts.mnt_opts_flags;
2469
2470         for (i = 0; i < opts.num_mnt_opts; i++) {
2471                 u32 sid;
2472                 size_t len;
2473
2474                 if (flags[i] == SBLABEL_MNT)
2475                         continue;
2476                 len = strlen(mount_options[i]);
2477                 rc = security_context_to_sid(mount_options[i], len, &sid);
2478                 if (rc) {
2479                         printk(KERN_WARNING "SELinux: security_context_to_sid"
2480                                "(%s) failed for (dev %s, type %s) errno=%d\n",
2481                                mount_options[i], sb->s_id, sb->s_type->name, rc);
2482                         goto out_free_opts;
2483                 }
2484                 rc = -EINVAL;
2485                 switch (flags[i]) {
2486                 case FSCONTEXT_MNT:
2487                         if (bad_option(sbsec, FSCONTEXT_MNT, sbsec->sid, sid))
2488                                 goto out_bad_option;
2489                         break;
2490                 case CONTEXT_MNT:
2491                         if (bad_option(sbsec, CONTEXT_MNT, sbsec->mntpoint_sid, sid))
2492                                 goto out_bad_option;
2493                         break;
2494                 case ROOTCONTEXT_MNT: {
2495                         struct inode_security_struct *root_isec;
2496                         root_isec = sb->s_root->d_inode->i_security;
2497
2498                         if (bad_option(sbsec, ROOTCONTEXT_MNT, root_isec->sid, sid))
2499                                 goto out_bad_option;
2500                         break;
2501                 }
2502                 case DEFCONTEXT_MNT:
2503                         if (bad_option(sbsec, DEFCONTEXT_MNT, sbsec->def_sid, sid))
2504                                 goto out_bad_option;
2505                         break;
2506                 default:
2507                         goto out_free_opts;
2508                 }
2509         }
2510
2511         rc = 0;
2512 out_free_opts:
2513         security_free_mnt_opts(&opts);
2514 out_free_secdata:
2515         free_secdata(secdata);
2516         return rc;
2517 out_bad_option:
2518         printk(KERN_WARNING "SELinux: unable to change security options "
2519                "during remount (dev %s, type=%s)\n", sb->s_id,
2520                sb->s_type->name);
2521         goto out_free_opts;
2522 }
2523
2524 static int selinux_sb_kern_mount(struct super_block *sb, int flags, void *data)
2525 {
2526         const struct cred *cred = current_cred();
2527         struct common_audit_data ad;
2528         int rc;
2529
2530         rc = superblock_doinit(sb, data);
2531         if (rc)
2532                 return rc;
2533
2534         /* Allow all mounts performed by the kernel */
2535         if (flags & MS_KERNMOUNT)
2536                 return 0;
2537
2538         ad.type = LSM_AUDIT_DATA_DENTRY;
2539         ad.u.dentry = sb->s_root;
2540         return superblock_has_perm(cred, sb, FILESYSTEM__MOUNT, &ad);
2541 }
2542
2543 static int selinux_sb_statfs(struct dentry *dentry)
2544 {
2545         const struct cred *cred = current_cred();
2546         struct common_audit_data ad;
2547
2548         ad.type = LSM_AUDIT_DATA_DENTRY;
2549         ad.u.dentry = dentry->d_sb->s_root;
2550         return superblock_has_perm(cred, dentry->d_sb, FILESYSTEM__GETATTR, &ad);
2551 }
2552
2553 static int selinux_mount(const char *dev_name,
2554                          struct path *path,
2555                          const char *type,
2556                          unsigned long flags,
2557                          void *data)
2558 {
2559         const struct cred *cred = current_cred();
2560
2561         if (flags & MS_REMOUNT)
2562                 return superblock_has_perm(cred, path->dentry->d_sb,
2563                                            FILESYSTEM__REMOUNT, NULL);
2564         else
2565                 return path_has_perm(cred, path, FILE__MOUNTON);
2566 }
2567
2568 static int selinux_umount(struct vfsmount *mnt, int flags)
2569 {
2570         const struct cred *cred = current_cred();
2571
2572         return superblock_has_perm(cred, mnt->mnt_sb,
2573                                    FILESYSTEM__UNMOUNT, NULL);
2574 }
2575
2576 /* inode security operations */
2577
2578 static int selinux_inode_alloc_security(struct inode *inode)
2579 {
2580         return inode_alloc_security(inode);
2581 }
2582
2583 static void selinux_inode_free_security(struct inode *inode)
2584 {
2585         inode_free_security(inode);
2586 }
2587
2588 static int selinux_dentry_init_security(struct dentry *dentry, int mode,
2589                                         struct qstr *name, void **ctx,
2590                                         u32 *ctxlen)
2591 {
2592         const struct cred *cred = current_cred();
2593         struct task_security_struct *tsec;
2594         struct inode_security_struct *dsec;
2595         struct superblock_security_struct *sbsec;
2596         struct inode *dir = dentry->d_parent->d_inode;
2597         u32 newsid;
2598         int rc;
2599
2600         tsec = cred->security;
2601         dsec = dir->i_security;
2602         sbsec = dir->i_sb->s_security;
2603
2604         if (tsec->create_sid && sbsec->behavior != SECURITY_FS_USE_MNTPOINT) {
2605                 newsid = tsec->create_sid;
2606         } else {
2607                 rc = security_transition_sid(tsec->sid, dsec->sid,
2608                                              inode_mode_to_security_class(mode),
2609                                              name,
2610                                              &newsid);
2611                 if (rc) {
2612                         printk(KERN_WARNING
2613                                 "%s: security_transition_sid failed, rc=%d\n",
2614                                __func__, -rc);
2615                         return rc;
2616                 }
2617         }
2618
2619         return security_sid_to_context(newsid, (char **)ctx, ctxlen);
2620 }
2621
2622 static int selinux_inode_init_security(struct inode *inode, struct inode *dir,
2623                                        const struct qstr *qstr,
2624                                        const char **name,
2625                                        void **value, size_t *len)
2626 {
2627         const struct task_security_struct *tsec = current_security();
2628         struct inode_security_struct *dsec;
2629         struct superblock_security_struct *sbsec;
2630         u32 sid, newsid, clen;
2631         int rc;
2632         char *context;
2633
2634         dsec = dir->i_security;
2635         sbsec = dir->i_sb->s_security;
2636
2637         sid = tsec->sid;
2638         newsid = tsec->create_sid;
2639
2640         if ((sbsec->flags & SE_SBINITIALIZED) &&
2641             (sbsec->behavior == SECURITY_FS_USE_MNTPOINT))
2642                 newsid = sbsec->mntpoint_sid;
2643         else if (!newsid || !(sbsec->flags & SBLABEL_MNT)) {
2644                 rc = security_transition_sid(sid, dsec->sid,
2645                                              inode_mode_to_security_class(inode->i_mode),
2646                                              qstr, &newsid);
2647                 if (rc) {
2648                         printk(KERN_WARNING "%s:  "
2649                                "security_transition_sid failed, rc=%d (dev=%s "
2650                                "ino=%ld)\n",
2651                                __func__,
2652                                -rc, inode->i_sb->s_id, inode->i_ino);
2653                         return rc;
2654                 }
2655         }
2656
2657         /* Possibly defer initialization to selinux_complete_init. */
2658         if (sbsec->flags & SE_SBINITIALIZED) {
2659                 struct inode_security_struct *isec = inode->i_security;
2660                 isec->sclass = inode_mode_to_security_class(inode->i_mode);
2661                 isec->sid = newsid;
2662                 isec->initialized = 1;
2663         }
2664
2665         if (!ss_initialized || !(sbsec->flags & SBLABEL_MNT))
2666                 return -EOPNOTSUPP;
2667
2668         if (name)
2669                 *name = XATTR_SELINUX_SUFFIX;
2670
2671         if (value && len) {
2672                 rc = security_sid_to_context_force(newsid, &context, &clen);
2673                 if (rc)
2674                         return rc;
2675                 *value = context;
2676                 *len = clen;
2677         }
2678
2679         return 0;
2680 }
2681
2682 static int selinux_inode_create(struct inode *dir, struct dentry *dentry, umode_t mode)
2683 {
2684         return may_create(dir, dentry, SECCLASS_FILE);
2685 }
2686
2687 static int selinux_inode_link(struct dentry *old_dentry, struct inode *dir, struct dentry *new_dentry)
2688 {
2689         return may_link(dir, old_dentry, MAY_LINK);
2690 }
2691
2692 static int selinux_inode_unlink(struct inode *dir, struct dentry *dentry)
2693 {
2694         return may_link(dir, dentry, MAY_UNLINK);
2695 }
2696
2697 static int selinux_inode_symlink(struct inode *dir, struct dentry *dentry, const char *name)
2698 {
2699         return may_create(dir, dentry, SECCLASS_LNK_FILE);
2700 }
2701
2702 static int selinux_inode_mkdir(struct inode *dir, struct dentry *dentry, umode_t mask)
2703 {
2704         return may_create(dir, dentry, SECCLASS_DIR);
2705 }
2706
2707 static int selinux_inode_rmdir(struct inode *dir, struct dentry *dentry)
2708 {
2709         return may_link(dir, dentry, MAY_RMDIR);
2710 }
2711
2712 static int selinux_inode_mknod(struct inode *dir, struct dentry *dentry, umode_t mode, dev_t dev)
2713 {
2714         return may_create(dir, dentry, inode_mode_to_security_class(mode));
2715 }
2716
2717 static int selinux_inode_rename(struct inode *old_inode, struct dentry *old_dentry,
2718                                 struct inode *new_inode, struct dentry *new_dentry)
2719 {
2720         return may_rename(old_inode, old_dentry, new_inode, new_dentry);
2721 }
2722
2723 static int selinux_inode_readlink(struct dentry *dentry)
2724 {
2725         const struct cred *cred = current_cred();
2726
2727         return dentry_has_perm(cred, dentry, FILE__READ);
2728 }
2729
2730 static int selinux_inode_follow_link(struct dentry *dentry, struct nameidata *nameidata)
2731 {
2732         const struct cred *cred = current_cred();
2733
2734         return dentry_has_perm(cred, dentry, FILE__READ);
2735 }
2736
2737 static noinline int audit_inode_permission(struct inode *inode,
2738                                            u32 perms, u32 audited, u32 denied,
2739                                            unsigned flags)
2740 {
2741         struct common_audit_data ad;
2742         struct inode_security_struct *isec = inode->i_security;
2743         int rc;
2744
2745         ad.type = LSM_AUDIT_DATA_INODE;
2746         ad.u.inode = inode;
2747
2748         rc = slow_avc_audit(current_sid(), isec->sid, isec->sclass, perms,
2749                             audited, denied, &ad, flags);
2750         if (rc)
2751                 return rc;
2752         return 0;
2753 }
2754
2755 static int selinux_inode_permission(struct inode *inode, int mask)
2756 {
2757         const struct cred *cred = current_cred();
2758         u32 perms;
2759         bool from_access;
2760         unsigned flags = mask & MAY_NOT_BLOCK;
2761         struct inode_security_struct *isec;
2762         u32 sid;
2763         struct av_decision avd;
2764         int rc, rc2;
2765         u32 audited, denied;
2766
2767         from_access = mask & MAY_ACCESS;
2768         mask &= (MAY_READ|MAY_WRITE|MAY_EXEC|MAY_APPEND);
2769
2770         /* No permission to check.  Existence test. */
2771         if (!mask)
2772                 return 0;
2773
2774         validate_creds(cred);
2775
2776         if (unlikely(IS_PRIVATE(inode)))
2777                 return 0;
2778
2779         perms = file_mask_to_av(inode->i_mode, mask);
2780
2781         sid = cred_sid(cred);
2782         isec = inode->i_security;
2783
2784         rc = avc_has_perm_noaudit(sid, isec->sid, isec->sclass, perms, 0, &avd);
2785         audited = avc_audit_required(perms, &avd, rc,
2786                                      from_access ? FILE__AUDIT_ACCESS : 0,
2787                                      &denied);
2788         if (likely(!audited))
2789                 return rc;
2790
2791         rc2 = audit_inode_permission(inode, perms, audited, denied, flags);
2792         if (rc2)
2793                 return rc2;
2794         return rc;
2795 }
2796
2797 static int selinux_inode_setattr(struct dentry *dentry, struct iattr *iattr)
2798 {
2799         const struct cred *cred = current_cred();
2800         unsigned int ia_valid = iattr->ia_valid;
2801         __u32 av = FILE__WRITE;
2802
2803         /* ATTR_FORCE is just used for ATTR_KILL_S[UG]ID. */
2804         if (ia_valid & ATTR_FORCE) {
2805                 ia_valid &= ~(ATTR_KILL_SUID | ATTR_KILL_SGID | ATTR_MODE |
2806                               ATTR_FORCE);
2807                 if (!ia_valid)
2808                         return 0;
2809         }
2810
2811         if (ia_valid & (ATTR_MODE | ATTR_UID | ATTR_GID |
2812                         ATTR_ATIME_SET | ATTR_MTIME_SET | ATTR_TIMES_SET))
2813                 return dentry_has_perm(cred, dentry, FILE__SETATTR);
2814
2815         if (selinux_policycap_openperm && (ia_valid & ATTR_SIZE))
2816                 av |= FILE__OPEN;
2817
2818         return dentry_has_perm(cred, dentry, av);
2819 }
2820
2821 static int selinux_inode_getattr(struct vfsmount *mnt, struct dentry *dentry)
2822 {
2823         const struct cred *cred = current_cred();
2824         struct path path;
2825
2826         path.dentry = dentry;
2827         path.mnt = mnt;
2828
2829         return path_has_perm(cred, &path, FILE__GETATTR);
2830 }
2831
2832 static int selinux_inode_setotherxattr(struct dentry *dentry, const char *name)
2833 {
2834         const struct cred *cred = current_cred();
2835
2836         if (!strncmp(name, XATTR_SECURITY_PREFIX,
2837                      sizeof XATTR_SECURITY_PREFIX - 1)) {
2838                 if (!strcmp(name, XATTR_NAME_CAPS)) {
2839                         if (!capable(CAP_SETFCAP))
2840                                 return -EPERM;
2841                 } else if (!capable(CAP_SYS_ADMIN)) {
2842                         /* A different attribute in the security namespace.
2843                            Restrict to administrator. */
2844                         return -EPERM;
2845                 }
2846         }
2847
2848         /* Not an attribute we recognize, so just check the
2849            ordinary setattr permission. */
2850         return dentry_has_perm(cred, dentry, FILE__SETATTR);
2851 }
2852
2853 static int selinux_inode_setxattr(struct dentry *dentry, const char *name,
2854                                   const void *value, size_t size, int flags)
2855 {
2856         struct inode *inode = dentry->d_inode;
2857         struct inode_security_struct *isec = inode->i_security;
2858         struct superblock_security_struct *sbsec;
2859         struct common_audit_data ad;
2860         u32 newsid, sid = current_sid();
2861         int rc = 0;
2862
2863         if (strcmp(name, XATTR_NAME_SELINUX))
2864                 return selinux_inode_setotherxattr(dentry, name);
2865
2866         sbsec = inode->i_sb->s_security;
2867         if (!(sbsec->flags & SBLABEL_MNT))
2868                 return -EOPNOTSUPP;
2869
2870         if (!inode_owner_or_capable(inode))
2871                 return -EPERM;
2872
2873         ad.type = LSM_AUDIT_DATA_DENTRY;
2874         ad.u.dentry = dentry;
2875
2876         rc = avc_has_perm(sid, isec->sid, isec->sclass,
2877                           FILE__RELABELFROM, &ad);
2878         if (rc)
2879                 return rc;
2880
2881         rc = security_context_to_sid(value, size, &newsid);
2882         if (rc == -EINVAL) {
2883                 if (!capable(CAP_MAC_ADMIN)) {
2884                         struct audit_buffer *ab;
2885                         size_t audit_size;
2886                         const char *str;
2887
2888                         /* We strip a nul only if it is at the end, otherwise the
2889                          * context contains a nul and we should audit that */
2890                         if (value) {
2891                                 str = value;
2892                                 if (str[size - 1] == '\0')
2893                                         audit_size = size - 1;
2894                                 else
2895                                         audit_size = size;
2896                         } else {
2897                                 str = "";
2898                                 audit_size = 0;
2899                         }
2900                         ab = audit_log_start(current->audit_context, GFP_ATOMIC, AUDIT_SELINUX_ERR);
2901                         audit_log_format(ab, "op=setxattr invalid_context=");
2902                         audit_log_n_untrustedstring(ab, value, audit_size);
2903                         audit_log_end(ab);
2904
2905                         return rc;
2906                 }
2907                 rc = security_context_to_sid_force(value, size, &newsid);
2908         }
2909         if (rc)
2910                 return rc;
2911
2912         rc = avc_has_perm(sid, newsid, isec->sclass,
2913                           FILE__RELABELTO, &ad);
2914         if (rc)
2915                 return rc;
2916
2917         rc = security_validate_transition(isec->sid, newsid, sid,
2918                                           isec->sclass);
2919         if (rc)
2920                 return rc;
2921
2922         return avc_has_perm(newsid,
2923                             sbsec->sid,
2924                             SECCLASS_FILESYSTEM,
2925                             FILESYSTEM__ASSOCIATE,
2926                             &ad);
2927 }
2928
2929 static void selinux_inode_post_setxattr(struct dentry *dentry, const char *name,
2930                                         const void *value, size_t size,
2931                                         int flags)
2932 {
2933         struct inode *inode = dentry->d_inode;
2934         struct inode_security_struct *isec = inode->i_security;
2935         u32 newsid;
2936         int rc;
2937
2938         if (strcmp(name, XATTR_NAME_SELINUX)) {
2939                 /* Not an attribute we recognize, so nothing to do. */
2940                 return;
2941         }
2942
2943         rc = security_context_to_sid_force(value, size, &newsid);
2944         if (rc) {
2945                 printk(KERN_ERR "SELinux:  unable to map context to SID"
2946                        "for (%s, %lu), rc=%d\n",
2947                        inode->i_sb->s_id, inode->i_ino, -rc);
2948                 return;
2949         }
2950
2951         isec->sclass = inode_mode_to_security_class(inode->i_mode);
2952         isec->sid = newsid;
2953         isec->initialized = 1;
2954
2955         return;
2956 }
2957
2958 static int selinux_inode_getxattr(struct dentry *dentry, const char *name)
2959 {
2960         const struct cred *cred = current_cred();
2961
2962         return dentry_has_perm(cred, dentry, FILE__GETATTR);
2963 }
2964
2965 static int selinux_inode_listxattr(struct dentry *dentry)
2966 {
2967         const struct cred *cred = current_cred();
2968
2969         return dentry_has_perm(cred, dentry, FILE__GETATTR);
2970 }
2971
2972 static int selinux_inode_removexattr(struct dentry *dentry, const char *name)
2973 {
2974         if (strcmp(name, XATTR_NAME_SELINUX))
2975                 return selinux_inode_setotherxattr(dentry, name);
2976
2977         /* No one is allowed to remove a SELinux security label.
2978            You can change the label, but all data must be labeled. */
2979         return -EACCES;
2980 }
2981
2982 /*
2983  * Copy the inode security context value to the user.
2984  *
2985  * Permission check is handled by selinux_inode_getxattr hook.
2986  */
2987 static int selinux_inode_getsecurity(const struct inode *inode, const char *name, void **buffer, bool alloc)
2988 {
2989         u32 size;
2990         int error;
2991         char *context = NULL;
2992         struct inode_security_struct *isec = inode->i_security;
2993
2994         if (strcmp(name, XATTR_SELINUX_SUFFIX))
2995                 return -EOPNOTSUPP;
2996
2997         /*
2998          * If the caller has CAP_MAC_ADMIN, then get the raw context
2999          * value even if it is not defined by current policy; otherwise,
3000          * use the in-core value under current policy.
3001          * Use the non-auditing forms of the permission checks since
3002          * getxattr may be called by unprivileged processes commonly
3003          * and lack of permission just means that we fall back to the
3004          * in-core context value, not a denial.
3005          */
3006         error = selinux_capable(current_cred(), &init_user_ns, CAP_MAC_ADMIN,
3007                                 SECURITY_CAP_NOAUDIT);
3008         if (!error)
3009                 error = security_sid_to_context_force(isec->sid, &context,
3010                                                       &size);
3011         else
3012                 error = security_sid_to_context(isec->sid, &context, &size);
3013         if (error)
3014                 return error;
3015         error = size;
3016         if (alloc) {
3017                 *buffer = context;
3018                 goto out_nofree;
3019         }
3020         kfree(context);
3021 out_nofree:
3022         return error;
3023 }
3024
3025 static int selinux_inode_setsecurity(struct inode *inode, const char *name,
3026                                      const void *value, size_t size, int flags)
3027 {
3028         struct inode_security_struct *isec = inode->i_security;
3029         u32 newsid;
3030         int rc;
3031
3032         if (strcmp(name, XATTR_SELINUX_SUFFIX))
3033                 return -EOPNOTSUPP;
3034
3035         if (!value || !size)
3036                 return -EACCES;
3037
3038         rc = security_context_to_sid((void *)value, size, &newsid);
3039         if (rc)
3040                 return rc;
3041
3042         isec->sclass = inode_mode_to_security_class(inode->i_mode);
3043         isec->sid = newsid;
3044         isec->initialized = 1;
3045         return 0;
3046 }
3047
3048 static int selinux_inode_listsecurity(struct inode *inode, char *buffer, size_t buffer_size)
3049 {
3050         const int len = sizeof(XATTR_NAME_SELINUX);
3051         if (buffer && len <= buffer_size)
3052                 memcpy(buffer, XATTR_NAME_SELINUX, len);
3053         return len;
3054 }
3055
3056 static void selinux_inode_getsecid(const struct inode *inode, u32 *secid)
3057 {
3058         struct inode_security_struct *isec = inode->i_security;
3059         *secid = isec->sid;
3060 }
3061
3062 /* file security operations */
3063
3064 static int selinux_revalidate_file_permission(struct file *file, int mask)
3065 {
3066         const struct cred *cred = current_cred();
3067         struct inode *inode = file_inode(file);
3068
3069         /* file_mask_to_av won't add FILE__WRITE if MAY_APPEND is set */
3070         if ((file->f_flags & O_APPEND) && (mask & MAY_WRITE))
3071                 mask |= MAY_APPEND;
3072
3073         return file_has_perm(cred, file,
3074                              file_mask_to_av(inode->i_mode, mask));
3075 }
3076
3077 static int selinux_file_permission(struct file *file, int mask)
3078 {
3079         struct inode *inode = file_inode(file);
3080         struct file_security_struct *fsec = file->f_security;
3081         struct inode_security_struct *isec = inode->i_security;
3082         u32 sid = current_sid();
3083
3084         if (!mask)
3085                 /* No permission to check.  Existence test. */
3086                 return 0;
3087
3088         if (sid == fsec->sid && fsec->isid == isec->sid &&
3089             fsec->pseqno == avc_policy_seqno())
3090                 /* No change since file_open check. */
3091                 return 0;
3092
3093         return selinux_revalidate_file_permission(file, mask);
3094 }
3095
3096 static int selinux_file_alloc_security(struct file *file)
3097 {
3098         return file_alloc_security(file);
3099 }
3100
3101 static void selinux_file_free_security(struct file *file)
3102 {
3103         file_free_security(file);
3104 }
3105
3106 static int selinux_file_ioctl(struct file *file, unsigned int cmd,
3107                               unsigned long arg)
3108 {
3109         const struct cred *cred = current_cred();
3110         int error = 0;
3111
3112         switch (cmd) {
3113         case FIONREAD:
3114         /* fall through */
3115         case FIBMAP:
3116         /* fall through */
3117         case FIGETBSZ:
3118         /* fall through */
3119         case FS_IOC_GETFLAGS:
3120         /* fall through */
3121         case FS_IOC_GETVERSION:
3122                 error = file_has_perm(cred, file, FILE__GETATTR);
3123                 break;
3124
3125         case FS_IOC_SETFLAGS:
3126         /* fall through */
3127         case FS_IOC_SETVERSION:
3128                 error = file_has_perm(cred, file, FILE__SETATTR);
3129                 break;
3130
3131         /* sys_ioctl() checks */
3132         case FIONBIO:
3133         /* fall through */
3134         case FIOASYNC:
3135                 error = file_has_perm(cred, file, 0);
3136                 break;
3137
3138         case KDSKBENT:
3139         case KDSKBSENT:
3140                 error = cred_has_capability(cred, CAP_SYS_TTY_CONFIG,
3141                                             SECURITY_CAP_AUDIT);
3142                 break;
3143
3144         /* default case assumes that the command will go
3145          * to the file's ioctl() function.
3146          */
3147         default:
3148                 error = file_has_perm(cred, file, FILE__IOCTL);
3149         }
3150         return error;
3151 }
3152
3153 static int default_noexec;
3154
3155 static int file_map_prot_check(struct file *file, unsigned long prot, int shared)
3156 {
3157         const struct cred *cred = current_cred();
3158         int rc = 0;
3159
3160         if (default_noexec &&
3161             (prot & PROT_EXEC) && (!file || (!shared && (prot & PROT_WRITE)))) {
3162                 /*
3163                  * We are making executable an anonymous mapping or a
3164                  * private file mapping that will also be writable.
3165                  * This has an additional check.
3166                  */
3167                 rc = cred_has_perm(cred, cred, PROCESS__EXECMEM);
3168                 if (rc)
3169                         goto error;
3170         }
3171
3172         if (file) {
3173                 /* read access is always possible with a mapping */
3174                 u32 av = FILE__READ;
3175
3176                 /* write access only matters if the mapping is shared */
3177                 if (shared && (prot & PROT_WRITE))
3178                         av |= FILE__WRITE;
3179
3180                 if (prot & PROT_EXEC)
3181                         av |= FILE__EXECUTE;
3182
3183                 return file_has_perm(cred, file, av);
3184         }
3185
3186 error:
3187         return rc;
3188 }
3189
3190 static int selinux_mmap_addr(unsigned long addr)
3191 {
3192         int rc = 0;
3193         u32 sid = current_sid();
3194
3195         /*
3196          * notice that we are intentionally putting the SELinux check before
3197          * the secondary cap_file_mmap check.  This is such a likely attempt
3198          * at bad behaviour/exploit that we always want to get the AVC, even
3199          * if DAC would have also denied the operation.
3200          */
3201         if (addr < CONFIG_LSM_MMAP_MIN_ADDR) {
3202                 rc = avc_has_perm(sid, sid, SECCLASS_MEMPROTECT,
3203                                   MEMPROTECT__MMAP_ZERO, NULL);
3204                 if (rc)
3205                         return rc;
3206         }
3207
3208         /* do DAC check on address space usage */
3209         return cap_mmap_addr(addr);
3210 }
3211
3212 static int selinux_mmap_file(struct file *file, unsigned long reqprot,
3213                              unsigned long prot, unsigned long flags)
3214 {
3215         if (selinux_checkreqprot)
3216                 prot = reqprot;
3217
3218         return file_map_prot_check(file, prot,
3219                                    (flags & MAP_TYPE) == MAP_SHARED);
3220 }
3221
3222 static int selinux_file_mprotect(struct vm_area_struct *vma,
3223                                  unsigned long reqprot,
3224                                  unsigned long prot)
3225 {
3226         const struct cred *cred = current_cred();
3227
3228         if (selinux_checkreqprot)
3229                 prot = reqprot;
3230
3231         if (default_noexec &&
3232             (prot & PROT_EXEC) && !(vma->vm_flags & VM_EXEC)) {
3233                 int rc = 0;
3234                 if (vma->vm_start >= vma->vm_mm->start_brk &&
3235                     vma->vm_end <= vma->vm_mm->brk) {
3236                         rc = cred_has_perm(cred, cred, PROCESS__EXECHEAP);
3237                 } else if (!vma->vm_file &&
3238                            vma->vm_start <= vma->vm_mm->start_stack &&
3239                            vma->vm_end >= vma->vm_mm->start_stack) {
3240                         rc = current_has_perm(current, PROCESS__EXECSTACK);
3241                 } else if (vma->vm_file && vma->anon_vma) {
3242                         /*
3243                          * We are making executable a file mapping that has
3244                          * had some COW done. Since pages might have been
3245                          * written, check ability to execute the possibly
3246                          * modified content.  This typically should only
3247                          * occur for text relocations.
3248                          */
3249                         rc = file_has_perm(cred, vma->vm_file, FILE__EXECMOD);
3250                 }
3251                 if (rc)
3252                         return rc;
3253         }
3254
3255         return file_map_prot_check(vma->vm_file, prot, vma->vm_flags&VM_SHARED);
3256 }
3257
3258 static int selinux_file_lock(struct file *file, unsigned int cmd)
3259 {
3260         const struct cred *cred = current_cred();
3261
3262         return file_has_perm(cred, file, FILE__LOCK);
3263 }
3264
3265 static int selinux_file_fcntl(struct file *file, unsigned int cmd,
3266                               unsigned long arg)
3267 {
3268         const struct cred *cred = current_cred();
3269         int err = 0;
3270
3271         switch (cmd) {
3272         case F_SETFL:
3273                 if ((file->f_flags & O_APPEND) && !(arg & O_APPEND)) {
3274                         err = file_has_perm(cred, file, FILE__WRITE);
3275                         break;
3276                 }
3277                 /* fall through */
3278         case F_SETOWN:
3279         case F_SETSIG:
3280         case F_GETFL:
3281         case F_GETOWN:
3282         case F_GETSIG:
3283         case F_GETOWNER_UIDS:
3284                 /* Just check FD__USE permission */
3285                 err = file_has_perm(cred, file, 0);
3286                 break;
3287         case F_GETLK:
3288         case F_SETLK:
3289         case F_SETLKW:
3290 #if BITS_PER_LONG == 32
3291         case F_GETLK64:
3292         case F_SETLK64:
3293         case F_SETLKW64:
3294 #endif
3295                 err = file_has_perm(cred, file, FILE__LOCK);
3296                 break;
3297         }
3298
3299         return err;
3300 }
3301
3302 static int selinux_file_set_fowner(struct file *file)
3303 {
3304         struct file_security_struct *fsec;
3305
3306         fsec = file->f_security;
3307         fsec->fown_sid = current_sid();
3308
3309         return 0;
3310 }
3311
3312 static int selinux_file_send_sigiotask(struct task_struct *tsk,
3313                                        struct fown_struct *fown, int signum)
3314 {
3315         struct file *file;
3316         u32 sid = task_sid(tsk);
3317         u32 perm;
3318         struct file_security_struct *fsec;
3319
3320         /* struct fown_struct is never outside the context of a struct file */
3321         file = container_of(fown, struct file, f_owner);
3322
3323         fsec = file->f_security;
3324
3325         if (!signum)
3326                 perm = signal_to_av(SIGIO); /* as per send_sigio_to_task */
3327         else
3328                 perm = signal_to_av(signum);
3329
3330         return avc_has_perm(fsec->fown_sid, sid,
3331                             SECCLASS_PROCESS, perm, NULL);
3332 }
3333
3334 static int selinux_file_receive(struct file *file)
3335 {
3336         const struct cred *cred = current_cred();
3337
3338         return file_has_perm(cred, file, file_to_av(file));
3339 }
3340
3341 static int selinux_file_open(struct file *file, const struct cred *cred)
3342 {
3343         struct file_security_struct *fsec;
3344         struct inode_security_struct *isec;
3345
3346         fsec = file->f_security;
3347         isec = file_inode(file)->i_security;
3348         /*
3349          * Save inode label and policy sequence number
3350          * at open-time so that selinux_file_permission
3351          * can determine whether revalidation is necessary.
3352          * Task label is already saved in the file security
3353          * struct as its SID.
3354          */
3355         fsec->isid = isec->sid;
3356         fsec->pseqno = avc_policy_seqno();
3357         /*
3358          * Since the inode label or policy seqno may have changed
3359          * between the selinux_inode_permission check and the saving
3360          * of state above, recheck that access is still permitted.
3361          * Otherwise, access might never be revalidated against the
3362          * new inode label or new policy.
3363          * This check is not redundant - do not remove.
3364          */
3365         return file_path_has_perm(cred, file, open_file_to_av(file));
3366 }
3367
3368 /* task security operations */
3369
3370 static int selinux_task_create(unsigned long clone_flags)
3371 {
3372         return current_has_perm(current, PROCESS__FORK);
3373 }
3374
3375 /*
3376  * allocate the SELinux part of blank credentials
3377  */
3378 static int selinux_cred_alloc_blank(struct cred *cred, gfp_t gfp)
3379 {
3380         struct task_security_struct *tsec;
3381
3382         tsec = kzalloc(sizeof(struct task_security_struct), gfp);
3383         if (!tsec)
3384                 return -ENOMEM;
3385
3386         cred->security = tsec;
3387         return 0;
3388 }
3389
3390 /*
3391  * detach and free the LSM part of a set of credentials
3392  */
3393 static void selinux_cred_free(struct cred *cred)
3394 {
3395         struct task_security_struct *tsec = cred->security;
3396
3397         /*
3398          * cred->security == NULL if security_cred_alloc_blank() or
3399          * security_prepare_creds() returned an error.
3400          */
3401         BUG_ON(cred->security && (unsigned long) cred->security < PAGE_SIZE);
3402         cred->security = (void *) 0x7UL;
3403         kfree(tsec);
3404 }
3405
3406 /*
3407  * prepare a new set of credentials for modification
3408  */
3409 static int selinux_cred_prepare(struct cred *new, const struct cred *old,
3410                                 gfp_t gfp)
3411 {
3412         const struct task_security_struct *old_tsec;
3413         struct task_security_struct *tsec;
3414
3415         old_tsec = old->security;
3416
3417         tsec = kmemdup(old_tsec, sizeof(struct task_security_struct), gfp);
3418         if (!tsec)
3419                 return -ENOMEM;
3420
3421         new->security = tsec;
3422         return 0;
3423 }
3424
3425 /*
3426  * transfer the SELinux data to a blank set of creds
3427  */
3428 static void selinux_cred_transfer(struct cred *new, const struct cred *old)
3429 {
3430         const struct task_security_struct *old_tsec = old->security;
3431         struct task_security_struct *tsec = new->security;
3432
3433         *tsec = *old_tsec;
3434 }
3435
3436 /*
3437  * set the security data for a kernel service
3438  * - all the creation contexts are set to unlabelled
3439  */
3440 static int selinux_kernel_act_as(struct cred *new, u32 secid)
3441 {
3442         struct task_security_struct *tsec = new->security;
3443         u32 sid = current_sid();
3444         int ret;
3445
3446         ret = avc_has_perm(sid, secid,
3447                            SECCLASS_KERNEL_SERVICE,
3448                            KERNEL_SERVICE__USE_AS_OVERRIDE,
3449                            NULL);
3450         if (ret == 0) {
3451                 tsec->sid = secid;
3452                 tsec->create_sid = 0;
3453                 tsec->keycreate_sid = 0;
3454                 tsec->sockcreate_sid = 0;
3455         }
3456         return ret;
3457 }
3458
3459 /*
3460  * set the file creation context in a security record to the same as the
3461  * objective context of the specified inode
3462  */
3463 static int selinux_kernel_create_files_as(struct cred *new, struct inode *inode)
3464 {
3465         struct inode_security_struct *isec = inode->i_security;
3466         struct task_security_struct *tsec = new->security;
3467         u32 sid = current_sid();
3468         int ret;
3469
3470         ret = avc_has_perm(sid, isec->sid,
3471                            SECCLASS_KERNEL_SERVICE,
3472                            KERNEL_SERVICE__CREATE_FILES_AS,
3473                            NULL);
3474
3475         if (ret == 0)
3476                 tsec->create_sid = isec->sid;
3477         return ret;
3478 }
3479
3480 static int selinux_kernel_module_request(char *kmod_name)
3481 {
3482         u32 sid;
3483         struct common_audit_data ad;
3484
3485         sid = task_sid(current);
3486
3487         ad.type = LSM_AUDIT_DATA_KMOD;
3488         ad.u.kmod_name = kmod_name;
3489
3490         return avc_has_perm(sid, SECINITSID_KERNEL, SECCLASS_SYSTEM,
3491                             SYSTEM__MODULE_REQUEST, &ad);
3492 }
3493
3494 static int selinux_task_setpgid(struct task_struct *p, pid_t pgid)
3495 {
3496         return current_has_perm(p, PROCESS__SETPGID);
3497 }
3498
3499 static int selinux_task_getpgid(struct task_struct *p)
3500 {
3501         return current_has_perm(p, PROCESS__GETPGID);
3502 }
3503
3504 static int selinux_task_getsid(struct task_struct *p)
3505 {
3506         return current_has_perm(p, PROCESS__GETSESSION);
3507 }
3508
3509 static void selinux_task_getsecid(struct task_struct *p, u32 *secid)
3510 {
3511         *secid = task_sid(p);
3512 }
3513
3514 static int selinux_task_setnice(struct task_struct *p, int nice)
3515 {
3516         int rc;
3517
3518         rc = cap_task_setnice(p, nice);
3519         if (rc)
3520                 return rc;
3521
3522         return current_has_perm(p, PROCESS__SETSCHED);
3523 }
3524
3525 static int selinux_task_setioprio(struct task_struct *p, int ioprio)
3526 {
3527         int rc;
3528
3529         rc = cap_task_setioprio(p, ioprio);
3530         if (rc)
3531                 return rc;
3532
3533         return current_has_perm(p, PROCESS__SETSCHED);
3534 }
3535
3536 static int selinux_task_getioprio(struct task_struct *p)
3537 {
3538         return current_has_perm(p, PROCESS__GETSCHED);
3539 }
3540
3541 static int selinux_task_setrlimit(struct task_struct *p, unsigned int resource,
3542                 struct rlimit *new_rlim)
3543 {
3544         struct rlimit *old_rlim = p->signal->rlim + resource;
3545
3546         /* Control the ability to change the hard limit (whether
3547            lowering or raising it), so that the hard limit can
3548            later be used as a safe reset point for the soft limit
3549            upon context transitions.  See selinux_bprm_committing_creds. */
3550         if (old_rlim->rlim_max != new_rlim->rlim_max)
3551                 return current_has_perm(p, PROCESS__SETRLIMIT);
3552
3553         return 0;
3554 }
3555
3556 static int selinux_task_setscheduler(struct task_struct *p)
3557 {
3558         int rc;
3559
3560         rc = cap_task_setscheduler(p);
3561         if (rc)
3562                 return rc;
3563
3564         return current_has_perm(p, PROCESS__SETSCHED);
3565 }
3566
3567 static int selinux_task_getscheduler(struct task_struct *p)
3568 {
3569         return current_has_perm(p, PROCESS__GETSCHED);
3570 }
3571
3572 static int selinux_task_movememory(struct task_struct *p)
3573 {
3574         return current_has_perm(p, PROCESS__SETSCHED);
3575 }
3576
3577 static int selinux_task_kill(struct task_struct *p, struct siginfo *info,
3578                                 int sig, u32 secid)
3579 {
3580         u32 perm;
3581         int rc;
3582
3583         if (!sig)
3584                 perm = PROCESS__SIGNULL; /* null signal; existence test */
3585         else
3586                 perm = signal_to_av(sig);
3587         if (secid)
3588                 rc = avc_has_perm(secid, task_sid(p),
3589                                   SECCLASS_PROCESS, perm, NULL);
3590         else
3591                 rc = current_has_perm(p, perm);
3592         return rc;
3593 }
3594
3595 static int selinux_task_wait(struct task_struct *p)
3596 {
3597         return task_has_perm(p, current, PROCESS__SIGCHLD);
3598 }
3599
3600 static void selinux_task_to_inode(struct task_struct *p,
3601                                   struct inode *inode)
3602 {
3603         struct inode_security_struct *isec = inode->i_security;
3604         u32 sid = task_sid(p);
3605
3606         isec->sid = sid;
3607         isec->initialized = 1;
3608 }
3609
3610 /* Returns error only if unable to parse addresses */
3611 static int selinux_parse_skb_ipv4(struct sk_buff *skb,
3612                         struct common_audit_data *ad, u8 *proto)
3613 {
3614         int offset, ihlen, ret = -EINVAL;
3615         struct iphdr _iph, *ih;
3616
3617         offset = skb_network_offset(skb);
3618         ih = skb_header_pointer(skb, offset, sizeof(_iph), &_iph);
3619         if (ih == NULL)
3620                 goto out;
3621
3622         ihlen = ih->ihl * 4;
3623         if (ihlen < sizeof(_iph))
3624                 goto out;
3625
3626         ad->u.net->v4info.saddr = ih->saddr;
3627         ad->u.net->v4info.daddr = ih->daddr;
3628         ret = 0;
3629
3630         if (proto)
3631                 *proto = ih->protocol;
3632
3633         switch (ih->protocol) {
3634         case IPPROTO_TCP: {
3635                 struct tcphdr _tcph, *th;
3636
3637                 if (ntohs(ih->frag_off) & IP_OFFSET)
3638                         break;
3639
3640                 offset += ihlen;
3641                 th = skb_header_pointer(skb, offset, sizeof(_tcph), &_tcph);
3642                 if (th == NULL)
3643                         break;
3644
3645                 ad->u.net->sport = th->source;
3646                 ad->u.net->dport = th->dest;
3647                 break;
3648         }
3649
3650         case IPPROTO_UDP: {
3651                 struct udphdr _udph, *uh;
3652
3653                 if (ntohs(ih->frag_off) & IP_OFFSET)
3654                         break;
3655
3656                 offset += ihlen;
3657                 uh = skb_header_pointer(skb, offset, sizeof(_udph), &_udph);
3658                 if (uh == NULL)
3659                         break;
3660
3661                 ad->u.net->sport = uh->source;
3662                 ad->u.net->dport = uh->dest;
3663                 break;
3664         }
3665
3666         case IPPROTO_DCCP: {
3667                 struct dccp_hdr _dccph, *dh;
3668
3669                 if (ntohs(ih->frag_off) & IP_OFFSET)
3670                         break;
3671
3672                 offset += ihlen;
3673                 dh = skb_header_pointer(skb, offset, sizeof(_dccph), &_dccph);
3674                 if (dh == NULL)
3675                         break;
3676
3677                 ad->u.net->sport = dh->dccph_sport;
3678                 ad->u.net->dport = dh->dccph_dport;
3679                 break;
3680         }
3681
3682         default:
3683                 break;
3684         }
3685 out:
3686         return ret;
3687 }
3688
3689 #if defined(CONFIG_IPV6) || defined(CONFIG_IPV6_MODULE)
3690
3691 /* Returns error only if unable to parse addresses */
3692 static int selinux_parse_skb_ipv6(struct sk_buff *skb,
3693                         struct common_audit_data *ad, u8 *proto)
3694 {
3695         u8 nexthdr;
3696         int ret = -EINVAL, offset;
3697         struct ipv6hdr _ipv6h, *ip6;
3698         __be16 frag_off;
3699
3700         offset = skb_network_offset(skb);
3701         ip6 = skb_header_pointer(skb, offset, sizeof(_ipv6h), &_ipv6h);
3702         if (ip6 == NULL)
3703                 goto out;
3704
3705         ad->u.net->v6info.saddr = ip6->saddr;
3706         ad->u.net->v6info.daddr = ip6->daddr;
3707         ret = 0;
3708
3709         nexthdr = ip6->nexthdr;
3710         offset += sizeof(_ipv6h);
3711         offset = ipv6_skip_exthdr(skb, offset, &nexthdr, &frag_off);
3712         if (offset < 0)
3713                 goto out;
3714
3715         if (proto)
3716                 *proto = nexthdr;
3717
3718         switch (nexthdr) {
3719         case IPPROTO_TCP: {
3720                 struct tcphdr _tcph, *th;
3721
3722                 th = skb_header_pointer(skb, offset, sizeof(_tcph), &_tcph);
3723                 if (th == NULL)
3724                         break;
3725
3726                 ad->u.net->sport = th->source;
3727                 ad->u.net->dport = th->dest;
3728                 break;
3729         }
3730
3731         case IPPROTO_UDP: {
3732                 struct udphdr _udph, *uh;
3733
3734                 uh = skb_header_pointer(skb, offset, sizeof(_udph), &_udph);
3735                 if (uh == NULL)
3736                         break;
3737
3738                 ad->u.net->sport = uh->source;
3739                 ad->u.net->dport = uh->dest;
3740                 break;
3741         }
3742
3743         case IPPROTO_DCCP: {
3744                 struct dccp_hdr _dccph, *dh;
3745
3746                 dh = skb_header_pointer(skb, offset, sizeof(_dccph), &_dccph);
3747                 if (dh == NULL)
3748                         break;
3749
3750                 ad->u.net->sport = dh->dccph_sport;
3751                 ad->u.net->dport = dh->dccph_dport;
3752                 break;
3753         }
3754
3755         /* includes fragments */
3756         default:
3757                 break;
3758         }
3759 out:
3760         return ret;
3761 }
3762
3763 #endif /* IPV6 */
3764
3765 static int selinux_parse_skb(struct sk_buff *skb, struct common_audit_data *ad,
3766                              char **_addrp, int src, u8 *proto)
3767 {
3768         char *addrp;
3769         int ret;
3770
3771         switch (ad->u.net->family) {
3772         case PF_INET:
3773                 ret = selinux_parse_skb_ipv4(skb, ad, proto);
3774                 if (ret)
3775                         goto parse_error;
3776                 addrp = (char *)(src ? &ad->u.net->v4info.saddr :
3777                                        &ad->u.net->v4info.daddr);
3778                 goto okay;
3779
3780 #if defined(CONFIG_IPV6) || defined(CONFIG_IPV6_MODULE)
3781         case PF_INET6:
3782                 ret = selinux_parse_skb_ipv6(skb, ad, proto);
3783                 if (ret)
3784                         goto parse_error;
3785                 addrp = (char *)(src ? &ad->u.net->v6info.saddr :
3786                                        &ad->u.net->v6info.daddr);
3787                 goto okay;
3788 #endif  /* IPV6 */
3789         default:
3790                 addrp = NULL;
3791                 goto okay;
3792         }
3793
3794 parse_error:
3795         printk(KERN_WARNING
3796                "SELinux: failure in selinux_parse_skb(),"
3797                " unable to parse packet\n");
3798         return ret;
3799
3800 okay:
3801         if (_addrp)
3802                 *_addrp = addrp;
3803         return 0;
3804 }
3805
3806 /**
3807  * selinux_skb_peerlbl_sid - Determine the peer label of a packet
3808  * @skb: the packet
3809  * @family: protocol family
3810  * @sid: the packet's peer label SID
3811  *
3812  * Description:
3813  * Check the various different forms of network peer labeling and determine
3814  * the peer label/SID for the packet; most of the magic actually occurs in
3815  * the security server function security_net_peersid_cmp().  The function
3816  * returns zero if the value in @sid is valid (although it may be SECSID_NULL)
3817  * or -EACCES if @sid is invalid due to inconsistencies with the different
3818  * peer labels.
3819  *
3820  */
3821 static int selinux_skb_peerlbl_sid(struct sk_buff *skb, u16 family, u32 *sid)
3822 {
3823         int err;
3824         u32 xfrm_sid;
3825         u32 nlbl_sid;
3826         u32 nlbl_type;
3827
3828         err = selinux_xfrm_skb_sid(skb, &xfrm_sid);
3829         if (unlikely(err))
3830                 return -EACCES;
3831         err = selinux_netlbl_skbuff_getsid(skb, family, &nlbl_type, &nlbl_sid);
3832         if (unlikely(err))
3833                 return -EACCES;
3834
3835         err = security_net_peersid_resolve(nlbl_sid, nlbl_type, xfrm_sid, sid);
3836         if (unlikely(err)) {
3837                 printk(KERN_WARNING
3838                        "SELinux: failure in selinux_skb_peerlbl_sid(),"
3839                        " unable to determine packet's peer label\n");
3840                 return -EACCES;
3841         }
3842
3843         return 0;
3844 }
3845
3846 /**
3847  * selinux_conn_sid - Determine the child socket label for a connection
3848  * @sk_sid: the parent socket's SID
3849  * @skb_sid: the packet's SID
3850  * @conn_sid: the resulting connection SID
3851  *
3852  * If @skb_sid is valid then the user:role:type information from @sk_sid is
3853  * combined with the MLS information from @skb_sid in order to create
3854  * @conn_sid.  If @skb_sid is not valid then then @conn_sid is simply a copy
3855  * of @sk_sid.  Returns zero on success, negative values on failure.
3856  *
3857  */
3858 static int selinux_conn_sid(u32 sk_sid, u32 skb_sid, u32 *conn_sid)
3859 {
3860         int err = 0;
3861
3862         if (skb_sid != SECSID_NULL)
3863                 err = security_sid_mls_copy(sk_sid, skb_sid, conn_sid);
3864         else
3865                 *conn_sid = sk_sid;
3866
3867         return err;
3868 }
3869
3870 /* socket security operations */
3871
3872 static int socket_sockcreate_sid(const struct task_security_struct *tsec,
3873                                  u16 secclass, u32 *socksid)
3874 {
3875         if (tsec->sockcreate_sid > SECSID_NULL) {
3876                 *socksid = tsec->sockcreate_sid;
3877                 return 0;
3878         }
3879
3880         return security_transition_sid(tsec->sid, tsec->sid, secclass, NULL,
3881                                        socksid);
3882 }
3883
3884 static int sock_has_perm(struct task_struct *task, struct sock *sk, u32 perms)
3885 {
3886         struct sk_security_struct *sksec = sk->sk_security;
3887         struct common_audit_data ad;
3888         struct lsm_network_audit net = {0,};
3889         u32 tsid = task_sid(task);
3890
3891         if (sksec->sid == SECINITSID_KERNEL)
3892                 return 0;
3893
3894         ad.type = LSM_AUDIT_DATA_NET;
3895         ad.u.net = &net;
3896         ad.u.net->sk = sk;
3897
3898         return avc_has_perm(tsid, sksec->sid, sksec->sclass, perms, &ad);
3899 }
3900
3901 static int selinux_socket_create(int family, int type,
3902                                  int protocol, int kern)
3903 {
3904         const struct task_security_struct *tsec = current_security();
3905         u32 newsid;
3906         u16 secclass;
3907         int rc;
3908
3909         if (kern)
3910                 return 0;
3911
3912         secclass = socket_type_to_security_class(family, type, protocol);
3913         rc = socket_sockcreate_sid(tsec, secclass, &newsid);
3914         if (rc)
3915                 return rc;
3916
3917         return avc_has_perm(tsec->sid, newsid, secclass, SOCKET__CREATE, NULL);
3918 }
3919
3920 static int selinux_socket_post_create(struct socket *sock, int family,
3921                                       int type, int protocol, int kern)
3922 {
3923         const struct task_security_struct *tsec = current_security();
3924         struct inode_security_struct *isec = SOCK_INODE(sock)->i_security;
3925         struct sk_security_struct *sksec;
3926         int err = 0;
3927
3928         isec->sclass = socket_type_to_security_class(family, type, protocol);
3929
3930         if (kern)
3931                 isec->sid = SECINITSID_KERNEL;
3932         else {
3933                 err = socket_sockcreate_sid(tsec, isec->sclass, &(isec->sid));
3934                 if (err)
3935                         return err;
3936         }
3937
3938         isec->initialized = 1;
3939
3940         if (sock->sk) {
3941                 sksec = sock->sk->sk_security;
3942                 sksec->sid = isec->sid;
3943                 sksec->sclass = isec->sclass;
3944                 err = selinux_netlbl_socket_post_create(sock->sk, family);
3945         }
3946
3947         return err;
3948 }
3949
3950 /* Range of port numbers used to automatically bind.
3951    Need to determine whether we should perform a name_bind
3952    permission check between the socket and the port number. */
3953
3954 static int selinux_socket_bind(struct socket *sock, struct sockaddr *address, int addrlen)
3955 {
3956         struct sock *sk = sock->sk;
3957         u16 family;
3958         int err;
3959
3960         err = sock_has_perm(current, sk, SOCKET__BIND);
3961         if (err)
3962                 goto out;
3963
3964         /*
3965          * If PF_INET or PF_INET6, check name_bind permission for the port.
3966          * Multiple address binding for SCTP is not supported yet: we just
3967          * check the first address now.
3968          */
3969         family = sk->sk_family;
3970         if (family == PF_INET || family == PF_INET6) {
3971                 char *addrp;
3972                 struct sk_security_struct *sksec = sk->sk_security;
3973                 struct common_audit_data ad;
3974                 struct lsm_network_audit net = {0,};
3975                 struct sockaddr_in *addr4 = NULL;
3976                 struct sockaddr_in6 *addr6 = NULL;
3977                 unsigned short snum;
3978                 u32 sid, node_perm;
3979
3980                 if (family == PF_INET) {
3981                         addr4 = (struct sockaddr_in *)address;
3982                         snum = ntohs(addr4->sin_port);
3983                         addrp = (char *)&addr4->sin_addr.s_addr;
3984                 } else {
3985                         addr6 = (struct sockaddr_in6 *)address;
3986                         snum = ntohs(addr6->sin6_port);
3987                         addrp = (char *)&addr6->sin6_addr.s6_addr;
3988                 }
3989
3990                 if (snum) {
3991                         int low, high;
3992
3993                         inet_get_local_port_range(sock_net(sk), &low, &high);
3994
3995                         if (snum < max(PROT_SOCK, low) || snum > high) {
3996                                 err = sel_netport_sid(sk->sk_protocol,
3997                                                       snum, &sid);
3998                                 if (err)
3999                                         goto out;
4000                                 ad.type = LSM_AUDIT_DATA_NET;
4001                                 ad.u.net = &net;
4002                                 ad.u.net->sport = htons(snum);
4003                                 ad.u.net->family = family;
4004                                 err = avc_has_perm(sksec->sid, sid,
4005                                                    sksec->sclass,
4006                                                    SOCKET__NAME_BIND, &ad);
4007                                 if (err)
4008                                         goto out;
4009                         }
4010                 }
4011
4012                 switch (sksec->sclass) {
4013                 case SECCLASS_TCP_SOCKET:
4014                         node_perm = TCP_SOCKET__NODE_BIND;
4015                         break;
4016
4017                 case SECCLASS_UDP_SOCKET:
4018                         node_perm = UDP_SOCKET__NODE_BIND;
4019                         break;
4020
4021                 case SECCLASS_DCCP_SOCKET:
4022                         node_perm = DCCP_SOCKET__NODE_BIND;
4023                         break;
4024
4025                 default:
4026                         node_perm = RAWIP_SOCKET__NODE_BIND;
4027                         break;
4028                 }
4029
4030                 err = sel_netnode_sid(addrp, family, &sid);
4031                 if (err)
4032                         goto out;
4033
4034                 ad.type = LSM_AUDIT_DATA_NET;
4035                 ad.u.net = &net;
4036                 ad.u.net->sport = htons(snum);
4037                 ad.u.net->family = family;
4038
4039                 if (family == PF_INET)
4040                         ad.u.net->v4info.saddr = addr4->sin_addr.s_addr;
4041                 else
4042                         ad.u.net->v6info.saddr = addr6->sin6_addr;
4043
4044                 err = avc_has_perm(sksec->sid, sid,
4045                                    sksec->sclass, node_perm, &ad);
4046                 if (err)
4047                         goto out;
4048         }
4049 out:
4050         return err;
4051 }
4052
4053 static int selinux_socket_connect(struct socket *sock, struct sockaddr *address, int addrlen)
4054 {
4055         struct sock *sk = sock->sk;
4056         struct sk_security_struct *sksec = sk->sk_security;
4057         int err;
4058
4059         err = sock_has_perm(current, sk, SOCKET__CONNECT);
4060         if (err)
4061                 return err;
4062
4063         /*
4064          * If a TCP or DCCP socket, check name_connect permission for the port.
4065          */
4066         if (sksec->sclass == SECCLASS_TCP_SOCKET ||
4067             sksec->sclass == SECCLASS_DCCP_SOCKET) {
4068                 struct common_audit_data ad;
4069                 struct lsm_network_audit net = {0,};
4070                 struct sockaddr_in *addr4 = NULL;
4071                 struct sockaddr_in6 *addr6 = NULL;
4072                 unsigned short snum;
4073                 u32 sid, perm;
4074
4075                 if (sk->sk_family == PF_INET) {
4076                         addr4 = (struct sockaddr_in *)address;
4077                         if (addrlen < sizeof(struct sockaddr_in))
4078                                 return -EINVAL;
4079                         snum = ntohs(addr4->sin_port);
4080                 } else {
4081                         addr6 = (struct sockaddr_in6 *)address;
4082                         if (addrlen < SIN6_LEN_RFC2133)
4083                                 return -EINVAL;
4084                         snum = ntohs(addr6->sin6_port);
4085                 }
4086
4087                 err = sel_netport_sid(sk->sk_protocol, snum, &sid);
4088                 if (err)
4089                         goto out;
4090
4091                 perm = (sksec->sclass == SECCLASS_TCP_SOCKET) ?
4092                        TCP_SOCKET__NAME_CONNECT : DCCP_SOCKET__NAME_CONNECT;
4093
4094                 ad.type = LSM_AUDIT_DATA_NET;
4095                 ad.u.net = &net;
4096                 ad.u.net->dport = htons(snum);
4097                 ad.u.net->family = sk->sk_family;
4098                 err = avc_has_perm(sksec->sid, sid, sksec->sclass, perm, &ad);
4099                 if (err)
4100                         goto out;
4101         }
4102
4103         err = selinux_netlbl_socket_connect(sk, address);
4104
4105 out:
4106         return err;
4107 }
4108
4109 static int selinux_socket_listen(struct socket *sock, int backlog)
4110 {
4111         return sock_has_perm(current, sock->sk, SOCKET__LISTEN);
4112 }
4113
4114 static int selinux_socket_accept(struct socket *sock, struct socket *newsock)
4115 {
4116         int err;
4117         struct inode_security_struct *isec;
4118         struct inode_security_struct *newisec;
4119
4120         err = sock_has_perm(current, sock->sk, SOCKET__ACCEPT);
4121         if (err)
4122                 return err;
4123
4124         newisec = SOCK_INODE(newsock)->i_security;
4125
4126         isec = SOCK_INODE(sock)->i_security;
4127         newisec->sclass = isec->sclass;
4128         newisec->sid = isec->sid;
4129         newisec->initialized = 1;
4130
4131         return 0;
4132 }
4133
4134 static int selinux_socket_sendmsg(struct socket *sock, struct msghdr *msg,
4135                                   int size)
4136 {
4137         return sock_has_perm(current, sock->sk, SOCKET__WRITE);
4138 }
4139
4140 static int selinux_socket_recvmsg(struct socket *sock, struct msghdr *msg,
4141                                   int size, int flags)
4142 {
4143         return sock_has_perm(current, sock->sk, SOCKET__READ);
4144 }
4145
4146 static int selinux_socket_getsockname(struct socket *sock)
4147 {
4148         return sock_has_perm(current, sock->sk, SOCKET__GETATTR);
4149 }
4150
4151 static int selinux_socket_getpeername(struct socket *sock)
4152 {
4153         return sock_has_perm(current, sock->sk, SOCKET__GETATTR);
4154 }
4155
4156 static int selinux_socket_setsockopt(struct socket *sock, int level, int optname)
4157 {
4158         int err;
4159
4160         err = sock_has_perm(current, sock->sk, SOCKET__SETOPT);
4161         if (err)
4162                 return err;
4163
4164         return selinux_netlbl_socket_setsockopt(sock, level, optname);
4165 }
4166
4167 static int selinux_socket_getsockopt(struct socket *sock, int level,
4168                                      int optname)
4169 {
4170         return sock_has_perm(current, sock->sk, SOCKET__GETOPT);
4171 }
4172
4173 static int selinux_socket_shutdown(struct socket *sock, int how)
4174 {
4175         return sock_has_perm(current, sock->sk, SOCKET__SHUTDOWN);
4176 }
4177
4178 static int selinux_socket_unix_stream_connect(struct sock *sock,
4179                                               struct sock *other,
4180                                               struct sock *newsk)
4181 {
4182         struct sk_security_struct *sksec_sock = sock->sk_security;
4183         struct sk_security_struct *sksec_other = other->sk_security;
4184         struct sk_security_struct *sksec_new = newsk->sk_security;
4185         struct common_audit_data ad;
4186         struct lsm_network_audit net = {0,};
4187         int err;
4188
4189         ad.type = LSM_AUDIT_DATA_NET;
4190         ad.u.net = &net;
4191         ad.u.net->sk = other;
4192
4193         err = avc_has_perm(sksec_sock->sid, sksec_other->sid,
4194                            sksec_other->sclass,
4195                            UNIX_STREAM_SOCKET__CONNECTTO, &ad);
4196         if (err)
4197                 return err;
4198
4199         /* server child socket */
4200         sksec_new->peer_sid = sksec_sock->sid;
4201         err = security_sid_mls_copy(sksec_other->sid, sksec_sock->sid,
4202                                     &sksec_new->sid);
4203         if (err)
4204                 return err;
4205
4206         /* connecting socket */
4207         sksec_sock->peer_sid = sksec_new->sid;
4208
4209         return 0;
4210 }
4211
4212 static int selinux_socket_unix_may_send(struct socket *sock,
4213                                         struct socket *other)
4214 {
4215         struct sk_security_struct *ssec = sock->sk->sk_security;
4216         struct sk_security_struct *osec = other->sk->sk_security;
4217         struct common_audit_data ad;
4218         struct lsm_network_audit net = {0,};
4219
4220         ad.type = LSM_AUDIT_DATA_NET;
4221         ad.u.net = &net;
4222         ad.u.net->sk = other->sk;
4223
4224         return avc_has_perm(ssec->sid, osec->sid, osec->sclass, SOCKET__SENDTO,
4225                             &ad);
4226 }
4227
4228 static int selinux_inet_sys_rcv_skb(int ifindex, char *addrp, u16 family,
4229                                     u32 peer_sid,
4230                                     struct common_audit_data *ad)
4231 {
4232         int err;
4233         u32 if_sid;
4234         u32 node_sid;
4235
4236         err = sel_netif_sid(ifindex, &if_sid);
4237         if (err)
4238                 return err;
4239         err = avc_has_perm(peer_sid, if_sid,
4240                            SECCLASS_NETIF, NETIF__INGRESS, ad);
4241         if (err)
4242                 return err;
4243
4244         err = sel_netnode_sid(addrp, family, &node_sid);
4245         if (err)
4246                 return err;
4247         return avc_has_perm(peer_sid, node_sid,
4248                             SECCLASS_NODE, NODE__RECVFROM, ad);
4249 }
4250
4251 static int selinux_sock_rcv_skb_compat(struct sock *sk, struct sk_buff *skb,
4252                                        u16 family)
4253 {
4254         int err = 0;
4255         struct sk_security_struct *sksec = sk->sk_security;
4256         u32 sk_sid = sksec->sid;
4257         struct common_audit_data ad;
4258         struct lsm_network_audit net = {0,};
4259         char *addrp;
4260
4261         ad.type = LSM_AUDIT_DATA_NET;
4262         ad.u.net = &net;
4263         ad.u.net->netif = skb->skb_iif;
4264         ad.u.net->family = family;
4265         err = selinux_parse_skb(skb, &ad, &addrp, 1, NULL);
4266         if (err)
4267                 return err;
4268
4269         if (selinux_secmark_enabled()) {
4270                 err = avc_has_perm(sk_sid, skb->secmark, SECCLASS_PACKET,
4271                                    PACKET__RECV, &ad);
4272                 if (err)
4273                         return err;
4274         }
4275
4276         err = selinux_netlbl_sock_rcv_skb(sksec, skb, family, &ad);
4277         if (err)
4278                 return err;
4279         err = selinux_xfrm_sock_rcv_skb(sksec->sid, skb, &ad);
4280
4281         return err;
4282 }
4283
4284 static int selinux_socket_sock_rcv_skb(struct sock *sk, struct sk_buff *skb)
4285 {
4286         int err;
4287         struct sk_security_struct *sksec = sk->sk_security;
4288         u16 family = sk->sk_family;
4289         u32 sk_sid = sksec->sid;
4290         struct common_audit_data ad;
4291         struct lsm_network_audit net = {0,};
4292         char *addrp;
4293         u8 secmark_active;
4294         u8 peerlbl_active;
4295
4296         if (family != PF_INET && family != PF_INET6)
4297                 return 0;
4298
4299         /* Handle mapped IPv4 packets arriving via IPv6 sockets */
4300         if (family == PF_INET6 && skb->protocol == htons(ETH_P_IP))
4301                 family = PF_INET;
4302
4303         /* If any sort of compatibility mode is enabled then handoff processing
4304          * to the selinux_sock_rcv_skb_compat() function to deal with the
4305          * special handling.  We do this in an attempt to keep this function
4306          * as fast and as clean as possible. */
4307         if (!selinux_policycap_netpeer)
4308                 return selinux_sock_rcv_skb_compat(sk, skb, family);
4309
4310         secmark_active = selinux_secmark_enabled();
4311         peerlbl_active = selinux_peerlbl_enabled();
4312         if (!secmark_active && !peerlbl_active)
4313                 return 0;
4314
4315         ad.type = LSM_AUDIT_DATA_NET;
4316         ad.u.net = &net;
4317         ad.u.net->netif = skb->skb_iif;
4318         ad.u.net->family = family;
4319         err = selinux_parse_skb(skb, &ad, &addrp, 1, NULL);
4320         if (err)
4321                 return err;
4322
4323         if (peerlbl_active) {
4324                 u32 peer_sid;
4325
4326                 err = selinux_skb_peerlbl_sid(skb, family, &peer_sid);
4327                 if (err)
4328                         return err;
4329                 err = selinux_inet_sys_rcv_skb(skb->skb_iif, addrp, family,
4330                                                peer_sid, &ad);
4331                 if (err) {
4332                         selinux_netlbl_err(skb, err, 0);
4333                         return err;
4334                 }
4335                 err = avc_has_perm(sk_sid, peer_sid, SECCLASS_PEER,
4336                                    PEER__RECV, &ad);
4337                 if (err) {
4338                         selinux_netlbl_err(skb, err, 0);
4339                         return err;
4340                 }
4341         }
4342
4343         if (secmark_active) {
4344                 err = avc_has_perm(sk_sid, skb->secmark, SECCLASS_PACKET,
4345                                    PACKET__RECV, &ad);
4346                 if (err)
4347                         return err;
4348         }
4349
4350         return err;
4351 }
4352
4353 static int selinux_socket_getpeersec_stream(struct socket *sock, char __user *optval,
4354                                             int __user *optlen, unsigned len)
4355 {
4356         int err = 0;
4357         char *scontext;
4358         u32 scontext_len;
4359         struct sk_security_struct *sksec = sock->sk->sk_security;
4360         u32 peer_sid = SECSID_NULL;
4361
4362         if (sksec->sclass == SECCLASS_UNIX_STREAM_SOCKET ||
4363             sksec->sclass == SECCLASS_TCP_SOCKET)
4364                 peer_sid = sksec->peer_sid;
4365         if (peer_sid == SECSID_NULL)
4366                 return -ENOPROTOOPT;
4367
4368         err = security_sid_to_context(peer_sid, &scontext, &scontext_len);
4369         if (err)
4370                 return err;
4371
4372         if (scontext_len > len) {
4373                 err = -ERANGE;
4374                 goto out_len;
4375         }
4376
4377         if (copy_to_user(optval, scontext, scontext_len))
4378                 err = -EFAULT;
4379
4380 out_len:
4381         if (put_user(scontext_len, optlen))
4382                 err = -EFAULT;
4383         kfree(scontext);
4384         return err;
4385 }
4386
4387 static int selinux_socket_getpeersec_dgram(struct socket *sock, struct sk_buff *skb, u32 *secid)
4388 {
4389         u32 peer_secid = SECSID_NULL;
4390         u16 family;
4391
4392         if (skb && skb->protocol == htons(ETH_P_IP))
4393                 family = PF_INET;
4394         else if (skb && skb->protocol == htons(ETH_P_IPV6))
4395                 family = PF_INET6;
4396         else if (sock)
4397                 family = sock->sk->sk_family;
4398         else
4399                 goto out;
4400
4401         if (sock && family == PF_UNIX)
4402                 selinux_inode_getsecid(SOCK_INODE(sock), &peer_secid);
4403         else if (skb)
4404                 selinux_skb_peerlbl_sid(skb, family, &peer_secid);
4405
4406 out:
4407         *secid = peer_secid;
4408         if (peer_secid == SECSID_NULL)
4409                 return -EINVAL;
4410         return 0;
4411 }
4412
4413 static int selinux_sk_alloc_security(struct sock *sk, int family, gfp_t priority)
4414 {
4415         struct sk_security_struct *sksec;
4416
4417         sksec = kzalloc(sizeof(*sksec), priority);
4418         if (!sksec)
4419                 return -ENOMEM;
4420
4421         sksec->peer_sid = SECINITSID_UNLABELED;
4422         sksec->sid = SECINITSID_UNLABELED;
4423         selinux_netlbl_sk_security_reset(sksec);
4424         sk->sk_security = sksec;
4425
4426         return 0;
4427 }
4428
4429 static void selinux_sk_free_security(struct sock *sk)
4430 {
4431         struct sk_security_struct *sksec = sk->sk_security;
4432
4433         sk->sk_security = NULL;
4434         selinux_netlbl_sk_security_free(sksec);
4435         kfree(sksec);
4436 }
4437
4438 static void selinux_sk_clone_security(const struct sock *sk, struct sock *newsk)
4439 {
4440         struct sk_security_struct *sksec = sk->sk_security;
4441         struct sk_security_struct *newsksec = newsk->sk_security;
4442
4443         newsksec->sid = sksec->sid;
4444         newsksec->peer_sid = sksec->peer_sid;
4445         newsksec->sclass = sksec->sclass;
4446
4447         selinux_netlbl_sk_security_reset(newsksec);
4448 }
4449
4450 static void selinux_sk_getsecid(struct sock *sk, u32 *secid)
4451 {
4452         if (!sk)
4453                 *secid = SECINITSID_ANY_SOCKET;
4454         else {
4455                 struct sk_security_struct *sksec = sk->sk_security;
4456
4457                 *secid = sksec->sid;
4458         }
4459 }
4460
4461 static void selinux_sock_graft(struct sock *sk, struct socket *parent)
4462 {
4463         struct inode_security_struct *isec = SOCK_INODE(parent)->i_security;
4464         struct sk_security_struct *sksec = sk->sk_security;
4465
4466         if (sk->sk_family == PF_INET || sk->sk_family == PF_INET6 ||
4467             sk->sk_family == PF_UNIX)
4468                 isec->sid = sksec->sid;
4469         sksec->sclass = isec->sclass;
4470 }
4471
4472 static int selinux_inet_conn_request(struct sock *sk, struct sk_buff *skb,
4473                                      struct request_sock *req)
4474 {
4475         struct sk_security_struct *sksec = sk->sk_security;
4476         int err;
4477         u16 family = sk->sk_family;
4478         u32 connsid;
4479         u32 peersid;
4480
4481         /* handle mapped IPv4 packets arriving via IPv6 sockets */
4482         if (family == PF_INET6 && skb->protocol == htons(ETH_P_IP))
4483                 family = PF_INET;
4484
4485         err = selinux_skb_peerlbl_sid(skb, family, &peersid);
4486         if (err)
4487                 return err;
4488         err = selinux_conn_sid(sksec->sid, peersid, &connsid);
4489         if (err)
4490                 return err;
4491         req->secid = connsid;
4492         req->peer_secid = peersid;
4493
4494         return selinux_netlbl_inet_conn_request(req, family);
4495 }
4496
4497 static void selinux_inet_csk_clone(struct sock *newsk,
4498                                    const struct request_sock *req)
4499 {
4500         struct sk_security_struct *newsksec = newsk->sk_security;
4501
4502         newsksec->sid = req->secid;
4503         newsksec->peer_sid = req->peer_secid;
4504         /* NOTE: Ideally, we should also get the isec->sid for the
4505            new socket in sync, but we don't have the isec available yet.
4506            So we will wait until sock_graft to do it, by which
4507            time it will have been created and available. */
4508
4509         /* We don't need to take any sort of lock here as we are the only
4510          * thread with access to newsksec */
4511         selinux_netlbl_inet_csk_clone(newsk, req->rsk_ops->family);
4512 }
4513
4514 static void selinux_inet_conn_established(struct sock *sk, struct sk_buff *skb)
4515 {
4516         u16 family = sk->sk_family;
4517         struct sk_security_struct *sksec = sk->sk_security;
4518
4519         /* handle mapped IPv4 packets arriving via IPv6 sockets */
4520         if (family == PF_INET6 && skb->protocol == htons(ETH_P_IP))
4521                 family = PF_INET;
4522
4523         selinux_skb_peerlbl_sid(skb, family, &sksec->peer_sid);
4524 }
4525
4526 static void selinux_skb_owned_by(struct sk_buff *skb, struct sock *sk)
4527 {
4528         skb_set_owner_w(skb, sk);
4529 }
4530
4531 static int selinux_secmark_relabel_packet(u32 sid)
4532 {
4533         const struct task_security_struct *__tsec;
4534         u32 tsid;
4535
4536         __tsec = current_security();
4537         tsid = __tsec->sid;
4538
4539         return avc_has_perm(tsid, sid, SECCLASS_PACKET, PACKET__RELABELTO, NULL);
4540 }
4541
4542 static void selinux_secmark_refcount_inc(void)
4543 {
4544         atomic_inc(&selinux_secmark_refcount);
4545 }
4546
4547 static void selinux_secmark_refcount_dec(void)
4548 {
4549         atomic_dec(&selinux_secmark_refcount);
4550 }
4551
4552 static void selinux_req_classify_flow(const struct request_sock *req,
4553                                       struct flowi *fl)
4554 {
4555         fl->flowi_secid = req->secid;
4556 }
4557
4558 static int selinux_tun_dev_alloc_security(void **security)
4559 {
4560         struct tun_security_struct *tunsec;
4561
4562         tunsec = kzalloc(sizeof(*tunsec), GFP_KERNEL);
4563         if (!tunsec)
4564                 return -ENOMEM;
4565         tunsec->sid = current_sid();
4566
4567         *security = tunsec;
4568         return 0;
4569 }
4570
4571 static void selinux_tun_dev_free_security(void *security)
4572 {
4573         kfree(security);
4574 }
4575
4576 static int selinux_tun_dev_create(void)
4577 {
4578         u32 sid = current_sid();
4579
4580         /* we aren't taking into account the "sockcreate" SID since the socket
4581          * that is being created here is not a socket in the traditional sense,
4582          * instead it is a private sock, accessible only to the kernel, and
4583          * representing a wide range of network traffic spanning multiple
4584          * connections unlike traditional sockets - check the TUN driver to
4585          * get a better understanding of why this socket is special */
4586
4587         return avc_has_perm(sid, sid, SECCLASS_TUN_SOCKET, TUN_SOCKET__CREATE,
4588                             NULL);
4589 }
4590
4591 static int selinux_tun_dev_attach_queue(void *security)
4592 {
4593         struct tun_security_struct *tunsec = security;
4594
4595         return avc_has_perm(current_sid(), tunsec->sid, SECCLASS_TUN_SOCKET,
4596                             TUN_SOCKET__ATTACH_QUEUE, NULL);
4597 }
4598
4599 static int selinux_tun_dev_attach(struct sock *sk, void *security)
4600 {
4601         struct tun_security_struct *tunsec = security;
4602         struct sk_security_struct *sksec = sk->sk_security;
4603
4604         /* we don't currently perform any NetLabel based labeling here and it
4605          * isn't clear that we would want to do so anyway; while we could apply
4606          * labeling without the support of the TUN user the resulting labeled
4607          * traffic from the other end of the connection would almost certainly
4608          * cause confusion to the TUN user that had no idea network labeling
4609          * protocols were being used */
4610
4611         sksec->sid = tunsec->sid;
4612         sksec->sclass = SECCLASS_TUN_SOCKET;
4613
4614         return 0;
4615 }
4616
4617 static int selinux_tun_dev_open(void *security)
4618 {
4619         struct tun_security_struct *tunsec = security;
4620         u32 sid = current_sid();
4621         int err;
4622
4623         err = avc_has_perm(sid, tunsec->sid, SECCLASS_TUN_SOCKET,
4624                            TUN_SOCKET__RELABELFROM, NULL);
4625         if (err)
4626                 return err;
4627         err = avc_has_perm(sid, sid, SECCLASS_TUN_SOCKET,
4628                            TUN_SOCKET__RELABELTO, NULL);
4629         if (err)
4630                 return err;
4631         tunsec->sid = sid;
4632
4633         return 0;
4634 }
4635
4636 static int selinux_nlmsg_perm(struct sock *sk, struct sk_buff *skb)
4637 {
4638         int err = 0;
4639         u32 perm;
4640         struct nlmsghdr *nlh;
4641         struct sk_security_struct *sksec = sk->sk_security;
4642
4643         if (skb->len < NLMSG_HDRLEN) {
4644                 err = -EINVAL;
4645                 goto out;
4646         }
4647         nlh = nlmsg_hdr(skb);
4648
4649         err = selinux_nlmsg_lookup(sksec->sclass, nlh->nlmsg_type, &perm);
4650         if (err) {
4651                 if (err == -EINVAL) {
4652                         audit_log(current->audit_context, GFP_KERNEL, AUDIT_SELINUX_ERR,
4653                                   "SELinux:  unrecognized netlink message"
4654                                   " type=%hu for sclass=%hu\n",
4655                                   nlh->nlmsg_type, sksec->sclass);
4656                         if (!selinux_enforcing || security_get_allow_unknown())
4657                                 err = 0;
4658                 }
4659
4660                 /* Ignore */
4661                 if (err == -ENOENT)
4662                         err = 0;
4663                 goto out;
4664         }
4665
4666         err = sock_has_perm(current, sk, perm);
4667 out:
4668         return err;
4669 }
4670
4671 #ifdef CONFIG_NETFILTER
4672
4673 static unsigned int selinux_ip_forward(struct sk_buff *skb, int ifindex,
4674                                        u16 family)
4675 {
4676         int err;
4677         char *addrp;
4678         u32 peer_sid;
4679         struct common_audit_data ad;
4680         struct lsm_network_audit net = {0,};
4681         u8 secmark_active;
4682         u8 netlbl_active;
4683         u8 peerlbl_active;
4684
4685         if (!selinux_policycap_netpeer)
4686                 return NF_ACCEPT;
4687
4688         secmark_active = selinux_secmark_enabled();
4689         netlbl_active = netlbl_enabled();
4690         peerlbl_active = selinux_peerlbl_enabled();
4691         if (!secmark_active && !peerlbl_active)
4692                 return NF_ACCEPT;
4693
4694         if (selinux_skb_peerlbl_sid(skb, family, &peer_sid) != 0)
4695                 return NF_DROP;
4696
4697         ad.type = LSM_AUDIT_DATA_NET;
4698         ad.u.net = &net;
4699         ad.u.net->netif = ifindex;
4700         ad.u.net->family = family;
4701         if (selinux_parse_skb(skb, &ad, &addrp, 1, NULL) != 0)
4702                 return NF_DROP;
4703
4704         if (peerlbl_active) {
4705                 err = selinux_inet_sys_rcv_skb(ifindex, addrp, family,
4706                                                peer_sid, &ad);
4707                 if (err) {
4708                         selinux_netlbl_err(skb, err, 1);
4709                         return NF_DROP;
4710                 }
4711         }
4712
4713         if (secmark_active)
4714                 if (avc_has_perm(peer_sid, skb->secmark,
4715                                  SECCLASS_PACKET, PACKET__FORWARD_IN, &ad))
4716                         return NF_DROP;
4717
4718         if (netlbl_active)
4719                 /* we do this in the FORWARD path and not the POST_ROUTING
4720                  * path because we want to make sure we apply the necessary
4721                  * labeling before IPsec is applied so we can leverage AH
4722                  * protection */
4723                 if (selinux_netlbl_skbuff_setsid(skb, family, peer_sid) != 0)
4724                         return NF_DROP;
4725
4726         return NF_ACCEPT;
4727 }
4728
4729 static unsigned int selinux_ipv4_forward(const struct nf_hook_ops *ops,
4730                                          struct sk_buff *skb,
4731                                          const struct net_device *in,
4732                                          const struct net_device *out,
4733                                          int (*okfn)(struct sk_buff *))
4734 {
4735         return selinux_ip_forward(skb, in->ifindex, PF_INET);
4736 }
4737
4738 #if defined(CONFIG_IPV6) || defined(CONFIG_IPV6_MODULE)
4739 static unsigned int selinux_ipv6_forward(const struct nf_hook_ops *ops,
4740                                          struct sk_buff *skb,
4741                                          const struct net_device *in,
4742                                          const struct net_device *out,
4743                                          int (*okfn)(struct sk_buff *))
4744 {
4745         return selinux_ip_forward(skb, in->ifindex, PF_INET6);
4746 }
4747 #endif  /* IPV6 */
4748
4749 static unsigned int selinux_ip_output(struct sk_buff *skb,
4750                                       u16 family)
4751 {
4752         struct sock *sk;
4753         u32 sid;
4754
4755         if (!netlbl_enabled())
4756                 return NF_ACCEPT;
4757
4758         /* we do this in the LOCAL_OUT path and not the POST_ROUTING path
4759          * because we want to make sure we apply the necessary labeling
4760          * before IPsec is applied so we can leverage AH protection */
4761         sk = skb->sk;
4762         if (sk) {
4763                 struct sk_security_struct *sksec;
4764
4765                 if (sk->sk_state == TCP_LISTEN)
4766                         /* if the socket is the listening state then this
4767                          * packet is a SYN-ACK packet which means it needs to
4768                          * be labeled based on the connection/request_sock and
4769                          * not the parent socket.  unfortunately, we can't
4770                          * lookup the request_sock yet as it isn't queued on
4771                          * the parent socket until after the SYN-ACK is sent.
4772                          * the "solution" is to simply pass the packet as-is
4773                          * as any IP option based labeling should be copied
4774                          * from the initial connection request (in the IP
4775                          * layer).  it is far from ideal, but until we get a
4776                          * security label in the packet itself this is the
4777                          * best we can do. */
4778                         return NF_ACCEPT;
4779
4780                 /* standard practice, label using the parent socket */
4781                 sksec = sk->sk_security;
4782                 sid = sksec->sid;
4783         } else
4784                 sid = SECINITSID_KERNEL;
4785         if (selinux_netlbl_skbuff_setsid(skb, family, sid) != 0)
4786                 return NF_DROP;
4787
4788         return NF_ACCEPT;
4789 }
4790
4791 static unsigned int selinux_ipv4_output(const struct nf_hook_ops *ops,
4792                                         struct sk_buff *skb,
4793                                         const struct net_device *in,
4794                                         const struct net_device *out,
4795                                         int (*okfn)(struct sk_buff *))
4796 {
4797         return selinux_ip_output(skb, PF_INET);
4798 }
4799
4800 static unsigned int selinux_ip_postroute_compat(struct sk_buff *skb,
4801                                                 int ifindex,
4802                                                 u16 family)
4803 {
4804         struct sock *sk = skb->sk;
4805         struct sk_security_struct *sksec;
4806         struct common_audit_data ad;
4807         struct lsm_network_audit net = {0,};
4808         char *addrp;
4809         u8 proto;
4810
4811         if (sk == NULL)
4812                 return NF_ACCEPT;
4813         sksec = sk->sk_security;
4814
4815         ad.type = LSM_AUDIT_DATA_NET;
4816         ad.u.net = &net;
4817         ad.u.net->netif = ifindex;
4818         ad.u.net->family = family;
4819         if (selinux_parse_skb(skb, &ad, &addrp, 0, &proto))
4820                 return NF_DROP;
4821
4822         if (selinux_secmark_enabled())
4823                 if (avc_has_perm(sksec->sid, skb->secmark,
4824                                  SECCLASS_PACKET, PACKET__SEND, &ad))
4825                         return NF_DROP_ERR(-ECONNREFUSED);
4826
4827         if (selinux_xfrm_postroute_last(sksec->sid, skb, &ad, proto))
4828                 return NF_DROP_ERR(-ECONNREFUSED);
4829
4830         return NF_ACCEPT;
4831 }
4832
4833 static unsigned int selinux_ip_postroute(struct sk_buff *skb, int ifindex,
4834                                          u16 family)
4835 {
4836         u32 secmark_perm;
4837         u32 peer_sid;
4838         struct sock *sk;
4839         struct common_audit_data ad;
4840         struct lsm_network_audit net = {0,};
4841         char *addrp;
4842         u8 secmark_active;
4843         u8 peerlbl_active;
4844
4845         /* If any sort of compatibility mode is enabled then handoff processing
4846          * to the selinux_ip_postroute_compat() function to deal with the
4847          * special handling.  We do this in an attempt to keep this function
4848          * as fast and as clean as possible. */
4849         if (!selinux_policycap_netpeer)
4850                 return selinux_ip_postroute_compat(skb, ifindex, family);
4851
4852         secmark_active = selinux_secmark_enabled();
4853         peerlbl_active = selinux_peerlbl_enabled();
4854         if (!secmark_active && !peerlbl_active)
4855                 return NF_ACCEPT;
4856
4857         sk = skb->sk;
4858
4859 #ifdef CONFIG_XFRM
4860         /* If skb->dst->xfrm is non-NULL then the packet is undergoing an IPsec
4861          * packet transformation so allow the packet to pass without any checks
4862          * since we'll have another chance to perform access control checks
4863          * when the packet is on it's final way out.
4864          * NOTE: there appear to be some IPv6 multicast cases where skb->dst
4865          *       is NULL, in this case go ahead and apply access control.
4866          * NOTE: if this is a local socket (skb->sk != NULL) that is in the
4867          *       TCP listening state we cannot wait until the XFRM processing
4868          *       is done as we will miss out on the SA label if we do;
4869          *       unfortunately, this means more work, but it is only once per
4870          *       connection. */
4871         if (skb_dst(skb) != NULL && skb_dst(skb)->xfrm != NULL &&
4872             !(sk != NULL && sk->sk_state == TCP_LISTEN))
4873                 return NF_ACCEPT;
4874 #endif
4875
4876         if (sk == NULL) {
4877                 /* Without an associated socket the packet is either coming
4878                  * from the kernel or it is being forwarded; check the packet
4879                  * to determine which and if the packet is being forwarded
4880                  * query the packet directly to determine the security label. */
4881                 if (skb->skb_iif) {
4882                         secmark_perm = PACKET__FORWARD_OUT;
4883                         if (selinux_skb_peerlbl_sid(skb, family, &peer_sid))
4884                                 return NF_DROP;
4885                 } else {
4886                         secmark_perm = PACKET__SEND;
4887                         peer_sid = SECINITSID_KERNEL;
4888                 }
4889         } else if (sk->sk_state == TCP_LISTEN) {
4890                 /* Locally generated packet but the associated socket is in the
4891                  * listening state which means this is a SYN-ACK packet.  In
4892                  * this particular case the correct security label is assigned
4893                  * to the connection/request_sock but unfortunately we can't
4894                  * query the request_sock as it isn't queued on the parent
4895                  * socket until after the SYN-ACK packet is sent; the only
4896                  * viable choice is to regenerate the label like we do in
4897                  * selinux_inet_conn_request().  See also selinux_ip_output()
4898                  * for similar problems. */
4899                 u32 skb_sid;
4900                 struct sk_security_struct *sksec = sk->sk_security;
4901                 if (selinux_skb_peerlbl_sid(skb, family, &skb_sid))
4902                         return NF_DROP;
4903                 /* At this point, if the returned skb peerlbl is SECSID_NULL
4904                  * and the packet has been through at least one XFRM
4905                  * transformation then we must be dealing with the "final"
4906                  * form of labeled IPsec packet; since we've already applied
4907                  * all of our access controls on this packet we can safely
4908                  * pass the packet. */
4909                 if (skb_sid == SECSID_NULL) {
4910                         switch (family) {
4911                         case PF_INET:
4912                                 if (IPCB(skb)->flags & IPSKB_XFRM_TRANSFORMED)
4913                                         return NF_ACCEPT;
4914                                 break;
4915                         case PF_INET6:
4916                                 if (IP6CB(skb)->flags & IP6SKB_XFRM_TRANSFORMED)
4917                                         return NF_ACCEPT;
4918                         default:
4919                                 return NF_DROP_ERR(-ECONNREFUSED);
4920                         }
4921                 }
4922                 if (selinux_conn_sid(sksec->sid, skb_sid, &peer_sid))
4923                         return NF_DROP;
4924                 secmark_perm = PACKET__SEND;
4925         } else {
4926                 /* Locally generated packet, fetch the security label from the
4927                  * associated socket. */
4928                 struct sk_security_struct *sksec = sk->sk_security;
4929                 peer_sid = sksec->sid;
4930                 secmark_perm = PACKET__SEND;
4931         }
4932
4933         ad.type = LSM_AUDIT_DATA_NET;
4934         ad.u.net = &net;
4935         ad.u.net->netif = ifindex;
4936         ad.u.net->family = family;
4937         if (selinux_parse_skb(skb, &ad, &addrp, 0, NULL))
4938                 return NF_DROP;
4939
4940         if (secmark_active)
4941                 if (avc_has_perm(peer_sid, skb->secmark,
4942                                  SECCLASS_PACKET, secmark_perm, &ad))
4943                         return NF_DROP_ERR(-ECONNREFUSED);
4944
4945         if (peerlbl_active) {
4946                 u32 if_sid;
4947                 u32 node_sid;
4948
4949                 if (sel_netif_sid(ifindex, &if_sid))
4950                         return NF_DROP;
4951                 if (avc_has_perm(peer_sid, if_sid,
4952                                  SECCLASS_NETIF, NETIF__EGRESS, &ad))
4953                         return NF_DROP_ERR(-ECONNREFUSED);
4954
4955                 if (sel_netnode_sid(addrp, family, &node_sid))
4956                         return NF_DROP;
4957                 if (avc_has_perm(peer_sid, node_sid,
4958                                  SECCLASS_NODE, NODE__SENDTO, &ad))
4959                         return NF_DROP_ERR(-ECONNREFUSED);
4960         }
4961
4962         return NF_ACCEPT;
4963 }
4964
4965 static unsigned int selinux_ipv4_postroute(const struct nf_hook_ops *ops,
4966                                            struct sk_buff *skb,
4967                                            const struct net_device *in,
4968                                            const struct net_device *out,
4969                                            int (*okfn)(struct sk_buff *))
4970 {
4971         return selinux_ip_postroute(skb, out->ifindex, PF_INET);
4972 }
4973
4974 #if defined(CONFIG_IPV6) || defined(CONFIG_IPV6_MODULE)
4975 static unsigned int selinux_ipv6_postroute(const struct nf_hook_ops *ops,
4976                                            struct sk_buff *skb,
4977                                            const struct net_device *in,
4978                                            const struct net_device *out,
4979                                            int (*okfn)(struct sk_buff *))
4980 {
4981         return selinux_ip_postroute(skb, out->ifindex, PF_INET6);
4982 }
4983 #endif  /* IPV6 */
4984
4985 #endif  /* CONFIG_NETFILTER */
4986
4987 static int selinux_netlink_send(struct sock *sk, struct sk_buff *skb)
4988 {
4989         int err;
4990
4991         err = cap_netlink_send(sk, skb);
4992         if (err)
4993                 return err;
4994
4995         return selinux_nlmsg_perm(sk, skb);
4996 }
4997
4998 static int ipc_alloc_security(struct task_struct *task,
4999                               struct kern_ipc_perm *perm,
5000                               u16 sclass)
5001 {
5002         struct ipc_security_struct *isec;
5003         u32 sid;
5004
5005         isec = kzalloc(sizeof(struct ipc_security_struct), GFP_KERNEL);
5006         if (!isec)
5007                 return -ENOMEM;
5008
5009         sid = task_sid(task);
5010         isec->sclass = sclass;
5011         isec->sid = sid;
5012         perm->security = isec;
5013
5014         return 0;
5015 }
5016
5017 static void ipc_free_security(struct kern_ipc_perm *perm)
5018 {
5019         struct ipc_security_struct *isec = perm->security;
5020         perm->security = NULL;
5021         kfree(isec);
5022 }
5023
5024 static int msg_msg_alloc_security(struct msg_msg *msg)
5025 {
5026         struct msg_security_struct *msec;
5027
5028         msec = kzalloc(sizeof(struct msg_security_struct), GFP_KERNEL);
5029         if (!msec)
5030                 return -ENOMEM;
5031
5032         msec->sid = SECINITSID_UNLABELED;
5033         msg->security = msec;
5034
5035         return 0;
5036 }
5037
5038 static void msg_msg_free_security(struct msg_msg *msg)
5039 {
5040         struct msg_security_struct *msec = msg->security;
5041
5042         msg->security = NULL;
5043         kfree(msec);
5044 }
5045
5046 static int ipc_has_perm(struct kern_ipc_perm *ipc_perms,
5047                         u32 perms)
5048 {
5049         struct ipc_security_struct *isec;
5050         struct common_audit_data ad;
5051         u32 sid = current_sid();
5052
5053         isec = ipc_perms->security;
5054
5055         ad.type = LSM_AUDIT_DATA_IPC;
5056         ad.u.ipc_id = ipc_perms->key;
5057
5058         return avc_has_perm(sid, isec->sid, isec->sclass, perms, &ad);
5059 }
5060
5061 static int selinux_msg_msg_alloc_security(struct msg_msg *msg)
5062 {
5063         return msg_msg_alloc_security(msg);
5064 }
5065
5066 static void selinux_msg_msg_free_security(struct msg_msg *msg)
5067 {
5068         msg_msg_free_security(msg);
5069 }
5070
5071 /* message queue security operations */
5072 static int selinux_msg_queue_alloc_security(struct msg_queue *msq)
5073 {
5074         struct ipc_security_struct *isec;
5075         struct common_audit_data ad;
5076         u32 sid = current_sid();
5077         int rc;
5078
5079         rc = ipc_alloc_security(current, &msq->q_perm, SECCLASS_MSGQ);
5080         if (rc)
5081                 return rc;
5082
5083         isec = msq->q_perm.security;
5084
5085         ad.type = LSM_AUDIT_DATA_IPC;
5086         ad.u.ipc_id = msq->q_perm.key;
5087
5088         rc = avc_has_perm(sid, isec->sid, SECCLASS_MSGQ,
5089                           MSGQ__CREATE, &ad);
5090         if (rc) {
5091                 ipc_free_security(&msq->q_perm);
5092                 return rc;
5093         }
5094         return 0;
5095 }
5096
5097 static void selinux_msg_queue_free_security(struct msg_queue *msq)
5098 {
5099         ipc_free_security(&msq->q_perm);
5100 }
5101
5102 static int selinux_msg_queue_associate(struct msg_queue *msq, int msqflg)
5103 {
5104         struct ipc_security_struct *isec;
5105         struct common_audit_data ad;
5106         u32 sid = current_sid();
5107
5108         isec = msq->q_perm.security;
5109
5110         ad.type = LSM_AUDIT_DATA_IPC;
5111         ad.u.ipc_id = msq->q_perm.key;
5112
5113         return avc_has_perm(sid, isec->sid, SECCLASS_MSGQ,
5114                             MSGQ__ASSOCIATE, &ad);
5115 }
5116
5117 static int selinux_msg_queue_msgctl(struct msg_queue *msq, int cmd)
5118 {
5119         int err;
5120         int perms;
5121
5122         switch (cmd) {
5123         case IPC_INFO:
5124         case MSG_INFO:
5125                 /* No specific object, just general system-wide information. */
5126                 return task_has_system(current, SYSTEM__IPC_INFO);
5127         case IPC_STAT:
5128         case MSG_STAT:
5129                 perms = MSGQ__GETATTR | MSGQ__ASSOCIATE;
5130                 break;
5131         case IPC_SET:
5132                 perms = MSGQ__SETATTR;
5133                 break;
5134         case IPC_RMID:
5135                 perms = MSGQ__DESTROY;
5136                 break;
5137         default:
5138                 return 0;
5139         }
5140
5141         err = ipc_has_perm(&msq->q_perm, perms);
5142         return err;
5143 }
5144
5145 static int selinux_msg_queue_msgsnd(struct msg_queue *msq, struct msg_msg *msg, int msqflg)
5146 {
5147         struct ipc_security_struct *isec;
5148         struct msg_security_struct *msec;
5149         struct common_audit_data ad;
5150         u32 sid = current_sid();
5151         int rc;
5152
5153         isec = msq->q_perm.security;
5154         msec = msg->security;
5155
5156         /*
5157          * First time through, need to assign label to the message
5158          */
5159         if (msec->sid == SECINITSID_UNLABELED) {
5160                 /*
5161                  * Compute new sid based on current process and
5162                  * message queue this message will be stored in
5163                  */
5164                 rc = security_transition_sid(sid, isec->sid, SECCLASS_MSG,
5165                                              NULL, &msec->sid);
5166                 if (rc)
5167                         return rc;
5168         }
5169
5170         ad.type = LSM_AUDIT_DATA_IPC;
5171         ad.u.ipc_id = msq->q_perm.key;
5172
5173         /* Can this process write to the queue? */
5174         rc = avc_has_perm(sid, isec->sid, SECCLASS_MSGQ,
5175                           MSGQ__WRITE, &ad);
5176         if (!rc)
5177                 /* Can this process send the message */
5178                 rc = avc_has_perm(sid, msec->sid, SECCLASS_MSG,
5179                                   MSG__SEND, &ad);
5180         if (!rc)
5181                 /* Can the message be put in the queue? */
5182                 rc = avc_has_perm(msec->sid, isec->sid, SECCLASS_MSGQ,
5183                                   MSGQ__ENQUEUE, &ad);
5184
5185         return rc;
5186 }
5187
5188 static int selinux_msg_queue_msgrcv(struct msg_queue *msq, struct msg_msg *msg,
5189                                     struct task_struct *target,
5190                                     long type, int mode)
5191 {
5192         struct ipc_security_struct *isec;
5193         struct msg_security_struct *msec;
5194         struct common_audit_data ad;
5195         u32 sid = task_sid(target);
5196         int rc;
5197
5198         isec = msq->q_perm.security;
5199         msec = msg->security;
5200
5201         ad.type = LSM_AUDIT_DATA_IPC;
5202         ad.u.ipc_id = msq->q_perm.key;
5203
5204         rc = avc_has_perm(sid, isec->sid,
5205                           SECCLASS_MSGQ, MSGQ__READ, &ad);
5206         if (!rc)
5207                 rc = avc_has_perm(sid, msec->sid,
5208                                   SECCLASS_MSG, MSG__RECEIVE, &ad);
5209         return rc;
5210 }
5211
5212 /* Shared Memory security operations */
5213 static int selinux_shm_alloc_security(struct shmid_kernel *shp)
5214 {
5215         struct ipc_security_struct *isec;
5216         struct common_audit_data ad;
5217         u32 sid = current_sid();
5218         int rc;
5219
5220         rc = ipc_alloc_security(current, &shp->shm_perm, SECCLASS_SHM);
5221         if (rc)
5222                 return rc;
5223
5224         isec = shp->shm_perm.security;
5225
5226         ad.type = LSM_AUDIT_DATA_IPC;
5227         ad.u.ipc_id = shp->shm_perm.key;
5228
5229         rc = avc_has_perm(sid, isec->sid, SECCLASS_SHM,
5230                           SHM__CREATE, &ad);
5231         if (rc) {
5232                 ipc_free_security(&shp->shm_perm);
5233                 return rc;
5234         }
5235         return 0;
5236 }
5237
5238 static void selinux_shm_free_security(struct shmid_kernel *shp)
5239 {
5240         ipc_free_security(&shp->shm_perm);
5241 }
5242
5243 static int selinux_shm_associate(struct shmid_kernel *shp, int shmflg)
5244 {
5245         struct ipc_security_struct *isec;
5246         struct common_audit_data ad;
5247         u32 sid = current_sid();
5248
5249         isec = shp->shm_perm.security;
5250
5251         ad.type = LSM_AUDIT_DATA_IPC;
5252         ad.u.ipc_id = shp->shm_perm.key;
5253
5254         return avc_has_perm(sid, isec->sid, SECCLASS_SHM,
5255                             SHM__ASSOCIATE, &ad);
5256 }
5257
5258 /* Note, at this point, shp is locked down */
5259 static int selinux_shm_shmctl(struct shmid_kernel *shp, int cmd)
5260 {
5261         int perms;
5262         int err;
5263
5264         switch (cmd) {
5265         case IPC_INFO:
5266         case SHM_INFO:
5267                 /* No specific object, just general system-wide information. */
5268                 return task_has_system(current, SYSTEM__IPC_INFO);
5269         case IPC_STAT:
5270         case SHM_STAT:
5271                 perms = SHM__GETATTR | SHM__ASSOCIATE;
5272                 break;
5273         case IPC_SET:
5274                 perms = SHM__SETATTR;
5275                 break;
5276         case SHM_LOCK:
5277         case SHM_UNLOCK:
5278                 perms = SHM__LOCK;
5279                 break;
5280         case IPC_RMID:
5281                 perms = SHM__DESTROY;
5282                 break;
5283         default:
5284                 return 0;
5285         }
5286
5287         err = ipc_has_perm(&shp->shm_perm, perms);
5288         return err;
5289 }
5290
5291 static int selinux_shm_shmat(struct shmid_kernel *shp,
5292                              char __user *shmaddr, int shmflg)
5293 {
5294         u32 perms;
5295
5296         if (shmflg & SHM_RDONLY)
5297                 perms = SHM__READ;
5298         else
5299                 perms = SHM__READ | SHM__WRITE;
5300
5301         return ipc_has_perm(&shp->shm_perm, perms);
5302 }
5303
5304 /* Semaphore security operations */
5305 static int selinux_sem_alloc_security(struct sem_array *sma)
5306 {
5307         struct ipc_security_struct *isec;
5308         struct common_audit_data ad;
5309         u32 sid = current_sid();
5310         int rc;
5311
5312         rc = ipc_alloc_security(current, &sma->sem_perm, SECCLASS_SEM);
5313         if (rc)
5314                 return rc;
5315
5316         isec = sma->sem_perm.security;
5317
5318         ad.type = LSM_AUDIT_DATA_IPC;
5319         ad.u.ipc_id = sma->sem_perm.key;
5320
5321         rc = avc_has_perm(sid, isec->sid, SECCLASS_SEM,
5322                           SEM__CREATE, &ad);
5323         if (rc) {
5324                 ipc_free_security(&sma->sem_perm);
5325                 return rc;
5326         }
5327         return 0;
5328 }
5329
5330 static void selinux_sem_free_security(struct sem_array *sma)
5331 {
5332         ipc_free_security(&sma->sem_perm);
5333 }
5334
5335 static int selinux_sem_associate(struct sem_array *sma, int semflg)
5336 {
5337         struct ipc_security_struct *isec;
5338         struct common_audit_data ad;
5339         u32 sid = current_sid();
5340
5341         isec = sma->sem_perm.security;
5342
5343         ad.type = LSM_AUDIT_DATA_IPC;
5344         ad.u.ipc_id = sma->sem_perm.key;
5345
5346         return avc_has_perm(sid, isec->sid, SECCLASS_SEM,
5347                             SEM__ASSOCIATE, &ad);
5348 }
5349
5350 /* Note, at this point, sma is locked down */
5351 static int selinux_sem_semctl(struct sem_array *sma, int cmd)
5352 {
5353         int err;
5354         u32 perms;
5355
5356         switch (cmd) {
5357         case IPC_INFO:
5358         case SEM_INFO:
5359                 /* No specific object, just general system-wide information. */
5360                 return task_has_system(current, SYSTEM__IPC_INFO);
5361         case GETPID:
5362         case GETNCNT:
5363         case GETZCNT:
5364                 perms = SEM__GETATTR;
5365                 break;
5366         case GETVAL:
5367         case GETALL:
5368                 perms = SEM__READ;
5369                 break;
5370         case SETVAL:
5371         case SETALL:
5372                 perms = SEM__WRITE;
5373                 break;
5374         case IPC_RMID:
5375                 perms = SEM__DESTROY;
5376                 break;
5377         case IPC_SET:
5378                 perms = SEM__SETATTR;
5379                 break;
5380         case IPC_STAT:
5381         case SEM_STAT:
5382                 perms = SEM__GETATTR | SEM__ASSOCIATE;
5383                 break;
5384         default:
5385                 return 0;
5386         }
5387
5388         err = ipc_has_perm(&sma->sem_perm, perms);
5389         return err;
5390 }
5391
5392 static int selinux_sem_semop(struct sem_array *sma,
5393                              struct sembuf *sops, unsigned nsops, int alter)
5394 {
5395         u32 perms;
5396
5397         if (alter)
5398                 perms = SEM__READ | SEM__WRITE;
5399         else
5400                 perms = SEM__READ;
5401
5402         return ipc_has_perm(&sma->sem_perm, perms);
5403 }
5404
5405 static int selinux_ipc_permission(struct kern_ipc_perm *ipcp, short flag)
5406 {
5407         u32 av = 0;
5408
5409         av = 0;
5410         if (flag & S_IRUGO)
5411                 av |= IPC__UNIX_READ;
5412         if (flag & S_IWUGO)
5413                 av |= IPC__UNIX_WRITE;
5414
5415         if (av == 0)
5416                 return 0;
5417
5418         return ipc_has_perm(ipcp, av);
5419 }
5420
5421 static void selinux_ipc_getsecid(struct kern_ipc_perm *ipcp, u32 *secid)
5422 {
5423         struct ipc_security_struct *isec = ipcp->security;
5424         *secid = isec->sid;
5425 }
5426
5427 static void selinux_d_instantiate(struct dentry *dentry, struct inode *inode)
5428 {
5429         if (inode)
5430                 inode_doinit_with_dentry(inode, dentry);
5431 }
5432
5433 static int selinux_getprocattr(struct task_struct *p,
5434                                char *name, char **value)
5435 {
5436         const struct task_security_struct *__tsec;
5437         u32 sid;
5438         int error;
5439         unsigned len;
5440
5441         if (current != p) {
5442                 error = current_has_perm(p, PROCESS__GETATTR);
5443                 if (error)
5444                         return error;
5445         }
5446
5447         rcu_read_lock();
5448         __tsec = __task_cred(p)->security;
5449
5450         if (!strcmp(name, "current"))
5451                 sid = __tsec->sid;
5452         else if (!strcmp(name, "prev"))
5453                 sid = __tsec->osid;
5454         else if (!strcmp(name, "exec"))
5455                 sid = __tsec->exec_sid;
5456         else if (!strcmp(name, "fscreate"))
5457                 sid = __tsec->create_sid;
5458         else if (!strcmp(name, "keycreate"))
5459                 sid = __tsec->keycreate_sid;
5460         else if (!strcmp(name, "sockcreate"))
5461                 sid = __tsec->sockcreate_sid;
5462         else
5463                 goto invalid;
5464         rcu_read_unlock();
5465
5466         if (!sid)
5467                 return 0;
5468
5469         error = security_sid_to_context(sid, value, &len);
5470         if (error)
5471                 return error;
5472         return len;
5473
5474 invalid:
5475         rcu_read_unlock();
5476         return -EINVAL;
5477 }
5478
5479 static int selinux_setprocattr(struct task_struct *p,
5480                                char *name, void *value, size_t size)
5481 {
5482         struct task_security_struct *tsec;
5483         struct task_struct *tracer;
5484         struct cred *new;
5485         u32 sid = 0, ptsid;
5486         int error;
5487         char *str = value;
5488
5489         if (current != p) {
5490                 /* SELinux only allows a process to change its own
5491                    security attributes. */
5492                 return -EACCES;
5493         }
5494
5495         /*
5496          * Basic control over ability to set these attributes at all.
5497          * current == p, but we'll pass them separately in case the
5498          * above restriction is ever removed.
5499          */
5500         if (!strcmp(name, "exec"))
5501                 error = current_has_perm(p, PROCESS__SETEXEC);
5502         else if (!strcmp(name, "fscreate"))
5503                 error = current_has_perm(p, PROCESS__SETFSCREATE);
5504         else if (!strcmp(name, "keycreate"))
5505                 error = current_has_perm(p, PROCESS__SETKEYCREATE);
5506         else if (!strcmp(name, "sockcreate"))
5507                 error = current_has_perm(p, PROCESS__SETSOCKCREATE);
5508         else if (!strcmp(name, "current"))
5509                 error = current_has_perm(p, PROCESS__SETCURRENT);
5510         else
5511                 error = -EINVAL;
5512         if (error)
5513                 return error;
5514
5515         /* Obtain a SID for the context, if one was specified. */
5516         if (size && str[1] && str[1] != '\n') {
5517                 if (str[size-1] == '\n') {
5518                         str[size-1] = 0;
5519                         size--;
5520                 }
5521                 error = security_context_to_sid(value, size, &sid);
5522                 if (error == -EINVAL && !strcmp(name, "fscreate")) {
5523                         if (!capable(CAP_MAC_ADMIN)) {
5524                                 struct audit_buffer *ab;
5525                                 size_t audit_size;
5526
5527                                 /* We strip a nul only if it is at the end, otherwise the
5528                                  * context contains a nul and we should audit that */
5529                                 if (str[size - 1] == '\0')
5530                                         audit_size = size - 1;
5531                                 else
5532                                         audit_size = size;
5533                                 ab = audit_log_start(current->audit_context, GFP_ATOMIC, AUDIT_SELINUX_ERR);
5534                                 audit_log_format(ab, "op=fscreate invalid_context=");
5535                                 audit_log_n_untrustedstring(ab, value, audit_size);
5536                                 audit_log_end(ab);
5537
5538                                 return error;
5539                         }
5540                         error = security_context_to_sid_force(value, size,
5541                                                               &sid);
5542                 }
5543                 if (error)
5544                         return error;
5545         }
5546
5547         new = prepare_creds();
5548         if (!new)
5549                 return -ENOMEM;
5550
5551         /* Permission checking based on the specified context is
5552            performed during the actual operation (execve,
5553            open/mkdir/...), when we know the full context of the
5554            operation.  See selinux_bprm_set_creds for the execve
5555            checks and may_create for the file creation checks. The
5556            operation will then fail if the context is not permitted. */
5557         tsec = new->security;
5558         if (!strcmp(name, "exec")) {
5559                 tsec->exec_sid = sid;
5560         } else if (!strcmp(name, "fscreate")) {
5561                 tsec->create_sid = sid;
5562         } else if (!strcmp(name, "keycreate")) {
5563                 error = may_create_key(sid, p);
5564                 if (error)
5565                         goto abort_change;
5566                 tsec->keycreate_sid = sid;
5567         } else if (!strcmp(name, "sockcreate")) {
5568                 tsec->sockcreate_sid = sid;
5569         } else if (!strcmp(name, "current")) {
5570                 error = -EINVAL;
5571                 if (sid == 0)
5572                         goto abort_change;
5573
5574                 /* Only allow single threaded processes to change context */
5575                 error = -EPERM;
5576                 if (!current_is_single_threaded()) {
5577                         error = security_bounded_transition(tsec->sid, sid);
5578                         if (error)
5579                                 goto abort_change;
5580                 }
5581
5582                 /* Check permissions for the transition. */
5583                 error = avc_has_perm(tsec->sid, sid, SECCLASS_PROCESS,
5584                                      PROCESS__DYNTRANSITION, NULL);
5585                 if (error)
5586                         goto abort_change;
5587
5588                 /* Check for ptracing, and update the task SID if ok.
5589                    Otherwise, leave SID unchanged and fail. */
5590                 ptsid = 0;
5591                 rcu_read_lock();
5592                 tracer = ptrace_parent(p);
5593                 if (tracer)
5594                         ptsid = task_sid(tracer);
5595                 rcu_read_unlock();
5596
5597                 if (tracer) {
5598                         error = avc_has_perm(ptsid, sid, SECCLASS_PROCESS,
5599                                              PROCESS__PTRACE, NULL);
5600                         if (error)
5601                                 goto abort_change;
5602                 }
5603
5604                 tsec->sid = sid;
5605         } else {
5606                 error = -EINVAL;
5607                 goto abort_change;
5608         }
5609
5610         commit_creds(new);
5611         return size;
5612
5613 abort_change:
5614         abort_creds(new);
5615         return error;
5616 }
5617
5618 static int selinux_ismaclabel(const char *name)
5619 {
5620         return (strcmp(name, XATTR_SELINUX_SUFFIX) == 0);
5621 }
5622
5623 static int selinux_secid_to_secctx(u32 secid, char **secdata, u32 *seclen)
5624 {
5625         return security_sid_to_context(secid, secdata, seclen);
5626 }
5627
5628 static int selinux_secctx_to_secid(const char *secdata, u32 seclen, u32 *secid)
5629 {
5630         return security_context_to_sid(secdata, seclen, secid);
5631 }
5632
5633 static void selinux_release_secctx(char *secdata, u32 seclen)
5634 {
5635         kfree(secdata);
5636 }
5637
5638 /*
5639  *      called with inode->i_mutex locked
5640  */
5641 static int selinux_inode_notifysecctx(struct inode *inode, void *ctx, u32 ctxlen)
5642 {
5643         return selinux_inode_setsecurity(inode, XATTR_SELINUX_SUFFIX, ctx, ctxlen, 0);
5644 }
5645
5646 /*
5647  *      called with inode->i_mutex locked
5648  */
5649 static int selinux_inode_setsecctx(struct dentry *dentry, void *ctx, u32 ctxlen)
5650 {
5651         return __vfs_setxattr_noperm(dentry, XATTR_NAME_SELINUX, ctx, ctxlen, 0);
5652 }
5653
5654 static int selinux_inode_getsecctx(struct inode *inode, void **ctx, u32 *ctxlen)
5655 {
5656         int len = 0;
5657         len = selinux_inode_getsecurity(inode, XATTR_SELINUX_SUFFIX,
5658                                                 ctx, true);
5659         if (len < 0)
5660                 return len;
5661         *ctxlen = len;
5662         return 0;
5663 }
5664 #ifdef CONFIG_KEYS
5665
5666 static int selinux_key_alloc(struct key *k, const struct cred *cred,
5667                              unsigned long flags)
5668 {
5669         const struct task_security_struct *tsec;
5670         struct key_security_struct *ksec;
5671
5672         ksec = kzalloc(sizeof(struct key_security_struct), GFP_KERNEL);
5673         if (!ksec)
5674                 return -ENOMEM;
5675
5676         tsec = cred->security;
5677         if (tsec->keycreate_sid)
5678                 ksec->sid = tsec->keycreate_sid;
5679         else
5680                 ksec->sid = tsec->sid;
5681
5682         k->security = ksec;
5683         return 0;
5684 }
5685
5686 static void selinux_key_free(struct key *k)
5687 {
5688         struct key_security_struct *ksec = k->security;
5689
5690         k->security = NULL;
5691         kfree(ksec);
5692 }
5693
5694 static int selinux_key_permission(key_ref_t key_ref,
5695                                   const struct cred *cred,
5696                                   key_perm_t perm)
5697 {
5698         struct key *key;
5699         struct key_security_struct *ksec;
5700         u32 sid;
5701
5702         /* if no specific permissions are requested, we skip the
5703            permission check. No serious, additional covert channels
5704            appear to be created. */
5705         if (perm == 0)
5706                 return 0;
5707
5708         sid = cred_sid(cred);
5709
5710         key = key_ref_to_ptr(key_ref);
5711         ksec = key->security;
5712
5713         return avc_has_perm(sid, ksec->sid, SECCLASS_KEY, perm, NULL);
5714 }
5715
5716 static int selinux_key_getsecurity(struct key *key, char **_buffer)
5717 {
5718         struct key_security_struct *ksec = key->security;
5719         char *context = NULL;
5720         unsigned len;
5721         int rc;
5722
5723         rc = security_sid_to_context(ksec->sid, &context, &len);
5724         if (!rc)
5725                 rc = len;
5726         *_buffer = context;
5727         return rc;
5728 }
5729
5730 #endif
5731
5732 static struct security_operations selinux_ops = {
5733         .name =                         "selinux",
5734
5735         .ptrace_access_check =          selinux_ptrace_access_check,
5736         .ptrace_traceme =               selinux_ptrace_traceme,
5737         .capget =                       selinux_capget,
5738         .capset =                       selinux_capset,
5739         .capable =                      selinux_capable,
5740         .quotactl =                     selinux_quotactl,
5741         .quota_on =                     selinux_quota_on,
5742         .syslog =                       selinux_syslog,
5743         .vm_enough_memory =             selinux_vm_enough_memory,
5744
5745         .netlink_send =                 selinux_netlink_send,
5746
5747         .bprm_set_creds =               selinux_bprm_set_creds,
5748         .bprm_committing_creds =        selinux_bprm_committing_creds,
5749         .bprm_committed_creds =         selinux_bprm_committed_creds,
5750         .bprm_secureexec =              selinux_bprm_secureexec,
5751
5752         .sb_alloc_security =            selinux_sb_alloc_security,
5753         .sb_free_security =             selinux_sb_free_security,
5754         .sb_copy_data =                 selinux_sb_copy_data,
5755         .sb_remount =                   selinux_sb_remount,
5756         .sb_kern_mount =                selinux_sb_kern_mount,
5757         .sb_show_options =              selinux_sb_show_options,
5758         .sb_statfs =                    selinux_sb_statfs,
5759         .sb_mount =                     selinux_mount,
5760         .sb_umount =                    selinux_umount,
5761         .sb_set_mnt_opts =              selinux_set_mnt_opts,
5762         .sb_clone_mnt_opts =            selinux_sb_clone_mnt_opts,
5763         .sb_parse_opts_str =            selinux_parse_opts_str,
5764
5765         .dentry_init_security =         selinux_dentry_init_security,
5766
5767         .inode_alloc_security =         selinux_inode_alloc_security,
5768         .inode_free_security =          selinux_inode_free_security,
5769         .inode_init_security =          selinux_inode_init_security,
5770         .inode_create =                 selinux_inode_create,
5771         .inode_link =                   selinux_inode_link,
5772         .inode_unlink =                 selinux_inode_unlink,
5773         .inode_symlink =                selinux_inode_symlink,
5774         .inode_mkdir =                  selinux_inode_mkdir,
5775         .inode_rmdir =                  selinux_inode_rmdir,
5776         .inode_mknod =                  selinux_inode_mknod,
5777         .inode_rename =                 selinux_inode_rename,
5778         .inode_readlink =               selinux_inode_readlink,
5779         .inode_follow_link =            selinux_inode_follow_link,
5780         .inode_permission =             selinux_inode_permission,
5781         .inode_setattr =                selinux_inode_setattr,
5782         .inode_getattr =                selinux_inode_getattr,
5783         .inode_setxattr =               selinux_inode_setxattr,
5784         .inode_post_setxattr =          selinux_inode_post_setxattr,
5785         .inode_getxattr =               selinux_inode_getxattr,
5786         .inode_listxattr =              selinux_inode_listxattr,
5787         .inode_removexattr =            selinux_inode_removexattr,
5788         .inode_getsecurity =            selinux_inode_getsecurity,
5789         .inode_setsecurity =            selinux_inode_setsecurity,
5790         .inode_listsecurity =           selinux_inode_listsecurity,
5791         .inode_getsecid =               selinux_inode_getsecid,
5792
5793         .file_permission =              selinux_file_permission,
5794         .file_alloc_security =          selinux_file_alloc_security,
5795         .file_free_security =           selinux_file_free_security,
5796         .file_ioctl =                   selinux_file_ioctl,
5797         .mmap_file =                    selinux_mmap_file,
5798         .mmap_addr =                    selinux_mmap_addr,
5799         .file_mprotect =                selinux_file_mprotect,
5800         .file_lock =                    selinux_file_lock,
5801         .file_fcntl =                   selinux_file_fcntl,
5802         .file_set_fowner =              selinux_file_set_fowner,
5803         .file_send_sigiotask =          selinux_file_send_sigiotask,
5804         .file_receive =                 selinux_file_receive,
5805
5806         .file_open =                    selinux_file_open,
5807
5808         .task_create =                  selinux_task_create,
5809         .cred_alloc_blank =             selinux_cred_alloc_blank,
5810         .cred_free =                    selinux_cred_free,
5811         .cred_prepare =                 selinux_cred_prepare,
5812         .cred_transfer =                selinux_cred_transfer,
5813         .kernel_act_as =                selinux_kernel_act_as,
5814         .kernel_create_files_as =       selinux_kernel_create_files_as,
5815         .kernel_module_request =        selinux_kernel_module_request,
5816         .task_setpgid =                 selinux_task_setpgid,
5817         .task_getpgid =                 selinux_task_getpgid,
5818         .task_getsid =                  selinux_task_getsid,
5819         .task_getsecid =                selinux_task_getsecid,
5820         .task_setnice =                 selinux_task_setnice,
5821         .task_setioprio =               selinux_task_setioprio,
5822         .task_getioprio =               selinux_task_getioprio,
5823         .task_setrlimit =               selinux_task_setrlimit,
5824         .task_setscheduler =            selinux_task_setscheduler,
5825         .task_getscheduler =            selinux_task_getscheduler,
5826         .task_movememory =              selinux_task_movememory,
5827         .task_kill =                    selinux_task_kill,
5828         .task_wait =                    selinux_task_wait,
5829         .task_to_inode =                selinux_task_to_inode,
5830
5831         .ipc_permission =               selinux_ipc_permission,
5832         .ipc_getsecid =                 selinux_ipc_getsecid,
5833
5834         .msg_msg_alloc_security =       selinux_msg_msg_alloc_security,
5835         .msg_msg_free_security =        selinux_msg_msg_free_security,
5836
5837         .msg_queue_alloc_security =     selinux_msg_queue_alloc_security,
5838         .msg_queue_free_security =      selinux_msg_queue_free_security,
5839         .msg_queue_associate =          selinux_msg_queue_associate,
5840         .msg_queue_msgctl =             selinux_msg_queue_msgctl,
5841         .msg_queue_msgsnd =             selinux_msg_queue_msgsnd,
5842         .msg_queue_msgrcv =             selinux_msg_queue_msgrcv,
5843
5844         .shm_alloc_security =           selinux_shm_alloc_security,
5845         .shm_free_security =            selinux_shm_free_security,
5846         .shm_associate =                selinux_shm_associate,
5847         .shm_shmctl =                   selinux_shm_shmctl,
5848         .shm_shmat =                    selinux_shm_shmat,
5849
5850         .sem_alloc_security =           selinux_sem_alloc_security,
5851         .sem_free_security =            selinux_sem_free_security,
5852         .sem_associate =                selinux_sem_associate,
5853         .sem_semctl =                   selinux_sem_semctl,
5854         .sem_semop =                    selinux_sem_semop,
5855
5856         .d_instantiate =                selinux_d_instantiate,
5857
5858         .getprocattr =                  selinux_getprocattr,
5859         .setprocattr =                  selinux_setprocattr,
5860
5861         .ismaclabel =                   selinux_ismaclabel,
5862         .secid_to_secctx =              selinux_secid_to_secctx,
5863         .secctx_to_secid =              selinux_secctx_to_secid,
5864         .release_secctx =               selinux_release_secctx,
5865         .inode_notifysecctx =           selinux_inode_notifysecctx,
5866         .inode_setsecctx =              selinux_inode_setsecctx,
5867         .inode_getsecctx =              selinux_inode_getsecctx,
5868
5869         .unix_stream_connect =          selinux_socket_unix_stream_connect,
5870         .unix_may_send =                selinux_socket_unix_may_send,
5871
5872         .socket_create =                selinux_socket_create,
5873         .socket_post_create =           selinux_socket_post_create,
5874         .socket_bind =                  selinux_socket_bind,
5875         .socket_connect =               selinux_socket_connect,
5876         .socket_listen =                selinux_socket_listen,
5877         .socket_accept =                selinux_socket_accept,
5878         .socket_sendmsg =               selinux_socket_sendmsg,
5879         .socket_recvmsg =               selinux_socket_recvmsg,
5880         .socket_getsockname =           selinux_socket_getsockname,
5881         .socket_getpeername =           selinux_socket_getpeername,
5882         .socket_getsockopt =            selinux_socket_getsockopt,
5883         .socket_setsockopt =            selinux_socket_setsockopt,
5884         .socket_shutdown =              selinux_socket_shutdown,
5885         .socket_sock_rcv_skb =          selinux_socket_sock_rcv_skb,
5886         .socket_getpeersec_stream =     selinux_socket_getpeersec_stream,
5887         .socket_getpeersec_dgram =      selinux_socket_getpeersec_dgram,
5888         .sk_alloc_security =            selinux_sk_alloc_security,
5889         .sk_free_security =             selinux_sk_free_security,
5890         .sk_clone_security =            selinux_sk_clone_security,
5891         .sk_getsecid =                  selinux_sk_getsecid,
5892         .sock_graft =                   selinux_sock_graft,
5893         .inet_conn_request =            selinux_inet_conn_request,
5894         .inet_csk_clone =               selinux_inet_csk_clone,
5895         .inet_conn_established =        selinux_inet_conn_established,
5896         .secmark_relabel_packet =       selinux_secmark_relabel_packet,
5897         .secmark_refcount_inc =         selinux_secmark_refcount_inc,
5898         .secmark_refcount_dec =         selinux_secmark_refcount_dec,
5899         .req_classify_flow =            selinux_req_classify_flow,
5900         .tun_dev_alloc_security =       selinux_tun_dev_alloc_security,
5901         .tun_dev_free_security =        selinux_tun_dev_free_security,
5902         .tun_dev_create =               selinux_tun_dev_create,
5903         .tun_dev_attach_queue =         selinux_tun_dev_attach_queue,
5904         .tun_dev_attach =               selinux_tun_dev_attach,
5905         .tun_dev_open =                 selinux_tun_dev_open,
5906         .skb_owned_by =                 selinux_skb_owned_by,
5907
5908 #ifdef CONFIG_SECURITY_NETWORK_XFRM
5909         .xfrm_policy_alloc_security =   selinux_xfrm_policy_alloc,
5910         .xfrm_policy_clone_security =   selinux_xfrm_policy_clone,
5911         .xfrm_policy_free_security =    selinux_xfrm_policy_free,
5912         .xfrm_policy_delete_security =  selinux_xfrm_policy_delete,
5913         .xfrm_state_alloc =             selinux_xfrm_state_alloc,
5914         .xfrm_state_alloc_acquire =     selinux_xfrm_state_alloc_acquire,
5915         .xfrm_state_free_security =     selinux_xfrm_state_free,
5916         .xfrm_state_delete_security =   selinux_xfrm_state_delete,
5917         .xfrm_policy_lookup =           selinux_xfrm_policy_lookup,
5918         .xfrm_state_pol_flow_match =    selinux_xfrm_state_pol_flow_match,
5919         .xfrm_decode_session =          selinux_xfrm_decode_session,
5920 #endif
5921
5922 #ifdef CONFIG_KEYS
5923         .key_alloc =                    selinux_key_alloc,
5924         .key_free =                     selinux_key_free,
5925         .key_permission =               selinux_key_permission,
5926         .key_getsecurity =              selinux_key_getsecurity,
5927 #endif
5928
5929 #ifdef CONFIG_AUDIT
5930         .audit_rule_init =              selinux_audit_rule_init,
5931         .audit_rule_known =             selinux_audit_rule_known,
5932         .audit_rule_match =             selinux_audit_rule_match,
5933         .audit_rule_free =              selinux_audit_rule_free,
5934 #endif
5935 };
5936
5937 static __init int selinux_init(void)
5938 {
5939         if (!security_module_enable(&selinux_ops)) {
5940                 selinux_enabled = 0;
5941                 return 0;
5942         }
5943
5944         if (!selinux_enabled) {
5945                 printk(KERN_INFO "SELinux:  Disabled at boot.\n");
5946                 return 0;
5947         }
5948
5949         printk(KERN_INFO "SELinux:  Initializing.\n");
5950
5951         /* Set the security state for the initial task. */
5952         cred_init_security();
5953
5954         default_noexec = !(VM_DATA_DEFAULT_FLAGS & VM_EXEC);
5955
5956         sel_inode_cache = kmem_cache_create("selinux_inode_security",
5957                                             sizeof(struct inode_security_struct),
5958                                             0, SLAB_PANIC, NULL);
5959         avc_init();
5960
5961         if (register_security(&selinux_ops))
5962                 panic("SELinux: Unable to register with kernel.\n");
5963
5964         if (selinux_enforcing)
5965                 printk(KERN_DEBUG "SELinux:  Starting in enforcing mode\n");
5966         else
5967                 printk(KERN_DEBUG "SELinux:  Starting in permissive mode\n");
5968
5969         return 0;
5970 }
5971
5972 static void delayed_superblock_init(struct super_block *sb, void *unused)
5973 {
5974         superblock_doinit(sb, NULL);
5975 }
5976
5977 void selinux_complete_init(void)
5978 {
5979         printk(KERN_DEBUG "SELinux:  Completing initialization.\n");
5980
5981         /* Set up any superblocks initialized prior to the policy load. */
5982         printk(KERN_DEBUG "SELinux:  Setting up existing superblocks.\n");
5983         iterate_supers(delayed_superblock_init, NULL);
5984 }
5985
5986 /* SELinux requires early initialization in order to label
5987    all processes and objects when they are created. */
5988 security_initcall(selinux_init);
5989
5990 #if defined(CONFIG_NETFILTER)
5991
5992 static struct nf_hook_ops selinux_ipv4_ops[] = {
5993         {
5994                 .hook =         selinux_ipv4_postroute,
5995                 .owner =        THIS_MODULE,
5996                 .pf =           NFPROTO_IPV4,
5997                 .hooknum =      NF_INET_POST_ROUTING,
5998                 .priority =     NF_IP_PRI_SELINUX_LAST,
5999         },
6000         {
6001                 .hook =         selinux_ipv4_forward,
6002                 .owner =        THIS_MODULE,
6003                 .pf =           NFPROTO_IPV4,
6004                 .hooknum =      NF_INET_FORWARD,
6005                 .priority =     NF_IP_PRI_SELINUX_FIRST,
6006         },
6007         {
6008                 .hook =         selinux_ipv4_output,
6009                 .owner =        THIS_MODULE,
6010                 .pf =           NFPROTO_IPV4,
6011                 .hooknum =      NF_INET_LOCAL_OUT,
6012                 .priority =     NF_IP_PRI_SELINUX_FIRST,
6013         }
6014 };
6015
6016 #if defined(CONFIG_IPV6) || defined(CONFIG_IPV6_MODULE)
6017
6018 static struct nf_hook_ops selinux_ipv6_ops[] = {
6019         {
6020                 .hook =         selinux_ipv6_postroute,
6021                 .owner =        THIS_MODULE,
6022                 .pf =           NFPROTO_IPV6,
6023                 .hooknum =      NF_INET_POST_ROUTING,
6024                 .priority =     NF_IP6_PRI_SELINUX_LAST,
6025         },
6026         {
6027                 .hook =         selinux_ipv6_forward,
6028                 .owner =        THIS_MODULE,
6029                 .pf =           NFPROTO_IPV6,
6030                 .hooknum =      NF_INET_FORWARD,
6031                 .priority =     NF_IP6_PRI_SELINUX_FIRST,
6032         }
6033 };
6034
6035 #endif  /* IPV6 */
6036
6037 static int __init selinux_nf_ip_init(void)
6038 {
6039         int err = 0;
6040
6041         if (!selinux_enabled)
6042                 goto out;
6043
6044         printk(KERN_DEBUG "SELinux:  Registering netfilter hooks\n");
6045
6046         err = nf_register_hooks(selinux_ipv4_ops, ARRAY_SIZE(selinux_ipv4_ops));
6047         if (err)
6048                 panic("SELinux: nf_register_hooks for IPv4: error %d\n", err);
6049
6050 #if defined(CONFIG_IPV6) || defined(CONFIG_IPV6_MODULE)
6051         err = nf_register_hooks(selinux_ipv6_ops, ARRAY_SIZE(selinux_ipv6_ops));
6052         if (err)
6053                 panic("SELinux: nf_register_hooks for IPv6: error %d\n", err);
6054 #endif  /* IPV6 */
6055
6056 out:
6057         return err;
6058 }
6059
6060 __initcall(selinux_nf_ip_init);
6061
6062 #ifdef CONFIG_SECURITY_SELINUX_DISABLE
6063 static void selinux_nf_ip_exit(void)
6064 {
6065         printk(KERN_DEBUG "SELinux:  Unregistering netfilter hooks\n");
6066
6067         nf_unregister_hooks(selinux_ipv4_ops, ARRAY_SIZE(selinux_ipv4_ops));
6068 #if defined(CONFIG_IPV6) || defined(CONFIG_IPV6_MODULE)
6069         nf_unregister_hooks(selinux_ipv6_ops, ARRAY_SIZE(selinux_ipv6_ops));
6070 #endif  /* IPV6 */
6071 }
6072 #endif
6073
6074 #else /* CONFIG_NETFILTER */
6075
6076 #ifdef CONFIG_SECURITY_SELINUX_DISABLE
6077 #define selinux_nf_ip_exit()
6078 #endif
6079
6080 #endif /* CONFIG_NETFILTER */
6081
6082 #ifdef CONFIG_SECURITY_SELINUX_DISABLE
6083 static int selinux_disabled;
6084
6085 int selinux_disable(void)
6086 {
6087         if (ss_initialized) {
6088                 /* Not permitted after initial policy load. */
6089                 return -EINVAL;
6090         }
6091
6092         if (selinux_disabled) {
6093                 /* Only do this once. */
6094                 return -EINVAL;
6095         }
6096
6097         printk(KERN_INFO "SELinux:  Disabled at runtime.\n");
6098
6099         selinux_disabled = 1;
6100         selinux_enabled = 0;
6101
6102         reset_security_ops();
6103
6104         /* Try to destroy the avc node cache */
6105         avc_disable();
6106
6107         /* Unregister netfilter hooks. */
6108         selinux_nf_ip_exit();
6109
6110         /* Unregister selinuxfs. */
6111         exit_sel_fs();
6112
6113         return 0;
6114 }
6115 #endif