xref: /openbmc/linux/kernel/auditsc.c (revision d40d48e1)
1 // SPDX-License-Identifier: GPL-2.0-or-later
2 /* auditsc.c -- System-call auditing support
3  * Handles all system-call specific auditing features.
4  *
5  * Copyright 2003-2004 Red Hat Inc., Durham, North Carolina.
6  * Copyright 2005 Hewlett-Packard Development Company, L.P.
7  * Copyright (C) 2005, 2006 IBM Corporation
8  * All Rights Reserved.
9  *
10  * Written by Rickard E. (Rik) Faith <faith@redhat.com>
11  *
12  * Many of the ideas implemented here are from Stephen C. Tweedie,
13  * especially the idea of avoiding a copy by using getname.
14  *
15  * The method for actual interception of syscall entry and exit (not in
16  * this file -- see entry.S) is based on a GPL'd patch written by
17  * okir@suse.de and Copyright 2003 SuSE Linux AG.
18  *
19  * POSIX message queue support added by George Wilson <ltcgcw@us.ibm.com>,
20  * 2006.
21  *
22  * The support of additional filter rules compares (>, <, >=, <=) was
23  * added by Dustin Kirkland <dustin.kirkland@us.ibm.com>, 2005.
24  *
25  * Modified by Amy Griffis <amy.griffis@hp.com> to collect additional
26  * filesystem information.
27  *
28  * Subject and object context labeling support added by <danjones@us.ibm.com>
29  * and <dustin.kirkland@us.ibm.com> for LSPP certification compliance.
30  */
31 
32 #define pr_fmt(fmt) KBUILD_MODNAME ": " fmt
33 
34 #include <linux/init.h>
35 #include <asm/types.h>
36 #include <linux/atomic.h>
37 #include <linux/fs.h>
38 #include <linux/namei.h>
39 #include <linux/mm.h>
40 #include <linux/export.h>
41 #include <linux/slab.h>
42 #include <linux/mount.h>
43 #include <linux/socket.h>
44 #include <linux/mqueue.h>
45 #include <linux/audit.h>
46 #include <linux/personality.h>
47 #include <linux/time.h>
48 #include <linux/netlink.h>
49 #include <linux/compiler.h>
50 #include <asm/unistd.h>
51 #include <linux/security.h>
52 #include <linux/list.h>
53 #include <linux/binfmts.h>
54 #include <linux/highmem.h>
55 #include <linux/syscalls.h>
56 #include <asm/syscall.h>
57 #include <linux/capability.h>
58 #include <linux/fs_struct.h>
59 #include <linux/compat.h>
60 #include <linux/ctype.h>
61 #include <linux/string.h>
62 #include <linux/uaccess.h>
63 #include <linux/fsnotify_backend.h>
64 #include <uapi/linux/limits.h>
65 #include <uapi/linux/netfilter/nf_tables.h>
66 #include <uapi/linux/openat2.h> // struct open_how
67 
68 #include "audit.h"
69 
70 /* flags stating the success for a syscall */
71 #define AUDITSC_INVALID 0
72 #define AUDITSC_SUCCESS 1
73 #define AUDITSC_FAILURE 2
74 
75 /* no execve audit message should be longer than this (userspace limits),
76  * see the note near the top of audit_log_execve_info() about this value */
77 #define MAX_EXECVE_AUDIT_LEN 7500
78 
79 /* max length to print of cmdline/proctitle value during audit */
80 #define MAX_PROCTITLE_AUDIT_LEN 128
81 
82 /* number of audit rules */
83 int audit_n_rules;
84 
85 /* determines whether we collect data for signals sent */
86 int audit_signals;
87 
88 struct audit_aux_data {
89 	struct audit_aux_data	*next;
90 	int			type;
91 };
92 
93 /* Number of target pids per aux struct. */
94 #define AUDIT_AUX_PIDS	16
95 
96 struct audit_aux_data_pids {
97 	struct audit_aux_data	d;
98 	pid_t			target_pid[AUDIT_AUX_PIDS];
99 	kuid_t			target_auid[AUDIT_AUX_PIDS];
100 	kuid_t			target_uid[AUDIT_AUX_PIDS];
101 	unsigned int		target_sessionid[AUDIT_AUX_PIDS];
102 	u32			target_sid[AUDIT_AUX_PIDS];
103 	char 			target_comm[AUDIT_AUX_PIDS][TASK_COMM_LEN];
104 	int			pid_count;
105 };
106 
107 struct audit_aux_data_bprm_fcaps {
108 	struct audit_aux_data	d;
109 	struct audit_cap_data	fcap;
110 	unsigned int		fcap_ver;
111 	struct audit_cap_data	old_pcap;
112 	struct audit_cap_data	new_pcap;
113 };
114 
115 struct audit_tree_refs {
116 	struct audit_tree_refs *next;
117 	struct audit_chunk *c[31];
118 };
119 
120 struct audit_nfcfgop_tab {
121 	enum audit_nfcfgop	op;
122 	const char		*s;
123 };
124 
125 static const struct audit_nfcfgop_tab audit_nfcfgs[] = {
126 	{ AUDIT_XT_OP_REGISTER,			"xt_register"		   },
127 	{ AUDIT_XT_OP_REPLACE,			"xt_replace"		   },
128 	{ AUDIT_XT_OP_UNREGISTER,		"xt_unregister"		   },
129 	{ AUDIT_NFT_OP_TABLE_REGISTER,		"nft_register_table"	   },
130 	{ AUDIT_NFT_OP_TABLE_UNREGISTER,	"nft_unregister_table"	   },
131 	{ AUDIT_NFT_OP_CHAIN_REGISTER,		"nft_register_chain"	   },
132 	{ AUDIT_NFT_OP_CHAIN_UNREGISTER,	"nft_unregister_chain"	   },
133 	{ AUDIT_NFT_OP_RULE_REGISTER,		"nft_register_rule"	   },
134 	{ AUDIT_NFT_OP_RULE_UNREGISTER,		"nft_unregister_rule"	   },
135 	{ AUDIT_NFT_OP_SET_REGISTER,		"nft_register_set"	   },
136 	{ AUDIT_NFT_OP_SET_UNREGISTER,		"nft_unregister_set"	   },
137 	{ AUDIT_NFT_OP_SETELEM_REGISTER,	"nft_register_setelem"	   },
138 	{ AUDIT_NFT_OP_SETELEM_UNREGISTER,	"nft_unregister_setelem"   },
139 	{ AUDIT_NFT_OP_GEN_REGISTER,		"nft_register_gen"	   },
140 	{ AUDIT_NFT_OP_OBJ_REGISTER,		"nft_register_obj"	   },
141 	{ AUDIT_NFT_OP_OBJ_UNREGISTER,		"nft_unregister_obj"	   },
142 	{ AUDIT_NFT_OP_OBJ_RESET,		"nft_reset_obj"		   },
143 	{ AUDIT_NFT_OP_FLOWTABLE_REGISTER,	"nft_register_flowtable"   },
144 	{ AUDIT_NFT_OP_FLOWTABLE_UNREGISTER,	"nft_unregister_flowtable" },
145 	{ AUDIT_NFT_OP_INVALID,			"nft_invalid"		   },
146 };
147 
148 static int audit_match_perm(struct audit_context *ctx, int mask)
149 {
150 	unsigned n;
151 
152 	if (unlikely(!ctx))
153 		return 0;
154 	n = ctx->major;
155 
156 	switch (audit_classify_syscall(ctx->arch, n)) {
157 	case AUDITSC_NATIVE:
158 		if ((mask & AUDIT_PERM_WRITE) &&
159 		     audit_match_class(AUDIT_CLASS_WRITE, n))
160 			return 1;
161 		if ((mask & AUDIT_PERM_READ) &&
162 		     audit_match_class(AUDIT_CLASS_READ, n))
163 			return 1;
164 		if ((mask & AUDIT_PERM_ATTR) &&
165 		     audit_match_class(AUDIT_CLASS_CHATTR, n))
166 			return 1;
167 		return 0;
168 	case AUDITSC_COMPAT: /* 32bit on biarch */
169 		if ((mask & AUDIT_PERM_WRITE) &&
170 		     audit_match_class(AUDIT_CLASS_WRITE_32, n))
171 			return 1;
172 		if ((mask & AUDIT_PERM_READ) &&
173 		     audit_match_class(AUDIT_CLASS_READ_32, n))
174 			return 1;
175 		if ((mask & AUDIT_PERM_ATTR) &&
176 		     audit_match_class(AUDIT_CLASS_CHATTR_32, n))
177 			return 1;
178 		return 0;
179 	case AUDITSC_OPEN:
180 		return mask & ACC_MODE(ctx->argv[1]);
181 	case AUDITSC_OPENAT:
182 		return mask & ACC_MODE(ctx->argv[2]);
183 	case AUDITSC_SOCKETCALL:
184 		return ((mask & AUDIT_PERM_WRITE) && ctx->argv[0] == SYS_BIND);
185 	case AUDITSC_EXECVE:
186 		return mask & AUDIT_PERM_EXEC;
187 	case AUDITSC_OPENAT2:
188 		return mask & ACC_MODE((u32)((struct open_how *)ctx->argv[2])->flags);
189 	default:
190 		return 0;
191 	}
192 }
193 
194 static int audit_match_filetype(struct audit_context *ctx, int val)
195 {
196 	struct audit_names *n;
197 	umode_t mode = (umode_t)val;
198 
199 	if (unlikely(!ctx))
200 		return 0;
201 
202 	list_for_each_entry(n, &ctx->names_list, list) {
203 		if ((n->ino != AUDIT_INO_UNSET) &&
204 		    ((n->mode & S_IFMT) == mode))
205 			return 1;
206 	}
207 
208 	return 0;
209 }
210 
211 /*
212  * We keep a linked list of fixed-sized (31 pointer) arrays of audit_chunk *;
213  * ->first_trees points to its beginning, ->trees - to the current end of data.
214  * ->tree_count is the number of free entries in array pointed to by ->trees.
215  * Original condition is (NULL, NULL, 0); as soon as it grows we never revert to NULL,
216  * "empty" becomes (p, p, 31) afterwards.  We don't shrink the list (and seriously,
217  * it's going to remain 1-element for almost any setup) until we free context itself.
218  * References in it _are_ dropped - at the same time we free/drop aux stuff.
219  */
220 
221 static void audit_set_auditable(struct audit_context *ctx)
222 {
223 	if (!ctx->prio) {
224 		ctx->prio = 1;
225 		ctx->current_state = AUDIT_STATE_RECORD;
226 	}
227 }
228 
229 static int put_tree_ref(struct audit_context *ctx, struct audit_chunk *chunk)
230 {
231 	struct audit_tree_refs *p = ctx->trees;
232 	int left = ctx->tree_count;
233 
234 	if (likely(left)) {
235 		p->c[--left] = chunk;
236 		ctx->tree_count = left;
237 		return 1;
238 	}
239 	if (!p)
240 		return 0;
241 	p = p->next;
242 	if (p) {
243 		p->c[30] = chunk;
244 		ctx->trees = p;
245 		ctx->tree_count = 30;
246 		return 1;
247 	}
248 	return 0;
249 }
250 
251 static int grow_tree_refs(struct audit_context *ctx)
252 {
253 	struct audit_tree_refs *p = ctx->trees;
254 
255 	ctx->trees = kzalloc(sizeof(struct audit_tree_refs), GFP_KERNEL);
256 	if (!ctx->trees) {
257 		ctx->trees = p;
258 		return 0;
259 	}
260 	if (p)
261 		p->next = ctx->trees;
262 	else
263 		ctx->first_trees = ctx->trees;
264 	ctx->tree_count = 31;
265 	return 1;
266 }
267 
268 static void unroll_tree_refs(struct audit_context *ctx,
269 		      struct audit_tree_refs *p, int count)
270 {
271 	struct audit_tree_refs *q;
272 	int n;
273 
274 	if (!p) {
275 		/* we started with empty chain */
276 		p = ctx->first_trees;
277 		count = 31;
278 		/* if the very first allocation has failed, nothing to do */
279 		if (!p)
280 			return;
281 	}
282 	n = count;
283 	for (q = p; q != ctx->trees; q = q->next, n = 31) {
284 		while (n--) {
285 			audit_put_chunk(q->c[n]);
286 			q->c[n] = NULL;
287 		}
288 	}
289 	while (n-- > ctx->tree_count) {
290 		audit_put_chunk(q->c[n]);
291 		q->c[n] = NULL;
292 	}
293 	ctx->trees = p;
294 	ctx->tree_count = count;
295 }
296 
297 static void free_tree_refs(struct audit_context *ctx)
298 {
299 	struct audit_tree_refs *p, *q;
300 
301 	for (p = ctx->first_trees; p; p = q) {
302 		q = p->next;
303 		kfree(p);
304 	}
305 }
306 
307 static int match_tree_refs(struct audit_context *ctx, struct audit_tree *tree)
308 {
309 	struct audit_tree_refs *p;
310 	int n;
311 
312 	if (!tree)
313 		return 0;
314 	/* full ones */
315 	for (p = ctx->first_trees; p != ctx->trees; p = p->next) {
316 		for (n = 0; n < 31; n++)
317 			if (audit_tree_match(p->c[n], tree))
318 				return 1;
319 	}
320 	/* partial */
321 	if (p) {
322 		for (n = ctx->tree_count; n < 31; n++)
323 			if (audit_tree_match(p->c[n], tree))
324 				return 1;
325 	}
326 	return 0;
327 }
328 
329 static int audit_compare_uid(kuid_t uid,
330 			     struct audit_names *name,
331 			     struct audit_field *f,
332 			     struct audit_context *ctx)
333 {
334 	struct audit_names *n;
335 	int rc;
336 
337 	if (name) {
338 		rc = audit_uid_comparator(uid, f->op, name->uid);
339 		if (rc)
340 			return rc;
341 	}
342 
343 	if (ctx) {
344 		list_for_each_entry(n, &ctx->names_list, list) {
345 			rc = audit_uid_comparator(uid, f->op, n->uid);
346 			if (rc)
347 				return rc;
348 		}
349 	}
350 	return 0;
351 }
352 
353 static int audit_compare_gid(kgid_t gid,
354 			     struct audit_names *name,
355 			     struct audit_field *f,
356 			     struct audit_context *ctx)
357 {
358 	struct audit_names *n;
359 	int rc;
360 
361 	if (name) {
362 		rc = audit_gid_comparator(gid, f->op, name->gid);
363 		if (rc)
364 			return rc;
365 	}
366 
367 	if (ctx) {
368 		list_for_each_entry(n, &ctx->names_list, list) {
369 			rc = audit_gid_comparator(gid, f->op, n->gid);
370 			if (rc)
371 				return rc;
372 		}
373 	}
374 	return 0;
375 }
376 
377 static int audit_field_compare(struct task_struct *tsk,
378 			       const struct cred *cred,
379 			       struct audit_field *f,
380 			       struct audit_context *ctx,
381 			       struct audit_names *name)
382 {
383 	switch (f->val) {
384 	/* process to file object comparisons */
385 	case AUDIT_COMPARE_UID_TO_OBJ_UID:
386 		return audit_compare_uid(cred->uid, name, f, ctx);
387 	case AUDIT_COMPARE_GID_TO_OBJ_GID:
388 		return audit_compare_gid(cred->gid, name, f, ctx);
389 	case AUDIT_COMPARE_EUID_TO_OBJ_UID:
390 		return audit_compare_uid(cred->euid, name, f, ctx);
391 	case AUDIT_COMPARE_EGID_TO_OBJ_GID:
392 		return audit_compare_gid(cred->egid, name, f, ctx);
393 	case AUDIT_COMPARE_AUID_TO_OBJ_UID:
394 		return audit_compare_uid(audit_get_loginuid(tsk), name, f, ctx);
395 	case AUDIT_COMPARE_SUID_TO_OBJ_UID:
396 		return audit_compare_uid(cred->suid, name, f, ctx);
397 	case AUDIT_COMPARE_SGID_TO_OBJ_GID:
398 		return audit_compare_gid(cred->sgid, name, f, ctx);
399 	case AUDIT_COMPARE_FSUID_TO_OBJ_UID:
400 		return audit_compare_uid(cred->fsuid, name, f, ctx);
401 	case AUDIT_COMPARE_FSGID_TO_OBJ_GID:
402 		return audit_compare_gid(cred->fsgid, name, f, ctx);
403 	/* uid comparisons */
404 	case AUDIT_COMPARE_UID_TO_AUID:
405 		return audit_uid_comparator(cred->uid, f->op,
406 					    audit_get_loginuid(tsk));
407 	case AUDIT_COMPARE_UID_TO_EUID:
408 		return audit_uid_comparator(cred->uid, f->op, cred->euid);
409 	case AUDIT_COMPARE_UID_TO_SUID:
410 		return audit_uid_comparator(cred->uid, f->op, cred->suid);
411 	case AUDIT_COMPARE_UID_TO_FSUID:
412 		return audit_uid_comparator(cred->uid, f->op, cred->fsuid);
413 	/* auid comparisons */
414 	case AUDIT_COMPARE_AUID_TO_EUID:
415 		return audit_uid_comparator(audit_get_loginuid(tsk), f->op,
416 					    cred->euid);
417 	case AUDIT_COMPARE_AUID_TO_SUID:
418 		return audit_uid_comparator(audit_get_loginuid(tsk), f->op,
419 					    cred->suid);
420 	case AUDIT_COMPARE_AUID_TO_FSUID:
421 		return audit_uid_comparator(audit_get_loginuid(tsk), f->op,
422 					    cred->fsuid);
423 	/* euid comparisons */
424 	case AUDIT_COMPARE_EUID_TO_SUID:
425 		return audit_uid_comparator(cred->euid, f->op, cred->suid);
426 	case AUDIT_COMPARE_EUID_TO_FSUID:
427 		return audit_uid_comparator(cred->euid, f->op, cred->fsuid);
428 	/* suid comparisons */
429 	case AUDIT_COMPARE_SUID_TO_FSUID:
430 		return audit_uid_comparator(cred->suid, f->op, cred->fsuid);
431 	/* gid comparisons */
432 	case AUDIT_COMPARE_GID_TO_EGID:
433 		return audit_gid_comparator(cred->gid, f->op, cred->egid);
434 	case AUDIT_COMPARE_GID_TO_SGID:
435 		return audit_gid_comparator(cred->gid, f->op, cred->sgid);
436 	case AUDIT_COMPARE_GID_TO_FSGID:
437 		return audit_gid_comparator(cred->gid, f->op, cred->fsgid);
438 	/* egid comparisons */
439 	case AUDIT_COMPARE_EGID_TO_SGID:
440 		return audit_gid_comparator(cred->egid, f->op, cred->sgid);
441 	case AUDIT_COMPARE_EGID_TO_FSGID:
442 		return audit_gid_comparator(cred->egid, f->op, cred->fsgid);
443 	/* sgid comparison */
444 	case AUDIT_COMPARE_SGID_TO_FSGID:
445 		return audit_gid_comparator(cred->sgid, f->op, cred->fsgid);
446 	default:
447 		WARN(1, "Missing AUDIT_COMPARE define.  Report as a bug\n");
448 		return 0;
449 	}
450 	return 0;
451 }
452 
453 /* Determine if any context name data matches a rule's watch data */
454 /* Compare a task_struct with an audit_rule.  Return 1 on match, 0
455  * otherwise.
456  *
457  * If task_creation is true, this is an explicit indication that we are
458  * filtering a task rule at task creation time.  This and tsk == current are
459  * the only situations where tsk->cred may be accessed without an rcu read lock.
460  */
461 static int audit_filter_rules(struct task_struct *tsk,
462 			      struct audit_krule *rule,
463 			      struct audit_context *ctx,
464 			      struct audit_names *name,
465 			      enum audit_state *state,
466 			      bool task_creation)
467 {
468 	const struct cred *cred;
469 	int i, need_sid = 1;
470 	u32 sid;
471 	unsigned int sessionid;
472 
473 	if (ctx && rule->prio <= ctx->prio)
474 		return 0;
475 
476 	cred = rcu_dereference_check(tsk->cred, tsk == current || task_creation);
477 
478 	for (i = 0; i < rule->field_count; i++) {
479 		struct audit_field *f = &rule->fields[i];
480 		struct audit_names *n;
481 		int result = 0;
482 		pid_t pid;
483 
484 		switch (f->type) {
485 		case AUDIT_PID:
486 			pid = task_tgid_nr(tsk);
487 			result = audit_comparator(pid, f->op, f->val);
488 			break;
489 		case AUDIT_PPID:
490 			if (ctx) {
491 				if (!ctx->ppid)
492 					ctx->ppid = task_ppid_nr(tsk);
493 				result = audit_comparator(ctx->ppid, f->op, f->val);
494 			}
495 			break;
496 		case AUDIT_EXE:
497 			result = audit_exe_compare(tsk, rule->exe);
498 			if (f->op == Audit_not_equal)
499 				result = !result;
500 			break;
501 		case AUDIT_UID:
502 			result = audit_uid_comparator(cred->uid, f->op, f->uid);
503 			break;
504 		case AUDIT_EUID:
505 			result = audit_uid_comparator(cred->euid, f->op, f->uid);
506 			break;
507 		case AUDIT_SUID:
508 			result = audit_uid_comparator(cred->suid, f->op, f->uid);
509 			break;
510 		case AUDIT_FSUID:
511 			result = audit_uid_comparator(cred->fsuid, f->op, f->uid);
512 			break;
513 		case AUDIT_GID:
514 			result = audit_gid_comparator(cred->gid, f->op, f->gid);
515 			if (f->op == Audit_equal) {
516 				if (!result)
517 					result = groups_search(cred->group_info, f->gid);
518 			} else if (f->op == Audit_not_equal) {
519 				if (result)
520 					result = !groups_search(cred->group_info, f->gid);
521 			}
522 			break;
523 		case AUDIT_EGID:
524 			result = audit_gid_comparator(cred->egid, f->op, f->gid);
525 			if (f->op == Audit_equal) {
526 				if (!result)
527 					result = groups_search(cred->group_info, f->gid);
528 			} else if (f->op == Audit_not_equal) {
529 				if (result)
530 					result = !groups_search(cred->group_info, f->gid);
531 			}
532 			break;
533 		case AUDIT_SGID:
534 			result = audit_gid_comparator(cred->sgid, f->op, f->gid);
535 			break;
536 		case AUDIT_FSGID:
537 			result = audit_gid_comparator(cred->fsgid, f->op, f->gid);
538 			break;
539 		case AUDIT_SESSIONID:
540 			sessionid = audit_get_sessionid(tsk);
541 			result = audit_comparator(sessionid, f->op, f->val);
542 			break;
543 		case AUDIT_PERS:
544 			result = audit_comparator(tsk->personality, f->op, f->val);
545 			break;
546 		case AUDIT_ARCH:
547 			if (ctx)
548 				result = audit_comparator(ctx->arch, f->op, f->val);
549 			break;
550 
551 		case AUDIT_EXIT:
552 			if (ctx && ctx->return_valid != AUDITSC_INVALID)
553 				result = audit_comparator(ctx->return_code, f->op, f->val);
554 			break;
555 		case AUDIT_SUCCESS:
556 			if (ctx && ctx->return_valid != AUDITSC_INVALID) {
557 				if (f->val)
558 					result = audit_comparator(ctx->return_valid, f->op, AUDITSC_SUCCESS);
559 				else
560 					result = audit_comparator(ctx->return_valid, f->op, AUDITSC_FAILURE);
561 			}
562 			break;
563 		case AUDIT_DEVMAJOR:
564 			if (name) {
565 				if (audit_comparator(MAJOR(name->dev), f->op, f->val) ||
566 				    audit_comparator(MAJOR(name->rdev), f->op, f->val))
567 					++result;
568 			} else if (ctx) {
569 				list_for_each_entry(n, &ctx->names_list, list) {
570 					if (audit_comparator(MAJOR(n->dev), f->op, f->val) ||
571 					    audit_comparator(MAJOR(n->rdev), f->op, f->val)) {
572 						++result;
573 						break;
574 					}
575 				}
576 			}
577 			break;
578 		case AUDIT_DEVMINOR:
579 			if (name) {
580 				if (audit_comparator(MINOR(name->dev), f->op, f->val) ||
581 				    audit_comparator(MINOR(name->rdev), f->op, f->val))
582 					++result;
583 			} else if (ctx) {
584 				list_for_each_entry(n, &ctx->names_list, list) {
585 					if (audit_comparator(MINOR(n->dev), f->op, f->val) ||
586 					    audit_comparator(MINOR(n->rdev), f->op, f->val)) {
587 						++result;
588 						break;
589 					}
590 				}
591 			}
592 			break;
593 		case AUDIT_INODE:
594 			if (name)
595 				result = audit_comparator(name->ino, f->op, f->val);
596 			else if (ctx) {
597 				list_for_each_entry(n, &ctx->names_list, list) {
598 					if (audit_comparator(n->ino, f->op, f->val)) {
599 						++result;
600 						break;
601 					}
602 				}
603 			}
604 			break;
605 		case AUDIT_OBJ_UID:
606 			if (name) {
607 				result = audit_uid_comparator(name->uid, f->op, f->uid);
608 			} else if (ctx) {
609 				list_for_each_entry(n, &ctx->names_list, list) {
610 					if (audit_uid_comparator(n->uid, f->op, f->uid)) {
611 						++result;
612 						break;
613 					}
614 				}
615 			}
616 			break;
617 		case AUDIT_OBJ_GID:
618 			if (name) {
619 				result = audit_gid_comparator(name->gid, f->op, f->gid);
620 			} else if (ctx) {
621 				list_for_each_entry(n, &ctx->names_list, list) {
622 					if (audit_gid_comparator(n->gid, f->op, f->gid)) {
623 						++result;
624 						break;
625 					}
626 				}
627 			}
628 			break;
629 		case AUDIT_WATCH:
630 			if (name) {
631 				result = audit_watch_compare(rule->watch,
632 							     name->ino,
633 							     name->dev);
634 				if (f->op == Audit_not_equal)
635 					result = !result;
636 			}
637 			break;
638 		case AUDIT_DIR:
639 			if (ctx) {
640 				result = match_tree_refs(ctx, rule->tree);
641 				if (f->op == Audit_not_equal)
642 					result = !result;
643 			}
644 			break;
645 		case AUDIT_LOGINUID:
646 			result = audit_uid_comparator(audit_get_loginuid(tsk),
647 						      f->op, f->uid);
648 			break;
649 		case AUDIT_LOGINUID_SET:
650 			result = audit_comparator(audit_loginuid_set(tsk), f->op, f->val);
651 			break;
652 		case AUDIT_SADDR_FAM:
653 			if (ctx && ctx->sockaddr)
654 				result = audit_comparator(ctx->sockaddr->ss_family,
655 							  f->op, f->val);
656 			break;
657 		case AUDIT_SUBJ_USER:
658 		case AUDIT_SUBJ_ROLE:
659 		case AUDIT_SUBJ_TYPE:
660 		case AUDIT_SUBJ_SEN:
661 		case AUDIT_SUBJ_CLR:
662 			/* NOTE: this may return negative values indicating
663 			   a temporary error.  We simply treat this as a
664 			   match for now to avoid losing information that
665 			   may be wanted.   An error message will also be
666 			   logged upon error */
667 			if (f->lsm_rule) {
668 				if (need_sid) {
669 					security_task_getsecid_subj(tsk, &sid);
670 					need_sid = 0;
671 				}
672 				result = security_audit_rule_match(sid, f->type,
673 								   f->op,
674 								   f->lsm_rule);
675 			}
676 			break;
677 		case AUDIT_OBJ_USER:
678 		case AUDIT_OBJ_ROLE:
679 		case AUDIT_OBJ_TYPE:
680 		case AUDIT_OBJ_LEV_LOW:
681 		case AUDIT_OBJ_LEV_HIGH:
682 			/* The above note for AUDIT_SUBJ_USER...AUDIT_SUBJ_CLR
683 			   also applies here */
684 			if (f->lsm_rule) {
685 				/* Find files that match */
686 				if (name) {
687 					result = security_audit_rule_match(
688 								name->osid,
689 								f->type,
690 								f->op,
691 								f->lsm_rule);
692 				} else if (ctx) {
693 					list_for_each_entry(n, &ctx->names_list, list) {
694 						if (security_audit_rule_match(
695 								n->osid,
696 								f->type,
697 								f->op,
698 								f->lsm_rule)) {
699 							++result;
700 							break;
701 						}
702 					}
703 				}
704 				/* Find ipc objects that match */
705 				if (!ctx || ctx->type != AUDIT_IPC)
706 					break;
707 				if (security_audit_rule_match(ctx->ipc.osid,
708 							      f->type, f->op,
709 							      f->lsm_rule))
710 					++result;
711 			}
712 			break;
713 		case AUDIT_ARG0:
714 		case AUDIT_ARG1:
715 		case AUDIT_ARG2:
716 		case AUDIT_ARG3:
717 			if (ctx)
718 				result = audit_comparator(ctx->argv[f->type-AUDIT_ARG0], f->op, f->val);
719 			break;
720 		case AUDIT_FILTERKEY:
721 			/* ignore this field for filtering */
722 			result = 1;
723 			break;
724 		case AUDIT_PERM:
725 			result = audit_match_perm(ctx, f->val);
726 			if (f->op == Audit_not_equal)
727 				result = !result;
728 			break;
729 		case AUDIT_FILETYPE:
730 			result = audit_match_filetype(ctx, f->val);
731 			if (f->op == Audit_not_equal)
732 				result = !result;
733 			break;
734 		case AUDIT_FIELD_COMPARE:
735 			result = audit_field_compare(tsk, cred, f, ctx, name);
736 			break;
737 		}
738 		if (!result)
739 			return 0;
740 	}
741 
742 	if (ctx) {
743 		if (rule->filterkey) {
744 			kfree(ctx->filterkey);
745 			ctx->filterkey = kstrdup(rule->filterkey, GFP_ATOMIC);
746 		}
747 		ctx->prio = rule->prio;
748 	}
749 	switch (rule->action) {
750 	case AUDIT_NEVER:
751 		*state = AUDIT_STATE_DISABLED;
752 		break;
753 	case AUDIT_ALWAYS:
754 		*state = AUDIT_STATE_RECORD;
755 		break;
756 	}
757 	return 1;
758 }
759 
760 /* At process creation time, we can determine if system-call auditing is
761  * completely disabled for this task.  Since we only have the task
762  * structure at this point, we can only check uid and gid.
763  */
764 static enum audit_state audit_filter_task(struct task_struct *tsk, char **key)
765 {
766 	struct audit_entry *e;
767 	enum audit_state   state;
768 
769 	rcu_read_lock();
770 	list_for_each_entry_rcu(e, &audit_filter_list[AUDIT_FILTER_TASK], list) {
771 		if (audit_filter_rules(tsk, &e->rule, NULL, NULL,
772 				       &state, true)) {
773 			if (state == AUDIT_STATE_RECORD)
774 				*key = kstrdup(e->rule.filterkey, GFP_ATOMIC);
775 			rcu_read_unlock();
776 			return state;
777 		}
778 	}
779 	rcu_read_unlock();
780 	return AUDIT_STATE_BUILD;
781 }
782 
783 static int audit_in_mask(const struct audit_krule *rule, unsigned long val)
784 {
785 	int word, bit;
786 
787 	if (val > 0xffffffff)
788 		return false;
789 
790 	word = AUDIT_WORD(val);
791 	if (word >= AUDIT_BITMASK_SIZE)
792 		return false;
793 
794 	bit = AUDIT_BIT(val);
795 
796 	return rule->mask[word] & bit;
797 }
798 
799 /**
800  * audit_filter_uring - apply filters to an io_uring operation
801  * @tsk: associated task
802  * @ctx: audit context
803  */
804 static void audit_filter_uring(struct task_struct *tsk,
805 			       struct audit_context *ctx)
806 {
807 	struct audit_entry *e;
808 	enum audit_state state;
809 
810 	if (auditd_test_task(tsk))
811 		return;
812 
813 	rcu_read_lock();
814 	list_for_each_entry_rcu(e, &audit_filter_list[AUDIT_FILTER_URING_EXIT],
815 				list) {
816 		if (audit_in_mask(&e->rule, ctx->uring_op) &&
817 		    audit_filter_rules(tsk, &e->rule, ctx, NULL, &state,
818 				       false)) {
819 			rcu_read_unlock();
820 			ctx->current_state = state;
821 			return;
822 		}
823 	}
824 	rcu_read_unlock();
825 }
826 
827 /* At syscall exit time, this filter is called if the audit_state is
828  * not low enough that auditing cannot take place, but is also not
829  * high enough that we already know we have to write an audit record
830  * (i.e., the state is AUDIT_STATE_BUILD).
831  */
832 static void audit_filter_syscall(struct task_struct *tsk,
833 				 struct audit_context *ctx)
834 {
835 	struct audit_entry *e;
836 	enum audit_state state;
837 
838 	if (auditd_test_task(tsk))
839 		return;
840 
841 	rcu_read_lock();
842 	list_for_each_entry_rcu(e, &audit_filter_list[AUDIT_FILTER_EXIT], list) {
843 		if (audit_in_mask(&e->rule, ctx->major) &&
844 		    audit_filter_rules(tsk, &e->rule, ctx, NULL,
845 				       &state, false)) {
846 			rcu_read_unlock();
847 			ctx->current_state = state;
848 			return;
849 		}
850 	}
851 	rcu_read_unlock();
852 	return;
853 }
854 
855 /*
856  * Given an audit_name check the inode hash table to see if they match.
857  * Called holding the rcu read lock to protect the use of audit_inode_hash
858  */
859 static int audit_filter_inode_name(struct task_struct *tsk,
860 				   struct audit_names *n,
861 				   struct audit_context *ctx) {
862 	int h = audit_hash_ino((u32)n->ino);
863 	struct list_head *list = &audit_inode_hash[h];
864 	struct audit_entry *e;
865 	enum audit_state state;
866 
867 	list_for_each_entry_rcu(e, list, list) {
868 		if (audit_in_mask(&e->rule, ctx->major) &&
869 		    audit_filter_rules(tsk, &e->rule, ctx, n, &state, false)) {
870 			ctx->current_state = state;
871 			return 1;
872 		}
873 	}
874 	return 0;
875 }
876 
877 /* At syscall exit time, this filter is called if any audit_names have been
878  * collected during syscall processing.  We only check rules in sublists at hash
879  * buckets applicable to the inode numbers in audit_names.
880  * Regarding audit_state, same rules apply as for audit_filter_syscall().
881  */
882 void audit_filter_inodes(struct task_struct *tsk, struct audit_context *ctx)
883 {
884 	struct audit_names *n;
885 
886 	if (auditd_test_task(tsk))
887 		return;
888 
889 	rcu_read_lock();
890 
891 	list_for_each_entry(n, &ctx->names_list, list) {
892 		if (audit_filter_inode_name(tsk, n, ctx))
893 			break;
894 	}
895 	rcu_read_unlock();
896 }
897 
898 static inline void audit_proctitle_free(struct audit_context *context)
899 {
900 	kfree(context->proctitle.value);
901 	context->proctitle.value = NULL;
902 	context->proctitle.len = 0;
903 }
904 
905 static inline void audit_free_module(struct audit_context *context)
906 {
907 	if (context->type == AUDIT_KERN_MODULE) {
908 		kfree(context->module.name);
909 		context->module.name = NULL;
910 	}
911 }
912 static inline void audit_free_names(struct audit_context *context)
913 {
914 	struct audit_names *n, *next;
915 
916 	list_for_each_entry_safe(n, next, &context->names_list, list) {
917 		list_del(&n->list);
918 		if (n->name)
919 			putname(n->name);
920 		if (n->should_free)
921 			kfree(n);
922 	}
923 	context->name_count = 0;
924 	path_put(&context->pwd);
925 	context->pwd.dentry = NULL;
926 	context->pwd.mnt = NULL;
927 }
928 
929 static inline void audit_free_aux(struct audit_context *context)
930 {
931 	struct audit_aux_data *aux;
932 
933 	while ((aux = context->aux)) {
934 		context->aux = aux->next;
935 		kfree(aux);
936 	}
937 	context->aux = NULL;
938 	while ((aux = context->aux_pids)) {
939 		context->aux_pids = aux->next;
940 		kfree(aux);
941 	}
942 	context->aux_pids = NULL;
943 }
944 
945 /**
946  * audit_reset_context - reset a audit_context structure
947  * @ctx: the audit_context to reset
948  *
949  * All fields in the audit_context will be reset to an initial state, all
950  * references held by fields will be dropped, and private memory will be
951  * released.  When this function returns the audit_context will be suitable
952  * for reuse, so long as the passed context is not NULL or a dummy context.
953  */
954 static void audit_reset_context(struct audit_context *ctx)
955 {
956 	if (!ctx)
957 		return;
958 
959 	/* if ctx is non-null, reset the "ctx->state" regardless */
960 	ctx->context = AUDIT_CTX_UNUSED;
961 	if (ctx->dummy)
962 		return;
963 
964 	/*
965 	 * NOTE: It shouldn't matter in what order we release the fields, so
966 	 *       release them in the order in which they appear in the struct;
967 	 *       this gives us some hope of quickly making sure we are
968 	 *       resetting the audit_context properly.
969 	 *
970 	 *       Other things worth mentioning:
971 	 *       - we don't reset "dummy"
972 	 *       - we don't reset "state", we do reset "current_state"
973 	 *       - we preserve "filterkey" if "state" is AUDIT_STATE_RECORD
974 	 *       - much of this is likely overkill, but play it safe for now
975 	 *       - we really need to work on improving the audit_context struct
976 	 */
977 
978 	ctx->current_state = ctx->state;
979 	ctx->serial = 0;
980 	ctx->major = 0;
981 	ctx->uring_op = 0;
982 	ctx->ctime = (struct timespec64){ .tv_sec = 0, .tv_nsec = 0 };
983 	memset(ctx->argv, 0, sizeof(ctx->argv));
984 	ctx->return_code = 0;
985 	ctx->prio = (ctx->state == AUDIT_STATE_RECORD ? ~0ULL : 0);
986 	ctx->return_valid = AUDITSC_INVALID;
987 	audit_free_names(ctx);
988 	if (ctx->state != AUDIT_STATE_RECORD) {
989 		kfree(ctx->filterkey);
990 		ctx->filterkey = NULL;
991 	}
992 	audit_free_aux(ctx);
993 	kfree(ctx->sockaddr);
994 	ctx->sockaddr = NULL;
995 	ctx->sockaddr_len = 0;
996 	ctx->pid = ctx->ppid = 0;
997 	ctx->uid = ctx->euid = ctx->suid = ctx->fsuid = KUIDT_INIT(0);
998 	ctx->gid = ctx->egid = ctx->sgid = ctx->fsgid = KGIDT_INIT(0);
999 	ctx->personality = 0;
1000 	ctx->arch = 0;
1001 	ctx->target_pid = 0;
1002 	ctx->target_auid = ctx->target_uid = KUIDT_INIT(0);
1003 	ctx->target_sessionid = 0;
1004 	ctx->target_sid = 0;
1005 	ctx->target_comm[0] = '\0';
1006 	unroll_tree_refs(ctx, NULL, 0);
1007 	WARN_ON(!list_empty(&ctx->killed_trees));
1008 	ctx->type = 0;
1009 	audit_free_module(ctx);
1010 	ctx->fds[0] = -1;
1011 	audit_proctitle_free(ctx);
1012 }
1013 
1014 static inline struct audit_context *audit_alloc_context(enum audit_state state)
1015 {
1016 	struct audit_context *context;
1017 
1018 	context = kzalloc(sizeof(*context), GFP_KERNEL);
1019 	if (!context)
1020 		return NULL;
1021 	context->context = AUDIT_CTX_UNUSED;
1022 	context->state = state;
1023 	context->prio = state == AUDIT_STATE_RECORD ? ~0ULL : 0;
1024 	INIT_LIST_HEAD(&context->killed_trees);
1025 	INIT_LIST_HEAD(&context->names_list);
1026 	context->fds[0] = -1;
1027 	context->return_valid = AUDITSC_INVALID;
1028 	return context;
1029 }
1030 
1031 /**
1032  * audit_alloc - allocate an audit context block for a task
1033  * @tsk: task
1034  *
1035  * Filter on the task information and allocate a per-task audit context
1036  * if necessary.  Doing so turns on system call auditing for the
1037  * specified task.  This is called from copy_process, so no lock is
1038  * needed.
1039  */
1040 int audit_alloc(struct task_struct *tsk)
1041 {
1042 	struct audit_context *context;
1043 	enum audit_state     state;
1044 	char *key = NULL;
1045 
1046 	if (likely(!audit_ever_enabled))
1047 		return 0;
1048 
1049 	state = audit_filter_task(tsk, &key);
1050 	if (state == AUDIT_STATE_DISABLED) {
1051 		clear_task_syscall_work(tsk, SYSCALL_AUDIT);
1052 		return 0;
1053 	}
1054 
1055 	if (!(context = audit_alloc_context(state))) {
1056 		kfree(key);
1057 		audit_log_lost("out of memory in audit_alloc");
1058 		return -ENOMEM;
1059 	}
1060 	context->filterkey = key;
1061 
1062 	audit_set_context(tsk, context);
1063 	set_task_syscall_work(tsk, SYSCALL_AUDIT);
1064 	return 0;
1065 }
1066 
1067 /**
1068  * audit_alloc_kernel - allocate an audit_context for a kernel task
1069  * @tsk: the kernel task
1070  *
1071  * Similar to the audit_alloc() function, but intended for kernel private
1072  * threads.  Returns zero on success, negative values on failure.
1073  */
1074 int audit_alloc_kernel(struct task_struct *tsk)
1075 {
1076 	/*
1077 	 * At the moment we are just going to call into audit_alloc() to
1078 	 * simplify the code, but there two things to keep in mind with this
1079 	 * approach:
1080 	 *
1081 	 * 1. Filtering internal kernel tasks is a bit laughable in almost all
1082 	 * cases, but there is at least one case where there is a benefit:
1083 	 * the '-a task,never' case allows the admin to effectively disable
1084 	 * task auditing at runtime.
1085 	 *
1086 	 * 2. The {set,clear}_task_syscall_work() ops likely have zero effect
1087 	 * on these internal kernel tasks, but they probably don't hurt either.
1088 	 */
1089 	return audit_alloc(tsk);
1090 }
1091 
1092 static inline void audit_free_context(struct audit_context *context)
1093 {
1094 	/* resetting is extra work, but it is likely just noise */
1095 	audit_reset_context(context);
1096 	free_tree_refs(context);
1097 	kfree(context->filterkey);
1098 	kfree(context);
1099 }
1100 
1101 static int audit_log_pid_context(struct audit_context *context, pid_t pid,
1102 				 kuid_t auid, kuid_t uid, unsigned int sessionid,
1103 				 u32 sid, char *comm)
1104 {
1105 	struct audit_buffer *ab;
1106 	char *ctx = NULL;
1107 	u32 len;
1108 	int rc = 0;
1109 
1110 	ab = audit_log_start(context, GFP_KERNEL, AUDIT_OBJ_PID);
1111 	if (!ab)
1112 		return rc;
1113 
1114 	audit_log_format(ab, "opid=%d oauid=%d ouid=%d oses=%d", pid,
1115 			 from_kuid(&init_user_ns, auid),
1116 			 from_kuid(&init_user_ns, uid), sessionid);
1117 	if (sid) {
1118 		if (security_secid_to_secctx(sid, &ctx, &len)) {
1119 			audit_log_format(ab, " obj=(none)");
1120 			rc = 1;
1121 		} else {
1122 			audit_log_format(ab, " obj=%s", ctx);
1123 			security_release_secctx(ctx, len);
1124 		}
1125 	}
1126 	audit_log_format(ab, " ocomm=");
1127 	audit_log_untrustedstring(ab, comm);
1128 	audit_log_end(ab);
1129 
1130 	return rc;
1131 }
1132 
1133 static void audit_log_execve_info(struct audit_context *context,
1134 				  struct audit_buffer **ab)
1135 {
1136 	long len_max;
1137 	long len_rem;
1138 	long len_full;
1139 	long len_buf;
1140 	long len_abuf = 0;
1141 	long len_tmp;
1142 	bool require_data;
1143 	bool encode;
1144 	unsigned int iter;
1145 	unsigned int arg;
1146 	char *buf_head;
1147 	char *buf;
1148 	const char __user *p = (const char __user *)current->mm->arg_start;
1149 
1150 	/* NOTE: this buffer needs to be large enough to hold all the non-arg
1151 	 *       data we put in the audit record for this argument (see the
1152 	 *       code below) ... at this point in time 96 is plenty */
1153 	char abuf[96];
1154 
1155 	/* NOTE: we set MAX_EXECVE_AUDIT_LEN to a rather arbitrary limit, the
1156 	 *       current value of 7500 is not as important as the fact that it
1157 	 *       is less than 8k, a setting of 7500 gives us plenty of wiggle
1158 	 *       room if we go over a little bit in the logging below */
1159 	WARN_ON_ONCE(MAX_EXECVE_AUDIT_LEN > 7500);
1160 	len_max = MAX_EXECVE_AUDIT_LEN;
1161 
1162 	/* scratch buffer to hold the userspace args */
1163 	buf_head = kmalloc(MAX_EXECVE_AUDIT_LEN + 1, GFP_KERNEL);
1164 	if (!buf_head) {
1165 		audit_panic("out of memory for argv string");
1166 		return;
1167 	}
1168 	buf = buf_head;
1169 
1170 	audit_log_format(*ab, "argc=%d", context->execve.argc);
1171 
1172 	len_rem = len_max;
1173 	len_buf = 0;
1174 	len_full = 0;
1175 	require_data = true;
1176 	encode = false;
1177 	iter = 0;
1178 	arg = 0;
1179 	do {
1180 		/* NOTE: we don't ever want to trust this value for anything
1181 		 *       serious, but the audit record format insists we
1182 		 *       provide an argument length for really long arguments,
1183 		 *       e.g. > MAX_EXECVE_AUDIT_LEN, so we have no choice but
1184 		 *       to use strncpy_from_user() to obtain this value for
1185 		 *       recording in the log, although we don't use it
1186 		 *       anywhere here to avoid a double-fetch problem */
1187 		if (len_full == 0)
1188 			len_full = strnlen_user(p, MAX_ARG_STRLEN) - 1;
1189 
1190 		/* read more data from userspace */
1191 		if (require_data) {
1192 			/* can we make more room in the buffer? */
1193 			if (buf != buf_head) {
1194 				memmove(buf_head, buf, len_buf);
1195 				buf = buf_head;
1196 			}
1197 
1198 			/* fetch as much as we can of the argument */
1199 			len_tmp = strncpy_from_user(&buf_head[len_buf], p,
1200 						    len_max - len_buf);
1201 			if (len_tmp == -EFAULT) {
1202 				/* unable to copy from userspace */
1203 				send_sig(SIGKILL, current, 0);
1204 				goto out;
1205 			} else if (len_tmp == (len_max - len_buf)) {
1206 				/* buffer is not large enough */
1207 				require_data = true;
1208 				/* NOTE: if we are going to span multiple
1209 				 *       buffers force the encoding so we stand
1210 				 *       a chance at a sane len_full value and
1211 				 *       consistent record encoding */
1212 				encode = true;
1213 				len_full = len_full * 2;
1214 				p += len_tmp;
1215 			} else {
1216 				require_data = false;
1217 				if (!encode)
1218 					encode = audit_string_contains_control(
1219 								buf, len_tmp);
1220 				/* try to use a trusted value for len_full */
1221 				if (len_full < len_max)
1222 					len_full = (encode ?
1223 						    len_tmp * 2 : len_tmp);
1224 				p += len_tmp + 1;
1225 			}
1226 			len_buf += len_tmp;
1227 			buf_head[len_buf] = '\0';
1228 
1229 			/* length of the buffer in the audit record? */
1230 			len_abuf = (encode ? len_buf * 2 : len_buf + 2);
1231 		}
1232 
1233 		/* write as much as we can to the audit log */
1234 		if (len_buf >= 0) {
1235 			/* NOTE: some magic numbers here - basically if we
1236 			 *       can't fit a reasonable amount of data into the
1237 			 *       existing audit buffer, flush it and start with
1238 			 *       a new buffer */
1239 			if ((sizeof(abuf) + 8) > len_rem) {
1240 				len_rem = len_max;
1241 				audit_log_end(*ab);
1242 				*ab = audit_log_start(context,
1243 						      GFP_KERNEL, AUDIT_EXECVE);
1244 				if (!*ab)
1245 					goto out;
1246 			}
1247 
1248 			/* create the non-arg portion of the arg record */
1249 			len_tmp = 0;
1250 			if (require_data || (iter > 0) ||
1251 			    ((len_abuf + sizeof(abuf)) > len_rem)) {
1252 				if (iter == 0) {
1253 					len_tmp += snprintf(&abuf[len_tmp],
1254 							sizeof(abuf) - len_tmp,
1255 							" a%d_len=%lu",
1256 							arg, len_full);
1257 				}
1258 				len_tmp += snprintf(&abuf[len_tmp],
1259 						    sizeof(abuf) - len_tmp,
1260 						    " a%d[%d]=", arg, iter++);
1261 			} else
1262 				len_tmp += snprintf(&abuf[len_tmp],
1263 						    sizeof(abuf) - len_tmp,
1264 						    " a%d=", arg);
1265 			WARN_ON(len_tmp >= sizeof(abuf));
1266 			abuf[sizeof(abuf) - 1] = '\0';
1267 
1268 			/* log the arg in the audit record */
1269 			audit_log_format(*ab, "%s", abuf);
1270 			len_rem -= len_tmp;
1271 			len_tmp = len_buf;
1272 			if (encode) {
1273 				if (len_abuf > len_rem)
1274 					len_tmp = len_rem / 2; /* encoding */
1275 				audit_log_n_hex(*ab, buf, len_tmp);
1276 				len_rem -= len_tmp * 2;
1277 				len_abuf -= len_tmp * 2;
1278 			} else {
1279 				if (len_abuf > len_rem)
1280 					len_tmp = len_rem - 2; /* quotes */
1281 				audit_log_n_string(*ab, buf, len_tmp);
1282 				len_rem -= len_tmp + 2;
1283 				/* don't subtract the "2" because we still need
1284 				 * to add quotes to the remaining string */
1285 				len_abuf -= len_tmp;
1286 			}
1287 			len_buf -= len_tmp;
1288 			buf += len_tmp;
1289 		}
1290 
1291 		/* ready to move to the next argument? */
1292 		if ((len_buf == 0) && !require_data) {
1293 			arg++;
1294 			iter = 0;
1295 			len_full = 0;
1296 			require_data = true;
1297 			encode = false;
1298 		}
1299 	} while (arg < context->execve.argc);
1300 
1301 	/* NOTE: the caller handles the final audit_log_end() call */
1302 
1303 out:
1304 	kfree(buf_head);
1305 }
1306 
1307 static void audit_log_cap(struct audit_buffer *ab, char *prefix,
1308 			  kernel_cap_t *cap)
1309 {
1310 	int i;
1311 
1312 	if (cap_isclear(*cap)) {
1313 		audit_log_format(ab, " %s=0", prefix);
1314 		return;
1315 	}
1316 	audit_log_format(ab, " %s=", prefix);
1317 	CAP_FOR_EACH_U32(i)
1318 		audit_log_format(ab, "%08x", cap->cap[CAP_LAST_U32 - i]);
1319 }
1320 
1321 static void audit_log_fcaps(struct audit_buffer *ab, struct audit_names *name)
1322 {
1323 	if (name->fcap_ver == -1) {
1324 		audit_log_format(ab, " cap_fe=? cap_fver=? cap_fp=? cap_fi=?");
1325 		return;
1326 	}
1327 	audit_log_cap(ab, "cap_fp", &name->fcap.permitted);
1328 	audit_log_cap(ab, "cap_fi", &name->fcap.inheritable);
1329 	audit_log_format(ab, " cap_fe=%d cap_fver=%x cap_frootid=%d",
1330 			 name->fcap.fE, name->fcap_ver,
1331 			 from_kuid(&init_user_ns, name->fcap.rootid));
1332 }
1333 
1334 static void show_special(struct audit_context *context, int *call_panic)
1335 {
1336 	struct audit_buffer *ab;
1337 	int i;
1338 
1339 	ab = audit_log_start(context, GFP_KERNEL, context->type);
1340 	if (!ab)
1341 		return;
1342 
1343 	switch (context->type) {
1344 	case AUDIT_SOCKETCALL: {
1345 		int nargs = context->socketcall.nargs;
1346 
1347 		audit_log_format(ab, "nargs=%d", nargs);
1348 		for (i = 0; i < nargs; i++)
1349 			audit_log_format(ab, " a%d=%lx", i,
1350 				context->socketcall.args[i]);
1351 		break; }
1352 	case AUDIT_IPC: {
1353 		u32 osid = context->ipc.osid;
1354 
1355 		audit_log_format(ab, "ouid=%u ogid=%u mode=%#ho",
1356 				 from_kuid(&init_user_ns, context->ipc.uid),
1357 				 from_kgid(&init_user_ns, context->ipc.gid),
1358 				 context->ipc.mode);
1359 		if (osid) {
1360 			char *ctx = NULL;
1361 			u32 len;
1362 
1363 			if (security_secid_to_secctx(osid, &ctx, &len)) {
1364 				audit_log_format(ab, " osid=%u", osid);
1365 				*call_panic = 1;
1366 			} else {
1367 				audit_log_format(ab, " obj=%s", ctx);
1368 				security_release_secctx(ctx, len);
1369 			}
1370 		}
1371 		if (context->ipc.has_perm) {
1372 			audit_log_end(ab);
1373 			ab = audit_log_start(context, GFP_KERNEL,
1374 					     AUDIT_IPC_SET_PERM);
1375 			if (unlikely(!ab))
1376 				return;
1377 			audit_log_format(ab,
1378 				"qbytes=%lx ouid=%u ogid=%u mode=%#ho",
1379 				context->ipc.qbytes,
1380 				context->ipc.perm_uid,
1381 				context->ipc.perm_gid,
1382 				context->ipc.perm_mode);
1383 		}
1384 		break; }
1385 	case AUDIT_MQ_OPEN:
1386 		audit_log_format(ab,
1387 			"oflag=0x%x mode=%#ho mq_flags=0x%lx mq_maxmsg=%ld "
1388 			"mq_msgsize=%ld mq_curmsgs=%ld",
1389 			context->mq_open.oflag, context->mq_open.mode,
1390 			context->mq_open.attr.mq_flags,
1391 			context->mq_open.attr.mq_maxmsg,
1392 			context->mq_open.attr.mq_msgsize,
1393 			context->mq_open.attr.mq_curmsgs);
1394 		break;
1395 	case AUDIT_MQ_SENDRECV:
1396 		audit_log_format(ab,
1397 			"mqdes=%d msg_len=%zd msg_prio=%u "
1398 			"abs_timeout_sec=%lld abs_timeout_nsec=%ld",
1399 			context->mq_sendrecv.mqdes,
1400 			context->mq_sendrecv.msg_len,
1401 			context->mq_sendrecv.msg_prio,
1402 			(long long) context->mq_sendrecv.abs_timeout.tv_sec,
1403 			context->mq_sendrecv.abs_timeout.tv_nsec);
1404 		break;
1405 	case AUDIT_MQ_NOTIFY:
1406 		audit_log_format(ab, "mqdes=%d sigev_signo=%d",
1407 				context->mq_notify.mqdes,
1408 				context->mq_notify.sigev_signo);
1409 		break;
1410 	case AUDIT_MQ_GETSETATTR: {
1411 		struct mq_attr *attr = &context->mq_getsetattr.mqstat;
1412 
1413 		audit_log_format(ab,
1414 			"mqdes=%d mq_flags=0x%lx mq_maxmsg=%ld mq_msgsize=%ld "
1415 			"mq_curmsgs=%ld ",
1416 			context->mq_getsetattr.mqdes,
1417 			attr->mq_flags, attr->mq_maxmsg,
1418 			attr->mq_msgsize, attr->mq_curmsgs);
1419 		break; }
1420 	case AUDIT_CAPSET:
1421 		audit_log_format(ab, "pid=%d", context->capset.pid);
1422 		audit_log_cap(ab, "cap_pi", &context->capset.cap.inheritable);
1423 		audit_log_cap(ab, "cap_pp", &context->capset.cap.permitted);
1424 		audit_log_cap(ab, "cap_pe", &context->capset.cap.effective);
1425 		audit_log_cap(ab, "cap_pa", &context->capset.cap.ambient);
1426 		break;
1427 	case AUDIT_MMAP:
1428 		audit_log_format(ab, "fd=%d flags=0x%x", context->mmap.fd,
1429 				 context->mmap.flags);
1430 		break;
1431 	case AUDIT_OPENAT2:
1432 		audit_log_format(ab, "oflag=0%llo mode=0%llo resolve=0x%llx",
1433 				 context->openat2.flags,
1434 				 context->openat2.mode,
1435 				 context->openat2.resolve);
1436 		break;
1437 	case AUDIT_EXECVE:
1438 		audit_log_execve_info(context, &ab);
1439 		break;
1440 	case AUDIT_KERN_MODULE:
1441 		audit_log_format(ab, "name=");
1442 		if (context->module.name) {
1443 			audit_log_untrustedstring(ab, context->module.name);
1444 		} else
1445 			audit_log_format(ab, "(null)");
1446 
1447 		break;
1448 	}
1449 	audit_log_end(ab);
1450 }
1451 
1452 static inline int audit_proctitle_rtrim(char *proctitle, int len)
1453 {
1454 	char *end = proctitle + len - 1;
1455 
1456 	while (end > proctitle && !isprint(*end))
1457 		end--;
1458 
1459 	/* catch the case where proctitle is only 1 non-print character */
1460 	len = end - proctitle + 1;
1461 	len -= isprint(proctitle[len-1]) == 0;
1462 	return len;
1463 }
1464 
1465 /*
1466  * audit_log_name - produce AUDIT_PATH record from struct audit_names
1467  * @context: audit_context for the task
1468  * @n: audit_names structure with reportable details
1469  * @path: optional path to report instead of audit_names->name
1470  * @record_num: record number to report when handling a list of names
1471  * @call_panic: optional pointer to int that will be updated if secid fails
1472  */
1473 static void audit_log_name(struct audit_context *context, struct audit_names *n,
1474 		    const struct path *path, int record_num, int *call_panic)
1475 {
1476 	struct audit_buffer *ab;
1477 
1478 	ab = audit_log_start(context, GFP_KERNEL, AUDIT_PATH);
1479 	if (!ab)
1480 		return;
1481 
1482 	audit_log_format(ab, "item=%d", record_num);
1483 
1484 	if (path)
1485 		audit_log_d_path(ab, " name=", path);
1486 	else if (n->name) {
1487 		switch (n->name_len) {
1488 		case AUDIT_NAME_FULL:
1489 			/* log the full path */
1490 			audit_log_format(ab, " name=");
1491 			audit_log_untrustedstring(ab, n->name->name);
1492 			break;
1493 		case 0:
1494 			/* name was specified as a relative path and the
1495 			 * directory component is the cwd
1496 			 */
1497 			if (context->pwd.dentry && context->pwd.mnt)
1498 				audit_log_d_path(ab, " name=", &context->pwd);
1499 			else
1500 				audit_log_format(ab, " name=(null)");
1501 			break;
1502 		default:
1503 			/* log the name's directory component */
1504 			audit_log_format(ab, " name=");
1505 			audit_log_n_untrustedstring(ab, n->name->name,
1506 						    n->name_len);
1507 		}
1508 	} else
1509 		audit_log_format(ab, " name=(null)");
1510 
1511 	if (n->ino != AUDIT_INO_UNSET)
1512 		audit_log_format(ab, " inode=%lu dev=%02x:%02x mode=%#ho ouid=%u ogid=%u rdev=%02x:%02x",
1513 				 n->ino,
1514 				 MAJOR(n->dev),
1515 				 MINOR(n->dev),
1516 				 n->mode,
1517 				 from_kuid(&init_user_ns, n->uid),
1518 				 from_kgid(&init_user_ns, n->gid),
1519 				 MAJOR(n->rdev),
1520 				 MINOR(n->rdev));
1521 	if (n->osid != 0) {
1522 		char *ctx = NULL;
1523 		u32 len;
1524 
1525 		if (security_secid_to_secctx(
1526 			n->osid, &ctx, &len)) {
1527 			audit_log_format(ab, " osid=%u", n->osid);
1528 			if (call_panic)
1529 				*call_panic = 2;
1530 		} else {
1531 			audit_log_format(ab, " obj=%s", ctx);
1532 			security_release_secctx(ctx, len);
1533 		}
1534 	}
1535 
1536 	/* log the audit_names record type */
1537 	switch (n->type) {
1538 	case AUDIT_TYPE_NORMAL:
1539 		audit_log_format(ab, " nametype=NORMAL");
1540 		break;
1541 	case AUDIT_TYPE_PARENT:
1542 		audit_log_format(ab, " nametype=PARENT");
1543 		break;
1544 	case AUDIT_TYPE_CHILD_DELETE:
1545 		audit_log_format(ab, " nametype=DELETE");
1546 		break;
1547 	case AUDIT_TYPE_CHILD_CREATE:
1548 		audit_log_format(ab, " nametype=CREATE");
1549 		break;
1550 	default:
1551 		audit_log_format(ab, " nametype=UNKNOWN");
1552 		break;
1553 	}
1554 
1555 	audit_log_fcaps(ab, n);
1556 	audit_log_end(ab);
1557 }
1558 
1559 static void audit_log_proctitle(void)
1560 {
1561 	int res;
1562 	char *buf;
1563 	char *msg = "(null)";
1564 	int len = strlen(msg);
1565 	struct audit_context *context = audit_context();
1566 	struct audit_buffer *ab;
1567 
1568 	ab = audit_log_start(context, GFP_KERNEL, AUDIT_PROCTITLE);
1569 	if (!ab)
1570 		return;	/* audit_panic or being filtered */
1571 
1572 	audit_log_format(ab, "proctitle=");
1573 
1574 	/* Not  cached */
1575 	if (!context->proctitle.value) {
1576 		buf = kmalloc(MAX_PROCTITLE_AUDIT_LEN, GFP_KERNEL);
1577 		if (!buf)
1578 			goto out;
1579 		/* Historically called this from procfs naming */
1580 		res = get_cmdline(current, buf, MAX_PROCTITLE_AUDIT_LEN);
1581 		if (res == 0) {
1582 			kfree(buf);
1583 			goto out;
1584 		}
1585 		res = audit_proctitle_rtrim(buf, res);
1586 		if (res == 0) {
1587 			kfree(buf);
1588 			goto out;
1589 		}
1590 		context->proctitle.value = buf;
1591 		context->proctitle.len = res;
1592 	}
1593 	msg = context->proctitle.value;
1594 	len = context->proctitle.len;
1595 out:
1596 	audit_log_n_untrustedstring(ab, msg, len);
1597 	audit_log_end(ab);
1598 }
1599 
1600 /**
1601  * audit_log_uring - generate a AUDIT_URINGOP record
1602  * @ctx: the audit context
1603  */
1604 static void audit_log_uring(struct audit_context *ctx)
1605 {
1606 	struct audit_buffer *ab;
1607 	const struct cred *cred;
1608 
1609 	ab = audit_log_start(ctx, GFP_ATOMIC, AUDIT_URINGOP);
1610 	if (!ab)
1611 		return;
1612 	cred = current_cred();
1613 	audit_log_format(ab, "uring_op=%d", ctx->uring_op);
1614 	if (ctx->return_valid != AUDITSC_INVALID)
1615 		audit_log_format(ab, " success=%s exit=%ld",
1616 				 (ctx->return_valid == AUDITSC_SUCCESS ?
1617 				  "yes" : "no"),
1618 				 ctx->return_code);
1619 	audit_log_format(ab,
1620 			 " items=%d"
1621 			 " ppid=%d pid=%d uid=%u gid=%u euid=%u suid=%u"
1622 			 " fsuid=%u egid=%u sgid=%u fsgid=%u",
1623 			 ctx->name_count,
1624 			 task_ppid_nr(current), task_tgid_nr(current),
1625 			 from_kuid(&init_user_ns, cred->uid),
1626 			 from_kgid(&init_user_ns, cred->gid),
1627 			 from_kuid(&init_user_ns, cred->euid),
1628 			 from_kuid(&init_user_ns, cred->suid),
1629 			 from_kuid(&init_user_ns, cred->fsuid),
1630 			 from_kgid(&init_user_ns, cred->egid),
1631 			 from_kgid(&init_user_ns, cred->sgid),
1632 			 from_kgid(&init_user_ns, cred->fsgid));
1633 	audit_log_task_context(ab);
1634 	audit_log_key(ab, ctx->filterkey);
1635 	audit_log_end(ab);
1636 }
1637 
1638 static void audit_log_exit(void)
1639 {
1640 	int i, call_panic = 0;
1641 	struct audit_context *context = audit_context();
1642 	struct audit_buffer *ab;
1643 	struct audit_aux_data *aux;
1644 	struct audit_names *n;
1645 
1646 	context->personality = current->personality;
1647 
1648 	switch (context->context) {
1649 	case AUDIT_CTX_SYSCALL:
1650 		ab = audit_log_start(context, GFP_KERNEL, AUDIT_SYSCALL);
1651 		if (!ab)
1652 			return;
1653 		audit_log_format(ab, "arch=%x syscall=%d",
1654 				 context->arch, context->major);
1655 		if (context->personality != PER_LINUX)
1656 			audit_log_format(ab, " per=%lx", context->personality);
1657 		if (context->return_valid != AUDITSC_INVALID)
1658 			audit_log_format(ab, " success=%s exit=%ld",
1659 					 (context->return_valid == AUDITSC_SUCCESS ?
1660 					  "yes" : "no"),
1661 					 context->return_code);
1662 		audit_log_format(ab,
1663 				 " a0=%lx a1=%lx a2=%lx a3=%lx items=%d",
1664 				 context->argv[0],
1665 				 context->argv[1],
1666 				 context->argv[2],
1667 				 context->argv[3],
1668 				 context->name_count);
1669 		audit_log_task_info(ab);
1670 		audit_log_key(ab, context->filterkey);
1671 		audit_log_end(ab);
1672 		break;
1673 	case AUDIT_CTX_URING:
1674 		audit_log_uring(context);
1675 		break;
1676 	default:
1677 		BUG();
1678 		break;
1679 	}
1680 
1681 	for (aux = context->aux; aux; aux = aux->next) {
1682 
1683 		ab = audit_log_start(context, GFP_KERNEL, aux->type);
1684 		if (!ab)
1685 			continue; /* audit_panic has been called */
1686 
1687 		switch (aux->type) {
1688 
1689 		case AUDIT_BPRM_FCAPS: {
1690 			struct audit_aux_data_bprm_fcaps *axs = (void *)aux;
1691 
1692 			audit_log_format(ab, "fver=%x", axs->fcap_ver);
1693 			audit_log_cap(ab, "fp", &axs->fcap.permitted);
1694 			audit_log_cap(ab, "fi", &axs->fcap.inheritable);
1695 			audit_log_format(ab, " fe=%d", axs->fcap.fE);
1696 			audit_log_cap(ab, "old_pp", &axs->old_pcap.permitted);
1697 			audit_log_cap(ab, "old_pi", &axs->old_pcap.inheritable);
1698 			audit_log_cap(ab, "old_pe", &axs->old_pcap.effective);
1699 			audit_log_cap(ab, "old_pa", &axs->old_pcap.ambient);
1700 			audit_log_cap(ab, "pp", &axs->new_pcap.permitted);
1701 			audit_log_cap(ab, "pi", &axs->new_pcap.inheritable);
1702 			audit_log_cap(ab, "pe", &axs->new_pcap.effective);
1703 			audit_log_cap(ab, "pa", &axs->new_pcap.ambient);
1704 			audit_log_format(ab, " frootid=%d",
1705 					 from_kuid(&init_user_ns,
1706 						   axs->fcap.rootid));
1707 			break; }
1708 
1709 		}
1710 		audit_log_end(ab);
1711 	}
1712 
1713 	if (context->type)
1714 		show_special(context, &call_panic);
1715 
1716 	if (context->fds[0] >= 0) {
1717 		ab = audit_log_start(context, GFP_KERNEL, AUDIT_FD_PAIR);
1718 		if (ab) {
1719 			audit_log_format(ab, "fd0=%d fd1=%d",
1720 					context->fds[0], context->fds[1]);
1721 			audit_log_end(ab);
1722 		}
1723 	}
1724 
1725 	if (context->sockaddr_len) {
1726 		ab = audit_log_start(context, GFP_KERNEL, AUDIT_SOCKADDR);
1727 		if (ab) {
1728 			audit_log_format(ab, "saddr=");
1729 			audit_log_n_hex(ab, (void *)context->sockaddr,
1730 					context->sockaddr_len);
1731 			audit_log_end(ab);
1732 		}
1733 	}
1734 
1735 	for (aux = context->aux_pids; aux; aux = aux->next) {
1736 		struct audit_aux_data_pids *axs = (void *)aux;
1737 
1738 		for (i = 0; i < axs->pid_count; i++)
1739 			if (audit_log_pid_context(context, axs->target_pid[i],
1740 						  axs->target_auid[i],
1741 						  axs->target_uid[i],
1742 						  axs->target_sessionid[i],
1743 						  axs->target_sid[i],
1744 						  axs->target_comm[i]))
1745 				call_panic = 1;
1746 	}
1747 
1748 	if (context->target_pid &&
1749 	    audit_log_pid_context(context, context->target_pid,
1750 				  context->target_auid, context->target_uid,
1751 				  context->target_sessionid,
1752 				  context->target_sid, context->target_comm))
1753 			call_panic = 1;
1754 
1755 	if (context->pwd.dentry && context->pwd.mnt) {
1756 		ab = audit_log_start(context, GFP_KERNEL, AUDIT_CWD);
1757 		if (ab) {
1758 			audit_log_d_path(ab, "cwd=", &context->pwd);
1759 			audit_log_end(ab);
1760 		}
1761 	}
1762 
1763 	i = 0;
1764 	list_for_each_entry(n, &context->names_list, list) {
1765 		if (n->hidden)
1766 			continue;
1767 		audit_log_name(context, n, NULL, i++, &call_panic);
1768 	}
1769 
1770 	if (context->context == AUDIT_CTX_SYSCALL)
1771 		audit_log_proctitle();
1772 
1773 	/* Send end of event record to help user space know we are finished */
1774 	ab = audit_log_start(context, GFP_KERNEL, AUDIT_EOE);
1775 	if (ab)
1776 		audit_log_end(ab);
1777 	if (call_panic)
1778 		audit_panic("error in audit_log_exit()");
1779 }
1780 
1781 /**
1782  * __audit_free - free a per-task audit context
1783  * @tsk: task whose audit context block to free
1784  *
1785  * Called from copy_process, do_exit, and the io_uring code
1786  */
1787 void __audit_free(struct task_struct *tsk)
1788 {
1789 	struct audit_context *context = tsk->audit_context;
1790 
1791 	if (!context)
1792 		return;
1793 
1794 	/* this may generate CONFIG_CHANGE records */
1795 	if (!list_empty(&context->killed_trees))
1796 		audit_kill_trees(context);
1797 
1798 	/* We are called either by do_exit() or the fork() error handling code;
1799 	 * in the former case tsk == current and in the latter tsk is a
1800 	 * random task_struct that doesn't doesn't have any meaningful data we
1801 	 * need to log via audit_log_exit().
1802 	 */
1803 	if (tsk == current && !context->dummy) {
1804 		context->return_valid = AUDITSC_INVALID;
1805 		context->return_code = 0;
1806 		if (context->context == AUDIT_CTX_SYSCALL) {
1807 			audit_filter_syscall(tsk, context);
1808 			audit_filter_inodes(tsk, context);
1809 			if (context->current_state == AUDIT_STATE_RECORD)
1810 				audit_log_exit();
1811 		} else if (context->context == AUDIT_CTX_URING) {
1812 			/* TODO: verify this case is real and valid */
1813 			audit_filter_uring(tsk, context);
1814 			audit_filter_inodes(tsk, context);
1815 			if (context->current_state == AUDIT_STATE_RECORD)
1816 				audit_log_uring(context);
1817 		}
1818 	}
1819 
1820 	audit_set_context(tsk, NULL);
1821 	audit_free_context(context);
1822 }
1823 
1824 /**
1825  * audit_return_fixup - fixup the return codes in the audit_context
1826  * @ctx: the audit_context
1827  * @success: true/false value to indicate if the operation succeeded or not
1828  * @code: operation return code
1829  *
1830  * We need to fixup the return code in the audit logs if the actual return
1831  * codes are later going to be fixed by the arch specific signal handlers.
1832  */
1833 static void audit_return_fixup(struct audit_context *ctx,
1834 			       int success, long code)
1835 {
1836 	/*
1837 	 * This is actually a test for:
1838 	 * (rc == ERESTARTSYS ) || (rc == ERESTARTNOINTR) ||
1839 	 * (rc == ERESTARTNOHAND) || (rc == ERESTART_RESTARTBLOCK)
1840 	 *
1841 	 * but is faster than a bunch of ||
1842 	 */
1843 	if (unlikely(code <= -ERESTARTSYS) &&
1844 	    (code >= -ERESTART_RESTARTBLOCK) &&
1845 	    (code != -ENOIOCTLCMD))
1846 		ctx->return_code = -EINTR;
1847 	else
1848 		ctx->return_code  = code;
1849 	ctx->return_valid = (success ? AUDITSC_SUCCESS : AUDITSC_FAILURE);
1850 }
1851 
1852 /**
1853  * __audit_uring_entry - prepare the kernel task's audit context for io_uring
1854  * @op: the io_uring opcode
1855  *
1856  * This is similar to audit_syscall_entry() but is intended for use by io_uring
1857  * operations.  This function should only ever be called from
1858  * audit_uring_entry() as we rely on the audit context checking present in that
1859  * function.
1860  */
1861 void __audit_uring_entry(u8 op)
1862 {
1863 	struct audit_context *ctx = audit_context();
1864 
1865 	if (ctx->state == AUDIT_STATE_DISABLED)
1866 		return;
1867 
1868 	/*
1869 	 * NOTE: It's possible that we can be called from the process' context
1870 	 *       before it returns to userspace, and before audit_syscall_exit()
1871 	 *       is called.  In this case there is not much to do, just record
1872 	 *       the io_uring details and return.
1873 	 */
1874 	ctx->uring_op = op;
1875 	if (ctx->context == AUDIT_CTX_SYSCALL)
1876 		return;
1877 
1878 	ctx->dummy = !audit_n_rules;
1879 	if (!ctx->dummy && ctx->state == AUDIT_STATE_BUILD)
1880 		ctx->prio = 0;
1881 
1882 	ctx->context = AUDIT_CTX_URING;
1883 	ctx->current_state = ctx->state;
1884 	ktime_get_coarse_real_ts64(&ctx->ctime);
1885 }
1886 
1887 /**
1888  * __audit_uring_exit - wrap up the kernel task's audit context after io_uring
1889  * @success: true/false value to indicate if the operation succeeded or not
1890  * @code: operation return code
1891  *
1892  * This is similar to audit_syscall_exit() but is intended for use by io_uring
1893  * operations.  This function should only ever be called from
1894  * audit_uring_exit() as we rely on the audit context checking present in that
1895  * function.
1896  */
1897 void __audit_uring_exit(int success, long code)
1898 {
1899 	struct audit_context *ctx = audit_context();
1900 
1901 	if (ctx->context == AUDIT_CTX_SYSCALL) {
1902 		/*
1903 		 * NOTE: See the note in __audit_uring_entry() about the case
1904 		 *       where we may be called from process context before we
1905 		 *       return to userspace via audit_syscall_exit().  In this
1906 		 *       case we simply emit a URINGOP record and bail, the
1907 		 *       normal syscall exit handling will take care of
1908 		 *       everything else.
1909 		 *       It is also worth mentioning that when we are called,
1910 		 *       the current process creds may differ from the creds
1911 		 *       used during the normal syscall processing; keep that
1912 		 *       in mind if/when we move the record generation code.
1913 		 */
1914 
1915 		/*
1916 		 * We need to filter on the syscall info here to decide if we
1917 		 * should emit a URINGOP record.  I know it seems odd but this
1918 		 * solves the problem where users have a filter to block *all*
1919 		 * syscall records in the "exit" filter; we want to preserve
1920 		 * the behavior here.
1921 		 */
1922 		audit_filter_syscall(current, ctx);
1923 		if (ctx->current_state != AUDIT_STATE_RECORD)
1924 			audit_filter_uring(current, ctx);
1925 		audit_filter_inodes(current, ctx);
1926 		if (ctx->current_state != AUDIT_STATE_RECORD)
1927 			return;
1928 
1929 		audit_log_uring(ctx);
1930 		return;
1931 	}
1932 
1933 	/* this may generate CONFIG_CHANGE records */
1934 	if (!list_empty(&ctx->killed_trees))
1935 		audit_kill_trees(ctx);
1936 
1937 	/* run through both filters to ensure we set the filterkey properly */
1938 	audit_filter_uring(current, ctx);
1939 	audit_filter_inodes(current, ctx);
1940 	if (ctx->current_state != AUDIT_STATE_RECORD)
1941 		goto out;
1942 	audit_return_fixup(ctx, success, code);
1943 	audit_log_exit();
1944 
1945 out:
1946 	audit_reset_context(ctx);
1947 }
1948 
1949 /**
1950  * __audit_syscall_entry - fill in an audit record at syscall entry
1951  * @major: major syscall type (function)
1952  * @a1: additional syscall register 1
1953  * @a2: additional syscall register 2
1954  * @a3: additional syscall register 3
1955  * @a4: additional syscall register 4
1956  *
1957  * Fill in audit context at syscall entry.  This only happens if the
1958  * audit context was created when the task was created and the state or
1959  * filters demand the audit context be built.  If the state from the
1960  * per-task filter or from the per-syscall filter is AUDIT_STATE_RECORD,
1961  * then the record will be written at syscall exit time (otherwise, it
1962  * will only be written if another part of the kernel requests that it
1963  * be written).
1964  */
1965 void __audit_syscall_entry(int major, unsigned long a1, unsigned long a2,
1966 			   unsigned long a3, unsigned long a4)
1967 {
1968 	struct audit_context *context = audit_context();
1969 	enum audit_state     state;
1970 
1971 	if (!audit_enabled || !context)
1972 		return;
1973 
1974 	WARN_ON(context->context != AUDIT_CTX_UNUSED);
1975 	WARN_ON(context->name_count);
1976 	if (context->context != AUDIT_CTX_UNUSED || context->name_count) {
1977 		audit_panic("unrecoverable error in audit_syscall_entry()");
1978 		return;
1979 	}
1980 
1981 	state = context->state;
1982 	if (state == AUDIT_STATE_DISABLED)
1983 		return;
1984 
1985 	context->dummy = !audit_n_rules;
1986 	if (!context->dummy && state == AUDIT_STATE_BUILD) {
1987 		context->prio = 0;
1988 		if (auditd_test_task(current))
1989 			return;
1990 	}
1991 
1992 	context->arch	    = syscall_get_arch(current);
1993 	context->major      = major;
1994 	context->argv[0]    = a1;
1995 	context->argv[1]    = a2;
1996 	context->argv[2]    = a3;
1997 	context->argv[3]    = a4;
1998 	context->context = AUDIT_CTX_SYSCALL;
1999 	context->current_state  = state;
2000 	ktime_get_coarse_real_ts64(&context->ctime);
2001 }
2002 
2003 /**
2004  * __audit_syscall_exit - deallocate audit context after a system call
2005  * @success: success value of the syscall
2006  * @return_code: return value of the syscall
2007  *
2008  * Tear down after system call.  If the audit context has been marked as
2009  * auditable (either because of the AUDIT_STATE_RECORD state from
2010  * filtering, or because some other part of the kernel wrote an audit
2011  * message), then write out the syscall information.  In call cases,
2012  * free the names stored from getname().
2013  */
2014 void __audit_syscall_exit(int success, long return_code)
2015 {
2016 	struct audit_context *context = audit_context();
2017 
2018 	if (!context || context->dummy ||
2019 	    context->context != AUDIT_CTX_SYSCALL)
2020 		goto out;
2021 
2022 	/* this may generate CONFIG_CHANGE records */
2023 	if (!list_empty(&context->killed_trees))
2024 		audit_kill_trees(context);
2025 
2026 	/* run through both filters to ensure we set the filterkey properly */
2027 	audit_filter_syscall(current, context);
2028 	audit_filter_inodes(current, context);
2029 	if (context->current_state < AUDIT_STATE_RECORD)
2030 		goto out;
2031 
2032 	audit_return_fixup(context, success, return_code);
2033 	audit_log_exit();
2034 
2035 out:
2036 	audit_reset_context(context);
2037 }
2038 
2039 static inline void handle_one(const struct inode *inode)
2040 {
2041 	struct audit_context *context;
2042 	struct audit_tree_refs *p;
2043 	struct audit_chunk *chunk;
2044 	int count;
2045 
2046 	if (likely(!inode->i_fsnotify_marks))
2047 		return;
2048 	context = audit_context();
2049 	p = context->trees;
2050 	count = context->tree_count;
2051 	rcu_read_lock();
2052 	chunk = audit_tree_lookup(inode);
2053 	rcu_read_unlock();
2054 	if (!chunk)
2055 		return;
2056 	if (likely(put_tree_ref(context, chunk)))
2057 		return;
2058 	if (unlikely(!grow_tree_refs(context))) {
2059 		pr_warn("out of memory, audit has lost a tree reference\n");
2060 		audit_set_auditable(context);
2061 		audit_put_chunk(chunk);
2062 		unroll_tree_refs(context, p, count);
2063 		return;
2064 	}
2065 	put_tree_ref(context, chunk);
2066 }
2067 
2068 static void handle_path(const struct dentry *dentry)
2069 {
2070 	struct audit_context *context;
2071 	struct audit_tree_refs *p;
2072 	const struct dentry *d, *parent;
2073 	struct audit_chunk *drop;
2074 	unsigned long seq;
2075 	int count;
2076 
2077 	context = audit_context();
2078 	p = context->trees;
2079 	count = context->tree_count;
2080 retry:
2081 	drop = NULL;
2082 	d = dentry;
2083 	rcu_read_lock();
2084 	seq = read_seqbegin(&rename_lock);
2085 	for(;;) {
2086 		struct inode *inode = d_backing_inode(d);
2087 
2088 		if (inode && unlikely(inode->i_fsnotify_marks)) {
2089 			struct audit_chunk *chunk;
2090 
2091 			chunk = audit_tree_lookup(inode);
2092 			if (chunk) {
2093 				if (unlikely(!put_tree_ref(context, chunk))) {
2094 					drop = chunk;
2095 					break;
2096 				}
2097 			}
2098 		}
2099 		parent = d->d_parent;
2100 		if (parent == d)
2101 			break;
2102 		d = parent;
2103 	}
2104 	if (unlikely(read_seqretry(&rename_lock, seq) || drop)) {  /* in this order */
2105 		rcu_read_unlock();
2106 		if (!drop) {
2107 			/* just a race with rename */
2108 			unroll_tree_refs(context, p, count);
2109 			goto retry;
2110 		}
2111 		audit_put_chunk(drop);
2112 		if (grow_tree_refs(context)) {
2113 			/* OK, got more space */
2114 			unroll_tree_refs(context, p, count);
2115 			goto retry;
2116 		}
2117 		/* too bad */
2118 		pr_warn("out of memory, audit has lost a tree reference\n");
2119 		unroll_tree_refs(context, p, count);
2120 		audit_set_auditable(context);
2121 		return;
2122 	}
2123 	rcu_read_unlock();
2124 }
2125 
2126 static struct audit_names *audit_alloc_name(struct audit_context *context,
2127 						unsigned char type)
2128 {
2129 	struct audit_names *aname;
2130 
2131 	if (context->name_count < AUDIT_NAMES) {
2132 		aname = &context->preallocated_names[context->name_count];
2133 		memset(aname, 0, sizeof(*aname));
2134 	} else {
2135 		aname = kzalloc(sizeof(*aname), GFP_NOFS);
2136 		if (!aname)
2137 			return NULL;
2138 		aname->should_free = true;
2139 	}
2140 
2141 	aname->ino = AUDIT_INO_UNSET;
2142 	aname->type = type;
2143 	list_add_tail(&aname->list, &context->names_list);
2144 
2145 	context->name_count++;
2146 	if (!context->pwd.dentry)
2147 		get_fs_pwd(current->fs, &context->pwd);
2148 	return aname;
2149 }
2150 
2151 /**
2152  * __audit_reusename - fill out filename with info from existing entry
2153  * @uptr: userland ptr to pathname
2154  *
2155  * Search the audit_names list for the current audit context. If there is an
2156  * existing entry with a matching "uptr" then return the filename
2157  * associated with that audit_name. If not, return NULL.
2158  */
2159 struct filename *
2160 __audit_reusename(const __user char *uptr)
2161 {
2162 	struct audit_context *context = audit_context();
2163 	struct audit_names *n;
2164 
2165 	list_for_each_entry(n, &context->names_list, list) {
2166 		if (!n->name)
2167 			continue;
2168 		if (n->name->uptr == uptr) {
2169 			n->name->refcnt++;
2170 			return n->name;
2171 		}
2172 	}
2173 	return NULL;
2174 }
2175 
2176 /**
2177  * __audit_getname - add a name to the list
2178  * @name: name to add
2179  *
2180  * Add a name to the list of audit names for this context.
2181  * Called from fs/namei.c:getname().
2182  */
2183 void __audit_getname(struct filename *name)
2184 {
2185 	struct audit_context *context = audit_context();
2186 	struct audit_names *n;
2187 
2188 	if (context->context == AUDIT_CTX_UNUSED)
2189 		return;
2190 
2191 	n = audit_alloc_name(context, AUDIT_TYPE_UNKNOWN);
2192 	if (!n)
2193 		return;
2194 
2195 	n->name = name;
2196 	n->name_len = AUDIT_NAME_FULL;
2197 	name->aname = n;
2198 	name->refcnt++;
2199 }
2200 
2201 static inline int audit_copy_fcaps(struct audit_names *name,
2202 				   const struct dentry *dentry)
2203 {
2204 	struct cpu_vfs_cap_data caps;
2205 	int rc;
2206 
2207 	if (!dentry)
2208 		return 0;
2209 
2210 	rc = get_vfs_caps_from_disk(&init_user_ns, dentry, &caps);
2211 	if (rc)
2212 		return rc;
2213 
2214 	name->fcap.permitted = caps.permitted;
2215 	name->fcap.inheritable = caps.inheritable;
2216 	name->fcap.fE = !!(caps.magic_etc & VFS_CAP_FLAGS_EFFECTIVE);
2217 	name->fcap.rootid = caps.rootid;
2218 	name->fcap_ver = (caps.magic_etc & VFS_CAP_REVISION_MASK) >>
2219 				VFS_CAP_REVISION_SHIFT;
2220 
2221 	return 0;
2222 }
2223 
2224 /* Copy inode data into an audit_names. */
2225 static void audit_copy_inode(struct audit_names *name,
2226 			     const struct dentry *dentry,
2227 			     struct inode *inode, unsigned int flags)
2228 {
2229 	name->ino   = inode->i_ino;
2230 	name->dev   = inode->i_sb->s_dev;
2231 	name->mode  = inode->i_mode;
2232 	name->uid   = inode->i_uid;
2233 	name->gid   = inode->i_gid;
2234 	name->rdev  = inode->i_rdev;
2235 	security_inode_getsecid(inode, &name->osid);
2236 	if (flags & AUDIT_INODE_NOEVAL) {
2237 		name->fcap_ver = -1;
2238 		return;
2239 	}
2240 	audit_copy_fcaps(name, dentry);
2241 }
2242 
2243 /**
2244  * __audit_inode - store the inode and device from a lookup
2245  * @name: name being audited
2246  * @dentry: dentry being audited
2247  * @flags: attributes for this particular entry
2248  */
2249 void __audit_inode(struct filename *name, const struct dentry *dentry,
2250 		   unsigned int flags)
2251 {
2252 	struct audit_context *context = audit_context();
2253 	struct inode *inode = d_backing_inode(dentry);
2254 	struct audit_names *n;
2255 	bool parent = flags & AUDIT_INODE_PARENT;
2256 	struct audit_entry *e;
2257 	struct list_head *list = &audit_filter_list[AUDIT_FILTER_FS];
2258 	int i;
2259 
2260 	if (context->context == AUDIT_CTX_UNUSED)
2261 		return;
2262 
2263 	rcu_read_lock();
2264 	list_for_each_entry_rcu(e, list, list) {
2265 		for (i = 0; i < e->rule.field_count; i++) {
2266 			struct audit_field *f = &e->rule.fields[i];
2267 
2268 			if (f->type == AUDIT_FSTYPE
2269 			    && audit_comparator(inode->i_sb->s_magic,
2270 						f->op, f->val)
2271 			    && e->rule.action == AUDIT_NEVER) {
2272 				rcu_read_unlock();
2273 				return;
2274 			}
2275 		}
2276 	}
2277 	rcu_read_unlock();
2278 
2279 	if (!name)
2280 		goto out_alloc;
2281 
2282 	/*
2283 	 * If we have a pointer to an audit_names entry already, then we can
2284 	 * just use it directly if the type is correct.
2285 	 */
2286 	n = name->aname;
2287 	if (n) {
2288 		if (parent) {
2289 			if (n->type == AUDIT_TYPE_PARENT ||
2290 			    n->type == AUDIT_TYPE_UNKNOWN)
2291 				goto out;
2292 		} else {
2293 			if (n->type != AUDIT_TYPE_PARENT)
2294 				goto out;
2295 		}
2296 	}
2297 
2298 	list_for_each_entry_reverse(n, &context->names_list, list) {
2299 		if (n->ino) {
2300 			/* valid inode number, use that for the comparison */
2301 			if (n->ino != inode->i_ino ||
2302 			    n->dev != inode->i_sb->s_dev)
2303 				continue;
2304 		} else if (n->name) {
2305 			/* inode number has not been set, check the name */
2306 			if (strcmp(n->name->name, name->name))
2307 				continue;
2308 		} else
2309 			/* no inode and no name (?!) ... this is odd ... */
2310 			continue;
2311 
2312 		/* match the correct record type */
2313 		if (parent) {
2314 			if (n->type == AUDIT_TYPE_PARENT ||
2315 			    n->type == AUDIT_TYPE_UNKNOWN)
2316 				goto out;
2317 		} else {
2318 			if (n->type != AUDIT_TYPE_PARENT)
2319 				goto out;
2320 		}
2321 	}
2322 
2323 out_alloc:
2324 	/* unable to find an entry with both a matching name and type */
2325 	n = audit_alloc_name(context, AUDIT_TYPE_UNKNOWN);
2326 	if (!n)
2327 		return;
2328 	if (name) {
2329 		n->name = name;
2330 		name->refcnt++;
2331 	}
2332 
2333 out:
2334 	if (parent) {
2335 		n->name_len = n->name ? parent_len(n->name->name) : AUDIT_NAME_FULL;
2336 		n->type = AUDIT_TYPE_PARENT;
2337 		if (flags & AUDIT_INODE_HIDDEN)
2338 			n->hidden = true;
2339 	} else {
2340 		n->name_len = AUDIT_NAME_FULL;
2341 		n->type = AUDIT_TYPE_NORMAL;
2342 	}
2343 	handle_path(dentry);
2344 	audit_copy_inode(n, dentry, inode, flags & AUDIT_INODE_NOEVAL);
2345 }
2346 
2347 void __audit_file(const struct file *file)
2348 {
2349 	__audit_inode(NULL, file->f_path.dentry, 0);
2350 }
2351 
2352 /**
2353  * __audit_inode_child - collect inode info for created/removed objects
2354  * @parent: inode of dentry parent
2355  * @dentry: dentry being audited
2356  * @type:   AUDIT_TYPE_* value that we're looking for
2357  *
2358  * For syscalls that create or remove filesystem objects, audit_inode
2359  * can only collect information for the filesystem object's parent.
2360  * This call updates the audit context with the child's information.
2361  * Syscalls that create a new filesystem object must be hooked after
2362  * the object is created.  Syscalls that remove a filesystem object
2363  * must be hooked prior, in order to capture the target inode during
2364  * unsuccessful attempts.
2365  */
2366 void __audit_inode_child(struct inode *parent,
2367 			 const struct dentry *dentry,
2368 			 const unsigned char type)
2369 {
2370 	struct audit_context *context = audit_context();
2371 	struct inode *inode = d_backing_inode(dentry);
2372 	const struct qstr *dname = &dentry->d_name;
2373 	struct audit_names *n, *found_parent = NULL, *found_child = NULL;
2374 	struct audit_entry *e;
2375 	struct list_head *list = &audit_filter_list[AUDIT_FILTER_FS];
2376 	int i;
2377 
2378 	if (context->context == AUDIT_CTX_UNUSED)
2379 		return;
2380 
2381 	rcu_read_lock();
2382 	list_for_each_entry_rcu(e, list, list) {
2383 		for (i = 0; i < e->rule.field_count; i++) {
2384 			struct audit_field *f = &e->rule.fields[i];
2385 
2386 			if (f->type == AUDIT_FSTYPE
2387 			    && audit_comparator(parent->i_sb->s_magic,
2388 						f->op, f->val)
2389 			    && e->rule.action == AUDIT_NEVER) {
2390 				rcu_read_unlock();
2391 				return;
2392 			}
2393 		}
2394 	}
2395 	rcu_read_unlock();
2396 
2397 	if (inode)
2398 		handle_one(inode);
2399 
2400 	/* look for a parent entry first */
2401 	list_for_each_entry(n, &context->names_list, list) {
2402 		if (!n->name ||
2403 		    (n->type != AUDIT_TYPE_PARENT &&
2404 		     n->type != AUDIT_TYPE_UNKNOWN))
2405 			continue;
2406 
2407 		if (n->ino == parent->i_ino && n->dev == parent->i_sb->s_dev &&
2408 		    !audit_compare_dname_path(dname,
2409 					      n->name->name, n->name_len)) {
2410 			if (n->type == AUDIT_TYPE_UNKNOWN)
2411 				n->type = AUDIT_TYPE_PARENT;
2412 			found_parent = n;
2413 			break;
2414 		}
2415 	}
2416 
2417 	/* is there a matching child entry? */
2418 	list_for_each_entry(n, &context->names_list, list) {
2419 		/* can only match entries that have a name */
2420 		if (!n->name ||
2421 		    (n->type != type && n->type != AUDIT_TYPE_UNKNOWN))
2422 			continue;
2423 
2424 		if (!strcmp(dname->name, n->name->name) ||
2425 		    !audit_compare_dname_path(dname, n->name->name,
2426 						found_parent ?
2427 						found_parent->name_len :
2428 						AUDIT_NAME_FULL)) {
2429 			if (n->type == AUDIT_TYPE_UNKNOWN)
2430 				n->type = type;
2431 			found_child = n;
2432 			break;
2433 		}
2434 	}
2435 
2436 	if (!found_parent) {
2437 		/* create a new, "anonymous" parent record */
2438 		n = audit_alloc_name(context, AUDIT_TYPE_PARENT);
2439 		if (!n)
2440 			return;
2441 		audit_copy_inode(n, NULL, parent, 0);
2442 	}
2443 
2444 	if (!found_child) {
2445 		found_child = audit_alloc_name(context, type);
2446 		if (!found_child)
2447 			return;
2448 
2449 		/* Re-use the name belonging to the slot for a matching parent
2450 		 * directory. All names for this context are relinquished in
2451 		 * audit_free_names() */
2452 		if (found_parent) {
2453 			found_child->name = found_parent->name;
2454 			found_child->name_len = AUDIT_NAME_FULL;
2455 			found_child->name->refcnt++;
2456 		}
2457 	}
2458 
2459 	if (inode)
2460 		audit_copy_inode(found_child, dentry, inode, 0);
2461 	else
2462 		found_child->ino = AUDIT_INO_UNSET;
2463 }
2464 EXPORT_SYMBOL_GPL(__audit_inode_child);
2465 
2466 /**
2467  * auditsc_get_stamp - get local copies of audit_context values
2468  * @ctx: audit_context for the task
2469  * @t: timespec64 to store time recorded in the audit_context
2470  * @serial: serial value that is recorded in the audit_context
2471  *
2472  * Also sets the context as auditable.
2473  */
2474 int auditsc_get_stamp(struct audit_context *ctx,
2475 		       struct timespec64 *t, unsigned int *serial)
2476 {
2477 	if (ctx->context == AUDIT_CTX_UNUSED)
2478 		return 0;
2479 	if (!ctx->serial)
2480 		ctx->serial = audit_serial();
2481 	t->tv_sec  = ctx->ctime.tv_sec;
2482 	t->tv_nsec = ctx->ctime.tv_nsec;
2483 	*serial    = ctx->serial;
2484 	if (!ctx->prio) {
2485 		ctx->prio = 1;
2486 		ctx->current_state = AUDIT_STATE_RECORD;
2487 	}
2488 	return 1;
2489 }
2490 
2491 /**
2492  * __audit_mq_open - record audit data for a POSIX MQ open
2493  * @oflag: open flag
2494  * @mode: mode bits
2495  * @attr: queue attributes
2496  *
2497  */
2498 void __audit_mq_open(int oflag, umode_t mode, struct mq_attr *attr)
2499 {
2500 	struct audit_context *context = audit_context();
2501 
2502 	if (attr)
2503 		memcpy(&context->mq_open.attr, attr, sizeof(struct mq_attr));
2504 	else
2505 		memset(&context->mq_open.attr, 0, sizeof(struct mq_attr));
2506 
2507 	context->mq_open.oflag = oflag;
2508 	context->mq_open.mode = mode;
2509 
2510 	context->type = AUDIT_MQ_OPEN;
2511 }
2512 
2513 /**
2514  * __audit_mq_sendrecv - record audit data for a POSIX MQ timed send/receive
2515  * @mqdes: MQ descriptor
2516  * @msg_len: Message length
2517  * @msg_prio: Message priority
2518  * @abs_timeout: Message timeout in absolute time
2519  *
2520  */
2521 void __audit_mq_sendrecv(mqd_t mqdes, size_t msg_len, unsigned int msg_prio,
2522 			const struct timespec64 *abs_timeout)
2523 {
2524 	struct audit_context *context = audit_context();
2525 	struct timespec64 *p = &context->mq_sendrecv.abs_timeout;
2526 
2527 	if (abs_timeout)
2528 		memcpy(p, abs_timeout, sizeof(*p));
2529 	else
2530 		memset(p, 0, sizeof(*p));
2531 
2532 	context->mq_sendrecv.mqdes = mqdes;
2533 	context->mq_sendrecv.msg_len = msg_len;
2534 	context->mq_sendrecv.msg_prio = msg_prio;
2535 
2536 	context->type = AUDIT_MQ_SENDRECV;
2537 }
2538 
2539 /**
2540  * __audit_mq_notify - record audit data for a POSIX MQ notify
2541  * @mqdes: MQ descriptor
2542  * @notification: Notification event
2543  *
2544  */
2545 
2546 void __audit_mq_notify(mqd_t mqdes, const struct sigevent *notification)
2547 {
2548 	struct audit_context *context = audit_context();
2549 
2550 	if (notification)
2551 		context->mq_notify.sigev_signo = notification->sigev_signo;
2552 	else
2553 		context->mq_notify.sigev_signo = 0;
2554 
2555 	context->mq_notify.mqdes = mqdes;
2556 	context->type = AUDIT_MQ_NOTIFY;
2557 }
2558 
2559 /**
2560  * __audit_mq_getsetattr - record audit data for a POSIX MQ get/set attribute
2561  * @mqdes: MQ descriptor
2562  * @mqstat: MQ flags
2563  *
2564  */
2565 void __audit_mq_getsetattr(mqd_t mqdes, struct mq_attr *mqstat)
2566 {
2567 	struct audit_context *context = audit_context();
2568 
2569 	context->mq_getsetattr.mqdes = mqdes;
2570 	context->mq_getsetattr.mqstat = *mqstat;
2571 	context->type = AUDIT_MQ_GETSETATTR;
2572 }
2573 
2574 /**
2575  * __audit_ipc_obj - record audit data for ipc object
2576  * @ipcp: ipc permissions
2577  *
2578  */
2579 void __audit_ipc_obj(struct kern_ipc_perm *ipcp)
2580 {
2581 	struct audit_context *context = audit_context();
2582 
2583 	context->ipc.uid = ipcp->uid;
2584 	context->ipc.gid = ipcp->gid;
2585 	context->ipc.mode = ipcp->mode;
2586 	context->ipc.has_perm = 0;
2587 	security_ipc_getsecid(ipcp, &context->ipc.osid);
2588 	context->type = AUDIT_IPC;
2589 }
2590 
2591 /**
2592  * __audit_ipc_set_perm - record audit data for new ipc permissions
2593  * @qbytes: msgq bytes
2594  * @uid: msgq user id
2595  * @gid: msgq group id
2596  * @mode: msgq mode (permissions)
2597  *
2598  * Called only after audit_ipc_obj().
2599  */
2600 void __audit_ipc_set_perm(unsigned long qbytes, uid_t uid, gid_t gid, umode_t mode)
2601 {
2602 	struct audit_context *context = audit_context();
2603 
2604 	context->ipc.qbytes = qbytes;
2605 	context->ipc.perm_uid = uid;
2606 	context->ipc.perm_gid = gid;
2607 	context->ipc.perm_mode = mode;
2608 	context->ipc.has_perm = 1;
2609 }
2610 
2611 void __audit_bprm(struct linux_binprm *bprm)
2612 {
2613 	struct audit_context *context = audit_context();
2614 
2615 	context->type = AUDIT_EXECVE;
2616 	context->execve.argc = bprm->argc;
2617 }
2618 
2619 
2620 /**
2621  * __audit_socketcall - record audit data for sys_socketcall
2622  * @nargs: number of args, which should not be more than AUDITSC_ARGS.
2623  * @args: args array
2624  *
2625  */
2626 int __audit_socketcall(int nargs, unsigned long *args)
2627 {
2628 	struct audit_context *context = audit_context();
2629 
2630 	if (nargs <= 0 || nargs > AUDITSC_ARGS || !args)
2631 		return -EINVAL;
2632 	context->type = AUDIT_SOCKETCALL;
2633 	context->socketcall.nargs = nargs;
2634 	memcpy(context->socketcall.args, args, nargs * sizeof(unsigned long));
2635 	return 0;
2636 }
2637 
2638 /**
2639  * __audit_fd_pair - record audit data for pipe and socketpair
2640  * @fd1: the first file descriptor
2641  * @fd2: the second file descriptor
2642  *
2643  */
2644 void __audit_fd_pair(int fd1, int fd2)
2645 {
2646 	struct audit_context *context = audit_context();
2647 
2648 	context->fds[0] = fd1;
2649 	context->fds[1] = fd2;
2650 }
2651 
2652 /**
2653  * __audit_sockaddr - record audit data for sys_bind, sys_connect, sys_sendto
2654  * @len: data length in user space
2655  * @a: data address in kernel space
2656  *
2657  * Returns 0 for success or NULL context or < 0 on error.
2658  */
2659 int __audit_sockaddr(int len, void *a)
2660 {
2661 	struct audit_context *context = audit_context();
2662 
2663 	if (!context->sockaddr) {
2664 		void *p = kmalloc(sizeof(struct sockaddr_storage), GFP_KERNEL);
2665 
2666 		if (!p)
2667 			return -ENOMEM;
2668 		context->sockaddr = p;
2669 	}
2670 
2671 	context->sockaddr_len = len;
2672 	memcpy(context->sockaddr, a, len);
2673 	return 0;
2674 }
2675 
2676 void __audit_ptrace(struct task_struct *t)
2677 {
2678 	struct audit_context *context = audit_context();
2679 
2680 	context->target_pid = task_tgid_nr(t);
2681 	context->target_auid = audit_get_loginuid(t);
2682 	context->target_uid = task_uid(t);
2683 	context->target_sessionid = audit_get_sessionid(t);
2684 	security_task_getsecid_obj(t, &context->target_sid);
2685 	memcpy(context->target_comm, t->comm, TASK_COMM_LEN);
2686 }
2687 
2688 /**
2689  * audit_signal_info_syscall - record signal info for syscalls
2690  * @t: task being signaled
2691  *
2692  * If the audit subsystem is being terminated, record the task (pid)
2693  * and uid that is doing that.
2694  */
2695 int audit_signal_info_syscall(struct task_struct *t)
2696 {
2697 	struct audit_aux_data_pids *axp;
2698 	struct audit_context *ctx = audit_context();
2699 	kuid_t t_uid = task_uid(t);
2700 
2701 	if (!audit_signals || audit_dummy_context())
2702 		return 0;
2703 
2704 	/* optimize the common case by putting first signal recipient directly
2705 	 * in audit_context */
2706 	if (!ctx->target_pid) {
2707 		ctx->target_pid = task_tgid_nr(t);
2708 		ctx->target_auid = audit_get_loginuid(t);
2709 		ctx->target_uid = t_uid;
2710 		ctx->target_sessionid = audit_get_sessionid(t);
2711 		security_task_getsecid_obj(t, &ctx->target_sid);
2712 		memcpy(ctx->target_comm, t->comm, TASK_COMM_LEN);
2713 		return 0;
2714 	}
2715 
2716 	axp = (void *)ctx->aux_pids;
2717 	if (!axp || axp->pid_count == AUDIT_AUX_PIDS) {
2718 		axp = kzalloc(sizeof(*axp), GFP_ATOMIC);
2719 		if (!axp)
2720 			return -ENOMEM;
2721 
2722 		axp->d.type = AUDIT_OBJ_PID;
2723 		axp->d.next = ctx->aux_pids;
2724 		ctx->aux_pids = (void *)axp;
2725 	}
2726 	BUG_ON(axp->pid_count >= AUDIT_AUX_PIDS);
2727 
2728 	axp->target_pid[axp->pid_count] = task_tgid_nr(t);
2729 	axp->target_auid[axp->pid_count] = audit_get_loginuid(t);
2730 	axp->target_uid[axp->pid_count] = t_uid;
2731 	axp->target_sessionid[axp->pid_count] = audit_get_sessionid(t);
2732 	security_task_getsecid_obj(t, &axp->target_sid[axp->pid_count]);
2733 	memcpy(axp->target_comm[axp->pid_count], t->comm, TASK_COMM_LEN);
2734 	axp->pid_count++;
2735 
2736 	return 0;
2737 }
2738 
2739 /**
2740  * __audit_log_bprm_fcaps - store information about a loading bprm and relevant fcaps
2741  * @bprm: pointer to the bprm being processed
2742  * @new: the proposed new credentials
2743  * @old: the old credentials
2744  *
2745  * Simply check if the proc already has the caps given by the file and if not
2746  * store the priv escalation info for later auditing at the end of the syscall
2747  *
2748  * -Eric
2749  */
2750 int __audit_log_bprm_fcaps(struct linux_binprm *bprm,
2751 			   const struct cred *new, const struct cred *old)
2752 {
2753 	struct audit_aux_data_bprm_fcaps *ax;
2754 	struct audit_context *context = audit_context();
2755 	struct cpu_vfs_cap_data vcaps;
2756 
2757 	ax = kmalloc(sizeof(*ax), GFP_KERNEL);
2758 	if (!ax)
2759 		return -ENOMEM;
2760 
2761 	ax->d.type = AUDIT_BPRM_FCAPS;
2762 	ax->d.next = context->aux;
2763 	context->aux = (void *)ax;
2764 
2765 	get_vfs_caps_from_disk(&init_user_ns,
2766 			       bprm->file->f_path.dentry, &vcaps);
2767 
2768 	ax->fcap.permitted = vcaps.permitted;
2769 	ax->fcap.inheritable = vcaps.inheritable;
2770 	ax->fcap.fE = !!(vcaps.magic_etc & VFS_CAP_FLAGS_EFFECTIVE);
2771 	ax->fcap.rootid = vcaps.rootid;
2772 	ax->fcap_ver = (vcaps.magic_etc & VFS_CAP_REVISION_MASK) >> VFS_CAP_REVISION_SHIFT;
2773 
2774 	ax->old_pcap.permitted   = old->cap_permitted;
2775 	ax->old_pcap.inheritable = old->cap_inheritable;
2776 	ax->old_pcap.effective   = old->cap_effective;
2777 	ax->old_pcap.ambient     = old->cap_ambient;
2778 
2779 	ax->new_pcap.permitted   = new->cap_permitted;
2780 	ax->new_pcap.inheritable = new->cap_inheritable;
2781 	ax->new_pcap.effective   = new->cap_effective;
2782 	ax->new_pcap.ambient     = new->cap_ambient;
2783 	return 0;
2784 }
2785 
2786 /**
2787  * __audit_log_capset - store information about the arguments to the capset syscall
2788  * @new: the new credentials
2789  * @old: the old (current) credentials
2790  *
2791  * Record the arguments userspace sent to sys_capset for later printing by the
2792  * audit system if applicable
2793  */
2794 void __audit_log_capset(const struct cred *new, const struct cred *old)
2795 {
2796 	struct audit_context *context = audit_context();
2797 
2798 	context->capset.pid = task_tgid_nr(current);
2799 	context->capset.cap.effective   = new->cap_effective;
2800 	context->capset.cap.inheritable = new->cap_effective;
2801 	context->capset.cap.permitted   = new->cap_permitted;
2802 	context->capset.cap.ambient     = new->cap_ambient;
2803 	context->type = AUDIT_CAPSET;
2804 }
2805 
2806 void __audit_mmap_fd(int fd, int flags)
2807 {
2808 	struct audit_context *context = audit_context();
2809 
2810 	context->mmap.fd = fd;
2811 	context->mmap.flags = flags;
2812 	context->type = AUDIT_MMAP;
2813 }
2814 
2815 void __audit_openat2_how(struct open_how *how)
2816 {
2817 	struct audit_context *context = audit_context();
2818 
2819 	context->openat2.flags = how->flags;
2820 	context->openat2.mode = how->mode;
2821 	context->openat2.resolve = how->resolve;
2822 	context->type = AUDIT_OPENAT2;
2823 }
2824 
2825 void __audit_log_kern_module(char *name)
2826 {
2827 	struct audit_context *context = audit_context();
2828 
2829 	context->module.name = kstrdup(name, GFP_KERNEL);
2830 	if (!context->module.name)
2831 		audit_log_lost("out of memory in __audit_log_kern_module");
2832 	context->type = AUDIT_KERN_MODULE;
2833 }
2834 
2835 void __audit_fanotify(unsigned int response)
2836 {
2837 	audit_log(audit_context(), GFP_KERNEL,
2838 		AUDIT_FANOTIFY,	"resp=%u", response);
2839 }
2840 
2841 void __audit_tk_injoffset(struct timespec64 offset)
2842 {
2843 	audit_log(audit_context(), GFP_KERNEL, AUDIT_TIME_INJOFFSET,
2844 		  "sec=%lli nsec=%li",
2845 		  (long long)offset.tv_sec, offset.tv_nsec);
2846 }
2847 
2848 static void audit_log_ntp_val(const struct audit_ntp_data *ad,
2849 			      const char *op, enum audit_ntp_type type)
2850 {
2851 	const struct audit_ntp_val *val = &ad->vals[type];
2852 
2853 	if (val->newval == val->oldval)
2854 		return;
2855 
2856 	audit_log(audit_context(), GFP_KERNEL, AUDIT_TIME_ADJNTPVAL,
2857 		  "op=%s old=%lli new=%lli", op, val->oldval, val->newval);
2858 }
2859 
2860 void __audit_ntp_log(const struct audit_ntp_data *ad)
2861 {
2862 	audit_log_ntp_val(ad, "offset",	AUDIT_NTP_OFFSET);
2863 	audit_log_ntp_val(ad, "freq",	AUDIT_NTP_FREQ);
2864 	audit_log_ntp_val(ad, "status",	AUDIT_NTP_STATUS);
2865 	audit_log_ntp_val(ad, "tai",	AUDIT_NTP_TAI);
2866 	audit_log_ntp_val(ad, "tick",	AUDIT_NTP_TICK);
2867 	audit_log_ntp_val(ad, "adjust",	AUDIT_NTP_ADJUST);
2868 }
2869 
2870 void __audit_log_nfcfg(const char *name, u8 af, unsigned int nentries,
2871 		       enum audit_nfcfgop op, gfp_t gfp)
2872 {
2873 	struct audit_buffer *ab;
2874 	char comm[sizeof(current->comm)];
2875 
2876 	ab = audit_log_start(audit_context(), gfp, AUDIT_NETFILTER_CFG);
2877 	if (!ab)
2878 		return;
2879 	audit_log_format(ab, "table=%s family=%u entries=%u op=%s",
2880 			 name, af, nentries, audit_nfcfgs[op].s);
2881 
2882 	audit_log_format(ab, " pid=%u", task_pid_nr(current));
2883 	audit_log_task_context(ab); /* subj= */
2884 	audit_log_format(ab, " comm=");
2885 	audit_log_untrustedstring(ab, get_task_comm(comm, current));
2886 	audit_log_end(ab);
2887 }
2888 EXPORT_SYMBOL_GPL(__audit_log_nfcfg);
2889 
2890 static void audit_log_task(struct audit_buffer *ab)
2891 {
2892 	kuid_t auid, uid;
2893 	kgid_t gid;
2894 	unsigned int sessionid;
2895 	char comm[sizeof(current->comm)];
2896 
2897 	auid = audit_get_loginuid(current);
2898 	sessionid = audit_get_sessionid(current);
2899 	current_uid_gid(&uid, &gid);
2900 
2901 	audit_log_format(ab, "auid=%u uid=%u gid=%u ses=%u",
2902 			 from_kuid(&init_user_ns, auid),
2903 			 from_kuid(&init_user_ns, uid),
2904 			 from_kgid(&init_user_ns, gid),
2905 			 sessionid);
2906 	audit_log_task_context(ab);
2907 	audit_log_format(ab, " pid=%d comm=", task_tgid_nr(current));
2908 	audit_log_untrustedstring(ab, get_task_comm(comm, current));
2909 	audit_log_d_path_exe(ab, current->mm);
2910 }
2911 
2912 /**
2913  * audit_core_dumps - record information about processes that end abnormally
2914  * @signr: signal value
2915  *
2916  * If a process ends with a core dump, something fishy is going on and we
2917  * should record the event for investigation.
2918  */
2919 void audit_core_dumps(long signr)
2920 {
2921 	struct audit_buffer *ab;
2922 
2923 	if (!audit_enabled)
2924 		return;
2925 
2926 	if (signr == SIGQUIT)	/* don't care for those */
2927 		return;
2928 
2929 	ab = audit_log_start(audit_context(), GFP_KERNEL, AUDIT_ANOM_ABEND);
2930 	if (unlikely(!ab))
2931 		return;
2932 	audit_log_task(ab);
2933 	audit_log_format(ab, " sig=%ld res=1", signr);
2934 	audit_log_end(ab);
2935 }
2936 
2937 /**
2938  * audit_seccomp - record information about a seccomp action
2939  * @syscall: syscall number
2940  * @signr: signal value
2941  * @code: the seccomp action
2942  *
2943  * Record the information associated with a seccomp action. Event filtering for
2944  * seccomp actions that are not to be logged is done in seccomp_log().
2945  * Therefore, this function forces auditing independent of the audit_enabled
2946  * and dummy context state because seccomp actions should be logged even when
2947  * audit is not in use.
2948  */
2949 void audit_seccomp(unsigned long syscall, long signr, int code)
2950 {
2951 	struct audit_buffer *ab;
2952 
2953 	ab = audit_log_start(audit_context(), GFP_KERNEL, AUDIT_SECCOMP);
2954 	if (unlikely(!ab))
2955 		return;
2956 	audit_log_task(ab);
2957 	audit_log_format(ab, " sig=%ld arch=%x syscall=%ld compat=%d ip=0x%lx code=0x%x",
2958 			 signr, syscall_get_arch(current), syscall,
2959 			 in_compat_syscall(), KSTK_EIP(current), code);
2960 	audit_log_end(ab);
2961 }
2962 
2963 void audit_seccomp_actions_logged(const char *names, const char *old_names,
2964 				  int res)
2965 {
2966 	struct audit_buffer *ab;
2967 
2968 	if (!audit_enabled)
2969 		return;
2970 
2971 	ab = audit_log_start(audit_context(), GFP_KERNEL,
2972 			     AUDIT_CONFIG_CHANGE);
2973 	if (unlikely(!ab))
2974 		return;
2975 
2976 	audit_log_format(ab,
2977 			 "op=seccomp-logging actions=%s old-actions=%s res=%d",
2978 			 names, old_names, res);
2979 	audit_log_end(ab);
2980 }
2981 
2982 struct list_head *audit_killed_trees(void)
2983 {
2984 	struct audit_context *ctx = audit_context();
2985 	if (likely(!ctx || ctx->context == AUDIT_CTX_UNUSED))
2986 		return NULL;
2987 	return &ctx->killed_trees;
2988 }
2989