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