xref: /linux/kernel/auditsc.c (revision 606d099cdd1080bbb50ea50dc52d98252f8f10a1)
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 <asm/atomic.h>
48 #include <asm/types.h>
49 #include <linux/fs.h>
50 #include <linux/namei.h>
51 #include <linux/mm.h>
52 #include <linux/module.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/selinux.h>
66 #include <linux/binfmts.h>
67 #include <linux/highmem.h>
68 #include <linux/syscalls.h>
69 
70 #include "audit.h"
71 
72 extern struct list_head audit_filter_list[];
73 
74 /* No syscall auditing will take place unless audit_enabled != 0. */
75 extern int audit_enabled;
76 
77 /* AUDIT_NAMES is the number of slots we reserve in the audit_context
78  * for saving names from getname(). */
79 #define AUDIT_NAMES    20
80 
81 /* AUDIT_NAMES_RESERVED is the number of slots we reserve in the
82  * audit_context from being used for nameless inodes from
83  * path_lookup. */
84 #define AUDIT_NAMES_RESERVED 7
85 
86 /* Indicates that audit should log the full pathname. */
87 #define AUDIT_NAME_FULL -1
88 
89 /* number of audit rules */
90 int audit_n_rules;
91 
92 /* When fs/namei.c:getname() is called, we store the pointer in name and
93  * we don't let putname() free it (instead we free all of the saved
94  * pointers at syscall exit time).
95  *
96  * Further, in fs/namei.c:path_lookup() we store the inode and device. */
97 struct audit_names {
98 	const char	*name;
99 	int		name_len;	/* number of name's characters to log */
100 	unsigned	name_put;	/* call __putname() for this name */
101 	unsigned long	ino;
102 	dev_t		dev;
103 	umode_t		mode;
104 	uid_t		uid;
105 	gid_t		gid;
106 	dev_t		rdev;
107 	u32		osid;
108 };
109 
110 struct audit_aux_data {
111 	struct audit_aux_data	*next;
112 	int			type;
113 };
114 
115 #define AUDIT_AUX_IPCPERM	0
116 
117 struct audit_aux_data_mq_open {
118 	struct audit_aux_data	d;
119 	int			oflag;
120 	mode_t			mode;
121 	struct mq_attr		attr;
122 };
123 
124 struct audit_aux_data_mq_sendrecv {
125 	struct audit_aux_data	d;
126 	mqd_t			mqdes;
127 	size_t			msg_len;
128 	unsigned int		msg_prio;
129 	struct timespec		abs_timeout;
130 };
131 
132 struct audit_aux_data_mq_notify {
133 	struct audit_aux_data	d;
134 	mqd_t			mqdes;
135 	struct sigevent 	notification;
136 };
137 
138 struct audit_aux_data_mq_getsetattr {
139 	struct audit_aux_data	d;
140 	mqd_t			mqdes;
141 	struct mq_attr 		mqstat;
142 };
143 
144 struct audit_aux_data_ipcctl {
145 	struct audit_aux_data	d;
146 	struct ipc_perm		p;
147 	unsigned long		qbytes;
148 	uid_t			uid;
149 	gid_t			gid;
150 	mode_t			mode;
151 	u32			osid;
152 };
153 
154 struct audit_aux_data_execve {
155 	struct audit_aux_data	d;
156 	int argc;
157 	int envc;
158 	char mem[0];
159 };
160 
161 struct audit_aux_data_socketcall {
162 	struct audit_aux_data	d;
163 	int			nargs;
164 	unsigned long		args[0];
165 };
166 
167 struct audit_aux_data_sockaddr {
168 	struct audit_aux_data	d;
169 	int			len;
170 	char			a[0];
171 };
172 
173 struct audit_aux_data_path {
174 	struct audit_aux_data	d;
175 	struct dentry		*dentry;
176 	struct vfsmount		*mnt;
177 };
178 
179 /* The per-task audit context. */
180 struct audit_context {
181 	int		    dummy;	/* must be the first element */
182 	int		    in_syscall;	/* 1 if task is in a syscall */
183 	enum audit_state    state;
184 	unsigned int	    serial;     /* serial number for record */
185 	struct timespec	    ctime;      /* time of syscall entry */
186 	uid_t		    loginuid;   /* login uid (identity) */
187 	int		    major;      /* syscall number */
188 	unsigned long	    argv[4];    /* syscall arguments */
189 	int		    return_valid; /* return code is valid */
190 	long		    return_code;/* syscall return code */
191 	int		    auditable;  /* 1 if record should be written */
192 	int		    name_count;
193 	struct audit_names  names[AUDIT_NAMES];
194 	char *		    filterkey;	/* key for rule that triggered record */
195 	struct dentry *	    pwd;
196 	struct vfsmount *   pwdmnt;
197 	struct audit_context *previous; /* For nested syscalls */
198 	struct audit_aux_data *aux;
199 
200 				/* Save things to print about task_struct */
201 	pid_t		    pid, ppid;
202 	uid_t		    uid, euid, suid, fsuid;
203 	gid_t		    gid, egid, sgid, fsgid;
204 	unsigned long	    personality;
205 	int		    arch;
206 
207 #if AUDIT_DEBUG
208 	int		    put_count;
209 	int		    ino_count;
210 #endif
211 };
212 
213 #define ACC_MODE(x) ("\004\002\006\006"[(x)&O_ACCMODE])
214 static inline int open_arg(int flags, int mask)
215 {
216 	int n = ACC_MODE(flags);
217 	if (flags & (O_TRUNC | O_CREAT))
218 		n |= AUDIT_PERM_WRITE;
219 	return n & mask;
220 }
221 
222 static int audit_match_perm(struct audit_context *ctx, int mask)
223 {
224 	unsigned n = ctx->major;
225 	switch (audit_classify_syscall(ctx->arch, n)) {
226 	case 0:	/* native */
227 		if ((mask & AUDIT_PERM_WRITE) &&
228 		     audit_match_class(AUDIT_CLASS_WRITE, n))
229 			return 1;
230 		if ((mask & AUDIT_PERM_READ) &&
231 		     audit_match_class(AUDIT_CLASS_READ, n))
232 			return 1;
233 		if ((mask & AUDIT_PERM_ATTR) &&
234 		     audit_match_class(AUDIT_CLASS_CHATTR, n))
235 			return 1;
236 		return 0;
237 	case 1: /* 32bit on biarch */
238 		if ((mask & AUDIT_PERM_WRITE) &&
239 		     audit_match_class(AUDIT_CLASS_WRITE_32, n))
240 			return 1;
241 		if ((mask & AUDIT_PERM_READ) &&
242 		     audit_match_class(AUDIT_CLASS_READ_32, n))
243 			return 1;
244 		if ((mask & AUDIT_PERM_ATTR) &&
245 		     audit_match_class(AUDIT_CLASS_CHATTR_32, n))
246 			return 1;
247 		return 0;
248 	case 2: /* open */
249 		return mask & ACC_MODE(ctx->argv[1]);
250 	case 3: /* openat */
251 		return mask & ACC_MODE(ctx->argv[2]);
252 	case 4: /* socketcall */
253 		return ((mask & AUDIT_PERM_WRITE) && ctx->argv[0] == SYS_BIND);
254 	case 5: /* execve */
255 		return mask & AUDIT_PERM_EXEC;
256 	default:
257 		return 0;
258 	}
259 }
260 
261 /* Determine if any context name data matches a rule's watch data */
262 /* Compare a task_struct with an audit_rule.  Return 1 on match, 0
263  * otherwise. */
264 static int audit_filter_rules(struct task_struct *tsk,
265 			      struct audit_krule *rule,
266 			      struct audit_context *ctx,
267 			      struct audit_names *name,
268 			      enum audit_state *state)
269 {
270 	int i, j, need_sid = 1;
271 	u32 sid;
272 
273 	for (i = 0; i < rule->field_count; i++) {
274 		struct audit_field *f = &rule->fields[i];
275 		int result = 0;
276 
277 		switch (f->type) {
278 		case AUDIT_PID:
279 			result = audit_comparator(tsk->pid, f->op, f->val);
280 			break;
281 		case AUDIT_PPID:
282 			if (ctx) {
283 				if (!ctx->ppid)
284 					ctx->ppid = sys_getppid();
285 				result = audit_comparator(ctx->ppid, f->op, f->val);
286 			}
287 			break;
288 		case AUDIT_UID:
289 			result = audit_comparator(tsk->uid, f->op, f->val);
290 			break;
291 		case AUDIT_EUID:
292 			result = audit_comparator(tsk->euid, f->op, f->val);
293 			break;
294 		case AUDIT_SUID:
295 			result = audit_comparator(tsk->suid, f->op, f->val);
296 			break;
297 		case AUDIT_FSUID:
298 			result = audit_comparator(tsk->fsuid, f->op, f->val);
299 			break;
300 		case AUDIT_GID:
301 			result = audit_comparator(tsk->gid, f->op, f->val);
302 			break;
303 		case AUDIT_EGID:
304 			result = audit_comparator(tsk->egid, f->op, f->val);
305 			break;
306 		case AUDIT_SGID:
307 			result = audit_comparator(tsk->sgid, f->op, f->val);
308 			break;
309 		case AUDIT_FSGID:
310 			result = audit_comparator(tsk->fsgid, f->op, f->val);
311 			break;
312 		case AUDIT_PERS:
313 			result = audit_comparator(tsk->personality, f->op, f->val);
314 			break;
315 		case AUDIT_ARCH:
316  			if (ctx)
317 				result = audit_comparator(ctx->arch, f->op, f->val);
318 			break;
319 
320 		case AUDIT_EXIT:
321 			if (ctx && ctx->return_valid)
322 				result = audit_comparator(ctx->return_code, f->op, f->val);
323 			break;
324 		case AUDIT_SUCCESS:
325 			if (ctx && ctx->return_valid) {
326 				if (f->val)
327 					result = audit_comparator(ctx->return_valid, f->op, AUDITSC_SUCCESS);
328 				else
329 					result = audit_comparator(ctx->return_valid, f->op, AUDITSC_FAILURE);
330 			}
331 			break;
332 		case AUDIT_DEVMAJOR:
333 			if (name)
334 				result = audit_comparator(MAJOR(name->dev),
335 							  f->op, f->val);
336 			else if (ctx) {
337 				for (j = 0; j < ctx->name_count; j++) {
338 					if (audit_comparator(MAJOR(ctx->names[j].dev),	f->op, f->val)) {
339 						++result;
340 						break;
341 					}
342 				}
343 			}
344 			break;
345 		case AUDIT_DEVMINOR:
346 			if (name)
347 				result = audit_comparator(MINOR(name->dev),
348 							  f->op, f->val);
349 			else if (ctx) {
350 				for (j = 0; j < ctx->name_count; j++) {
351 					if (audit_comparator(MINOR(ctx->names[j].dev), f->op, f->val)) {
352 						++result;
353 						break;
354 					}
355 				}
356 			}
357 			break;
358 		case AUDIT_INODE:
359 			if (name)
360 				result = (name->ino == f->val);
361 			else if (ctx) {
362 				for (j = 0; j < ctx->name_count; j++) {
363 					if (audit_comparator(ctx->names[j].ino, f->op, f->val)) {
364 						++result;
365 						break;
366 					}
367 				}
368 			}
369 			break;
370 		case AUDIT_WATCH:
371 			if (name && rule->watch->ino != (unsigned long)-1)
372 				result = (name->dev == rule->watch->dev &&
373 					  name->ino == rule->watch->ino);
374 			break;
375 		case AUDIT_LOGINUID:
376 			result = 0;
377 			if (ctx)
378 				result = audit_comparator(ctx->loginuid, f->op, f->val);
379 			break;
380 		case AUDIT_SUBJ_USER:
381 		case AUDIT_SUBJ_ROLE:
382 		case AUDIT_SUBJ_TYPE:
383 		case AUDIT_SUBJ_SEN:
384 		case AUDIT_SUBJ_CLR:
385 			/* NOTE: this may return negative values indicating
386 			   a temporary error.  We simply treat this as a
387 			   match for now to avoid losing information that
388 			   may be wanted.   An error message will also be
389 			   logged upon error */
390 			if (f->se_rule) {
391 				if (need_sid) {
392 					selinux_get_task_sid(tsk, &sid);
393 					need_sid = 0;
394 				}
395 				result = selinux_audit_rule_match(sid, f->type,
396 				                                  f->op,
397 				                                  f->se_rule,
398 				                                  ctx);
399 			}
400 			break;
401 		case AUDIT_OBJ_USER:
402 		case AUDIT_OBJ_ROLE:
403 		case AUDIT_OBJ_TYPE:
404 		case AUDIT_OBJ_LEV_LOW:
405 		case AUDIT_OBJ_LEV_HIGH:
406 			/* The above note for AUDIT_SUBJ_USER...AUDIT_SUBJ_CLR
407 			   also applies here */
408 			if (f->se_rule) {
409 				/* Find files that match */
410 				if (name) {
411 					result = selinux_audit_rule_match(
412 					           name->osid, f->type, f->op,
413 					           f->se_rule, ctx);
414 				} else if (ctx) {
415 					for (j = 0; j < ctx->name_count; j++) {
416 						if (selinux_audit_rule_match(
417 						      ctx->names[j].osid,
418 						      f->type, f->op,
419 						      f->se_rule, ctx)) {
420 							++result;
421 							break;
422 						}
423 					}
424 				}
425 				/* Find ipc objects that match */
426 				if (ctx) {
427 					struct audit_aux_data *aux;
428 					for (aux = ctx->aux; aux;
429 					     aux = aux->next) {
430 						if (aux->type == AUDIT_IPC) {
431 							struct audit_aux_data_ipcctl *axi = (void *)aux;
432 							if (selinux_audit_rule_match(axi->osid, f->type, f->op, f->se_rule, ctx)) {
433 								++result;
434 								break;
435 							}
436 						}
437 					}
438 				}
439 			}
440 			break;
441 		case AUDIT_ARG0:
442 		case AUDIT_ARG1:
443 		case AUDIT_ARG2:
444 		case AUDIT_ARG3:
445 			if (ctx)
446 				result = audit_comparator(ctx->argv[f->type-AUDIT_ARG0], f->op, f->val);
447 			break;
448 		case AUDIT_FILTERKEY:
449 			/* ignore this field for filtering */
450 			result = 1;
451 			break;
452 		case AUDIT_PERM:
453 			result = audit_match_perm(ctx, f->val);
454 			break;
455 		}
456 
457 		if (!result)
458 			return 0;
459 	}
460 	if (rule->filterkey)
461 		ctx->filterkey = kstrdup(rule->filterkey, GFP_ATOMIC);
462 	switch (rule->action) {
463 	case AUDIT_NEVER:    *state = AUDIT_DISABLED;	    break;
464 	case AUDIT_ALWAYS:   *state = AUDIT_RECORD_CONTEXT; break;
465 	}
466 	return 1;
467 }
468 
469 /* At process creation time, we can determine if system-call auditing is
470  * completely disabled for this task.  Since we only have the task
471  * structure at this point, we can only check uid and gid.
472  */
473 static enum audit_state audit_filter_task(struct task_struct *tsk)
474 {
475 	struct audit_entry *e;
476 	enum audit_state   state;
477 
478 	rcu_read_lock();
479 	list_for_each_entry_rcu(e, &audit_filter_list[AUDIT_FILTER_TASK], list) {
480 		if (audit_filter_rules(tsk, &e->rule, NULL, NULL, &state)) {
481 			rcu_read_unlock();
482 			return state;
483 		}
484 	}
485 	rcu_read_unlock();
486 	return AUDIT_BUILD_CONTEXT;
487 }
488 
489 /* At syscall entry and exit time, this filter is called if the
490  * audit_state is not low enough that auditing cannot take place, but is
491  * also not high enough that we already know we have to write an audit
492  * record (i.e., the state is AUDIT_SETUP_CONTEXT or AUDIT_BUILD_CONTEXT).
493  */
494 static enum audit_state audit_filter_syscall(struct task_struct *tsk,
495 					     struct audit_context *ctx,
496 					     struct list_head *list)
497 {
498 	struct audit_entry *e;
499 	enum audit_state state;
500 
501 	if (audit_pid && tsk->tgid == audit_pid)
502 		return AUDIT_DISABLED;
503 
504 	rcu_read_lock();
505 	if (!list_empty(list)) {
506 		int word = AUDIT_WORD(ctx->major);
507 		int bit  = AUDIT_BIT(ctx->major);
508 
509 		list_for_each_entry_rcu(e, list, list) {
510 			if ((e->rule.mask[word] & bit) == bit &&
511 			    audit_filter_rules(tsk, &e->rule, ctx, NULL,
512 					       &state)) {
513 				rcu_read_unlock();
514 				return state;
515 			}
516 		}
517 	}
518 	rcu_read_unlock();
519 	return AUDIT_BUILD_CONTEXT;
520 }
521 
522 /* At syscall exit time, this filter is called if any audit_names[] have been
523  * collected during syscall processing.  We only check rules in sublists at hash
524  * buckets applicable to the inode numbers in audit_names[].
525  * Regarding audit_state, same rules apply as for audit_filter_syscall().
526  */
527 enum audit_state audit_filter_inodes(struct task_struct *tsk,
528 				     struct audit_context *ctx)
529 {
530 	int i;
531 	struct audit_entry *e;
532 	enum audit_state state;
533 
534 	if (audit_pid && tsk->tgid == audit_pid)
535 		return AUDIT_DISABLED;
536 
537 	rcu_read_lock();
538 	for (i = 0; i < ctx->name_count; i++) {
539 		int word = AUDIT_WORD(ctx->major);
540 		int bit  = AUDIT_BIT(ctx->major);
541 		struct audit_names *n = &ctx->names[i];
542 		int h = audit_hash_ino((u32)n->ino);
543 		struct list_head *list = &audit_inode_hash[h];
544 
545 		if (list_empty(list))
546 			continue;
547 
548 		list_for_each_entry_rcu(e, list, list) {
549 			if ((e->rule.mask[word] & bit) == bit &&
550 			    audit_filter_rules(tsk, &e->rule, ctx, n, &state)) {
551 				rcu_read_unlock();
552 				return state;
553 			}
554 		}
555 	}
556 	rcu_read_unlock();
557 	return AUDIT_BUILD_CONTEXT;
558 }
559 
560 void audit_set_auditable(struct audit_context *ctx)
561 {
562 	ctx->auditable = 1;
563 }
564 
565 static inline struct audit_context *audit_get_context(struct task_struct *tsk,
566 						      int return_valid,
567 						      int return_code)
568 {
569 	struct audit_context *context = tsk->audit_context;
570 
571 	if (likely(!context))
572 		return NULL;
573 	context->return_valid = return_valid;
574 	context->return_code  = return_code;
575 
576 	if (context->in_syscall && !context->dummy && !context->auditable) {
577 		enum audit_state state;
578 
579 		state = audit_filter_syscall(tsk, context, &audit_filter_list[AUDIT_FILTER_EXIT]);
580 		if (state == AUDIT_RECORD_CONTEXT) {
581 			context->auditable = 1;
582 			goto get_context;
583 		}
584 
585 		state = audit_filter_inodes(tsk, context);
586 		if (state == AUDIT_RECORD_CONTEXT)
587 			context->auditable = 1;
588 
589 	}
590 
591 get_context:
592 
593 	tsk->audit_context = NULL;
594 	return context;
595 }
596 
597 static inline void audit_free_names(struct audit_context *context)
598 {
599 	int i;
600 
601 #if AUDIT_DEBUG == 2
602 	if (context->auditable
603 	    ||context->put_count + context->ino_count != context->name_count) {
604 		printk(KERN_ERR "%s:%d(:%d): major=%d in_syscall=%d"
605 		       " name_count=%d put_count=%d"
606 		       " ino_count=%d [NOT freeing]\n",
607 		       __FILE__, __LINE__,
608 		       context->serial, context->major, context->in_syscall,
609 		       context->name_count, context->put_count,
610 		       context->ino_count);
611 		for (i = 0; i < context->name_count; i++) {
612 			printk(KERN_ERR "names[%d] = %p = %s\n", i,
613 			       context->names[i].name,
614 			       context->names[i].name ?: "(null)");
615 		}
616 		dump_stack();
617 		return;
618 	}
619 #endif
620 #if AUDIT_DEBUG
621 	context->put_count  = 0;
622 	context->ino_count  = 0;
623 #endif
624 
625 	for (i = 0; i < context->name_count; i++) {
626 		if (context->names[i].name && context->names[i].name_put)
627 			__putname(context->names[i].name);
628 	}
629 	context->name_count = 0;
630 	if (context->pwd)
631 		dput(context->pwd);
632 	if (context->pwdmnt)
633 		mntput(context->pwdmnt);
634 	context->pwd = NULL;
635 	context->pwdmnt = NULL;
636 }
637 
638 static inline void audit_free_aux(struct audit_context *context)
639 {
640 	struct audit_aux_data *aux;
641 
642 	while ((aux = context->aux)) {
643 		if (aux->type == AUDIT_AVC_PATH) {
644 			struct audit_aux_data_path *axi = (void *)aux;
645 			dput(axi->dentry);
646 			mntput(axi->mnt);
647 		}
648 
649 		context->aux = aux->next;
650 		kfree(aux);
651 	}
652 }
653 
654 static inline void audit_zero_context(struct audit_context *context,
655 				      enum audit_state state)
656 {
657 	uid_t loginuid = context->loginuid;
658 
659 	memset(context, 0, sizeof(*context));
660 	context->state      = state;
661 	context->loginuid   = loginuid;
662 }
663 
664 static inline struct audit_context *audit_alloc_context(enum audit_state state)
665 {
666 	struct audit_context *context;
667 
668 	if (!(context = kmalloc(sizeof(*context), GFP_KERNEL)))
669 		return NULL;
670 	audit_zero_context(context, state);
671 	return context;
672 }
673 
674 /**
675  * audit_alloc - allocate an audit context block for a task
676  * @tsk: task
677  *
678  * Filter on the task information and allocate a per-task audit context
679  * if necessary.  Doing so turns on system call auditing for the
680  * specified task.  This is called from copy_process, so no lock is
681  * needed.
682  */
683 int audit_alloc(struct task_struct *tsk)
684 {
685 	struct audit_context *context;
686 	enum audit_state     state;
687 
688 	if (likely(!audit_enabled))
689 		return 0; /* Return if not auditing. */
690 
691 	state = audit_filter_task(tsk);
692 	if (likely(state == AUDIT_DISABLED))
693 		return 0;
694 
695 	if (!(context = audit_alloc_context(state))) {
696 		audit_log_lost("out of memory in audit_alloc");
697 		return -ENOMEM;
698 	}
699 
700 				/* Preserve login uid */
701 	context->loginuid = -1;
702 	if (current->audit_context)
703 		context->loginuid = current->audit_context->loginuid;
704 
705 	tsk->audit_context  = context;
706 	set_tsk_thread_flag(tsk, TIF_SYSCALL_AUDIT);
707 	return 0;
708 }
709 
710 static inline void audit_free_context(struct audit_context *context)
711 {
712 	struct audit_context *previous;
713 	int		     count = 0;
714 
715 	do {
716 		previous = context->previous;
717 		if (previous || (count &&  count < 10)) {
718 			++count;
719 			printk(KERN_ERR "audit(:%d): major=%d name_count=%d:"
720 			       " freeing multiple contexts (%d)\n",
721 			       context->serial, context->major,
722 			       context->name_count, count);
723 		}
724 		audit_free_names(context);
725 		audit_free_aux(context);
726 		kfree(context->filterkey);
727 		kfree(context);
728 		context  = previous;
729 	} while (context);
730 	if (count >= 10)
731 		printk(KERN_ERR "audit: freed %d contexts\n", count);
732 }
733 
734 void audit_log_task_context(struct audit_buffer *ab)
735 {
736 	char *ctx = NULL;
737 	ssize_t len = 0;
738 
739 	len = security_getprocattr(current, "current", NULL, 0);
740 	if (len < 0) {
741 		if (len != -EINVAL)
742 			goto error_path;
743 		return;
744 	}
745 
746 	ctx = kmalloc(len, GFP_KERNEL);
747 	if (!ctx)
748 		goto error_path;
749 
750 	len = security_getprocattr(current, "current", ctx, len);
751 	if (len < 0 )
752 		goto error_path;
753 
754 	audit_log_format(ab, " subj=%s", ctx);
755 	return;
756 
757 error_path:
758 	kfree(ctx);
759 	audit_panic("error in audit_log_task_context");
760 	return;
761 }
762 
763 EXPORT_SYMBOL(audit_log_task_context);
764 
765 static void audit_log_task_info(struct audit_buffer *ab, struct task_struct *tsk)
766 {
767 	char name[sizeof(tsk->comm)];
768 	struct mm_struct *mm = tsk->mm;
769 	struct vm_area_struct *vma;
770 
771 	/* tsk == current */
772 
773 	get_task_comm(name, tsk);
774 	audit_log_format(ab, " comm=");
775 	audit_log_untrustedstring(ab, name);
776 
777 	if (mm) {
778 		down_read(&mm->mmap_sem);
779 		vma = mm->mmap;
780 		while (vma) {
781 			if ((vma->vm_flags & VM_EXECUTABLE) &&
782 			    vma->vm_file) {
783 				audit_log_d_path(ab, "exe=",
784 						 vma->vm_file->f_path.dentry,
785 						 vma->vm_file->f_path.mnt);
786 				break;
787 			}
788 			vma = vma->vm_next;
789 		}
790 		up_read(&mm->mmap_sem);
791 	}
792 	audit_log_task_context(ab);
793 }
794 
795 static void audit_log_exit(struct audit_context *context, struct task_struct *tsk)
796 {
797 	int i, call_panic = 0;
798 	struct audit_buffer *ab;
799 	struct audit_aux_data *aux;
800 	const char *tty;
801 
802 	/* tsk == current */
803 	context->pid = tsk->pid;
804 	if (!context->ppid)
805 		context->ppid = sys_getppid();
806 	context->uid = tsk->uid;
807 	context->gid = tsk->gid;
808 	context->euid = tsk->euid;
809 	context->suid = tsk->suid;
810 	context->fsuid = tsk->fsuid;
811 	context->egid = tsk->egid;
812 	context->sgid = tsk->sgid;
813 	context->fsgid = tsk->fsgid;
814 	context->personality = tsk->personality;
815 
816 	ab = audit_log_start(context, GFP_KERNEL, AUDIT_SYSCALL);
817 	if (!ab)
818 		return;		/* audit_panic has been called */
819 	audit_log_format(ab, "arch=%x syscall=%d",
820 			 context->arch, context->major);
821 	if (context->personality != PER_LINUX)
822 		audit_log_format(ab, " per=%lx", context->personality);
823 	if (context->return_valid)
824 		audit_log_format(ab, " success=%s exit=%ld",
825 				 (context->return_valid==AUDITSC_SUCCESS)?"yes":"no",
826 				 context->return_code);
827 
828 	mutex_lock(&tty_mutex);
829 	read_lock(&tasklist_lock);
830 	if (tsk->signal && tsk->signal->tty && tsk->signal->tty->name)
831 		tty = tsk->signal->tty->name;
832 	else
833 		tty = "(none)";
834 	read_unlock(&tasklist_lock);
835 	audit_log_format(ab,
836 		  " a0=%lx a1=%lx a2=%lx a3=%lx items=%d"
837 		  " ppid=%d pid=%d auid=%u uid=%u gid=%u"
838 		  " euid=%u suid=%u fsuid=%u"
839 		  " egid=%u sgid=%u fsgid=%u tty=%s",
840 		  context->argv[0],
841 		  context->argv[1],
842 		  context->argv[2],
843 		  context->argv[3],
844 		  context->name_count,
845 		  context->ppid,
846 		  context->pid,
847 		  context->loginuid,
848 		  context->uid,
849 		  context->gid,
850 		  context->euid, context->suid, context->fsuid,
851 		  context->egid, context->sgid, context->fsgid, tty);
852 
853 	mutex_unlock(&tty_mutex);
854 
855 	audit_log_task_info(ab, tsk);
856 	if (context->filterkey) {
857 		audit_log_format(ab, " key=");
858 		audit_log_untrustedstring(ab, context->filterkey);
859 	} else
860 		audit_log_format(ab, " key=(null)");
861 	audit_log_end(ab);
862 
863 	for (aux = context->aux; aux; aux = aux->next) {
864 
865 		ab = audit_log_start(context, GFP_KERNEL, aux->type);
866 		if (!ab)
867 			continue; /* audit_panic has been called */
868 
869 		switch (aux->type) {
870 		case AUDIT_MQ_OPEN: {
871 			struct audit_aux_data_mq_open *axi = (void *)aux;
872 			audit_log_format(ab,
873 				"oflag=0x%x mode=%#o mq_flags=0x%lx mq_maxmsg=%ld "
874 				"mq_msgsize=%ld mq_curmsgs=%ld",
875 				axi->oflag, axi->mode, axi->attr.mq_flags,
876 				axi->attr.mq_maxmsg, axi->attr.mq_msgsize,
877 				axi->attr.mq_curmsgs);
878 			break; }
879 
880 		case AUDIT_MQ_SENDRECV: {
881 			struct audit_aux_data_mq_sendrecv *axi = (void *)aux;
882 			audit_log_format(ab,
883 				"mqdes=%d msg_len=%zd msg_prio=%u "
884 				"abs_timeout_sec=%ld abs_timeout_nsec=%ld",
885 				axi->mqdes, axi->msg_len, axi->msg_prio,
886 				axi->abs_timeout.tv_sec, axi->abs_timeout.tv_nsec);
887 			break; }
888 
889 		case AUDIT_MQ_NOTIFY: {
890 			struct audit_aux_data_mq_notify *axi = (void *)aux;
891 			audit_log_format(ab,
892 				"mqdes=%d sigev_signo=%d",
893 				axi->mqdes,
894 				axi->notification.sigev_signo);
895 			break; }
896 
897 		case AUDIT_MQ_GETSETATTR: {
898 			struct audit_aux_data_mq_getsetattr *axi = (void *)aux;
899 			audit_log_format(ab,
900 				"mqdes=%d mq_flags=0x%lx mq_maxmsg=%ld mq_msgsize=%ld "
901 				"mq_curmsgs=%ld ",
902 				axi->mqdes,
903 				axi->mqstat.mq_flags, axi->mqstat.mq_maxmsg,
904 				axi->mqstat.mq_msgsize, axi->mqstat.mq_curmsgs);
905 			break; }
906 
907 		case AUDIT_IPC: {
908 			struct audit_aux_data_ipcctl *axi = (void *)aux;
909 			audit_log_format(ab,
910 				 "ouid=%u ogid=%u mode=%x",
911 				 axi->uid, axi->gid, axi->mode);
912 			if (axi->osid != 0) {
913 				char *ctx = NULL;
914 				u32 len;
915 				if (selinux_sid_to_string(
916 						axi->osid, &ctx, &len)) {
917 					audit_log_format(ab, " osid=%u",
918 							axi->osid);
919 					call_panic = 1;
920 				} else
921 					audit_log_format(ab, " obj=%s", ctx);
922 				kfree(ctx);
923 			}
924 			break; }
925 
926 		case AUDIT_IPC_SET_PERM: {
927 			struct audit_aux_data_ipcctl *axi = (void *)aux;
928 			audit_log_format(ab,
929 				"qbytes=%lx ouid=%u ogid=%u mode=%x",
930 				axi->qbytes, axi->uid, axi->gid, axi->mode);
931 			break; }
932 
933 		case AUDIT_EXECVE: {
934 			struct audit_aux_data_execve *axi = (void *)aux;
935 			int i;
936 			const char *p;
937 			for (i = 0, p = axi->mem; i < axi->argc; i++) {
938 				audit_log_format(ab, "a%d=", i);
939 				p = audit_log_untrustedstring(ab, p);
940 				audit_log_format(ab, "\n");
941 			}
942 			break; }
943 
944 		case AUDIT_SOCKETCALL: {
945 			int i;
946 			struct audit_aux_data_socketcall *axs = (void *)aux;
947 			audit_log_format(ab, "nargs=%d", axs->nargs);
948 			for (i=0; i<axs->nargs; i++)
949 				audit_log_format(ab, " a%d=%lx", i, axs->args[i]);
950 			break; }
951 
952 		case AUDIT_SOCKADDR: {
953 			struct audit_aux_data_sockaddr *axs = (void *)aux;
954 
955 			audit_log_format(ab, "saddr=");
956 			audit_log_hex(ab, axs->a, axs->len);
957 			break; }
958 
959 		case AUDIT_AVC_PATH: {
960 			struct audit_aux_data_path *axi = (void *)aux;
961 			audit_log_d_path(ab, "path=", axi->dentry, axi->mnt);
962 			break; }
963 
964 		}
965 		audit_log_end(ab);
966 	}
967 
968 	if (context->pwd && context->pwdmnt) {
969 		ab = audit_log_start(context, GFP_KERNEL, AUDIT_CWD);
970 		if (ab) {
971 			audit_log_d_path(ab, "cwd=", context->pwd, context->pwdmnt);
972 			audit_log_end(ab);
973 		}
974 	}
975 	for (i = 0; i < context->name_count; i++) {
976 		struct audit_names *n = &context->names[i];
977 
978 		ab = audit_log_start(context, GFP_KERNEL, AUDIT_PATH);
979 		if (!ab)
980 			continue; /* audit_panic has been called */
981 
982 		audit_log_format(ab, "item=%d", i);
983 
984 		if (n->name) {
985 			switch(n->name_len) {
986 			case AUDIT_NAME_FULL:
987 				/* log the full path */
988 				audit_log_format(ab, " name=");
989 				audit_log_untrustedstring(ab, n->name);
990 				break;
991 			case 0:
992 				/* name was specified as a relative path and the
993 				 * directory component is the cwd */
994 				audit_log_d_path(ab, " name=", context->pwd,
995 						 context->pwdmnt);
996 				break;
997 			default:
998 				/* log the name's directory component */
999 				audit_log_format(ab, " name=");
1000 				audit_log_n_untrustedstring(ab, n->name_len,
1001 							    n->name);
1002 			}
1003 		} else
1004 			audit_log_format(ab, " name=(null)");
1005 
1006 		if (n->ino != (unsigned long)-1) {
1007 			audit_log_format(ab, " inode=%lu"
1008 					 " dev=%02x:%02x mode=%#o"
1009 					 " ouid=%u ogid=%u rdev=%02x:%02x",
1010 					 n->ino,
1011 					 MAJOR(n->dev),
1012 					 MINOR(n->dev),
1013 					 n->mode,
1014 					 n->uid,
1015 					 n->gid,
1016 					 MAJOR(n->rdev),
1017 					 MINOR(n->rdev));
1018 		}
1019 		if (n->osid != 0) {
1020 			char *ctx = NULL;
1021 			u32 len;
1022 			if (selinux_sid_to_string(
1023 				n->osid, &ctx, &len)) {
1024 				audit_log_format(ab, " osid=%u", n->osid);
1025 				call_panic = 2;
1026 			} else
1027 				audit_log_format(ab, " obj=%s", ctx);
1028 			kfree(ctx);
1029 		}
1030 
1031 		audit_log_end(ab);
1032 	}
1033 	if (call_panic)
1034 		audit_panic("error converting sid to string");
1035 }
1036 
1037 /**
1038  * audit_free - free a per-task audit context
1039  * @tsk: task whose audit context block to free
1040  *
1041  * Called from copy_process and do_exit
1042  */
1043 void audit_free(struct task_struct *tsk)
1044 {
1045 	struct audit_context *context;
1046 
1047 	context = audit_get_context(tsk, 0, 0);
1048 	if (likely(!context))
1049 		return;
1050 
1051 	/* Check for system calls that do not go through the exit
1052 	 * function (e.g., exit_group), then free context block.
1053 	 * We use GFP_ATOMIC here because we might be doing this
1054 	 * in the context of the idle thread */
1055 	/* that can happen only if we are called from do_exit() */
1056 	if (context->in_syscall && context->auditable)
1057 		audit_log_exit(context, tsk);
1058 
1059 	audit_free_context(context);
1060 }
1061 
1062 /**
1063  * audit_syscall_entry - fill in an audit record at syscall entry
1064  * @tsk: task being audited
1065  * @arch: architecture type
1066  * @major: major syscall type (function)
1067  * @a1: additional syscall register 1
1068  * @a2: additional syscall register 2
1069  * @a3: additional syscall register 3
1070  * @a4: additional syscall register 4
1071  *
1072  * Fill in audit context at syscall entry.  This only happens if the
1073  * audit context was created when the task was created and the state or
1074  * filters demand the audit context be built.  If the state from the
1075  * per-task filter or from the per-syscall filter is AUDIT_RECORD_CONTEXT,
1076  * then the record will be written at syscall exit time (otherwise, it
1077  * will only be written if another part of the kernel requests that it
1078  * be written).
1079  */
1080 void audit_syscall_entry(int arch, int major,
1081 			 unsigned long a1, unsigned long a2,
1082 			 unsigned long a3, unsigned long a4)
1083 {
1084 	struct task_struct *tsk = current;
1085 	struct audit_context *context = tsk->audit_context;
1086 	enum audit_state     state;
1087 
1088 	BUG_ON(!context);
1089 
1090 	/*
1091 	 * This happens only on certain architectures that make system
1092 	 * calls in kernel_thread via the entry.S interface, instead of
1093 	 * with direct calls.  (If you are porting to a new
1094 	 * architecture, hitting this condition can indicate that you
1095 	 * got the _exit/_leave calls backward in entry.S.)
1096 	 *
1097 	 * i386     no
1098 	 * x86_64   no
1099 	 * ppc64    yes (see arch/powerpc/platforms/iseries/misc.S)
1100 	 *
1101 	 * This also happens with vm86 emulation in a non-nested manner
1102 	 * (entries without exits), so this case must be caught.
1103 	 */
1104 	if (context->in_syscall) {
1105 		struct audit_context *newctx;
1106 
1107 #if AUDIT_DEBUG
1108 		printk(KERN_ERR
1109 		       "audit(:%d) pid=%d in syscall=%d;"
1110 		       " entering syscall=%d\n",
1111 		       context->serial, tsk->pid, context->major, major);
1112 #endif
1113 		newctx = audit_alloc_context(context->state);
1114 		if (newctx) {
1115 			newctx->previous   = context;
1116 			context		   = newctx;
1117 			tsk->audit_context = newctx;
1118 		} else	{
1119 			/* If we can't alloc a new context, the best we
1120 			 * can do is to leak memory (any pending putname
1121 			 * will be lost).  The only other alternative is
1122 			 * to abandon auditing. */
1123 			audit_zero_context(context, context->state);
1124 		}
1125 	}
1126 	BUG_ON(context->in_syscall || context->name_count);
1127 
1128 	if (!audit_enabled)
1129 		return;
1130 
1131 	context->arch	    = arch;
1132 	context->major      = major;
1133 	context->argv[0]    = a1;
1134 	context->argv[1]    = a2;
1135 	context->argv[2]    = a3;
1136 	context->argv[3]    = a4;
1137 
1138 	state = context->state;
1139 	context->dummy = !audit_n_rules;
1140 	if (!context->dummy && (state == AUDIT_SETUP_CONTEXT || state == AUDIT_BUILD_CONTEXT))
1141 		state = audit_filter_syscall(tsk, context, &audit_filter_list[AUDIT_FILTER_ENTRY]);
1142 	if (likely(state == AUDIT_DISABLED))
1143 		return;
1144 
1145 	context->serial     = 0;
1146 	context->ctime      = CURRENT_TIME;
1147 	context->in_syscall = 1;
1148 	context->auditable  = !!(state == AUDIT_RECORD_CONTEXT);
1149 	context->ppid       = 0;
1150 }
1151 
1152 /**
1153  * audit_syscall_exit - deallocate audit context after a system call
1154  * @tsk: task being audited
1155  * @valid: success/failure flag
1156  * @return_code: syscall return value
1157  *
1158  * Tear down after system call.  If the audit context has been marked as
1159  * auditable (either because of the AUDIT_RECORD_CONTEXT state from
1160  * filtering, or because some other part of the kernel write an audit
1161  * message), then write out the syscall information.  In call cases,
1162  * free the names stored from getname().
1163  */
1164 void audit_syscall_exit(int valid, long return_code)
1165 {
1166 	struct task_struct *tsk = current;
1167 	struct audit_context *context;
1168 
1169 	context = audit_get_context(tsk, valid, return_code);
1170 
1171 	if (likely(!context))
1172 		return;
1173 
1174 	if (context->in_syscall && context->auditable)
1175 		audit_log_exit(context, tsk);
1176 
1177 	context->in_syscall = 0;
1178 	context->auditable  = 0;
1179 
1180 	if (context->previous) {
1181 		struct audit_context *new_context = context->previous;
1182 		context->previous  = NULL;
1183 		audit_free_context(context);
1184 		tsk->audit_context = new_context;
1185 	} else {
1186 		audit_free_names(context);
1187 		audit_free_aux(context);
1188 		kfree(context->filterkey);
1189 		context->filterkey = NULL;
1190 		tsk->audit_context = context;
1191 	}
1192 }
1193 
1194 /**
1195  * audit_getname - add a name to the list
1196  * @name: name to add
1197  *
1198  * Add a name to the list of audit names for this context.
1199  * Called from fs/namei.c:getname().
1200  */
1201 void __audit_getname(const char *name)
1202 {
1203 	struct audit_context *context = current->audit_context;
1204 
1205 	if (IS_ERR(name) || !name)
1206 		return;
1207 
1208 	if (!context->in_syscall) {
1209 #if AUDIT_DEBUG == 2
1210 		printk(KERN_ERR "%s:%d(:%d): ignoring getname(%p)\n",
1211 		       __FILE__, __LINE__, context->serial, name);
1212 		dump_stack();
1213 #endif
1214 		return;
1215 	}
1216 	BUG_ON(context->name_count >= AUDIT_NAMES);
1217 	context->names[context->name_count].name = name;
1218 	context->names[context->name_count].name_len = AUDIT_NAME_FULL;
1219 	context->names[context->name_count].name_put = 1;
1220 	context->names[context->name_count].ino  = (unsigned long)-1;
1221 	++context->name_count;
1222 	if (!context->pwd) {
1223 		read_lock(&current->fs->lock);
1224 		context->pwd = dget(current->fs->pwd);
1225 		context->pwdmnt = mntget(current->fs->pwdmnt);
1226 		read_unlock(&current->fs->lock);
1227 	}
1228 
1229 }
1230 
1231 /* audit_putname - intercept a putname request
1232  * @name: name to intercept and delay for putname
1233  *
1234  * If we have stored the name from getname in the audit context,
1235  * then we delay the putname until syscall exit.
1236  * Called from include/linux/fs.h:putname().
1237  */
1238 void audit_putname(const char *name)
1239 {
1240 	struct audit_context *context = current->audit_context;
1241 
1242 	BUG_ON(!context);
1243 	if (!context->in_syscall) {
1244 #if AUDIT_DEBUG == 2
1245 		printk(KERN_ERR "%s:%d(:%d): __putname(%p)\n",
1246 		       __FILE__, __LINE__, context->serial, name);
1247 		if (context->name_count) {
1248 			int i;
1249 			for (i = 0; i < context->name_count; i++)
1250 				printk(KERN_ERR "name[%d] = %p = %s\n", i,
1251 				       context->names[i].name,
1252 				       context->names[i].name ?: "(null)");
1253 		}
1254 #endif
1255 		__putname(name);
1256 	}
1257 #if AUDIT_DEBUG
1258 	else {
1259 		++context->put_count;
1260 		if (context->put_count > context->name_count) {
1261 			printk(KERN_ERR "%s:%d(:%d): major=%d"
1262 			       " in_syscall=%d putname(%p) name_count=%d"
1263 			       " put_count=%d\n",
1264 			       __FILE__, __LINE__,
1265 			       context->serial, context->major,
1266 			       context->in_syscall, name, context->name_count,
1267 			       context->put_count);
1268 			dump_stack();
1269 		}
1270 	}
1271 #endif
1272 }
1273 
1274 /* Copy inode data into an audit_names. */
1275 static void audit_copy_inode(struct audit_names *name, const struct inode *inode)
1276 {
1277 	name->ino   = inode->i_ino;
1278 	name->dev   = inode->i_sb->s_dev;
1279 	name->mode  = inode->i_mode;
1280 	name->uid   = inode->i_uid;
1281 	name->gid   = inode->i_gid;
1282 	name->rdev  = inode->i_rdev;
1283 	selinux_get_inode_sid(inode, &name->osid);
1284 }
1285 
1286 /**
1287  * audit_inode - store the inode and device from a lookup
1288  * @name: name being audited
1289  * @inode: inode being audited
1290  *
1291  * Called from fs/namei.c:path_lookup().
1292  */
1293 void __audit_inode(const char *name, const struct inode *inode)
1294 {
1295 	int idx;
1296 	struct audit_context *context = current->audit_context;
1297 
1298 	if (!context->in_syscall)
1299 		return;
1300 	if (context->name_count
1301 	    && context->names[context->name_count-1].name
1302 	    && context->names[context->name_count-1].name == name)
1303 		idx = context->name_count - 1;
1304 	else if (context->name_count > 1
1305 		 && context->names[context->name_count-2].name
1306 		 && context->names[context->name_count-2].name == name)
1307 		idx = context->name_count - 2;
1308 	else {
1309 		/* FIXME: how much do we care about inodes that have no
1310 		 * associated name? */
1311 		if (context->name_count >= AUDIT_NAMES - AUDIT_NAMES_RESERVED)
1312 			return;
1313 		idx = context->name_count++;
1314 		context->names[idx].name = NULL;
1315 #if AUDIT_DEBUG
1316 		++context->ino_count;
1317 #endif
1318 	}
1319 	audit_copy_inode(&context->names[idx], inode);
1320 }
1321 
1322 /**
1323  * audit_inode_child - collect inode info for created/removed objects
1324  * @dname: inode's dentry name
1325  * @inode: inode being audited
1326  * @parent: inode of dentry parent
1327  *
1328  * For syscalls that create or remove filesystem objects, audit_inode
1329  * can only collect information for the filesystem object's parent.
1330  * This call updates the audit context with the child's information.
1331  * Syscalls that create a new filesystem object must be hooked after
1332  * the object is created.  Syscalls that remove a filesystem object
1333  * must be hooked prior, in order to capture the target inode during
1334  * unsuccessful attempts.
1335  */
1336 void __audit_inode_child(const char *dname, const struct inode *inode,
1337 			 const struct inode *parent)
1338 {
1339 	int idx;
1340 	struct audit_context *context = current->audit_context;
1341 	const char *found_name = NULL;
1342 	int dirlen = 0;
1343 
1344 	if (!context->in_syscall)
1345 		return;
1346 
1347 	/* determine matching parent */
1348 	if (!dname)
1349 		goto update_context;
1350 	for (idx = 0; idx < context->name_count; idx++)
1351 		if (context->names[idx].ino == parent->i_ino) {
1352 			const char *name = context->names[idx].name;
1353 
1354 			if (!name)
1355 				continue;
1356 
1357 			if (audit_compare_dname_path(dname, name, &dirlen) == 0) {
1358 				context->names[idx].name_len = dirlen;
1359 				found_name = name;
1360 				break;
1361 			}
1362 		}
1363 
1364 update_context:
1365 	idx = context->name_count;
1366 	if (context->name_count == AUDIT_NAMES) {
1367 		printk(KERN_DEBUG "name_count maxed and losing %s\n",
1368 			found_name ?: "(null)");
1369 		return;
1370 	}
1371 	context->name_count++;
1372 #if AUDIT_DEBUG
1373 	context->ino_count++;
1374 #endif
1375 	/* Re-use the name belonging to the slot for a matching parent directory.
1376 	 * All names for this context are relinquished in audit_free_names() */
1377 	context->names[idx].name = found_name;
1378 	context->names[idx].name_len = AUDIT_NAME_FULL;
1379 	context->names[idx].name_put = 0;	/* don't call __putname() */
1380 
1381 	if (!inode)
1382 		context->names[idx].ino = (unsigned long)-1;
1383 	else
1384 		audit_copy_inode(&context->names[idx], inode);
1385 
1386 	/* A parent was not found in audit_names, so copy the inode data for the
1387 	 * provided parent. */
1388 	if (!found_name) {
1389 		idx = context->name_count;
1390 		if (context->name_count == AUDIT_NAMES) {
1391 			printk(KERN_DEBUG
1392 				"name_count maxed and losing parent inode data: dev=%02x:%02x, inode=%lu",
1393 				MAJOR(parent->i_sb->s_dev),
1394 				MINOR(parent->i_sb->s_dev),
1395 				parent->i_ino);
1396 			return;
1397 		}
1398 		context->name_count++;
1399 #if AUDIT_DEBUG
1400 		context->ino_count++;
1401 #endif
1402 		audit_copy_inode(&context->names[idx], parent);
1403 	}
1404 }
1405 
1406 /**
1407  * audit_inode_update - update inode info for last collected name
1408  * @inode: inode being audited
1409  *
1410  * When open() is called on an existing object with the O_CREAT flag, the inode
1411  * data audit initially collects is incorrect.  This additional hook ensures
1412  * audit has the inode data for the actual object to be opened.
1413  */
1414 void __audit_inode_update(const struct inode *inode)
1415 {
1416 	struct audit_context *context = current->audit_context;
1417 	int idx;
1418 
1419 	if (!context->in_syscall || !inode)
1420 		return;
1421 
1422 	if (context->name_count == 0) {
1423 		context->name_count++;
1424 #if AUDIT_DEBUG
1425 		context->ino_count++;
1426 #endif
1427 	}
1428 	idx = context->name_count - 1;
1429 
1430 	audit_copy_inode(&context->names[idx], inode);
1431 }
1432 
1433 /**
1434  * auditsc_get_stamp - get local copies of audit_context values
1435  * @ctx: audit_context for the task
1436  * @t: timespec to store time recorded in the audit_context
1437  * @serial: serial value that is recorded in the audit_context
1438  *
1439  * Also sets the context as auditable.
1440  */
1441 void auditsc_get_stamp(struct audit_context *ctx,
1442 		       struct timespec *t, unsigned int *serial)
1443 {
1444 	if (!ctx->serial)
1445 		ctx->serial = audit_serial();
1446 	t->tv_sec  = ctx->ctime.tv_sec;
1447 	t->tv_nsec = ctx->ctime.tv_nsec;
1448 	*serial    = ctx->serial;
1449 	ctx->auditable = 1;
1450 }
1451 
1452 /**
1453  * audit_set_loginuid - set a task's audit_context loginuid
1454  * @task: task whose audit context is being modified
1455  * @loginuid: loginuid value
1456  *
1457  * Returns 0.
1458  *
1459  * Called (set) from fs/proc/base.c::proc_loginuid_write().
1460  */
1461 int audit_set_loginuid(struct task_struct *task, uid_t loginuid)
1462 {
1463 	struct audit_context *context = task->audit_context;
1464 
1465 	if (context) {
1466 		/* Only log if audit is enabled */
1467 		if (context->in_syscall) {
1468 			struct audit_buffer *ab;
1469 
1470 			ab = audit_log_start(NULL, GFP_KERNEL, AUDIT_LOGIN);
1471 			if (ab) {
1472 				audit_log_format(ab, "login pid=%d uid=%u "
1473 					"old auid=%u new auid=%u",
1474 					task->pid, task->uid,
1475 					context->loginuid, loginuid);
1476 				audit_log_end(ab);
1477 			}
1478 		}
1479 		context->loginuid = loginuid;
1480 	}
1481 	return 0;
1482 }
1483 
1484 /**
1485  * audit_get_loginuid - get the loginuid for an audit_context
1486  * @ctx: the audit_context
1487  *
1488  * Returns the context's loginuid or -1 if @ctx is NULL.
1489  */
1490 uid_t audit_get_loginuid(struct audit_context *ctx)
1491 {
1492 	return ctx ? ctx->loginuid : -1;
1493 }
1494 
1495 EXPORT_SYMBOL(audit_get_loginuid);
1496 
1497 /**
1498  * __audit_mq_open - record audit data for a POSIX MQ open
1499  * @oflag: open flag
1500  * @mode: mode bits
1501  * @u_attr: queue attributes
1502  *
1503  * Returns 0 for success or NULL context or < 0 on error.
1504  */
1505 int __audit_mq_open(int oflag, mode_t mode, struct mq_attr __user *u_attr)
1506 {
1507 	struct audit_aux_data_mq_open *ax;
1508 	struct audit_context *context = current->audit_context;
1509 
1510 	if (!audit_enabled)
1511 		return 0;
1512 
1513 	if (likely(!context))
1514 		return 0;
1515 
1516 	ax = kmalloc(sizeof(*ax), GFP_ATOMIC);
1517 	if (!ax)
1518 		return -ENOMEM;
1519 
1520 	if (u_attr != NULL) {
1521 		if (copy_from_user(&ax->attr, u_attr, sizeof(ax->attr))) {
1522 			kfree(ax);
1523 			return -EFAULT;
1524 		}
1525 	} else
1526 		memset(&ax->attr, 0, sizeof(ax->attr));
1527 
1528 	ax->oflag = oflag;
1529 	ax->mode = mode;
1530 
1531 	ax->d.type = AUDIT_MQ_OPEN;
1532 	ax->d.next = context->aux;
1533 	context->aux = (void *)ax;
1534 	return 0;
1535 }
1536 
1537 /**
1538  * __audit_mq_timedsend - record audit data for a POSIX MQ timed send
1539  * @mqdes: MQ descriptor
1540  * @msg_len: Message length
1541  * @msg_prio: Message priority
1542  * @u_abs_timeout: Message timeout in absolute time
1543  *
1544  * Returns 0 for success or NULL context or < 0 on error.
1545  */
1546 int __audit_mq_timedsend(mqd_t mqdes, size_t msg_len, unsigned int msg_prio,
1547 			const struct timespec __user *u_abs_timeout)
1548 {
1549 	struct audit_aux_data_mq_sendrecv *ax;
1550 	struct audit_context *context = current->audit_context;
1551 
1552 	if (!audit_enabled)
1553 		return 0;
1554 
1555 	if (likely(!context))
1556 		return 0;
1557 
1558 	ax = kmalloc(sizeof(*ax), GFP_ATOMIC);
1559 	if (!ax)
1560 		return -ENOMEM;
1561 
1562 	if (u_abs_timeout != NULL) {
1563 		if (copy_from_user(&ax->abs_timeout, u_abs_timeout, sizeof(ax->abs_timeout))) {
1564 			kfree(ax);
1565 			return -EFAULT;
1566 		}
1567 	} else
1568 		memset(&ax->abs_timeout, 0, sizeof(ax->abs_timeout));
1569 
1570 	ax->mqdes = mqdes;
1571 	ax->msg_len = msg_len;
1572 	ax->msg_prio = msg_prio;
1573 
1574 	ax->d.type = AUDIT_MQ_SENDRECV;
1575 	ax->d.next = context->aux;
1576 	context->aux = (void *)ax;
1577 	return 0;
1578 }
1579 
1580 /**
1581  * __audit_mq_timedreceive - record audit data for a POSIX MQ timed receive
1582  * @mqdes: MQ descriptor
1583  * @msg_len: Message length
1584  * @u_msg_prio: Message priority
1585  * @u_abs_timeout: Message timeout in absolute time
1586  *
1587  * Returns 0 for success or NULL context or < 0 on error.
1588  */
1589 int __audit_mq_timedreceive(mqd_t mqdes, size_t msg_len,
1590 				unsigned int __user *u_msg_prio,
1591 				const struct timespec __user *u_abs_timeout)
1592 {
1593 	struct audit_aux_data_mq_sendrecv *ax;
1594 	struct audit_context *context = current->audit_context;
1595 
1596 	if (!audit_enabled)
1597 		return 0;
1598 
1599 	if (likely(!context))
1600 		return 0;
1601 
1602 	ax = kmalloc(sizeof(*ax), GFP_ATOMIC);
1603 	if (!ax)
1604 		return -ENOMEM;
1605 
1606 	if (u_msg_prio != NULL) {
1607 		if (get_user(ax->msg_prio, u_msg_prio)) {
1608 			kfree(ax);
1609 			return -EFAULT;
1610 		}
1611 	} else
1612 		ax->msg_prio = 0;
1613 
1614 	if (u_abs_timeout != NULL) {
1615 		if (copy_from_user(&ax->abs_timeout, u_abs_timeout, sizeof(ax->abs_timeout))) {
1616 			kfree(ax);
1617 			return -EFAULT;
1618 		}
1619 	} else
1620 		memset(&ax->abs_timeout, 0, sizeof(ax->abs_timeout));
1621 
1622 	ax->mqdes = mqdes;
1623 	ax->msg_len = msg_len;
1624 
1625 	ax->d.type = AUDIT_MQ_SENDRECV;
1626 	ax->d.next = context->aux;
1627 	context->aux = (void *)ax;
1628 	return 0;
1629 }
1630 
1631 /**
1632  * __audit_mq_notify - record audit data for a POSIX MQ notify
1633  * @mqdes: MQ descriptor
1634  * @u_notification: Notification event
1635  *
1636  * Returns 0 for success or NULL context or < 0 on error.
1637  */
1638 
1639 int __audit_mq_notify(mqd_t mqdes, const struct sigevent __user *u_notification)
1640 {
1641 	struct audit_aux_data_mq_notify *ax;
1642 	struct audit_context *context = current->audit_context;
1643 
1644 	if (!audit_enabled)
1645 		return 0;
1646 
1647 	if (likely(!context))
1648 		return 0;
1649 
1650 	ax = kmalloc(sizeof(*ax), GFP_ATOMIC);
1651 	if (!ax)
1652 		return -ENOMEM;
1653 
1654 	if (u_notification != NULL) {
1655 		if (copy_from_user(&ax->notification, u_notification, sizeof(ax->notification))) {
1656 			kfree(ax);
1657 			return -EFAULT;
1658 		}
1659 	} else
1660 		memset(&ax->notification, 0, sizeof(ax->notification));
1661 
1662 	ax->mqdes = mqdes;
1663 
1664 	ax->d.type = AUDIT_MQ_NOTIFY;
1665 	ax->d.next = context->aux;
1666 	context->aux = (void *)ax;
1667 	return 0;
1668 }
1669 
1670 /**
1671  * __audit_mq_getsetattr - record audit data for a POSIX MQ get/set attribute
1672  * @mqdes: MQ descriptor
1673  * @mqstat: MQ flags
1674  *
1675  * Returns 0 for success or NULL context or < 0 on error.
1676  */
1677 int __audit_mq_getsetattr(mqd_t mqdes, struct mq_attr *mqstat)
1678 {
1679 	struct audit_aux_data_mq_getsetattr *ax;
1680 	struct audit_context *context = current->audit_context;
1681 
1682 	if (!audit_enabled)
1683 		return 0;
1684 
1685 	if (likely(!context))
1686 		return 0;
1687 
1688 	ax = kmalloc(sizeof(*ax), GFP_ATOMIC);
1689 	if (!ax)
1690 		return -ENOMEM;
1691 
1692 	ax->mqdes = mqdes;
1693 	ax->mqstat = *mqstat;
1694 
1695 	ax->d.type = AUDIT_MQ_GETSETATTR;
1696 	ax->d.next = context->aux;
1697 	context->aux = (void *)ax;
1698 	return 0;
1699 }
1700 
1701 /**
1702  * audit_ipc_obj - record audit data for ipc object
1703  * @ipcp: ipc permissions
1704  *
1705  * Returns 0 for success or NULL context or < 0 on error.
1706  */
1707 int __audit_ipc_obj(struct kern_ipc_perm *ipcp)
1708 {
1709 	struct audit_aux_data_ipcctl *ax;
1710 	struct audit_context *context = current->audit_context;
1711 
1712 	ax = kmalloc(sizeof(*ax), GFP_ATOMIC);
1713 	if (!ax)
1714 		return -ENOMEM;
1715 
1716 	ax->uid = ipcp->uid;
1717 	ax->gid = ipcp->gid;
1718 	ax->mode = ipcp->mode;
1719 	selinux_get_ipc_sid(ipcp, &ax->osid);
1720 
1721 	ax->d.type = AUDIT_IPC;
1722 	ax->d.next = context->aux;
1723 	context->aux = (void *)ax;
1724 	return 0;
1725 }
1726 
1727 /**
1728  * audit_ipc_set_perm - record audit data for new ipc permissions
1729  * @qbytes: msgq bytes
1730  * @uid: msgq user id
1731  * @gid: msgq group id
1732  * @mode: msgq mode (permissions)
1733  *
1734  * Returns 0 for success or NULL context or < 0 on error.
1735  */
1736 int __audit_ipc_set_perm(unsigned long qbytes, uid_t uid, gid_t gid, mode_t mode)
1737 {
1738 	struct audit_aux_data_ipcctl *ax;
1739 	struct audit_context *context = current->audit_context;
1740 
1741 	ax = kmalloc(sizeof(*ax), GFP_ATOMIC);
1742 	if (!ax)
1743 		return -ENOMEM;
1744 
1745 	ax->qbytes = qbytes;
1746 	ax->uid = uid;
1747 	ax->gid = gid;
1748 	ax->mode = mode;
1749 
1750 	ax->d.type = AUDIT_IPC_SET_PERM;
1751 	ax->d.next = context->aux;
1752 	context->aux = (void *)ax;
1753 	return 0;
1754 }
1755 
1756 int audit_bprm(struct linux_binprm *bprm)
1757 {
1758 	struct audit_aux_data_execve *ax;
1759 	struct audit_context *context = current->audit_context;
1760 	unsigned long p, next;
1761 	void *to;
1762 
1763 	if (likely(!audit_enabled || !context || context->dummy))
1764 		return 0;
1765 
1766 	ax = kmalloc(sizeof(*ax) + PAGE_SIZE * MAX_ARG_PAGES - bprm->p,
1767 				GFP_KERNEL);
1768 	if (!ax)
1769 		return -ENOMEM;
1770 
1771 	ax->argc = bprm->argc;
1772 	ax->envc = bprm->envc;
1773 	for (p = bprm->p, to = ax->mem; p < MAX_ARG_PAGES*PAGE_SIZE; p = next) {
1774 		struct page *page = bprm->page[p / PAGE_SIZE];
1775 		void *kaddr = kmap(page);
1776 		next = (p + PAGE_SIZE) & ~(PAGE_SIZE - 1);
1777 		memcpy(to, kaddr + (p & (PAGE_SIZE - 1)), next - p);
1778 		to += next - p;
1779 		kunmap(page);
1780 	}
1781 
1782 	ax->d.type = AUDIT_EXECVE;
1783 	ax->d.next = context->aux;
1784 	context->aux = (void *)ax;
1785 	return 0;
1786 }
1787 
1788 
1789 /**
1790  * audit_socketcall - record audit data for sys_socketcall
1791  * @nargs: number of args
1792  * @args: args array
1793  *
1794  * Returns 0 for success or NULL context or < 0 on error.
1795  */
1796 int audit_socketcall(int nargs, unsigned long *args)
1797 {
1798 	struct audit_aux_data_socketcall *ax;
1799 	struct audit_context *context = current->audit_context;
1800 
1801 	if (likely(!context || context->dummy))
1802 		return 0;
1803 
1804 	ax = kmalloc(sizeof(*ax) + nargs * sizeof(unsigned long), GFP_KERNEL);
1805 	if (!ax)
1806 		return -ENOMEM;
1807 
1808 	ax->nargs = nargs;
1809 	memcpy(ax->args, args, nargs * sizeof(unsigned long));
1810 
1811 	ax->d.type = AUDIT_SOCKETCALL;
1812 	ax->d.next = context->aux;
1813 	context->aux = (void *)ax;
1814 	return 0;
1815 }
1816 
1817 /**
1818  * audit_sockaddr - record audit data for sys_bind, sys_connect, sys_sendto
1819  * @len: data length in user space
1820  * @a: data address in kernel space
1821  *
1822  * Returns 0 for success or NULL context or < 0 on error.
1823  */
1824 int audit_sockaddr(int len, void *a)
1825 {
1826 	struct audit_aux_data_sockaddr *ax;
1827 	struct audit_context *context = current->audit_context;
1828 
1829 	if (likely(!context || context->dummy))
1830 		return 0;
1831 
1832 	ax = kmalloc(sizeof(*ax) + len, GFP_KERNEL);
1833 	if (!ax)
1834 		return -ENOMEM;
1835 
1836 	ax->len = len;
1837 	memcpy(ax->a, a, len);
1838 
1839 	ax->d.type = AUDIT_SOCKADDR;
1840 	ax->d.next = context->aux;
1841 	context->aux = (void *)ax;
1842 	return 0;
1843 }
1844 
1845 /**
1846  * audit_avc_path - record the granting or denial of permissions
1847  * @dentry: dentry to record
1848  * @mnt: mnt to record
1849  *
1850  * Returns 0 for success or NULL context or < 0 on error.
1851  *
1852  * Called from security/selinux/avc.c::avc_audit()
1853  */
1854 int audit_avc_path(struct dentry *dentry, struct vfsmount *mnt)
1855 {
1856 	struct audit_aux_data_path *ax;
1857 	struct audit_context *context = current->audit_context;
1858 
1859 	if (likely(!context))
1860 		return 0;
1861 
1862 	ax = kmalloc(sizeof(*ax), GFP_ATOMIC);
1863 	if (!ax)
1864 		return -ENOMEM;
1865 
1866 	ax->dentry = dget(dentry);
1867 	ax->mnt = mntget(mnt);
1868 
1869 	ax->d.type = AUDIT_AVC_PATH;
1870 	ax->d.next = context->aux;
1871 	context->aux = (void *)ax;
1872 	return 0;
1873 }
1874 
1875 /**
1876  * audit_signal_info - record signal info for shutting down audit subsystem
1877  * @sig: signal value
1878  * @t: task being signaled
1879  *
1880  * If the audit subsystem is being terminated, record the task (pid)
1881  * and uid that is doing that.
1882  */
1883 void __audit_signal_info(int sig, struct task_struct *t)
1884 {
1885 	extern pid_t audit_sig_pid;
1886 	extern uid_t audit_sig_uid;
1887 	extern u32 audit_sig_sid;
1888 
1889 	if (sig == SIGTERM || sig == SIGHUP || sig == SIGUSR1) {
1890 		struct task_struct *tsk = current;
1891 		struct audit_context *ctx = tsk->audit_context;
1892 		audit_sig_pid = tsk->pid;
1893 		if (ctx)
1894 			audit_sig_uid = ctx->loginuid;
1895 		else
1896 			audit_sig_uid = tsk->uid;
1897 		selinux_get_task_sid(tsk, &audit_sig_sid);
1898 	}
1899 }
1900