• Home
  • Line#
  • Scopes#
  • Navigate#
  • Raw
  • Download
1 /* auditsc.c -- System-call auditing support
2  * Handles all system-call specific auditing features.
3  *
4  * Copyright 2003-2004 Red Hat Inc., Durham, North Carolina.
5  * Copyright 2005 Hewlett-Packard Development Company, L.P.
6  * Copyright (C) 2005, 2006 IBM Corporation
7  * All Rights Reserved.
8  *
9  * This program is free software; you can redistribute it and/or modify
10  * it under the terms of the GNU General Public License as published by
11  * the Free Software Foundation; either version 2 of the License, or
12  * (at your option) any later version.
13  *
14  * This program is distributed in the hope that it will be useful,
15  * but WITHOUT ANY WARRANTY; without even the implied warranty of
16  * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
17  * GNU General Public License for more details.
18  *
19  * You should have received a copy of the GNU General Public License
20  * along with this program; if not, write to the Free Software
21  * Foundation, Inc., 59 Temple Place, Suite 330, Boston, MA  02111-1307  USA
22  *
23  * Written by Rickard E. (Rik) Faith <faith@redhat.com>
24  *
25  * Many of the ideas implemented here are from Stephen C. Tweedie,
26  * especially the idea of avoiding a copy by using getname.
27  *
28  * The method for actual interception of syscall entry and exit (not in
29  * this file -- see entry.S) is based on a GPL'd patch written by
30  * okir@suse.de and Copyright 2003 SuSE Linux AG.
31  *
32  * POSIX message queue support added by George Wilson <ltcgcw@us.ibm.com>,
33  * 2006.
34  *
35  * The support of additional filter rules compares (>, <, >=, <=) was
36  * added by Dustin Kirkland <dustin.kirkland@us.ibm.com>, 2005.
37  *
38  * Modified by Amy Griffis <amy.griffis@hp.com> to collect additional
39  * filesystem information.
40  *
41  * Subject and object context labeling support added by <danjones@us.ibm.com>
42  * and <dustin.kirkland@us.ibm.com> for LSPP certification compliance.
43  */
44 
45 #include <linux/init.h>
46 #include <asm/types.h>
47 #include <linux/atomic.h>
48 #include <linux/fs.h>
49 #include <linux/namei.h>
50 #include <linux/mm.h>
51 #include <linux/export.h>
52 #include <linux/slab.h>
53 #include <linux/mount.h>
54 #include <linux/socket.h>
55 #include <linux/mqueue.h>
56 #include <linux/audit.h>
57 #include <linux/personality.h>
58 #include <linux/time.h>
59 #include <linux/netlink.h>
60 #include <linux/compiler.h>
61 #include <asm/unistd.h>
62 #include <linux/security.h>
63 #include <linux/list.h>
64 #include <linux/tty.h>
65 #include <linux/binfmts.h>
66 #include <linux/highmem.h>
67 #include <linux/syscalls.h>
68 #include <linux/capability.h>
69 #include <linux/fs_struct.h>
70 #include <linux/compat.h>
71 #include <linux/uaccess.h>
72 
73 #include "audit.h"
74 
75 /* flags stating the success for a syscall */
76 #define AUDITSC_INVALID 0
77 #define AUDITSC_SUCCESS 1
78 #define AUDITSC_FAILURE 2
79 
80 /* no execve audit message should be longer than this (userspace limits),
81  * see the note near the top of audit_log_execve_info() about this value */
82 #define MAX_EXECVE_AUDIT_LEN 7500
83 
84 /* number of audit rules */
85 int audit_n_rules;
86 
87 /* determines whether we collect data for signals sent */
88 int audit_signals;
89 
90 struct audit_aux_data {
91 	struct audit_aux_data	*next;
92 	int			type;
93 };
94 
95 #define AUDIT_AUX_IPCPERM	0
96 
97 /* Number of target pids per aux struct. */
98 #define AUDIT_AUX_PIDS	16
99 
100 struct audit_aux_data_execve {
101 	struct audit_aux_data	d;
102 	int argc;
103 	int envc;
104 	struct mm_struct *mm;
105 };
106 
107 struct audit_aux_data_pids {
108 	struct audit_aux_data	d;
109 	pid_t			target_pid[AUDIT_AUX_PIDS];
110 	kuid_t			target_auid[AUDIT_AUX_PIDS];
111 	kuid_t			target_uid[AUDIT_AUX_PIDS];
112 	unsigned int		target_sessionid[AUDIT_AUX_PIDS];
113 	u32			target_sid[AUDIT_AUX_PIDS];
114 	char 			target_comm[AUDIT_AUX_PIDS][TASK_COMM_LEN];
115 	int			pid_count;
116 };
117 
118 struct audit_aux_data_bprm_fcaps {
119 	struct audit_aux_data	d;
120 	struct audit_cap_data	fcap;
121 	unsigned int		fcap_ver;
122 	struct audit_cap_data	old_pcap;
123 	struct audit_cap_data	new_pcap;
124 };
125 
126 struct audit_aux_data_capset {
127 	struct audit_aux_data	d;
128 	pid_t			pid;
129 	struct audit_cap_data	cap;
130 };
131 
132 struct audit_tree_refs {
133 	struct audit_tree_refs *next;
134 	struct audit_chunk *c[31];
135 };
136 
open_arg(int flags,int mask)137 static inline int open_arg(int flags, int mask)
138 {
139 	int n = ACC_MODE(flags);
140 	if (flags & (O_TRUNC | O_CREAT))
141 		n |= AUDIT_PERM_WRITE;
142 	return n & mask;
143 }
144 
audit_match_perm(struct audit_context * ctx,int mask)145 static int audit_match_perm(struct audit_context *ctx, int mask)
146 {
147 	unsigned n;
148 	if (unlikely(!ctx))
149 		return 0;
150 	n = ctx->major;
151 
152 	switch (audit_classify_syscall(ctx->arch, n)) {
153 	case 0:	/* native */
154 		if ((mask & AUDIT_PERM_WRITE) &&
155 		     audit_match_class(AUDIT_CLASS_WRITE, n))
156 			return 1;
157 		if ((mask & AUDIT_PERM_READ) &&
158 		     audit_match_class(AUDIT_CLASS_READ, n))
159 			return 1;
160 		if ((mask & AUDIT_PERM_ATTR) &&
161 		     audit_match_class(AUDIT_CLASS_CHATTR, n))
162 			return 1;
163 		return 0;
164 	case 1: /* 32bit on biarch */
165 		if ((mask & AUDIT_PERM_WRITE) &&
166 		     audit_match_class(AUDIT_CLASS_WRITE_32, n))
167 			return 1;
168 		if ((mask & AUDIT_PERM_READ) &&
169 		     audit_match_class(AUDIT_CLASS_READ_32, n))
170 			return 1;
171 		if ((mask & AUDIT_PERM_ATTR) &&
172 		     audit_match_class(AUDIT_CLASS_CHATTR_32, n))
173 			return 1;
174 		return 0;
175 	case 2: /* open */
176 		return mask & ACC_MODE(ctx->argv[1]);
177 	case 3: /* openat */
178 		return mask & ACC_MODE(ctx->argv[2]);
179 	case 4: /* socketcall */
180 		return ((mask & AUDIT_PERM_WRITE) && ctx->argv[0] == SYS_BIND);
181 	case 5: /* execve */
182 		return mask & AUDIT_PERM_EXEC;
183 	default:
184 		return 0;
185 	}
186 }
187 
audit_match_filetype(struct audit_context * ctx,int val)188 static int audit_match_filetype(struct audit_context *ctx, int val)
189 {
190 	struct audit_names *n;
191 	umode_t mode = (umode_t)val;
192 
193 	if (unlikely(!ctx))
194 		return 0;
195 
196 	list_for_each_entry(n, &ctx->names_list, list) {
197 		if ((n->ino != -1) &&
198 		    ((n->mode & S_IFMT) == mode))
199 			return 1;
200 	}
201 
202 	return 0;
203 }
204 
205 /*
206  * We keep a linked list of fixed-sized (31 pointer) arrays of audit_chunk *;
207  * ->first_trees points to its beginning, ->trees - to the current end of data.
208  * ->tree_count is the number of free entries in array pointed to by ->trees.
209  * Original condition is (NULL, NULL, 0); as soon as it grows we never revert to NULL,
210  * "empty" becomes (p, p, 31) afterwards.  We don't shrink the list (and seriously,
211  * it's going to remain 1-element for almost any setup) until we free context itself.
212  * References in it _are_ dropped - at the same time we free/drop aux stuff.
213  */
214 
215 #ifdef CONFIG_AUDIT_TREE
audit_set_auditable(struct audit_context * ctx)216 static void audit_set_auditable(struct audit_context *ctx)
217 {
218 	if (!ctx->prio) {
219 		ctx->prio = 1;
220 		ctx->current_state = AUDIT_RECORD_CONTEXT;
221 	}
222 }
223 
put_tree_ref(struct audit_context * ctx,struct audit_chunk * chunk)224 static int put_tree_ref(struct audit_context *ctx, struct audit_chunk *chunk)
225 {
226 	struct audit_tree_refs *p = ctx->trees;
227 	int left = ctx->tree_count;
228 	if (likely(left)) {
229 		p->c[--left] = chunk;
230 		ctx->tree_count = left;
231 		return 1;
232 	}
233 	if (!p)
234 		return 0;
235 	p = p->next;
236 	if (p) {
237 		p->c[30] = chunk;
238 		ctx->trees = p;
239 		ctx->tree_count = 30;
240 		return 1;
241 	}
242 	return 0;
243 }
244 
grow_tree_refs(struct audit_context * ctx)245 static int grow_tree_refs(struct audit_context *ctx)
246 {
247 	struct audit_tree_refs *p = ctx->trees;
248 	ctx->trees = kzalloc(sizeof(struct audit_tree_refs), GFP_KERNEL);
249 	if (!ctx->trees) {
250 		ctx->trees = p;
251 		return 0;
252 	}
253 	if (p)
254 		p->next = ctx->trees;
255 	else
256 		ctx->first_trees = ctx->trees;
257 	ctx->tree_count = 31;
258 	return 1;
259 }
260 #endif
261 
unroll_tree_refs(struct audit_context * ctx,struct audit_tree_refs * p,int count)262 static void unroll_tree_refs(struct audit_context *ctx,
263 		      struct audit_tree_refs *p, int count)
264 {
265 #ifdef CONFIG_AUDIT_TREE
266 	struct audit_tree_refs *q;
267 	int n;
268 	if (!p) {
269 		/* we started with empty chain */
270 		p = ctx->first_trees;
271 		count = 31;
272 		/* if the very first allocation has failed, nothing to do */
273 		if (!p)
274 			return;
275 	}
276 	n = count;
277 	for (q = p; q != ctx->trees; q = q->next, n = 31) {
278 		while (n--) {
279 			audit_put_chunk(q->c[n]);
280 			q->c[n] = NULL;
281 		}
282 	}
283 	while (n-- > ctx->tree_count) {
284 		audit_put_chunk(q->c[n]);
285 		q->c[n] = NULL;
286 	}
287 	ctx->trees = p;
288 	ctx->tree_count = count;
289 #endif
290 }
291 
free_tree_refs(struct audit_context * ctx)292 static void free_tree_refs(struct audit_context *ctx)
293 {
294 	struct audit_tree_refs *p, *q;
295 	for (p = ctx->first_trees; p; p = q) {
296 		q = p->next;
297 		kfree(p);
298 	}
299 }
300 
match_tree_refs(struct audit_context * ctx,struct audit_tree * tree)301 static int match_tree_refs(struct audit_context *ctx, struct audit_tree *tree)
302 {
303 #ifdef CONFIG_AUDIT_TREE
304 	struct audit_tree_refs *p;
305 	int n;
306 	if (!tree)
307 		return 0;
308 	/* full ones */
309 	for (p = ctx->first_trees; p != ctx->trees; p = p->next) {
310 		for (n = 0; n < 31; n++)
311 			if (audit_tree_match(p->c[n], tree))
312 				return 1;
313 	}
314 	/* partial */
315 	if (p) {
316 		for (n = ctx->tree_count; n < 31; n++)
317 			if (audit_tree_match(p->c[n], tree))
318 				return 1;
319 	}
320 #endif
321 	return 0;
322 }
323 
audit_compare_uid(kuid_t uid,struct audit_names * name,struct audit_field * f,struct audit_context * ctx)324 static int audit_compare_uid(kuid_t uid,
325 			     struct audit_names *name,
326 			     struct audit_field *f,
327 			     struct audit_context *ctx)
328 {
329 	struct audit_names *n;
330 	int rc;
331 
332 	if (name) {
333 		rc = audit_uid_comparator(uid, f->op, name->uid);
334 		if (rc)
335 			return rc;
336 	}
337 
338 	if (ctx) {
339 		list_for_each_entry(n, &ctx->names_list, list) {
340 			rc = audit_uid_comparator(uid, f->op, n->uid);
341 			if (rc)
342 				return rc;
343 		}
344 	}
345 	return 0;
346 }
347 
audit_compare_gid(kgid_t gid,struct audit_names * name,struct audit_field * f,struct audit_context * ctx)348 static int audit_compare_gid(kgid_t gid,
349 			     struct audit_names *name,
350 			     struct audit_field *f,
351 			     struct audit_context *ctx)
352 {
353 	struct audit_names *n;
354 	int rc;
355 
356 	if (name) {
357 		rc = audit_gid_comparator(gid, f->op, name->gid);
358 		if (rc)
359 			return rc;
360 	}
361 
362 	if (ctx) {
363 		list_for_each_entry(n, &ctx->names_list, list) {
364 			rc = audit_gid_comparator(gid, f->op, n->gid);
365 			if (rc)
366 				return rc;
367 		}
368 	}
369 	return 0;
370 }
371 
audit_field_compare(struct task_struct * tsk,const struct cred * cred,struct audit_field * f,struct audit_context * ctx,struct audit_names * name)372 static int audit_field_compare(struct task_struct *tsk,
373 			       const struct cred *cred,
374 			       struct audit_field *f,
375 			       struct audit_context *ctx,
376 			       struct audit_names *name)
377 {
378 	switch (f->val) {
379 	/* process to file object comparisons */
380 	case AUDIT_COMPARE_UID_TO_OBJ_UID:
381 		return audit_compare_uid(cred->uid, name, f, ctx);
382 	case AUDIT_COMPARE_GID_TO_OBJ_GID:
383 		return audit_compare_gid(cred->gid, name, f, ctx);
384 	case AUDIT_COMPARE_EUID_TO_OBJ_UID:
385 		return audit_compare_uid(cred->euid, name, f, ctx);
386 	case AUDIT_COMPARE_EGID_TO_OBJ_GID:
387 		return audit_compare_gid(cred->egid, name, f, ctx);
388 	case AUDIT_COMPARE_AUID_TO_OBJ_UID:
389 		return audit_compare_uid(tsk->loginuid, name, f, ctx);
390 	case AUDIT_COMPARE_SUID_TO_OBJ_UID:
391 		return audit_compare_uid(cred->suid, name, f, ctx);
392 	case AUDIT_COMPARE_SGID_TO_OBJ_GID:
393 		return audit_compare_gid(cred->sgid, name, f, ctx);
394 	case AUDIT_COMPARE_FSUID_TO_OBJ_UID:
395 		return audit_compare_uid(cred->fsuid, name, f, ctx);
396 	case AUDIT_COMPARE_FSGID_TO_OBJ_GID:
397 		return audit_compare_gid(cred->fsgid, name, f, ctx);
398 	/* uid comparisons */
399 	case AUDIT_COMPARE_UID_TO_AUID:
400 		return audit_uid_comparator(cred->uid, f->op, tsk->loginuid);
401 	case AUDIT_COMPARE_UID_TO_EUID:
402 		return audit_uid_comparator(cred->uid, f->op, cred->euid);
403 	case AUDIT_COMPARE_UID_TO_SUID:
404 		return audit_uid_comparator(cred->uid, f->op, cred->suid);
405 	case AUDIT_COMPARE_UID_TO_FSUID:
406 		return audit_uid_comparator(cred->uid, f->op, cred->fsuid);
407 	/* auid comparisons */
408 	case AUDIT_COMPARE_AUID_TO_EUID:
409 		return audit_uid_comparator(tsk->loginuid, f->op, cred->euid);
410 	case AUDIT_COMPARE_AUID_TO_SUID:
411 		return audit_uid_comparator(tsk->loginuid, f->op, cred->suid);
412 	case AUDIT_COMPARE_AUID_TO_FSUID:
413 		return audit_uid_comparator(tsk->loginuid, f->op, cred->fsuid);
414 	/* euid comparisons */
415 	case AUDIT_COMPARE_EUID_TO_SUID:
416 		return audit_uid_comparator(cred->euid, f->op, cred->suid);
417 	case AUDIT_COMPARE_EUID_TO_FSUID:
418 		return audit_uid_comparator(cred->euid, f->op, cred->fsuid);
419 	/* suid comparisons */
420 	case AUDIT_COMPARE_SUID_TO_FSUID:
421 		return audit_uid_comparator(cred->suid, f->op, cred->fsuid);
422 	/* gid comparisons */
423 	case AUDIT_COMPARE_GID_TO_EGID:
424 		return audit_gid_comparator(cred->gid, f->op, cred->egid);
425 	case AUDIT_COMPARE_GID_TO_SGID:
426 		return audit_gid_comparator(cred->gid, f->op, cred->sgid);
427 	case AUDIT_COMPARE_GID_TO_FSGID:
428 		return audit_gid_comparator(cred->gid, f->op, cred->fsgid);
429 	/* egid comparisons */
430 	case AUDIT_COMPARE_EGID_TO_SGID:
431 		return audit_gid_comparator(cred->egid, f->op, cred->sgid);
432 	case AUDIT_COMPARE_EGID_TO_FSGID:
433 		return audit_gid_comparator(cred->egid, f->op, cred->fsgid);
434 	/* sgid comparison */
435 	case AUDIT_COMPARE_SGID_TO_FSGID:
436 		return audit_gid_comparator(cred->sgid, f->op, cred->fsgid);
437 	default:
438 		WARN(1, "Missing AUDIT_COMPARE define.  Report as a bug\n");
439 		return 0;
440 	}
441 	return 0;
442 }
443 
444 /* Determine if any context name data matches a rule's watch data */
445 /* Compare a task_struct with an audit_rule.  Return 1 on match, 0
446  * otherwise.
447  *
448  * If task_creation is true, this is an explicit indication that we are
449  * filtering a task rule at task creation time.  This and tsk == current are
450  * the only situations where tsk->cred may be accessed without an rcu read lock.
451  */
audit_filter_rules(struct task_struct * tsk,struct audit_krule * rule,struct audit_context * ctx,struct audit_names * name,enum audit_state * state,bool task_creation)452 static int audit_filter_rules(struct task_struct *tsk,
453 			      struct audit_krule *rule,
454 			      struct audit_context *ctx,
455 			      struct audit_names *name,
456 			      enum audit_state *state,
457 			      bool task_creation)
458 {
459 	const struct cred *cred;
460 	int i, need_sid = 1;
461 	u32 sid;
462 
463 	cred = rcu_dereference_check(tsk->cred, tsk == current || task_creation);
464 
465 	for (i = 0; i < rule->field_count; i++) {
466 		struct audit_field *f = &rule->fields[i];
467 		struct audit_names *n;
468 		int result = 0;
469 
470 		switch (f->type) {
471 		case AUDIT_PID:
472 			result = audit_comparator(task_tgid_nr(tsk), f->op, f->val);
473 			break;
474 		case AUDIT_PPID:
475 			if (ctx) {
476 				if (!ctx->ppid)
477 					ctx->ppid = sys_getppid();
478 				result = audit_comparator(ctx->ppid, f->op, f->val);
479 			}
480 			break;
481 		case AUDIT_UID:
482 			result = audit_uid_comparator(cred->uid, f->op, f->uid);
483 			break;
484 		case AUDIT_EUID:
485 			result = audit_uid_comparator(cred->euid, f->op, f->uid);
486 			break;
487 		case AUDIT_SUID:
488 			result = audit_uid_comparator(cred->suid, f->op, f->uid);
489 			break;
490 		case AUDIT_FSUID:
491 			result = audit_uid_comparator(cred->fsuid, f->op, f->uid);
492 			break;
493 		case AUDIT_GID:
494 			result = audit_gid_comparator(cred->gid, f->op, f->gid);
495 			if (f->op == Audit_equal) {
496 				if (!result)
497 					result = in_group_p(f->gid);
498 			} else if (f->op == Audit_not_equal) {
499 				if (result)
500 					result = !in_group_p(f->gid);
501 			}
502 			break;
503 		case AUDIT_EGID:
504 			result = audit_gid_comparator(cred->egid, f->op, f->gid);
505 			if (f->op == Audit_equal) {
506 				if (!result)
507 					result = in_egroup_p(f->gid);
508 			} else if (f->op == Audit_not_equal) {
509 				if (result)
510 					result = !in_egroup_p(f->gid);
511 			}
512 			break;
513 		case AUDIT_SGID:
514 			result = audit_gid_comparator(cred->sgid, f->op, f->gid);
515 			break;
516 		case AUDIT_FSGID:
517 			result = audit_gid_comparator(cred->fsgid, f->op, f->gid);
518 			break;
519 		case AUDIT_PERS:
520 			result = audit_comparator(tsk->personality, f->op, f->val);
521 			break;
522 		case AUDIT_ARCH:
523 			if (ctx)
524 				result = audit_comparator(ctx->arch, f->op, f->val);
525 			break;
526 
527 		case AUDIT_EXIT:
528 			if (ctx && ctx->return_valid)
529 				result = audit_comparator(ctx->return_code, f->op, f->val);
530 			break;
531 		case AUDIT_SUCCESS:
532 			if (ctx && ctx->return_valid) {
533 				if (f->val)
534 					result = audit_comparator(ctx->return_valid, f->op, AUDITSC_SUCCESS);
535 				else
536 					result = audit_comparator(ctx->return_valid, f->op, AUDITSC_FAILURE);
537 			}
538 			break;
539 		case AUDIT_DEVMAJOR:
540 			if (name) {
541 				if (audit_comparator(MAJOR(name->dev), f->op, f->val) ||
542 				    audit_comparator(MAJOR(name->rdev), f->op, f->val))
543 					++result;
544 			} else if (ctx) {
545 				list_for_each_entry(n, &ctx->names_list, list) {
546 					if (audit_comparator(MAJOR(n->dev), f->op, f->val) ||
547 					    audit_comparator(MAJOR(n->rdev), f->op, f->val)) {
548 						++result;
549 						break;
550 					}
551 				}
552 			}
553 			break;
554 		case AUDIT_DEVMINOR:
555 			if (name) {
556 				if (audit_comparator(MINOR(name->dev), f->op, f->val) ||
557 				    audit_comparator(MINOR(name->rdev), f->op, f->val))
558 					++result;
559 			} else if (ctx) {
560 				list_for_each_entry(n, &ctx->names_list, list) {
561 					if (audit_comparator(MINOR(n->dev), f->op, f->val) ||
562 					    audit_comparator(MINOR(n->rdev), f->op, f->val)) {
563 						++result;
564 						break;
565 					}
566 				}
567 			}
568 			break;
569 		case AUDIT_INODE:
570 			if (name)
571 				result = (name->ino == f->val);
572 			else if (ctx) {
573 				list_for_each_entry(n, &ctx->names_list, list) {
574 					if (audit_comparator(n->ino, f->op, f->val)) {
575 						++result;
576 						break;
577 					}
578 				}
579 			}
580 			break;
581 		case AUDIT_OBJ_UID:
582 			if (name) {
583 				result = audit_uid_comparator(name->uid, f->op, f->uid);
584 			} else if (ctx) {
585 				list_for_each_entry(n, &ctx->names_list, list) {
586 					if (audit_uid_comparator(n->uid, f->op, f->uid)) {
587 						++result;
588 						break;
589 					}
590 				}
591 			}
592 			break;
593 		case AUDIT_OBJ_GID:
594 			if (name) {
595 				result = audit_gid_comparator(name->gid, f->op, f->gid);
596 			} else if (ctx) {
597 				list_for_each_entry(n, &ctx->names_list, list) {
598 					if (audit_gid_comparator(n->gid, f->op, f->gid)) {
599 						++result;
600 						break;
601 					}
602 				}
603 			}
604 			break;
605 		case AUDIT_WATCH:
606 			if (name)
607 				result = audit_watch_compare(rule->watch, name->ino, name->dev);
608 			break;
609 		case AUDIT_DIR:
610 			if (ctx)
611 				result = match_tree_refs(ctx, rule->tree);
612 			break;
613 		case AUDIT_LOGINUID:
614 			result = 0;
615 			if (ctx)
616 				result = audit_uid_comparator(tsk->loginuid, f->op, f->uid);
617 			break;
618 		case AUDIT_LOGINUID_SET:
619 			result = audit_comparator(audit_loginuid_set(tsk), f->op, f->val);
620 			break;
621 		case AUDIT_SUBJ_USER:
622 		case AUDIT_SUBJ_ROLE:
623 		case AUDIT_SUBJ_TYPE:
624 		case AUDIT_SUBJ_SEN:
625 		case AUDIT_SUBJ_CLR:
626 			/* NOTE: this may return negative values indicating
627 			   a temporary error.  We simply treat this as a
628 			   match for now to avoid losing information that
629 			   may be wanted.   An error message will also be
630 			   logged upon error */
631 			if (f->lsm_rule) {
632 				if (need_sid) {
633 					security_task_getsecid(tsk, &sid);
634 					need_sid = 0;
635 				}
636 				result = security_audit_rule_match(sid, f->type,
637 				                                  f->op,
638 				                                  f->lsm_rule,
639 				                                  ctx);
640 			}
641 			break;
642 		case AUDIT_OBJ_USER:
643 		case AUDIT_OBJ_ROLE:
644 		case AUDIT_OBJ_TYPE:
645 		case AUDIT_OBJ_LEV_LOW:
646 		case AUDIT_OBJ_LEV_HIGH:
647 			/* The above note for AUDIT_SUBJ_USER...AUDIT_SUBJ_CLR
648 			   also applies here */
649 			if (f->lsm_rule) {
650 				/* Find files that match */
651 				if (name) {
652 					result = security_audit_rule_match(
653 					           name->osid, f->type, f->op,
654 					           f->lsm_rule, ctx);
655 				} else if (ctx) {
656 					list_for_each_entry(n, &ctx->names_list, list) {
657 						if (security_audit_rule_match(n->osid, f->type,
658 									      f->op, f->lsm_rule,
659 									      ctx)) {
660 							++result;
661 							break;
662 						}
663 					}
664 				}
665 				/* Find ipc objects that match */
666 				if (!ctx || ctx->type != AUDIT_IPC)
667 					break;
668 				if (security_audit_rule_match(ctx->ipc.osid,
669 							      f->type, f->op,
670 							      f->lsm_rule, ctx))
671 					++result;
672 			}
673 			break;
674 		case AUDIT_ARG0:
675 		case AUDIT_ARG1:
676 		case AUDIT_ARG2:
677 		case AUDIT_ARG3:
678 			if (ctx)
679 				result = audit_comparator(ctx->argv[f->type-AUDIT_ARG0], f->op, f->val);
680 			break;
681 		case AUDIT_FILTERKEY:
682 			/* ignore this field for filtering */
683 			result = 1;
684 			break;
685 		case AUDIT_PERM:
686 			result = audit_match_perm(ctx, f->val);
687 			break;
688 		case AUDIT_FILETYPE:
689 			result = audit_match_filetype(ctx, f->val);
690 			break;
691 		case AUDIT_FIELD_COMPARE:
692 			result = audit_field_compare(tsk, cred, f, ctx, name);
693 			break;
694 		}
695 		if (!result)
696 			return 0;
697 	}
698 
699 	if (ctx) {
700 		if (rule->prio <= ctx->prio)
701 			return 0;
702 		if (rule->filterkey) {
703 			kfree(ctx->filterkey);
704 			ctx->filterkey = kstrdup(rule->filterkey, GFP_ATOMIC);
705 		}
706 		ctx->prio = rule->prio;
707 	}
708 	switch (rule->action) {
709 	case AUDIT_NEVER:    *state = AUDIT_DISABLED;	    break;
710 	case AUDIT_ALWAYS:   *state = AUDIT_RECORD_CONTEXT; break;
711 	}
712 	return 1;
713 }
714 
715 /* At process creation time, we can determine if system-call auditing is
716  * completely disabled for this task.  Since we only have the task
717  * structure at this point, we can only check uid and gid.
718  */
audit_filter_task(struct task_struct * tsk,char ** key)719 static enum audit_state audit_filter_task(struct task_struct *tsk, char **key)
720 {
721 	struct audit_entry *e;
722 	enum audit_state   state;
723 
724 	rcu_read_lock();
725 	list_for_each_entry_rcu(e, &audit_filter_list[AUDIT_FILTER_TASK], list) {
726 		if (audit_filter_rules(tsk, &e->rule, NULL, NULL,
727 				       &state, true)) {
728 			if (state == AUDIT_RECORD_CONTEXT)
729 				*key = kstrdup(e->rule.filterkey, GFP_ATOMIC);
730 			rcu_read_unlock();
731 			return state;
732 		}
733 	}
734 	rcu_read_unlock();
735 	return AUDIT_BUILD_CONTEXT;
736 }
737 
738 /* At syscall entry and exit time, this filter is called if the
739  * audit_state is not low enough that auditing cannot take place, but is
740  * also not high enough that we already know we have to write an audit
741  * record (i.e., the state is AUDIT_SETUP_CONTEXT or AUDIT_BUILD_CONTEXT).
742  */
audit_filter_syscall(struct task_struct * tsk,struct audit_context * ctx,struct list_head * list)743 static enum audit_state audit_filter_syscall(struct task_struct *tsk,
744 					     struct audit_context *ctx,
745 					     struct list_head *list)
746 {
747 	struct audit_entry *e;
748 	enum audit_state state;
749 
750 	if (audit_pid && tsk->tgid == audit_pid)
751 		return AUDIT_DISABLED;
752 
753 	rcu_read_lock();
754 	if (!list_empty(list)) {
755 		int word = AUDIT_WORD(ctx->major);
756 		int bit  = AUDIT_BIT(ctx->major);
757 
758 		list_for_each_entry_rcu(e, list, list) {
759 			if ((e->rule.mask[word] & bit) == bit &&
760 			    audit_filter_rules(tsk, &e->rule, ctx, NULL,
761 					       &state, false)) {
762 				rcu_read_unlock();
763 				ctx->current_state = state;
764 				return state;
765 			}
766 		}
767 	}
768 	rcu_read_unlock();
769 	return AUDIT_BUILD_CONTEXT;
770 }
771 
772 /*
773  * Given an audit_name check the inode hash table to see if they match.
774  * Called holding the rcu read lock to protect the use of audit_inode_hash
775  */
audit_filter_inode_name(struct task_struct * tsk,struct audit_names * n,struct audit_context * ctx)776 static int audit_filter_inode_name(struct task_struct *tsk,
777 				   struct audit_names *n,
778 				   struct audit_context *ctx) {
779 	int word, bit;
780 	int h = audit_hash_ino((u32)n->ino);
781 	struct list_head *list = &audit_inode_hash[h];
782 	struct audit_entry *e;
783 	enum audit_state state;
784 
785 	word = AUDIT_WORD(ctx->major);
786 	bit  = AUDIT_BIT(ctx->major);
787 
788 	if (list_empty(list))
789 		return 0;
790 
791 	list_for_each_entry_rcu(e, list, list) {
792 		if ((e->rule.mask[word] & bit) == bit &&
793 		    audit_filter_rules(tsk, &e->rule, ctx, n, &state, false)) {
794 			ctx->current_state = state;
795 			return 1;
796 		}
797 	}
798 
799 	return 0;
800 }
801 
802 /* At syscall exit time, this filter is called if any audit_names have been
803  * collected during syscall processing.  We only check rules in sublists at hash
804  * buckets applicable to the inode numbers in audit_names.
805  * Regarding audit_state, same rules apply as for audit_filter_syscall().
806  */
audit_filter_inodes(struct task_struct * tsk,struct audit_context * ctx)807 void audit_filter_inodes(struct task_struct *tsk, struct audit_context *ctx)
808 {
809 	struct audit_names *n;
810 
811 	if (audit_pid && tsk->tgid == audit_pid)
812 		return;
813 
814 	rcu_read_lock();
815 
816 	list_for_each_entry(n, &ctx->names_list, list) {
817 		if (audit_filter_inode_name(tsk, n, ctx))
818 			break;
819 	}
820 	rcu_read_unlock();
821 }
822 
audit_get_context(struct task_struct * tsk,int return_valid,long return_code)823 static inline struct audit_context *audit_get_context(struct task_struct *tsk,
824 						      int return_valid,
825 						      long return_code)
826 {
827 	struct audit_context *context = tsk->audit_context;
828 
829 	if (!context)
830 		return NULL;
831 	context->return_valid = return_valid;
832 
833 	/*
834 	 * we need to fix up the return code in the audit logs if the actual
835 	 * return codes are later going to be fixed up by the arch specific
836 	 * signal handlers
837 	 *
838 	 * This is actually a test for:
839 	 * (rc == ERESTARTSYS ) || (rc == ERESTARTNOINTR) ||
840 	 * (rc == ERESTARTNOHAND) || (rc == ERESTART_RESTARTBLOCK)
841 	 *
842 	 * but is faster than a bunch of ||
843 	 */
844 	if (unlikely(return_code <= -ERESTARTSYS) &&
845 	    (return_code >= -ERESTART_RESTARTBLOCK) &&
846 	    (return_code != -ENOIOCTLCMD))
847 		context->return_code = -EINTR;
848 	else
849 		context->return_code  = return_code;
850 
851 	if (context->in_syscall && !context->dummy) {
852 		audit_filter_syscall(tsk, context, &audit_filter_list[AUDIT_FILTER_EXIT]);
853 		audit_filter_inodes(tsk, context);
854 	}
855 
856 	tsk->audit_context = NULL;
857 	return context;
858 }
859 
audit_free_names(struct audit_context * context)860 static inline void audit_free_names(struct audit_context *context)
861 {
862 	struct audit_names *n, *next;
863 
864 #if AUDIT_DEBUG == 2
865 	if (context->put_count + context->ino_count != context->name_count) {
866 		int i = 0;
867 
868 		printk(KERN_ERR "%s:%d(:%d): major=%d in_syscall=%d"
869 		       " name_count=%d put_count=%d"
870 		       " ino_count=%d [NOT freeing]\n",
871 		       __FILE__, __LINE__,
872 		       context->serial, context->major, context->in_syscall,
873 		       context->name_count, context->put_count,
874 		       context->ino_count);
875 		list_for_each_entry(n, &context->names_list, list) {
876 			printk(KERN_ERR "names[%d] = %p = %s\n", i++,
877 			       n->name, n->name->name ?: "(null)");
878 		}
879 		dump_stack();
880 		return;
881 	}
882 #endif
883 #if AUDIT_DEBUG
884 	context->put_count  = 0;
885 	context->ino_count  = 0;
886 #endif
887 
888 	list_for_each_entry_safe(n, next, &context->names_list, list) {
889 		list_del(&n->list);
890 		if (n->name && n->name_put)
891 			final_putname(n->name);
892 		if (n->should_free)
893 			kfree(n);
894 	}
895 	context->name_count = 0;
896 	path_put(&context->pwd);
897 	context->pwd.dentry = NULL;
898 	context->pwd.mnt = NULL;
899 }
900 
audit_free_aux(struct audit_context * context)901 static inline void audit_free_aux(struct audit_context *context)
902 {
903 	struct audit_aux_data *aux;
904 
905 	while ((aux = context->aux)) {
906 		context->aux = aux->next;
907 		kfree(aux);
908 	}
909 	while ((aux = context->aux_pids)) {
910 		context->aux_pids = aux->next;
911 		kfree(aux);
912 	}
913 }
914 
audit_alloc_context(enum audit_state state)915 static inline struct audit_context *audit_alloc_context(enum audit_state state)
916 {
917 	struct audit_context *context;
918 
919 	context = kzalloc(sizeof(*context), GFP_KERNEL);
920 	if (!context)
921 		return NULL;
922 	context->state = state;
923 	context->prio = state == AUDIT_RECORD_CONTEXT ? ~0ULL : 0;
924 	INIT_LIST_HEAD(&context->killed_trees);
925 	INIT_LIST_HEAD(&context->names_list);
926 	return context;
927 }
928 
929 /**
930  * audit_alloc - allocate an audit context block for a task
931  * @tsk: task
932  *
933  * Filter on the task information and allocate a per-task audit context
934  * if necessary.  Doing so turns on system call auditing for the
935  * specified task.  This is called from copy_process, so no lock is
936  * needed.
937  */
audit_alloc(struct task_struct * tsk)938 int audit_alloc(struct task_struct *tsk)
939 {
940 	struct audit_context *context;
941 	enum audit_state     state;
942 	char *key = NULL;
943 
944 	if (likely(!audit_ever_enabled))
945 		return 0; /* Return if not auditing. */
946 
947 	state = audit_filter_task(tsk, &key);
948 	if (state == AUDIT_DISABLED)
949 		return 0;
950 
951 	if (!(context = audit_alloc_context(state))) {
952 		kfree(key);
953 		audit_log_lost("out of memory in audit_alloc");
954 		return -ENOMEM;
955 	}
956 	context->filterkey = key;
957 
958 	tsk->audit_context  = context;
959 	set_tsk_thread_flag(tsk, TIF_SYSCALL_AUDIT);
960 	return 0;
961 }
962 
audit_free_context(struct audit_context * context)963 static inline void audit_free_context(struct audit_context *context)
964 {
965 	audit_free_names(context);
966 	unroll_tree_refs(context, NULL, 0);
967 	free_tree_refs(context);
968 	audit_free_aux(context);
969 	kfree(context->filterkey);
970 	kfree(context->sockaddr);
971 	kfree(context);
972 }
973 
audit_log_pid_context(struct audit_context * context,pid_t pid,kuid_t auid,kuid_t uid,unsigned int sessionid,u32 sid,char * comm)974 static int audit_log_pid_context(struct audit_context *context, pid_t pid,
975 				 kuid_t auid, kuid_t uid, unsigned int sessionid,
976 				 u32 sid, char *comm)
977 {
978 	struct audit_buffer *ab;
979 	char *ctx = NULL;
980 	u32 len;
981 	int rc = 0;
982 
983 	ab = audit_log_start(context, GFP_KERNEL, AUDIT_OBJ_PID);
984 	if (!ab)
985 		return rc;
986 
987 	audit_log_format(ab, "opid=%d oauid=%d ouid=%d oses=%d", pid,
988 			 from_kuid(&init_user_ns, auid),
989 			 from_kuid(&init_user_ns, uid), sessionid);
990 	if (sid) {
991 		if (security_secid_to_secctx(sid, &ctx, &len)) {
992 			audit_log_format(ab, " obj=(none)");
993 			rc = 1;
994 		} else {
995 			audit_log_format(ab, " obj=%s", ctx);
996 			security_release_secctx(ctx, len);
997 		}
998 	}
999 	audit_log_format(ab, " ocomm=");
1000 	audit_log_untrustedstring(ab, comm);
1001 	audit_log_end(ab);
1002 
1003 	return rc;
1004 }
1005 
audit_log_execve_info(struct audit_context * context,struct audit_buffer ** ab,struct audit_aux_data_execve * axi)1006 static void audit_log_execve_info(struct audit_context *context,
1007 				  struct audit_buffer **ab,
1008 				  struct audit_aux_data_execve *axi)
1009 {
1010 	long len_max;
1011 	long len_rem;
1012 	long len_full;
1013 	long len_buf;
1014 	long len_abuf;
1015 	long len_tmp;
1016 	bool require_data;
1017 	bool encode;
1018 	unsigned int iter;
1019 	unsigned int arg;
1020 	char *buf_head;
1021 	char *buf;
1022 	const char __user *p;
1023 
1024 	/* NOTE: this buffer needs to be large enough to hold all the non-arg
1025 	 *       data we put in the audit record for this argument (see the
1026 	 *       code below) ... at this point in time 96 is plenty */
1027 	char abuf[96];
1028 
1029 	if (axi->mm != current->mm)
1030 		return; /* execve failed, no additional info */
1031 
1032 	p = (const char __user *)axi->mm->arg_start;
1033 
1034 	/* NOTE: we set MAX_EXECVE_AUDIT_LEN to a rather arbitrary limit, the
1035 	 *       current value of 7500 is not as important as the fact that it
1036 	 *       is less than 8k, a setting of 7500 gives us plenty of wiggle
1037 	 *       room if we go over a little bit in the logging below */
1038 	WARN_ON_ONCE(MAX_EXECVE_AUDIT_LEN > 7500);
1039 	len_max = MAX_EXECVE_AUDIT_LEN;
1040 
1041 	/* scratch buffer to hold the userspace args */
1042 	buf_head = kmalloc(MAX_EXECVE_AUDIT_LEN + 1, GFP_KERNEL);
1043 	if (!buf_head) {
1044 		audit_panic("out of memory for argv string");
1045 		return;
1046 	}
1047 	buf = buf_head;
1048 
1049 	audit_log_format(*ab, "argc=%d", axi->argc);
1050 
1051 	len_rem = len_max;
1052 	len_buf = 0;
1053 	len_full = 0;
1054 	require_data = true;
1055 	encode = false;
1056 	iter = 0;
1057 	arg = 0;
1058 	do {
1059 		/* NOTE: we don't ever want to trust this value for anything
1060 		 *       serious, but the audit record format insists we
1061 		 *       provide an argument length for really long arguments,
1062 		 *       e.g. > MAX_EXECVE_AUDIT_LEN, so we have no choice but
1063 		 *       to use strncpy_from_user() to obtain this value for
1064 		 *       recording in the log, although we don't use it
1065 		 *       anywhere here to avoid a double-fetch problem */
1066 		if (len_full == 0)
1067 			len_full = strnlen_user(p, MAX_ARG_STRLEN) - 1;
1068 
1069 		/* read more data from userspace */
1070 		if (require_data) {
1071 			/* can we make more room in the buffer? */
1072 			if (buf != buf_head) {
1073 				memmove(buf_head, buf, len_buf);
1074 				buf = buf_head;
1075 			}
1076 
1077 			/* fetch as much as we can of the argument */
1078 			len_tmp = strncpy_from_user(&buf_head[len_buf], p,
1079 						    len_max - len_buf);
1080 			if (len_tmp == -EFAULT) {
1081 				/* unable to copy from userspace */
1082 				send_sig(SIGKILL, current, 0);
1083 				goto out;
1084 			} else if (len_tmp == (len_max - len_buf)) {
1085 				/* buffer is not large enough */
1086 				require_data = true;
1087 				/* NOTE: if we are going to span multiple
1088 				 *       buffers force the encoding so we stand
1089 				 *       a chance at a sane len_full value and
1090 				 *       consistent record encoding */
1091 				encode = true;
1092 				len_full = len_full * 2;
1093 				p += len_tmp;
1094 			} else {
1095 				require_data = false;
1096 				if (!encode)
1097 					encode = audit_string_contains_control(
1098 								buf, len_tmp);
1099 				/* try to use a trusted value for len_full */
1100 				if (len_full < len_max)
1101 					len_full = (encode ?
1102 						    len_tmp * 2 : len_tmp);
1103 				p += len_tmp + 1;
1104 			}
1105 			len_buf += len_tmp;
1106 			buf_head[len_buf] = '\0';
1107 
1108 			/* length of the buffer in the audit record? */
1109 			len_abuf = (encode ? len_buf * 2 : len_buf + 2);
1110 		}
1111 
1112 		/* write as much as we can to the audit log */
1113 		if (len_buf > 0) {
1114 			/* NOTE: some magic numbers here - basically if we
1115 			 *       can't fit a reasonable amount of data into the
1116 			 *       existing audit buffer, flush it and start with
1117 			 *       a new buffer */
1118 			if ((sizeof(abuf) + 8) > len_rem) {
1119 				len_rem = len_max;
1120 				audit_log_end(*ab);
1121 				*ab = audit_log_start(context,
1122 						      GFP_KERNEL, AUDIT_EXECVE);
1123 				if (!*ab)
1124 					goto out;
1125 			}
1126 
1127 			/* create the non-arg portion of the arg record */
1128 			len_tmp = 0;
1129 			if (require_data || (iter > 0) ||
1130 			    ((len_abuf + sizeof(abuf)) > len_rem)) {
1131 				if (iter == 0) {
1132 					len_tmp += snprintf(&abuf[len_tmp],
1133 							sizeof(abuf) - len_tmp,
1134 							" a%d_len=%lu",
1135 							arg, len_full);
1136 				}
1137 				len_tmp += snprintf(&abuf[len_tmp],
1138 						    sizeof(abuf) - len_tmp,
1139 						    " a%d[%d]=", arg, iter++);
1140 			} else
1141 				len_tmp += snprintf(&abuf[len_tmp],
1142 						    sizeof(abuf) - len_tmp,
1143 						    " a%d=", arg);
1144 			WARN_ON(len_tmp >= sizeof(abuf));
1145 			abuf[sizeof(abuf) - 1] = '\0';
1146 
1147 			/* log the arg in the audit record */
1148 			audit_log_format(*ab, "%s", abuf);
1149 			len_rem -= len_tmp;
1150 			len_tmp = len_buf;
1151 			if (encode) {
1152 				if (len_abuf > len_rem)
1153 					len_tmp = len_rem / 2; /* encoding */
1154 				audit_log_n_hex(*ab, buf, len_tmp);
1155 				len_rem -= len_tmp * 2;
1156 				len_abuf -= len_tmp * 2;
1157 			} else {
1158 				if (len_abuf > len_rem)
1159 					len_tmp = len_rem - 2; /* quotes */
1160 				audit_log_n_string(*ab, buf, len_tmp);
1161 				len_rem -= len_tmp + 2;
1162 				/* don't subtract the "2" because we still need
1163 				 * to add quotes to the remaining string */
1164 				len_abuf -= len_tmp;
1165 			}
1166 			len_buf -= len_tmp;
1167 			buf += len_tmp;
1168 		}
1169 
1170 		/* ready to move to the next argument? */
1171 		if ((len_buf == 0) && !require_data) {
1172 			arg++;
1173 			iter = 0;
1174 			len_full = 0;
1175 			require_data = true;
1176 			encode = false;
1177 		}
1178 	} while (arg < axi->argc);
1179 
1180 	/* NOTE: the caller handles the final audit_log_end() call */
1181 
1182 out:
1183 	kfree(buf_head);
1184 }
1185 
show_special(struct audit_context * context,int * call_panic)1186 static void show_special(struct audit_context *context, int *call_panic)
1187 {
1188 	struct audit_buffer *ab;
1189 	int i;
1190 
1191 	ab = audit_log_start(context, GFP_KERNEL, context->type);
1192 	if (!ab)
1193 		return;
1194 
1195 	switch (context->type) {
1196 	case AUDIT_SOCKETCALL: {
1197 		int nargs = context->socketcall.nargs;
1198 		audit_log_format(ab, "nargs=%d", nargs);
1199 		for (i = 0; i < nargs; i++)
1200 			audit_log_format(ab, " a%d=%lx", i,
1201 				context->socketcall.args[i]);
1202 		break; }
1203 	case AUDIT_IPC: {
1204 		u32 osid = context->ipc.osid;
1205 
1206 		audit_log_format(ab, "ouid=%u ogid=%u mode=%#ho",
1207 				 from_kuid(&init_user_ns, context->ipc.uid),
1208 				 from_kgid(&init_user_ns, context->ipc.gid),
1209 				 context->ipc.mode);
1210 		if (osid) {
1211 			char *ctx = NULL;
1212 			u32 len;
1213 			if (security_secid_to_secctx(osid, &ctx, &len)) {
1214 				audit_log_format(ab, " osid=%u", osid);
1215 				*call_panic = 1;
1216 			} else {
1217 				audit_log_format(ab, " obj=%s", ctx);
1218 				security_release_secctx(ctx, len);
1219 			}
1220 		}
1221 		if (context->ipc.has_perm) {
1222 			audit_log_end(ab);
1223 			ab = audit_log_start(context, GFP_KERNEL,
1224 					     AUDIT_IPC_SET_PERM);
1225 			if (unlikely(!ab))
1226 				return;
1227 			audit_log_format(ab,
1228 				"qbytes=%lx ouid=%u ogid=%u mode=%#ho",
1229 				context->ipc.qbytes,
1230 				context->ipc.perm_uid,
1231 				context->ipc.perm_gid,
1232 				context->ipc.perm_mode);
1233 		}
1234 		break; }
1235 	case AUDIT_MQ_OPEN: {
1236 		audit_log_format(ab,
1237 			"oflag=0x%x mode=%#ho mq_flags=0x%lx mq_maxmsg=%ld "
1238 			"mq_msgsize=%ld mq_curmsgs=%ld",
1239 			context->mq_open.oflag, context->mq_open.mode,
1240 			context->mq_open.attr.mq_flags,
1241 			context->mq_open.attr.mq_maxmsg,
1242 			context->mq_open.attr.mq_msgsize,
1243 			context->mq_open.attr.mq_curmsgs);
1244 		break; }
1245 	case AUDIT_MQ_SENDRECV: {
1246 		audit_log_format(ab,
1247 			"mqdes=%d msg_len=%zd msg_prio=%u "
1248 			"abs_timeout_sec=%ld abs_timeout_nsec=%ld",
1249 			context->mq_sendrecv.mqdes,
1250 			context->mq_sendrecv.msg_len,
1251 			context->mq_sendrecv.msg_prio,
1252 			context->mq_sendrecv.abs_timeout.tv_sec,
1253 			context->mq_sendrecv.abs_timeout.tv_nsec);
1254 		break; }
1255 	case AUDIT_MQ_NOTIFY: {
1256 		audit_log_format(ab, "mqdes=%d sigev_signo=%d",
1257 				context->mq_notify.mqdes,
1258 				context->mq_notify.sigev_signo);
1259 		break; }
1260 	case AUDIT_MQ_GETSETATTR: {
1261 		struct mq_attr *attr = &context->mq_getsetattr.mqstat;
1262 		audit_log_format(ab,
1263 			"mqdes=%d mq_flags=0x%lx mq_maxmsg=%ld mq_msgsize=%ld "
1264 			"mq_curmsgs=%ld ",
1265 			context->mq_getsetattr.mqdes,
1266 			attr->mq_flags, attr->mq_maxmsg,
1267 			attr->mq_msgsize, attr->mq_curmsgs);
1268 		break; }
1269 	case AUDIT_CAPSET: {
1270 		audit_log_format(ab, "pid=%d", context->capset.pid);
1271 		audit_log_cap(ab, "cap_pi", &context->capset.cap.inheritable);
1272 		audit_log_cap(ab, "cap_pp", &context->capset.cap.permitted);
1273 		audit_log_cap(ab, "cap_pe", &context->capset.cap.effective);
1274 		break; }
1275 	case AUDIT_MMAP: {
1276 		audit_log_format(ab, "fd=%d flags=0x%x", context->mmap.fd,
1277 				 context->mmap.flags);
1278 		break; }
1279 	}
1280 	audit_log_end(ab);
1281 }
1282 
audit_log_exit(struct audit_context * context,struct task_struct * tsk)1283 static void audit_log_exit(struct audit_context *context, struct task_struct *tsk)
1284 {
1285 	int i, call_panic = 0;
1286 	struct audit_buffer *ab;
1287 	struct audit_aux_data *aux;
1288 	struct audit_names *n;
1289 
1290 	/* tsk == current */
1291 	context->personality = tsk->personality;
1292 
1293 	ab = audit_log_start(context, GFP_KERNEL, AUDIT_SYSCALL);
1294 	if (!ab)
1295 		return;		/* audit_panic has been called */
1296 	audit_log_format(ab, "arch=%x syscall=%d",
1297 			 context->arch, context->major);
1298 	if (context->personality != PER_LINUX)
1299 		audit_log_format(ab, " per=%lx", context->personality);
1300 	if (context->return_valid)
1301 		audit_log_format(ab, " success=%s exit=%ld",
1302 				 (context->return_valid==AUDITSC_SUCCESS)?"yes":"no",
1303 				 context->return_code);
1304 
1305 	audit_log_format(ab,
1306 			 " a0=%lx a1=%lx a2=%lx a3=%lx items=%d",
1307 			 context->argv[0],
1308 			 context->argv[1],
1309 			 context->argv[2],
1310 			 context->argv[3],
1311 			 context->name_count);
1312 
1313 	audit_log_task_info(ab, tsk);
1314 	audit_log_key(ab, context->filterkey);
1315 	audit_log_end(ab);
1316 
1317 	for (aux = context->aux; aux; aux = aux->next) {
1318 
1319 		ab = audit_log_start(context, GFP_KERNEL, aux->type);
1320 		if (!ab)
1321 			continue; /* audit_panic has been called */
1322 
1323 		switch (aux->type) {
1324 
1325 		case AUDIT_EXECVE: {
1326 			struct audit_aux_data_execve *axi = (void *)aux;
1327 			audit_log_execve_info(context, &ab, axi);
1328 			break; }
1329 
1330 		case AUDIT_BPRM_FCAPS: {
1331 			struct audit_aux_data_bprm_fcaps *axs = (void *)aux;
1332 			audit_log_format(ab, "fver=%x", axs->fcap_ver);
1333 			audit_log_cap(ab, "fp", &axs->fcap.permitted);
1334 			audit_log_cap(ab, "fi", &axs->fcap.inheritable);
1335 			audit_log_format(ab, " fe=%d", axs->fcap.fE);
1336 			audit_log_cap(ab, "old_pp", &axs->old_pcap.permitted);
1337 			audit_log_cap(ab, "old_pi", &axs->old_pcap.inheritable);
1338 			audit_log_cap(ab, "old_pe", &axs->old_pcap.effective);
1339 			audit_log_cap(ab, "new_pp", &axs->new_pcap.permitted);
1340 			audit_log_cap(ab, "new_pi", &axs->new_pcap.inheritable);
1341 			audit_log_cap(ab, "new_pe", &axs->new_pcap.effective);
1342 			break; }
1343 
1344 		}
1345 		audit_log_end(ab);
1346 	}
1347 
1348 	if (context->type)
1349 		show_special(context, &call_panic);
1350 
1351 	if (context->fds[0] >= 0) {
1352 		ab = audit_log_start(context, GFP_KERNEL, AUDIT_FD_PAIR);
1353 		if (ab) {
1354 			audit_log_format(ab, "fd0=%d fd1=%d",
1355 					context->fds[0], context->fds[1]);
1356 			audit_log_end(ab);
1357 		}
1358 	}
1359 
1360 	if (context->sockaddr_len) {
1361 		ab = audit_log_start(context, GFP_KERNEL, AUDIT_SOCKADDR);
1362 		if (ab) {
1363 			audit_log_format(ab, "saddr=");
1364 			audit_log_n_hex(ab, (void *)context->sockaddr,
1365 					context->sockaddr_len);
1366 			audit_log_end(ab);
1367 		}
1368 	}
1369 
1370 	for (aux = context->aux_pids; aux; aux = aux->next) {
1371 		struct audit_aux_data_pids *axs = (void *)aux;
1372 
1373 		for (i = 0; i < axs->pid_count; i++)
1374 			if (audit_log_pid_context(context, axs->target_pid[i],
1375 						  axs->target_auid[i],
1376 						  axs->target_uid[i],
1377 						  axs->target_sessionid[i],
1378 						  axs->target_sid[i],
1379 						  axs->target_comm[i]))
1380 				call_panic = 1;
1381 	}
1382 
1383 	if (context->target_pid &&
1384 	    audit_log_pid_context(context, context->target_pid,
1385 				  context->target_auid, context->target_uid,
1386 				  context->target_sessionid,
1387 				  context->target_sid, context->target_comm))
1388 			call_panic = 1;
1389 
1390 	if (context->pwd.dentry && context->pwd.mnt) {
1391 		ab = audit_log_start(context, GFP_KERNEL, AUDIT_CWD);
1392 		if (ab) {
1393 			audit_log_d_path(ab, " cwd=", &context->pwd);
1394 			audit_log_end(ab);
1395 		}
1396 	}
1397 
1398 	i = 0;
1399 	list_for_each_entry(n, &context->names_list, list)
1400 		audit_log_name(context, n, NULL, i++, &call_panic);
1401 
1402 	/* Send end of event record to help user space know we are finished */
1403 	ab = audit_log_start(context, GFP_KERNEL, AUDIT_EOE);
1404 	if (ab)
1405 		audit_log_end(ab);
1406 	if (call_panic)
1407 		audit_panic("error converting sid to string");
1408 }
1409 
1410 /**
1411  * audit_free - free a per-task audit context
1412  * @tsk: task whose audit context block to free
1413  *
1414  * Called from copy_process and do_exit
1415  */
__audit_free(struct task_struct * tsk)1416 void __audit_free(struct task_struct *tsk)
1417 {
1418 	struct audit_context *context;
1419 
1420 	context = audit_get_context(tsk, 0, 0);
1421 	if (!context)
1422 		return;
1423 
1424 	/* Check for system calls that do not go through the exit
1425 	 * function (e.g., exit_group), then free context block.
1426 	 * We use GFP_ATOMIC here because we might be doing this
1427 	 * in the context of the idle thread */
1428 	/* that can happen only if we are called from do_exit() */
1429 	if (context->in_syscall && context->current_state == AUDIT_RECORD_CONTEXT)
1430 		audit_log_exit(context, tsk);
1431 	if (!list_empty(&context->killed_trees))
1432 		audit_kill_trees(&context->killed_trees);
1433 
1434 	audit_free_context(context);
1435 }
1436 
1437 /**
1438  * audit_syscall_entry - fill in an audit record at syscall entry
1439  * @arch: architecture type
1440  * @major: major syscall type (function)
1441  * @a1: additional syscall register 1
1442  * @a2: additional syscall register 2
1443  * @a3: additional syscall register 3
1444  * @a4: additional syscall register 4
1445  *
1446  * Fill in audit context at syscall entry.  This only happens if the
1447  * audit context was created when the task was created and the state or
1448  * filters demand the audit context be built.  If the state from the
1449  * per-task filter or from the per-syscall filter is AUDIT_RECORD_CONTEXT,
1450  * then the record will be written at syscall exit time (otherwise, it
1451  * will only be written if another part of the kernel requests that it
1452  * be written).
1453  */
__audit_syscall_entry(int arch,int major,unsigned long a1,unsigned long a2,unsigned long a3,unsigned long a4)1454 void __audit_syscall_entry(int arch, int major,
1455 			 unsigned long a1, unsigned long a2,
1456 			 unsigned long a3, unsigned long a4)
1457 {
1458 	struct task_struct *tsk = current;
1459 	struct audit_context *context = tsk->audit_context;
1460 	enum audit_state     state;
1461 
1462 	if (!context)
1463 		return;
1464 
1465 	BUG_ON(context->in_syscall || context->name_count);
1466 
1467 	if (!audit_enabled)
1468 		return;
1469 
1470 	context->arch	    = arch;
1471 	context->major      = major;
1472 	context->argv[0]    = a1;
1473 	context->argv[1]    = a2;
1474 	context->argv[2]    = a3;
1475 	context->argv[3]    = a4;
1476 
1477 	state = context->state;
1478 	context->dummy = !audit_n_rules;
1479 	if (!context->dummy && state == AUDIT_BUILD_CONTEXT) {
1480 		context->prio = 0;
1481 		state = audit_filter_syscall(tsk, context, &audit_filter_list[AUDIT_FILTER_ENTRY]);
1482 	}
1483 	if (state == AUDIT_DISABLED)
1484 		return;
1485 
1486 	context->serial     = 0;
1487 	context->ctime      = CURRENT_TIME;
1488 	context->in_syscall = 1;
1489 	context->current_state  = state;
1490 	context->ppid       = 0;
1491 }
1492 
1493 /**
1494  * audit_syscall_exit - deallocate audit context after a system call
1495  * @success: success value of the syscall
1496  * @return_code: return value of the syscall
1497  *
1498  * Tear down after system call.  If the audit context has been marked as
1499  * auditable (either because of the AUDIT_RECORD_CONTEXT state from
1500  * filtering, or because some other part of the kernel wrote an audit
1501  * message), then write out the syscall information.  In call cases,
1502  * free the names stored from getname().
1503  */
__audit_syscall_exit(int success,long return_code)1504 void __audit_syscall_exit(int success, long return_code)
1505 {
1506 	struct task_struct *tsk = current;
1507 	struct audit_context *context;
1508 
1509 	if (success)
1510 		success = AUDITSC_SUCCESS;
1511 	else
1512 		success = AUDITSC_FAILURE;
1513 
1514 	context = audit_get_context(tsk, success, return_code);
1515 	if (!context)
1516 		return;
1517 
1518 	if (context->in_syscall && context->current_state == AUDIT_RECORD_CONTEXT)
1519 		audit_log_exit(context, tsk);
1520 
1521 	context->in_syscall = 0;
1522 	context->prio = context->state == AUDIT_RECORD_CONTEXT ? ~0ULL : 0;
1523 
1524 	if (!list_empty(&context->killed_trees))
1525 		audit_kill_trees(&context->killed_trees);
1526 
1527 	audit_free_names(context);
1528 	unroll_tree_refs(context, NULL, 0);
1529 	audit_free_aux(context);
1530 	context->aux = NULL;
1531 	context->aux_pids = NULL;
1532 	context->target_pid = 0;
1533 	context->target_sid = 0;
1534 	context->sockaddr_len = 0;
1535 	context->type = 0;
1536 	context->fds[0] = -1;
1537 	if (context->state != AUDIT_RECORD_CONTEXT) {
1538 		kfree(context->filterkey);
1539 		context->filterkey = NULL;
1540 	}
1541 	tsk->audit_context = context;
1542 }
1543 
handle_one(const struct inode * inode)1544 static inline void handle_one(const struct inode *inode)
1545 {
1546 #ifdef CONFIG_AUDIT_TREE
1547 	struct audit_context *context;
1548 	struct audit_tree_refs *p;
1549 	struct audit_chunk *chunk;
1550 	int count;
1551 	if (likely(hlist_empty(&inode->i_fsnotify_marks)))
1552 		return;
1553 	context = current->audit_context;
1554 	p = context->trees;
1555 	count = context->tree_count;
1556 	rcu_read_lock();
1557 	chunk = audit_tree_lookup(inode);
1558 	rcu_read_unlock();
1559 	if (!chunk)
1560 		return;
1561 	if (likely(put_tree_ref(context, chunk)))
1562 		return;
1563 	if (unlikely(!grow_tree_refs(context))) {
1564 		printk(KERN_WARNING "out of memory, audit has lost a tree reference\n");
1565 		audit_set_auditable(context);
1566 		audit_put_chunk(chunk);
1567 		unroll_tree_refs(context, p, count);
1568 		return;
1569 	}
1570 	put_tree_ref(context, chunk);
1571 #endif
1572 }
1573 
handle_path(const struct dentry * dentry)1574 static void handle_path(const struct dentry *dentry)
1575 {
1576 #ifdef CONFIG_AUDIT_TREE
1577 	struct audit_context *context;
1578 	struct audit_tree_refs *p;
1579 	const struct dentry *d, *parent;
1580 	struct audit_chunk *drop;
1581 	unsigned long seq;
1582 	int count;
1583 
1584 	context = current->audit_context;
1585 	p = context->trees;
1586 	count = context->tree_count;
1587 retry:
1588 	drop = NULL;
1589 	d = dentry;
1590 	rcu_read_lock();
1591 	seq = read_seqbegin(&rename_lock);
1592 	for(;;) {
1593 		struct inode *inode = d->d_inode;
1594 		if (inode && unlikely(!hlist_empty(&inode->i_fsnotify_marks))) {
1595 			struct audit_chunk *chunk;
1596 			chunk = audit_tree_lookup(inode);
1597 			if (chunk) {
1598 				if (unlikely(!put_tree_ref(context, chunk))) {
1599 					drop = chunk;
1600 					break;
1601 				}
1602 			}
1603 		}
1604 		parent = d->d_parent;
1605 		if (parent == d)
1606 			break;
1607 		d = parent;
1608 	}
1609 	if (unlikely(read_seqretry(&rename_lock, seq) || drop)) {  /* in this order */
1610 		rcu_read_unlock();
1611 		if (!drop) {
1612 			/* just a race with rename */
1613 			unroll_tree_refs(context, p, count);
1614 			goto retry;
1615 		}
1616 		audit_put_chunk(drop);
1617 		if (grow_tree_refs(context)) {
1618 			/* OK, got more space */
1619 			unroll_tree_refs(context, p, count);
1620 			goto retry;
1621 		}
1622 		/* too bad */
1623 		printk(KERN_WARNING
1624 			"out of memory, audit has lost a tree reference\n");
1625 		unroll_tree_refs(context, p, count);
1626 		audit_set_auditable(context);
1627 		return;
1628 	}
1629 	rcu_read_unlock();
1630 #endif
1631 }
1632 
audit_alloc_name(struct audit_context * context,unsigned char type)1633 static struct audit_names *audit_alloc_name(struct audit_context *context,
1634 						unsigned char type)
1635 {
1636 	struct audit_names *aname;
1637 
1638 	if (context->name_count < AUDIT_NAMES) {
1639 		aname = &context->preallocated_names[context->name_count];
1640 		memset(aname, 0, sizeof(*aname));
1641 	} else {
1642 		aname = kzalloc(sizeof(*aname), GFP_NOFS);
1643 		if (!aname)
1644 			return NULL;
1645 		aname->should_free = true;
1646 	}
1647 
1648 	aname->ino = (unsigned long)-1;
1649 	aname->type = type;
1650 	list_add_tail(&aname->list, &context->names_list);
1651 
1652 	context->name_count++;
1653 #if AUDIT_DEBUG
1654 	context->ino_count++;
1655 #endif
1656 	return aname;
1657 }
1658 
1659 /**
1660  * audit_reusename - fill out filename with info from existing entry
1661  * @uptr: userland ptr to pathname
1662  *
1663  * Search the audit_names list for the current audit context. If there is an
1664  * existing entry with a matching "uptr" then return the filename
1665  * associated with that audit_name. If not, return NULL.
1666  */
1667 struct filename *
__audit_reusename(const __user char * uptr)1668 __audit_reusename(const __user char *uptr)
1669 {
1670 	struct audit_context *context = current->audit_context;
1671 	struct audit_names *n;
1672 
1673 	list_for_each_entry(n, &context->names_list, list) {
1674 		if (!n->name)
1675 			continue;
1676 		if (n->name->uptr == uptr)
1677 			return n->name;
1678 	}
1679 	return NULL;
1680 }
1681 
1682 /**
1683  * audit_getname - add a name to the list
1684  * @name: name to add
1685  *
1686  * Add a name to the list of audit names for this context.
1687  * Called from fs/namei.c:getname().
1688  */
__audit_getname(struct filename * name)1689 void __audit_getname(struct filename *name)
1690 {
1691 	struct audit_context *context = current->audit_context;
1692 	struct audit_names *n;
1693 
1694 	if (!context->in_syscall) {
1695 #if AUDIT_DEBUG == 2
1696 		printk(KERN_ERR "%s:%d(:%d): ignoring getname(%p)\n",
1697 		       __FILE__, __LINE__, context->serial, name);
1698 		dump_stack();
1699 #endif
1700 		return;
1701 	}
1702 
1703 #if AUDIT_DEBUG
1704 	/* The filename _must_ have a populated ->name */
1705 	BUG_ON(!name->name);
1706 #endif
1707 
1708 	n = audit_alloc_name(context, AUDIT_TYPE_UNKNOWN);
1709 	if (!n)
1710 		return;
1711 
1712 	n->name = name;
1713 	n->name_len = AUDIT_NAME_FULL;
1714 	n->name_put = true;
1715 	name->aname = n;
1716 
1717 	if (!context->pwd.dentry)
1718 		get_fs_pwd(current->fs, &context->pwd);
1719 }
1720 
1721 /* audit_putname - intercept a putname request
1722  * @name: name to intercept and delay for putname
1723  *
1724  * If we have stored the name from getname in the audit context,
1725  * then we delay the putname until syscall exit.
1726  * Called from include/linux/fs.h:putname().
1727  */
audit_putname(struct filename * name)1728 void audit_putname(struct filename *name)
1729 {
1730 	struct audit_context *context = current->audit_context;
1731 
1732 	BUG_ON(!context);
1733 	if (!context->in_syscall) {
1734 #if AUDIT_DEBUG == 2
1735 		printk(KERN_ERR "%s:%d(:%d): final_putname(%p)\n",
1736 		       __FILE__, __LINE__, context->serial, name);
1737 		if (context->name_count) {
1738 			struct audit_names *n;
1739 			int i = 0;
1740 
1741 			list_for_each_entry(n, &context->names_list, list)
1742 				printk(KERN_ERR "name[%d] = %p = %s\n", i++,
1743 				       n->name, n->name->name ?: "(null)");
1744 			}
1745 #endif
1746 		final_putname(name);
1747 	}
1748 #if AUDIT_DEBUG
1749 	else {
1750 		++context->put_count;
1751 		if (context->put_count > context->name_count) {
1752 			printk(KERN_ERR "%s:%d(:%d): major=%d"
1753 			       " in_syscall=%d putname(%p) name_count=%d"
1754 			       " put_count=%d\n",
1755 			       __FILE__, __LINE__,
1756 			       context->serial, context->major,
1757 			       context->in_syscall, name->name,
1758 			       context->name_count, context->put_count);
1759 			dump_stack();
1760 		}
1761 	}
1762 #endif
1763 }
1764 
1765 /**
1766  * __audit_inode - store the inode and device from a lookup
1767  * @name: name being audited
1768  * @dentry: dentry being audited
1769  * @parent: does this dentry represent the parent?
1770  */
__audit_inode(struct filename * name,const struct dentry * dentry,unsigned int parent)1771 void __audit_inode(struct filename *name, const struct dentry *dentry,
1772 		   unsigned int parent)
1773 {
1774 	struct audit_context *context = current->audit_context;
1775 	const struct inode *inode = dentry->d_inode;
1776 	struct audit_names *n;
1777 
1778 	if (!context->in_syscall)
1779 		return;
1780 
1781 	if (!name)
1782 		goto out_alloc;
1783 
1784 #if AUDIT_DEBUG
1785 	/* The struct filename _must_ have a populated ->name */
1786 	BUG_ON(!name->name);
1787 #endif
1788 	/*
1789 	 * If we have a pointer to an audit_names entry already, then we can
1790 	 * just use it directly if the type is correct.
1791 	 */
1792 	n = name->aname;
1793 	if (n) {
1794 		if (parent) {
1795 			if (n->type == AUDIT_TYPE_PARENT ||
1796 			    n->type == AUDIT_TYPE_UNKNOWN)
1797 				goto out;
1798 		} else {
1799 			if (n->type != AUDIT_TYPE_PARENT)
1800 				goto out;
1801 		}
1802 	}
1803 
1804 	list_for_each_entry_reverse(n, &context->names_list, list) {
1805 		/* does the name pointer match? */
1806 		if (!n->name || n->name->name != name->name)
1807 			continue;
1808 
1809 		/* match the correct record type */
1810 		if (parent) {
1811 			if (n->type == AUDIT_TYPE_PARENT ||
1812 			    n->type == AUDIT_TYPE_UNKNOWN)
1813 				goto out;
1814 		} else {
1815 			if (n->type != AUDIT_TYPE_PARENT)
1816 				goto out;
1817 		}
1818 	}
1819 
1820 out_alloc:
1821 	/* unable to find the name from a previous getname(). Allocate a new
1822 	 * anonymous entry.
1823 	 */
1824 	n = audit_alloc_name(context, AUDIT_TYPE_NORMAL);
1825 	if (!n)
1826 		return;
1827 out:
1828 	if (parent) {
1829 		n->name_len = n->name ? parent_len(n->name->name) : AUDIT_NAME_FULL;
1830 		n->type = AUDIT_TYPE_PARENT;
1831 	} else {
1832 		n->name_len = AUDIT_NAME_FULL;
1833 		n->type = AUDIT_TYPE_NORMAL;
1834 	}
1835 	handle_path(dentry);
1836 	audit_copy_inode(n, dentry, inode);
1837 }
1838 
1839 /**
1840  * __audit_inode_child - collect inode info for created/removed objects
1841  * @parent: inode of dentry parent
1842  * @dentry: dentry being audited
1843  * @type:   AUDIT_TYPE_* value that we're looking for
1844  *
1845  * For syscalls that create or remove filesystem objects, audit_inode
1846  * can only collect information for the filesystem object's parent.
1847  * This call updates the audit context with the child's information.
1848  * Syscalls that create a new filesystem object must be hooked after
1849  * the object is created.  Syscalls that remove a filesystem object
1850  * must be hooked prior, in order to capture the target inode during
1851  * unsuccessful attempts.
1852  */
__audit_inode_child(const struct inode * parent,const struct dentry * dentry,const unsigned char type)1853 void __audit_inode_child(const struct inode *parent,
1854 			 const struct dentry *dentry,
1855 			 const unsigned char type)
1856 {
1857 	struct audit_context *context = current->audit_context;
1858 	const struct inode *inode = dentry->d_inode;
1859 	const char *dname = dentry->d_name.name;
1860 	struct audit_names *n, *found_parent = NULL, *found_child = NULL;
1861 
1862 	if (!context->in_syscall)
1863 		return;
1864 
1865 	if (inode)
1866 		handle_one(inode);
1867 
1868 	/* look for a parent entry first */
1869 	list_for_each_entry(n, &context->names_list, list) {
1870 		if (!n->name || n->type != AUDIT_TYPE_PARENT)
1871 			continue;
1872 
1873 		if (n->ino == parent->i_ino &&
1874 		    !audit_compare_dname_path(dname, n->name->name, n->name_len)) {
1875 			found_parent = n;
1876 			break;
1877 		}
1878 	}
1879 
1880 	/* is there a matching child entry? */
1881 	list_for_each_entry(n, &context->names_list, list) {
1882 		/* can only match entries that have a name */
1883 		if (!n->name || n->type != type)
1884 			continue;
1885 
1886 		/* if we found a parent, make sure this one is a child of it */
1887 		if (found_parent && (n->name != found_parent->name))
1888 			continue;
1889 
1890 		if (!strcmp(dname, n->name->name) ||
1891 		    !audit_compare_dname_path(dname, n->name->name,
1892 						found_parent ?
1893 						found_parent->name_len :
1894 						AUDIT_NAME_FULL)) {
1895 			found_child = n;
1896 			break;
1897 		}
1898 	}
1899 
1900 	if (!found_parent) {
1901 		/* create a new, "anonymous" parent record */
1902 		n = audit_alloc_name(context, AUDIT_TYPE_PARENT);
1903 		if (!n)
1904 			return;
1905 		audit_copy_inode(n, NULL, parent);
1906 	}
1907 
1908 	if (!found_child) {
1909 		found_child = audit_alloc_name(context, type);
1910 		if (!found_child)
1911 			return;
1912 
1913 		/* Re-use the name belonging to the slot for a matching parent
1914 		 * directory. All names for this context are relinquished in
1915 		 * audit_free_names() */
1916 		if (found_parent) {
1917 			found_child->name = found_parent->name;
1918 			found_child->name_len = AUDIT_NAME_FULL;
1919 			/* don't call __putname() */
1920 			found_child->name_put = false;
1921 		}
1922 	}
1923 	if (inode)
1924 		audit_copy_inode(found_child, dentry, inode);
1925 	else
1926 		found_child->ino = (unsigned long)-1;
1927 }
1928 EXPORT_SYMBOL_GPL(__audit_inode_child);
1929 
1930 /**
1931  * auditsc_get_stamp - get local copies of audit_context values
1932  * @ctx: audit_context for the task
1933  * @t: timespec to store time recorded in the audit_context
1934  * @serial: serial value that is recorded in the audit_context
1935  *
1936  * Also sets the context as auditable.
1937  */
auditsc_get_stamp(struct audit_context * ctx,struct timespec * t,unsigned int * serial)1938 int auditsc_get_stamp(struct audit_context *ctx,
1939 		       struct timespec *t, unsigned int *serial)
1940 {
1941 	if (!ctx->in_syscall)
1942 		return 0;
1943 	if (!ctx->serial)
1944 		ctx->serial = audit_serial();
1945 	t->tv_sec  = ctx->ctime.tv_sec;
1946 	t->tv_nsec = ctx->ctime.tv_nsec;
1947 	*serial    = ctx->serial;
1948 	if (!ctx->prio) {
1949 		ctx->prio = 1;
1950 		ctx->current_state = AUDIT_RECORD_CONTEXT;
1951 	}
1952 	return 1;
1953 }
1954 
1955 /* global counter which is incremented every time something logs in */
1956 static atomic_t session_id = ATOMIC_INIT(0);
1957 
1958 /**
1959  * audit_set_loginuid - set current task's audit_context loginuid
1960  * @loginuid: loginuid value
1961  *
1962  * Returns 0.
1963  *
1964  * Called (set) from fs/proc/base.c::proc_loginuid_write().
1965  */
audit_set_loginuid(kuid_t loginuid)1966 int audit_set_loginuid(kuid_t loginuid)
1967 {
1968 	struct task_struct *task = current;
1969 	struct audit_context *context = task->audit_context;
1970 	unsigned int sessionid;
1971 
1972 #ifdef CONFIG_AUDIT_LOGINUID_IMMUTABLE
1973 	if (audit_loginuid_set(task))
1974 		return -EPERM;
1975 #else /* CONFIG_AUDIT_LOGINUID_IMMUTABLE */
1976 	if (!capable(CAP_AUDIT_CONTROL))
1977 		return -EPERM;
1978 #endif  /* CONFIG_AUDIT_LOGINUID_IMMUTABLE */
1979 
1980 	sessionid = atomic_inc_return(&session_id);
1981 	if (context && context->in_syscall) {
1982 		struct audit_buffer *ab;
1983 
1984 		ab = audit_log_start(NULL, GFP_KERNEL, AUDIT_LOGIN);
1985 		if (ab) {
1986 			audit_log_format(ab, "login pid=%d uid=%u "
1987 				"old auid=%u new auid=%u"
1988 				" old ses=%u new ses=%u",
1989 				task_tgid_nr(task),
1990 				from_kuid(&init_user_ns, task_uid(task)),
1991 				from_kuid(&init_user_ns, task->loginuid),
1992 				from_kuid(&init_user_ns, loginuid),
1993 				task->sessionid, sessionid);
1994 			audit_log_end(ab);
1995 		}
1996 	}
1997 	task->sessionid = sessionid;
1998 	task->loginuid = loginuid;
1999 	return 0;
2000 }
2001 
2002 /**
2003  * __audit_mq_open - record audit data for a POSIX MQ open
2004  * @oflag: open flag
2005  * @mode: mode bits
2006  * @attr: queue attributes
2007  *
2008  */
__audit_mq_open(int oflag,umode_t mode,struct mq_attr * attr)2009 void __audit_mq_open(int oflag, umode_t mode, struct mq_attr *attr)
2010 {
2011 	struct audit_context *context = current->audit_context;
2012 
2013 	if (attr)
2014 		memcpy(&context->mq_open.attr, attr, sizeof(struct mq_attr));
2015 	else
2016 		memset(&context->mq_open.attr, 0, sizeof(struct mq_attr));
2017 
2018 	context->mq_open.oflag = oflag;
2019 	context->mq_open.mode = mode;
2020 
2021 	context->type = AUDIT_MQ_OPEN;
2022 }
2023 
2024 /**
2025  * __audit_mq_sendrecv - record audit data for a POSIX MQ timed send/receive
2026  * @mqdes: MQ descriptor
2027  * @msg_len: Message length
2028  * @msg_prio: Message priority
2029  * @abs_timeout: Message timeout in absolute time
2030  *
2031  */
__audit_mq_sendrecv(mqd_t mqdes,size_t msg_len,unsigned int msg_prio,const struct timespec * abs_timeout)2032 void __audit_mq_sendrecv(mqd_t mqdes, size_t msg_len, unsigned int msg_prio,
2033 			const struct timespec *abs_timeout)
2034 {
2035 	struct audit_context *context = current->audit_context;
2036 	struct timespec *p = &context->mq_sendrecv.abs_timeout;
2037 
2038 	if (abs_timeout)
2039 		memcpy(p, abs_timeout, sizeof(struct timespec));
2040 	else
2041 		memset(p, 0, sizeof(struct timespec));
2042 
2043 	context->mq_sendrecv.mqdes = mqdes;
2044 	context->mq_sendrecv.msg_len = msg_len;
2045 	context->mq_sendrecv.msg_prio = msg_prio;
2046 
2047 	context->type = AUDIT_MQ_SENDRECV;
2048 }
2049 
2050 /**
2051  * __audit_mq_notify - record audit data for a POSIX MQ notify
2052  * @mqdes: MQ descriptor
2053  * @notification: Notification event
2054  *
2055  */
2056 
__audit_mq_notify(mqd_t mqdes,const struct sigevent * notification)2057 void __audit_mq_notify(mqd_t mqdes, const struct sigevent *notification)
2058 {
2059 	struct audit_context *context = current->audit_context;
2060 
2061 	if (notification)
2062 		context->mq_notify.sigev_signo = notification->sigev_signo;
2063 	else
2064 		context->mq_notify.sigev_signo = 0;
2065 
2066 	context->mq_notify.mqdes = mqdes;
2067 	context->type = AUDIT_MQ_NOTIFY;
2068 }
2069 
2070 /**
2071  * __audit_mq_getsetattr - record audit data for a POSIX MQ get/set attribute
2072  * @mqdes: MQ descriptor
2073  * @mqstat: MQ flags
2074  *
2075  */
__audit_mq_getsetattr(mqd_t mqdes,struct mq_attr * mqstat)2076 void __audit_mq_getsetattr(mqd_t mqdes, struct mq_attr *mqstat)
2077 {
2078 	struct audit_context *context = current->audit_context;
2079 	context->mq_getsetattr.mqdes = mqdes;
2080 	context->mq_getsetattr.mqstat = *mqstat;
2081 	context->type = AUDIT_MQ_GETSETATTR;
2082 }
2083 
2084 /**
2085  * audit_ipc_obj - record audit data for ipc object
2086  * @ipcp: ipc permissions
2087  *
2088  */
__audit_ipc_obj(struct kern_ipc_perm * ipcp)2089 void __audit_ipc_obj(struct kern_ipc_perm *ipcp)
2090 {
2091 	struct audit_context *context = current->audit_context;
2092 	context->ipc.uid = ipcp->uid;
2093 	context->ipc.gid = ipcp->gid;
2094 	context->ipc.mode = ipcp->mode;
2095 	context->ipc.has_perm = 0;
2096 	security_ipc_getsecid(ipcp, &context->ipc.osid);
2097 	context->type = AUDIT_IPC;
2098 }
2099 
2100 /**
2101  * audit_ipc_set_perm - record audit data for new ipc permissions
2102  * @qbytes: msgq bytes
2103  * @uid: msgq user id
2104  * @gid: msgq group id
2105  * @mode: msgq mode (permissions)
2106  *
2107  * Called only after audit_ipc_obj().
2108  */
__audit_ipc_set_perm(unsigned long qbytes,uid_t uid,gid_t gid,umode_t mode)2109 void __audit_ipc_set_perm(unsigned long qbytes, uid_t uid, gid_t gid, umode_t mode)
2110 {
2111 	struct audit_context *context = current->audit_context;
2112 
2113 	context->ipc.qbytes = qbytes;
2114 	context->ipc.perm_uid = uid;
2115 	context->ipc.perm_gid = gid;
2116 	context->ipc.perm_mode = mode;
2117 	context->ipc.has_perm = 1;
2118 }
2119 
__audit_bprm(struct linux_binprm * bprm)2120 int __audit_bprm(struct linux_binprm *bprm)
2121 {
2122 	struct audit_aux_data_execve *ax;
2123 	struct audit_context *context = current->audit_context;
2124 
2125 	ax = kmalloc(sizeof(*ax), GFP_KERNEL);
2126 	if (!ax)
2127 		return -ENOMEM;
2128 
2129 	ax->argc = bprm->argc;
2130 	ax->envc = bprm->envc;
2131 	ax->mm = bprm->mm;
2132 	ax->d.type = AUDIT_EXECVE;
2133 	ax->d.next = context->aux;
2134 	context->aux = (void *)ax;
2135 	return 0;
2136 }
2137 
2138 
2139 /**
2140  * audit_socketcall - record audit data for sys_socketcall
2141  * @nargs: number of args, which should not be more than AUDITSC_ARGS.
2142  * @args: args array
2143  *
2144  */
__audit_socketcall(int nargs,unsigned long * args)2145 int __audit_socketcall(int nargs, unsigned long *args)
2146 {
2147 	struct audit_context *context = current->audit_context;
2148 
2149 	if (nargs <= 0 || nargs > AUDITSC_ARGS || !args)
2150 		return -EINVAL;
2151 	context->type = AUDIT_SOCKETCALL;
2152 	context->socketcall.nargs = nargs;
2153 	memcpy(context->socketcall.args, args, nargs * sizeof(unsigned long));
2154 	return 0;
2155 }
2156 
2157 /**
2158  * __audit_fd_pair - record audit data for pipe and socketpair
2159  * @fd1: the first file descriptor
2160  * @fd2: the second file descriptor
2161  *
2162  */
__audit_fd_pair(int fd1,int fd2)2163 void __audit_fd_pair(int fd1, int fd2)
2164 {
2165 	struct audit_context *context = current->audit_context;
2166 	context->fds[0] = fd1;
2167 	context->fds[1] = fd2;
2168 }
2169 
2170 /**
2171  * audit_sockaddr - record audit data for sys_bind, sys_connect, sys_sendto
2172  * @len: data length in user space
2173  * @a: data address in kernel space
2174  *
2175  * Returns 0 for success or NULL context or < 0 on error.
2176  */
__audit_sockaddr(int len,void * a)2177 int __audit_sockaddr(int len, void *a)
2178 {
2179 	struct audit_context *context = current->audit_context;
2180 
2181 	if (!context->sockaddr) {
2182 		void *p = kmalloc(sizeof(struct sockaddr_storage), GFP_KERNEL);
2183 		if (!p)
2184 			return -ENOMEM;
2185 		context->sockaddr = p;
2186 	}
2187 
2188 	context->sockaddr_len = len;
2189 	memcpy(context->sockaddr, a, len);
2190 	return 0;
2191 }
2192 
__audit_ptrace(struct task_struct * t)2193 void __audit_ptrace(struct task_struct *t)
2194 {
2195 	struct audit_context *context = current->audit_context;
2196 
2197 	context->target_pid = task_tgid_nr(t);
2198 	context->target_auid = audit_get_loginuid(t);
2199 	context->target_uid = task_uid(t);
2200 	context->target_sessionid = audit_get_sessionid(t);
2201 	security_task_getsecid(t, &context->target_sid);
2202 	memcpy(context->target_comm, t->comm, TASK_COMM_LEN);
2203 }
2204 
2205 /**
2206  * audit_signal_info - record signal info for shutting down audit subsystem
2207  * @sig: signal value
2208  * @t: task being signaled
2209  *
2210  * If the audit subsystem is being terminated, record the task (pid)
2211  * and uid that is doing that.
2212  */
__audit_signal_info(int sig,struct task_struct * t)2213 int __audit_signal_info(int sig, struct task_struct *t)
2214 {
2215 	struct audit_aux_data_pids *axp;
2216 	struct task_struct *tsk = current;
2217 	struct audit_context *ctx = tsk->audit_context;
2218 	kuid_t uid = current_uid(), t_uid = task_uid(t);
2219 
2220 	if (audit_pid && t->tgid == audit_pid) {
2221 		if (sig == SIGTERM || sig == SIGHUP || sig == SIGUSR1 || sig == SIGUSR2) {
2222 			audit_sig_pid = task_tgid_nr(tsk);
2223 			if (uid_valid(tsk->loginuid))
2224 				audit_sig_uid = tsk->loginuid;
2225 			else
2226 				audit_sig_uid = uid;
2227 			security_task_getsecid(tsk, &audit_sig_sid);
2228 		}
2229 		if (!audit_signals || audit_dummy_context())
2230 			return 0;
2231 	}
2232 
2233 	/* optimize the common case by putting first signal recipient directly
2234 	 * in audit_context */
2235 	if (!ctx->target_pid) {
2236 		ctx->target_pid = t->tgid;
2237 		ctx->target_auid = audit_get_loginuid(t);
2238 		ctx->target_uid = t_uid;
2239 		ctx->target_sessionid = audit_get_sessionid(t);
2240 		security_task_getsecid(t, &ctx->target_sid);
2241 		memcpy(ctx->target_comm, t->comm, TASK_COMM_LEN);
2242 		return 0;
2243 	}
2244 
2245 	axp = (void *)ctx->aux_pids;
2246 	if (!axp || axp->pid_count == AUDIT_AUX_PIDS) {
2247 		axp = kzalloc(sizeof(*axp), GFP_ATOMIC);
2248 		if (!axp)
2249 			return -ENOMEM;
2250 
2251 		axp->d.type = AUDIT_OBJ_PID;
2252 		axp->d.next = ctx->aux_pids;
2253 		ctx->aux_pids = (void *)axp;
2254 	}
2255 	BUG_ON(axp->pid_count >= AUDIT_AUX_PIDS);
2256 
2257 	axp->target_pid[axp->pid_count] = t->tgid;
2258 	axp->target_auid[axp->pid_count] = audit_get_loginuid(t);
2259 	axp->target_uid[axp->pid_count] = t_uid;
2260 	axp->target_sessionid[axp->pid_count] = audit_get_sessionid(t);
2261 	security_task_getsecid(t, &axp->target_sid[axp->pid_count]);
2262 	memcpy(axp->target_comm[axp->pid_count], t->comm, TASK_COMM_LEN);
2263 	axp->pid_count++;
2264 
2265 	return 0;
2266 }
2267 
2268 /**
2269  * __audit_log_bprm_fcaps - store information about a loading bprm and relevant fcaps
2270  * @bprm: pointer to the bprm being processed
2271  * @new: the proposed new credentials
2272  * @old: the old credentials
2273  *
2274  * Simply check if the proc already has the caps given by the file and if not
2275  * store the priv escalation info for later auditing at the end of the syscall
2276  *
2277  * -Eric
2278  */
__audit_log_bprm_fcaps(struct linux_binprm * bprm,const struct cred * new,const struct cred * old)2279 int __audit_log_bprm_fcaps(struct linux_binprm *bprm,
2280 			   const struct cred *new, const struct cred *old)
2281 {
2282 	struct audit_aux_data_bprm_fcaps *ax;
2283 	struct audit_context *context = current->audit_context;
2284 	struct cpu_vfs_cap_data vcaps;
2285 	struct dentry *dentry;
2286 
2287 	ax = kmalloc(sizeof(*ax), GFP_KERNEL);
2288 	if (!ax)
2289 		return -ENOMEM;
2290 
2291 	ax->d.type = AUDIT_BPRM_FCAPS;
2292 	ax->d.next = context->aux;
2293 	context->aux = (void *)ax;
2294 
2295 	dentry = dget(bprm->file->f_dentry);
2296 	get_vfs_caps_from_disk(dentry, &vcaps);
2297 	dput(dentry);
2298 
2299 	ax->fcap.permitted = vcaps.permitted;
2300 	ax->fcap.inheritable = vcaps.inheritable;
2301 	ax->fcap.fE = !!(vcaps.magic_etc & VFS_CAP_FLAGS_EFFECTIVE);
2302 	ax->fcap_ver = (vcaps.magic_etc & VFS_CAP_REVISION_MASK) >> VFS_CAP_REVISION_SHIFT;
2303 
2304 	ax->old_pcap.permitted   = old->cap_permitted;
2305 	ax->old_pcap.inheritable = old->cap_inheritable;
2306 	ax->old_pcap.effective   = old->cap_effective;
2307 
2308 	ax->new_pcap.permitted   = new->cap_permitted;
2309 	ax->new_pcap.inheritable = new->cap_inheritable;
2310 	ax->new_pcap.effective   = new->cap_effective;
2311 	return 0;
2312 }
2313 
2314 /**
2315  * __audit_log_capset - store information about the arguments to the capset syscall
2316  * @pid: target pid of the capset call
2317  * @new: the new credentials
2318  * @old: the old (current) credentials
2319  *
2320  * Record the aguments userspace sent to sys_capset for later printing by the
2321  * audit system if applicable
2322  */
__audit_log_capset(pid_t pid,const struct cred * new,const struct cred * old)2323 void __audit_log_capset(pid_t pid,
2324 		       const struct cred *new, const struct cred *old)
2325 {
2326 	struct audit_context *context = current->audit_context;
2327 	context->capset.pid = task_tgid_nr(current);
2328 	context->capset.cap.effective   = new->cap_effective;
2329 	context->capset.cap.inheritable = new->cap_effective;
2330 	context->capset.cap.permitted   = new->cap_permitted;
2331 	context->type = AUDIT_CAPSET;
2332 }
2333 
__audit_mmap_fd(int fd,int flags)2334 void __audit_mmap_fd(int fd, int flags)
2335 {
2336 	struct audit_context *context = current->audit_context;
2337 	context->mmap.fd = fd;
2338 	context->mmap.flags = flags;
2339 	context->type = AUDIT_MMAP;
2340 }
2341 
audit_log_task(struct audit_buffer * ab)2342 static void audit_log_task(struct audit_buffer *ab)
2343 {
2344 	kuid_t auid, uid;
2345 	kgid_t gid;
2346 	unsigned int sessionid;
2347 
2348 	auid = audit_get_loginuid(current);
2349 	sessionid = audit_get_sessionid(current);
2350 	current_uid_gid(&uid, &gid);
2351 
2352 	audit_log_format(ab, "auid=%u uid=%u gid=%u ses=%u",
2353 			 from_kuid(&init_user_ns, auid),
2354 			 from_kuid(&init_user_ns, uid),
2355 			 from_kgid(&init_user_ns, gid),
2356 			 sessionid);
2357 	audit_log_task_context(ab);
2358 	audit_log_format(ab, " pid=%d comm=", task_tgid_nr(current));
2359 	audit_log_untrustedstring(ab, current->comm);
2360 }
2361 
audit_log_abend(struct audit_buffer * ab,char * reason,long signr)2362 static void audit_log_abend(struct audit_buffer *ab, char *reason, long signr)
2363 {
2364 	audit_log_task(ab);
2365 	audit_log_format(ab, " reason=");
2366 	audit_log_string(ab, reason);
2367 	audit_log_format(ab, " sig=%ld", signr);
2368 }
2369 /**
2370  * audit_core_dumps - record information about processes that end abnormally
2371  * @signr: signal value
2372  *
2373  * If a process ends with a core dump, something fishy is going on and we
2374  * should record the event for investigation.
2375  */
audit_core_dumps(long signr)2376 void audit_core_dumps(long signr)
2377 {
2378 	struct audit_buffer *ab;
2379 
2380 	if (!audit_enabled)
2381 		return;
2382 
2383 	if (signr == SIGQUIT)	/* don't care for those */
2384 		return;
2385 
2386 	ab = audit_log_start(NULL, GFP_KERNEL, AUDIT_ANOM_ABEND);
2387 	if (unlikely(!ab))
2388 		return;
2389 	audit_log_abend(ab, "memory violation", signr);
2390 	audit_log_end(ab);
2391 }
2392 
__audit_seccomp(unsigned long syscall,long signr,int code)2393 void __audit_seccomp(unsigned long syscall, long signr, int code)
2394 {
2395 	struct audit_buffer *ab;
2396 
2397 	ab = audit_log_start(NULL, GFP_KERNEL, AUDIT_SECCOMP);
2398 	if (unlikely(!ab))
2399 		return;
2400 	audit_log_task(ab);
2401 	audit_log_format(ab, " sig=%ld", signr);
2402 	audit_log_format(ab, " syscall=%ld", syscall);
2403 	audit_log_format(ab, " compat=%d", is_compat_task());
2404 	audit_log_format(ab, " ip=0x%lx", KSTK_EIP(current));
2405 	audit_log_format(ab, " code=0x%x", code);
2406 	audit_log_end(ab);
2407 }
2408 
audit_killed_trees(void)2409 struct list_head *audit_killed_trees(void)
2410 {
2411 	struct audit_context *ctx = current->audit_context;
2412 	if (likely(!ctx || !ctx->in_syscall))
2413 		return NULL;
2414 	return &ctx->killed_trees;
2415 }
2416