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