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