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