File Index
Files and directories
Sign in
FILE

lsm.c

File preview with syntax highlighting.

linux-6.19.14/security/apparmor/lsm.c C
   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/af_unix.h"
  30#include "include/apparmor.h"
  31#include "include/apparmorfs.h"
  32#include "include/audit.h"
  33#include "include/capability.h"
  34#include "include/cred.h"
  35#include "include/crypto.h"
  36#include "include/file.h"
  37#include "include/ipc.h"
  38#include "include/net.h"
  39#include "include/path.h"
  40#include "include/label.h"
  41#include "include/policy.h"
  42#include "include/policy_ns.h"
  43#include "include/procattr.h"
  44#include "include/mount.h"
  45#include "include/secid.h"
  46
  47/* Flag indicating whether initialization completed */
  48int apparmor_initialized;
  49
  50union aa_buffer {
  51	struct list_head list;
  52	DECLARE_FLEX_ARRAY(char, buffer);
  53};
  54
  55struct aa_local_cache {
  56	unsigned int hold;
  57	unsigned int count;
  58	struct list_head head;
  59};
  60
  61#define RESERVE_COUNT 2
  62static int reserve_count = RESERVE_COUNT;
  63static int buffer_count;
  64
  65static LIST_HEAD(aa_global_buffers);
  66static DEFINE_SPINLOCK(aa_buffers_lock);
  67static DEFINE_PER_CPU(struct aa_local_cache, aa_local_buffers);
  68
  69/*
  70 * LSM hook functions
  71 */
  72
  73/*
  74 * put the associated labels
  75 */
  76static void apparmor_cred_free(struct cred *cred)
  77{
  78	aa_put_label(cred_label(cred));
  79	set_cred_label(cred, NULL);
  80}
  81
  82/*
  83 * allocate the apparmor part of blank credentials
  84 */
  85static int apparmor_cred_alloc_blank(struct cred *cred, gfp_t gfp)
  86{
  87	set_cred_label(cred, NULL);
  88	return 0;
  89}
  90
  91/*
  92 * prepare new cred label for modification by prepare_cred block
  93 */
  94static int apparmor_cred_prepare(struct cred *new, const struct cred *old,
  95				 gfp_t gfp)
  96{
  97	set_cred_label(new, aa_get_newest_label(cred_label(old)));
  98	return 0;
  99}
 100
 101/*
 102 * transfer the apparmor data to a blank set of creds
 103 */
 104static void apparmor_cred_transfer(struct cred *new, const struct cred *old)
 105{
 106	set_cred_label(new, aa_get_newest_label(cred_label(old)));
 107}
 108
 109static void apparmor_task_free(struct task_struct *task)
 110{
 111
 112	aa_free_task_ctx(task_ctx(task));
 113}
 114
 115static int apparmor_task_alloc(struct task_struct *task,
 116			       u64 clone_flags)
 117{
 118	struct aa_task_ctx *new = task_ctx(task);
 119
 120	aa_dup_task_ctx(new, task_ctx(current));
 121
 122	return 0;
 123}
 124
 125static int apparmor_ptrace_access_check(struct task_struct *child,
 126					unsigned int mode)
 127{
 128	struct aa_label *tracer, *tracee;
 129	const struct cred *cred;
 130	int error;
 131	bool needput;
 132
 133	cred = get_task_cred(child);
 134	tracee = cred_label(cred);	/* ref count on cred */
 135	tracer = __begin_current_label_crit_section(&needput);
 136	error = aa_may_ptrace(current_cred(), tracer, cred, tracee,
 137			(mode & PTRACE_MODE_READ) ? AA_PTRACE_READ
 138						  : AA_PTRACE_TRACE);
 139	__end_current_label_crit_section(tracer, needput);
 140	put_cred(cred);
 141
 142	return error;
 143}
 144
 145static int apparmor_ptrace_traceme(struct task_struct *parent)
 146{
 147	struct aa_label *tracer, *tracee;
 148	const struct cred *cred;
 149	int error;
 150	bool needput;
 151
 152	tracee = __begin_current_label_crit_section(&needput);
 153	cred = get_task_cred(parent);
 154	tracer = cred_label(cred);	/* ref count on cred */
 155	error = aa_may_ptrace(cred, tracer, current_cred(), tracee,
 156			      AA_PTRACE_TRACE);
 157	put_cred(cred);
 158	__end_current_label_crit_section(tracee, needput);
 159
 160	return error;
 161}
 162
 163/* Derived from security/commoncap.c:cap_capget */
 164static int apparmor_capget(const struct task_struct *target, kernel_cap_t *effective,
 165			   kernel_cap_t *inheritable, kernel_cap_t *permitted)
 166{
 167	struct aa_label *label;
 168	const struct cred *cred;
 169
 170	rcu_read_lock();
 171	cred = __task_cred(target);
 172	label = aa_get_newest_cred_label(cred);
 173
 174	/*
 175	 * cap_capget is stacked ahead of this and will
 176	 * initialize effective and permitted.
 177	 */
 178	if (!unconfined(label)) {
 179		struct aa_profile *profile;
 180		struct label_it i;
 181
 182		label_for_each_confined(i, label, profile) {
 183			kernel_cap_t allowed;
 184
 185			allowed = aa_profile_capget(profile);
 186			*effective = cap_intersect(*effective, allowed);
 187			*permitted = cap_intersect(*permitted, allowed);
 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	bool needput;
 225
 226	label = __begin_current_label_crit_section(&needput);
 227	if (!unconfined(label))
 228		error = aa_path_perm(op, current_cred(), label, path, 0, mask,
 229				     cond);
 230	__end_current_label_crit_section(label, needput);
 231
 232	return error;
 233}
 234
 235/**
 236 * common_perm_cond - common permission wrapper around inode cond
 237 * @op: operation being checked
 238 * @path: location to check (NOT NULL)
 239 * @mask: requested permissions mask
 240 *
 241 * Returns: %0 else error code if error or permission denied
 242 */
 243static int common_perm_cond(const char *op, const struct path *path, u32 mask)
 244{
 245	vfsuid_t vfsuid = i_uid_into_vfsuid(mnt_idmap(path->mnt),
 246					    d_backing_inode(path->dentry));
 247	struct path_cond cond = {
 248		vfsuid_into_kuid(vfsuid),
 249		d_backing_inode(path->dentry)->i_mode
 250	};
 251
 252	if (!path_mediated_fs(path->dentry))
 253		return 0;
 254
 255	return common_perm(op, path, mask, &cond);
 256}
 257
 258/**
 259 * common_perm_dir_dentry - common permission wrapper when path is dir, dentry
 260 * @op: operation being checked
 261 * @dir: directory of the dentry  (NOT NULL)
 262 * @dentry: dentry to check  (NOT NULL)
 263 * @mask: requested permissions mask
 264 * @cond: conditional info for the permission request  (NOT NULL)
 265 *
 266 * Returns: %0 else error code if error or permission denied
 267 */
 268static int common_perm_dir_dentry(const char *op, const struct path *dir,
 269				  struct dentry *dentry, u32 mask,
 270				  struct path_cond *cond)
 271{
 272	struct path path = { .mnt = dir->mnt, .dentry = dentry };
 273
 274	return common_perm(op, &path, mask, cond);
 275}
 276
 277/**
 278 * common_perm_rm - common permission wrapper for operations doing rm
 279 * @op: operation being checked
 280 * @dir: directory that the dentry is in  (NOT NULL)
 281 * @dentry: dentry being rm'd  (NOT NULL)
 282 * @mask: requested permission mask
 283 *
 284 * Returns: %0 else error code if error or permission denied
 285 */
 286static int common_perm_rm(const char *op, const struct path *dir,
 287			  struct dentry *dentry, u32 mask)
 288{
 289	struct inode *inode = d_backing_inode(dentry);
 290	struct path_cond cond = { };
 291	vfsuid_t vfsuid;
 292
 293	if (!inode || !path_mediated_fs(dentry))
 294		return 0;
 295
 296	vfsuid = i_uid_into_vfsuid(mnt_idmap(dir->mnt), inode);
 297	cond.uid = vfsuid_into_kuid(vfsuid);
 298	cond.mode = inode->i_mode;
 299
 300	return common_perm_dir_dentry(op, dir, dentry, mask, &cond);
 301}
 302
 303/**
 304 * common_perm_create - common permission wrapper for operations doing create
 305 * @op: operation being checked
 306 * @dir: directory that dentry will be created in  (NOT NULL)
 307 * @dentry: dentry to create   (NOT NULL)
 308 * @mask: request permission mask
 309 * @mode: created file mode
 310 *
 311 * Returns: %0 else error code if error or permission denied
 312 */
 313static int common_perm_create(const char *op, const struct path *dir,
 314			      struct dentry *dentry, u32 mask, umode_t mode)
 315{
 316	struct path_cond cond = { current_fsuid(), mode };
 317
 318	if (!path_mediated_fs(dir->dentry))
 319		return 0;
 320
 321	return common_perm_dir_dentry(op, dir, dentry, mask, &cond);
 322}
 323
 324static int apparmor_path_unlink(const struct path *dir, struct dentry *dentry)
 325{
 326	return common_perm_rm(OP_UNLINK, dir, dentry, AA_MAY_DELETE);
 327}
 328
 329static int apparmor_path_mkdir(const struct path *dir, struct dentry *dentry,
 330			       umode_t mode)
 331{
 332	return common_perm_create(OP_MKDIR, dir, dentry, AA_MAY_CREATE,
 333				  S_IFDIR);
 334}
 335
 336static int apparmor_path_rmdir(const struct path *dir, struct dentry *dentry)
 337{
 338	return common_perm_rm(OP_RMDIR, dir, dentry, AA_MAY_DELETE);
 339}
 340
 341static int apparmor_path_mknod(const struct path *dir, struct dentry *dentry,
 342			       umode_t mode, unsigned int dev)
 343{
 344	return common_perm_create(OP_MKNOD, dir, dentry, AA_MAY_CREATE, mode);
 345}
 346
 347static int apparmor_path_truncate(const struct path *path)
 348{
 349	return common_perm_cond(OP_TRUNC, path, MAY_WRITE | AA_MAY_SETATTR);
 350}
 351
 352static int apparmor_file_truncate(struct file *file)
 353{
 354	return apparmor_path_truncate(&file->f_path);
 355}
 356
 357static int apparmor_path_symlink(const struct path *dir, struct dentry *dentry,
 358				 const char *old_name)
 359{
 360	return common_perm_create(OP_SYMLINK, dir, dentry, AA_MAY_CREATE,
 361				  S_IFLNK);
 362}
 363
 364static int apparmor_path_link(struct dentry *old_dentry, const struct path *new_dir,
 365			      struct dentry *new_dentry)
 366{
 367	struct aa_label *label;
 368	int error = 0;
 369
 370	if (!path_mediated_fs(old_dentry))
 371		return 0;
 372
 373	label = begin_current_label_crit_section();
 374	if (!unconfined(label))
 375		error = aa_path_link(current_cred(), label, old_dentry, new_dir,
 376				     new_dentry);
 377	end_current_label_crit_section(label);
 378
 379	return error;
 380}
 381
 382static int apparmor_path_rename(const struct path *old_dir, struct dentry *old_dentry,
 383				const struct path *new_dir, struct dentry *new_dentry,
 384				const unsigned int flags)
 385{
 386	struct aa_label *label;
 387	int error = 0;
 388
 389	if (!path_mediated_fs(old_dentry))
 390		return 0;
 391	if ((flags & RENAME_EXCHANGE) && !path_mediated_fs(new_dentry))
 392		return 0;
 393
 394	label = begin_current_label_crit_section();
 395	if (!unconfined(label)) {
 396		struct mnt_idmap *idmap = mnt_idmap(old_dir->mnt);
 397		vfsuid_t vfsuid;
 398		struct path old_path = { .mnt = old_dir->mnt,
 399					 .dentry = old_dentry };
 400		struct path new_path = { .mnt = new_dir->mnt,
 401					 .dentry = new_dentry };
 402		struct path_cond cond = {
 403			.mode = d_backing_inode(old_dentry)->i_mode
 404		};
 405		vfsuid = i_uid_into_vfsuid(idmap, d_backing_inode(old_dentry));
 406		cond.uid = vfsuid_into_kuid(vfsuid);
 407
 408		if (flags & RENAME_EXCHANGE) {
 409			struct path_cond cond_exchange = {
 410				.mode = d_backing_inode(new_dentry)->i_mode,
 411			};
 412			vfsuid = i_uid_into_vfsuid(idmap, d_backing_inode(old_dentry));
 413			cond_exchange.uid = vfsuid_into_kuid(vfsuid);
 414
 415			error = aa_path_perm(OP_RENAME_SRC, current_cred(),
 416					     label, &new_path, 0,
 417					     MAY_READ | AA_MAY_GETATTR | MAY_WRITE |
 418					     AA_MAY_SETATTR | AA_MAY_DELETE,
 419					     &cond_exchange);
 420			if (!error)
 421				error = aa_path_perm(OP_RENAME_DEST, current_cred(),
 422						     label, &old_path,
 423						     0, MAY_WRITE | AA_MAY_SETATTR |
 424						     AA_MAY_CREATE, &cond_exchange);
 425		}
 426
 427		if (!error)
 428			error = aa_path_perm(OP_RENAME_SRC, current_cred(),
 429					     label, &old_path, 0,
 430					     MAY_READ | AA_MAY_GETATTR | MAY_WRITE |
 431					     AA_MAY_SETATTR | AA_MAY_DELETE,
 432					     &cond);
 433		if (!error)
 434			error = aa_path_perm(OP_RENAME_DEST, current_cred(),
 435					     label, &new_path,
 436					     0, MAY_WRITE | AA_MAY_SETATTR |
 437					     AA_MAY_CREATE, &cond);
 438
 439	}
 440	end_current_label_crit_section(label);
 441
 442	return error;
 443}
 444
 445static int apparmor_path_chmod(const struct path *path, umode_t mode)
 446{
 447	return common_perm_cond(OP_CHMOD, path, AA_MAY_CHMOD);
 448}
 449
 450static int apparmor_path_chown(const struct path *path, kuid_t uid, kgid_t gid)
 451{
 452	return common_perm_cond(OP_CHOWN, path, AA_MAY_CHOWN);
 453}
 454
 455static int apparmor_inode_getattr(const struct path *path)
 456{
 457	return common_perm_cond(OP_GETATTR, path, AA_MAY_GETATTR);
 458}
 459
 460static int apparmor_file_open(struct file *file)
 461{
 462	struct aa_file_ctx *fctx = file_ctx(file);
 463	struct aa_label *label;
 464	int error = 0;
 465	bool needput;
 466
 467	if (!path_mediated_fs(file->f_path.dentry))
 468		return 0;
 469
 470	/* If in exec, permission is handled by bprm hooks.
 471	 * Cache permissions granted by the previous exec check, with
 472	 * implicit read and executable mmap which are required to
 473	 * actually execute the image.
 474	 *
 475	 * Illogically, FMODE_EXEC is in f_flags, not f_mode.
 476	 */
 477	if (file->f_flags & __FMODE_EXEC) {
 478		fctx->allow = MAY_EXEC | MAY_READ | AA_EXEC_MMAP;
 479		return 0;
 480	}
 481
 482	label = aa_get_newest_cred_label_condref(file->f_cred, &needput);
 483	if (!unconfined(label)) {
 484		struct mnt_idmap *idmap = file_mnt_idmap(file);
 485		struct inode *inode = file_inode(file);
 486		vfsuid_t vfsuid;
 487		struct path_cond cond = {
 488			.mode = inode->i_mode,
 489		};
 490		vfsuid = i_uid_into_vfsuid(idmap, inode);
 491		cond.uid = vfsuid_into_kuid(vfsuid);
 492
 493		error = aa_path_perm(OP_OPEN, file->f_cred,
 494				     label, &file->f_path, 0,
 495				     aa_map_file_to_perms(file), &cond);
 496		/* todo cache full allowed permissions set and state */
 497		fctx->allow = aa_map_file_to_perms(file);
 498	}
 499	aa_put_label_condref(label, needput);
 500
 501	return error;
 502}
 503
 504static int apparmor_file_alloc_security(struct file *file)
 505{
 506	struct aa_file_ctx *ctx = file_ctx(file);
 507	struct aa_label *label = begin_current_label_crit_section();
 508
 509	spin_lock_init(&ctx->lock);
 510	rcu_assign_pointer(ctx->label, aa_get_label(label));
 511	end_current_label_crit_section(label);
 512	return 0;
 513}
 514
 515static void apparmor_file_free_security(struct file *file)
 516{
 517	struct aa_file_ctx *ctx = file_ctx(file);
 518
 519	if (ctx)
 520		aa_put_label(rcu_access_pointer(ctx->label));
 521}
 522
 523static int common_file_perm(const char *op, struct file *file, u32 mask)
 524{
 525	struct aa_label *label;
 526	int error = 0;
 527
 528	label = begin_current_label_crit_section();
 529	error = aa_file_perm(op, current_cred(), label, file, mask, false);
 530	end_current_label_crit_section(label);
 531
 532	return error;
 533}
 534
 535static int apparmor_file_receive(struct file *file)
 536{
 537	return common_file_perm(OP_FRECEIVE, file, aa_map_file_to_perms(file));
 538}
 539
 540static int apparmor_file_permission(struct file *file, int mask)
 541{
 542	return common_file_perm(OP_FPERM, file, mask);
 543}
 544
 545static int apparmor_file_lock(struct file *file, unsigned int cmd)
 546{
 547	u32 mask = AA_MAY_LOCK;
 548
 549	if (cmd == F_WRLCK)
 550		mask |= MAY_WRITE;
 551
 552	return common_file_perm(OP_FLOCK, file, mask);
 553}
 554
 555static int common_mmap(const char *op, struct file *file, unsigned long prot,
 556		       unsigned long flags)
 557{
 558	int mask = 0;
 559
 560	if (!file || !file_ctx(file))
 561		return 0;
 562
 563	if (prot & PROT_READ)
 564		mask |= MAY_READ;
 565	/*
 566	 * Private mappings don't require write perms since they don't
 567	 * write back to the files
 568	 */
 569	if ((prot & PROT_WRITE) && !(flags & MAP_PRIVATE))
 570		mask |= MAY_WRITE;
 571	if (prot & PROT_EXEC)
 572		mask |= AA_EXEC_MMAP;
 573
 574	return common_file_perm(op, file, mask);
 575}
 576
 577static int apparmor_mmap_file(struct file *file, unsigned long reqprot,
 578			      unsigned long prot, unsigned long flags)
 579{
 580	return common_mmap(OP_FMMAP, file, prot, flags);
 581}
 582
 583static int apparmor_file_mprotect(struct vm_area_struct *vma,
 584				  unsigned long reqprot, unsigned long prot)
 585{
 586	return common_mmap(OP_FMPROT, vma->vm_file, prot,
 587			   !(vma->vm_flags & VM_SHARED) ? MAP_PRIVATE : 0);
 588}
 589
 590#ifdef CONFIG_IO_URING
 591static const char *audit_uring_mask(u32 mask)
 592{
 593	if (mask & AA_MAY_CREATE_SQPOLL)
 594		return "sqpoll";
 595	if (mask & AA_MAY_OVERRIDE_CRED)
 596		return "override_creds";
 597	return "";
 598}
 599
 600static void audit_uring_cb(struct audit_buffer *ab, void *va)
 601{
 602	struct apparmor_audit_data *ad = aad_of_va(va);
 603
 604	if (ad->request & AA_URING_PERM_MASK) {
 605		audit_log_format(ab, " requested=\"%s\"",
 606				 audit_uring_mask(ad->request));
 607		if (ad->denied & AA_URING_PERM_MASK) {
 608			audit_log_format(ab, " denied=\"%s\"",
 609					 audit_uring_mask(ad->denied));
 610		}
 611	}
 612	if (ad->uring.target) {
 613		audit_log_format(ab, " tcontext=");
 614		aa_label_xaudit(ab, labels_ns(ad->subj_label),
 615				ad->uring.target,
 616				FLAGS_NONE, GFP_ATOMIC);
 617	}
 618}
 619
 620static int profile_uring(struct aa_profile *profile, u32 request,
 621			 struct aa_label *new, int cap,
 622			 struct apparmor_audit_data *ad)
 623{
 624	unsigned int state;
 625	struct aa_ruleset *rules;
 626	int error = 0;
 627
 628	AA_BUG(!profile);
 629
 630	rules = profile->label.rules[0];
 631	state = RULE_MEDIATES(rules, AA_CLASS_IO_URING);
 632	if (state) {
 633		struct aa_perms perms = { };
 634
 635		if (new) {
 636			aa_label_match(profile, rules, new, state,
 637				       false, request, &perms);
 638		} else {
 639			perms = *aa_lookup_perms(rules->policy, state);
 640		}
 641		aa_apply_modes_to_perms(profile, &perms);
 642		error = aa_check_perms(profile, &perms, request, ad,
 643				       audit_uring_cb);
 644	}
 645
 646	return error;
 647}
 648
 649/**
 650 * apparmor_uring_override_creds - check the requested cred override
 651 * @new: the target creds
 652 *
 653 * Check to see if the current task is allowed to override it's credentials
 654 * to service an io_uring operation.
 655 */
 656static int apparmor_uring_override_creds(const struct cred *new)
 657{
 658	struct aa_profile *profile;
 659	struct aa_label *label;
 660	int error;
 661	bool needput;
 662	DEFINE_AUDIT_DATA(ad, LSM_AUDIT_DATA_NONE, AA_CLASS_IO_URING,
 663			  OP_URING_OVERRIDE);
 664
 665	ad.uring.target = cred_label(new);
 666	label = __begin_current_label_crit_section(&needput);
 667	error = fn_for_each(label, profile,
 668			profile_uring(profile, AA_MAY_OVERRIDE_CRED,
 669				      cred_label(new), CAP_SYS_ADMIN, &ad));
 670	__end_current_label_crit_section(label, needput);
 671
 672	return error;
 673}
 674
 675/**
 676 * apparmor_uring_sqpoll - check if a io_uring polling thread can be created
 677 *
 678 * Check to see if the current task is allowed to create a new io_uring
 679 * kernel polling thread.
 680 */
 681static int apparmor_uring_sqpoll(void)
 682{
 683	struct aa_profile *profile;
 684	struct aa_label *label;
 685	int error;
 686	bool needput;
 687	DEFINE_AUDIT_DATA(ad, LSM_AUDIT_DATA_NONE, AA_CLASS_IO_URING,
 688			  OP_URING_SQPOLL);
 689
 690	label = __begin_current_label_crit_section(&needput);
 691	error = fn_for_each(label, profile,
 692			profile_uring(profile, AA_MAY_CREATE_SQPOLL,
 693				      NULL, CAP_SYS_ADMIN, &ad));
 694	__end_current_label_crit_section(label, needput);
 695
 696	return error;
 697}
 698#endif /* CONFIG_IO_URING */
 699
 700static int apparmor_sb_mount(const char *dev_name, const struct path *path,
 701			     const char *type, unsigned long flags, void *data)
 702{
 703	struct aa_label *label;
 704	int error = 0;
 705	bool needput;
 706
 707	/* Discard magic */
 708	if ((flags & MS_MGC_MSK) == MS_MGC_VAL)
 709		flags &= ~MS_MGC_MSK;
 710
 711	flags &= ~AA_MS_IGNORE_MASK;
 712
 713	label = __begin_current_label_crit_section(&needput);
 714	if (!unconfined(label)) {
 715		if (flags & MS_REMOUNT)
 716			error = aa_remount(current_cred(), label, path, flags,
 717					   data);
 718		else if (flags & MS_BIND)
 719			error = aa_bind_mount(current_cred(), label, path,
 720					      dev_name, flags);
 721		else if (flags & (MS_SHARED | MS_PRIVATE | MS_SLAVE |
 722				  MS_UNBINDABLE))
 723			error = aa_mount_change_type(current_cred(), label,
 724						     path, flags);
 725		else if (flags & MS_MOVE)
 726			error = aa_move_mount_old(current_cred(), label, path,
 727						  dev_name);
 728		else
 729			error = aa_new_mount(current_cred(), label, dev_name,
 730					     path, type, flags, data);
 731	}
 732	__end_current_label_crit_section(label, needput);
 733
 734	return error;
 735}
 736
 737static int apparmor_move_mount(const struct path *from_path,
 738			       const struct path *to_path)
 739{
 740	struct aa_label *label;
 741	int error = 0;
 742	bool needput;
 743
 744	label = __begin_current_label_crit_section(&needput);
 745	if (!unconfined(label))
 746		error = aa_move_mount(current_cred(), label, from_path,
 747				      to_path);
 748	__end_current_label_crit_section(label, needput);
 749
 750	return error;
 751}
 752
 753static int apparmor_sb_umount(struct vfsmount *mnt, int flags)
 754{
 755	struct aa_label *label;
 756	int error = 0;
 757	bool needput;
 758
 759	label = __begin_current_label_crit_section(&needput);
 760	if (!unconfined(label))
 761		error = aa_umount(current_cred(), label, mnt, flags);
 762	__end_current_label_crit_section(label, needput);
 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				u32 *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				u32 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_getlsmprop_subj(struct lsm_prop *prop)
 985{
 986	struct aa_label *label;
 987	bool needput;
 988
 989	label = __begin_current_label_crit_section(&needput);
 990	prop->apparmor.label = label;
 991	__end_current_label_crit_section(label, needput);
 992}
 993
 994static void apparmor_task_getlsmprop_obj(struct task_struct *p,
 995					  struct lsm_prop *prop)
 996{
 997	struct aa_label *label = aa_get_task_label(p);
 998
 999	prop->apparmor.label = label;
1000	aa_put_label(label);
1001}
1002
1003static int apparmor_task_setrlimit(struct task_struct *task,
1004		unsigned int resource, struct rlimit *new_rlim)
1005{
1006	struct aa_label *label;
1007	int error = 0;
1008	bool needput;
1009
1010	label = __begin_current_label_crit_section(&needput);
1011
1012	if (!unconfined(label))
1013		error = aa_task_setrlimit(current_cred(), label, task,
1014					  resource, new_rlim);
1015	__end_current_label_crit_section(label, needput);
1016
1017	return error;
1018}
1019
1020static int apparmor_task_kill(struct task_struct *target, struct kernel_siginfo *info,
1021			      int sig, const struct cred *cred)
1022{
1023	const struct cred *tc;
1024	struct aa_label *cl, *tl;
1025	int error;
1026	bool needput;
1027
1028	tc = get_task_cred(target);
1029	tl = aa_get_newest_cred_label(tc);
1030	if (cred) {
1031		/*
1032		 * Dealing with USB IO specific behavior
1033		 */
1034		cl = aa_get_newest_cred_label(cred);
1035		error = aa_may_signal(cred, cl, tc, tl, sig);
1036		aa_put_label(cl);
1037	} else {
1038		cl = __begin_current_label_crit_section(&needput);
1039		error = aa_may_signal(current_cred(), cl, tc, tl, sig);
1040		__end_current_label_crit_section(cl, needput);
1041	}
1042	aa_put_label(tl);
1043	put_cred(tc);
1044
1045	return error;
1046}
1047
1048static int apparmor_userns_create(const struct cred *cred)
1049{
1050	struct aa_label *label;
1051	struct aa_profile *profile;
1052	int error = 0;
1053	DEFINE_AUDIT_DATA(ad, LSM_AUDIT_DATA_TASK, AA_CLASS_NS,
1054			  OP_USERNS_CREATE);
1055
1056	ad.subj_cred = current_cred();
1057
1058	label = begin_current_label_crit_section();
1059	if (!unconfined(label)) {
1060		error = fn_for_each(label, profile,
1061				    aa_profile_ns_perm(profile, &ad,
1062						       AA_USERNS_CREATE));
1063	}
1064	end_current_label_crit_section(label);
1065
1066	return error;
1067}
1068
1069static int apparmor_sk_alloc_security(struct sock *sk, int family, gfp_t gfp)
1070{
1071	struct aa_sk_ctx *ctx = aa_sock(sk);
1072	struct aa_label *label;
1073	bool needput;
1074
1075	label = __begin_current_label_crit_section(&needput);
1076	//spin_lock_init(&ctx->lock);
1077	rcu_assign_pointer(ctx->label, aa_get_label(label));
1078	rcu_assign_pointer(ctx->peer, NULL);
1079	rcu_assign_pointer(ctx->peer_lastupdate, NULL);
1080	__end_current_label_crit_section(label, needput);
1081	return 0;
1082}
1083
1084static void apparmor_sk_free_security(struct sock *sk)
1085{
1086	struct aa_sk_ctx *ctx = aa_sock(sk);
1087
1088	/* dead these won't be updated any more */
1089	aa_put_label(rcu_dereference_protected(ctx->label, true));
1090	aa_put_label(rcu_dereference_protected(ctx->peer, true));
1091	aa_put_label(rcu_dereference_protected(ctx->peer_lastupdate, true));
1092}
1093
1094/**
1095 * apparmor_sk_clone_security - clone the sk_security field
1096 * @sk: sock to have security cloned
1097 * @newsk: sock getting clone
1098 */
1099static void apparmor_sk_clone_security(const struct sock *sk,
1100				       struct sock *newsk)
1101{
1102	struct aa_sk_ctx *ctx = aa_sock(sk);
1103	struct aa_sk_ctx *new = aa_sock(newsk);
1104
1105	/* not actually in use yet */
1106	if (rcu_access_pointer(ctx->label) != rcu_access_pointer(new->label)) {
1107		aa_put_label(rcu_dereference_protected(new->label, true));
1108		rcu_assign_pointer(new->label, aa_get_label_rcu(&ctx->label));
1109	}
1110
1111	if (rcu_access_pointer(ctx->peer) != rcu_access_pointer(new->peer)) {
1112		aa_put_label(rcu_dereference_protected(new->peer, true));
1113		rcu_assign_pointer(new->peer, aa_get_label_rcu(&ctx->peer));
1114	}
1115
1116	if (rcu_access_pointer(ctx->peer_lastupdate) != rcu_access_pointer(new->peer_lastupdate)) {
1117		aa_put_label(rcu_dereference_protected(new->peer_lastupdate, true));
1118		rcu_assign_pointer(new->peer_lastupdate,
1119				   aa_get_label_rcu(&ctx->peer_lastupdate));
1120	}
1121}
1122
1123static int unix_connect_perm(const struct cred *cred, struct aa_label *label,
1124			     struct sock *sk, struct sock *peer_sk)
1125{
1126	struct aa_sk_ctx *peer_ctx = aa_sock(peer_sk);
1127	int error;
1128
1129	error = aa_unix_peer_perm(cred, label, OP_CONNECT,
1130				(AA_MAY_CONNECT | AA_MAY_SEND | AA_MAY_RECEIVE),
1131				  sk, peer_sk,
1132				  rcu_dereference_protected(peer_ctx->label,
1133				     lockdep_is_held(&unix_sk(peer_sk)->lock)));
1134	if (!is_unix_fs(peer_sk)) {
1135		last_error(error,
1136			   aa_unix_peer_perm(cred,
1137				rcu_dereference_protected(peer_ctx->label,
1138				     lockdep_is_held(&unix_sk(peer_sk)->lock)),
1139				OP_CONNECT,
1140				(AA_MAY_ACCEPT | AA_MAY_SEND | AA_MAY_RECEIVE),
1141							  peer_sk, sk, label));
1142	}
1143
1144	return error;
1145}
1146
1147/* lockdep check in unix_connect_perm - push sks here to check */
1148static void unix_connect_peers(struct aa_sk_ctx *sk_ctx,
1149			       struct aa_sk_ctx *peer_ctx)
1150{
1151	/* Cross reference the peer labels for SO_PEERSEC */
1152	struct aa_label *label = rcu_dereference_protected(sk_ctx->label, true);
1153
1154	aa_get_label(label);
1155	aa_put_label(rcu_dereference_protected(peer_ctx->peer,
1156					     true));
1157	rcu_assign_pointer(peer_ctx->peer, label);	/* transfer cnt */
1158
1159	label = aa_get_label(rcu_dereference_protected(peer_ctx->label,
1160					     true));
1161	//spin_unlock(&peer_ctx->lock);
1162
1163	//spin_lock(&sk_ctx->lock);
1164	aa_put_label(rcu_dereference_protected(sk_ctx->peer,
1165					       true));
1166	aa_put_label(rcu_dereference_protected(sk_ctx->peer_lastupdate,
1167					       true));
1168
1169	rcu_assign_pointer(sk_ctx->peer, aa_get_label(label));
1170	rcu_assign_pointer(sk_ctx->peer_lastupdate, label);     /* transfer cnt */
1171	//spin_unlock(&sk_ctx->lock);
1172}
1173
1174/**
1175 * apparmor_unix_stream_connect - check perms before making unix domain conn
1176 * @sk: sk attempting to connect
1177 * @peer_sk: sk that is accepting the connection
1178 * @newsk: new sk created for this connection
1179 * peer is locked when this hook is called
1180 *
1181 * Return:
1182 *   0 if connection is permitted
1183 *   error code on denial or failure
1184 */
1185static int apparmor_unix_stream_connect(struct sock *sk, struct sock *peer_sk,
1186					struct sock *newsk)
1187{
1188	struct aa_sk_ctx *sk_ctx = aa_sock(sk);
1189	struct aa_sk_ctx *peer_ctx = aa_sock(peer_sk);
1190	struct aa_sk_ctx *new_ctx = aa_sock(newsk);
1191	struct aa_label *label;
1192	int error;
1193	bool needput;
1194
1195	label = __begin_current_label_crit_section(&needput);
1196	error = unix_connect_perm(current_cred(), label, sk, peer_sk);
1197	__end_current_label_crit_section(label, needput);
1198
1199	if (error)
1200		return error;
1201
1202	/* newsk doesn't go through post_create, but does go through
1203	 * security_sk_alloc()
1204	 */
1205	rcu_assign_pointer(new_ctx->label,
1206			   aa_get_label(rcu_dereference_protected(peer_ctx->label,
1207								  true)));
1208
1209	/* Cross reference the peer labels for SO_PEERSEC */
1210	unix_connect_peers(sk_ctx, new_ctx);
1211
1212	return 0;
1213}
1214
1215/**
1216 * apparmor_unix_may_send - check perms before conn or sending unix dgrams
1217 * @sock: socket sending the message
1218 * @peer: socket message is being send to
1219 *
1220 * Performs bidirectional permission checks for Unix domain socket communication:
1221 * 1. Verifies sender has AA_MAY_SEND to target socket
1222 * 2. Verifies receiver has AA_MAY_RECEIVE from source socket
1223 *
1224 * sock and peer are locked when this hook is called
1225 * called by: dgram_connect peer setup but path not copied to newsk
1226 *
1227 * Return:
1228 *   0 if transmission is permitted
1229 *   error code on denial or failure
1230 */
1231static int apparmor_unix_may_send(struct socket *sock, struct socket *peer)
1232{
1233	struct aa_sk_ctx *peer_ctx = aa_sock(peer->sk);
1234	struct aa_label *label;
1235	int error;
1236	bool needput;
1237
1238	label = __begin_current_label_crit_section(&needput);
1239	error = xcheck(aa_unix_peer_perm(current_cred(),
1240				label, OP_SENDMSG, AA_MAY_SEND,
1241				sock->sk, peer->sk,
1242				rcu_dereference_protected(peer_ctx->label,
1243							  true)),
1244		       aa_unix_peer_perm(peer->file ? peer->file->f_cred : NULL,
1245				rcu_dereference_protected(peer_ctx->label,
1246							  true),
1247				OP_SENDMSG, AA_MAY_RECEIVE, peer->sk,
1248				sock->sk, label));
1249	__end_current_label_crit_section(label, needput);
1250
1251	return error;
1252}
1253
1254static int apparmor_socket_create(int family, int type, int protocol, int kern)
1255{
1256	struct aa_label *label;
1257	int error = 0;
1258
1259	AA_BUG(in_interrupt());
1260
1261	if (kern)
1262		return 0;
1263
1264	label = begin_current_label_crit_section();
1265	if (!unconfined(label)) {
1266		if (family == PF_UNIX)
1267			error = aa_unix_create_perm(label, family, type,
1268						    protocol);
1269		else
1270			error = aa_af_perm(current_cred(), label, OP_CREATE,
1271					   AA_MAY_CREATE, family, type,
1272					   protocol);
1273	}
1274	end_current_label_crit_section(label);
1275
1276	return error;
1277}
1278
1279/**
1280 * apparmor_socket_post_create - setup the per-socket security struct
1281 * @sock: socket that is being setup
1282 * @family: family of socket being created
1283 * @type: type of the socket
1284 * @protocol: protocol of the socket
1285 * @kern: socket is a special kernel socket
1286 *
1287 * Note:
1288 * -   kernel sockets labeled kernel_t used to use unconfined
1289 * -   socket may not have sk here if created with sock_create_lite or
1290 *     sock_alloc. These should be accept cases which will be handled in
1291 *     sock_graft.
1292 */
1293static int apparmor_socket_post_create(struct socket *sock, int family,
1294				       int type, int protocol, int kern)
1295{
1296	struct aa_label *label;
1297
1298	if (kern) {
1299		label = aa_get_label(kernel_t);
1300	} else
1301		label = aa_get_current_label();
1302
1303	if (sock->sk) {
1304		struct aa_sk_ctx *ctx = aa_sock(sock->sk);
1305
1306		/* still not live */
1307		aa_put_label(rcu_dereference_protected(ctx->label, true));
1308		rcu_assign_pointer(ctx->label, aa_get_label(label));
1309	}
1310	aa_put_label(label);
1311
1312	return 0;
1313}
1314
1315static int apparmor_socket_socketpair(struct socket *socka,
1316				      struct socket *sockb)
1317{
1318	struct aa_sk_ctx *a_ctx = aa_sock(socka->sk);
1319	struct aa_sk_ctx *b_ctx = aa_sock(sockb->sk);
1320	struct aa_label *label;
1321
1322	/* socks not live yet - initial values set in sk_alloc */
1323	label = begin_current_label_crit_section();
1324	if (rcu_access_pointer(a_ctx->label) != label) {
1325		AA_BUG("a_ctx != label");
1326		aa_put_label(rcu_dereference_protected(a_ctx->label, true));
1327		rcu_assign_pointer(a_ctx->label, aa_get_label(label));
1328	}
1329	if (rcu_access_pointer(b_ctx->label) != label) {
1330		AA_BUG("b_ctx != label");
1331		aa_put_label(rcu_dereference_protected(b_ctx->label, true));
1332		rcu_assign_pointer(b_ctx->label, aa_get_label(label));
1333	}
1334
1335	if (socka->sk->sk_family == PF_UNIX) {
1336		/* unix socket pairs by-pass unix_stream_connect */
1337		unix_connect_peers(a_ctx, b_ctx);
1338	}
1339	end_current_label_crit_section(label);
1340
1341	return 0;
1342}
1343
1344/**
1345 * apparmor_socket_bind - check perms before bind addr to socket
1346 * @sock: socket to bind the address to (must be non-NULL)
1347 * @address: address that is being bound (must be non-NULL)
1348 * @addrlen: length of @address
1349 *
1350 * Performs security checks before allowing a socket to bind to an address.
1351 * Handles Unix domain sockets specially through aa_unix_bind_perm().
1352 * For other socket families, uses generic permission check via aa_sk_perm().
1353 *
1354 * Return:
1355 *   0 if binding is permitted
1356 *   error code on denial or invalid parameters
1357 */
1358static int apparmor_socket_bind(struct socket *sock,
1359				struct sockaddr *address, int addrlen)
1360{
1361	AA_BUG(!sock);
1362	AA_BUG(!sock->sk);
1363	AA_BUG(!address);
1364	AA_BUG(in_interrupt());
1365
1366	if (sock->sk->sk_family == PF_UNIX)
1367		return aa_unix_bind_perm(sock, address, addrlen);
1368	return aa_sk_perm(OP_BIND, AA_MAY_BIND, sock->sk);
1369}
1370
1371static int apparmor_socket_connect(struct socket *sock,
1372				   struct sockaddr *address, int addrlen)
1373{
1374	AA_BUG(!sock);
1375	AA_BUG(!sock->sk);
1376	AA_BUG(!address);
1377	AA_BUG(in_interrupt());
1378
1379	/* PF_UNIX goes through unix_stream_connect && unix_may_send */
1380	if (sock->sk->sk_family == PF_UNIX)
1381		return 0;
1382	return aa_sk_perm(OP_CONNECT, AA_MAY_CONNECT, sock->sk);
1383}
1384
1385static int apparmor_socket_listen(struct socket *sock, int backlog)
1386{
1387	AA_BUG(!sock);
1388	AA_BUG(!sock->sk);
1389	AA_BUG(in_interrupt());
1390
1391	if (sock->sk->sk_family == PF_UNIX)
1392		return aa_unix_listen_perm(sock, backlog);
1393	return aa_sk_perm(OP_LISTEN, AA_MAY_LISTEN, sock->sk);
1394}
1395
1396/*
1397 * Note: while @newsock is created and has some information, the accept
1398 *       has not been done.
1399 */
1400static int apparmor_socket_accept(struct socket *sock, struct socket *newsock)
1401{
1402	AA_BUG(!sock);
1403	AA_BUG(!sock->sk);
1404	AA_BUG(!newsock);
1405	AA_BUG(in_interrupt());
1406
1407	if (sock->sk->sk_family == PF_UNIX)
1408		return aa_unix_accept_perm(sock, newsock);
1409	return aa_sk_perm(OP_ACCEPT, AA_MAY_ACCEPT, sock->sk);
1410}
1411
1412static int aa_sock_msg_perm(const char *op, u32 request, struct socket *sock,
1413			    struct msghdr *msg, int size)
1414{
1415	AA_BUG(!sock);
1416	AA_BUG(!sock->sk);
1417	AA_BUG(!msg);
1418	AA_BUG(in_interrupt());
1419
1420	/* PF_UNIX goes through unix_may_send */
1421	if (sock->sk->sk_family == PF_UNIX)
1422		return 0;
1423	return aa_sk_perm(op, request, sock->sk);
1424}
1425
1426static int apparmor_socket_sendmsg(struct socket *sock,
1427				   struct msghdr *msg, int size)
1428{
1429	return aa_sock_msg_perm(OP_SENDMSG, AA_MAY_SEND, sock, msg, size);
1430}
1431
1432static int apparmor_socket_recvmsg(struct socket *sock,
1433				   struct msghdr *msg, int size, int flags)
1434{
1435	return aa_sock_msg_perm(OP_RECVMSG, AA_MAY_RECEIVE, sock, msg, size);
1436}
1437
1438/* revaliation, get/set attr, shutdown */
1439static int aa_sock_perm(const char *op, u32 request, struct socket *sock)
1440{
1441	AA_BUG(!sock);
1442	AA_BUG(!sock->sk);
1443	AA_BUG(in_interrupt());
1444
1445	if (sock->sk->sk_family == PF_UNIX)
1446		return aa_unix_sock_perm(op, request, sock);
1447	return aa_sk_perm(op, request, sock->sk);
1448}
1449
1450static int apparmor_socket_getsockname(struct socket *sock)
1451{
1452	return aa_sock_perm(OP_GETSOCKNAME, AA_MAY_GETATTR, sock);
1453}
1454
1455static int apparmor_socket_getpeername(struct socket *sock)
1456{
1457	return aa_sock_perm(OP_GETPEERNAME, AA_MAY_GETATTR, sock);
1458}
1459
1460/* revaliation, get/set attr, opt */
1461static int aa_sock_opt_perm(const char *op, u32 request, struct socket *sock,
1462			    int level, int optname)
1463{
1464	AA_BUG(!sock);
1465	AA_BUG(!sock->sk);
1466	AA_BUG(in_interrupt());
1467
1468	if (sock->sk->sk_family == PF_UNIX)
1469		return aa_unix_opt_perm(op, request, sock, level, optname);
1470	return aa_sk_perm(op, request, sock->sk);
1471}
1472
1473static int apparmor_socket_getsockopt(struct socket *sock, int level,
1474				      int optname)
1475{
1476	return aa_sock_opt_perm(OP_GETSOCKOPT, AA_MAY_GETOPT, sock,
1477				level, optname);
1478}
1479
1480static int apparmor_socket_setsockopt(struct socket *sock, int level,
1481				      int optname)
1482{
1483	return aa_sock_opt_perm(OP_SETSOCKOPT, AA_MAY_SETOPT, sock,
1484				level, optname);
1485}
1486
1487static int apparmor_socket_shutdown(struct socket *sock, int how)
1488{
1489	return aa_sock_perm(OP_SHUTDOWN, AA_MAY_SHUTDOWN, sock);
1490}
1491
1492#ifdef CONFIG_NETWORK_SECMARK
1493/**
1494 * apparmor_socket_sock_rcv_skb - check perms before associating skb to sk
1495 * @sk: sk to associate @skb with
1496 * @skb: skb to check for perms
1497 *
1498 * Note: can not sleep may be called with locks held
1499 *
1500 * dont want protocol specific in __skb_recv_datagram()
1501 * to deny an incoming connection  socket_sock_rcv_skb()
1502 */
1503static int apparmor_socket_sock_rcv_skb(struct sock *sk, struct sk_buff *skb)
1504{
1505	struct aa_sk_ctx *ctx = aa_sock(sk);
1506	int error;
1507
1508	if (!skb->secmark)
1509		return 0;
1510
1511	/*
1512	 * If reach here before socket_post_create hook is called, in which
1513	 * case label is null, drop the packet.
1514	 */
1515	if (!rcu_access_pointer(ctx->label))
1516		return -EACCES;
1517
1518	rcu_read_lock();
1519	error = apparmor_secmark_check(rcu_dereference(ctx->label), OP_RECVMSG,
1520				       AA_MAY_RECEIVE, skb->secmark, sk);
1521	rcu_read_unlock();
1522
1523	return error;
1524}
1525#endif
1526
1527
1528static struct aa_label *sk_peer_get_label(struct sock *sk)
1529{
1530	struct aa_sk_ctx *ctx = aa_sock(sk);
1531	struct aa_label *label = ERR_PTR(-ENOPROTOOPT);
1532
1533	if (rcu_access_pointer(ctx->peer))
1534		return aa_get_label_rcu(&ctx->peer);
1535
1536	if (sk->sk_family != PF_UNIX)
1537		return ERR_PTR(-ENOPROTOOPT);
1538
1539	return label;
1540}
1541
1542/**
1543 * apparmor_socket_getpeersec_stream - get security context of peer
1544 * @sock: socket that we are trying to get the peer context of
1545 * @optval: output - buffer to copy peer name to
1546 * @optlen: output - size of copied name in @optval
1547 * @len: size of @optval buffer
1548 * Returns: 0 on success, -errno of failure
1549 *
1550 * Note: for tcp only valid if using ipsec or cipso on lan
1551 */
1552static int apparmor_socket_getpeersec_stream(struct socket *sock,
1553					     sockptr_t optval, sockptr_t optlen,
1554					     unsigned int len)
1555{
1556	char *name = NULL;
1557	int slen, error = 0;
1558	struct aa_label *label;
1559	struct aa_label *peer;
1560
1561	peer = sk_peer_get_label(sock->sk);
1562	if (IS_ERR(peer)) {
1563		error = PTR_ERR(peer);
1564		goto done;
1565	}
1566	label = begin_current_label_crit_section();
1567	slen = aa_label_asxprint(&name, labels_ns(label), peer,
1568				 FLAG_SHOW_MODE | FLAG_VIEW_SUBNS |
1569				 FLAG_HIDDEN_UNCONFINED, GFP_KERNEL);
1570	/* don't include terminating \0 in slen, it breaks some apps */
1571	if (slen < 0) {
1572		error = -ENOMEM;
1573		goto done_put;
1574	}
1575	if (slen > len) {
1576		error = -ERANGE;
1577		goto done_len;
1578	}
1579
1580	if (copy_to_sockptr(optval, name, slen))
1581		error = -EFAULT;
1582done_len:
1583	if (copy_to_sockptr(optlen, &slen, sizeof(slen)))
1584		error = -EFAULT;
1585
1586done_put:
1587	end_current_label_crit_section(label);
1588	aa_put_label(peer);
1589done:
1590	kfree(name);
1591	return error;
1592}
1593
1594/**
1595 * apparmor_socket_getpeersec_dgram - get security label of packet
1596 * @sock: the peer socket
1597 * @skb: packet data
1598 * @secid: pointer to where to put the secid of the packet
1599 *
1600 * Sets the netlabel socket state on sk from parent
1601 */
1602static int apparmor_socket_getpeersec_dgram(struct socket *sock,
1603					    struct sk_buff *skb, u32 *secid)
1604
1605{
1606	/* TODO: requires secid support */
1607	return -ENOPROTOOPT;
1608}
1609
1610/**
1611 * apparmor_sock_graft - Initialize newly created socket
1612 * @sk: child sock
1613 * @parent: parent socket
1614 *
1615 * Note: could set off of SOCK_CTX(parent) but need to track inode and we can
1616 *       just set sk security information off of current creating process label
1617 *       Labeling of sk for accept case - probably should be sock based
1618 *       instead of task, because of the case where an implicitly labeled
1619 *       socket is shared by different tasks.
1620 */
1621static void apparmor_sock_graft(struct sock *sk, struct socket *parent)
1622{
1623	struct aa_sk_ctx *ctx = aa_sock(sk);
1624
1625	/* setup - not live */
1626	if (!rcu_access_pointer(ctx->label))
1627		rcu_assign_pointer(ctx->label, aa_get_current_label());
1628}
1629
1630#ifdef CONFIG_NETWORK_SECMARK
1631static int apparmor_inet_conn_request(const struct sock *sk, struct sk_buff *skb,
1632				      struct request_sock *req)
1633{
1634	struct aa_sk_ctx *ctx = aa_sock(sk);
1635	int error;
1636
1637	if (!skb->secmark)
1638		return 0;
1639
1640	rcu_read_lock();
1641	error = apparmor_secmark_check(rcu_dereference(ctx->label), OP_CONNECT,
1642				       AA_MAY_CONNECT, skb->secmark, sk);
1643	rcu_read_unlock();
1644
1645	return error;
1646}
1647#endif
1648
1649/*
1650 * The cred blob is a pointer to, not an instance of, an aa_label.
1651 */
1652struct lsm_blob_sizes apparmor_blob_sizes __ro_after_init = {
1653	.lbs_cred = sizeof(struct aa_label *),
1654	.lbs_file = sizeof(struct aa_file_ctx),
1655	.lbs_task = sizeof(struct aa_task_ctx),
1656	.lbs_sock = sizeof(struct aa_sk_ctx),
1657};
1658
1659static const struct lsm_id apparmor_lsmid = {
1660	.name = "apparmor",
1661	.id = LSM_ID_APPARMOR,
1662};
1663
1664static struct security_hook_list apparmor_hooks[] __ro_after_init = {
1665	LSM_HOOK_INIT(ptrace_access_check, apparmor_ptrace_access_check),
1666	LSM_HOOK_INIT(ptrace_traceme, apparmor_ptrace_traceme),
1667	LSM_HOOK_INIT(capget, apparmor_capget),
1668	LSM_HOOK_INIT(capable, apparmor_capable),
1669
1670	LSM_HOOK_INIT(move_mount, apparmor_move_mount),
1671	LSM_HOOK_INIT(sb_mount, apparmor_sb_mount),
1672	LSM_HOOK_INIT(sb_umount, apparmor_sb_umount),
1673	LSM_HOOK_INIT(sb_pivotroot, apparmor_sb_pivotroot),
1674
1675	LSM_HOOK_INIT(path_link, apparmor_path_link),
1676	LSM_HOOK_INIT(path_unlink, apparmor_path_unlink),
1677	LSM_HOOK_INIT(path_symlink, apparmor_path_symlink),
1678	LSM_HOOK_INIT(path_mkdir, apparmor_path_mkdir),
1679	LSM_HOOK_INIT(path_rmdir, apparmor_path_rmdir),
1680	LSM_HOOK_INIT(path_mknod, apparmor_path_mknod),
1681	LSM_HOOK_INIT(path_rename, apparmor_path_rename),
1682	LSM_HOOK_INIT(path_chmod, apparmor_path_chmod),
1683	LSM_HOOK_INIT(path_chown, apparmor_path_chown),
1684	LSM_HOOK_INIT(path_truncate, apparmor_path_truncate),
1685	LSM_HOOK_INIT(inode_getattr, apparmor_inode_getattr),
1686
1687	LSM_HOOK_INIT(file_open, apparmor_file_open),
1688	LSM_HOOK_INIT(file_receive, apparmor_file_receive),
1689	LSM_HOOK_INIT(file_permission, apparmor_file_permission),
1690	LSM_HOOK_INIT(file_alloc_security, apparmor_file_alloc_security),
1691	LSM_HOOK_INIT(file_free_security, apparmor_file_free_security),
1692	LSM_HOOK_INIT(mmap_file, apparmor_mmap_file),
1693	LSM_HOOK_INIT(file_mprotect, apparmor_file_mprotect),
1694	LSM_HOOK_INIT(file_lock, apparmor_file_lock),
1695	LSM_HOOK_INIT(file_truncate, apparmor_file_truncate),
1696
1697	LSM_HOOK_INIT(getselfattr, apparmor_getselfattr),
1698	LSM_HOOK_INIT(setselfattr, apparmor_setselfattr),
1699	LSM_HOOK_INIT(getprocattr, apparmor_getprocattr),
1700	LSM_HOOK_INIT(setprocattr, apparmor_setprocattr),
1701
1702	LSM_HOOK_INIT(sk_alloc_security, apparmor_sk_alloc_security),
1703	LSM_HOOK_INIT(sk_free_security, apparmor_sk_free_security),
1704	LSM_HOOK_INIT(sk_clone_security, apparmor_sk_clone_security),
1705
1706	LSM_HOOK_INIT(unix_stream_connect, apparmor_unix_stream_connect),
1707	LSM_HOOK_INIT(unix_may_send, apparmor_unix_may_send),
1708
1709	LSM_HOOK_INIT(socket_create, apparmor_socket_create),
1710	LSM_HOOK_INIT(socket_post_create, apparmor_socket_post_create),
1711	LSM_HOOK_INIT(socket_socketpair, apparmor_socket_socketpair),
1712	LSM_HOOK_INIT(socket_bind, apparmor_socket_bind),
1713	LSM_HOOK_INIT(socket_connect, apparmor_socket_connect),
1714	LSM_HOOK_INIT(socket_listen, apparmor_socket_listen),
1715	LSM_HOOK_INIT(socket_accept, apparmor_socket_accept),
1716	LSM_HOOK_INIT(socket_sendmsg, apparmor_socket_sendmsg),
1717	LSM_HOOK_INIT(socket_recvmsg, apparmor_socket_recvmsg),
1718	LSM_HOOK_INIT(socket_getsockname, apparmor_socket_getsockname),
1719	LSM_HOOK_INIT(socket_getpeername, apparmor_socket_getpeername),
1720	LSM_HOOK_INIT(socket_getsockopt, apparmor_socket_getsockopt),
1721	LSM_HOOK_INIT(socket_setsockopt, apparmor_socket_setsockopt),
1722	LSM_HOOK_INIT(socket_shutdown, apparmor_socket_shutdown),
1723#ifdef CONFIG_NETWORK_SECMARK
1724	LSM_HOOK_INIT(socket_sock_rcv_skb, apparmor_socket_sock_rcv_skb),
1725#endif
1726	LSM_HOOK_INIT(socket_getpeersec_stream,
1727		      apparmor_socket_getpeersec_stream),
1728	LSM_HOOK_INIT(socket_getpeersec_dgram,
1729		      apparmor_socket_getpeersec_dgram),
1730	LSM_HOOK_INIT(sock_graft, apparmor_sock_graft),
1731#ifdef CONFIG_NETWORK_SECMARK
1732	LSM_HOOK_INIT(inet_conn_request, apparmor_inet_conn_request),
1733#endif
1734
1735	LSM_HOOK_INIT(cred_alloc_blank, apparmor_cred_alloc_blank),
1736	LSM_HOOK_INIT(cred_free, apparmor_cred_free),
1737	LSM_HOOK_INIT(cred_prepare, apparmor_cred_prepare),
1738	LSM_HOOK_INIT(cred_transfer, apparmor_cred_transfer),
1739
1740	LSM_HOOK_INIT(bprm_creds_for_exec, apparmor_bprm_creds_for_exec),
1741	LSM_HOOK_INIT(bprm_committing_creds, apparmor_bprm_committing_creds),
1742	LSM_HOOK_INIT(bprm_committed_creds, apparmor_bprm_committed_creds),
1743
1744	LSM_HOOK_INIT(task_free, apparmor_task_free),
1745	LSM_HOOK_INIT(task_alloc, apparmor_task_alloc),
1746	LSM_HOOK_INIT(current_getlsmprop_subj,
1747		      apparmor_current_getlsmprop_subj),
1748	LSM_HOOK_INIT(task_getlsmprop_obj, apparmor_task_getlsmprop_obj),
1749	LSM_HOOK_INIT(task_setrlimit, apparmor_task_setrlimit),
1750	LSM_HOOK_INIT(task_kill, apparmor_task_kill),
1751	LSM_HOOK_INIT(userns_create, apparmor_userns_create),
1752
1753#ifdef CONFIG_AUDIT
1754	LSM_HOOK_INIT(audit_rule_init, aa_audit_rule_init),
1755	LSM_HOOK_INIT(audit_rule_known, aa_audit_rule_known),
1756	LSM_HOOK_INIT(audit_rule_match, aa_audit_rule_match),
1757	LSM_HOOK_INIT(audit_rule_free, aa_audit_rule_free),
1758#endif
1759
1760	LSM_HOOK_INIT(secid_to_secctx, apparmor_secid_to_secctx),
1761	LSM_HOOK_INIT(lsmprop_to_secctx, apparmor_lsmprop_to_secctx),
1762	LSM_HOOK_INIT(secctx_to_secid, apparmor_secctx_to_secid),
1763	LSM_HOOK_INIT(release_secctx, apparmor_release_secctx),
1764
1765#ifdef CONFIG_IO_URING
1766	LSM_HOOK_INIT(uring_override_creds, apparmor_uring_override_creds),
1767	LSM_HOOK_INIT(uring_sqpoll, apparmor_uring_sqpoll),
1768#endif
1769};
1770
1771/*
1772 * AppArmor sysfs module parameters
1773 */
1774
1775static int param_set_aabool(const char *val, const struct kernel_param *kp);
1776static int param_get_aabool(char *buffer, const struct kernel_param *kp);
1777#define param_check_aabool param_check_bool
1778static const struct kernel_param_ops param_ops_aabool = {
1779	.flags = KERNEL_PARAM_OPS_FL_NOARG,
1780	.set = param_set_aabool,
1781	.get = param_get_aabool
1782};
1783
1784static int param_set_aauint(const char *val, const struct kernel_param *kp);
1785static int param_get_aauint(char *buffer, const struct kernel_param *kp);
1786#define param_check_aauint param_check_uint
1787static const struct kernel_param_ops param_ops_aauint = {
1788	.set = param_set_aauint,
1789	.get = param_get_aauint
1790};
1791
1792static int param_set_aacompressionlevel(const char *val,
1793					const struct kernel_param *kp);
1794static int param_get_aacompressionlevel(char *buffer,
1795					const struct kernel_param *kp);
1796#define param_check_aacompressionlevel param_check_int
1797static const struct kernel_param_ops param_ops_aacompressionlevel = {
1798	.set = param_set_aacompressionlevel,
1799	.get = param_get_aacompressionlevel
1800};
1801
1802static int param_set_aalockpolicy(const char *val, const struct kernel_param *kp);
1803static int param_get_aalockpolicy(char *buffer, const struct kernel_param *kp);
1804#define param_check_aalockpolicy param_check_bool
1805static const struct kernel_param_ops param_ops_aalockpolicy = {
1806	.flags = KERNEL_PARAM_OPS_FL_NOARG,
1807	.set = param_set_aalockpolicy,
1808	.get = param_get_aalockpolicy
1809};
1810
1811static int param_set_debug(const char *val, const struct kernel_param *kp);
1812static int param_get_debug(char *buffer, const struct kernel_param *kp);
1813
1814static int param_set_audit(const char *val, const struct kernel_param *kp);
1815static int param_get_audit(char *buffer, const struct kernel_param *kp);
1816
1817static int param_set_mode(const char *val, const struct kernel_param *kp);
1818static int param_get_mode(char *buffer, const struct kernel_param *kp);
1819
1820/* Flag values, also controllable via /sys/module/apparmor/parameters
1821 * We define special types as we want to do additional mediation.
1822 */
1823
1824/* AppArmor global enforcement switch - complain, enforce, kill */
1825enum profile_mode aa_g_profile_mode = APPARMOR_ENFORCE;
1826module_param_call(mode, param_set_mode, param_get_mode,
1827		  &aa_g_profile_mode, S_IRUSR | S_IWUSR);
1828
1829/* whether policy verification hashing is enabled */
1830bool aa_g_hash_policy = IS_ENABLED(CONFIG_SECURITY_APPARMOR_HASH_DEFAULT);
1831#ifdef CONFIG_SECURITY_APPARMOR_HASH
1832module_param_named(hash_policy, aa_g_hash_policy, aabool, S_IRUSR | S_IWUSR);
1833#endif
1834
1835/* whether policy exactly as loaded is retained for debug and checkpointing */
1836bool aa_g_export_binary = IS_ENABLED(CONFIG_SECURITY_APPARMOR_EXPORT_BINARY);
1837#ifdef CONFIG_SECURITY_APPARMOR_EXPORT_BINARY
1838module_param_named(export_binary, aa_g_export_binary, aabool, 0600);
1839#endif
1840
1841/* policy loaddata compression level */
1842int aa_g_rawdata_compression_level = AA_DEFAULT_CLEVEL;
1843module_param_named(rawdata_compression_level, aa_g_rawdata_compression_level,
1844		   aacompressionlevel, 0400);
1845
1846/* Debug mode */
1847int aa_g_debug;
1848module_param_call(debug, param_set_debug, param_get_debug,
1849		  &aa_g_debug, 0600);
1850
1851/* Audit mode */
1852enum audit_mode aa_g_audit;
1853module_param_call(audit, param_set_audit, param_get_audit,
1854		  &aa_g_audit, S_IRUSR | S_IWUSR);
1855
1856/* Determines if audit header is included in audited messages.  This
1857 * provides more context if the audit daemon is not running
1858 */
1859bool aa_g_audit_header = true;
1860module_param_named(audit_header, aa_g_audit_header, aabool,
1861		   S_IRUSR | S_IWUSR);
1862
1863/* lock out loading/removal of policy
1864 * TODO: add in at boot loading of policy, which is the only way to
1865 *       load policy, if lock_policy is set
1866 */
1867bool aa_g_lock_policy;
1868module_param_named(lock_policy, aa_g_lock_policy, aalockpolicy,
1869		   S_IRUSR | S_IWUSR);
1870
1871/* Syscall logging mode */
1872bool aa_g_logsyscall;
1873module_param_named(logsyscall, aa_g_logsyscall, aabool, S_IRUSR | S_IWUSR);
1874
1875/* Maximum pathname length before accesses will start getting rejected */
1876unsigned int aa_g_path_max = 2 * PATH_MAX;
1877module_param_named(path_max, aa_g_path_max, aauint, S_IRUSR);
1878
1879/* Determines how paranoid loading of policy is and how much verification
1880 * on the loaded policy is done.
1881 * DEPRECATED: read only as strict checking of load is always done now
1882 * that none root users (user namespaces) can load policy.
1883 */
1884bool aa_g_paranoid_load = IS_ENABLED(CONFIG_SECURITY_APPARMOR_PARANOID_LOAD);
1885module_param_named(paranoid_load, aa_g_paranoid_load, aabool, S_IRUGO);
1886
1887static int param_get_aaintbool(char *buffer, const struct kernel_param *kp);
1888static int param_set_aaintbool(const char *val, const struct kernel_param *kp);
1889#define param_check_aaintbool param_check_int
1890static const struct kernel_param_ops param_ops_aaintbool = {
1891	.set = param_set_aaintbool,
1892	.get = param_get_aaintbool
1893};
1894/* Boot time disable flag */
1895static int apparmor_enabled __ro_after_init = 1;
1896module_param_named(enabled, apparmor_enabled, aaintbool, 0444);
1897
1898static int __init apparmor_enabled_setup(char *str)
1899{
1900	unsigned long enabled;
1901	int error = kstrtoul(str, 0, &enabled);
1902	if (!error)
1903		apparmor_enabled = enabled ? 1 : 0;
1904	return 1;
1905}
1906
1907__setup("apparmor=", apparmor_enabled_setup);
1908
1909/* set global flag turning off the ability to load policy */
1910static int param_set_aalockpolicy(const char *val, const struct kernel_param *kp)
1911{
1912	if (!apparmor_enabled)
1913		return -EINVAL;
1914	if (apparmor_initialized && !aa_current_policy_admin_capable(NULL))
1915		return -EPERM;
1916	return param_set_bool(val, kp);
1917}
1918
1919static int param_get_aalockpolicy(char *buffer, const struct kernel_param *kp)
1920{
1921	if (!apparmor_enabled)
1922		return -EINVAL;
1923	if (apparmor_initialized && !aa_current_policy_view_capable(NULL))
1924		return -EPERM;
1925	return param_get_bool(buffer, kp);
1926}
1927
1928static int param_set_aabool(const char *val, const struct kernel_param *kp)
1929{
1930	if (!apparmor_enabled)
1931		return -EINVAL;
1932	if (apparmor_initialized && !aa_current_policy_admin_capable(NULL))
1933		return -EPERM;
1934	return param_set_bool(val, kp);
1935}
1936
1937static int param_get_aabool(char *buffer, const struct kernel_param *kp)
1938{
1939	if (!apparmor_enabled)
1940		return -EINVAL;
1941	if (apparmor_initialized && !aa_current_policy_view_capable(NULL))
1942		return -EPERM;
1943	return param_get_bool(buffer, kp);
1944}
1945
1946static int param_set_aauint(const char *val, const struct kernel_param *kp)
1947{
1948	int error;
1949
1950	if (!apparmor_enabled)
1951		return -EINVAL;
1952	/* file is ro but enforce 2nd line check */
1953	if (apparmor_initialized)
1954		return -EPERM;
1955
1956	error = param_set_uint(val, kp);
1957	aa_g_path_max = max_t(uint32_t, aa_g_path_max, sizeof(union aa_buffer));
1958	pr_info("AppArmor: buffer size set to %d bytes\n", aa_g_path_max);
1959
1960	return error;
1961}
1962
1963static int param_get_aauint(char *buffer, const struct kernel_param *kp)
1964{
1965	if (!apparmor_enabled)
1966		return -EINVAL;
1967	if (apparmor_initialized && !aa_current_policy_view_capable(NULL))
1968		return -EPERM;
1969	return param_get_uint(buffer, kp);
1970}
1971
1972/* Can only be set before AppArmor is initialized (i.e. on boot cmdline). */
1973static int param_set_aaintbool(const char *val, const struct kernel_param *kp)
1974{
1975	struct kernel_param kp_local;
1976	bool value;
1977	int error;
1978
1979	if (apparmor_initialized)
1980		return -EPERM;
1981
1982	/* Create local copy, with arg pointing to bool type. */
1983	value = !!*((int *)kp->arg);
1984	memcpy(&kp_local, kp, sizeof(kp_local));
1985	kp_local.arg = &value;
1986
1987	error = param_set_bool(val, &kp_local);
1988	if (!error)
1989		*((int *)kp->arg) = *((bool *)kp_local.arg);
1990	return error;
1991}
1992
1993/*
1994 * To avoid changing /sys/module/apparmor/parameters/enabled from Y/N to
1995 * 1/0, this converts the "int that is actually bool" back to bool for
1996 * display in the /sys filesystem, while keeping it "int" for the LSM
1997 * infrastructure.
1998 */
1999static int param_get_aaintbool(char *buffer, const struct kernel_param *kp)
2000{
2001	struct kernel_param kp_local;
2002	bool value;
2003
2004	/* Create local copy, with arg pointing to bool type. */
2005	value = !!*((int *)kp->arg);
2006	memcpy(&kp_local, kp, sizeof(kp_local));
2007	kp_local.arg = &value;
2008
2009	return param_get_bool(buffer, &kp_local);
2010}
2011
2012static int param_set_aacompressionlevel(const char *val,
2013					const struct kernel_param *kp)
2014{
2015	int error;
2016
2017	if (!apparmor_enabled)
2018		return -EINVAL;
2019	if (apparmor_initialized)
2020		return -EPERM;
2021
2022	error = param_set_int(val, kp);
2023
2024	aa_g_rawdata_compression_level = clamp(aa_g_rawdata_compression_level,
2025					       AA_MIN_CLEVEL, AA_MAX_CLEVEL);
2026	pr_info("AppArmor: policy rawdata compression level set to %d\n",
2027		aa_g_rawdata_compression_level);
2028
2029	return error;
2030}
2031
2032static int param_get_aacompressionlevel(char *buffer,
2033					const struct kernel_param *kp)
2034{
2035	if (!apparmor_enabled)
2036		return -EINVAL;
2037	if (apparmor_initialized && !aa_current_policy_view_capable(NULL))
2038		return -EPERM;
2039	return param_get_int(buffer, kp);
2040}
2041
2042static int param_get_debug(char *buffer, const struct kernel_param *kp)
2043{
2044	if (!apparmor_enabled)
2045		return -EINVAL;
2046	if (apparmor_initialized && !aa_current_policy_view_capable(NULL))
2047		return -EPERM;
2048	return aa_print_debug_params(buffer);
2049}
2050
2051static int param_set_debug(const char *val, const struct kernel_param *kp)
2052{
2053	int i;
2054
2055	if (!apparmor_enabled)
2056		return -EINVAL;
2057	if (!val)
2058		return -EINVAL;
2059	if (apparmor_initialized && !aa_current_policy_admin_capable(NULL))
2060		return -EPERM;
2061
2062	i = aa_parse_debug_params(val);
2063	if (i == DEBUG_PARSE_ERROR)
2064		return -EINVAL;
2065
2066	aa_g_debug = i;
2067	return 0;
2068}
2069
2070static int param_get_audit(char *buffer, const struct kernel_param *kp)
2071{
2072	if (!apparmor_enabled)
2073		return -EINVAL;
2074	if (apparmor_initialized && !aa_current_policy_view_capable(NULL))
2075		return -EPERM;
2076	return sprintf(buffer, "%s", audit_mode_names[aa_g_audit]);
2077}
2078
2079static int param_set_audit(const char *val, const struct kernel_param *kp)
2080{
2081	int i;
2082
2083	if (!apparmor_enabled)
2084		return -EINVAL;
2085	if (!val)
2086		return -EINVAL;
2087	if (apparmor_initialized && !aa_current_policy_admin_capable(NULL))
2088		return -EPERM;
2089
2090	i = match_string(audit_mode_names, AUDIT_MAX_INDEX, val);
2091	if (i < 0)
2092		return -EINVAL;
2093
2094	aa_g_audit = i;
2095	return 0;
2096}
2097
2098static int param_get_mode(char *buffer, const struct kernel_param *kp)
2099{
2100	if (!apparmor_enabled)
2101		return -EINVAL;
2102	if (apparmor_initialized && !aa_current_policy_view_capable(NULL))
2103		return -EPERM;
2104
2105	return sprintf(buffer, "%s", aa_profile_mode_names[aa_g_profile_mode]);
2106}
2107
2108static int param_set_mode(const char *val, const struct kernel_param *kp)
2109{
2110	int i;
2111
2112	if (!apparmor_enabled)
2113		return -EINVAL;
2114	if (!val)
2115		return -EINVAL;
2116	if (apparmor_initialized && !aa_current_policy_admin_capable(NULL))
2117		return -EPERM;
2118
2119	i = match_string(aa_profile_mode_names, APPARMOR_MODE_NAMES_MAX_INDEX,
2120			 val);
2121	if (i < 0)
2122		return -EINVAL;
2123
2124	aa_g_profile_mode = i;
2125	return 0;
2126}
2127
2128char *aa_get_buffer(bool in_atomic)
2129{
2130	union aa_buffer *aa_buf;
2131	struct aa_local_cache *cache;
2132	bool try_again = true;
2133	gfp_t flags = (GFP_KERNEL | __GFP_RETRY_MAYFAIL | __GFP_NOWARN);
2134
2135	/* use per cpu cached buffers first */
2136	cache = get_cpu_ptr(&aa_local_buffers);
2137	if (!list_empty(&cache->head)) {
2138		aa_buf = list_first_entry(&cache->head, union aa_buffer, list);
2139		list_del(&aa_buf->list);
2140		if (cache->hold)
2141			cache->hold--;
2142		cache->count--;
2143		put_cpu_ptr(&aa_local_buffers);
2144		return &aa_buf->buffer[0];
2145	}
2146	put_cpu_ptr(&aa_local_buffers);
2147
2148	if (!spin_trylock(&aa_buffers_lock)) {
2149		cache = get_cpu_ptr(&aa_local_buffers);
2150		cache->hold += 1;
2151		put_cpu_ptr(&aa_local_buffers);
2152		spin_lock(&aa_buffers_lock);
2153	} else {
2154		cache = get_cpu_ptr(&aa_local_buffers);
2155		put_cpu_ptr(&aa_local_buffers);
2156	}
2157retry:
2158	if (buffer_count > reserve_count ||
2159	    (in_atomic && !list_empty(&aa_global_buffers))) {
2160		aa_buf = list_first_entry(&aa_global_buffers, union aa_buffer,
2161					  list);
2162		list_del(&aa_buf->list);
2163		buffer_count--;
2164		spin_unlock(&aa_buffers_lock);
2165		return aa_buf->buffer;
2166	}
2167	if (in_atomic) {
2168		/*
2169		 * out of reserve buffers and in atomic context so increase
2170		 * how many buffers to keep in reserve
2171		 */
2172		reserve_count++;
2173		flags = GFP_ATOMIC;
2174	}
2175	spin_unlock(&aa_buffers_lock);
2176
2177	if (!in_atomic)
2178		might_sleep();
2179	aa_buf = kmalloc(aa_g_path_max, flags);
2180	if (!aa_buf) {
2181		if (try_again) {
2182			try_again = false;
2183			spin_lock(&aa_buffers_lock);
2184			goto retry;
2185		}
2186		pr_warn_once("AppArmor: Failed to allocate a memory buffer.\n");
2187		return NULL;
2188	}
2189	return aa_buf->buffer;
2190}
2191
2192void aa_put_buffer(char *buf)
2193{
2194	union aa_buffer *aa_buf;
2195	struct aa_local_cache *cache;
2196
2197	if (!buf)
2198		return;
2199	aa_buf = container_of(buf, union aa_buffer, buffer[0]);
2200
2201	cache = get_cpu_ptr(&aa_local_buffers);
2202	if (!cache->hold) {
2203		put_cpu_ptr(&aa_local_buffers);
2204
2205		if (spin_trylock(&aa_buffers_lock)) {
2206			/* put back on global list */
2207			list_add(&aa_buf->list, &aa_global_buffers);
2208			buffer_count++;
2209			spin_unlock(&aa_buffers_lock);
2210			cache = get_cpu_ptr(&aa_local_buffers);
2211			put_cpu_ptr(&aa_local_buffers);
2212			return;
2213		}
2214		/* contention on global list, fallback to percpu */
2215		cache = get_cpu_ptr(&aa_local_buffers);
2216		cache->hold += 1;
2217	}
2218
2219	/* cache in percpu list */
2220	list_add(&aa_buf->list, &cache->head);
2221	cache->count++;
2222	put_cpu_ptr(&aa_local_buffers);
2223}
2224
2225/*
2226 * AppArmor init functions
2227 */
2228
2229/**
2230 * set_init_ctx - set a task context and profile on the first task.
2231 *
2232 * TODO: allow setting an alternate profile than unconfined
2233 */
2234static int __init set_init_ctx(void)
2235{
2236	struct cred *cred = (__force struct cred *)current->real_cred;
2237
2238	set_cred_label(cred, aa_get_label(ns_unconfined(root_ns)));
2239
2240	return 0;
2241}
2242
2243static void destroy_buffers(void)
2244{
2245	union aa_buffer *aa_buf;
2246
2247	spin_lock(&aa_buffers_lock);
2248	while (!list_empty(&aa_global_buffers)) {
2249		aa_buf = list_first_entry(&aa_global_buffers, union aa_buffer,
2250					 list);
2251		list_del(&aa_buf->list);
2252		spin_unlock(&aa_buffers_lock);
2253		kfree(aa_buf);
2254		spin_lock(&aa_buffers_lock);
2255	}
2256	spin_unlock(&aa_buffers_lock);
2257}
2258
2259static int __init alloc_buffers(void)
2260{
2261	union aa_buffer *aa_buf;
2262	int i, num;
2263
2264	/*
2265	 * per cpu set of cached allocated buffers used to help reduce
2266	 * lock contention
2267	 */
2268	for_each_possible_cpu(i) {
2269		per_cpu(aa_local_buffers, i).hold = 0;
2270		per_cpu(aa_local_buffers, i).count = 0;
2271		INIT_LIST_HEAD(&per_cpu(aa_local_buffers, i).head);
2272	}
2273	/*
2274	 * A function may require two buffers at once. Usually the buffers are
2275	 * used for a short period of time and are shared. On UP kernel buffers
2276	 * two should be enough, with more CPUs it is possible that more
2277	 * buffers will be used simultaneously. The preallocated pool may grow.
2278	 * This preallocation has also the side-effect that AppArmor will be
2279	 * disabled early at boot if aa_g_path_max is extremely high.
2280	 */
2281	if (num_online_cpus() > 1)
2282		num = 4 + RESERVE_COUNT;
2283	else
2284		num = 2 + RESERVE_COUNT;
2285
2286	for (i = 0; i < num; i++) {
2287
2288		aa_buf = kmalloc(aa_g_path_max, GFP_KERNEL |
2289				 __GFP_RETRY_MAYFAIL | __GFP_NOWARN);
2290		if (!aa_buf) {
2291			destroy_buffers();
2292			return -ENOMEM;
2293		}
2294		aa_put_buffer(aa_buf->buffer);
2295	}
2296	return 0;
2297}
2298
2299#ifdef CONFIG_SYSCTL
2300static int apparmor_dointvec(const struct ctl_table *table, int write,
2301			     void *buffer, size_t *lenp, loff_t *ppos)
2302{
2303	if (!aa_current_policy_admin_capable(NULL))
2304		return -EPERM;
2305	if (!apparmor_enabled)
2306		return -EINVAL;
2307
2308	return proc_dointvec(table, write, buffer, lenp, ppos);
2309}
2310
2311static const struct ctl_table apparmor_sysctl_table[] = {
2312#ifdef CONFIG_USER_NS
2313	{
2314		.procname       = "unprivileged_userns_apparmor_policy",
2315		.data           = &unprivileged_userns_apparmor_policy,
2316		.maxlen         = sizeof(int),
2317		.mode           = 0600,
2318		.proc_handler   = apparmor_dointvec,
2319	},
2320#endif /* CONFIG_USER_NS */
2321	{
2322		.procname       = "apparmor_display_secid_mode",
2323		.data           = &apparmor_display_secid_mode,
2324		.maxlen         = sizeof(int),
2325		.mode           = 0600,
2326		.proc_handler   = apparmor_dointvec,
2327	},
2328	{
2329		.procname       = "apparmor_restrict_unprivileged_unconfined",
2330		.data           = &aa_unprivileged_unconfined_restricted,
2331		.maxlen         = sizeof(int),
2332		.mode           = 0600,
2333		.proc_handler   = apparmor_dointvec,
2334	},
2335};
2336
2337static int __init apparmor_init_sysctl(void)
2338{
2339	return register_sysctl("kernel", apparmor_sysctl_table) ? 0 : -ENOMEM;
2340}
2341#else
2342static inline int apparmor_init_sysctl(void)
2343{
2344	return 0;
2345}
2346#endif /* CONFIG_SYSCTL */
2347
2348#if defined(CONFIG_NETFILTER) && defined(CONFIG_NETWORK_SECMARK)
2349static unsigned int apparmor_ip_postroute(void *priv,
2350					  struct sk_buff *skb,
2351					  const struct nf_hook_state *state)
2352{
2353	struct aa_sk_ctx *ctx;
2354	struct sock *sk;
2355	int error;
2356
2357	if (!skb->secmark)
2358		return NF_ACCEPT;
2359
2360	sk = skb_to_full_sk(skb);
2361	if (sk == NULL)
2362		return NF_ACCEPT;
2363
2364	ctx = aa_sock(sk);
2365	rcu_read_lock();
2366	error = apparmor_secmark_check(rcu_dereference(ctx->label), OP_SENDMSG,
2367				       AA_MAY_SEND, skb->secmark, sk);
2368	rcu_read_unlock();
2369	if (!error)
2370		return NF_ACCEPT;
2371
2372	return NF_DROP_ERR(-ECONNREFUSED);
2373
2374}
2375
2376static const struct nf_hook_ops apparmor_nf_ops[] = {
2377	{
2378		.hook =         apparmor_ip_postroute,
2379		.pf =           NFPROTO_IPV4,
2380		.hooknum =      NF_INET_POST_ROUTING,
2381		.priority =     NF_IP_PRI_SELINUX_FIRST,
2382	},
2383#if IS_ENABLED(CONFIG_IPV6)
2384	{
2385		.hook =         apparmor_ip_postroute,
2386		.pf =           NFPROTO_IPV6,
2387		.hooknum =      NF_INET_POST_ROUTING,
2388		.priority =     NF_IP6_PRI_SELINUX_FIRST,
2389	},
2390#endif
2391};
2392
2393static int __net_init apparmor_nf_register(struct net *net)
2394{
2395	return nf_register_net_hooks(net, apparmor_nf_ops,
2396				    ARRAY_SIZE(apparmor_nf_ops));
2397}
2398
2399static void __net_exit apparmor_nf_unregister(struct net *net)
2400{
2401	nf_unregister_net_hooks(net, apparmor_nf_ops,
2402				ARRAY_SIZE(apparmor_nf_ops));
2403}
2404
2405static struct pernet_operations apparmor_net_ops = {
2406	.init = apparmor_nf_register,
2407	.exit = apparmor_nf_unregister,
2408};
2409
2410static int __init apparmor_nf_ip_init(void)
2411{
2412	int err;
2413
2414	if (!apparmor_enabled)
2415		return 0;
2416
2417	err = register_pernet_subsys(&apparmor_net_ops);
2418	if (err)
2419		panic("Apparmor: register_pernet_subsys: error %d\n", err);
2420
2421	return 0;
2422}
2423#endif
2424
2425static char nulldfa_src[] __aligned(8) = {
2426	#include "nulldfa.in"
2427};
2428static struct aa_dfa *nulldfa;
2429
2430static char stacksplitdfa_src[] __aligned(8) = {
2431	#include "stacksplitdfa.in"
2432};
2433struct aa_dfa *stacksplitdfa;
2434struct aa_policydb *nullpdb;
2435
2436static int __init aa_setup_dfa_engine(void)
2437{
2438	int error = -ENOMEM;
2439
2440	nullpdb = aa_alloc_pdb(GFP_KERNEL);
2441	if (!nullpdb)
2442		return -ENOMEM;
2443
2444	nulldfa = aa_dfa_unpack(nulldfa_src, sizeof(nulldfa_src),
2445			    TO_ACCEPT1_FLAG(YYTD_DATA32) |
2446			    TO_ACCEPT2_FLAG(YYTD_DATA32));
2447	if (IS_ERR(nulldfa)) {
2448		error = PTR_ERR(nulldfa);
2449		goto fail;
2450	}
2451	nullpdb->dfa = aa_get_dfa(nulldfa);
2452	nullpdb->perms = kcalloc(2, sizeof(struct aa_perms), GFP_KERNEL);
2453	if (!nullpdb->perms)
2454		goto fail;
2455	nullpdb->size = 2;
2456
2457	stacksplitdfa = aa_dfa_unpack(stacksplitdfa_src,
2458				      sizeof(stacksplitdfa_src),
2459				      TO_ACCEPT1_FLAG(YYTD_DATA32) |
2460				      TO_ACCEPT2_FLAG(YYTD_DATA32));
2461	if (IS_ERR(stacksplitdfa)) {
2462		error = PTR_ERR(stacksplitdfa);
2463		goto fail;
2464	}
2465
2466	return 0;
2467
2468fail:
2469	aa_put_pdb(nullpdb);
2470	aa_put_dfa(nulldfa);
2471	nullpdb = NULL;
2472	nulldfa = NULL;
2473	stacksplitdfa = NULL;
2474
2475	return error;
2476}
2477
2478static void __init aa_teardown_dfa_engine(void)
2479{
2480	aa_put_dfa(stacksplitdfa);
2481	aa_put_dfa(nulldfa);
2482	aa_put_pdb(nullpdb);
2483	nullpdb = NULL;
2484	stacksplitdfa = NULL;
2485	nulldfa = NULL;
2486}
2487
2488static int __init apparmor_init(void)
2489{
2490	int error;
2491
2492	error = aa_setup_dfa_engine();
2493	if (error) {
2494		AA_ERROR("Unable to setup dfa engine\n");
2495		goto alloc_out;
2496	}
2497
2498	error = aa_alloc_root_ns();
2499	if (error) {
2500		AA_ERROR("Unable to allocate default profile namespace\n");
2501		goto alloc_out;
2502	}
2503
2504	error = apparmor_init_sysctl();
2505	if (error) {
2506		AA_ERROR("Unable to register sysctls\n");
2507		goto alloc_out;
2508
2509	}
2510
2511	error = alloc_buffers();
2512	if (error) {
2513		AA_ERROR("Unable to allocate work buffers\n");
2514		goto alloc_out;
2515	}
2516
2517	error = set_init_ctx();
2518	if (error) {
2519		AA_ERROR("Failed to set context on init task\n");
2520		aa_free_root_ns();
2521		goto buffers_out;
2522	}
2523	security_add_hooks(apparmor_hooks, ARRAY_SIZE(apparmor_hooks),
2524				&apparmor_lsmid);
2525
2526	/* Inform the audit system that secctx is used */
2527	audit_cfg_lsm(&apparmor_lsmid, AUDIT_CFG_LSM_SECCTX_SUBJECT);
2528
2529	/* Report that AppArmor successfully initialized */
2530	apparmor_initialized = 1;
2531	if (aa_g_profile_mode == APPARMOR_COMPLAIN)
2532		aa_info_message("AppArmor initialized: complain mode enabled");
2533	else if (aa_g_profile_mode == APPARMOR_KILL)
2534		aa_info_message("AppArmor initialized: kill mode enabled");
2535	else
2536		aa_info_message("AppArmor initialized");
2537
2538	return error;
2539
2540buffers_out:
2541	destroy_buffers();
2542alloc_out:
2543	aa_destroy_aafs();
2544	aa_teardown_dfa_engine();
2545
2546	apparmor_enabled = false;
2547	return error;
2548}
2549
2550DEFINE_LSM(apparmor) = {
2551	.id = &apparmor_lsmid,
2552	.flags = LSM_FLAG_LEGACY_MAJOR | LSM_FLAG_EXCLUSIVE,
2553	.enabled = &apparmor_enabled,
2554	.blobs = &apparmor_blob_sizes,
2555	.init = apparmor_init,
2556	.initcall_fs = aa_create_aafs,
2557#if defined(CONFIG_NETFILTER) && defined(CONFIG_NETWORK_SECMARK)
2558	.initcall_device = apparmor_nf_ip_init,
2559#endif
2560#ifdef CONFIG_SECURITY_APPARMOR_HASH
2561	.initcall_late = init_profile_hash,
2562#endif
2563};
~/ Read-only file preview.