xref: /linux/kernel/audit.c (revision 24c776355f4097316a763005434ffff716aa21a8)
1 // SPDX-License-Identifier: GPL-2.0-or-later
2 /* audit.c -- Auditing support
3  * Gateway between the kernel (e.g., selinux) and the user-space audit daemon.
4  * System-call specific features have moved to auditsc.c
5  *
6  * Copyright 2003-2007 Red Hat Inc., Durham, North Carolina.
7  * All Rights Reserved.
8  *
9  * Written by Rickard E. (Rik) Faith <faith@redhat.com>
10  *
11  * Goals: 1) Integrate fully with Security Modules.
12  *	  2) Minimal run-time overhead:
13  *	     a) Minimal when syscall auditing is disabled (audit_enable=0).
14  *	     b) Small when syscall auditing is enabled and no audit record
15  *		is generated (defer as much work as possible to record
16  *		generation time):
17  *		i) context is allocated,
18  *		ii) names from getname are stored without a copy, and
19  *		iii) inode information stored from path_lookup.
20  *	  3) Ability to disable syscall auditing at boot time (audit=0).
21  *	  4) Usable by other parts of the kernel (if audit_log* is called,
22  *	     then a syscall record will be generated automatically for the
23  *	     current syscall).
24  *	  5) Netlink interface to user-space.
25  *	  6) Support low-overhead kernel-based filtering to minimize the
26  *	     information that must be passed to user-space.
27  *
28  * Audit userspace, documentation, tests, and bug/issue trackers:
29  * 	https://github.com/linux-audit
30  */
31 
32 #define pr_fmt(fmt) KBUILD_MODNAME ": " fmt
33 
34 #include <linux/file.h>
35 #include <linux/hex.h>
36 #include <linux/init.h>
37 #include <linux/types.h>
38 #include <linux/atomic.h>
39 #include <linux/mm.h>
40 #include <linux/export.h>
41 #include <linux/slab.h>
42 #include <linux/err.h>
43 #include <linux/kthread.h>
44 #include <linux/kernel.h>
45 #include <linux/syscalls.h>
46 #include <linux/spinlock.h>
47 #include <linux/rcupdate.h>
48 #include <linux/mutex.h>
49 #include <linux/gfp.h>
50 #include <linux/pid.h>
51 
52 #include <linux/audit.h>
53 
54 #include <net/sock.h>
55 #include <net/netlink.h>
56 #include <linux/skbuff.h>
57 #include <linux/security.h>
58 #include <linux/lsm_hooks.h>
59 #include <linux/freezer.h>
60 #include <linux/pid_namespace.h>
61 #include <net/netns/generic.h>
62 
63 #include "audit.h"
64 
65 /* No auditing will take place until audit_initialized == AUDIT_INITIALIZED.
66  * (Initialization happens after skb_init is called.) */
67 #define AUDIT_DISABLED		-1
68 #define AUDIT_UNINITIALIZED	0
69 #define AUDIT_INITIALIZED	1
70 static int	audit_initialized = AUDIT_UNINITIALIZED;
71 
72 u32		audit_enabled = AUDIT_OFF;
73 bool		audit_ever_enabled = !!AUDIT_OFF;
74 
75 EXPORT_SYMBOL_GPL(audit_enabled);
76 
77 /* Default state when kernel boots without any parameters. */
78 static u32	audit_default = AUDIT_OFF;
79 
80 /* If auditing cannot proceed, audit_failure selects what happens. */
81 static u32	audit_failure = AUDIT_FAIL_PRINTK;
82 
83 /* private audit network namespace index */
84 static unsigned int audit_net_id;
85 
86 /* Number of modules that provide a security context.
87    List of lsms that provide a security context */
88 static u32 audit_subj_secctx_cnt;
89 static u32 audit_obj_secctx_cnt;
90 static const struct lsm_id *audit_subj_lsms[MAX_LSM_COUNT];
91 static const struct lsm_id *audit_obj_lsms[MAX_LSM_COUNT];
92 
93 /**
94  * struct audit_net - audit private network namespace data
95  * @sk: communication socket
96  */
97 struct audit_net {
98 	struct sock *sk;
99 };
100 
101 /**
102  * struct auditd_connection - kernel/auditd connection state
103  * @pid: auditd PID
104  * @portid: netlink portid
105  * @net: the associated network namespace
106  * @rcu: RCU head
107  *
108  * Description:
109  * This struct is RCU protected; you must either hold the RCU lock for reading
110  * or the associated spinlock for writing.
111  */
112 struct auditd_connection {
113 	struct pid *pid;
114 	u32 portid;
115 	struct net *net;
116 	struct rcu_head rcu;
117 };
118 static struct auditd_connection __rcu *auditd_conn;
119 static DEFINE_SPINLOCK(auditd_conn_lock);
120 
121 /* If audit_rate_limit is non-zero, limit the rate of sending audit records
122  * to that number per second.  This prevents DoS attacks, but results in
123  * audit records being dropped. */
124 static u32	audit_rate_limit;
125 
126 /* Number of outstanding audit_buffers allowed.
127  * When set to zero, this means unlimited. */
128 static u32	audit_backlog_limit = 64;
129 #define AUDIT_BACKLOG_WAIT_TIME (60 * HZ)
130 static u32	audit_backlog_wait_time = AUDIT_BACKLOG_WAIT_TIME;
131 
132 /* The identity of the user shutting down the audit system. */
133 static kuid_t		audit_sig_uid = INVALID_UID;
134 static pid_t		audit_sig_pid = -1;
135 static struct lsm_prop	audit_sig_lsm;
136 
137 /* Records can be lost in several ways:
138    0) [suppressed in audit_alloc]
139    1) out of memory in audit_log_start [kmalloc of struct audit_buffer]
140    2) out of memory in audit_log_move [alloc_skb]
141    3) suppressed due to audit_rate_limit
142    4) suppressed due to audit_backlog_limit
143 */
144 static atomic_t	audit_lost = ATOMIC_INIT(0);
145 
146 /* Monotonically increasing sum of time the kernel has spent
147  * waiting while the backlog limit is exceeded.
148  */
149 static atomic_t audit_backlog_wait_time_actual = ATOMIC_INIT(0);
150 
151 /* Hash for inode-based rules */
152 struct list_head audit_inode_hash[AUDIT_INODE_BUCKETS];
153 
154 static struct kmem_cache *audit_buffer_cache;
155 
156 /* queue msgs to send via kauditd_task */
157 static struct sk_buff_head audit_queue;
158 /* queue msgs due to temporary unicast send problems */
159 static struct sk_buff_head audit_retry_queue;
160 /* queue msgs waiting for new auditd connection */
161 static struct sk_buff_head audit_hold_queue;
162 
163 /* queue servicing thread */
164 static struct task_struct *kauditd_task;
165 static DECLARE_WAIT_QUEUE_HEAD(kauditd_wait);
166 
167 /* waitqueue for callers who are blocked on the audit backlog */
168 static DECLARE_WAIT_QUEUE_HEAD(audit_backlog_wait);
169 
170 static struct audit_features af = {.vers = AUDIT_FEATURE_VERSION,
171 				   .mask = -1,
172 				   .features = 0,
173 				   .lock = 0,};
174 
175 static char *audit_feature_names[2] = {
176 	"only_unset_loginuid",
177 	"loginuid_immutable",
178 };
179 
180 /**
181  * struct audit_ctl_mutex - serialize requests from userspace
182  * @lock: the mutex used for locking
183  * @owner: the task which owns the lock
184  *
185  * Description:
186  * This is the lock struct used to ensure we only process userspace requests
187  * in an orderly fashion.  We can't simply use a mutex/lock here because we
188  * need to track lock ownership so we don't end up blocking the lock owner in
189  * audit_log_start() or similar.
190  */
191 static struct audit_ctl_mutex {
192 	struct mutex lock;
193 	void *owner;
194 } audit_cmd_mutex;
195 
196 /* AUDIT_BUFSIZ is the size of the temporary buffer used for formatting
197  * audit records.  Since printk uses a 1024 byte buffer, this buffer
198  * should be at least that large. */
199 #define AUDIT_BUFSIZ 1024
200 
201 /* The audit_buffer is used when formatting an audit record.  The caller
202  * locks briefly to get the record off the freelist or to allocate the
203  * buffer, and locks briefly to send the buffer to the netlink layer or
204  * to place it on a transmit queue.  Multiple audit_buffers can be in
205  * use simultaneously. */
206 struct audit_buffer {
207 	struct sk_buff       *skb;	/* the skb for audit_log functions */
208 	struct sk_buff_head  skb_list;	/* formatted skbs, ready to send */
209 	struct audit_context *ctx;	/* NULL or associated context */
210 	struct audit_stamp   stamp;	/* audit stamp for these records */
211 	gfp_t		     gfp_mask;
212 };
213 
214 struct audit_reply {
215 	__u32 portid;
216 	struct net *net;
217 	struct sk_buff *skb;
218 };
219 
220 /**
221  * auditd_test_task - Check to see if a given task is an audit daemon
222  * @task: the task to check
223  *
224  * Description:
225  * Return 1 if the task is a registered audit daemon, 0 otherwise.
226  */
227 int auditd_test_task(struct task_struct *task)
228 {
229 	int rc;
230 	struct auditd_connection *ac;
231 
232 	rcu_read_lock();
233 	ac = rcu_dereference(auditd_conn);
234 	rc = (ac && ac->pid == task_tgid(task) ? 1 : 0);
235 	rcu_read_unlock();
236 
237 	return rc;
238 }
239 
240 /**
241  * audit_ctl_lock - Take the audit control lock
242  */
243 void audit_ctl_lock(void)
244 {
245 	mutex_lock(&audit_cmd_mutex.lock);
246 	audit_cmd_mutex.owner = current;
247 }
248 
249 /**
250  * audit_ctl_unlock - Drop the audit control lock
251  */
252 void audit_ctl_unlock(void)
253 {
254 	audit_cmd_mutex.owner = NULL;
255 	mutex_unlock(&audit_cmd_mutex.lock);
256 }
257 
258 /**
259  * audit_ctl_owner_current - Test to see if the current task owns the lock
260  *
261  * Description:
262  * Return true if the current task owns the audit control lock, false if it
263  * doesn't own the lock.
264  */
265 static bool audit_ctl_owner_current(void)
266 {
267 	return (current == audit_cmd_mutex.owner);
268 }
269 
270 /**
271  * auditd_pid_vnr - Return the auditd PID relative to the namespace
272  *
273  * Description:
274  * Returns the PID in relation to the namespace, 0 on failure.
275  */
276 static pid_t auditd_pid_vnr(void)
277 {
278 	pid_t pid;
279 	const struct auditd_connection *ac;
280 
281 	rcu_read_lock();
282 	ac = rcu_dereference(auditd_conn);
283 	if (!ac || !ac->pid)
284 		pid = 0;
285 	else
286 		pid = pid_vnr(ac->pid);
287 	rcu_read_unlock();
288 
289 	return pid;
290 }
291 
292 /**
293  * audit_cfg_lsm - Identify a security module as providing a secctx.
294  * @lsmid: LSM identity
295  * @flags: which contexts are provided
296  *
297  * Description:
298  * Increments the count of the security modules providing a secctx.
299  * If the LSM id is already in the list leave it alone.
300  */
301 void audit_cfg_lsm(const struct lsm_id *lsmid, int flags)
302 {
303 	int i;
304 
305 	if (flags & AUDIT_CFG_LSM_SECCTX_SUBJECT) {
306 		for (i = 0 ; i < audit_subj_secctx_cnt; i++)
307 			if (audit_subj_lsms[i] == lsmid)
308 				return;
309 		audit_subj_lsms[audit_subj_secctx_cnt++] = lsmid;
310 	}
311 	if (flags & AUDIT_CFG_LSM_SECCTX_OBJECT) {
312 		for (i = 0 ; i < audit_obj_secctx_cnt; i++)
313 			if (audit_obj_lsms[i] == lsmid)
314 				return;
315 		audit_obj_lsms[audit_obj_secctx_cnt++] = lsmid;
316 	}
317 }
318 
319 /**
320  * audit_get_sk - Return the audit socket for the given network namespace
321  * @net: the destination network namespace
322  *
323  * Description:
324  * Returns the sock pointer if valid, NULL otherwise.  The caller must ensure
325  * that a reference is held for the network namespace while the sock is in use.
326  */
327 static struct sock *audit_get_sk(const struct net *net)
328 {
329 	struct audit_net *aunet;
330 
331 	if (!net)
332 		return NULL;
333 
334 	aunet = net_generic(net, audit_net_id);
335 	return aunet->sk;
336 }
337 
338 void audit_panic(const char *message)
339 {
340 	switch (audit_failure) {
341 	case AUDIT_FAIL_SILENT:
342 		break;
343 	case AUDIT_FAIL_PRINTK:
344 		if (printk_ratelimit())
345 			pr_err("%s\n", message);
346 		break;
347 	case AUDIT_FAIL_PANIC:
348 		panic("audit: %s\n", message);
349 		break;
350 	}
351 }
352 
353 static inline int audit_rate_check(void)
354 {
355 	static unsigned long	last_check = 0;
356 	static int		messages   = 0;
357 	static DEFINE_SPINLOCK(lock);
358 	unsigned long		flags;
359 	unsigned long		now;
360 	int			retval	   = 0;
361 
362 	if (!audit_rate_limit)
363 		return 1;
364 
365 	spin_lock_irqsave(&lock, flags);
366 	if (++messages < audit_rate_limit) {
367 		retval = 1;
368 	} else {
369 		now = jiffies;
370 		if (time_after(now, last_check + HZ)) {
371 			last_check = now;
372 			messages   = 0;
373 			retval     = 1;
374 		}
375 	}
376 	spin_unlock_irqrestore(&lock, flags);
377 
378 	return retval;
379 }
380 
381 /**
382  * audit_log_lost - conditionally log lost audit message event
383  * @message: the message stating reason for lost audit message
384  *
385  * Emit at least 1 message per second, even if audit_rate_check is
386  * throttling.
387  * Always increment the lost messages counter.
388 */
389 void audit_log_lost(const char *message)
390 {
391 	static unsigned long	last_msg = 0;
392 	static DEFINE_SPINLOCK(lock);
393 	unsigned long		flags;
394 	unsigned long		now;
395 	int			print;
396 
397 	atomic_inc(&audit_lost);
398 
399 	print = (audit_failure == AUDIT_FAIL_PANIC || !audit_rate_limit);
400 
401 	if (!print) {
402 		spin_lock_irqsave(&lock, flags);
403 		now = jiffies;
404 		if (time_after(now, last_msg + HZ)) {
405 			print = 1;
406 			last_msg = now;
407 		}
408 		spin_unlock_irqrestore(&lock, flags);
409 	}
410 
411 	if (print) {
412 		if (printk_ratelimit())
413 			pr_warn("audit_lost=%u audit_rate_limit=%u audit_backlog_limit=%u\n",
414 				atomic_read(&audit_lost),
415 				audit_rate_limit,
416 				audit_backlog_limit);
417 		audit_panic(message);
418 	}
419 }
420 
421 static int audit_log_config_change(char *function_name, u32 new, u32 old,
422 				   int allow_changes)
423 {
424 	struct audit_buffer *ab;
425 	int rc = 0;
426 
427 	ab = audit_log_start(audit_context(), GFP_KERNEL, AUDIT_CONFIG_CHANGE);
428 	if (unlikely(!ab))
429 		return rc;
430 	audit_log_format(ab, "op=set %s=%u old=%u ", function_name, new, old);
431 	audit_log_session_info(ab);
432 	rc = audit_log_task_context(ab);
433 	if (rc)
434 		allow_changes = 0; /* Something weird, deny request */
435 	audit_log_format(ab, " res=%d", allow_changes);
436 	audit_log_end(ab);
437 	return rc;
438 }
439 
440 static int audit_do_config_change(char *function_name, u32 *to_change, u32 new)
441 {
442 	int allow_changes, rc = 0;
443 	u32 old = *to_change;
444 
445 	/* check if we are locked */
446 	if (audit_enabled == AUDIT_LOCKED)
447 		allow_changes = 0;
448 	else
449 		allow_changes = 1;
450 
451 	if (audit_enabled != AUDIT_OFF) {
452 		rc = audit_log_config_change(function_name, new, old, allow_changes);
453 		if (rc)
454 			allow_changes = 0;
455 	}
456 
457 	/* If we are allowed, make the change */
458 	if (allow_changes == 1)
459 		*to_change = new;
460 	/* Not allowed, update reason */
461 	else if (rc == 0)
462 		rc = -EPERM;
463 	return rc;
464 }
465 
466 static int audit_set_rate_limit(u32 limit)
467 {
468 	return audit_do_config_change("audit_rate_limit", &audit_rate_limit, limit);
469 }
470 
471 static int audit_set_backlog_limit(u32 limit)
472 {
473 	return audit_do_config_change("audit_backlog_limit", &audit_backlog_limit, limit);
474 }
475 
476 static int audit_set_backlog_wait_time(u32 timeout)
477 {
478 	return audit_do_config_change("audit_backlog_wait_time",
479 				      &audit_backlog_wait_time, timeout);
480 }
481 
482 static int audit_set_enabled(u32 state)
483 {
484 	int rc;
485 	if (state > AUDIT_LOCKED)
486 		return -EINVAL;
487 
488 	rc =  audit_do_config_change("audit_enabled", &audit_enabled, state);
489 	if (!rc)
490 		audit_ever_enabled |= !!state;
491 
492 	return rc;
493 }
494 
495 static int audit_set_failure(u32 state)
496 {
497 	if (state != AUDIT_FAIL_SILENT
498 	    && state != AUDIT_FAIL_PRINTK
499 	    && state != AUDIT_FAIL_PANIC)
500 		return -EINVAL;
501 
502 	return audit_do_config_change("audit_failure", &audit_failure, state);
503 }
504 
505 /**
506  * auditd_conn_free - RCU helper to release an auditd connection struct
507  * @rcu: RCU head
508  *
509  * Description:
510  * Drop any references inside the auditd connection tracking struct and free
511  * the memory.
512  */
513 static void auditd_conn_free(struct rcu_head *rcu)
514 {
515 	struct auditd_connection *ac;
516 
517 	ac = container_of(rcu, struct auditd_connection, rcu);
518 	put_pid(ac->pid);
519 	put_net(ac->net);
520 	kfree(ac);
521 }
522 
523 /**
524  * auditd_set - Set/Reset the auditd connection state
525  * @pid: auditd PID
526  * @portid: auditd netlink portid
527  * @net: auditd network namespace pointer
528  * @skb: the netlink command from the audit daemon
529  * @ack: netlink ack flag, cleared if ack'd here
530  *
531  * Description:
532  * This function will obtain and drop network namespace references as
533  * necessary.  Returns zero on success, negative values on failure.
534  */
535 static int auditd_set(struct pid *pid, u32 portid, struct net *net,
536 		      struct sk_buff *skb, bool *ack)
537 {
538 	unsigned long flags;
539 	struct auditd_connection *ac_old, *ac_new;
540 	struct nlmsghdr *nlh;
541 
542 	if (!pid || !net)
543 		return -EINVAL;
544 
545 	ac_new = kzalloc(sizeof(*ac_new), GFP_KERNEL);
546 	if (!ac_new)
547 		return -ENOMEM;
548 	ac_new->pid = get_pid(pid);
549 	ac_new->portid = portid;
550 	ac_new->net = get_net(net);
551 
552 	/* send the ack now to avoid a race with the queue backlog */
553 	if (*ack) {
554 		nlh = nlmsg_hdr(skb);
555 		netlink_ack(skb, nlh, 0, NULL);
556 		*ack = false;
557 	}
558 
559 	spin_lock_irqsave(&auditd_conn_lock, flags);
560 	ac_old = rcu_dereference_protected(auditd_conn,
561 					   lockdep_is_held(&auditd_conn_lock));
562 	rcu_assign_pointer(auditd_conn, ac_new);
563 	spin_unlock_irqrestore(&auditd_conn_lock, flags);
564 
565 	if (ac_old)
566 		call_rcu(&ac_old->rcu, auditd_conn_free);
567 
568 	return 0;
569 }
570 
571 /**
572  * kauditd_printk_skb - Print the audit record to the ring buffer
573  * @skb: audit record
574  *
575  * Whatever the reason, this packet may not make it to the auditd connection
576  * so write it via printk so the information isn't completely lost.
577  */
578 static void kauditd_printk_skb(struct sk_buff *skb)
579 {
580 	struct nlmsghdr *nlh = nlmsg_hdr(skb);
581 	char *data = nlmsg_data(nlh);
582 
583 	if (nlh->nlmsg_type != AUDIT_EOE && printk_ratelimit())
584 		pr_notice("type=%d %s\n", nlh->nlmsg_type, data);
585 }
586 
587 /**
588  * kauditd_rehold_skb - Handle a audit record send failure in the hold queue
589  * @skb: audit record
590  * @error: error code (unused)
591  *
592  * Description:
593  * This should only be used by the kauditd_thread when it fails to flush the
594  * hold queue.
595  */
596 static void kauditd_rehold_skb(struct sk_buff *skb, __always_unused int error)
597 {
598 	/* put the record back in the queue */
599 	skb_queue_tail(&audit_hold_queue, skb);
600 }
601 
602 /**
603  * kauditd_hold_skb - Queue an audit record, waiting for auditd
604  * @skb: audit record
605  * @error: error code
606  *
607  * Description:
608  * Queue the audit record, waiting for an instance of auditd.  When this
609  * function is called we haven't given up yet on sending the record, but things
610  * are not looking good.  The first thing we want to do is try to write the
611  * record via printk and then see if we want to try and hold on to the record
612  * and queue it, if we have room.  If we want to hold on to the record, but we
613  * don't have room, record a record lost message.
614  */
615 static void kauditd_hold_skb(struct sk_buff *skb, int error)
616 {
617 	/* at this point it is uncertain if we will ever send this to auditd so
618 	 * try to send the message via printk before we go any further */
619 	kauditd_printk_skb(skb);
620 
621 	/* can we just silently drop the message? */
622 	if (!audit_default)
623 		goto drop;
624 
625 	/* the hold queue is only for when the daemon goes away completely,
626 	 * not -EAGAIN failures; if we are in a -EAGAIN state requeue the
627 	 * record on the retry queue unless it's full, in which case drop it
628 	 */
629 	if (error == -EAGAIN) {
630 		if (!audit_backlog_limit ||
631 		    skb_queue_len(&audit_retry_queue) < audit_backlog_limit) {
632 			skb_queue_tail(&audit_retry_queue, skb);
633 			return;
634 		}
635 		audit_log_lost("kauditd retry queue overflow");
636 		goto drop;
637 	}
638 
639 	/* if we have room in the hold queue, queue the message */
640 	if (!audit_backlog_limit ||
641 	    skb_queue_len(&audit_hold_queue) < audit_backlog_limit) {
642 		skb_queue_tail(&audit_hold_queue, skb);
643 		return;
644 	}
645 
646 	/* we have no other options - drop the message */
647 	audit_log_lost("kauditd hold queue overflow");
648 drop:
649 	kfree_skb(skb);
650 }
651 
652 /**
653  * kauditd_retry_skb - Queue an audit record, attempt to send again to auditd
654  * @skb: audit record
655  * @error: error code (unused)
656  *
657  * Description:
658  * Not as serious as kauditd_hold_skb() as we still have a connected auditd,
659  * but for some reason we are having problems sending it audit records so
660  * queue the given record and attempt to resend.
661  */
662 static void kauditd_retry_skb(struct sk_buff *skb, __always_unused int error)
663 {
664 	if (!audit_backlog_limit ||
665 	    skb_queue_len(&audit_retry_queue) < audit_backlog_limit) {
666 		skb_queue_tail(&audit_retry_queue, skb);
667 		return;
668 	}
669 
670 	/* we have to drop the record, send it via printk as a last effort */
671 	kauditd_printk_skb(skb);
672 	audit_log_lost("kauditd retry queue overflow");
673 	kfree_skb(skb);
674 }
675 
676 /**
677  * auditd_reset - Disconnect the auditd connection
678  * @ac: auditd connection state
679  *
680  * Description:
681  * Break the auditd/kauditd connection and move all the queued records into the
682  * hold queue in case auditd reconnects.  It is important to note that the @ac
683  * pointer should never be dereferenced inside this function as it may be NULL
684  * or invalid, you can only compare the memory address!  If @ac is NULL then
685  * the connection will always be reset.
686  */
687 static void auditd_reset(const struct auditd_connection *ac)
688 {
689 	unsigned long flags;
690 	struct sk_buff *skb;
691 	struct auditd_connection *ac_old;
692 
693 	/* if it isn't already broken, break the connection */
694 	spin_lock_irqsave(&auditd_conn_lock, flags);
695 	ac_old = rcu_dereference_protected(auditd_conn,
696 					   lockdep_is_held(&auditd_conn_lock));
697 	if (ac && ac != ac_old) {
698 		/* someone already registered a new auditd connection */
699 		spin_unlock_irqrestore(&auditd_conn_lock, flags);
700 		return;
701 	}
702 	rcu_assign_pointer(auditd_conn, NULL);
703 	spin_unlock_irqrestore(&auditd_conn_lock, flags);
704 
705 	if (ac_old)
706 		call_rcu(&ac_old->rcu, auditd_conn_free);
707 
708 	/* flush the retry queue to the hold queue, but don't touch the main
709 	 * queue since we need to process that normally for multicast */
710 	while ((skb = skb_dequeue(&audit_retry_queue)))
711 		kauditd_hold_skb(skb, -ECONNREFUSED);
712 }
713 
714 /**
715  * auditd_send_unicast_skb - Send a record via unicast to auditd
716  * @skb: audit record
717  *
718  * Description:
719  * Send a skb to the audit daemon, returns positive/zero values on success and
720  * negative values on failure; in all cases the skb will be consumed by this
721  * function.  If the send results in -ECONNREFUSED the connection with auditd
722  * will be reset.  This function may sleep so callers should not hold any locks
723  * where this would cause a problem.
724  */
725 static int auditd_send_unicast_skb(struct sk_buff *skb)
726 {
727 	int rc;
728 	u32 portid;
729 	struct net *net;
730 	struct sock *sk;
731 	struct auditd_connection *ac;
732 
733 	/* NOTE: we can't call netlink_unicast while in the RCU section so
734 	 *       take a reference to the network namespace and grab local
735 	 *       copies of the namespace, the sock, and the portid; the
736 	 *       namespace and sock aren't going to go away while we hold a
737 	 *       reference and if the portid does become invalid after the RCU
738 	 *       section netlink_unicast() should safely return an error */
739 
740 	rcu_read_lock();
741 	ac = rcu_dereference(auditd_conn);
742 	if (!ac) {
743 		rcu_read_unlock();
744 		kfree_skb(skb);
745 		rc = -ECONNREFUSED;
746 		goto err;
747 	}
748 	net = get_net(ac->net);
749 	sk = audit_get_sk(net);
750 	portid = ac->portid;
751 	rcu_read_unlock();
752 
753 	rc = netlink_unicast(sk, skb, portid, 0);
754 	put_net(net);
755 	if (rc < 0)
756 		goto err;
757 
758 	return rc;
759 
760 err:
761 	if (ac && rc == -ECONNREFUSED)
762 		auditd_reset(ac);
763 	return rc;
764 }
765 
766 /**
767  * kauditd_send_queue - Helper for kauditd_thread to flush skb queues
768  * @sk: the sending sock
769  * @portid: the netlink destination
770  * @queue: the skb queue to process
771  * @retry_limit: limit on number of netlink unicast failures
772  * @skb_hook: per-skb hook for additional processing
773  * @err_hook: hook called if the skb fails the netlink unicast send
774  *
775  * Description:
776  * Run through the given queue and attempt to send the audit records to auditd,
777  * returns zero on success, negative values on failure.  It is up to the caller
778  * to ensure that the @sk is valid for the duration of this function.
779  *
780  */
781 static int kauditd_send_queue(struct sock *sk, u32 portid,
782 			      struct sk_buff_head *queue,
783 			      unsigned int retry_limit,
784 			      void (*skb_hook)(struct sk_buff *skb),
785 			      void (*err_hook)(struct sk_buff *skb, int error))
786 {
787 	int rc = 0;
788 	struct sk_buff *skb = NULL;
789 	struct sk_buff *skb_tail;
790 	unsigned int failed = 0;
791 
792 	/* NOTE: kauditd_thread takes care of all our locking, we just use
793 	 *       the netlink info passed to us (e.g. sk and portid) */
794 
795 	skb_tail = skb_peek_tail(queue);
796 	while ((skb != skb_tail) && (skb = skb_dequeue(queue))) {
797 		/* call the skb_hook for each skb we touch */
798 		if (skb_hook)
799 			(*skb_hook)(skb);
800 
801 		/* can we send to anyone via unicast? */
802 		if (!sk) {
803 			if (err_hook)
804 				(*err_hook)(skb, -ECONNREFUSED);
805 			continue;
806 		}
807 
808 retry:
809 		/* grab an extra skb reference in case of error */
810 		skb_get(skb);
811 		rc = netlink_unicast(sk, skb, portid, 0);
812 		if (rc < 0) {
813 			/* send failed - try a few times unless fatal error */
814 			if (++failed >= retry_limit ||
815 			    rc == -ECONNREFUSED || rc == -EPERM) {
816 				sk = NULL;
817 				if (err_hook)
818 					(*err_hook)(skb, rc);
819 				if (rc == -EAGAIN)
820 					rc = 0;
821 				/* continue to drain the queue */
822 				continue;
823 			} else
824 				goto retry;
825 		} else {
826 			/* skb sent - drop the extra reference and continue */
827 			consume_skb(skb);
828 			failed = 0;
829 		}
830 	}
831 
832 	return (rc >= 0 ? 0 : rc);
833 }
834 
835 /*
836  * kauditd_send_multicast_skb - Send a record to any multicast listeners
837  * @skb: audit record
838  *
839  * Description:
840  * Write a multicast message to anyone listening in the initial network
841  * namespace.  This function doesn't consume an skb as might be expected since
842  * it has to copy it anyways.
843  */
844 static void kauditd_send_multicast_skb(struct sk_buff *skb)
845 {
846 	struct sk_buff *copy;
847 	struct sock *sock = audit_get_sk(&init_net);
848 	struct nlmsghdr *nlh;
849 
850 	/* NOTE: we are not taking an additional reference for init_net since
851 	 *       we don't have to worry about it going away */
852 
853 	if (!netlink_has_listeners(sock, AUDIT_NLGRP_READLOG))
854 		return;
855 
856 	/*
857 	 * The seemingly wasteful skb_copy() rather than bumping the refcount
858 	 * using skb_get() is necessary because non-standard mods are made to
859 	 * the skb by the original kaudit unicast socket send routine.  The
860 	 * existing auditd daemon assumes this breakage.  Fixing this would
861 	 * require co-ordinating a change in the established protocol between
862 	 * the kaudit kernel subsystem and the auditd userspace code.  There is
863 	 * no reason for new multicast clients to continue with this
864 	 * non-compliance.
865 	 */
866 	copy = skb_copy(skb, GFP_KERNEL);
867 	if (!copy)
868 		return;
869 	nlh = nlmsg_hdr(copy);
870 	nlh->nlmsg_len = skb->len;
871 
872 	nlmsg_multicast(sock, copy, 0, AUDIT_NLGRP_READLOG, GFP_KERNEL);
873 }
874 
875 /**
876  * kauditd_thread - Worker thread to send audit records to userspace
877  * @dummy: unused
878  */
879 static int kauditd_thread(void *dummy)
880 {
881 	int rc;
882 	u32 portid = 0;
883 	struct net *net = NULL;
884 	struct sock *sk = NULL;
885 	struct auditd_connection *ac;
886 
887 #define UNICAST_RETRIES 5
888 
889 	set_freezable();
890 	while (!kthread_should_stop()) {
891 		/* NOTE: see the lock comments in auditd_send_unicast_skb() */
892 		rcu_read_lock();
893 		ac = rcu_dereference(auditd_conn);
894 		if (!ac) {
895 			rcu_read_unlock();
896 			goto main_queue;
897 		}
898 		net = get_net(ac->net);
899 		sk = audit_get_sk(net);
900 		portid = ac->portid;
901 		rcu_read_unlock();
902 
903 		/* attempt to flush the hold queue */
904 		rc = kauditd_send_queue(sk, portid,
905 					&audit_hold_queue, UNICAST_RETRIES,
906 					NULL, kauditd_rehold_skb);
907 		if (rc < 0) {
908 			sk = NULL;
909 			auditd_reset(ac);
910 			goto main_queue;
911 		}
912 
913 		/* attempt to flush the retry queue */
914 		rc = kauditd_send_queue(sk, portid,
915 					&audit_retry_queue, UNICAST_RETRIES,
916 					NULL, kauditd_hold_skb);
917 		if (rc < 0) {
918 			sk = NULL;
919 			auditd_reset(ac);
920 			goto main_queue;
921 		}
922 
923 main_queue:
924 		/* process the main queue - do the multicast send and attempt
925 		 * unicast, dump failed record sends to the retry queue; if
926 		 * sk == NULL due to previous failures we will just do the
927 		 * multicast send and move the record to the hold queue */
928 		rc = kauditd_send_queue(sk, portid, &audit_queue, 1,
929 					kauditd_send_multicast_skb,
930 					(sk ?
931 					 kauditd_retry_skb : kauditd_hold_skb));
932 		if (ac && rc < 0)
933 			auditd_reset(ac);
934 		sk = NULL;
935 
936 		/* drop our netns reference, no auditd sends past this line */
937 		if (net) {
938 			put_net(net);
939 			net = NULL;
940 		}
941 
942 		/* we have processed all the queues so wake everyone */
943 		wake_up(&audit_backlog_wait);
944 
945 		/* NOTE: we want to wake up if there is anything on the queue,
946 		 *       regardless of if an auditd is connected, as we need to
947 		 *       do the multicast send and rotate records from the
948 		 *       main queue to the retry/hold queues */
949 		wait_event_freezable(kauditd_wait,
950 				     (skb_queue_len(&audit_queue) ? 1 : 0));
951 	}
952 
953 	return 0;
954 }
955 
956 int audit_send_list_thread(void *_dest)
957 {
958 	struct audit_netlink_list *dest = _dest;
959 	struct sk_buff *skb;
960 	struct sock *sk = audit_get_sk(dest->net);
961 
962 	/* wait for parent to finish and send an ACK */
963 	audit_ctl_lock();
964 	audit_ctl_unlock();
965 
966 	while ((skb = __skb_dequeue(&dest->q)) != NULL)
967 		netlink_unicast(sk, skb, dest->portid, 0);
968 
969 	put_net(dest->net);
970 	kfree(dest);
971 
972 	return 0;
973 }
974 
975 struct sk_buff *audit_make_reply(int seq, int type, int done,
976 				 int multi, const void *payload, int size)
977 {
978 	struct sk_buff	*skb;
979 	struct nlmsghdr	*nlh;
980 	void		*data;
981 	int		flags = multi ? NLM_F_MULTI : 0;
982 	int		t     = done  ? NLMSG_DONE  : type;
983 
984 	skb = nlmsg_new(size, GFP_KERNEL);
985 	if (!skb)
986 		return NULL;
987 
988 	nlh	= nlmsg_put(skb, 0, seq, t, size, flags);
989 	if (!nlh)
990 		goto out_kfree_skb;
991 	data = nlmsg_data(nlh);
992 	memcpy(data, payload, size);
993 	return skb;
994 
995 out_kfree_skb:
996 	kfree_skb(skb);
997 	return NULL;
998 }
999 
1000 static void audit_free_reply(struct audit_reply *reply)
1001 {
1002 	if (!reply)
1003 		return;
1004 
1005 	kfree_skb(reply->skb);
1006 	if (reply->net)
1007 		put_net(reply->net);
1008 	kfree(reply);
1009 }
1010 
1011 static int audit_send_reply_thread(void *arg)
1012 {
1013 	struct audit_reply *reply = (struct audit_reply *)arg;
1014 
1015 	audit_ctl_lock();
1016 	audit_ctl_unlock();
1017 
1018 	/* Ignore failure. It'll only happen if the sender goes away,
1019 	   because our timeout is set to infinite. */
1020 	netlink_unicast(audit_get_sk(reply->net), reply->skb, reply->portid, 0);
1021 	reply->skb = NULL;
1022 	audit_free_reply(reply);
1023 	return 0;
1024 }
1025 
1026 /**
1027  * audit_send_reply - send an audit reply message via netlink
1028  * @request_skb: skb of request we are replying to (used to target the reply)
1029  * @seq: sequence number
1030  * @type: audit message type
1031  * @done: done (last) flag
1032  * @multi: multi-part message flag
1033  * @payload: payload data
1034  * @size: payload size
1035  *
1036  * Allocates a skb, builds the netlink message, and sends it to the port id.
1037  */
1038 static void audit_send_reply(struct sk_buff *request_skb, int seq, int type, int done,
1039 			     int multi, const void *payload, int size)
1040 {
1041 	struct task_struct *tsk;
1042 	struct audit_reply *reply;
1043 
1044 	reply = kzalloc(sizeof(*reply), GFP_KERNEL);
1045 	if (!reply)
1046 		return;
1047 
1048 	reply->skb = audit_make_reply(seq, type, done, multi, payload, size);
1049 	if (!reply->skb)
1050 		goto err;
1051 	reply->net = get_net(sock_net(NETLINK_CB(request_skb).sk));
1052 	reply->portid = NETLINK_CB(request_skb).portid;
1053 
1054 	tsk = kthread_run(audit_send_reply_thread, reply, "audit_send_reply");
1055 	if (IS_ERR(tsk))
1056 		goto err;
1057 
1058 	return;
1059 
1060 err:
1061 	audit_free_reply(reply);
1062 }
1063 
1064 /*
1065  * Check for appropriate CAP_AUDIT_ capabilities on incoming audit
1066  * control messages.
1067  */
1068 static int audit_netlink_ok(struct sk_buff *skb, u16 msg_type)
1069 {
1070 	int err = 0;
1071 
1072 	/* Only support initial user namespace for now. */
1073 	/*
1074 	 * We return ECONNREFUSED because it tricks userspace into thinking
1075 	 * that audit was not configured into the kernel.  Lots of users
1076 	 * configure their PAM stack (because that's what the distro does)
1077 	 * to reject login if unable to send messages to audit.  If we return
1078 	 * ECONNREFUSED the PAM stack thinks the kernel does not have audit
1079 	 * configured in and will let login proceed.  If we return EPERM
1080 	 * userspace will reject all logins.  This should be removed when we
1081 	 * support non init namespaces!!
1082 	 */
1083 	if (current_user_ns() != &init_user_ns)
1084 		return -ECONNREFUSED;
1085 
1086 	switch (msg_type) {
1087 	case AUDIT_LIST:
1088 	case AUDIT_ADD:
1089 	case AUDIT_DEL:
1090 		return -EOPNOTSUPP;
1091 	case AUDIT_GET:
1092 	case AUDIT_SET:
1093 	case AUDIT_GET_FEATURE:
1094 	case AUDIT_SET_FEATURE:
1095 	case AUDIT_LIST_RULES:
1096 	case AUDIT_ADD_RULE:
1097 	case AUDIT_DEL_RULE:
1098 	case AUDIT_SIGNAL_INFO:
1099 	case AUDIT_TTY_GET:
1100 	case AUDIT_TTY_SET:
1101 	case AUDIT_TRIM:
1102 	case AUDIT_MAKE_EQUIV:
1103 		/* Only support auditd and auditctl in initial pid namespace
1104 		 * for now. */
1105 		if (task_active_pid_ns(current) != &init_pid_ns)
1106 			return -EPERM;
1107 
1108 		if (!netlink_capable(skb, CAP_AUDIT_CONTROL))
1109 			err = -EPERM;
1110 		break;
1111 	case AUDIT_USER:
1112 	case AUDIT_FIRST_USER_MSG ... AUDIT_LAST_USER_MSG:
1113 	case AUDIT_FIRST_USER_MSG2 ... AUDIT_LAST_USER_MSG2:
1114 		if (!netlink_capable(skb, CAP_AUDIT_WRITE))
1115 			err = -EPERM;
1116 		break;
1117 	default:  /* bad msg */
1118 		err = -EINVAL;
1119 	}
1120 
1121 	return err;
1122 }
1123 
1124 static void audit_log_common_recv_msg(struct audit_context *context,
1125 					struct audit_buffer **ab, u16 msg_type)
1126 {
1127 	uid_t uid = from_kuid(&init_user_ns, current_uid());
1128 	pid_t pid = task_tgid_nr(current);
1129 
1130 	if (!audit_enabled && msg_type != AUDIT_USER_AVC) {
1131 		*ab = NULL;
1132 		return;
1133 	}
1134 
1135 	*ab = audit_log_start(context, GFP_KERNEL, msg_type);
1136 	if (unlikely(!*ab))
1137 		return;
1138 	audit_log_format(*ab, "pid=%d uid=%u ", pid, uid);
1139 	audit_log_session_info(*ab);
1140 	audit_log_task_context(*ab);
1141 }
1142 
1143 static inline void audit_log_user_recv_msg(struct audit_buffer **ab,
1144 					   u16 msg_type)
1145 {
1146 	audit_log_common_recv_msg(NULL, ab, msg_type);
1147 }
1148 
1149 static int is_audit_feature_set(int i)
1150 {
1151 	return af.features & AUDIT_FEATURE_TO_MASK(i);
1152 }
1153 
1154 static int audit_get_feature(struct sk_buff *skb)
1155 {
1156 	u32 seq;
1157 
1158 	seq = nlmsg_hdr(skb)->nlmsg_seq;
1159 
1160 	audit_send_reply(skb, seq, AUDIT_GET_FEATURE, 0, 0, &af, sizeof(af));
1161 
1162 	return 0;
1163 }
1164 
1165 static void audit_log_feature_change(int which, u32 old_feature, u32 new_feature,
1166 				     u32 old_lock, u32 new_lock, int res)
1167 {
1168 	struct audit_buffer *ab;
1169 
1170 	if (audit_enabled == AUDIT_OFF)
1171 		return;
1172 
1173 	ab = audit_log_start(audit_context(), GFP_KERNEL, AUDIT_FEATURE_CHANGE);
1174 	if (!ab)
1175 		return;
1176 	audit_log_task_info(ab);
1177 	audit_log_format(ab, " feature=%s old=%u new=%u old_lock=%u new_lock=%u res=%d",
1178 			 audit_feature_names[which], !!old_feature, !!new_feature,
1179 			 !!old_lock, !!new_lock, res);
1180 	audit_log_end(ab);
1181 }
1182 
1183 static int audit_set_feature(struct audit_features *uaf)
1184 {
1185 	int i;
1186 
1187 	BUILD_BUG_ON(AUDIT_LAST_FEATURE + 1 > ARRAY_SIZE(audit_feature_names));
1188 
1189 	/* if there is ever a version 2 we should handle that here */
1190 
1191 	for (i = 0; i <= AUDIT_LAST_FEATURE; i++) {
1192 		u32 feature = AUDIT_FEATURE_TO_MASK(i);
1193 		u32 old_feature, new_feature, old_lock, new_lock;
1194 
1195 		/* if we are not changing this feature, move along */
1196 		if (!(feature & uaf->mask))
1197 			continue;
1198 
1199 		old_feature = af.features & feature;
1200 		new_feature = uaf->features & feature;
1201 		new_lock = (uaf->lock | af.lock) & feature;
1202 		old_lock = af.lock & feature;
1203 
1204 		/* are we changing a locked feature? */
1205 		if (old_lock && (new_feature != old_feature)) {
1206 			audit_log_feature_change(i, old_feature, new_feature,
1207 						 old_lock, new_lock, 0);
1208 			return -EPERM;
1209 		}
1210 	}
1211 	/* nothing invalid, do the changes */
1212 	for (i = 0; i <= AUDIT_LAST_FEATURE; i++) {
1213 		u32 feature = AUDIT_FEATURE_TO_MASK(i);
1214 		u32 old_feature, new_feature, old_lock, new_lock;
1215 
1216 		/* if we are not changing this feature, move along */
1217 		if (!(feature & uaf->mask))
1218 			continue;
1219 
1220 		old_feature = af.features & feature;
1221 		new_feature = uaf->features & feature;
1222 		old_lock = af.lock & feature;
1223 		new_lock = (uaf->lock | af.lock) & feature;
1224 
1225 		if (new_feature != old_feature)
1226 			audit_log_feature_change(i, old_feature, new_feature,
1227 						 old_lock, new_lock, 1);
1228 
1229 		if (new_feature)
1230 			af.features |= feature;
1231 		else
1232 			af.features &= ~feature;
1233 		af.lock |= new_lock;
1234 	}
1235 
1236 	return 0;
1237 }
1238 
1239 static int audit_replace(struct pid *pid)
1240 {
1241 	pid_t pvnr;
1242 	struct sk_buff *skb;
1243 
1244 	pvnr = pid_vnr(pid);
1245 	skb = audit_make_reply(0, AUDIT_REPLACE, 0, 0, &pvnr, sizeof(pvnr));
1246 	if (!skb)
1247 		return -ENOMEM;
1248 	return auditd_send_unicast_skb(skb);
1249 }
1250 
1251 static int audit_receive_msg(struct sk_buff *skb, struct nlmsghdr *nlh,
1252 			     bool *ack)
1253 {
1254 	u32			seq;
1255 	void			*data;
1256 	int			data_len;
1257 	int			err;
1258 	struct audit_buffer	*ab;
1259 	u16			msg_type = nlh->nlmsg_type;
1260 	struct audit_sig_info   *sig_data;
1261 	struct lsm_context	lsmctx = { NULL, 0, 0 };
1262 
1263 	err = audit_netlink_ok(skb, msg_type);
1264 	if (err)
1265 		return err;
1266 
1267 	seq  = nlh->nlmsg_seq;
1268 	data = nlmsg_data(nlh);
1269 	data_len = nlmsg_len(nlh);
1270 
1271 	switch (msg_type) {
1272 	case AUDIT_GET: {
1273 		struct audit_status	s;
1274 		memset(&s, 0, sizeof(s));
1275 		s.enabled		   = audit_enabled;
1276 		s.failure		   = audit_failure;
1277 		/* NOTE: use pid_vnr() so the PID is relative to the current
1278 		 *       namespace */
1279 		s.pid			   = auditd_pid_vnr();
1280 		s.rate_limit		   = audit_rate_limit;
1281 		s.backlog_limit		   = audit_backlog_limit;
1282 		s.lost			   = atomic_read(&audit_lost);
1283 		s.backlog		   = skb_queue_len(&audit_queue);
1284 		s.feature_bitmap	   = AUDIT_FEATURE_BITMAP_ALL;
1285 		s.backlog_wait_time	   = audit_backlog_wait_time;
1286 		s.backlog_wait_time_actual = atomic_read(&audit_backlog_wait_time_actual);
1287 		audit_send_reply(skb, seq, AUDIT_GET, 0, 0, &s, sizeof(s));
1288 		break;
1289 	}
1290 	case AUDIT_SET: {
1291 		struct audit_status	s;
1292 		memset(&s, 0, sizeof(s));
1293 		/* guard against past and future API changes */
1294 		memcpy(&s, data, min_t(size_t, sizeof(s), data_len));
1295 		if (s.mask & AUDIT_STATUS_ENABLED) {
1296 			err = audit_set_enabled(s.enabled);
1297 			if (err < 0)
1298 				return err;
1299 		}
1300 		if (s.mask & AUDIT_STATUS_FAILURE) {
1301 			err = audit_set_failure(s.failure);
1302 			if (err < 0)
1303 				return err;
1304 		}
1305 		if (s.mask & AUDIT_STATUS_PID) {
1306 			/* NOTE: we are using the vnr PID functions below
1307 			 *       because the s.pid value is relative to the
1308 			 *       namespace of the caller; at present this
1309 			 *       doesn't matter much since you can really only
1310 			 *       run auditd from the initial pid namespace, but
1311 			 *       something to keep in mind if this changes */
1312 			pid_t new_pid = s.pid;
1313 			pid_t auditd_pid;
1314 			struct pid *req_pid = task_tgid(current);
1315 
1316 			/* Sanity check - PID values must match. Setting
1317 			 * pid to 0 is how auditd ends auditing. */
1318 			if (new_pid && (new_pid != pid_vnr(req_pid)))
1319 				return -EINVAL;
1320 
1321 			/* test the auditd connection */
1322 			audit_replace(req_pid);
1323 
1324 			auditd_pid = auditd_pid_vnr();
1325 			if (auditd_pid) {
1326 				/* replacing a healthy auditd is not allowed */
1327 				if (new_pid) {
1328 					audit_log_config_change("audit_pid",
1329 							new_pid, auditd_pid, 0);
1330 					return -EEXIST;
1331 				}
1332 				/* only current auditd can unregister itself */
1333 				if (pid_vnr(req_pid) != auditd_pid) {
1334 					audit_log_config_change("audit_pid",
1335 							new_pid, auditd_pid, 0);
1336 					return -EACCES;
1337 				}
1338 			}
1339 
1340 			if (new_pid) {
1341 				/* register a new auditd connection */
1342 				err = auditd_set(req_pid,
1343 						 NETLINK_CB(skb).portid,
1344 						 sock_net(NETLINK_CB(skb).sk),
1345 						 skb, ack);
1346 				if (audit_enabled != AUDIT_OFF)
1347 					audit_log_config_change("audit_pid",
1348 								new_pid,
1349 								auditd_pid,
1350 								err ? 0 : 1);
1351 				if (err)
1352 					return err;
1353 
1354 				/* try to process any backlog */
1355 				wake_up_interruptible(&kauditd_wait);
1356 			} else {
1357 				if (audit_enabled != AUDIT_OFF)
1358 					audit_log_config_change("audit_pid",
1359 								new_pid,
1360 								auditd_pid, 1);
1361 
1362 				/* unregister the auditd connection */
1363 				auditd_reset(NULL);
1364 			}
1365 		}
1366 		if (s.mask & AUDIT_STATUS_RATE_LIMIT) {
1367 			err = audit_set_rate_limit(s.rate_limit);
1368 			if (err < 0)
1369 				return err;
1370 		}
1371 		if (s.mask & AUDIT_STATUS_BACKLOG_LIMIT) {
1372 			err = audit_set_backlog_limit(s.backlog_limit);
1373 			if (err < 0)
1374 				return err;
1375 		}
1376 		if (s.mask & AUDIT_STATUS_BACKLOG_WAIT_TIME) {
1377 			if (sizeof(s) > (size_t)nlh->nlmsg_len)
1378 				return -EINVAL;
1379 			if (s.backlog_wait_time > 10*AUDIT_BACKLOG_WAIT_TIME)
1380 				return -EINVAL;
1381 			err = audit_set_backlog_wait_time(s.backlog_wait_time);
1382 			if (err < 0)
1383 				return err;
1384 		}
1385 		if (s.mask == AUDIT_STATUS_LOST) {
1386 			u32 lost = atomic_xchg(&audit_lost, 0);
1387 
1388 			audit_log_config_change("lost", 0, lost, 1);
1389 			return lost;
1390 		}
1391 		if (s.mask == AUDIT_STATUS_BACKLOG_WAIT_TIME_ACTUAL) {
1392 			u32 actual = atomic_xchg(&audit_backlog_wait_time_actual, 0);
1393 
1394 			audit_log_config_change("backlog_wait_time_actual", 0, actual, 1);
1395 			return actual;
1396 		}
1397 		break;
1398 	}
1399 	case AUDIT_GET_FEATURE:
1400 		err = audit_get_feature(skb);
1401 		if (err)
1402 			return err;
1403 		break;
1404 	case AUDIT_SET_FEATURE:
1405 		if (data_len < sizeof(struct audit_features))
1406 			return -EINVAL;
1407 		err = audit_set_feature(data);
1408 		if (err)
1409 			return err;
1410 		break;
1411 	case AUDIT_USER:
1412 	case AUDIT_FIRST_USER_MSG ... AUDIT_LAST_USER_MSG:
1413 	case AUDIT_FIRST_USER_MSG2 ... AUDIT_LAST_USER_MSG2:
1414 		if (!audit_enabled && msg_type != AUDIT_USER_AVC)
1415 			return 0;
1416 		/* exit early if there isn't at least one character to print */
1417 		if (data_len < 2)
1418 			return -EINVAL;
1419 
1420 		err = audit_filter(msg_type, AUDIT_FILTER_USER);
1421 		if (err == 1) { /* match or error */
1422 			char *str = data;
1423 
1424 			err = 0;
1425 			if (msg_type == AUDIT_USER_TTY) {
1426 				err = tty_audit_push();
1427 				if (err)
1428 					break;
1429 			}
1430 			audit_log_user_recv_msg(&ab, msg_type);
1431 			if (msg_type != AUDIT_USER_TTY) {
1432 				/* ensure NULL termination */
1433 				str[data_len - 1] = '\0';
1434 				audit_log_format(ab, " msg='%.*s'",
1435 						 AUDIT_MESSAGE_TEXT_MAX,
1436 						 str);
1437 			} else {
1438 				audit_log_format(ab, " data=");
1439 				if (str[data_len - 1] == '\0')
1440 					data_len--;
1441 				audit_log_n_untrustedstring(ab, str, data_len);
1442 			}
1443 			audit_log_end(ab);
1444 		}
1445 		break;
1446 	case AUDIT_ADD_RULE:
1447 	case AUDIT_DEL_RULE:
1448 		if (data_len < sizeof(struct audit_rule_data))
1449 			return -EINVAL;
1450 		if (audit_enabled == AUDIT_LOCKED) {
1451 			audit_log_common_recv_msg(audit_context(), &ab,
1452 						  AUDIT_CONFIG_CHANGE);
1453 			audit_log_format(ab, " op=%s audit_enabled=%d res=0",
1454 					 msg_type == AUDIT_ADD_RULE ?
1455 						"add_rule" : "remove_rule",
1456 					 audit_enabled);
1457 			audit_log_end(ab);
1458 			return -EPERM;
1459 		}
1460 		err = audit_rule_change(msg_type, seq, data, data_len);
1461 		break;
1462 	case AUDIT_LIST_RULES:
1463 		err = audit_list_rules_send(skb, seq);
1464 		break;
1465 	case AUDIT_TRIM:
1466 		audit_trim_trees();
1467 		audit_log_common_recv_msg(audit_context(), &ab,
1468 					  AUDIT_CONFIG_CHANGE);
1469 		audit_log_format(ab, " op=trim res=1");
1470 		audit_log_end(ab);
1471 		break;
1472 	case AUDIT_MAKE_EQUIV: {
1473 		void *bufp = data;
1474 		u32 sizes[2];
1475 		size_t msglen = data_len;
1476 		char *old, *new;
1477 
1478 		err = -EINVAL;
1479 		if (msglen < 2 * sizeof(u32))
1480 			break;
1481 		memcpy(sizes, bufp, 2 * sizeof(u32));
1482 		bufp += 2 * sizeof(u32);
1483 		msglen -= 2 * sizeof(u32);
1484 		old = audit_unpack_string(&bufp, &msglen, sizes[0]);
1485 		if (IS_ERR(old)) {
1486 			err = PTR_ERR(old);
1487 			break;
1488 		}
1489 		new = audit_unpack_string(&bufp, &msglen, sizes[1]);
1490 		if (IS_ERR(new)) {
1491 			err = PTR_ERR(new);
1492 			kfree(old);
1493 			break;
1494 		}
1495 		/* OK, here comes... */
1496 		err = audit_tag_tree(old, new);
1497 
1498 		audit_log_common_recv_msg(audit_context(), &ab,
1499 					  AUDIT_CONFIG_CHANGE);
1500 		audit_log_format(ab, " op=make_equiv old=");
1501 		audit_log_untrustedstring(ab, old);
1502 		audit_log_format(ab, " new=");
1503 		audit_log_untrustedstring(ab, new);
1504 		audit_log_format(ab, " res=%d", !err);
1505 		audit_log_end(ab);
1506 		kfree(old);
1507 		kfree(new);
1508 		break;
1509 	}
1510 	case AUDIT_SIGNAL_INFO:
1511 		if (lsmprop_is_set(&audit_sig_lsm)) {
1512 			err = security_lsmprop_to_secctx(&audit_sig_lsm,
1513 							 &lsmctx, LSM_ID_UNDEF);
1514 			if (err < 0)
1515 				return err;
1516 		}
1517 		sig_data = kmalloc(struct_size(sig_data, ctx, lsmctx.len),
1518 				   GFP_KERNEL);
1519 		if (!sig_data) {
1520 			if (lsmprop_is_set(&audit_sig_lsm))
1521 				security_release_secctx(&lsmctx);
1522 			return -ENOMEM;
1523 		}
1524 		sig_data->uid = from_kuid(&init_user_ns, audit_sig_uid);
1525 		sig_data->pid = audit_sig_pid;
1526 		if (lsmprop_is_set(&audit_sig_lsm)) {
1527 			memcpy(sig_data->ctx, lsmctx.context, lsmctx.len);
1528 			security_release_secctx(&lsmctx);
1529 		}
1530 		audit_send_reply(skb, seq, AUDIT_SIGNAL_INFO, 0, 0,
1531 				 sig_data, struct_size(sig_data, ctx,
1532 						       lsmctx.len));
1533 		kfree(sig_data);
1534 		break;
1535 	case AUDIT_TTY_GET: {
1536 		struct audit_tty_status s;
1537 		unsigned int t;
1538 
1539 		t = READ_ONCE(current->signal->audit_tty);
1540 		s.enabled = t & AUDIT_TTY_ENABLE;
1541 		s.log_passwd = !!(t & AUDIT_TTY_LOG_PASSWD);
1542 
1543 		audit_send_reply(skb, seq, AUDIT_TTY_GET, 0, 0, &s, sizeof(s));
1544 		break;
1545 	}
1546 	case AUDIT_TTY_SET: {
1547 		struct audit_tty_status s, old;
1548 		struct audit_buffer	*ab;
1549 		unsigned int t;
1550 
1551 		memset(&s, 0, sizeof(s));
1552 		/* guard against past and future API changes */
1553 		memcpy(&s, data, min_t(size_t, sizeof(s), data_len));
1554 		/* check if new data is valid */
1555 		if ((s.enabled != 0 && s.enabled != 1) ||
1556 		    (s.log_passwd != 0 && s.log_passwd != 1))
1557 			err = -EINVAL;
1558 
1559 		if (err)
1560 			t = READ_ONCE(current->signal->audit_tty);
1561 		else {
1562 			t = s.enabled | (-s.log_passwd & AUDIT_TTY_LOG_PASSWD);
1563 			t = xchg(&current->signal->audit_tty, t);
1564 		}
1565 		old.enabled = t & AUDIT_TTY_ENABLE;
1566 		old.log_passwd = !!(t & AUDIT_TTY_LOG_PASSWD);
1567 
1568 		audit_log_common_recv_msg(audit_context(), &ab,
1569 					  AUDIT_CONFIG_CHANGE);
1570 		audit_log_format(ab, " op=tty_set old-enabled=%d new-enabled=%d"
1571 				 " old-log_passwd=%d new-log_passwd=%d res=%d",
1572 				 old.enabled, s.enabled, old.log_passwd,
1573 				 s.log_passwd, !err);
1574 		audit_log_end(ab);
1575 		break;
1576 	}
1577 	default:
1578 		err = -EINVAL;
1579 		break;
1580 	}
1581 
1582 	return err < 0 ? err : 0;
1583 }
1584 
1585 /**
1586  * audit_receive - receive messages from a netlink control socket
1587  * @skb: the message buffer
1588  *
1589  * Parse the provided skb and deal with any messages that may be present,
1590  * malformed skbs are discarded.
1591  */
1592 static void audit_receive(struct sk_buff *skb)
1593 {
1594 	struct nlmsghdr *nlh;
1595 	bool ack;
1596 	/*
1597 	 * len MUST be signed for nlmsg_next to be able to dec it below 0
1598 	 * if the nlmsg_len was not aligned
1599 	 */
1600 	int len;
1601 	int err;
1602 
1603 	nlh = nlmsg_hdr(skb);
1604 	len = skb->len;
1605 
1606 	audit_ctl_lock();
1607 	while (nlmsg_ok(nlh, len)) {
1608 		ack = nlh->nlmsg_flags & NLM_F_ACK;
1609 		err = audit_receive_msg(skb, nlh, &ack);
1610 
1611 		/* send an ack if the user asked for one and audit_receive_msg
1612 		 * didn't already do it, or if there was an error. */
1613 		if (ack || err)
1614 			netlink_ack(skb, nlh, err, NULL);
1615 
1616 		nlh = nlmsg_next(nlh, &len);
1617 	}
1618 	audit_ctl_unlock();
1619 
1620 	/* can't block with the ctrl lock, so penalize the sender now */
1621 	if (audit_backlog_limit &&
1622 	    (skb_queue_len(&audit_queue) > audit_backlog_limit)) {
1623 		DECLARE_WAITQUEUE(wait, current);
1624 
1625 		/* wake kauditd to try and flush the queue */
1626 		wake_up_interruptible(&kauditd_wait);
1627 
1628 		add_wait_queue_exclusive(&audit_backlog_wait, &wait);
1629 		set_current_state(TASK_UNINTERRUPTIBLE);
1630 		schedule_timeout(audit_backlog_wait_time);
1631 		remove_wait_queue(&audit_backlog_wait, &wait);
1632 	}
1633 }
1634 
1635 /* Log information about who is connecting to the audit multicast socket */
1636 static void audit_log_multicast(int group, const char *op, int err)
1637 {
1638 	const struct cred *cred;
1639 	struct tty_struct *tty;
1640 	char comm[sizeof(current->comm)];
1641 	struct audit_buffer *ab;
1642 
1643 	if (!audit_enabled)
1644 		return;
1645 
1646 	ab = audit_log_start(audit_context(), GFP_KERNEL, AUDIT_EVENT_LISTENER);
1647 	if (!ab)
1648 		return;
1649 
1650 	cred = current_cred();
1651 	tty = audit_get_tty();
1652 	audit_log_format(ab, "pid=%u uid=%u auid=%u tty=%s ses=%u",
1653 			 task_tgid_nr(current),
1654 			 from_kuid(&init_user_ns, cred->uid),
1655 			 from_kuid(&init_user_ns, audit_get_loginuid(current)),
1656 			 tty ? tty_name(tty) : "(none)",
1657 			 audit_get_sessionid(current));
1658 	audit_put_tty(tty);
1659 	audit_log_task_context(ab); /* subj= */
1660 	audit_log_format(ab, " comm=");
1661 	audit_log_untrustedstring(ab, get_task_comm(comm, current));
1662 	audit_log_d_path_exe(ab, current->mm); /* exe= */
1663 	audit_log_format(ab, " nl-mcgrp=%d op=%s res=%d", group, op, !err);
1664 	audit_log_end(ab);
1665 }
1666 
1667 /* Run custom bind function on netlink socket group connect or bind requests. */
1668 static int audit_multicast_bind(struct net *net, int group)
1669 {
1670 	int err = 0;
1671 
1672 	if (!capable(CAP_AUDIT_READ))
1673 		err = -EPERM;
1674 	audit_log_multicast(group, "connect", err);
1675 	return err;
1676 }
1677 
1678 static void audit_multicast_unbind(struct net *net, int group)
1679 {
1680 	audit_log_multicast(group, "disconnect", 0);
1681 }
1682 
1683 static int __net_init audit_net_init(struct net *net)
1684 {
1685 	struct netlink_kernel_cfg cfg = {
1686 		.input	= audit_receive,
1687 		.bind	= audit_multicast_bind,
1688 		.unbind	= audit_multicast_unbind,
1689 		.flags	= NL_CFG_F_NONROOT_RECV,
1690 		.groups	= AUDIT_NLGRP_MAX,
1691 	};
1692 
1693 	struct audit_net *aunet = net_generic(net, audit_net_id);
1694 
1695 	aunet->sk = netlink_kernel_create(net, NETLINK_AUDIT, &cfg);
1696 	if (aunet->sk == NULL) {
1697 		audit_panic("cannot initialize netlink socket in namespace");
1698 		return -ENOMEM;
1699 	}
1700 	/* limit the timeout in case auditd is blocked/stopped */
1701 	aunet->sk->sk_sndtimeo = HZ / 10;
1702 
1703 	return 0;
1704 }
1705 
1706 static void __net_exit audit_net_exit(struct net *net)
1707 {
1708 	struct audit_net *aunet = net_generic(net, audit_net_id);
1709 
1710 	/* NOTE: you would think that we would want to check the auditd
1711 	 * connection and potentially reset it here if it lives in this
1712 	 * namespace, but since the auditd connection tracking struct holds a
1713 	 * reference to this namespace (see auditd_set()) we are only ever
1714 	 * going to get here after that connection has been released */
1715 
1716 	netlink_kernel_release(aunet->sk);
1717 }
1718 
1719 static struct pernet_operations audit_net_ops __net_initdata = {
1720 	.init = audit_net_init,
1721 	.exit = audit_net_exit,
1722 	.id = &audit_net_id,
1723 	.size = sizeof(struct audit_net),
1724 };
1725 
1726 /* Initialize audit support at boot time. */
1727 static int __init audit_init(void)
1728 {
1729 	int i;
1730 
1731 	if (audit_initialized == AUDIT_DISABLED)
1732 		return 0;
1733 
1734 	audit_buffer_cache = KMEM_CACHE(audit_buffer, SLAB_PANIC);
1735 
1736 	skb_queue_head_init(&audit_queue);
1737 	skb_queue_head_init(&audit_retry_queue);
1738 	skb_queue_head_init(&audit_hold_queue);
1739 
1740 	for (i = 0; i < AUDIT_INODE_BUCKETS; i++)
1741 		INIT_LIST_HEAD(&audit_inode_hash[i]);
1742 
1743 	mutex_init(&audit_cmd_mutex.lock);
1744 	audit_cmd_mutex.owner = NULL;
1745 
1746 	pr_info("initializing netlink subsys (%s)\n",
1747 		str_enabled_disabled(audit_default));
1748 	register_pernet_subsys(&audit_net_ops);
1749 
1750 	audit_initialized = AUDIT_INITIALIZED;
1751 
1752 	kauditd_task = kthread_run(kauditd_thread, NULL, "kauditd");
1753 	if (IS_ERR(kauditd_task)) {
1754 		int err = PTR_ERR(kauditd_task);
1755 		panic("audit: failed to start the kauditd thread (%d)\n", err);
1756 	}
1757 
1758 	audit_log(NULL, GFP_KERNEL, AUDIT_KERNEL,
1759 		"state=initialized audit_enabled=%u res=1",
1760 		 audit_enabled);
1761 
1762 	return 0;
1763 }
1764 postcore_initcall(audit_init);
1765 
1766 /*
1767  * Process kernel command-line parameter at boot time.
1768  * audit={0|off} or audit={1|on}.
1769  */
1770 static int __init audit_enable(char *str)
1771 {
1772 	if (!strcasecmp(str, "off") || !strcmp(str, "0"))
1773 		audit_default = AUDIT_OFF;
1774 	else if (!strcasecmp(str, "on") || !strcmp(str, "1"))
1775 		audit_default = AUDIT_ON;
1776 	else {
1777 		pr_err("audit: invalid 'audit' parameter value (%s)\n", str);
1778 		audit_default = AUDIT_ON;
1779 	}
1780 
1781 	if (audit_default == AUDIT_OFF)
1782 		audit_initialized = AUDIT_DISABLED;
1783 	if (audit_set_enabled(audit_default))
1784 		pr_err("audit: error setting audit state (%d)\n",
1785 		       audit_default);
1786 
1787 	pr_info("%s\n", audit_default ?
1788 		"enabled (after initialization)" : "disabled (until reboot)");
1789 
1790 	return 1;
1791 }
1792 __setup("audit=", audit_enable);
1793 
1794 /* Process kernel command-line parameter at boot time.
1795  * audit_backlog_limit=<n> */
1796 static int __init audit_backlog_limit_set(char *str)
1797 {
1798 	u32 audit_backlog_limit_arg;
1799 
1800 	pr_info("audit_backlog_limit: ");
1801 	if (kstrtouint(str, 0, &audit_backlog_limit_arg)) {
1802 		pr_cont("using default of %u, unable to parse %s\n",
1803 			audit_backlog_limit, str);
1804 		return 1;
1805 	}
1806 
1807 	audit_backlog_limit = audit_backlog_limit_arg;
1808 	pr_cont("%d\n", audit_backlog_limit);
1809 
1810 	return 1;
1811 }
1812 __setup("audit_backlog_limit=", audit_backlog_limit_set);
1813 
1814 static void audit_buffer_free(struct audit_buffer *ab)
1815 {
1816 	struct sk_buff *skb;
1817 
1818 	if (!ab)
1819 		return;
1820 
1821 	while ((skb = skb_dequeue(&ab->skb_list)))
1822 		kfree_skb(skb);
1823 	kmem_cache_free(audit_buffer_cache, ab);
1824 }
1825 
1826 static struct audit_buffer *audit_buffer_alloc(struct audit_context *ctx,
1827 					       gfp_t gfp_mask, int type)
1828 {
1829 	struct audit_buffer *ab;
1830 
1831 	ab = kmem_cache_alloc(audit_buffer_cache, gfp_mask);
1832 	if (!ab)
1833 		return NULL;
1834 
1835 	skb_queue_head_init(&ab->skb_list);
1836 
1837 	ab->skb = nlmsg_new(AUDIT_BUFSIZ, gfp_mask);
1838 	if (!ab->skb)
1839 		goto err;
1840 
1841 	skb_queue_tail(&ab->skb_list, ab->skb);
1842 
1843 	if (!nlmsg_put(ab->skb, 0, 0, type, 0, 0))
1844 		goto err;
1845 
1846 	ab->ctx = ctx;
1847 	ab->gfp_mask = gfp_mask;
1848 
1849 	return ab;
1850 
1851 err:
1852 	audit_buffer_free(ab);
1853 	return NULL;
1854 }
1855 
1856 /**
1857  * audit_serial - compute a serial number for the audit record
1858  *
1859  * Compute a serial number for the audit record.  Audit records are
1860  * written to user-space as soon as they are generated, so a complete
1861  * audit record may be written in several pieces.  The timestamp of the
1862  * record and this serial number are used by the user-space tools to
1863  * determine which pieces belong to the same audit record.  The
1864  * (timestamp,serial) tuple is unique for each syscall and is live from
1865  * syscall entry to syscall exit.
1866  *
1867  * NOTE: Another possibility is to store the formatted records off the
1868  * audit context (for those records that have a context), and emit them
1869  * all at syscall exit.  However, this could delay the reporting of
1870  * significant errors until syscall exit (or never, if the system
1871  * halts).
1872  */
1873 unsigned int audit_serial(void)
1874 {
1875 	static atomic_t serial = ATOMIC_INIT(0);
1876 
1877 	return atomic_inc_return(&serial);
1878 }
1879 
1880 static inline void audit_get_stamp(struct audit_context *ctx,
1881 				   struct audit_stamp *stamp)
1882 {
1883 	if (!ctx || !auditsc_get_stamp(ctx, stamp)) {
1884 		ktime_get_coarse_real_ts64(&stamp->ctime);
1885 		stamp->serial = audit_serial();
1886 	}
1887 }
1888 
1889 /**
1890  * audit_log_start - obtain an audit buffer
1891  * @ctx: audit_context (may be NULL)
1892  * @gfp_mask: type of allocation
1893  * @type: audit message type
1894  *
1895  * Returns audit_buffer pointer on success or NULL on error.
1896  *
1897  * Obtain an audit buffer.  This routine does locking to obtain the
1898  * audit buffer, but then no locking is required for calls to
1899  * audit_log_*format.  If the task (ctx) is a task that is currently in a
1900  * syscall, then the syscall is marked as auditable and an audit record
1901  * will be written at syscall exit.  If there is no associated task, then
1902  * task context (ctx) should be NULL.
1903  */
1904 struct audit_buffer *audit_log_start(struct audit_context *ctx, gfp_t gfp_mask,
1905 				     int type)
1906 {
1907 	struct audit_buffer *ab;
1908 
1909 	if (audit_initialized != AUDIT_INITIALIZED)
1910 		return NULL;
1911 
1912 	if (unlikely(!audit_filter(type, AUDIT_FILTER_EXCLUDE)))
1913 		return NULL;
1914 
1915 	/* NOTE: don't ever fail/sleep on these two conditions:
1916 	 * 1. auditd generated record - since we need auditd to drain the
1917 	 *    queue; also, when we are checking for auditd, compare PIDs using
1918 	 *    task_tgid_vnr() since auditd_pid is set in audit_receive_msg()
1919 	 *    using a PID anchored in the caller's namespace
1920 	 * 2. generator holding the audit_cmd_mutex - we don't want to block
1921 	 *    while holding the mutex, although we do penalize the sender
1922 	 *    later in audit_receive() when it is safe to block
1923 	 */
1924 	if (!(auditd_test_task(current) || audit_ctl_owner_current())) {
1925 		long stime = audit_backlog_wait_time;
1926 
1927 		while (audit_backlog_limit &&
1928 		       (skb_queue_len(&audit_queue) > audit_backlog_limit)) {
1929 			/* wake kauditd to try and flush the queue */
1930 			wake_up_interruptible(&kauditd_wait);
1931 
1932 			/* sleep if we are allowed and we haven't exhausted our
1933 			 * backlog wait limit */
1934 			if (gfpflags_allow_blocking(gfp_mask) && (stime > 0)) {
1935 				long rtime = stime;
1936 
1937 				DECLARE_WAITQUEUE(wait, current);
1938 
1939 				add_wait_queue_exclusive(&audit_backlog_wait,
1940 							 &wait);
1941 				set_current_state(TASK_UNINTERRUPTIBLE);
1942 				stime = schedule_timeout(rtime);
1943 				atomic_add(rtime - stime, &audit_backlog_wait_time_actual);
1944 				remove_wait_queue(&audit_backlog_wait, &wait);
1945 			} else {
1946 				if (audit_rate_check() && printk_ratelimit())
1947 					pr_warn("audit_backlog=%d > audit_backlog_limit=%d\n",
1948 						skb_queue_len(&audit_queue),
1949 						audit_backlog_limit);
1950 				audit_log_lost("backlog limit exceeded");
1951 				return NULL;
1952 			}
1953 		}
1954 	}
1955 
1956 	ab = audit_buffer_alloc(ctx, gfp_mask, type);
1957 	if (!ab) {
1958 		audit_log_lost("out of memory in audit_log_start");
1959 		return NULL;
1960 	}
1961 
1962 	audit_get_stamp(ab->ctx, &ab->stamp);
1963 	/* cancel dummy context to enable supporting records */
1964 	if (ctx)
1965 		ctx->dummy = 0;
1966 	audit_log_format(ab, "audit(%llu.%03lu:%u): ",
1967 			 (unsigned long long)ab->stamp.ctime.tv_sec,
1968 			 ab->stamp.ctime.tv_nsec/1000000,
1969 			 ab->stamp.serial);
1970 
1971 	return ab;
1972 }
1973 
1974 /**
1975  * audit_expand - expand skb in the audit buffer
1976  * @ab: audit_buffer
1977  * @extra: space to add at tail of the skb
1978  *
1979  * Returns 0 (no space) on failed expansion, or available space if
1980  * successful.
1981  */
1982 static inline int audit_expand(struct audit_buffer *ab, int extra)
1983 {
1984 	struct sk_buff *skb = ab->skb;
1985 	int oldtail = skb_tailroom(skb);
1986 	int ret = pskb_expand_head(skb, 0, extra, ab->gfp_mask);
1987 	int newtail = skb_tailroom(skb);
1988 
1989 	if (ret < 0) {
1990 		audit_log_lost("out of memory in audit_expand");
1991 		return 0;
1992 	}
1993 
1994 	skb->truesize += newtail - oldtail;
1995 	return newtail;
1996 }
1997 
1998 /*
1999  * Format an audit message into the audit buffer.  If there isn't enough
2000  * room in the audit buffer, more room will be allocated and vsnprint
2001  * will be called a second time.  Currently, we assume that a printk
2002  * can't format message larger than 1024 bytes, so we don't either.
2003  */
2004 static __printf(2, 0)
2005 void audit_log_vformat(struct audit_buffer *ab, const char *fmt, va_list args)
2006 {
2007 	int len, avail;
2008 	struct sk_buff *skb;
2009 	va_list args2;
2010 
2011 	if (!ab)
2012 		return;
2013 
2014 	BUG_ON(!ab->skb);
2015 	skb = ab->skb;
2016 	avail = skb_tailroom(skb);
2017 	if (avail == 0) {
2018 		avail = audit_expand(ab, AUDIT_BUFSIZ);
2019 		if (!avail)
2020 			goto out;
2021 	}
2022 	va_copy(args2, args);
2023 	len = vsnprintf(skb_tail_pointer(skb), avail, fmt, args);
2024 	if (len >= avail) {
2025 		/* The printk buffer is 1024 bytes long, so if we get
2026 		 * here and AUDIT_BUFSIZ is at least 1024, then we can
2027 		 * log everything that printk could have logged. */
2028 		avail = audit_expand(ab,
2029 			max_t(unsigned, AUDIT_BUFSIZ, 1+len-avail));
2030 		if (!avail)
2031 			goto out_va_end;
2032 		len = vsnprintf(skb_tail_pointer(skb), avail, fmt, args2);
2033 	}
2034 	if (len > 0)
2035 		skb_put(skb, len);
2036 out_va_end:
2037 	va_end(args2);
2038 out:
2039 	return;
2040 }
2041 
2042 /**
2043  * audit_log_format - format a message into the audit buffer.
2044  * @ab: audit_buffer
2045  * @fmt: format string
2046  * @...: optional parameters matching @fmt string
2047  *
2048  * All the work is done in audit_log_vformat.
2049  */
2050 void audit_log_format(struct audit_buffer *ab, const char *fmt, ...)
2051 {
2052 	va_list args;
2053 
2054 	if (!ab)
2055 		return;
2056 	va_start(args, fmt);
2057 	audit_log_vformat(ab, fmt, args);
2058 	va_end(args);
2059 }
2060 
2061 /**
2062  * audit_log_n_hex - convert a buffer to hex and append it to the audit skb
2063  * @ab: the audit_buffer
2064  * @buf: buffer to convert to hex
2065  * @len: length of @buf to be converted
2066  *
2067  * No return value; failure to expand is silently ignored.
2068  *
2069  * This function will take the passed buf and convert it into a string of
2070  * ascii hex digits. The new string is placed onto the skb.
2071  */
2072 void audit_log_n_hex(struct audit_buffer *ab, const unsigned char *buf,
2073 		size_t len)
2074 {
2075 	int i, avail, new_len;
2076 	unsigned char *ptr;
2077 	struct sk_buff *skb;
2078 
2079 	if (!ab)
2080 		return;
2081 
2082 	BUG_ON(!ab->skb);
2083 	skb = ab->skb;
2084 	avail = skb_tailroom(skb);
2085 	new_len = len<<1;
2086 	if (new_len >= avail) {
2087 		/* Round the buffer request up to the next multiple */
2088 		new_len = AUDIT_BUFSIZ*(((new_len-avail)/AUDIT_BUFSIZ) + 1);
2089 		avail = audit_expand(ab, new_len);
2090 		if (!avail)
2091 			return;
2092 	}
2093 
2094 	ptr = skb_tail_pointer(skb);
2095 	for (i = 0; i < len; i++)
2096 		ptr = hex_byte_pack_upper(ptr, buf[i]);
2097 	*ptr = 0;
2098 	skb_put(skb, len << 1); /* new string is twice the old string */
2099 }
2100 
2101 /*
2102  * Format a string of no more than slen characters into the audit buffer,
2103  * enclosed in quote marks.
2104  */
2105 void audit_log_n_string(struct audit_buffer *ab, const char *string,
2106 			size_t slen)
2107 {
2108 	int avail, new_len;
2109 	unsigned char *ptr;
2110 	struct sk_buff *skb;
2111 
2112 	if (!ab)
2113 		return;
2114 
2115 	BUG_ON(!ab->skb);
2116 	skb = ab->skb;
2117 	avail = skb_tailroom(skb);
2118 	new_len = slen + 3;	/* enclosing quotes + null terminator */
2119 	if (new_len > avail) {
2120 		avail = audit_expand(ab, new_len);
2121 		if (!avail)
2122 			return;
2123 	}
2124 	ptr = skb_tail_pointer(skb);
2125 	*ptr++ = '"';
2126 	memcpy(ptr, string, slen);
2127 	ptr += slen;
2128 	*ptr++ = '"';
2129 	*ptr = 0;
2130 	skb_put(skb, slen + 2);	/* don't include null terminator */
2131 }
2132 
2133 /**
2134  * audit_string_contains_control - does a string need to be logged in hex
2135  * @string: string to be checked
2136  * @len: max length of the string to check
2137  */
2138 bool audit_string_contains_control(const char *string, size_t len)
2139 {
2140 	const unsigned char *p;
2141 	for (p = string; p < (const unsigned char *)string + len; p++) {
2142 		if (*p == '"' || *p < 0x21 || *p > 0x7e)
2143 			return true;
2144 	}
2145 	return false;
2146 }
2147 
2148 /**
2149  * audit_log_n_untrustedstring - log a string that may contain random characters
2150  * @ab: audit_buffer
2151  * @string: string to be logged
2152  * @len: length of string (not including trailing null)
2153  *
2154  * This code will escape a string that is passed to it if the string
2155  * contains a control character, unprintable character, double quote mark,
2156  * or a space. Unescaped strings will start and end with a double quote mark.
2157  * Strings that are escaped are printed in hex (2 digits per char).
2158  *
2159  * The caller specifies the number of characters in the string to log, which may
2160  * or may not be the entire string.
2161  */
2162 void audit_log_n_untrustedstring(struct audit_buffer *ab, const char *string,
2163 				 size_t len)
2164 {
2165 	if (audit_string_contains_control(string, len))
2166 		audit_log_n_hex(ab, string, len);
2167 	else
2168 		audit_log_n_string(ab, string, len);
2169 }
2170 
2171 /**
2172  * audit_log_untrustedstring - log a string that may contain random characters
2173  * @ab: audit_buffer
2174  * @string: string to be logged
2175  *
2176  * Same as audit_log_n_untrustedstring(), except that strlen is used to
2177  * determine string length.
2178  */
2179 void audit_log_untrustedstring(struct audit_buffer *ab, const char *string)
2180 {
2181 	audit_log_n_untrustedstring(ab, string, strlen(string));
2182 }
2183 
2184 /* This is a helper-function to print the escaped d_path */
2185 void audit_log_d_path(struct audit_buffer *ab, const char *prefix,
2186 		      const struct path *path)
2187 {
2188 	char *p, *pathname;
2189 
2190 	if (prefix)
2191 		audit_log_format(ab, "%s", prefix);
2192 
2193 	/* We will allow 11 spaces for ' (deleted)' to be appended */
2194 	pathname = kmalloc(PATH_MAX+11, ab->gfp_mask);
2195 	if (!pathname) {
2196 		audit_log_format(ab, "\"<no_memory>\"");
2197 		return;
2198 	}
2199 	p = d_path(path, pathname, PATH_MAX+11);
2200 	if (IS_ERR(p)) { /* Should never happen since we send PATH_MAX */
2201 		/* FIXME: can we save some information here? */
2202 		audit_log_format(ab, "\"<too_long>\"");
2203 	} else
2204 		audit_log_untrustedstring(ab, p);
2205 	kfree(pathname);
2206 }
2207 
2208 void audit_log_session_info(struct audit_buffer *ab)
2209 {
2210 	unsigned int sessionid = audit_get_sessionid(current);
2211 	uid_t auid = from_kuid(&init_user_ns, audit_get_loginuid(current));
2212 
2213 	audit_log_format(ab, "auid=%u ses=%u", auid, sessionid);
2214 }
2215 
2216 void audit_log_key(struct audit_buffer *ab, char *key)
2217 {
2218 	audit_log_format(ab, " key=");
2219 	if (key)
2220 		audit_log_untrustedstring(ab, key);
2221 	else
2222 		audit_log_format(ab, "(null)");
2223 }
2224 
2225 /**
2226  * audit_buffer_aux_new - Add an aux record buffer to the skb list
2227  * @ab: audit_buffer
2228  * @type: message type
2229  *
2230  * Aux records are allocated and added to the skb list of
2231  * the "main" record. The ab->skb is reset to point to the
2232  * aux record on its creation. When the aux record in complete
2233  * ab->skb has to be reset to point to the "main" record.
2234  * This allows the audit_log_ functions to be ignorant of
2235  * which kind of record it is logging to. It also avoids adding
2236  * special data for aux records.
2237  *
2238  * On success ab->skb will point to the new aux record.
2239  * Returns 0 on success, -ENOMEM should allocation fail.
2240  */
2241 static int audit_buffer_aux_new(struct audit_buffer *ab, int type)
2242 {
2243 	WARN_ON(ab->skb != skb_peek(&ab->skb_list));
2244 
2245 	ab->skb = nlmsg_new(AUDIT_BUFSIZ, ab->gfp_mask);
2246 	if (!ab->skb)
2247 		goto err;
2248 	if (!nlmsg_put(ab->skb, 0, 0, type, 0, 0))
2249 		goto err;
2250 	skb_queue_tail(&ab->skb_list, ab->skb);
2251 
2252 	audit_log_format(ab, "audit(%llu.%03lu:%u): ",
2253 			 (unsigned long long)ab->stamp.ctime.tv_sec,
2254 			 ab->stamp.ctime.tv_nsec/1000000,
2255 			 ab->stamp.serial);
2256 
2257 	return 0;
2258 
2259 err:
2260 	kfree_skb(ab->skb);
2261 	ab->skb = skb_peek(&ab->skb_list);
2262 	return -ENOMEM;
2263 }
2264 
2265 /**
2266  * audit_buffer_aux_end - Switch back to the "main" record from an aux record
2267  * @ab: audit_buffer
2268  *
2269  * Restores the "main" audit record to ab->skb.
2270  */
2271 static void audit_buffer_aux_end(struct audit_buffer *ab)
2272 {
2273 	ab->skb = skb_peek(&ab->skb_list);
2274 }
2275 
2276 /**
2277  * audit_log_subj_ctx - Add LSM subject information
2278  * @ab: audit_buffer
2279  * @prop: LSM subject properties.
2280  *
2281  * Add a subj= field and, if necessary, a AUDIT_MAC_TASK_CONTEXTS record.
2282  */
2283 int audit_log_subj_ctx(struct audit_buffer *ab, struct lsm_prop *prop)
2284 {
2285 	struct lsm_context ctx;
2286 	char *space = "";
2287 	int error;
2288 	int i;
2289 
2290 	security_current_getlsmprop_subj(prop);
2291 	if (!lsmprop_is_set(prop))
2292 		return 0;
2293 
2294 	if (audit_subj_secctx_cnt < 2) {
2295 		error = security_lsmprop_to_secctx(prop, &ctx, LSM_ID_UNDEF);
2296 		if (error < 0) {
2297 			if (error != -EINVAL)
2298 				goto error_path;
2299 			return 0;
2300 		}
2301 		audit_log_format(ab, " subj=%s", ctx.context);
2302 		security_release_secctx(&ctx);
2303 		return 0;
2304 	}
2305 	/* Multiple LSMs provide contexts. Include an aux record. */
2306 	audit_log_format(ab, " subj=?");
2307 	error = audit_buffer_aux_new(ab, AUDIT_MAC_TASK_CONTEXTS);
2308 	if (error)
2309 		goto error_path;
2310 
2311 	for (i = 0; i < audit_subj_secctx_cnt; i++) {
2312 		error = security_lsmprop_to_secctx(prop, &ctx,
2313 						   audit_subj_lsms[i]->id);
2314 		if (error < 0) {
2315 			/*
2316 			 * Don't print anything. An LSM like BPF could
2317 			 * claim to support contexts, but only do so under
2318 			 * certain conditions.
2319 			 */
2320 			if (error == -EOPNOTSUPP)
2321 				continue;
2322 			if (error != -EINVAL)
2323 				audit_panic("error in audit_log_subj_ctx");
2324 		} else {
2325 			audit_log_format(ab, "%ssubj_%s=%s", space,
2326 					 audit_subj_lsms[i]->name, ctx.context);
2327 			space = " ";
2328 			security_release_secctx(&ctx);
2329 		}
2330 	}
2331 	audit_buffer_aux_end(ab);
2332 	return 0;
2333 
2334 error_path:
2335 	audit_panic("error in audit_log_subj_ctx");
2336 	return error;
2337 }
2338 EXPORT_SYMBOL(audit_log_subj_ctx);
2339 
2340 int audit_log_task_context(struct audit_buffer *ab)
2341 {
2342 	struct lsm_prop prop;
2343 
2344 	security_current_getlsmprop_subj(&prop);
2345 	return audit_log_subj_ctx(ab, &prop);
2346 }
2347 EXPORT_SYMBOL(audit_log_task_context);
2348 
2349 int audit_log_obj_ctx(struct audit_buffer *ab, struct lsm_prop *prop)
2350 {
2351 	int i;
2352 	int rc;
2353 	int error = 0;
2354 	char *space = "";
2355 	struct lsm_context ctx;
2356 
2357 	if (audit_obj_secctx_cnt < 2) {
2358 		error = security_lsmprop_to_secctx(prop, &ctx, LSM_ID_UNDEF);
2359 		if (error < 0) {
2360 			if (error != -EINVAL)
2361 				goto error_path;
2362 			return error;
2363 		}
2364 		audit_log_format(ab, " obj=%s", ctx.context);
2365 		security_release_secctx(&ctx);
2366 		return 0;
2367 	}
2368 	audit_log_format(ab, " obj=?");
2369 	error = audit_buffer_aux_new(ab, AUDIT_MAC_OBJ_CONTEXTS);
2370 	if (error)
2371 		goto error_path;
2372 
2373 	for (i = 0; i < audit_obj_secctx_cnt; i++) {
2374 		rc = security_lsmprop_to_secctx(prop, &ctx,
2375 						audit_obj_lsms[i]->id);
2376 		if (rc < 0) {
2377 			audit_log_format(ab, "%sobj_%s=?", space,
2378 					 audit_obj_lsms[i]->name);
2379 			if (rc != -EINVAL)
2380 				audit_panic("error in audit_log_obj_ctx");
2381 			error = rc;
2382 		} else {
2383 			audit_log_format(ab, "%sobj_%s=%s", space,
2384 					 audit_obj_lsms[i]->name, ctx.context);
2385 			security_release_secctx(&ctx);
2386 		}
2387 		space = " ";
2388 	}
2389 
2390 	audit_buffer_aux_end(ab);
2391 	return error;
2392 
2393 error_path:
2394 	audit_panic("error in audit_log_obj_ctx");
2395 	return error;
2396 }
2397 
2398 void audit_log_d_path_exe(struct audit_buffer *ab,
2399 			  struct mm_struct *mm)
2400 {
2401 	struct file *exe_file;
2402 
2403 	if (!mm)
2404 		goto out_null;
2405 
2406 	exe_file = get_mm_exe_file(mm);
2407 	if (!exe_file)
2408 		goto out_null;
2409 
2410 	audit_log_d_path(ab, " exe=", &exe_file->f_path);
2411 	fput(exe_file);
2412 	return;
2413 out_null:
2414 	audit_log_format(ab, " exe=(null)");
2415 }
2416 
2417 struct tty_struct *audit_get_tty(void)
2418 {
2419 	struct tty_struct *tty = NULL;
2420 	unsigned long flags;
2421 
2422 	spin_lock_irqsave(&current->sighand->siglock, flags);
2423 	if (current->signal)
2424 		tty = tty_kref_get(current->signal->tty);
2425 	spin_unlock_irqrestore(&current->sighand->siglock, flags);
2426 	return tty;
2427 }
2428 
2429 void audit_put_tty(struct tty_struct *tty)
2430 {
2431 	tty_kref_put(tty);
2432 }
2433 
2434 void audit_log_task_info(struct audit_buffer *ab)
2435 {
2436 	const struct cred *cred;
2437 	char comm[sizeof(current->comm)];
2438 	struct tty_struct *tty;
2439 
2440 	if (!ab)
2441 		return;
2442 
2443 	cred = current_cred();
2444 	tty = audit_get_tty();
2445 	audit_log_format(ab,
2446 			 " ppid=%d pid=%d auid=%u uid=%u gid=%u"
2447 			 " euid=%u suid=%u fsuid=%u"
2448 			 " egid=%u sgid=%u fsgid=%u tty=%s ses=%u",
2449 			 task_ppid_nr(current),
2450 			 task_tgid_nr(current),
2451 			 from_kuid(&init_user_ns, audit_get_loginuid(current)),
2452 			 from_kuid(&init_user_ns, cred->uid),
2453 			 from_kgid(&init_user_ns, cred->gid),
2454 			 from_kuid(&init_user_ns, cred->euid),
2455 			 from_kuid(&init_user_ns, cred->suid),
2456 			 from_kuid(&init_user_ns, cred->fsuid),
2457 			 from_kgid(&init_user_ns, cred->egid),
2458 			 from_kgid(&init_user_ns, cred->sgid),
2459 			 from_kgid(&init_user_ns, cred->fsgid),
2460 			 tty ? tty_name(tty) : "(none)",
2461 			 audit_get_sessionid(current));
2462 	audit_put_tty(tty);
2463 	audit_log_format(ab, " comm=");
2464 	audit_log_untrustedstring(ab, get_task_comm(comm, current));
2465 	audit_log_d_path_exe(ab, current->mm);
2466 	audit_log_task_context(ab);
2467 }
2468 EXPORT_SYMBOL(audit_log_task_info);
2469 
2470 /**
2471  * audit_log_path_denied - report a path restriction denial
2472  * @type: audit message type (AUDIT_ANOM_LINK, AUDIT_ANOM_CREAT, etc)
2473  * @operation: specific operation name
2474  */
2475 void audit_log_path_denied(int type, const char *operation)
2476 {
2477 	struct audit_buffer *ab;
2478 
2479 	if (!audit_enabled)
2480 		return;
2481 
2482 	/* Generate log with subject, operation, outcome. */
2483 	ab = audit_log_start(audit_context(), GFP_KERNEL, type);
2484 	if (!ab)
2485 		return;
2486 	audit_log_format(ab, "op=%s", operation);
2487 	audit_log_task_info(ab);
2488 	audit_log_format(ab, " res=0");
2489 	audit_log_end(ab);
2490 }
2491 
2492 /* global counter which is incremented every time something logs in */
2493 static atomic_t session_id = ATOMIC_INIT(0);
2494 
2495 static int audit_set_loginuid_perm(kuid_t loginuid)
2496 {
2497 	/* if we are unset, we don't need privs */
2498 	if (!audit_loginuid_set(current))
2499 		return 0;
2500 	/* if AUDIT_FEATURE_LOGINUID_IMMUTABLE means never ever allow a change*/
2501 	if (is_audit_feature_set(AUDIT_FEATURE_LOGINUID_IMMUTABLE))
2502 		return -EPERM;
2503 	/* it is set, you need permission */
2504 	if (!capable(CAP_AUDIT_CONTROL))
2505 		return -EPERM;
2506 	/* reject if this is not an unset and we don't allow that */
2507 	if (is_audit_feature_set(AUDIT_FEATURE_ONLY_UNSET_LOGINUID)
2508 				 && uid_valid(loginuid))
2509 		return -EPERM;
2510 	return 0;
2511 }
2512 
2513 static void audit_log_set_loginuid(kuid_t koldloginuid, kuid_t kloginuid,
2514 				   unsigned int oldsessionid,
2515 				   unsigned int sessionid, int rc)
2516 {
2517 	struct audit_buffer *ab;
2518 	uid_t uid, oldloginuid, loginuid;
2519 	struct tty_struct *tty;
2520 
2521 	if (!audit_enabled)
2522 		return;
2523 
2524 	ab = audit_log_start(audit_context(), GFP_KERNEL, AUDIT_LOGIN);
2525 	if (!ab)
2526 		return;
2527 
2528 	uid = from_kuid(&init_user_ns, task_uid(current));
2529 	oldloginuid = from_kuid(&init_user_ns, koldloginuid);
2530 	loginuid = from_kuid(&init_user_ns, kloginuid);
2531 	tty = audit_get_tty();
2532 
2533 	audit_log_format(ab, "pid=%d uid=%u", task_tgid_nr(current), uid);
2534 	audit_log_task_context(ab);
2535 	audit_log_format(ab, " old-auid=%u auid=%u tty=%s old-ses=%u ses=%u res=%d",
2536 			 oldloginuid, loginuid, tty ? tty_name(tty) : "(none)",
2537 			 oldsessionid, sessionid, !rc);
2538 	audit_put_tty(tty);
2539 	audit_log_end(ab);
2540 }
2541 
2542 /**
2543  * audit_set_loginuid - set current task's loginuid
2544  * @loginuid: loginuid value
2545  *
2546  * Returns 0.
2547  *
2548  * Called (set) from fs/proc/base.c::proc_loginuid_write().
2549  */
2550 int audit_set_loginuid(kuid_t loginuid)
2551 {
2552 	unsigned int oldsessionid, sessionid = AUDIT_SID_UNSET;
2553 	kuid_t oldloginuid;
2554 	int rc;
2555 
2556 	oldloginuid = audit_get_loginuid(current);
2557 	oldsessionid = audit_get_sessionid(current);
2558 
2559 	rc = audit_set_loginuid_perm(loginuid);
2560 	if (rc)
2561 		goto out;
2562 
2563 	/* are we setting or clearing? */
2564 	if (uid_valid(loginuid)) {
2565 		sessionid = (unsigned int)atomic_inc_return(&session_id);
2566 		if (unlikely(sessionid == AUDIT_SID_UNSET))
2567 			sessionid = (unsigned int)atomic_inc_return(&session_id);
2568 	}
2569 
2570 	current->sessionid = sessionid;
2571 	current->loginuid = loginuid;
2572 out:
2573 	audit_log_set_loginuid(oldloginuid, loginuid, oldsessionid, sessionid, rc);
2574 	return rc;
2575 }
2576 
2577 /**
2578  * audit_signal_info - record signal info for shutting down audit subsystem
2579  * @sig: signal value
2580  * @t: task being signaled
2581  *
2582  * If the audit subsystem is being terminated, record the task (pid)
2583  * and uid that is doing that.
2584  */
2585 int audit_signal_info(int sig, struct task_struct *t)
2586 {
2587 	kuid_t uid = current_uid(), auid;
2588 
2589 	if (auditd_test_task(t) &&
2590 	    (sig == SIGTERM || sig == SIGHUP ||
2591 	     sig == SIGUSR1 || sig == SIGUSR2)) {
2592 		audit_sig_pid = task_tgid_nr(current);
2593 		auid = audit_get_loginuid(current);
2594 		if (uid_valid(auid))
2595 			audit_sig_uid = auid;
2596 		else
2597 			audit_sig_uid = uid;
2598 		security_current_getlsmprop_subj(&audit_sig_lsm);
2599 	}
2600 
2601 	return audit_signal_info_syscall(t);
2602 }
2603 
2604 /**
2605  * __audit_log_end - enqueue one audit record
2606  * @skb: the buffer to send
2607  */
2608 static void __audit_log_end(struct sk_buff *skb)
2609 {
2610 	struct nlmsghdr *nlh;
2611 
2612 	if (audit_rate_check()) {
2613 		/* setup the netlink header, see the comments in
2614 		 * kauditd_send_multicast_skb() for length quirks */
2615 		nlh = nlmsg_hdr(skb);
2616 		nlh->nlmsg_len = skb->len - NLMSG_HDRLEN;
2617 
2618 		/* queue the netlink packet */
2619 		skb_queue_tail(&audit_queue, skb);
2620 	} else {
2621 		audit_log_lost("rate limit exceeded");
2622 		kfree_skb(skb);
2623 	}
2624 }
2625 
2626 /**
2627  * audit_log_end - end one audit record
2628  * @ab: the audit_buffer
2629  *
2630  * We can not do a netlink send inside an irq context because it blocks (last
2631  * arg, flags, is not set to MSG_DONTWAIT), so the audit buffer is placed on a
2632  * queue and a kthread is scheduled to remove them from the queue outside the
2633  * irq context.  May be called in any context.
2634  */
2635 void audit_log_end(struct audit_buffer *ab)
2636 {
2637 	struct sk_buff *skb;
2638 
2639 	if (!ab)
2640 		return;
2641 
2642 	while ((skb = skb_dequeue(&ab->skb_list)))
2643 		__audit_log_end(skb);
2644 
2645 	/* poke the kauditd thread */
2646 	wake_up_interruptible(&kauditd_wait);
2647 
2648 	audit_buffer_free(ab);
2649 }
2650 
2651 /**
2652  * audit_log - Log an audit record
2653  * @ctx: audit context
2654  * @gfp_mask: type of allocation
2655  * @type: audit message type
2656  * @fmt: format string to use
2657  * @...: variable parameters matching the format string
2658  *
2659  * This is a convenience function that calls audit_log_start,
2660  * audit_log_vformat, and audit_log_end.  It may be called
2661  * in any context.
2662  */
2663 void audit_log(struct audit_context *ctx, gfp_t gfp_mask, int type,
2664 	       const char *fmt, ...)
2665 {
2666 	struct audit_buffer *ab;
2667 	va_list args;
2668 
2669 	ab = audit_log_start(ctx, gfp_mask, type);
2670 	if (ab) {
2671 		va_start(args, fmt);
2672 		audit_log_vformat(ab, fmt, args);
2673 		va_end(args);
2674 		audit_log_end(ab);
2675 	}
2676 }
2677 
2678 EXPORT_SYMBOL(audit_log_start);
2679 EXPORT_SYMBOL(audit_log_end);
2680 EXPORT_SYMBOL(audit_log_format);
2681 EXPORT_SYMBOL(audit_log);
2682