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