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