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