xref: /linux/security/apparmor/lsm.c (revision 79997eda0d31bc68203c95ecb978773ee6ce7a1f)
1 // SPDX-License-Identifier: GPL-2.0-only
2 /*
3  * AppArmor security module
4  *
5  * This file contains AppArmor LSM hooks.
6  *
7  * Copyright (C) 1998-2008 Novell/SUSE
8  * Copyright 2009-2010 Canonical Ltd.
9  */
10 
11 #include <linux/lsm_hooks.h>
12 #include <linux/moduleparam.h>
13 #include <linux/mm.h>
14 #include <linux/mman.h>
15 #include <linux/mount.h>
16 #include <linux/namei.h>
17 #include <linux/ptrace.h>
18 #include <linux/ctype.h>
19 #include <linux/sysctl.h>
20 #include <linux/audit.h>
21 #include <linux/user_namespace.h>
22 #include <linux/netfilter_ipv4.h>
23 #include <linux/netfilter_ipv6.h>
24 #include <linux/zstd.h>
25 #include <net/sock.h>
26 #include <uapi/linux/mount.h>
27 
28 #include "include/apparmor.h"
29 #include "include/apparmorfs.h"
30 #include "include/audit.h"
31 #include "include/capability.h"
32 #include "include/cred.h"
33 #include "include/file.h"
34 #include "include/ipc.h"
35 #include "include/net.h"
36 #include "include/path.h"
37 #include "include/label.h"
38 #include "include/policy.h"
39 #include "include/policy_ns.h"
40 #include "include/procattr.h"
41 #include "include/mount.h"
42 #include "include/secid.h"
43 
44 /* Flag indicating whether initialization completed */
45 int apparmor_initialized;
46 
47 union aa_buffer {
48 	struct list_head list;
49 	DECLARE_FLEX_ARRAY(char, buffer);
50 };
51 
52 struct aa_local_cache {
53 	unsigned int hold;
54 	unsigned int count;
55 	struct list_head head;
56 };
57 
58 #define RESERVE_COUNT 2
59 static int reserve_count = RESERVE_COUNT;
60 static int buffer_count;
61 
62 static LIST_HEAD(aa_global_buffers);
63 static DEFINE_SPINLOCK(aa_buffers_lock);
64 static DEFINE_PER_CPU(struct aa_local_cache, aa_local_buffers);
65 
66 /*
67  * LSM hook functions
68  */
69 
70 /*
71  * put the associated labels
72  */
73 static void apparmor_cred_free(struct cred *cred)
74 {
75 	aa_put_label(cred_label(cred));
76 	set_cred_label(cred, NULL);
77 }
78 
79 /*
80  * allocate the apparmor part of blank credentials
81  */
82 static int apparmor_cred_alloc_blank(struct cred *cred, gfp_t gfp)
83 {
84 	set_cred_label(cred, NULL);
85 	return 0;
86 }
87 
88 /*
89  * prepare new cred label for modification by prepare_cred block
90  */
91 static int apparmor_cred_prepare(struct cred *new, const struct cred *old,
92 				 gfp_t gfp)
93 {
94 	set_cred_label(new, aa_get_newest_label(cred_label(old)));
95 	return 0;
96 }
97 
98 /*
99  * transfer the apparmor data to a blank set of creds
100  */
101 static void apparmor_cred_transfer(struct cred *new, const struct cred *old)
102 {
103 	set_cred_label(new, aa_get_newest_label(cred_label(old)));
104 }
105 
106 static void apparmor_task_free(struct task_struct *task)
107 {
108 
109 	aa_free_task_ctx(task_ctx(task));
110 }
111 
112 static int apparmor_task_alloc(struct task_struct *task,
113 			       unsigned long clone_flags)
114 {
115 	struct aa_task_ctx *new = task_ctx(task);
116 
117 	aa_dup_task_ctx(new, task_ctx(current));
118 
119 	return 0;
120 }
121 
122 static int apparmor_ptrace_access_check(struct task_struct *child,
123 					unsigned int mode)
124 {
125 	struct aa_label *tracer, *tracee;
126 	const struct cred *cred;
127 	int error;
128 
129 	cred = get_task_cred(child);
130 	tracee = cred_label(cred);	/* ref count on cred */
131 	tracer = __begin_current_label_crit_section();
132 	error = aa_may_ptrace(current_cred(), tracer, cred, tracee,
133 			(mode & PTRACE_MODE_READ) ? AA_PTRACE_READ
134 						  : AA_PTRACE_TRACE);
135 	__end_current_label_crit_section(tracer);
136 	put_cred(cred);
137 
138 	return error;
139 }
140 
141 static int apparmor_ptrace_traceme(struct task_struct *parent)
142 {
143 	struct aa_label *tracer, *tracee;
144 	const struct cred *cred;
145 	int error;
146 
147 	tracee = __begin_current_label_crit_section();
148 	cred = get_task_cred(parent);
149 	tracer = cred_label(cred);	/* ref count on cred */
150 	error = aa_may_ptrace(cred, tracer, current_cred(), tracee,
151 			      AA_PTRACE_TRACE);
152 	put_cred(cred);
153 	__end_current_label_crit_section(tracee);
154 
155 	return error;
156 }
157 
158 /* Derived from security/commoncap.c:cap_capget */
159 static int apparmor_capget(const struct task_struct *target, kernel_cap_t *effective,
160 			   kernel_cap_t *inheritable, kernel_cap_t *permitted)
161 {
162 	struct aa_label *label;
163 	const struct cred *cred;
164 
165 	rcu_read_lock();
166 	cred = __task_cred(target);
167 	label = aa_get_newest_cred_label(cred);
168 
169 	/*
170 	 * cap_capget is stacked ahead of this and will
171 	 * initialize effective and permitted.
172 	 */
173 	if (!unconfined(label)) {
174 		struct aa_profile *profile;
175 		struct label_it i;
176 
177 		label_for_each_confined(i, label, profile) {
178 			struct aa_ruleset *rules;
179 			if (COMPLAIN_MODE(profile))
180 				continue;
181 			rules = list_first_entry(&profile->rules,
182 						 typeof(*rules), list);
183 			*effective = cap_intersect(*effective,
184 						   rules->caps.allow);
185 			*permitted = cap_intersect(*permitted,
186 						   rules->caps.allow);
187 		}
188 	}
189 	rcu_read_unlock();
190 	aa_put_label(label);
191 
192 	return 0;
193 }
194 
195 static int apparmor_capable(const struct cred *cred, struct user_namespace *ns,
196 			    int cap, unsigned int opts)
197 {
198 	struct aa_label *label;
199 	int error = 0;
200 
201 	label = aa_get_newest_cred_label(cred);
202 	if (!unconfined(label))
203 		error = aa_capable(cred, label, cap, opts);
204 	aa_put_label(label);
205 
206 	return error;
207 }
208 
209 /**
210  * common_perm - basic common permission check wrapper fn for paths
211  * @op: operation being checked
212  * @path: path to check permission of  (NOT NULL)
213  * @mask: requested permissions mask
214  * @cond: conditional info for the permission request  (NOT NULL)
215  *
216  * Returns: %0 else error code if error or permission denied
217  */
218 static int common_perm(const char *op, const struct path *path, u32 mask,
219 		       struct path_cond *cond)
220 {
221 	struct aa_label *label;
222 	int error = 0;
223 
224 	label = __begin_current_label_crit_section();
225 	if (!unconfined(label))
226 		error = aa_path_perm(op, current_cred(), label, path, 0, mask,
227 				     cond);
228 	__end_current_label_crit_section(label);
229 
230 	return error;
231 }
232 
233 /**
234  * common_perm_cond - common permission wrapper around inode cond
235  * @op: operation being checked
236  * @path: location to check (NOT NULL)
237  * @mask: requested permissions mask
238  *
239  * Returns: %0 else error code if error or permission denied
240  */
241 static int common_perm_cond(const char *op, const struct path *path, u32 mask)
242 {
243 	vfsuid_t vfsuid = i_uid_into_vfsuid(mnt_idmap(path->mnt),
244 					    d_backing_inode(path->dentry));
245 	struct path_cond cond = {
246 		vfsuid_into_kuid(vfsuid),
247 		d_backing_inode(path->dentry)->i_mode
248 	};
249 
250 	if (!path_mediated_fs(path->dentry))
251 		return 0;
252 
253 	return common_perm(op, path, mask, &cond);
254 }
255 
256 /**
257  * common_perm_dir_dentry - common permission wrapper when path is dir, dentry
258  * @op: operation being checked
259  * @dir: directory of the dentry  (NOT NULL)
260  * @dentry: dentry to check  (NOT NULL)
261  * @mask: requested permissions mask
262  * @cond: conditional info for the permission request  (NOT NULL)
263  *
264  * Returns: %0 else error code if error or permission denied
265  */
266 static int common_perm_dir_dentry(const char *op, const struct path *dir,
267 				  struct dentry *dentry, u32 mask,
268 				  struct path_cond *cond)
269 {
270 	struct path path = { .mnt = dir->mnt, .dentry = dentry };
271 
272 	return common_perm(op, &path, mask, cond);
273 }
274 
275 /**
276  * common_perm_rm - common permission wrapper for operations doing rm
277  * @op: operation being checked
278  * @dir: directory that the dentry is in  (NOT NULL)
279  * @dentry: dentry being rm'd  (NOT NULL)
280  * @mask: requested permission mask
281  *
282  * Returns: %0 else error code if error or permission denied
283  */
284 static int common_perm_rm(const char *op, const struct path *dir,
285 			  struct dentry *dentry, u32 mask)
286 {
287 	struct inode *inode = d_backing_inode(dentry);
288 	struct path_cond cond = { };
289 	vfsuid_t vfsuid;
290 
291 	if (!inode || !path_mediated_fs(dentry))
292 		return 0;
293 
294 	vfsuid = i_uid_into_vfsuid(mnt_idmap(dir->mnt), inode);
295 	cond.uid = vfsuid_into_kuid(vfsuid);
296 	cond.mode = inode->i_mode;
297 
298 	return common_perm_dir_dentry(op, dir, dentry, mask, &cond);
299 }
300 
301 /**
302  * common_perm_create - common permission wrapper for operations doing create
303  * @op: operation being checked
304  * @dir: directory that dentry will be created in  (NOT NULL)
305  * @dentry: dentry to create   (NOT NULL)
306  * @mask: request permission mask
307  * @mode: created file mode
308  *
309  * Returns: %0 else error code if error or permission denied
310  */
311 static int common_perm_create(const char *op, const struct path *dir,
312 			      struct dentry *dentry, u32 mask, umode_t mode)
313 {
314 	struct path_cond cond = { current_fsuid(), mode };
315 
316 	if (!path_mediated_fs(dir->dentry))
317 		return 0;
318 
319 	return common_perm_dir_dentry(op, dir, dentry, mask, &cond);
320 }
321 
322 static int apparmor_path_unlink(const struct path *dir, struct dentry *dentry)
323 {
324 	return common_perm_rm(OP_UNLINK, dir, dentry, AA_MAY_DELETE);
325 }
326 
327 static int apparmor_path_mkdir(const struct path *dir, struct dentry *dentry,
328 			       umode_t mode)
329 {
330 	return common_perm_create(OP_MKDIR, dir, dentry, AA_MAY_CREATE,
331 				  S_IFDIR);
332 }
333 
334 static int apparmor_path_rmdir(const struct path *dir, struct dentry *dentry)
335 {
336 	return common_perm_rm(OP_RMDIR, dir, dentry, AA_MAY_DELETE);
337 }
338 
339 static int apparmor_path_mknod(const struct path *dir, struct dentry *dentry,
340 			       umode_t mode, unsigned int dev)
341 {
342 	return common_perm_create(OP_MKNOD, dir, dentry, AA_MAY_CREATE, mode);
343 }
344 
345 static int apparmor_path_truncate(const struct path *path)
346 {
347 	return common_perm_cond(OP_TRUNC, path, MAY_WRITE | AA_MAY_SETATTR);
348 }
349 
350 static int apparmor_file_truncate(struct file *file)
351 {
352 	return apparmor_path_truncate(&file->f_path);
353 }
354 
355 static int apparmor_path_symlink(const struct path *dir, struct dentry *dentry,
356 				 const char *old_name)
357 {
358 	return common_perm_create(OP_SYMLINK, dir, dentry, AA_MAY_CREATE,
359 				  S_IFLNK);
360 }
361 
362 static int apparmor_path_link(struct dentry *old_dentry, const struct path *new_dir,
363 			      struct dentry *new_dentry)
364 {
365 	struct aa_label *label;
366 	int error = 0;
367 
368 	if (!path_mediated_fs(old_dentry))
369 		return 0;
370 
371 	label = begin_current_label_crit_section();
372 	if (!unconfined(label))
373 		error = aa_path_link(current_cred(), label, old_dentry, new_dir,
374 				     new_dentry);
375 	end_current_label_crit_section(label);
376 
377 	return error;
378 }
379 
380 static int apparmor_path_rename(const struct path *old_dir, struct dentry *old_dentry,
381 				const struct path *new_dir, struct dentry *new_dentry,
382 				const unsigned int flags)
383 {
384 	struct aa_label *label;
385 	int error = 0;
386 
387 	if (!path_mediated_fs(old_dentry))
388 		return 0;
389 	if ((flags & RENAME_EXCHANGE) && !path_mediated_fs(new_dentry))
390 		return 0;
391 
392 	label = begin_current_label_crit_section();
393 	if (!unconfined(label)) {
394 		struct mnt_idmap *idmap = mnt_idmap(old_dir->mnt);
395 		vfsuid_t vfsuid;
396 		struct path old_path = { .mnt = old_dir->mnt,
397 					 .dentry = old_dentry };
398 		struct path new_path = { .mnt = new_dir->mnt,
399 					 .dentry = new_dentry };
400 		struct path_cond cond = {
401 			.mode = d_backing_inode(old_dentry)->i_mode
402 		};
403 		vfsuid = i_uid_into_vfsuid(idmap, d_backing_inode(old_dentry));
404 		cond.uid = vfsuid_into_kuid(vfsuid);
405 
406 		if (flags & RENAME_EXCHANGE) {
407 			struct path_cond cond_exchange = {
408 				.mode = d_backing_inode(new_dentry)->i_mode,
409 			};
410 			vfsuid = i_uid_into_vfsuid(idmap, d_backing_inode(old_dentry));
411 			cond_exchange.uid = vfsuid_into_kuid(vfsuid);
412 
413 			error = aa_path_perm(OP_RENAME_SRC, current_cred(),
414 					     label, &new_path, 0,
415 					     MAY_READ | AA_MAY_GETATTR | MAY_WRITE |
416 					     AA_MAY_SETATTR | AA_MAY_DELETE,
417 					     &cond_exchange);
418 			if (!error)
419 				error = aa_path_perm(OP_RENAME_DEST, current_cred(),
420 						     label, &old_path,
421 						     0, MAY_WRITE | AA_MAY_SETATTR |
422 						     AA_MAY_CREATE, &cond_exchange);
423 		}
424 
425 		if (!error)
426 			error = aa_path_perm(OP_RENAME_SRC, current_cred(),
427 					     label, &old_path, 0,
428 					     MAY_READ | AA_MAY_GETATTR | MAY_WRITE |
429 					     AA_MAY_SETATTR | AA_MAY_DELETE,
430 					     &cond);
431 		if (!error)
432 			error = aa_path_perm(OP_RENAME_DEST, current_cred(),
433 					     label, &new_path,
434 					     0, MAY_WRITE | AA_MAY_SETATTR |
435 					     AA_MAY_CREATE, &cond);
436 
437 	}
438 	end_current_label_crit_section(label);
439 
440 	return error;
441 }
442 
443 static int apparmor_path_chmod(const struct path *path, umode_t mode)
444 {
445 	return common_perm_cond(OP_CHMOD, path, AA_MAY_CHMOD);
446 }
447 
448 static int apparmor_path_chown(const struct path *path, kuid_t uid, kgid_t gid)
449 {
450 	return common_perm_cond(OP_CHOWN, path, AA_MAY_CHOWN);
451 }
452 
453 static int apparmor_inode_getattr(const struct path *path)
454 {
455 	return common_perm_cond(OP_GETATTR, path, AA_MAY_GETATTR);
456 }
457 
458 static int apparmor_file_open(struct file *file)
459 {
460 	struct aa_file_ctx *fctx = file_ctx(file);
461 	struct aa_label *label;
462 	int error = 0;
463 
464 	if (!path_mediated_fs(file->f_path.dentry))
465 		return 0;
466 
467 	/* If in exec, permission is handled by bprm hooks.
468 	 * Cache permissions granted by the previous exec check, with
469 	 * implicit read and executable mmap which are required to
470 	 * actually execute the image.
471 	 */
472 	if (current->in_execve) {
473 		fctx->allow = MAY_EXEC | MAY_READ | AA_EXEC_MMAP;
474 		return 0;
475 	}
476 
477 	label = aa_get_newest_cred_label(file->f_cred);
478 	if (!unconfined(label)) {
479 		struct mnt_idmap *idmap = file_mnt_idmap(file);
480 		struct inode *inode = file_inode(file);
481 		vfsuid_t vfsuid;
482 		struct path_cond cond = {
483 			.mode = inode->i_mode,
484 		};
485 		vfsuid = i_uid_into_vfsuid(idmap, inode);
486 		cond.uid = vfsuid_into_kuid(vfsuid);
487 
488 		error = aa_path_perm(OP_OPEN, file->f_cred,
489 				     label, &file->f_path, 0,
490 				     aa_map_file_to_perms(file), &cond);
491 		/* todo cache full allowed permissions set and state */
492 		fctx->allow = aa_map_file_to_perms(file);
493 	}
494 	aa_put_label(label);
495 
496 	return error;
497 }
498 
499 static int apparmor_file_alloc_security(struct file *file)
500 {
501 	struct aa_file_ctx *ctx = file_ctx(file);
502 	struct aa_label *label = begin_current_label_crit_section();
503 
504 	spin_lock_init(&ctx->lock);
505 	rcu_assign_pointer(ctx->label, aa_get_label(label));
506 	end_current_label_crit_section(label);
507 	return 0;
508 }
509 
510 static void apparmor_file_free_security(struct file *file)
511 {
512 	struct aa_file_ctx *ctx = file_ctx(file);
513 
514 	if (ctx)
515 		aa_put_label(rcu_access_pointer(ctx->label));
516 }
517 
518 static int common_file_perm(const char *op, struct file *file, u32 mask,
519 			    bool in_atomic)
520 {
521 	struct aa_label *label;
522 	int error = 0;
523 
524 	/* don't reaudit files closed during inheritance */
525 	if (file->f_path.dentry == aa_null.dentry)
526 		return -EACCES;
527 
528 	label = __begin_current_label_crit_section();
529 	error = aa_file_perm(op, current_cred(), label, file, mask, in_atomic);
530 	__end_current_label_crit_section(label);
531 
532 	return error;
533 }
534 
535 static int apparmor_file_receive(struct file *file)
536 {
537 	return common_file_perm(OP_FRECEIVE, file, aa_map_file_to_perms(file),
538 				false);
539 }
540 
541 static int apparmor_file_permission(struct file *file, int mask)
542 {
543 	return common_file_perm(OP_FPERM, file, mask, false);
544 }
545 
546 static int apparmor_file_lock(struct file *file, unsigned int cmd)
547 {
548 	u32 mask = AA_MAY_LOCK;
549 
550 	if (cmd == F_WRLCK)
551 		mask |= MAY_WRITE;
552 
553 	return common_file_perm(OP_FLOCK, file, mask, false);
554 }
555 
556 static int common_mmap(const char *op, struct file *file, unsigned long prot,
557 		       unsigned long flags, bool in_atomic)
558 {
559 	int mask = 0;
560 
561 	if (!file || !file_ctx(file))
562 		return 0;
563 
564 	if (prot & PROT_READ)
565 		mask |= MAY_READ;
566 	/*
567 	 * Private mappings don't require write perms since they don't
568 	 * write back to the files
569 	 */
570 	if ((prot & PROT_WRITE) && !(flags & MAP_PRIVATE))
571 		mask |= MAY_WRITE;
572 	if (prot & PROT_EXEC)
573 		mask |= AA_EXEC_MMAP;
574 
575 	return common_file_perm(op, file, mask, in_atomic);
576 }
577 
578 static int apparmor_mmap_file(struct file *file, unsigned long reqprot,
579 			      unsigned long prot, unsigned long flags)
580 {
581 	return common_mmap(OP_FMMAP, file, prot, flags, GFP_ATOMIC);
582 }
583 
584 static int apparmor_file_mprotect(struct vm_area_struct *vma,
585 				  unsigned long reqprot, unsigned long prot)
586 {
587 	return common_mmap(OP_FMPROT, vma->vm_file, prot,
588 			   !(vma->vm_flags & VM_SHARED) ? MAP_PRIVATE : 0,
589 			   false);
590 }
591 
592 #ifdef CONFIG_IO_URING
593 static const char *audit_uring_mask(u32 mask)
594 {
595 	if (mask & AA_MAY_CREATE_SQPOLL)
596 		return "sqpoll";
597 	if (mask & AA_MAY_OVERRIDE_CRED)
598 		return "override_creds";
599 	return "";
600 }
601 
602 static void audit_uring_cb(struct audit_buffer *ab, void *va)
603 {
604 	struct apparmor_audit_data *ad = aad_of_va(va);
605 
606 	if (ad->request & AA_URING_PERM_MASK) {
607 		audit_log_format(ab, " requested=\"%s\"",
608 				 audit_uring_mask(ad->request));
609 		if (ad->denied & AA_URING_PERM_MASK) {
610 			audit_log_format(ab, " denied=\"%s\"",
611 					 audit_uring_mask(ad->denied));
612 		}
613 	}
614 	if (ad->uring.target) {
615 		audit_log_format(ab, " tcontext=");
616 		aa_label_xaudit(ab, labels_ns(ad->subj_label),
617 				ad->uring.target,
618 				FLAGS_NONE, GFP_ATOMIC);
619 	}
620 }
621 
622 static int profile_uring(struct aa_profile *profile, u32 request,
623 			 struct aa_label *new, int cap,
624 			 struct apparmor_audit_data *ad)
625 {
626 	unsigned int state;
627 	struct aa_ruleset *rules;
628 	int error = 0;
629 
630 	AA_BUG(!profile);
631 
632 	rules = list_first_entry(&profile->rules, typeof(*rules), list);
633 	state = RULE_MEDIATES(rules, AA_CLASS_IO_URING);
634 	if (state) {
635 		struct aa_perms perms = { };
636 
637 		if (new) {
638 			aa_label_match(profile, rules, new, state,
639 				       false, request, &perms);
640 		} else {
641 			perms = *aa_lookup_perms(rules->policy, state);
642 		}
643 		aa_apply_modes_to_perms(profile, &perms);
644 		error = aa_check_perms(profile, &perms, request, ad,
645 				       audit_uring_cb);
646 	}
647 
648 	return error;
649 }
650 
651 /**
652  * apparmor_uring_override_creds - check the requested cred override
653  * @new: the target creds
654  *
655  * Check to see if the current task is allowed to override it's credentials
656  * to service an io_uring operation.
657  */
658 static int apparmor_uring_override_creds(const struct cred *new)
659 {
660 	struct aa_profile *profile;
661 	struct aa_label *label;
662 	int error;
663 	DEFINE_AUDIT_DATA(ad, LSM_AUDIT_DATA_NONE, AA_CLASS_IO_URING,
664 			  OP_URING_OVERRIDE);
665 
666 	ad.uring.target = cred_label(new);
667 	label = __begin_current_label_crit_section();
668 	error = fn_for_each(label, profile,
669 			profile_uring(profile, AA_MAY_OVERRIDE_CRED,
670 				      cred_label(new), CAP_SYS_ADMIN, &ad));
671 	__end_current_label_crit_section(label);
672 
673 	return error;
674 }
675 
676 /**
677  * apparmor_uring_sqpoll - check if a io_uring polling thread can be created
678  *
679  * Check to see if the current task is allowed to create a new io_uring
680  * kernel polling thread.
681  */
682 static int apparmor_uring_sqpoll(void)
683 {
684 	struct aa_profile *profile;
685 	struct aa_label *label;
686 	int error;
687 	DEFINE_AUDIT_DATA(ad, LSM_AUDIT_DATA_NONE, AA_CLASS_IO_URING,
688 			  OP_URING_SQPOLL);
689 
690 	label = __begin_current_label_crit_section();
691 	error = fn_for_each(label, profile,
692 			profile_uring(profile, AA_MAY_CREATE_SQPOLL,
693 				      NULL, CAP_SYS_ADMIN, &ad));
694 	__end_current_label_crit_section(label);
695 
696 	return error;
697 }
698 #endif /* CONFIG_IO_URING */
699 
700 static int apparmor_sb_mount(const char *dev_name, const struct path *path,
701 			     const char *type, unsigned long flags, void *data)
702 {
703 	struct aa_label *label;
704 	int error = 0;
705 
706 	/* Discard magic */
707 	if ((flags & MS_MGC_MSK) == MS_MGC_VAL)
708 		flags &= ~MS_MGC_MSK;
709 
710 	flags &= ~AA_MS_IGNORE_MASK;
711 
712 	label = __begin_current_label_crit_section();
713 	if (!unconfined(label)) {
714 		if (flags & MS_REMOUNT)
715 			error = aa_remount(current_cred(), label, path, flags,
716 					   data);
717 		else if (flags & MS_BIND)
718 			error = aa_bind_mount(current_cred(), label, path,
719 					      dev_name, flags);
720 		else if (flags & (MS_SHARED | MS_PRIVATE | MS_SLAVE |
721 				  MS_UNBINDABLE))
722 			error = aa_mount_change_type(current_cred(), label,
723 						     path, flags);
724 		else if (flags & MS_MOVE)
725 			error = aa_move_mount_old(current_cred(), label, path,
726 						  dev_name);
727 		else
728 			error = aa_new_mount(current_cred(), label, dev_name,
729 					     path, type, flags, data);
730 	}
731 	__end_current_label_crit_section(label);
732 
733 	return error;
734 }
735 
736 static int apparmor_move_mount(const struct path *from_path,
737 			       const struct path *to_path)
738 {
739 	struct aa_label *label;
740 	int error = 0;
741 
742 	label = __begin_current_label_crit_section();
743 	if (!unconfined(label))
744 		error = aa_move_mount(current_cred(), label, from_path,
745 				      to_path);
746 	__end_current_label_crit_section(label);
747 
748 	return error;
749 }
750 
751 static int apparmor_sb_umount(struct vfsmount *mnt, int flags)
752 {
753 	struct aa_label *label;
754 	int error = 0;
755 
756 	label = __begin_current_label_crit_section();
757 	if (!unconfined(label))
758 		error = aa_umount(current_cred(), label, mnt, flags);
759 	__end_current_label_crit_section(label);
760 
761 	return error;
762 }
763 
764 static int apparmor_sb_pivotroot(const struct path *old_path,
765 				 const struct path *new_path)
766 {
767 	struct aa_label *label;
768 	int error = 0;
769 
770 	label = aa_get_current_label();
771 	if (!unconfined(label))
772 		error = aa_pivotroot(current_cred(), label, old_path, new_path);
773 	aa_put_label(label);
774 
775 	return error;
776 }
777 
778 static int apparmor_getprocattr(struct task_struct *task, const char *name,
779 				char **value)
780 {
781 	int error = -ENOENT;
782 	/* released below */
783 	const struct cred *cred = get_task_cred(task);
784 	struct aa_task_ctx *ctx = task_ctx(current);
785 	struct aa_label *label = NULL;
786 
787 	if (strcmp(name, "current") == 0)
788 		label = aa_get_newest_label(cred_label(cred));
789 	else if (strcmp(name, "prev") == 0  && ctx->previous)
790 		label = aa_get_newest_label(ctx->previous);
791 	else if (strcmp(name, "exec") == 0 && ctx->onexec)
792 		label = aa_get_newest_label(ctx->onexec);
793 	else
794 		error = -EINVAL;
795 
796 	if (label)
797 		error = aa_getprocattr(label, value);
798 
799 	aa_put_label(label);
800 	put_cred(cred);
801 
802 	return error;
803 }
804 
805 static int apparmor_setprocattr(const char *name, void *value,
806 				size_t size)
807 {
808 	char *command, *largs = NULL, *args = value;
809 	size_t arg_size;
810 	int error;
811 	DEFINE_AUDIT_DATA(ad, LSM_AUDIT_DATA_NONE, AA_CLASS_NONE,
812 			  OP_SETPROCATTR);
813 
814 	if (size == 0)
815 		return -EINVAL;
816 
817 	/* AppArmor requires that the buffer must be null terminated atm */
818 	if (args[size - 1] != '\0') {
819 		/* null terminate */
820 		largs = args = kmalloc(size + 1, GFP_KERNEL);
821 		if (!args)
822 			return -ENOMEM;
823 		memcpy(args, value, size);
824 		args[size] = '\0';
825 	}
826 
827 	error = -EINVAL;
828 	args = strim(args);
829 	command = strsep(&args, " ");
830 	if (!args)
831 		goto out;
832 	args = skip_spaces(args);
833 	if (!*args)
834 		goto out;
835 
836 	arg_size = size - (args - (largs ? largs : (char *) value));
837 	if (strcmp(name, "current") == 0) {
838 		if (strcmp(command, "changehat") == 0) {
839 			error = aa_setprocattr_changehat(args, arg_size,
840 							 AA_CHANGE_NOFLAGS);
841 		} else if (strcmp(command, "permhat") == 0) {
842 			error = aa_setprocattr_changehat(args, arg_size,
843 							 AA_CHANGE_TEST);
844 		} else if (strcmp(command, "changeprofile") == 0) {
845 			error = aa_change_profile(args, AA_CHANGE_NOFLAGS);
846 		} else if (strcmp(command, "permprofile") == 0) {
847 			error = aa_change_profile(args, AA_CHANGE_TEST);
848 		} else if (strcmp(command, "stack") == 0) {
849 			error = aa_change_profile(args, AA_CHANGE_STACK);
850 		} else
851 			goto fail;
852 	} else if (strcmp(name, "exec") == 0) {
853 		if (strcmp(command, "exec") == 0)
854 			error = aa_change_profile(args, AA_CHANGE_ONEXEC);
855 		else if (strcmp(command, "stack") == 0)
856 			error = aa_change_profile(args, (AA_CHANGE_ONEXEC |
857 							 AA_CHANGE_STACK));
858 		else
859 			goto fail;
860 	} else
861 		/* only support the "current" and "exec" process attributes */
862 		goto fail;
863 
864 	if (!error)
865 		error = size;
866 out:
867 	kfree(largs);
868 	return error;
869 
870 fail:
871 	ad.subj_label = begin_current_label_crit_section();
872 	ad.info = name;
873 	ad.error = error = -EINVAL;
874 	aa_audit_msg(AUDIT_APPARMOR_DENIED, &ad, NULL);
875 	end_current_label_crit_section(ad.subj_label);
876 	goto out;
877 }
878 
879 /**
880  * apparmor_bprm_committing_creds - do task cleanup on committing new creds
881  * @bprm: binprm for the exec  (NOT NULL)
882  */
883 static void apparmor_bprm_committing_creds(const struct linux_binprm *bprm)
884 {
885 	struct aa_label *label = aa_current_raw_label();
886 	struct aa_label *new_label = cred_label(bprm->cred);
887 
888 	/* bail out if unconfined or not changing profile */
889 	if ((new_label->proxy == label->proxy) ||
890 	    (unconfined(new_label)))
891 		return;
892 
893 	aa_inherit_files(bprm->cred, current->files);
894 
895 	current->pdeath_signal = 0;
896 
897 	/* reset soft limits and set hard limits for the new label */
898 	__aa_transition_rlimits(label, new_label);
899 }
900 
901 /**
902  * apparmor_bprm_committed_creds() - do cleanup after new creds committed
903  * @bprm: binprm for the exec  (NOT NULL)
904  */
905 static void apparmor_bprm_committed_creds(const struct linux_binprm *bprm)
906 {
907 	/* clear out temporary/transitional state from the context */
908 	aa_clear_task_ctx_trans(task_ctx(current));
909 
910 	return;
911 }
912 
913 static void apparmor_current_getsecid_subj(u32 *secid)
914 {
915 	struct aa_label *label = __begin_current_label_crit_section();
916 	*secid = label->secid;
917 	__end_current_label_crit_section(label);
918 }
919 
920 static void apparmor_task_getsecid_obj(struct task_struct *p, u32 *secid)
921 {
922 	struct aa_label *label = aa_get_task_label(p);
923 	*secid = label->secid;
924 	aa_put_label(label);
925 }
926 
927 static int apparmor_task_setrlimit(struct task_struct *task,
928 		unsigned int resource, struct rlimit *new_rlim)
929 {
930 	struct aa_label *label = __begin_current_label_crit_section();
931 	int error = 0;
932 
933 	if (!unconfined(label))
934 		error = aa_task_setrlimit(current_cred(), label, task,
935 					  resource, new_rlim);
936 	__end_current_label_crit_section(label);
937 
938 	return error;
939 }
940 
941 static int apparmor_task_kill(struct task_struct *target, struct kernel_siginfo *info,
942 			      int sig, const struct cred *cred)
943 {
944 	const struct cred *tc;
945 	struct aa_label *cl, *tl;
946 	int error;
947 
948 	tc = get_task_cred(target);
949 	tl = aa_get_newest_cred_label(tc);
950 	if (cred) {
951 		/*
952 		 * Dealing with USB IO specific behavior
953 		 */
954 		cl = aa_get_newest_cred_label(cred);
955 		error = aa_may_signal(cred, cl, tc, tl, sig);
956 		aa_put_label(cl);
957 		return error;
958 	} else {
959 		cl = __begin_current_label_crit_section();
960 		error = aa_may_signal(current_cred(), cl, tc, tl, sig);
961 		__end_current_label_crit_section(cl);
962 	}
963 	aa_put_label(tl);
964 	put_cred(tc);
965 
966 	return error;
967 }
968 
969 static int apparmor_userns_create(const struct cred *cred)
970 {
971 	struct aa_label *label;
972 	struct aa_profile *profile;
973 	int error = 0;
974 	DEFINE_AUDIT_DATA(ad, LSM_AUDIT_DATA_TASK, AA_CLASS_NS,
975 			  OP_USERNS_CREATE);
976 
977 	ad.subj_cred = current_cred();
978 
979 	label = begin_current_label_crit_section();
980 	if (!unconfined(label)) {
981 		error = fn_for_each(label, profile,
982 				    aa_profile_ns_perm(profile, &ad,
983 						       AA_USERNS_CREATE));
984 	}
985 	end_current_label_crit_section(label);
986 
987 	return error;
988 }
989 
990 /**
991  * apparmor_sk_alloc_security - allocate and attach the sk_security field
992  */
993 static int apparmor_sk_alloc_security(struct sock *sk, int family, gfp_t flags)
994 {
995 	struct aa_sk_ctx *ctx;
996 
997 	ctx = kzalloc(sizeof(*ctx), flags);
998 	if (!ctx)
999 		return -ENOMEM;
1000 
1001 	sk->sk_security = ctx;
1002 
1003 	return 0;
1004 }
1005 
1006 /**
1007  * apparmor_sk_free_security - free the sk_security field
1008  */
1009 static void apparmor_sk_free_security(struct sock *sk)
1010 {
1011 	struct aa_sk_ctx *ctx = aa_sock(sk);
1012 
1013 	sk->sk_security = NULL;
1014 	aa_put_label(ctx->label);
1015 	aa_put_label(ctx->peer);
1016 	kfree(ctx);
1017 }
1018 
1019 /**
1020  * apparmor_sk_clone_security - clone the sk_security field
1021  */
1022 static void apparmor_sk_clone_security(const struct sock *sk,
1023 				       struct sock *newsk)
1024 {
1025 	struct aa_sk_ctx *ctx = aa_sock(sk);
1026 	struct aa_sk_ctx *new = aa_sock(newsk);
1027 
1028 	if (new->label)
1029 		aa_put_label(new->label);
1030 	new->label = aa_get_label(ctx->label);
1031 
1032 	if (new->peer)
1033 		aa_put_label(new->peer);
1034 	new->peer = aa_get_label(ctx->peer);
1035 }
1036 
1037 /**
1038  * apparmor_socket_create - check perms before creating a new socket
1039  */
1040 static int apparmor_socket_create(int family, int type, int protocol, int kern)
1041 {
1042 	struct aa_label *label;
1043 	int error = 0;
1044 
1045 	AA_BUG(in_interrupt());
1046 
1047 	label = begin_current_label_crit_section();
1048 	if (!(kern || unconfined(label)))
1049 		error = af_select(family,
1050 				  create_perm(label, family, type, protocol),
1051 				  aa_af_perm(current_cred(), label,
1052 					     OP_CREATE, AA_MAY_CREATE,
1053 					     family, type, protocol));
1054 	end_current_label_crit_section(label);
1055 
1056 	return error;
1057 }
1058 
1059 /**
1060  * apparmor_socket_post_create - setup the per-socket security struct
1061  *
1062  * Note:
1063  * -   kernel sockets currently labeled unconfined but we may want to
1064  *     move to a special kernel label
1065  * -   socket may not have sk here if created with sock_create_lite or
1066  *     sock_alloc. These should be accept cases which will be handled in
1067  *     sock_graft.
1068  */
1069 static int apparmor_socket_post_create(struct socket *sock, int family,
1070 				       int type, int protocol, int kern)
1071 {
1072 	struct aa_label *label;
1073 
1074 	if (kern) {
1075 		label = aa_get_label(kernel_t);
1076 	} else
1077 		label = aa_get_current_label();
1078 
1079 	if (sock->sk) {
1080 		struct aa_sk_ctx *ctx = aa_sock(sock->sk);
1081 
1082 		aa_put_label(ctx->label);
1083 		ctx->label = aa_get_label(label);
1084 	}
1085 	aa_put_label(label);
1086 
1087 	return 0;
1088 }
1089 
1090 /**
1091  * apparmor_socket_bind - check perms before bind addr to socket
1092  */
1093 static int apparmor_socket_bind(struct socket *sock,
1094 				struct sockaddr *address, int addrlen)
1095 {
1096 	AA_BUG(!sock);
1097 	AA_BUG(!sock->sk);
1098 	AA_BUG(!address);
1099 	AA_BUG(in_interrupt());
1100 
1101 	return af_select(sock->sk->sk_family,
1102 			 bind_perm(sock, address, addrlen),
1103 			 aa_sk_perm(OP_BIND, AA_MAY_BIND, sock->sk));
1104 }
1105 
1106 /**
1107  * apparmor_socket_connect - check perms before connecting @sock to @address
1108  */
1109 static int apparmor_socket_connect(struct socket *sock,
1110 				   struct sockaddr *address, int addrlen)
1111 {
1112 	AA_BUG(!sock);
1113 	AA_BUG(!sock->sk);
1114 	AA_BUG(!address);
1115 	AA_BUG(in_interrupt());
1116 
1117 	return af_select(sock->sk->sk_family,
1118 			 connect_perm(sock, address, addrlen),
1119 			 aa_sk_perm(OP_CONNECT, AA_MAY_CONNECT, sock->sk));
1120 }
1121 
1122 /**
1123  * apparmor_socket_listen - check perms before allowing listen
1124  */
1125 static int apparmor_socket_listen(struct socket *sock, int backlog)
1126 {
1127 	AA_BUG(!sock);
1128 	AA_BUG(!sock->sk);
1129 	AA_BUG(in_interrupt());
1130 
1131 	return af_select(sock->sk->sk_family,
1132 			 listen_perm(sock, backlog),
1133 			 aa_sk_perm(OP_LISTEN, AA_MAY_LISTEN, sock->sk));
1134 }
1135 
1136 /**
1137  * apparmor_socket_accept - check perms before accepting a new connection.
1138  *
1139  * Note: while @newsock is created and has some information, the accept
1140  *       has not been done.
1141  */
1142 static int apparmor_socket_accept(struct socket *sock, struct socket *newsock)
1143 {
1144 	AA_BUG(!sock);
1145 	AA_BUG(!sock->sk);
1146 	AA_BUG(!newsock);
1147 	AA_BUG(in_interrupt());
1148 
1149 	return af_select(sock->sk->sk_family,
1150 			 accept_perm(sock, newsock),
1151 			 aa_sk_perm(OP_ACCEPT, AA_MAY_ACCEPT, sock->sk));
1152 }
1153 
1154 static int aa_sock_msg_perm(const char *op, u32 request, struct socket *sock,
1155 			    struct msghdr *msg, int size)
1156 {
1157 	AA_BUG(!sock);
1158 	AA_BUG(!sock->sk);
1159 	AA_BUG(!msg);
1160 	AA_BUG(in_interrupt());
1161 
1162 	return af_select(sock->sk->sk_family,
1163 			 msg_perm(op, request, sock, msg, size),
1164 			 aa_sk_perm(op, request, sock->sk));
1165 }
1166 
1167 /**
1168  * apparmor_socket_sendmsg - check perms before sending msg to another socket
1169  */
1170 static int apparmor_socket_sendmsg(struct socket *sock,
1171 				   struct msghdr *msg, int size)
1172 {
1173 	return aa_sock_msg_perm(OP_SENDMSG, AA_MAY_SEND, sock, msg, size);
1174 }
1175 
1176 /**
1177  * apparmor_socket_recvmsg - check perms before receiving a message
1178  */
1179 static int apparmor_socket_recvmsg(struct socket *sock,
1180 				   struct msghdr *msg, int size, int flags)
1181 {
1182 	return aa_sock_msg_perm(OP_RECVMSG, AA_MAY_RECEIVE, sock, msg, size);
1183 }
1184 
1185 /* revaliation, get/set attr, shutdown */
1186 static int aa_sock_perm(const char *op, u32 request, struct socket *sock)
1187 {
1188 	AA_BUG(!sock);
1189 	AA_BUG(!sock->sk);
1190 	AA_BUG(in_interrupt());
1191 
1192 	return af_select(sock->sk->sk_family,
1193 			 sock_perm(op, request, sock),
1194 			 aa_sk_perm(op, request, sock->sk));
1195 }
1196 
1197 /**
1198  * apparmor_socket_getsockname - check perms before getting the local address
1199  */
1200 static int apparmor_socket_getsockname(struct socket *sock)
1201 {
1202 	return aa_sock_perm(OP_GETSOCKNAME, AA_MAY_GETATTR, sock);
1203 }
1204 
1205 /**
1206  * apparmor_socket_getpeername - check perms before getting remote address
1207  */
1208 static int apparmor_socket_getpeername(struct socket *sock)
1209 {
1210 	return aa_sock_perm(OP_GETPEERNAME, AA_MAY_GETATTR, sock);
1211 }
1212 
1213 /* revaliation, get/set attr, opt */
1214 static int aa_sock_opt_perm(const char *op, u32 request, struct socket *sock,
1215 			    int level, int optname)
1216 {
1217 	AA_BUG(!sock);
1218 	AA_BUG(!sock->sk);
1219 	AA_BUG(in_interrupt());
1220 
1221 	return af_select(sock->sk->sk_family,
1222 			 opt_perm(op, request, sock, level, optname),
1223 			 aa_sk_perm(op, request, sock->sk));
1224 }
1225 
1226 /**
1227  * apparmor_socket_getsockopt - check perms before getting socket options
1228  */
1229 static int apparmor_socket_getsockopt(struct socket *sock, int level,
1230 				      int optname)
1231 {
1232 	return aa_sock_opt_perm(OP_GETSOCKOPT, AA_MAY_GETOPT, sock,
1233 				level, optname);
1234 }
1235 
1236 /**
1237  * apparmor_socket_setsockopt - check perms before setting socket options
1238  */
1239 static int apparmor_socket_setsockopt(struct socket *sock, int level,
1240 				      int optname)
1241 {
1242 	return aa_sock_opt_perm(OP_SETSOCKOPT, AA_MAY_SETOPT, sock,
1243 				level, optname);
1244 }
1245 
1246 /**
1247  * apparmor_socket_shutdown - check perms before shutting down @sock conn
1248  */
1249 static int apparmor_socket_shutdown(struct socket *sock, int how)
1250 {
1251 	return aa_sock_perm(OP_SHUTDOWN, AA_MAY_SHUTDOWN, sock);
1252 }
1253 
1254 #ifdef CONFIG_NETWORK_SECMARK
1255 /**
1256  * apparmor_socket_sock_rcv_skb - check perms before associating skb to sk
1257  *
1258  * Note: can not sleep may be called with locks held
1259  *
1260  * dont want protocol specific in __skb_recv_datagram()
1261  * to deny an incoming connection  socket_sock_rcv_skb()
1262  */
1263 static int apparmor_socket_sock_rcv_skb(struct sock *sk, struct sk_buff *skb)
1264 {
1265 	struct aa_sk_ctx *ctx = aa_sock(sk);
1266 
1267 	if (!skb->secmark)
1268 		return 0;
1269 
1270 	return apparmor_secmark_check(ctx->label, OP_RECVMSG, AA_MAY_RECEIVE,
1271 				      skb->secmark, sk);
1272 }
1273 #endif
1274 
1275 
1276 static struct aa_label *sk_peer_label(struct sock *sk)
1277 {
1278 	struct aa_sk_ctx *ctx = aa_sock(sk);
1279 
1280 	if (ctx->peer)
1281 		return ctx->peer;
1282 
1283 	return ERR_PTR(-ENOPROTOOPT);
1284 }
1285 
1286 /**
1287  * apparmor_socket_getpeersec_stream - get security context of peer
1288  *
1289  * Note: for tcp only valid if using ipsec or cipso on lan
1290  */
1291 static int apparmor_socket_getpeersec_stream(struct socket *sock,
1292 					     sockptr_t optval, sockptr_t optlen,
1293 					     unsigned int len)
1294 {
1295 	char *name = NULL;
1296 	int slen, error = 0;
1297 	struct aa_label *label;
1298 	struct aa_label *peer;
1299 
1300 	label = begin_current_label_crit_section();
1301 	peer = sk_peer_label(sock->sk);
1302 	if (IS_ERR(peer)) {
1303 		error = PTR_ERR(peer);
1304 		goto done;
1305 	}
1306 	slen = aa_label_asxprint(&name, labels_ns(label), peer,
1307 				 FLAG_SHOW_MODE | FLAG_VIEW_SUBNS |
1308 				 FLAG_HIDDEN_UNCONFINED, GFP_KERNEL);
1309 	/* don't include terminating \0 in slen, it breaks some apps */
1310 	if (slen < 0) {
1311 		error = -ENOMEM;
1312 		goto done;
1313 	}
1314 	if (slen > len) {
1315 		error = -ERANGE;
1316 		goto done_len;
1317 	}
1318 
1319 	if (copy_to_sockptr(optval, name, slen))
1320 		error = -EFAULT;
1321 done_len:
1322 	if (copy_to_sockptr(optlen, &slen, sizeof(slen)))
1323 		error = -EFAULT;
1324 done:
1325 	end_current_label_crit_section(label);
1326 	kfree(name);
1327 	return error;
1328 }
1329 
1330 /**
1331  * apparmor_socket_getpeersec_dgram - get security label of packet
1332  * @sock: the peer socket
1333  * @skb: packet data
1334  * @secid: pointer to where to put the secid of the packet
1335  *
1336  * Sets the netlabel socket state on sk from parent
1337  */
1338 static int apparmor_socket_getpeersec_dgram(struct socket *sock,
1339 					    struct sk_buff *skb, u32 *secid)
1340 
1341 {
1342 	/* TODO: requires secid support */
1343 	return -ENOPROTOOPT;
1344 }
1345 
1346 /**
1347  * apparmor_sock_graft - Initialize newly created socket
1348  * @sk: child sock
1349  * @parent: parent socket
1350  *
1351  * Note: could set off of SOCK_CTX(parent) but need to track inode and we can
1352  *       just set sk security information off of current creating process label
1353  *       Labeling of sk for accept case - probably should be sock based
1354  *       instead of task, because of the case where an implicitly labeled
1355  *       socket is shared by different tasks.
1356  */
1357 static void apparmor_sock_graft(struct sock *sk, struct socket *parent)
1358 {
1359 	struct aa_sk_ctx *ctx = aa_sock(sk);
1360 
1361 	if (!ctx->label)
1362 		ctx->label = aa_get_current_label();
1363 }
1364 
1365 #ifdef CONFIG_NETWORK_SECMARK
1366 static int apparmor_inet_conn_request(const struct sock *sk, struct sk_buff *skb,
1367 				      struct request_sock *req)
1368 {
1369 	struct aa_sk_ctx *ctx = aa_sock(sk);
1370 
1371 	if (!skb->secmark)
1372 		return 0;
1373 
1374 	return apparmor_secmark_check(ctx->label, OP_CONNECT, AA_MAY_CONNECT,
1375 				      skb->secmark, sk);
1376 }
1377 #endif
1378 
1379 /*
1380  * The cred blob is a pointer to, not an instance of, an aa_label.
1381  */
1382 struct lsm_blob_sizes apparmor_blob_sizes __ro_after_init = {
1383 	.lbs_cred = sizeof(struct aa_label *),
1384 	.lbs_file = sizeof(struct aa_file_ctx),
1385 	.lbs_task = sizeof(struct aa_task_ctx),
1386 };
1387 
1388 static struct security_hook_list apparmor_hooks[] __ro_after_init = {
1389 	LSM_HOOK_INIT(ptrace_access_check, apparmor_ptrace_access_check),
1390 	LSM_HOOK_INIT(ptrace_traceme, apparmor_ptrace_traceme),
1391 	LSM_HOOK_INIT(capget, apparmor_capget),
1392 	LSM_HOOK_INIT(capable, apparmor_capable),
1393 
1394 	LSM_HOOK_INIT(move_mount, apparmor_move_mount),
1395 	LSM_HOOK_INIT(sb_mount, apparmor_sb_mount),
1396 	LSM_HOOK_INIT(sb_umount, apparmor_sb_umount),
1397 	LSM_HOOK_INIT(sb_pivotroot, apparmor_sb_pivotroot),
1398 
1399 	LSM_HOOK_INIT(path_link, apparmor_path_link),
1400 	LSM_HOOK_INIT(path_unlink, apparmor_path_unlink),
1401 	LSM_HOOK_INIT(path_symlink, apparmor_path_symlink),
1402 	LSM_HOOK_INIT(path_mkdir, apparmor_path_mkdir),
1403 	LSM_HOOK_INIT(path_rmdir, apparmor_path_rmdir),
1404 	LSM_HOOK_INIT(path_mknod, apparmor_path_mknod),
1405 	LSM_HOOK_INIT(path_rename, apparmor_path_rename),
1406 	LSM_HOOK_INIT(path_chmod, apparmor_path_chmod),
1407 	LSM_HOOK_INIT(path_chown, apparmor_path_chown),
1408 	LSM_HOOK_INIT(path_truncate, apparmor_path_truncate),
1409 	LSM_HOOK_INIT(inode_getattr, apparmor_inode_getattr),
1410 
1411 	LSM_HOOK_INIT(file_open, apparmor_file_open),
1412 	LSM_HOOK_INIT(file_receive, apparmor_file_receive),
1413 	LSM_HOOK_INIT(file_permission, apparmor_file_permission),
1414 	LSM_HOOK_INIT(file_alloc_security, apparmor_file_alloc_security),
1415 	LSM_HOOK_INIT(file_free_security, apparmor_file_free_security),
1416 	LSM_HOOK_INIT(mmap_file, apparmor_mmap_file),
1417 	LSM_HOOK_INIT(file_mprotect, apparmor_file_mprotect),
1418 	LSM_HOOK_INIT(file_lock, apparmor_file_lock),
1419 	LSM_HOOK_INIT(file_truncate, apparmor_file_truncate),
1420 
1421 	LSM_HOOK_INIT(getprocattr, apparmor_getprocattr),
1422 	LSM_HOOK_INIT(setprocattr, apparmor_setprocattr),
1423 
1424 	LSM_HOOK_INIT(sk_alloc_security, apparmor_sk_alloc_security),
1425 	LSM_HOOK_INIT(sk_free_security, apparmor_sk_free_security),
1426 	LSM_HOOK_INIT(sk_clone_security, apparmor_sk_clone_security),
1427 
1428 	LSM_HOOK_INIT(socket_create, apparmor_socket_create),
1429 	LSM_HOOK_INIT(socket_post_create, apparmor_socket_post_create),
1430 	LSM_HOOK_INIT(socket_bind, apparmor_socket_bind),
1431 	LSM_HOOK_INIT(socket_connect, apparmor_socket_connect),
1432 	LSM_HOOK_INIT(socket_listen, apparmor_socket_listen),
1433 	LSM_HOOK_INIT(socket_accept, apparmor_socket_accept),
1434 	LSM_HOOK_INIT(socket_sendmsg, apparmor_socket_sendmsg),
1435 	LSM_HOOK_INIT(socket_recvmsg, apparmor_socket_recvmsg),
1436 	LSM_HOOK_INIT(socket_getsockname, apparmor_socket_getsockname),
1437 	LSM_HOOK_INIT(socket_getpeername, apparmor_socket_getpeername),
1438 	LSM_HOOK_INIT(socket_getsockopt, apparmor_socket_getsockopt),
1439 	LSM_HOOK_INIT(socket_setsockopt, apparmor_socket_setsockopt),
1440 	LSM_HOOK_INIT(socket_shutdown, apparmor_socket_shutdown),
1441 #ifdef CONFIG_NETWORK_SECMARK
1442 	LSM_HOOK_INIT(socket_sock_rcv_skb, apparmor_socket_sock_rcv_skb),
1443 #endif
1444 	LSM_HOOK_INIT(socket_getpeersec_stream,
1445 		      apparmor_socket_getpeersec_stream),
1446 	LSM_HOOK_INIT(socket_getpeersec_dgram,
1447 		      apparmor_socket_getpeersec_dgram),
1448 	LSM_HOOK_INIT(sock_graft, apparmor_sock_graft),
1449 #ifdef CONFIG_NETWORK_SECMARK
1450 	LSM_HOOK_INIT(inet_conn_request, apparmor_inet_conn_request),
1451 #endif
1452 
1453 	LSM_HOOK_INIT(cred_alloc_blank, apparmor_cred_alloc_blank),
1454 	LSM_HOOK_INIT(cred_free, apparmor_cred_free),
1455 	LSM_HOOK_INIT(cred_prepare, apparmor_cred_prepare),
1456 	LSM_HOOK_INIT(cred_transfer, apparmor_cred_transfer),
1457 
1458 	LSM_HOOK_INIT(bprm_creds_for_exec, apparmor_bprm_creds_for_exec),
1459 	LSM_HOOK_INIT(bprm_committing_creds, apparmor_bprm_committing_creds),
1460 	LSM_HOOK_INIT(bprm_committed_creds, apparmor_bprm_committed_creds),
1461 
1462 	LSM_HOOK_INIT(task_free, apparmor_task_free),
1463 	LSM_HOOK_INIT(task_alloc, apparmor_task_alloc),
1464 	LSM_HOOK_INIT(current_getsecid_subj, apparmor_current_getsecid_subj),
1465 	LSM_HOOK_INIT(task_getsecid_obj, apparmor_task_getsecid_obj),
1466 	LSM_HOOK_INIT(task_setrlimit, apparmor_task_setrlimit),
1467 	LSM_HOOK_INIT(task_kill, apparmor_task_kill),
1468 	LSM_HOOK_INIT(userns_create, apparmor_userns_create),
1469 
1470 #ifdef CONFIG_AUDIT
1471 	LSM_HOOK_INIT(audit_rule_init, aa_audit_rule_init),
1472 	LSM_HOOK_INIT(audit_rule_known, aa_audit_rule_known),
1473 	LSM_HOOK_INIT(audit_rule_match, aa_audit_rule_match),
1474 	LSM_HOOK_INIT(audit_rule_free, aa_audit_rule_free),
1475 #endif
1476 
1477 	LSM_HOOK_INIT(secid_to_secctx, apparmor_secid_to_secctx),
1478 	LSM_HOOK_INIT(secctx_to_secid, apparmor_secctx_to_secid),
1479 	LSM_HOOK_INIT(release_secctx, apparmor_release_secctx),
1480 
1481 #ifdef CONFIG_IO_URING
1482 	LSM_HOOK_INIT(uring_override_creds, apparmor_uring_override_creds),
1483 	LSM_HOOK_INIT(uring_sqpoll, apparmor_uring_sqpoll),
1484 #endif
1485 };
1486 
1487 /*
1488  * AppArmor sysfs module parameters
1489  */
1490 
1491 static int param_set_aabool(const char *val, const struct kernel_param *kp);
1492 static int param_get_aabool(char *buffer, const struct kernel_param *kp);
1493 #define param_check_aabool param_check_bool
1494 static const struct kernel_param_ops param_ops_aabool = {
1495 	.flags = KERNEL_PARAM_OPS_FL_NOARG,
1496 	.set = param_set_aabool,
1497 	.get = param_get_aabool
1498 };
1499 
1500 static int param_set_aauint(const char *val, const struct kernel_param *kp);
1501 static int param_get_aauint(char *buffer, const struct kernel_param *kp);
1502 #define param_check_aauint param_check_uint
1503 static const struct kernel_param_ops param_ops_aauint = {
1504 	.set = param_set_aauint,
1505 	.get = param_get_aauint
1506 };
1507 
1508 static int param_set_aacompressionlevel(const char *val,
1509 					const struct kernel_param *kp);
1510 static int param_get_aacompressionlevel(char *buffer,
1511 					const struct kernel_param *kp);
1512 #define param_check_aacompressionlevel param_check_int
1513 static const struct kernel_param_ops param_ops_aacompressionlevel = {
1514 	.set = param_set_aacompressionlevel,
1515 	.get = param_get_aacompressionlevel
1516 };
1517 
1518 static int param_set_aalockpolicy(const char *val, const struct kernel_param *kp);
1519 static int param_get_aalockpolicy(char *buffer, const struct kernel_param *kp);
1520 #define param_check_aalockpolicy param_check_bool
1521 static const struct kernel_param_ops param_ops_aalockpolicy = {
1522 	.flags = KERNEL_PARAM_OPS_FL_NOARG,
1523 	.set = param_set_aalockpolicy,
1524 	.get = param_get_aalockpolicy
1525 };
1526 
1527 static int param_set_audit(const char *val, const struct kernel_param *kp);
1528 static int param_get_audit(char *buffer, const struct kernel_param *kp);
1529 
1530 static int param_set_mode(const char *val, const struct kernel_param *kp);
1531 static int param_get_mode(char *buffer, const struct kernel_param *kp);
1532 
1533 /* Flag values, also controllable via /sys/module/apparmor/parameters
1534  * We define special types as we want to do additional mediation.
1535  */
1536 
1537 /* AppArmor global enforcement switch - complain, enforce, kill */
1538 enum profile_mode aa_g_profile_mode = APPARMOR_ENFORCE;
1539 module_param_call(mode, param_set_mode, param_get_mode,
1540 		  &aa_g_profile_mode, S_IRUSR | S_IWUSR);
1541 
1542 /* whether policy verification hashing is enabled */
1543 bool aa_g_hash_policy = IS_ENABLED(CONFIG_SECURITY_APPARMOR_HASH_DEFAULT);
1544 #ifdef CONFIG_SECURITY_APPARMOR_HASH
1545 module_param_named(hash_policy, aa_g_hash_policy, aabool, S_IRUSR | S_IWUSR);
1546 #endif
1547 
1548 /* whether policy exactly as loaded is retained for debug and checkpointing */
1549 bool aa_g_export_binary = IS_ENABLED(CONFIG_SECURITY_APPARMOR_EXPORT_BINARY);
1550 #ifdef CONFIG_SECURITY_APPARMOR_EXPORT_BINARY
1551 module_param_named(export_binary, aa_g_export_binary, aabool, 0600);
1552 #endif
1553 
1554 /* policy loaddata compression level */
1555 int aa_g_rawdata_compression_level = AA_DEFAULT_CLEVEL;
1556 module_param_named(rawdata_compression_level, aa_g_rawdata_compression_level,
1557 		   aacompressionlevel, 0400);
1558 
1559 /* Debug mode */
1560 bool aa_g_debug = IS_ENABLED(CONFIG_SECURITY_APPARMOR_DEBUG_MESSAGES);
1561 module_param_named(debug, aa_g_debug, aabool, S_IRUSR | S_IWUSR);
1562 
1563 /* Audit mode */
1564 enum audit_mode aa_g_audit;
1565 module_param_call(audit, param_set_audit, param_get_audit,
1566 		  &aa_g_audit, S_IRUSR | S_IWUSR);
1567 
1568 /* Determines if audit header is included in audited messages.  This
1569  * provides more context if the audit daemon is not running
1570  */
1571 bool aa_g_audit_header = true;
1572 module_param_named(audit_header, aa_g_audit_header, aabool,
1573 		   S_IRUSR | S_IWUSR);
1574 
1575 /* lock out loading/removal of policy
1576  * TODO: add in at boot loading of policy, which is the only way to
1577  *       load policy, if lock_policy is set
1578  */
1579 bool aa_g_lock_policy;
1580 module_param_named(lock_policy, aa_g_lock_policy, aalockpolicy,
1581 		   S_IRUSR | S_IWUSR);
1582 
1583 /* Syscall logging mode */
1584 bool aa_g_logsyscall;
1585 module_param_named(logsyscall, aa_g_logsyscall, aabool, S_IRUSR | S_IWUSR);
1586 
1587 /* Maximum pathname length before accesses will start getting rejected */
1588 unsigned int aa_g_path_max = 2 * PATH_MAX;
1589 module_param_named(path_max, aa_g_path_max, aauint, S_IRUSR);
1590 
1591 /* Determines how paranoid loading of policy is and how much verification
1592  * on the loaded policy is done.
1593  * DEPRECATED: read only as strict checking of load is always done now
1594  * that none root users (user namespaces) can load policy.
1595  */
1596 bool aa_g_paranoid_load = IS_ENABLED(CONFIG_SECURITY_APPARMOR_PARANOID_LOAD);
1597 module_param_named(paranoid_load, aa_g_paranoid_load, aabool, S_IRUGO);
1598 
1599 static int param_get_aaintbool(char *buffer, const struct kernel_param *kp);
1600 static int param_set_aaintbool(const char *val, const struct kernel_param *kp);
1601 #define param_check_aaintbool param_check_int
1602 static const struct kernel_param_ops param_ops_aaintbool = {
1603 	.set = param_set_aaintbool,
1604 	.get = param_get_aaintbool
1605 };
1606 /* Boot time disable flag */
1607 static int apparmor_enabled __ro_after_init = 1;
1608 module_param_named(enabled, apparmor_enabled, aaintbool, 0444);
1609 
1610 static int __init apparmor_enabled_setup(char *str)
1611 {
1612 	unsigned long enabled;
1613 	int error = kstrtoul(str, 0, &enabled);
1614 	if (!error)
1615 		apparmor_enabled = enabled ? 1 : 0;
1616 	return 1;
1617 }
1618 
1619 __setup("apparmor=", apparmor_enabled_setup);
1620 
1621 /* set global flag turning off the ability to load policy */
1622 static int param_set_aalockpolicy(const char *val, const struct kernel_param *kp)
1623 {
1624 	if (!apparmor_enabled)
1625 		return -EINVAL;
1626 	if (apparmor_initialized && !aa_current_policy_admin_capable(NULL))
1627 		return -EPERM;
1628 	return param_set_bool(val, kp);
1629 }
1630 
1631 static int param_get_aalockpolicy(char *buffer, const struct kernel_param *kp)
1632 {
1633 	if (!apparmor_enabled)
1634 		return -EINVAL;
1635 	if (apparmor_initialized && !aa_current_policy_view_capable(NULL))
1636 		return -EPERM;
1637 	return param_get_bool(buffer, kp);
1638 }
1639 
1640 static int param_set_aabool(const char *val, const struct kernel_param *kp)
1641 {
1642 	if (!apparmor_enabled)
1643 		return -EINVAL;
1644 	if (apparmor_initialized && !aa_current_policy_admin_capable(NULL))
1645 		return -EPERM;
1646 	return param_set_bool(val, kp);
1647 }
1648 
1649 static int param_get_aabool(char *buffer, const struct kernel_param *kp)
1650 {
1651 	if (!apparmor_enabled)
1652 		return -EINVAL;
1653 	if (apparmor_initialized && !aa_current_policy_view_capable(NULL))
1654 		return -EPERM;
1655 	return param_get_bool(buffer, kp);
1656 }
1657 
1658 static int param_set_aauint(const char *val, const struct kernel_param *kp)
1659 {
1660 	int error;
1661 
1662 	if (!apparmor_enabled)
1663 		return -EINVAL;
1664 	/* file is ro but enforce 2nd line check */
1665 	if (apparmor_initialized)
1666 		return -EPERM;
1667 
1668 	error = param_set_uint(val, kp);
1669 	aa_g_path_max = max_t(uint32_t, aa_g_path_max, sizeof(union aa_buffer));
1670 	pr_info("AppArmor: buffer size set to %d bytes\n", aa_g_path_max);
1671 
1672 	return error;
1673 }
1674 
1675 static int param_get_aauint(char *buffer, const struct kernel_param *kp)
1676 {
1677 	if (!apparmor_enabled)
1678 		return -EINVAL;
1679 	if (apparmor_initialized && !aa_current_policy_view_capable(NULL))
1680 		return -EPERM;
1681 	return param_get_uint(buffer, kp);
1682 }
1683 
1684 /* Can only be set before AppArmor is initialized (i.e. on boot cmdline). */
1685 static int param_set_aaintbool(const char *val, const struct kernel_param *kp)
1686 {
1687 	struct kernel_param kp_local;
1688 	bool value;
1689 	int error;
1690 
1691 	if (apparmor_initialized)
1692 		return -EPERM;
1693 
1694 	/* Create local copy, with arg pointing to bool type. */
1695 	value = !!*((int *)kp->arg);
1696 	memcpy(&kp_local, kp, sizeof(kp_local));
1697 	kp_local.arg = &value;
1698 
1699 	error = param_set_bool(val, &kp_local);
1700 	if (!error)
1701 		*((int *)kp->arg) = *((bool *)kp_local.arg);
1702 	return error;
1703 }
1704 
1705 /*
1706  * To avoid changing /sys/module/apparmor/parameters/enabled from Y/N to
1707  * 1/0, this converts the "int that is actually bool" back to bool for
1708  * display in the /sys filesystem, while keeping it "int" for the LSM
1709  * infrastructure.
1710  */
1711 static int param_get_aaintbool(char *buffer, const struct kernel_param *kp)
1712 {
1713 	struct kernel_param kp_local;
1714 	bool value;
1715 
1716 	/* Create local copy, with arg pointing to bool type. */
1717 	value = !!*((int *)kp->arg);
1718 	memcpy(&kp_local, kp, sizeof(kp_local));
1719 	kp_local.arg = &value;
1720 
1721 	return param_get_bool(buffer, &kp_local);
1722 }
1723 
1724 static int param_set_aacompressionlevel(const char *val,
1725 					const struct kernel_param *kp)
1726 {
1727 	int error;
1728 
1729 	if (!apparmor_enabled)
1730 		return -EINVAL;
1731 	if (apparmor_initialized)
1732 		return -EPERM;
1733 
1734 	error = param_set_int(val, kp);
1735 
1736 	aa_g_rawdata_compression_level = clamp(aa_g_rawdata_compression_level,
1737 					       AA_MIN_CLEVEL, AA_MAX_CLEVEL);
1738 	pr_info("AppArmor: policy rawdata compression level set to %d\n",
1739 		aa_g_rawdata_compression_level);
1740 
1741 	return error;
1742 }
1743 
1744 static int param_get_aacompressionlevel(char *buffer,
1745 					const struct kernel_param *kp)
1746 {
1747 	if (!apparmor_enabled)
1748 		return -EINVAL;
1749 	if (apparmor_initialized && !aa_current_policy_view_capable(NULL))
1750 		return -EPERM;
1751 	return param_get_int(buffer, kp);
1752 }
1753 
1754 static int param_get_audit(char *buffer, const struct kernel_param *kp)
1755 {
1756 	if (!apparmor_enabled)
1757 		return -EINVAL;
1758 	if (apparmor_initialized && !aa_current_policy_view_capable(NULL))
1759 		return -EPERM;
1760 	return sprintf(buffer, "%s", audit_mode_names[aa_g_audit]);
1761 }
1762 
1763 static int param_set_audit(const char *val, const struct kernel_param *kp)
1764 {
1765 	int i;
1766 
1767 	if (!apparmor_enabled)
1768 		return -EINVAL;
1769 	if (!val)
1770 		return -EINVAL;
1771 	if (apparmor_initialized && !aa_current_policy_admin_capable(NULL))
1772 		return -EPERM;
1773 
1774 	i = match_string(audit_mode_names, AUDIT_MAX_INDEX, val);
1775 	if (i < 0)
1776 		return -EINVAL;
1777 
1778 	aa_g_audit = i;
1779 	return 0;
1780 }
1781 
1782 static int param_get_mode(char *buffer, const struct kernel_param *kp)
1783 {
1784 	if (!apparmor_enabled)
1785 		return -EINVAL;
1786 	if (apparmor_initialized && !aa_current_policy_view_capable(NULL))
1787 		return -EPERM;
1788 
1789 	return sprintf(buffer, "%s", aa_profile_mode_names[aa_g_profile_mode]);
1790 }
1791 
1792 static int param_set_mode(const char *val, const struct kernel_param *kp)
1793 {
1794 	int i;
1795 
1796 	if (!apparmor_enabled)
1797 		return -EINVAL;
1798 	if (!val)
1799 		return -EINVAL;
1800 	if (apparmor_initialized && !aa_current_policy_admin_capable(NULL))
1801 		return -EPERM;
1802 
1803 	i = match_string(aa_profile_mode_names, APPARMOR_MODE_NAMES_MAX_INDEX,
1804 			 val);
1805 	if (i < 0)
1806 		return -EINVAL;
1807 
1808 	aa_g_profile_mode = i;
1809 	return 0;
1810 }
1811 
1812 char *aa_get_buffer(bool in_atomic)
1813 {
1814 	union aa_buffer *aa_buf;
1815 	struct aa_local_cache *cache;
1816 	bool try_again = true;
1817 	gfp_t flags = (GFP_KERNEL | __GFP_RETRY_MAYFAIL | __GFP_NOWARN);
1818 
1819 	/* use per cpu cached buffers first */
1820 	cache = get_cpu_ptr(&aa_local_buffers);
1821 	if (!list_empty(&cache->head)) {
1822 		aa_buf = list_first_entry(&cache->head, union aa_buffer, list);
1823 		list_del(&aa_buf->list);
1824 		cache->hold--;
1825 		cache->count--;
1826 		put_cpu_ptr(&aa_local_buffers);
1827 		return &aa_buf->buffer[0];
1828 	}
1829 	put_cpu_ptr(&aa_local_buffers);
1830 
1831 	if (!spin_trylock(&aa_buffers_lock)) {
1832 		cache = get_cpu_ptr(&aa_local_buffers);
1833 		cache->hold += 1;
1834 		put_cpu_ptr(&aa_local_buffers);
1835 		spin_lock(&aa_buffers_lock);
1836 	} else {
1837 		cache = get_cpu_ptr(&aa_local_buffers);
1838 		put_cpu_ptr(&aa_local_buffers);
1839 	}
1840 retry:
1841 	if (buffer_count > reserve_count ||
1842 	    (in_atomic && !list_empty(&aa_global_buffers))) {
1843 		aa_buf = list_first_entry(&aa_global_buffers, union aa_buffer,
1844 					  list);
1845 		list_del(&aa_buf->list);
1846 		buffer_count--;
1847 		spin_unlock(&aa_buffers_lock);
1848 		return aa_buf->buffer;
1849 	}
1850 	if (in_atomic) {
1851 		/*
1852 		 * out of reserve buffers and in atomic context so increase
1853 		 * how many buffers to keep in reserve
1854 		 */
1855 		reserve_count++;
1856 		flags = GFP_ATOMIC;
1857 	}
1858 	spin_unlock(&aa_buffers_lock);
1859 
1860 	if (!in_atomic)
1861 		might_sleep();
1862 	aa_buf = kmalloc(aa_g_path_max, flags);
1863 	if (!aa_buf) {
1864 		if (try_again) {
1865 			try_again = false;
1866 			spin_lock(&aa_buffers_lock);
1867 			goto retry;
1868 		}
1869 		pr_warn_once("AppArmor: Failed to allocate a memory buffer.\n");
1870 		return NULL;
1871 	}
1872 	return aa_buf->buffer;
1873 }
1874 
1875 void aa_put_buffer(char *buf)
1876 {
1877 	union aa_buffer *aa_buf;
1878 	struct aa_local_cache *cache;
1879 
1880 	if (!buf)
1881 		return;
1882 	aa_buf = container_of(buf, union aa_buffer, buffer[0]);
1883 
1884 	cache = get_cpu_ptr(&aa_local_buffers);
1885 	if (!cache->hold) {
1886 		put_cpu_ptr(&aa_local_buffers);
1887 
1888 		if (spin_trylock(&aa_buffers_lock)) {
1889 			/* put back on global list */
1890 			list_add(&aa_buf->list, &aa_global_buffers);
1891 			buffer_count++;
1892 			spin_unlock(&aa_buffers_lock);
1893 			cache = get_cpu_ptr(&aa_local_buffers);
1894 			put_cpu_ptr(&aa_local_buffers);
1895 			return;
1896 		}
1897 		/* contention on global list, fallback to percpu */
1898 		cache = get_cpu_ptr(&aa_local_buffers);
1899 		cache->hold += 1;
1900 	}
1901 
1902 	/* cache in percpu list */
1903 	list_add(&aa_buf->list, &cache->head);
1904 	cache->count++;
1905 	put_cpu_ptr(&aa_local_buffers);
1906 }
1907 
1908 /*
1909  * AppArmor init functions
1910  */
1911 
1912 /**
1913  * set_init_ctx - set a task context and profile on the first task.
1914  *
1915  * TODO: allow setting an alternate profile than unconfined
1916  */
1917 static int __init set_init_ctx(void)
1918 {
1919 	struct cred *cred = (__force struct cred *)current->real_cred;
1920 
1921 	set_cred_label(cred, aa_get_label(ns_unconfined(root_ns)));
1922 
1923 	return 0;
1924 }
1925 
1926 static void destroy_buffers(void)
1927 {
1928 	union aa_buffer *aa_buf;
1929 
1930 	spin_lock(&aa_buffers_lock);
1931 	while (!list_empty(&aa_global_buffers)) {
1932 		aa_buf = list_first_entry(&aa_global_buffers, union aa_buffer,
1933 					 list);
1934 		list_del(&aa_buf->list);
1935 		spin_unlock(&aa_buffers_lock);
1936 		kfree(aa_buf);
1937 		spin_lock(&aa_buffers_lock);
1938 	}
1939 	spin_unlock(&aa_buffers_lock);
1940 }
1941 
1942 static int __init alloc_buffers(void)
1943 {
1944 	union aa_buffer *aa_buf;
1945 	int i, num;
1946 
1947 	/*
1948 	 * per cpu set of cached allocated buffers used to help reduce
1949 	 * lock contention
1950 	 */
1951 	for_each_possible_cpu(i) {
1952 		per_cpu(aa_local_buffers, i).hold = 0;
1953 		per_cpu(aa_local_buffers, i).count = 0;
1954 		INIT_LIST_HEAD(&per_cpu(aa_local_buffers, i).head);
1955 	}
1956 	/*
1957 	 * A function may require two buffers at once. Usually the buffers are
1958 	 * used for a short period of time and are shared. On UP kernel buffers
1959 	 * two should be enough, with more CPUs it is possible that more
1960 	 * buffers will be used simultaneously. The preallocated pool may grow.
1961 	 * This preallocation has also the side-effect that AppArmor will be
1962 	 * disabled early at boot if aa_g_path_max is extremly high.
1963 	 */
1964 	if (num_online_cpus() > 1)
1965 		num = 4 + RESERVE_COUNT;
1966 	else
1967 		num = 2 + RESERVE_COUNT;
1968 
1969 	for (i = 0; i < num; i++) {
1970 
1971 		aa_buf = kmalloc(aa_g_path_max, GFP_KERNEL |
1972 				 __GFP_RETRY_MAYFAIL | __GFP_NOWARN);
1973 		if (!aa_buf) {
1974 			destroy_buffers();
1975 			return -ENOMEM;
1976 		}
1977 		aa_put_buffer(aa_buf->buffer);
1978 	}
1979 	return 0;
1980 }
1981 
1982 #ifdef CONFIG_SYSCTL
1983 static int apparmor_dointvec(struct ctl_table *table, int write,
1984 			     void *buffer, size_t *lenp, loff_t *ppos)
1985 {
1986 	if (!aa_current_policy_admin_capable(NULL))
1987 		return -EPERM;
1988 	if (!apparmor_enabled)
1989 		return -EINVAL;
1990 
1991 	return proc_dointvec(table, write, buffer, lenp, ppos);
1992 }
1993 
1994 static struct ctl_table apparmor_sysctl_table[] = {
1995 #ifdef CONFIG_USER_NS
1996 	{
1997 		.procname       = "unprivileged_userns_apparmor_policy",
1998 		.data           = &unprivileged_userns_apparmor_policy,
1999 		.maxlen         = sizeof(int),
2000 		.mode           = 0600,
2001 		.proc_handler   = apparmor_dointvec,
2002 	},
2003 #endif /* CONFIG_USER_NS */
2004 	{
2005 		.procname       = "apparmor_display_secid_mode",
2006 		.data           = &apparmor_display_secid_mode,
2007 		.maxlen         = sizeof(int),
2008 		.mode           = 0600,
2009 		.proc_handler   = apparmor_dointvec,
2010 	},
2011 	{
2012 		.procname       = "apparmor_restrict_unprivileged_unconfined",
2013 		.data           = &aa_unprivileged_unconfined_restricted,
2014 		.maxlen         = sizeof(int),
2015 		.mode           = 0600,
2016 		.proc_handler   = apparmor_dointvec,
2017 	},
2018 	{ }
2019 };
2020 
2021 static int __init apparmor_init_sysctl(void)
2022 {
2023 	return register_sysctl("kernel", apparmor_sysctl_table) ? 0 : -ENOMEM;
2024 }
2025 #else
2026 static inline int apparmor_init_sysctl(void)
2027 {
2028 	return 0;
2029 }
2030 #endif /* CONFIG_SYSCTL */
2031 
2032 #if defined(CONFIG_NETFILTER) && defined(CONFIG_NETWORK_SECMARK)
2033 static unsigned int apparmor_ip_postroute(void *priv,
2034 					  struct sk_buff *skb,
2035 					  const struct nf_hook_state *state)
2036 {
2037 	struct aa_sk_ctx *ctx;
2038 	struct sock *sk;
2039 
2040 	if (!skb->secmark)
2041 		return NF_ACCEPT;
2042 
2043 	sk = skb_to_full_sk(skb);
2044 	if (sk == NULL)
2045 		return NF_ACCEPT;
2046 
2047 	ctx = aa_sock(sk);
2048 	if (!apparmor_secmark_check(ctx->label, OP_SENDMSG, AA_MAY_SEND,
2049 				    skb->secmark, sk))
2050 		return NF_ACCEPT;
2051 
2052 	return NF_DROP_ERR(-ECONNREFUSED);
2053 
2054 }
2055 
2056 static const struct nf_hook_ops apparmor_nf_ops[] = {
2057 	{
2058 		.hook =         apparmor_ip_postroute,
2059 		.pf =           NFPROTO_IPV4,
2060 		.hooknum =      NF_INET_POST_ROUTING,
2061 		.priority =     NF_IP_PRI_SELINUX_FIRST,
2062 	},
2063 #if IS_ENABLED(CONFIG_IPV6)
2064 	{
2065 		.hook =         apparmor_ip_postroute,
2066 		.pf =           NFPROTO_IPV6,
2067 		.hooknum =      NF_INET_POST_ROUTING,
2068 		.priority =     NF_IP6_PRI_SELINUX_FIRST,
2069 	},
2070 #endif
2071 };
2072 
2073 static int __net_init apparmor_nf_register(struct net *net)
2074 {
2075 	return nf_register_net_hooks(net, apparmor_nf_ops,
2076 				    ARRAY_SIZE(apparmor_nf_ops));
2077 }
2078 
2079 static void __net_exit apparmor_nf_unregister(struct net *net)
2080 {
2081 	nf_unregister_net_hooks(net, apparmor_nf_ops,
2082 				ARRAY_SIZE(apparmor_nf_ops));
2083 }
2084 
2085 static struct pernet_operations apparmor_net_ops = {
2086 	.init = apparmor_nf_register,
2087 	.exit = apparmor_nf_unregister,
2088 };
2089 
2090 static int __init apparmor_nf_ip_init(void)
2091 {
2092 	int err;
2093 
2094 	if (!apparmor_enabled)
2095 		return 0;
2096 
2097 	err = register_pernet_subsys(&apparmor_net_ops);
2098 	if (err)
2099 		panic("Apparmor: register_pernet_subsys: error %d\n", err);
2100 
2101 	return 0;
2102 }
2103 __initcall(apparmor_nf_ip_init);
2104 #endif
2105 
2106 static char nulldfa_src[] = {
2107 	#include "nulldfa.in"
2108 };
2109 struct aa_dfa *nulldfa;
2110 
2111 static char stacksplitdfa_src[] = {
2112 	#include "stacksplitdfa.in"
2113 };
2114 struct aa_dfa *stacksplitdfa;
2115 struct aa_policydb *nullpdb;
2116 
2117 static int __init aa_setup_dfa_engine(void)
2118 {
2119 	int error = -ENOMEM;
2120 
2121 	nullpdb = aa_alloc_pdb(GFP_KERNEL);
2122 	if (!nullpdb)
2123 		return -ENOMEM;
2124 
2125 	nulldfa = aa_dfa_unpack(nulldfa_src, sizeof(nulldfa_src),
2126 			    TO_ACCEPT1_FLAG(YYTD_DATA32) |
2127 			    TO_ACCEPT2_FLAG(YYTD_DATA32));
2128 	if (IS_ERR(nulldfa)) {
2129 		error = PTR_ERR(nulldfa);
2130 		goto fail;
2131 	}
2132 	nullpdb->dfa = aa_get_dfa(nulldfa);
2133 	nullpdb->perms = kcalloc(2, sizeof(struct aa_perms), GFP_KERNEL);
2134 	if (!nullpdb->perms)
2135 		goto fail;
2136 	nullpdb->size = 2;
2137 
2138 	stacksplitdfa = aa_dfa_unpack(stacksplitdfa_src,
2139 				      sizeof(stacksplitdfa_src),
2140 				      TO_ACCEPT1_FLAG(YYTD_DATA32) |
2141 				      TO_ACCEPT2_FLAG(YYTD_DATA32));
2142 	if (IS_ERR(stacksplitdfa)) {
2143 		error = PTR_ERR(stacksplitdfa);
2144 		goto fail;
2145 	}
2146 
2147 	return 0;
2148 
2149 fail:
2150 	aa_put_pdb(nullpdb);
2151 	aa_put_dfa(nulldfa);
2152 	nullpdb = NULL;
2153 	nulldfa = NULL;
2154 	stacksplitdfa = NULL;
2155 
2156 	return error;
2157 }
2158 
2159 static void __init aa_teardown_dfa_engine(void)
2160 {
2161 	aa_put_dfa(stacksplitdfa);
2162 	aa_put_dfa(nulldfa);
2163 	aa_put_pdb(nullpdb);
2164 	nullpdb = NULL;
2165 	stacksplitdfa = NULL;
2166 	nulldfa = NULL;
2167 }
2168 
2169 static int __init apparmor_init(void)
2170 {
2171 	int error;
2172 
2173 	error = aa_setup_dfa_engine();
2174 	if (error) {
2175 		AA_ERROR("Unable to setup dfa engine\n");
2176 		goto alloc_out;
2177 	}
2178 
2179 	error = aa_alloc_root_ns();
2180 	if (error) {
2181 		AA_ERROR("Unable to allocate default profile namespace\n");
2182 		goto alloc_out;
2183 	}
2184 
2185 	error = apparmor_init_sysctl();
2186 	if (error) {
2187 		AA_ERROR("Unable to register sysctls\n");
2188 		goto alloc_out;
2189 
2190 	}
2191 
2192 	error = alloc_buffers();
2193 	if (error) {
2194 		AA_ERROR("Unable to allocate work buffers\n");
2195 		goto alloc_out;
2196 	}
2197 
2198 	error = set_init_ctx();
2199 	if (error) {
2200 		AA_ERROR("Failed to set context on init task\n");
2201 		aa_free_root_ns();
2202 		goto buffers_out;
2203 	}
2204 	security_add_hooks(apparmor_hooks, ARRAY_SIZE(apparmor_hooks),
2205 				"apparmor");
2206 
2207 	/* Report that AppArmor successfully initialized */
2208 	apparmor_initialized = 1;
2209 	if (aa_g_profile_mode == APPARMOR_COMPLAIN)
2210 		aa_info_message("AppArmor initialized: complain mode enabled");
2211 	else if (aa_g_profile_mode == APPARMOR_KILL)
2212 		aa_info_message("AppArmor initialized: kill mode enabled");
2213 	else
2214 		aa_info_message("AppArmor initialized");
2215 
2216 	return error;
2217 
2218 buffers_out:
2219 	destroy_buffers();
2220 alloc_out:
2221 	aa_destroy_aafs();
2222 	aa_teardown_dfa_engine();
2223 
2224 	apparmor_enabled = false;
2225 	return error;
2226 }
2227 
2228 DEFINE_LSM(apparmor) = {
2229 	.name = "apparmor",
2230 	.flags = LSM_FLAG_LEGACY_MAJOR | LSM_FLAG_EXCLUSIVE,
2231 	.enabled = &apparmor_enabled,
2232 	.blobs = &apparmor_blob_sizes,
2233 	.init = apparmor_init,
2234 };
2235