Linux Audio

Check our new training course

Linux debugging, profiling, tracing and performance analysis training

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