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