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