• Home
  • Line#
  • Scopes#
  • Navigate#
  • Raw
  • Download
1 /* audit.c -- Auditing support
2  * Gateway between the kernel (e.g., selinux) and the user-space audit daemon.
3  * System-call specific features have moved to auditsc.c
4  *
5  * Copyright 2003-2007 Red Hat Inc., Durham, North Carolina.
6  * All Rights Reserved.
7  *
8  * This program is free software; you can redistribute it and/or modify
9  * it under the terms of the GNU General Public License as published by
10  * the Free Software Foundation; either version 2 of the License, or
11  * (at your option) any later version.
12  *
13  * This program is distributed in the hope that it will be useful,
14  * but WITHOUT ANY WARRANTY; without even the implied warranty of
15  * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
16  * GNU General Public License for more details.
17  *
18  * You should have received a copy of the GNU General Public License
19  * along with this program; if not, write to the Free Software
20  * Foundation, Inc., 59 Temple Place, Suite 330, Boston, MA  02111-1307  USA
21  *
22  * Written by Rickard E. (Rik) Faith <faith@redhat.com>
23  *
24  * Goals: 1) Integrate fully with Security Modules.
25  *	  2) Minimal run-time overhead:
26  *	     a) Minimal when syscall auditing is disabled (audit_enable=0).
27  *	     b) Small when syscall auditing is enabled and no audit record
28  *		is generated (defer as much work as possible to record
29  *		generation time):
30  *		i) context is allocated,
31  *		ii) names from getname are stored without a copy, and
32  *		iii) inode information stored from path_lookup.
33  *	  3) Ability to disable syscall auditing at boot time (audit=0).
34  *	  4) Usable by other parts of the kernel (if audit_log* is called,
35  *	     then a syscall record will be generated automatically for the
36  *	     current syscall).
37  *	  5) Netlink interface to user-space.
38  *	  6) Support low-overhead kernel-based filtering to minimize the
39  *	     information that must be passed to user-space.
40  *
41  * Example user-space utilities: http://people.redhat.com/sgrubb/audit/
42  */
43 
44 #include <linux/init.h>
45 #include <asm/types.h>
46 #include <linux/atomic.h>
47 #include <linux/mm.h>
48 #include <linux/export.h>
49 #include <linux/slab.h>
50 #include <linux/err.h>
51 #include <linux/kthread.h>
52 #include <linux/kernel.h>
53 #include <linux/syscalls.h>
54 
55 #include <linux/audit.h>
56 
57 #include <net/sock.h>
58 #include <net/netlink.h>
59 #include <linux/skbuff.h>
60 #ifdef CONFIG_SECURITY
61 #include <linux/security.h>
62 #endif
63 #include <net/netlink.h>
64 #include <linux/freezer.h>
65 #include <linux/tty.h>
66 #include <linux/pid_namespace.h>
67 
68 #include "audit.h"
69 
70 /* No auditing will take place until audit_initialized == AUDIT_INITIALIZED.
71  * (Initialization happens after skb_init is called.) */
72 #define AUDIT_DISABLED		-1
73 #define AUDIT_UNINITIALIZED	0
74 #define AUDIT_INITIALIZED	1
75 static int	audit_initialized;
76 
77 #define AUDIT_OFF	0
78 #define AUDIT_ON	1
79 #define AUDIT_LOCKED	2
80 int		audit_enabled;
81 int		audit_ever_enabled;
82 
83 EXPORT_SYMBOL_GPL(audit_enabled);
84 
85 /* Default state when kernel boots without any parameters. */
86 static int	audit_default;
87 
88 /* If auditing cannot proceed, audit_failure selects what happens. */
89 static int	audit_failure = AUDIT_FAIL_PRINTK;
90 
91 /*
92  * If audit records are to be written to the netlink socket, audit_pid
93  * contains the pid of the auditd process and audit_nlk_portid contains
94  * the portid to use to send netlink messages to that process.
95  */
96 int		audit_pid;
97 static int	audit_nlk_portid;
98 
99 /* If audit_rate_limit is non-zero, limit the rate of sending audit records
100  * to that number per second.  This prevents DoS attacks, but results in
101  * audit records being dropped. */
102 static int	audit_rate_limit;
103 
104 /* Number of outstanding audit_buffers allowed. */
105 static int	audit_backlog_limit = 64;
106 static int	audit_backlog_wait_time = 60 * HZ;
107 static int	audit_backlog_wait_overflow = 0;
108 
109 /* The identity of the user shutting down the audit system. */
110 kuid_t		audit_sig_uid = INVALID_UID;
111 pid_t		audit_sig_pid = -1;
112 u32		audit_sig_sid = 0;
113 
114 /* Records can be lost in several ways:
115    0) [suppressed in audit_alloc]
116    1) out of memory in audit_log_start [kmalloc of struct audit_buffer]
117    2) out of memory in audit_log_move [alloc_skb]
118    3) suppressed due to audit_rate_limit
119    4) suppressed due to audit_backlog_limit
120 */
121 static atomic_t    audit_lost = ATOMIC_INIT(0);
122 
123 /* The netlink socket. */
124 static struct sock *audit_sock;
125 
126 /* Hash for inode-based rules */
127 struct list_head audit_inode_hash[AUDIT_INODE_BUCKETS];
128 
129 /* The audit_freelist is a list of pre-allocated audit buffers (if more
130  * than AUDIT_MAXFREE are in use, the audit buffer is freed instead of
131  * being placed on the freelist). */
132 static DEFINE_SPINLOCK(audit_freelist_lock);
133 static int	   audit_freelist_count;
134 static LIST_HEAD(audit_freelist);
135 
136 static struct sk_buff_head audit_skb_queue;
137 /* queue of skbs to send to auditd when/if it comes back */
138 static struct sk_buff_head audit_skb_hold_queue;
139 static struct task_struct *kauditd_task;
140 static DECLARE_WAIT_QUEUE_HEAD(kauditd_wait);
141 static DECLARE_WAIT_QUEUE_HEAD(audit_backlog_wait);
142 
143 /* Serialize requests from userspace. */
144 DEFINE_MUTEX(audit_cmd_mutex);
145 
146 /* AUDIT_BUFSIZ is the size of the temporary buffer used for formatting
147  * audit records.  Since printk uses a 1024 byte buffer, this buffer
148  * should be at least that large. */
149 #define AUDIT_BUFSIZ 1024
150 
151 /* AUDIT_MAXFREE is the number of empty audit_buffers we keep on the
152  * audit_freelist.  Doing so eliminates many kmalloc/kfree calls. */
153 #define AUDIT_MAXFREE  (2*NR_CPUS)
154 
155 /* The audit_buffer is used when formatting an audit record.  The caller
156  * locks briefly to get the record off the freelist or to allocate the
157  * buffer, and locks briefly to send the buffer to the netlink layer or
158  * to place it on a transmit queue.  Multiple audit_buffers can be in
159  * use simultaneously. */
160 struct audit_buffer {
161 	struct list_head     list;
162 	struct sk_buff       *skb;	/* formatted skb ready to send */
163 	struct audit_context *ctx;	/* NULL or associated context */
164 	gfp_t		     gfp_mask;
165 };
166 
167 struct audit_reply {
168 	int pid;
169 	struct sk_buff *skb;
170 };
171 
audit_set_pid(struct audit_buffer * ab,pid_t pid)172 static void audit_set_pid(struct audit_buffer *ab, pid_t pid)
173 {
174 	if (ab) {
175 		struct nlmsghdr *nlh = nlmsg_hdr(ab->skb);
176 		nlh->nlmsg_pid = pid;
177 	}
178 }
179 
audit_panic(const char * message)180 void audit_panic(const char *message)
181 {
182 	switch (audit_failure)
183 	{
184 	case AUDIT_FAIL_SILENT:
185 		break;
186 	case AUDIT_FAIL_PRINTK:
187 		if (printk_ratelimit())
188 			printk(KERN_ERR "audit: %s\n", message);
189 		break;
190 	case AUDIT_FAIL_PANIC:
191 		/* test audit_pid since printk is always losey, why bother? */
192 		if (audit_pid)
193 			panic("audit: %s\n", message);
194 		break;
195 	}
196 }
197 
audit_rate_check(void)198 static inline int audit_rate_check(void)
199 {
200 	static unsigned long	last_check = 0;
201 	static int		messages   = 0;
202 	static DEFINE_SPINLOCK(lock);
203 	unsigned long		flags;
204 	unsigned long		now;
205 	unsigned long		elapsed;
206 	int			retval	   = 0;
207 
208 	if (!audit_rate_limit) return 1;
209 
210 	spin_lock_irqsave(&lock, flags);
211 	if (++messages < audit_rate_limit) {
212 		retval = 1;
213 	} else {
214 		now     = jiffies;
215 		elapsed = now - last_check;
216 		if (elapsed > HZ) {
217 			last_check = now;
218 			messages   = 0;
219 			retval     = 1;
220 		}
221 	}
222 	spin_unlock_irqrestore(&lock, flags);
223 
224 	return retval;
225 }
226 
227 /**
228  * audit_log_lost - conditionally log lost audit message event
229  * @message: the message stating reason for lost audit message
230  *
231  * Emit at least 1 message per second, even if audit_rate_check is
232  * throttling.
233  * Always increment the lost messages counter.
234 */
audit_log_lost(const char * message)235 void audit_log_lost(const char *message)
236 {
237 	static unsigned long	last_msg = 0;
238 	static DEFINE_SPINLOCK(lock);
239 	unsigned long		flags;
240 	unsigned long		now;
241 	int			print;
242 
243 	atomic_inc(&audit_lost);
244 
245 	print = (audit_failure == AUDIT_FAIL_PANIC || !audit_rate_limit);
246 
247 	if (!print) {
248 		spin_lock_irqsave(&lock, flags);
249 		now = jiffies;
250 		if (now - last_msg > HZ) {
251 			print = 1;
252 			last_msg = now;
253 		}
254 		spin_unlock_irqrestore(&lock, flags);
255 	}
256 
257 	if (print) {
258 		if (printk_ratelimit())
259 			printk(KERN_WARNING
260 				"audit: audit_lost=%d audit_rate_limit=%d "
261 				"audit_backlog_limit=%d\n",
262 				atomic_read(&audit_lost),
263 				audit_rate_limit,
264 				audit_backlog_limit);
265 		audit_panic(message);
266 	}
267 }
268 
audit_log_config_change(char * function_name,int new,int old,int allow_changes)269 static int audit_log_config_change(char *function_name, int new, int old,
270 				   int allow_changes)
271 {
272 	struct audit_buffer *ab;
273 	int rc = 0;
274 
275 	ab = audit_log_start(NULL, GFP_KERNEL, AUDIT_CONFIG_CHANGE);
276 	if (unlikely(!ab))
277 		return rc;
278 	audit_log_format(ab, "%s=%d old=%d", function_name, new, old);
279 	audit_log_session_info(ab);
280 	rc = audit_log_task_context(ab);
281 	if (rc)
282 		allow_changes = 0; /* Something weird, deny request */
283 	audit_log_format(ab, " res=%d", allow_changes);
284 	audit_log_end(ab);
285 	return rc;
286 }
287 
audit_do_config_change(char * function_name,int * to_change,int new)288 static int audit_do_config_change(char *function_name, int *to_change, int new)
289 {
290 	int allow_changes, rc = 0, old = *to_change;
291 
292 	/* check if we are locked */
293 	if (audit_enabled == AUDIT_LOCKED)
294 		allow_changes = 0;
295 	else
296 		allow_changes = 1;
297 
298 	if (audit_enabled != AUDIT_OFF) {
299 		rc = audit_log_config_change(function_name, new, old, allow_changes);
300 		if (rc)
301 			allow_changes = 0;
302 	}
303 
304 	/* If we are allowed, make the change */
305 	if (allow_changes == 1)
306 		*to_change = new;
307 	/* Not allowed, update reason */
308 	else if (rc == 0)
309 		rc = -EPERM;
310 	return rc;
311 }
312 
audit_set_rate_limit(int limit)313 static int audit_set_rate_limit(int limit)
314 {
315 	return audit_do_config_change("audit_rate_limit", &audit_rate_limit, limit);
316 }
317 
audit_set_backlog_limit(int limit)318 static int audit_set_backlog_limit(int limit)
319 {
320 	return audit_do_config_change("audit_backlog_limit", &audit_backlog_limit, limit);
321 }
322 
audit_set_enabled(int state)323 static int audit_set_enabled(int state)
324 {
325 	int rc;
326 	if (state < AUDIT_OFF || state > AUDIT_LOCKED)
327 		return -EINVAL;
328 
329 	rc =  audit_do_config_change("audit_enabled", &audit_enabled, state);
330 	if (!rc)
331 		audit_ever_enabled |= !!state;
332 
333 	return rc;
334 }
335 
audit_set_failure(int state)336 static int audit_set_failure(int state)
337 {
338 	if (state != AUDIT_FAIL_SILENT
339 	    && state != AUDIT_FAIL_PRINTK
340 	    && state != AUDIT_FAIL_PANIC)
341 		return -EINVAL;
342 
343 	return audit_do_config_change("audit_failure", &audit_failure, state);
344 }
345 
346 /*
347  * Queue skbs to be sent to auditd when/if it comes back.  These skbs should
348  * already have been sent via prink/syslog and so if these messages are dropped
349  * it is not a huge concern since we already passed the audit_log_lost()
350  * notification and stuff.  This is just nice to get audit messages during
351  * boot before auditd is running or messages generated while auditd is stopped.
352  * This only holds messages is audit_default is set, aka booting with audit=1
353  * or building your kernel that way.
354  */
audit_hold_skb(struct sk_buff * skb)355 static void audit_hold_skb(struct sk_buff *skb)
356 {
357 	if (audit_default &&
358 	    skb_queue_len(&audit_skb_hold_queue) < audit_backlog_limit)
359 		skb_queue_tail(&audit_skb_hold_queue, skb);
360 	else
361 		kfree_skb(skb);
362 }
363 
364 /*
365  * For one reason or another this nlh isn't getting delivered to the userspace
366  * audit daemon, just send it to printk.
367  */
audit_printk_skb(struct sk_buff * skb)368 static void audit_printk_skb(struct sk_buff *skb)
369 {
370 	struct nlmsghdr *nlh = nlmsg_hdr(skb);
371 	char *data = nlmsg_data(nlh);
372 
373 	if (nlh->nlmsg_type != AUDIT_EOE) {
374 		if (printk_ratelimit())
375 			printk(KERN_NOTICE "type=%d %s\n", nlh->nlmsg_type, data);
376 		else
377 			audit_log_lost("printk limit exceeded\n");
378 	}
379 
380 	audit_hold_skb(skb);
381 }
382 
kauditd_send_skb(struct sk_buff * skb)383 static void kauditd_send_skb(struct sk_buff *skb)
384 {
385 	int err;
386 	/* take a reference in case we can't send it and we want to hold it */
387 	skb_get(skb);
388 	err = netlink_unicast(audit_sock, skb, audit_nlk_portid, 0);
389 	if (err < 0) {
390 		BUG_ON(err != -ECONNREFUSED); /* Shouldn't happen */
391 		printk(KERN_ERR "audit: *NO* daemon at audit_pid=%d\n", audit_pid);
392 		audit_log_lost("auditd disappeared\n");
393 		audit_pid = 0;
394 		/* we might get lucky and get this in the next auditd */
395 		audit_hold_skb(skb);
396 	} else
397 		/* drop the extra reference if sent ok */
398 		consume_skb(skb);
399 }
400 
401 /*
402  * flush_hold_queue - empty the hold queue if auditd appears
403  *
404  * If auditd just started, drain the queue of messages already
405  * sent to syslog/printk.  Remember loss here is ok.  We already
406  * called audit_log_lost() if it didn't go out normally.  so the
407  * race between the skb_dequeue and the next check for audit_pid
408  * doesn't matter.
409  *
410  * If you ever find kauditd to be too slow we can get a perf win
411  * by doing our own locking and keeping better track if there
412  * are messages in this queue.  I don't see the need now, but
413  * in 5 years when I want to play with this again I'll see this
414  * note and still have no friggin idea what i'm thinking today.
415  */
flush_hold_queue(void)416 static void flush_hold_queue(void)
417 {
418 	struct sk_buff *skb;
419 
420 	if (!audit_default || !audit_pid)
421 		return;
422 
423 	skb = skb_dequeue(&audit_skb_hold_queue);
424 	if (likely(!skb))
425 		return;
426 
427 	while (skb && audit_pid) {
428 		kauditd_send_skb(skb);
429 		skb = skb_dequeue(&audit_skb_hold_queue);
430 	}
431 
432 	/*
433 	 * if auditd just disappeared but we
434 	 * dequeued an skb we need to drop ref
435 	 */
436 	if (skb)
437 		consume_skb(skb);
438 }
439 
kauditd_thread(void * dummy)440 static int kauditd_thread(void *dummy)
441 {
442 	set_freezable();
443 	while (!kthread_should_stop()) {
444 		struct sk_buff *skb;
445 		DECLARE_WAITQUEUE(wait, current);
446 
447 		flush_hold_queue();
448 
449 		skb = skb_dequeue(&audit_skb_queue);
450 		wake_up(&audit_backlog_wait);
451 		if (skb) {
452 			if (audit_pid)
453 				kauditd_send_skb(skb);
454 			else
455 				audit_printk_skb(skb);
456 			continue;
457 		}
458 		set_current_state(TASK_INTERRUPTIBLE);
459 		add_wait_queue(&kauditd_wait, &wait);
460 
461 		if (!skb_queue_len(&audit_skb_queue)) {
462 			try_to_freeze();
463 			schedule();
464 		}
465 
466 		__set_current_state(TASK_RUNNING);
467 		remove_wait_queue(&kauditd_wait, &wait);
468 	}
469 	return 0;
470 }
471 
audit_send_list(void * _dest)472 int audit_send_list(void *_dest)
473 {
474 	struct audit_netlink_list *dest = _dest;
475 	int pid = dest->pid;
476 	struct sk_buff *skb;
477 
478 	/* wait for parent to finish and send an ACK */
479 	mutex_lock(&audit_cmd_mutex);
480 	mutex_unlock(&audit_cmd_mutex);
481 
482 	while ((skb = __skb_dequeue(&dest->q)) != NULL)
483 		netlink_unicast(audit_sock, skb, pid, 0);
484 
485 	kfree(dest);
486 
487 	return 0;
488 }
489 
audit_make_reply(int pid,int seq,int type,int done,int multi,const void * payload,int size)490 struct sk_buff *audit_make_reply(int pid, int seq, int type, int done,
491 				 int multi, const void *payload, int size)
492 {
493 	struct sk_buff	*skb;
494 	struct nlmsghdr	*nlh;
495 	void		*data;
496 	int		flags = multi ? NLM_F_MULTI : 0;
497 	int		t     = done  ? NLMSG_DONE  : type;
498 
499 	skb = nlmsg_new(size, GFP_KERNEL);
500 	if (!skb)
501 		return NULL;
502 
503 	nlh	= nlmsg_put(skb, pid, seq, t, size, flags);
504 	if (!nlh)
505 		goto out_kfree_skb;
506 	data = nlmsg_data(nlh);
507 	memcpy(data, payload, size);
508 	return skb;
509 
510 out_kfree_skb:
511 	kfree_skb(skb);
512 	return NULL;
513 }
514 
audit_send_reply_thread(void * arg)515 static int audit_send_reply_thread(void *arg)
516 {
517 	struct audit_reply *reply = (struct audit_reply *)arg;
518 
519 	mutex_lock(&audit_cmd_mutex);
520 	mutex_unlock(&audit_cmd_mutex);
521 
522 	/* Ignore failure. It'll only happen if the sender goes away,
523 	   because our timeout is set to infinite. */
524 	netlink_unicast(audit_sock, reply->skb, reply->pid, 0);
525 	kfree(reply);
526 	return 0;
527 }
528 /**
529  * audit_send_reply - send an audit reply message via netlink
530  * @pid: process id to send reply to
531  * @seq: sequence number
532  * @type: audit message type
533  * @done: done (last) flag
534  * @multi: multi-part message flag
535  * @payload: payload data
536  * @size: payload size
537  *
538  * Allocates an skb, builds the netlink message, and sends it to the pid.
539  * No failure notifications.
540  */
audit_send_reply(int pid,int seq,int type,int done,int multi,const void * payload,int size)541 static void audit_send_reply(int pid, int seq, int type, int done, int multi,
542 			     const void *payload, int size)
543 {
544 	struct sk_buff *skb;
545 	struct task_struct *tsk;
546 	struct audit_reply *reply = kmalloc(sizeof(struct audit_reply),
547 					    GFP_KERNEL);
548 
549 	if (!reply)
550 		return;
551 
552 	skb = audit_make_reply(pid, seq, type, done, multi, payload, size);
553 	if (!skb)
554 		goto out;
555 
556 	reply->pid = pid;
557 	reply->skb = skb;
558 
559 	tsk = kthread_run(audit_send_reply_thread, reply, "audit_send_reply");
560 	if (!IS_ERR(tsk))
561 		return;
562 	kfree_skb(skb);
563 out:
564 	kfree(reply);
565 }
566 
567 /*
568  * Check for appropriate CAP_AUDIT_ capabilities on incoming audit
569  * control messages.
570  */
audit_netlink_ok(struct sk_buff * skb,u16 msg_type)571 static int audit_netlink_ok(struct sk_buff *skb, u16 msg_type)
572 {
573 	int err = 0;
574 
575 	/* Only support the initial namespaces for now. */
576 	if ((current_user_ns() != &init_user_ns) ||
577 	    (task_active_pid_ns(current) != &init_pid_ns))
578 		return -EPERM;
579 
580 	switch (msg_type) {
581 	case AUDIT_LIST:
582 	case AUDIT_ADD:
583 	case AUDIT_DEL:
584 		return -EOPNOTSUPP;
585 	case AUDIT_GET:
586 	case AUDIT_SET:
587 	case AUDIT_LIST_RULES:
588 	case AUDIT_ADD_RULE:
589 	case AUDIT_DEL_RULE:
590 	case AUDIT_SIGNAL_INFO:
591 	case AUDIT_TTY_GET:
592 	case AUDIT_TTY_SET:
593 	case AUDIT_TRIM:
594 	case AUDIT_MAKE_EQUIV:
595 		if (!capable(CAP_AUDIT_CONTROL))
596 			err = -EPERM;
597 		break;
598 	case AUDIT_USER:
599 	case AUDIT_FIRST_USER_MSG ... AUDIT_LAST_USER_MSG:
600 	case AUDIT_FIRST_USER_MSG2 ... AUDIT_LAST_USER_MSG2:
601 		if (!capable(CAP_AUDIT_WRITE))
602 			err = -EPERM;
603 		break;
604 	default:  /* bad msg */
605 		err = -EINVAL;
606 	}
607 
608 	return err;
609 }
610 
audit_log_common_recv_msg(struct audit_buffer ** ab,u16 msg_type)611 static int audit_log_common_recv_msg(struct audit_buffer **ab, u16 msg_type)
612 {
613 	int rc = 0;
614 	uid_t uid = from_kuid(&init_user_ns, current_uid());
615 
616 	if (!audit_enabled) {
617 		*ab = NULL;
618 		return rc;
619 	}
620 
621 	*ab = audit_log_start(NULL, GFP_KERNEL, msg_type);
622 	if (unlikely(!*ab))
623 		return rc;
624 	audit_log_format(*ab, "pid=%d uid=%u", task_tgid_vnr(current), uid);
625 	audit_log_session_info(*ab);
626 	audit_log_task_context(*ab);
627 
628 	return rc;
629 }
630 
audit_receive_msg(struct sk_buff * skb,struct nlmsghdr * nlh)631 static int audit_receive_msg(struct sk_buff *skb, struct nlmsghdr *nlh)
632 {
633 	u32			seq;
634 	void			*data;
635 	struct audit_status	*status_get, status_set;
636 	int			err;
637 	struct audit_buffer	*ab;
638 	u16			msg_type = nlh->nlmsg_type;
639 	struct audit_sig_info   *sig_data;
640 	char			*ctx = NULL;
641 	u32			len;
642 
643 	err = audit_netlink_ok(skb, msg_type);
644 	if (err)
645 		return err;
646 
647 	/* As soon as there's any sign of userspace auditd,
648 	 * start kauditd to talk to it */
649 	if (!kauditd_task) {
650 		kauditd_task = kthread_run(kauditd_thread, NULL, "kauditd");
651 		if (IS_ERR(kauditd_task)) {
652 			err = PTR_ERR(kauditd_task);
653 			kauditd_task = NULL;
654 			return err;
655 		}
656 	}
657 	seq  = nlh->nlmsg_seq;
658 	data = nlmsg_data(nlh);
659 
660 	switch (msg_type) {
661 	case AUDIT_GET:
662 		status_set.enabled	 = audit_enabled;
663 		status_set.failure	 = audit_failure;
664 		status_set.pid		 = audit_pid;
665 		status_set.rate_limit	 = audit_rate_limit;
666 		status_set.backlog_limit = audit_backlog_limit;
667 		status_set.lost		 = atomic_read(&audit_lost);
668 		status_set.backlog	 = skb_queue_len(&audit_skb_queue);
669 		audit_send_reply(NETLINK_CB(skb).portid, seq, AUDIT_GET, 0, 0,
670 				 &status_set, sizeof(status_set));
671 		break;
672 	case AUDIT_SET:
673 		if (nlh->nlmsg_len < sizeof(struct audit_status))
674 			return -EINVAL;
675 		status_get   = (struct audit_status *)data;
676 		if (status_get->mask & AUDIT_STATUS_ENABLED) {
677 			err = audit_set_enabled(status_get->enabled);
678 			if (err < 0)
679 				return err;
680 		}
681 		if (status_get->mask & AUDIT_STATUS_FAILURE) {
682 			err = audit_set_failure(status_get->failure);
683 			if (err < 0)
684 				return err;
685 		}
686 		if (status_get->mask & AUDIT_STATUS_PID) {
687 			/* NOTE: we are using task_tgid_vnr() below because
688 			 *       the s.pid value is relative to the namespace
689 			 *       of the caller; at present this doesn't matter
690 			 *       much since you can really only run auditd
691 			 *       from the initial pid namespace, but something
692 			 *       to keep in mind if this changes */
693 			int new_pid = status_get->pid;
694 
695 			if (audit_enabled != AUDIT_OFF)
696 				audit_log_config_change("audit_pid", new_pid, audit_pid, 1);
697 			audit_pid = new_pid;
698 			audit_nlk_portid = NETLINK_CB(skb).portid;
699 		}
700 		if (status_get->mask & AUDIT_STATUS_RATE_LIMIT) {
701 			err = audit_set_rate_limit(status_get->rate_limit);
702 			if (err < 0)
703 				return err;
704 		}
705 		if (status_get->mask & AUDIT_STATUS_BACKLOG_LIMIT)
706 			err = audit_set_backlog_limit(status_get->backlog_limit);
707 		break;
708 	case AUDIT_USER:
709 	case AUDIT_FIRST_USER_MSG ... AUDIT_LAST_USER_MSG:
710 	case AUDIT_FIRST_USER_MSG2 ... AUDIT_LAST_USER_MSG2:
711 		if (!audit_enabled && msg_type != AUDIT_USER_AVC)
712 			return 0;
713 
714 		err = audit_filter_user(msg_type);
715 		if (err == 1) {
716 			err = 0;
717 			if (msg_type == AUDIT_USER_TTY) {
718 				err = tty_audit_push_current();
719 				if (err)
720 					break;
721 			}
722 			audit_log_common_recv_msg(&ab, msg_type);
723 			if (msg_type != AUDIT_USER_TTY)
724 				audit_log_format(ab, " msg='%.1024s'",
725 						 (char *)data);
726 			else {
727 				int size;
728 
729 				audit_log_format(ab, " data=");
730 				size = nlmsg_len(nlh);
731 				if (size > 0 &&
732 				    ((unsigned char *)data)[size - 1] == '\0')
733 					size--;
734 				audit_log_n_untrustedstring(ab, data, size);
735 			}
736 			audit_set_pid(ab, NETLINK_CB(skb).portid);
737 			audit_log_end(ab);
738 		}
739 		break;
740 	case AUDIT_ADD_RULE:
741 	case AUDIT_DEL_RULE:
742 		if (nlmsg_len(nlh) < sizeof(struct audit_rule_data))
743 			return -EINVAL;
744 		if (audit_enabled == AUDIT_LOCKED) {
745 			audit_log_common_recv_msg(&ab, AUDIT_CONFIG_CHANGE);
746 			audit_log_format(ab, " audit_enabled=%d res=0", audit_enabled);
747 			audit_log_end(ab);
748 			return -EPERM;
749 		}
750 		/* fallthrough */
751 	case AUDIT_LIST_RULES:
752 		err = audit_receive_filter(msg_type, NETLINK_CB(skb).portid,
753 					   seq, data, nlmsg_len(nlh));
754 		break;
755 	case AUDIT_TRIM:
756 		audit_trim_trees();
757 		audit_log_common_recv_msg(&ab, AUDIT_CONFIG_CHANGE);
758 		audit_log_format(ab, " op=trim res=1");
759 		audit_log_end(ab);
760 		break;
761 	case AUDIT_MAKE_EQUIV: {
762 		void *bufp = data;
763 		u32 sizes[2];
764 		size_t msglen = nlmsg_len(nlh);
765 		char *old, *new;
766 
767 		err = -EINVAL;
768 		if (msglen < 2 * sizeof(u32))
769 			break;
770 		memcpy(sizes, bufp, 2 * sizeof(u32));
771 		bufp += 2 * sizeof(u32);
772 		msglen -= 2 * sizeof(u32);
773 		old = audit_unpack_string(&bufp, &msglen, sizes[0]);
774 		if (IS_ERR(old)) {
775 			err = PTR_ERR(old);
776 			break;
777 		}
778 		new = audit_unpack_string(&bufp, &msglen, sizes[1]);
779 		if (IS_ERR(new)) {
780 			err = PTR_ERR(new);
781 			kfree(old);
782 			break;
783 		}
784 		/* OK, here comes... */
785 		err = audit_tag_tree(old, new);
786 
787 		audit_log_common_recv_msg(&ab, AUDIT_CONFIG_CHANGE);
788 
789 		audit_log_format(ab, " op=make_equiv old=");
790 		audit_log_untrustedstring(ab, old);
791 		audit_log_format(ab, " new=");
792 		audit_log_untrustedstring(ab, new);
793 		audit_log_format(ab, " res=%d", !err);
794 		audit_log_end(ab);
795 		kfree(old);
796 		kfree(new);
797 		break;
798 	}
799 	case AUDIT_SIGNAL_INFO:
800 		len = 0;
801 		if (audit_sig_sid) {
802 			err = security_secid_to_secctx(audit_sig_sid, &ctx, &len);
803 			if (err)
804 				return err;
805 		}
806 		sig_data = kmalloc(sizeof(*sig_data) + len, GFP_KERNEL);
807 		if (!sig_data) {
808 			if (audit_sig_sid)
809 				security_release_secctx(ctx, len);
810 			return -ENOMEM;
811 		}
812 		sig_data->uid = from_kuid(&init_user_ns, audit_sig_uid);
813 		sig_data->pid = audit_sig_pid;
814 		if (audit_sig_sid) {
815 			memcpy(sig_data->ctx, ctx, len);
816 			security_release_secctx(ctx, len);
817 		}
818 		audit_send_reply(NETLINK_CB(skb).portid, seq, AUDIT_SIGNAL_INFO,
819 				0, 0, sig_data, sizeof(*sig_data) + len);
820 		kfree(sig_data);
821 		break;
822 	case AUDIT_TTY_GET: {
823 		struct audit_tty_status s;
824 		struct task_struct *tsk = current;
825 
826 		spin_lock(&tsk->sighand->siglock);
827 		s.enabled = tsk->signal->audit_tty != 0;
828 		s.log_passwd = tsk->signal->audit_tty_log_passwd;
829 		spin_unlock(&tsk->sighand->siglock);
830 
831 		audit_send_reply(NETLINK_CB(skb).portid, seq,
832 				 AUDIT_TTY_GET, 0, 0, &s, sizeof(s));
833 		break;
834 	}
835 	case AUDIT_TTY_SET: {
836 		struct audit_tty_status s;
837 		struct task_struct *tsk = current;
838 
839 		memset(&s, 0, sizeof(s));
840 		/* guard against past and future API changes */
841 		memcpy(&s, data, min(sizeof(s), (size_t)nlh->nlmsg_len));
842 		if ((s.enabled != 0 && s.enabled != 1) ||
843 		    (s.log_passwd != 0 && s.log_passwd != 1))
844 			return -EINVAL;
845 
846 		spin_lock(&tsk->sighand->siglock);
847 		tsk->signal->audit_tty = s.enabled;
848 		tsk->signal->audit_tty_log_passwd = s.log_passwd;
849 		spin_unlock(&tsk->sighand->siglock);
850 		break;
851 	}
852 	default:
853 		err = -EINVAL;
854 		break;
855 	}
856 
857 	return err < 0 ? err : 0;
858 }
859 
860 /*
861  * Get message from skb.  Each message is processed by audit_receive_msg.
862  * Malformed skbs with wrong length are discarded silently.
863  */
audit_receive_skb(struct sk_buff * skb)864 static void audit_receive_skb(struct sk_buff *skb)
865 {
866 	struct nlmsghdr *nlh;
867 	/*
868 	 * len MUST be signed for nlmsg_next to be able to dec it below 0
869 	 * if the nlmsg_len was not aligned
870 	 */
871 	int len;
872 	int err;
873 
874 	nlh = nlmsg_hdr(skb);
875 	len = skb->len;
876 
877 	while (nlmsg_ok(nlh, len)) {
878 		err = audit_receive_msg(skb, nlh);
879 		/* if err or if this message says it wants a response */
880 		if (err || (nlh->nlmsg_flags & NLM_F_ACK))
881 			netlink_ack(skb, nlh, err);
882 
883 		nlh = nlmsg_next(nlh, &len);
884 	}
885 }
886 
887 /* Receive messages from netlink socket. */
audit_receive(struct sk_buff * skb)888 static void audit_receive(struct sk_buff  *skb)
889 {
890 	mutex_lock(&audit_cmd_mutex);
891 	audit_receive_skb(skb);
892 	mutex_unlock(&audit_cmd_mutex);
893 }
894 
895 /* Initialize audit support at boot time. */
audit_init(void)896 static int __init audit_init(void)
897 {
898 	int i;
899 	struct netlink_kernel_cfg cfg = {
900 		.input	= audit_receive,
901 	};
902 
903 	if (audit_initialized == AUDIT_DISABLED)
904 		return 0;
905 
906 	printk(KERN_INFO "audit: initializing netlink socket (%s)\n",
907 	       audit_default ? "enabled" : "disabled");
908 	audit_sock = netlink_kernel_create(&init_net, NETLINK_AUDIT, &cfg);
909 	if (!audit_sock)
910 		audit_panic("cannot initialize netlink socket");
911 	else
912 		audit_sock->sk_sndtimeo = MAX_SCHEDULE_TIMEOUT;
913 
914 	skb_queue_head_init(&audit_skb_queue);
915 	skb_queue_head_init(&audit_skb_hold_queue);
916 	audit_initialized = AUDIT_INITIALIZED;
917 	audit_enabled = audit_default;
918 	audit_ever_enabled |= !!audit_default;
919 
920 	audit_log(NULL, GFP_KERNEL, AUDIT_KERNEL, "initialized");
921 
922 	for (i = 0; i < AUDIT_INODE_BUCKETS; i++)
923 		INIT_LIST_HEAD(&audit_inode_hash[i]);
924 
925 	return 0;
926 }
927 __initcall(audit_init);
928 
929 /* Process kernel command-line parameter at boot time.  audit=0 or audit=1. */
audit_enable(char * str)930 static int __init audit_enable(char *str)
931 {
932 	audit_default = !!simple_strtol(str, NULL, 0);
933 	if (!audit_default)
934 		audit_initialized = AUDIT_DISABLED;
935 
936 	printk(KERN_INFO "audit: %s", audit_default ? "enabled" : "disabled");
937 
938 	if (audit_initialized == AUDIT_INITIALIZED) {
939 		audit_enabled = audit_default;
940 		audit_ever_enabled |= !!audit_default;
941 	} else if (audit_initialized == AUDIT_UNINITIALIZED) {
942 		printk(" (after initialization)");
943 	} else {
944 		printk(" (until reboot)");
945 	}
946 	printk("\n");
947 
948 	return 1;
949 }
950 
951 __setup("audit=", audit_enable);
952 
audit_buffer_free(struct audit_buffer * ab)953 static void audit_buffer_free(struct audit_buffer *ab)
954 {
955 	unsigned long flags;
956 
957 	if (!ab)
958 		return;
959 
960 	if (ab->skb)
961 		kfree_skb(ab->skb);
962 
963 	spin_lock_irqsave(&audit_freelist_lock, flags);
964 	if (audit_freelist_count > AUDIT_MAXFREE)
965 		kfree(ab);
966 	else {
967 		audit_freelist_count++;
968 		list_add(&ab->list, &audit_freelist);
969 	}
970 	spin_unlock_irqrestore(&audit_freelist_lock, flags);
971 }
972 
audit_buffer_alloc(struct audit_context * ctx,gfp_t gfp_mask,int type)973 static struct audit_buffer * audit_buffer_alloc(struct audit_context *ctx,
974 						gfp_t gfp_mask, int type)
975 {
976 	unsigned long flags;
977 	struct audit_buffer *ab = NULL;
978 	struct nlmsghdr *nlh;
979 
980 	spin_lock_irqsave(&audit_freelist_lock, flags);
981 	if (!list_empty(&audit_freelist)) {
982 		ab = list_entry(audit_freelist.next,
983 				struct audit_buffer, list);
984 		list_del(&ab->list);
985 		--audit_freelist_count;
986 	}
987 	spin_unlock_irqrestore(&audit_freelist_lock, flags);
988 
989 	if (!ab) {
990 		ab = kmalloc(sizeof(*ab), gfp_mask);
991 		if (!ab)
992 			goto err;
993 	}
994 
995 	ab->ctx = ctx;
996 	ab->gfp_mask = gfp_mask;
997 
998 	ab->skb = nlmsg_new(AUDIT_BUFSIZ, gfp_mask);
999 	if (!ab->skb)
1000 		goto err;
1001 
1002 	nlh = nlmsg_put(ab->skb, 0, 0, type, 0, 0);
1003 	if (!nlh)
1004 		goto out_kfree_skb;
1005 
1006 	return ab;
1007 
1008 out_kfree_skb:
1009 	kfree_skb(ab->skb);
1010 	ab->skb = NULL;
1011 err:
1012 	audit_buffer_free(ab);
1013 	return NULL;
1014 }
1015 
1016 /**
1017  * audit_serial - compute a serial number for the audit record
1018  *
1019  * Compute a serial number for the audit record.  Audit records are
1020  * written to user-space as soon as they are generated, so a complete
1021  * audit record may be written in several pieces.  The timestamp of the
1022  * record and this serial number are used by the user-space tools to
1023  * determine which pieces belong to the same audit record.  The
1024  * (timestamp,serial) tuple is unique for each syscall and is live from
1025  * syscall entry to syscall exit.
1026  *
1027  * NOTE: Another possibility is to store the formatted records off the
1028  * audit context (for those records that have a context), and emit them
1029  * all at syscall exit.  However, this could delay the reporting of
1030  * significant errors until syscall exit (or never, if the system
1031  * halts).
1032  */
audit_serial(void)1033 unsigned int audit_serial(void)
1034 {
1035 	static DEFINE_SPINLOCK(serial_lock);
1036 	static unsigned int serial = 0;
1037 
1038 	unsigned long flags;
1039 	unsigned int ret;
1040 
1041 	spin_lock_irqsave(&serial_lock, flags);
1042 	do {
1043 		ret = ++serial;
1044 	} while (unlikely(!ret));
1045 	spin_unlock_irqrestore(&serial_lock, flags);
1046 
1047 	return ret;
1048 }
1049 
audit_get_stamp(struct audit_context * ctx,struct timespec * t,unsigned int * serial)1050 static inline void audit_get_stamp(struct audit_context *ctx,
1051 				   struct timespec *t, unsigned int *serial)
1052 {
1053 	if (!ctx || !auditsc_get_stamp(ctx, t, serial)) {
1054 		*t = CURRENT_TIME;
1055 		*serial = audit_serial();
1056 	}
1057 }
1058 
1059 /*
1060  * Wait for auditd to drain the queue a little
1061  */
wait_for_auditd(unsigned long sleep_time)1062 static void wait_for_auditd(unsigned long sleep_time)
1063 {
1064 	DECLARE_WAITQUEUE(wait, current);
1065 	set_current_state(TASK_UNINTERRUPTIBLE);
1066 	add_wait_queue(&audit_backlog_wait, &wait);
1067 
1068 	if (audit_backlog_limit &&
1069 	    skb_queue_len(&audit_skb_queue) > audit_backlog_limit)
1070 		schedule_timeout(sleep_time);
1071 
1072 	__set_current_state(TASK_RUNNING);
1073 	remove_wait_queue(&audit_backlog_wait, &wait);
1074 }
1075 
1076 /* Obtain an audit buffer.  This routine does locking to obtain the
1077  * audit buffer, but then no locking is required for calls to
1078  * audit_log_*format.  If the tsk is a task that is currently in a
1079  * syscall, then the syscall is marked as auditable and an audit record
1080  * will be written at syscall exit.  If there is no associated task, tsk
1081  * should be NULL. */
1082 
1083 /**
1084  * audit_log_start - obtain an audit buffer
1085  * @ctx: audit_context (may be NULL)
1086  * @gfp_mask: type of allocation
1087  * @type: audit message type
1088  *
1089  * Returns audit_buffer pointer on success or NULL on error.
1090  *
1091  * Obtain an audit buffer.  This routine does locking to obtain the
1092  * audit buffer, but then no locking is required for calls to
1093  * audit_log_*format.  If the task (ctx) is a task that is currently in a
1094  * syscall, then the syscall is marked as auditable and an audit record
1095  * will be written at syscall exit.  If there is no associated task, then
1096  * task context (ctx) should be NULL.
1097  */
audit_log_start(struct audit_context * ctx,gfp_t gfp_mask,int type)1098 struct audit_buffer *audit_log_start(struct audit_context *ctx, gfp_t gfp_mask,
1099 				     int type)
1100 {
1101 	struct audit_buffer	*ab	= NULL;
1102 	struct timespec		t;
1103 	unsigned int		uninitialized_var(serial);
1104 	int reserve;
1105 	unsigned long timeout_start = jiffies;
1106 
1107 	if (audit_initialized != AUDIT_INITIALIZED)
1108 		return NULL;
1109 
1110 	if (unlikely(audit_filter_type(type)))
1111 		return NULL;
1112 
1113 	if (gfp_mask & __GFP_WAIT)
1114 		reserve = 0;
1115 	else
1116 		reserve = 5; /* Allow atomic callers to go up to five
1117 				entries over the normal backlog limit */
1118 
1119 	while (audit_backlog_limit
1120 	       && skb_queue_len(&audit_skb_queue) > audit_backlog_limit + reserve) {
1121 		if (gfp_mask & __GFP_WAIT && audit_backlog_wait_time) {
1122 			unsigned long sleep_time;
1123 
1124 			sleep_time = timeout_start + audit_backlog_wait_time -
1125 					jiffies;
1126 			if ((long)sleep_time > 0)
1127 				wait_for_auditd(sleep_time);
1128 			continue;
1129 		}
1130 		if (audit_rate_check() && printk_ratelimit())
1131 			printk(KERN_WARNING
1132 			       "audit: audit_backlog=%d > "
1133 			       "audit_backlog_limit=%d\n",
1134 			       skb_queue_len(&audit_skb_queue),
1135 			       audit_backlog_limit);
1136 		audit_log_lost("backlog limit exceeded");
1137 		audit_backlog_wait_time = audit_backlog_wait_overflow;
1138 		wake_up(&audit_backlog_wait);
1139 		return NULL;
1140 	}
1141 
1142 	ab = audit_buffer_alloc(ctx, gfp_mask, type);
1143 	if (!ab) {
1144 		audit_log_lost("out of memory in audit_log_start");
1145 		return NULL;
1146 	}
1147 
1148 	audit_get_stamp(ab->ctx, &t, &serial);
1149 
1150 	audit_log_format(ab, "audit(%lu.%03lu:%u): ",
1151 			 t.tv_sec, t.tv_nsec/1000000, serial);
1152 	return ab;
1153 }
1154 
1155 /**
1156  * audit_expand - expand skb in the audit buffer
1157  * @ab: audit_buffer
1158  * @extra: space to add at tail of the skb
1159  *
1160  * Returns 0 (no space) on failed expansion, or available space if
1161  * successful.
1162  */
audit_expand(struct audit_buffer * ab,int extra)1163 static inline int audit_expand(struct audit_buffer *ab, int extra)
1164 {
1165 	struct sk_buff *skb = ab->skb;
1166 	int oldtail = skb_tailroom(skb);
1167 	int ret = pskb_expand_head(skb, 0, extra, ab->gfp_mask);
1168 	int newtail = skb_tailroom(skb);
1169 
1170 	if (ret < 0) {
1171 		audit_log_lost("out of memory in audit_expand");
1172 		return 0;
1173 	}
1174 
1175 	skb->truesize += newtail - oldtail;
1176 	return newtail;
1177 }
1178 
1179 /*
1180  * Format an audit message into the audit buffer.  If there isn't enough
1181  * room in the audit buffer, more room will be allocated and vsnprint
1182  * will be called a second time.  Currently, we assume that a printk
1183  * can't format message larger than 1024 bytes, so we don't either.
1184  */
audit_log_vformat(struct audit_buffer * ab,const char * fmt,va_list args)1185 static void audit_log_vformat(struct audit_buffer *ab, const char *fmt,
1186 			      va_list args)
1187 {
1188 	int len, avail;
1189 	struct sk_buff *skb;
1190 	va_list args2;
1191 
1192 	if (!ab)
1193 		return;
1194 
1195 	BUG_ON(!ab->skb);
1196 	skb = ab->skb;
1197 	avail = skb_tailroom(skb);
1198 	if (avail == 0) {
1199 		avail = audit_expand(ab, AUDIT_BUFSIZ);
1200 		if (!avail)
1201 			goto out;
1202 	}
1203 	va_copy(args2, args);
1204 	len = vsnprintf(skb_tail_pointer(skb), avail, fmt, args);
1205 	if (len >= avail) {
1206 		/* The printk buffer is 1024 bytes long, so if we get
1207 		 * here and AUDIT_BUFSIZ is at least 1024, then we can
1208 		 * log everything that printk could have logged. */
1209 		avail = audit_expand(ab,
1210 			max_t(unsigned, AUDIT_BUFSIZ, 1+len-avail));
1211 		if (!avail)
1212 			goto out_va_end;
1213 		len = vsnprintf(skb_tail_pointer(skb), avail, fmt, args2);
1214 	}
1215 	if (len > 0)
1216 		skb_put(skb, len);
1217 out_va_end:
1218 	va_end(args2);
1219 out:
1220 	return;
1221 }
1222 
1223 /**
1224  * audit_log_format - format a message into the audit buffer.
1225  * @ab: audit_buffer
1226  * @fmt: format string
1227  * @...: optional parameters matching @fmt string
1228  *
1229  * All the work is done in audit_log_vformat.
1230  */
audit_log_format(struct audit_buffer * ab,const char * fmt,...)1231 void audit_log_format(struct audit_buffer *ab, const char *fmt, ...)
1232 {
1233 	va_list args;
1234 
1235 	if (!ab)
1236 		return;
1237 	va_start(args, fmt);
1238 	audit_log_vformat(ab, fmt, args);
1239 	va_end(args);
1240 }
1241 
1242 /**
1243  * audit_log_hex - convert a buffer to hex and append it to the audit skb
1244  * @ab: the audit_buffer
1245  * @buf: buffer to convert to hex
1246  * @len: length of @buf to be converted
1247  *
1248  * No return value; failure to expand is silently ignored.
1249  *
1250  * This function will take the passed buf and convert it into a string of
1251  * ascii hex digits. The new string is placed onto the skb.
1252  */
audit_log_n_hex(struct audit_buffer * ab,const unsigned char * buf,size_t len)1253 void audit_log_n_hex(struct audit_buffer *ab, const unsigned char *buf,
1254 		size_t len)
1255 {
1256 	int i, avail, new_len;
1257 	unsigned char *ptr;
1258 	struct sk_buff *skb;
1259 	static const unsigned char *hex = "0123456789ABCDEF";
1260 
1261 	if (!ab)
1262 		return;
1263 
1264 	BUG_ON(!ab->skb);
1265 	skb = ab->skb;
1266 	avail = skb_tailroom(skb);
1267 	new_len = len<<1;
1268 	if (new_len >= avail) {
1269 		/* Round the buffer request up to the next multiple */
1270 		new_len = AUDIT_BUFSIZ*(((new_len-avail)/AUDIT_BUFSIZ) + 1);
1271 		avail = audit_expand(ab, new_len);
1272 		if (!avail)
1273 			return;
1274 	}
1275 
1276 	ptr = skb_tail_pointer(skb);
1277 	for (i=0; i<len; i++) {
1278 		*ptr++ = hex[(buf[i] & 0xF0)>>4]; /* Upper nibble */
1279 		*ptr++ = hex[buf[i] & 0x0F];	  /* Lower nibble */
1280 	}
1281 	*ptr = 0;
1282 	skb_put(skb, len << 1); /* new string is twice the old string */
1283 }
1284 
1285 /*
1286  * Format a string of no more than slen characters into the audit buffer,
1287  * enclosed in quote marks.
1288  */
audit_log_n_string(struct audit_buffer * ab,const char * string,size_t slen)1289 void audit_log_n_string(struct audit_buffer *ab, const char *string,
1290 			size_t slen)
1291 {
1292 	int avail, new_len;
1293 	unsigned char *ptr;
1294 	struct sk_buff *skb;
1295 
1296 	if (!ab)
1297 		return;
1298 
1299 	BUG_ON(!ab->skb);
1300 	skb = ab->skb;
1301 	avail = skb_tailroom(skb);
1302 	new_len = slen + 3;	/* enclosing quotes + null terminator */
1303 	if (new_len > avail) {
1304 		avail = audit_expand(ab, new_len);
1305 		if (!avail)
1306 			return;
1307 	}
1308 	ptr = skb_tail_pointer(skb);
1309 	*ptr++ = '"';
1310 	memcpy(ptr, string, slen);
1311 	ptr += slen;
1312 	*ptr++ = '"';
1313 	*ptr = 0;
1314 	skb_put(skb, slen + 2);	/* don't include null terminator */
1315 }
1316 
1317 /**
1318  * audit_string_contains_control - does a string need to be logged in hex
1319  * @string: string to be checked
1320  * @len: max length of the string to check
1321  */
audit_string_contains_control(const char * string,size_t len)1322 int audit_string_contains_control(const char *string, size_t len)
1323 {
1324 	const unsigned char *p;
1325 	for (p = string; p < (const unsigned char *)string + len; p++) {
1326 		if (*p == '"' || *p < 0x21 || *p > 0x7e)
1327 			return 1;
1328 	}
1329 	return 0;
1330 }
1331 
1332 /**
1333  * audit_log_n_untrustedstring - log a string that may contain random characters
1334  * @ab: audit_buffer
1335  * @len: length of string (not including trailing null)
1336  * @string: string to be logged
1337  *
1338  * This code will escape a string that is passed to it if the string
1339  * contains a control character, unprintable character, double quote mark,
1340  * or a space. Unescaped strings will start and end with a double quote mark.
1341  * Strings that are escaped are printed in hex (2 digits per char).
1342  *
1343  * The caller specifies the number of characters in the string to log, which may
1344  * or may not be the entire string.
1345  */
audit_log_n_untrustedstring(struct audit_buffer * ab,const char * string,size_t len)1346 void audit_log_n_untrustedstring(struct audit_buffer *ab, const char *string,
1347 				 size_t len)
1348 {
1349 	if (audit_string_contains_control(string, len))
1350 		audit_log_n_hex(ab, string, len);
1351 	else
1352 		audit_log_n_string(ab, string, len);
1353 }
1354 
1355 /**
1356  * audit_log_untrustedstring - log a string that may contain random characters
1357  * @ab: audit_buffer
1358  * @string: string to be logged
1359  *
1360  * Same as audit_log_n_untrustedstring(), except that strlen is used to
1361  * determine string length.
1362  */
audit_log_untrustedstring(struct audit_buffer * ab,const char * string)1363 void audit_log_untrustedstring(struct audit_buffer *ab, const char *string)
1364 {
1365 	audit_log_n_untrustedstring(ab, string, strlen(string));
1366 }
1367 
1368 /* This is a helper-function to print the escaped d_path */
audit_log_d_path(struct audit_buffer * ab,const char * prefix,const struct path * path)1369 void audit_log_d_path(struct audit_buffer *ab, const char *prefix,
1370 		      const struct path *path)
1371 {
1372 	char *p, *pathname;
1373 
1374 	if (prefix)
1375 		audit_log_format(ab, "%s", prefix);
1376 
1377 	/* We will allow 11 spaces for ' (deleted)' to be appended */
1378 	pathname = kmalloc(PATH_MAX+11, ab->gfp_mask);
1379 	if (!pathname) {
1380 		audit_log_string(ab, "<no_memory>");
1381 		return;
1382 	}
1383 	p = d_path(path, pathname, PATH_MAX+11);
1384 	if (IS_ERR(p)) { /* Should never happen since we send PATH_MAX */
1385 		/* FIXME: can we save some information here? */
1386 		audit_log_string(ab, "<too_long>");
1387 	} else
1388 		audit_log_untrustedstring(ab, p);
1389 	kfree(pathname);
1390 }
1391 
audit_log_session_info(struct audit_buffer * ab)1392 void audit_log_session_info(struct audit_buffer *ab)
1393 {
1394 	u32 sessionid = audit_get_sessionid(current);
1395 	uid_t auid = from_kuid(&init_user_ns, audit_get_loginuid(current));
1396 
1397 	audit_log_format(ab, " auid=%u ses=%u\n", auid, sessionid);
1398 }
1399 
audit_log_key(struct audit_buffer * ab,char * key)1400 void audit_log_key(struct audit_buffer *ab, char *key)
1401 {
1402 	audit_log_format(ab, " key=");
1403 	if (key)
1404 		audit_log_untrustedstring(ab, key);
1405 	else
1406 		audit_log_format(ab, "(null)");
1407 }
1408 
audit_log_cap(struct audit_buffer * ab,char * prefix,kernel_cap_t * cap)1409 void audit_log_cap(struct audit_buffer *ab, char *prefix, kernel_cap_t *cap)
1410 {
1411 	int i;
1412 
1413 	audit_log_format(ab, " %s=", prefix);
1414 	CAP_FOR_EACH_U32(i) {
1415 		audit_log_format(ab, "%08x",
1416 				 cap->cap[(_KERNEL_CAPABILITY_U32S-1) - i]);
1417 	}
1418 }
1419 
audit_log_fcaps(struct audit_buffer * ab,struct audit_names * name)1420 void audit_log_fcaps(struct audit_buffer *ab, struct audit_names *name)
1421 {
1422 	kernel_cap_t *perm = &name->fcap.permitted;
1423 	kernel_cap_t *inh = &name->fcap.inheritable;
1424 	int log = 0;
1425 
1426 	if (!cap_isclear(*perm)) {
1427 		audit_log_cap(ab, "cap_fp", perm);
1428 		log = 1;
1429 	}
1430 	if (!cap_isclear(*inh)) {
1431 		audit_log_cap(ab, "cap_fi", inh);
1432 		log = 1;
1433 	}
1434 
1435 	if (log)
1436 		audit_log_format(ab, " cap_fe=%d cap_fver=%x",
1437 				 name->fcap.fE, name->fcap_ver);
1438 }
1439 
audit_copy_fcaps(struct audit_names * name,const struct dentry * dentry)1440 static inline int audit_copy_fcaps(struct audit_names *name,
1441 				   const struct dentry *dentry)
1442 {
1443 	struct cpu_vfs_cap_data caps;
1444 	int rc;
1445 
1446 	if (!dentry)
1447 		return 0;
1448 
1449 	rc = get_vfs_caps_from_disk(dentry, &caps);
1450 	if (rc)
1451 		return rc;
1452 
1453 	name->fcap.permitted = caps.permitted;
1454 	name->fcap.inheritable = caps.inheritable;
1455 	name->fcap.fE = !!(caps.magic_etc & VFS_CAP_FLAGS_EFFECTIVE);
1456 	name->fcap_ver = (caps.magic_etc & VFS_CAP_REVISION_MASK) >>
1457 				VFS_CAP_REVISION_SHIFT;
1458 
1459 	return 0;
1460 }
1461 
1462 /* Copy inode data into an audit_names. */
audit_copy_inode(struct audit_names * name,const struct dentry * dentry,const struct inode * inode)1463 void audit_copy_inode(struct audit_names *name, const struct dentry *dentry,
1464 		      const struct inode *inode)
1465 {
1466 	name->ino   = inode->i_ino;
1467 	name->dev   = inode->i_sb->s_dev;
1468 	name->mode  = inode->i_mode;
1469 	name->uid   = inode->i_uid;
1470 	name->gid   = inode->i_gid;
1471 	name->rdev  = inode->i_rdev;
1472 	security_inode_getsecid(inode, &name->osid);
1473 	audit_copy_fcaps(name, dentry);
1474 }
1475 
1476 /**
1477  * audit_log_name - produce AUDIT_PATH record from struct audit_names
1478  * @context: audit_context for the task
1479  * @n: audit_names structure with reportable details
1480  * @path: optional path to report instead of audit_names->name
1481  * @record_num: record number to report when handling a list of names
1482  * @call_panic: optional pointer to int that will be updated if secid fails
1483  */
audit_log_name(struct audit_context * context,struct audit_names * n,struct path * path,int record_num,int * call_panic)1484 void audit_log_name(struct audit_context *context, struct audit_names *n,
1485 		    struct path *path, int record_num, int *call_panic)
1486 {
1487 	struct audit_buffer *ab;
1488 	ab = audit_log_start(context, GFP_KERNEL, AUDIT_PATH);
1489 	if (!ab)
1490 		return;
1491 
1492 	audit_log_format(ab, "item=%d", record_num);
1493 
1494 	if (path)
1495 		audit_log_d_path(ab, " name=", path);
1496 	else if (n->name) {
1497 		switch (n->name_len) {
1498 		case AUDIT_NAME_FULL:
1499 			/* log the full path */
1500 			audit_log_format(ab, " name=");
1501 			audit_log_untrustedstring(ab, n->name->name);
1502 			break;
1503 		case 0:
1504 			/* name was specified as a relative path and the
1505 			 * directory component is the cwd */
1506 			audit_log_d_path(ab, " name=", &context->pwd);
1507 			break;
1508 		default:
1509 			/* log the name's directory component */
1510 			audit_log_format(ab, " name=");
1511 			audit_log_n_untrustedstring(ab, n->name->name,
1512 						    n->name_len);
1513 		}
1514 	} else
1515 		audit_log_format(ab, " name=(null)");
1516 
1517 	if (n->ino != (unsigned long)-1) {
1518 		audit_log_format(ab, " inode=%lu"
1519 				 " dev=%02x:%02x mode=%#ho"
1520 				 " ouid=%u ogid=%u rdev=%02x:%02x",
1521 				 n->ino,
1522 				 MAJOR(n->dev),
1523 				 MINOR(n->dev),
1524 				 n->mode,
1525 				 from_kuid(&init_user_ns, n->uid),
1526 				 from_kgid(&init_user_ns, n->gid),
1527 				 MAJOR(n->rdev),
1528 				 MINOR(n->rdev));
1529 	}
1530 	if (n->osid != 0) {
1531 		char *ctx = NULL;
1532 		u32 len;
1533 		if (security_secid_to_secctx(
1534 			n->osid, &ctx, &len)) {
1535 			audit_log_format(ab, " osid=%u", n->osid);
1536 			if (call_panic)
1537 				*call_panic = 2;
1538 		} else {
1539 			audit_log_format(ab, " obj=%s", ctx);
1540 			security_release_secctx(ctx, len);
1541 		}
1542 	}
1543 
1544 	audit_log_fcaps(ab, n);
1545 	audit_log_end(ab);
1546 }
1547 
audit_log_task_context(struct audit_buffer * ab)1548 int audit_log_task_context(struct audit_buffer *ab)
1549 {
1550 	char *ctx = NULL;
1551 	unsigned len;
1552 	int error;
1553 	u32 sid;
1554 
1555 	security_task_getsecid(current, &sid);
1556 	if (!sid)
1557 		return 0;
1558 
1559 	error = security_secid_to_secctx(sid, &ctx, &len);
1560 	if (error) {
1561 		if (error != -EINVAL)
1562 			goto error_path;
1563 		return 0;
1564 	}
1565 
1566 	audit_log_format(ab, " subj=%s", ctx);
1567 	security_release_secctx(ctx, len);
1568 	return 0;
1569 
1570 error_path:
1571 	audit_panic("error in audit_log_task_context");
1572 	return error;
1573 }
1574 EXPORT_SYMBOL(audit_log_task_context);
1575 
audit_log_task_info(struct audit_buffer * ab,struct task_struct * tsk)1576 void audit_log_task_info(struct audit_buffer *ab, struct task_struct *tsk)
1577 {
1578 	const struct cred *cred;
1579 	char name[sizeof(tsk->comm)];
1580 	struct mm_struct *mm = tsk->mm;
1581 	char *tty;
1582 
1583 	if (!ab)
1584 		return;
1585 
1586 	/* tsk == current */
1587 	cred = current_cred();
1588 
1589 	spin_lock_irq(&tsk->sighand->siglock);
1590 	if (tsk->signal && tsk->signal->tty && tsk->signal->tty->name)
1591 		tty = tsk->signal->tty->name;
1592 	else
1593 		tty = "(none)";
1594 	spin_unlock_irq(&tsk->sighand->siglock);
1595 
1596 	audit_log_format(ab,
1597 			 " ppid=%ld pid=%d auid=%u uid=%u gid=%u"
1598 			 " euid=%u suid=%u fsuid=%u"
1599 			 " egid=%u sgid=%u fsgid=%u ses=%u tty=%s",
1600 			 sys_getppid(),
1601 			 task_tgid_nr(tsk),
1602 			 from_kuid(&init_user_ns, audit_get_loginuid(tsk)),
1603 			 from_kuid(&init_user_ns, cred->uid),
1604 			 from_kgid(&init_user_ns, cred->gid),
1605 			 from_kuid(&init_user_ns, cred->euid),
1606 			 from_kuid(&init_user_ns, cred->suid),
1607 			 from_kuid(&init_user_ns, cred->fsuid),
1608 			 from_kgid(&init_user_ns, cred->egid),
1609 			 from_kgid(&init_user_ns, cred->sgid),
1610 			 from_kgid(&init_user_ns, cred->fsgid),
1611 			 audit_get_sessionid(tsk), tty);
1612 
1613 	get_task_comm(name, tsk);
1614 	audit_log_format(ab, " comm=");
1615 	audit_log_untrustedstring(ab, name);
1616 
1617 	if (mm) {
1618 		down_read(&mm->mmap_sem);
1619 		if (mm->exe_file)
1620 			audit_log_d_path(ab, " exe=", &mm->exe_file->f_path);
1621 		up_read(&mm->mmap_sem);
1622 	}
1623 	audit_log_task_context(ab);
1624 }
1625 EXPORT_SYMBOL(audit_log_task_info);
1626 
1627 /**
1628  * audit_log_link_denied - report a link restriction denial
1629  * @operation: specific link opreation
1630  * @link: the path that triggered the restriction
1631  */
audit_log_link_denied(const char * operation,struct path * link)1632 void audit_log_link_denied(const char *operation, struct path *link)
1633 {
1634 	struct audit_buffer *ab;
1635 	struct audit_names *name;
1636 
1637 	name = kzalloc(sizeof(*name), GFP_NOFS);
1638 	if (!name)
1639 		return;
1640 
1641 	/* Generate AUDIT_ANOM_LINK with subject, operation, outcome. */
1642 	ab = audit_log_start(current->audit_context, GFP_KERNEL,
1643 			     AUDIT_ANOM_LINK);
1644 	if (!ab)
1645 		goto out;
1646 	audit_log_format(ab, "op=%s", operation);
1647 	audit_log_task_info(ab, current);
1648 	audit_log_format(ab, " res=0");
1649 	audit_log_end(ab);
1650 
1651 	/* Generate AUDIT_PATH record with object. */
1652 	name->type = AUDIT_TYPE_NORMAL;
1653 	audit_copy_inode(name, link->dentry, link->dentry->d_inode);
1654 	audit_log_name(current->audit_context, name, link, 0, NULL);
1655 out:
1656 	kfree(name);
1657 }
1658 
1659 /**
1660  * audit_log_end - end one audit record
1661  * @ab: the audit_buffer
1662  *
1663  * The netlink_* functions cannot be called inside an irq context, so
1664  * the audit buffer is placed on a queue and a tasklet is scheduled to
1665  * remove them from the queue outside the irq context.  May be called in
1666  * any context.
1667  */
audit_log_end(struct audit_buffer * ab)1668 void audit_log_end(struct audit_buffer *ab)
1669 {
1670 	if (!ab)
1671 		return;
1672 	if (!audit_rate_check()) {
1673 		audit_log_lost("rate limit exceeded");
1674 	} else {
1675 		struct nlmsghdr *nlh = nlmsg_hdr(ab->skb);
1676 		nlh->nlmsg_len = ab->skb->len - NLMSG_HDRLEN;
1677 
1678 		if (audit_pid) {
1679 			skb_queue_tail(&audit_skb_queue, ab->skb);
1680 			wake_up_interruptible(&kauditd_wait);
1681 		} else {
1682 			audit_printk_skb(ab->skb);
1683 		}
1684 		ab->skb = NULL;
1685 	}
1686 	audit_buffer_free(ab);
1687 }
1688 
1689 /**
1690  * audit_log - Log an audit record
1691  * @ctx: audit context
1692  * @gfp_mask: type of allocation
1693  * @type: audit message type
1694  * @fmt: format string to use
1695  * @...: variable parameters matching the format string
1696  *
1697  * This is a convenience function that calls audit_log_start,
1698  * audit_log_vformat, and audit_log_end.  It may be called
1699  * in any context.
1700  */
audit_log(struct audit_context * ctx,gfp_t gfp_mask,int type,const char * fmt,...)1701 void audit_log(struct audit_context *ctx, gfp_t gfp_mask, int type,
1702 	       const char *fmt, ...)
1703 {
1704 	struct audit_buffer *ab;
1705 	va_list args;
1706 
1707 	ab = audit_log_start(ctx, gfp_mask, type);
1708 	if (ab) {
1709 		va_start(args, fmt);
1710 		audit_log_vformat(ab, fmt, args);
1711 		va_end(args);
1712 		audit_log_end(ab);
1713 	}
1714 }
1715 
1716 #ifdef CONFIG_SECURITY
1717 /**
1718  * audit_log_secctx - Converts and logs SELinux context
1719  * @ab: audit_buffer
1720  * @secid: security number
1721  *
1722  * This is a helper function that calls security_secid_to_secctx to convert
1723  * secid to secctx and then adds the (converted) SELinux context to the audit
1724  * log by calling audit_log_format, thus also preventing leak of internal secid
1725  * to userspace. If secid cannot be converted audit_panic is called.
1726  */
audit_log_secctx(struct audit_buffer * ab,u32 secid)1727 void audit_log_secctx(struct audit_buffer *ab, u32 secid)
1728 {
1729 	u32 len;
1730 	char *secctx;
1731 
1732 	if (security_secid_to_secctx(secid, &secctx, &len)) {
1733 		audit_panic("Cannot convert secid to context");
1734 	} else {
1735 		audit_log_format(ab, " obj=%s", secctx);
1736 		security_release_secctx(secctx, len);
1737 	}
1738 }
1739 EXPORT_SYMBOL(audit_log_secctx);
1740 #endif
1741 
1742 EXPORT_SYMBOL(audit_log_start);
1743 EXPORT_SYMBOL(audit_log_end);
1744 EXPORT_SYMBOL(audit_log_format);
1745 EXPORT_SYMBOL(audit_log);
1746