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