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