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