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