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