xref: /linux/kernel/audit.c (revision 136114e0abf03005e182d75761ab694648e6d388)
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 = 0;
359 	static int		messages   = 0;
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 = 0;
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(sizeof(*ac_new), GFP_KERNEL);
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(sizeof(*reply), GFP_KERNEL);
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_ENABLED) {
1299 			err = audit_set_enabled(s.enabled);
1300 			if (err < 0)
1301 				return err;
1302 		}
1303 		if (s.mask & AUDIT_STATUS_FAILURE) {
1304 			err = audit_set_failure(s.failure);
1305 			if (err < 0)
1306 				return err;
1307 		}
1308 		if (s.mask & AUDIT_STATUS_PID) {
1309 			/* NOTE: we are using the vnr PID functions below
1310 			 *       because the s.pid value is relative to the
1311 			 *       namespace of the caller; at present this
1312 			 *       doesn't matter much since you can really only
1313 			 *       run auditd from the initial pid namespace, but
1314 			 *       something to keep in mind if this changes */
1315 			pid_t new_pid = s.pid;
1316 			pid_t auditd_pid;
1317 			struct pid *req_pid = task_tgid(current);
1318 
1319 			/* Sanity check - PID values must match. Setting
1320 			 * pid to 0 is how auditd ends auditing. */
1321 			if (new_pid && (new_pid != pid_vnr(req_pid)))
1322 				return -EINVAL;
1323 
1324 			/* test the auditd connection */
1325 			audit_replace(req_pid);
1326 
1327 			auditd_pid = auditd_pid_vnr();
1328 			if (auditd_pid) {
1329 				/* replacing a healthy auditd is not allowed */
1330 				if (new_pid) {
1331 					audit_log_config_change("audit_pid",
1332 							new_pid, auditd_pid, 0);
1333 					return -EEXIST;
1334 				}
1335 				/* only current auditd can unregister itself */
1336 				if (pid_vnr(req_pid) != auditd_pid) {
1337 					audit_log_config_change("audit_pid",
1338 							new_pid, auditd_pid, 0);
1339 					return -EACCES;
1340 				}
1341 			}
1342 
1343 			if (new_pid) {
1344 				/* register a new auditd connection */
1345 				err = auditd_set(req_pid,
1346 						 NETLINK_CB(skb).portid,
1347 						 sock_net(NETLINK_CB(skb).sk),
1348 						 skb, ack);
1349 				if (audit_enabled != AUDIT_OFF)
1350 					audit_log_config_change("audit_pid",
1351 								new_pid,
1352 								auditd_pid,
1353 								err ? 0 : 1);
1354 				if (err)
1355 					return err;
1356 
1357 				/* try to process any backlog */
1358 				wake_up_interruptible(&kauditd_wait);
1359 			} else {
1360 				if (audit_enabled != AUDIT_OFF)
1361 					audit_log_config_change("audit_pid",
1362 								new_pid,
1363 								auditd_pid, 1);
1364 
1365 				/* unregister the auditd connection */
1366 				auditd_reset(NULL);
1367 			}
1368 		}
1369 		if (s.mask & AUDIT_STATUS_RATE_LIMIT) {
1370 			err = audit_set_rate_limit(s.rate_limit);
1371 			if (err < 0)
1372 				return err;
1373 		}
1374 		if (s.mask & AUDIT_STATUS_BACKLOG_LIMIT) {
1375 			err = audit_set_backlog_limit(s.backlog_limit);
1376 			if (err < 0)
1377 				return err;
1378 		}
1379 		if (s.mask & AUDIT_STATUS_BACKLOG_WAIT_TIME) {
1380 			if (sizeof(s) > (size_t)nlh->nlmsg_len)
1381 				return -EINVAL;
1382 			if (s.backlog_wait_time > 10*AUDIT_BACKLOG_WAIT_TIME)
1383 				return -EINVAL;
1384 			err = audit_set_backlog_wait_time(s.backlog_wait_time);
1385 			if (err < 0)
1386 				return err;
1387 		}
1388 		if (s.mask == AUDIT_STATUS_LOST) {
1389 			u32 lost = atomic_xchg(&audit_lost, 0);
1390 
1391 			audit_log_config_change("lost", 0, lost, 1);
1392 			return lost;
1393 		}
1394 		if (s.mask == AUDIT_STATUS_BACKLOG_WAIT_TIME_ACTUAL) {
1395 			u32 actual = atomic_xchg(&audit_backlog_wait_time_actual, 0);
1396 
1397 			audit_log_config_change("backlog_wait_time_actual", 0, actual, 1);
1398 			return actual;
1399 		}
1400 		break;
1401 	}
1402 	case AUDIT_GET_FEATURE:
1403 		err = audit_get_feature(skb);
1404 		if (err)
1405 			return err;
1406 		break;
1407 	case AUDIT_SET_FEATURE:
1408 		if (data_len < sizeof(struct audit_features))
1409 			return -EINVAL;
1410 		err = audit_set_feature(data);
1411 		if (err)
1412 			return err;
1413 		break;
1414 	case AUDIT_USER:
1415 	case AUDIT_FIRST_USER_MSG ... AUDIT_LAST_USER_MSG:
1416 	case AUDIT_FIRST_USER_MSG2 ... AUDIT_LAST_USER_MSG2:
1417 		if (!audit_enabled && msg_type != AUDIT_USER_AVC)
1418 			return 0;
1419 		/* exit early if there isn't at least one character to print */
1420 		if (data_len < 2)
1421 			return -EINVAL;
1422 
1423 		err = audit_filter(msg_type, AUDIT_FILTER_USER);
1424 		if (err == 1) { /* match or error */
1425 			char *str = data;
1426 
1427 			err = 0;
1428 			if (msg_type == AUDIT_USER_TTY) {
1429 				err = tty_audit_push();
1430 				if (err)
1431 					break;
1432 			}
1433 			audit_log_user_recv_msg(&ab, msg_type);
1434 			if (msg_type != AUDIT_USER_TTY) {
1435 				/* ensure NULL termination */
1436 				str[data_len - 1] = '\0';
1437 				audit_log_format(ab, " msg='%.*s'",
1438 						 AUDIT_MESSAGE_TEXT_MAX,
1439 						 str);
1440 			} else {
1441 				audit_log_format(ab, " data=");
1442 				if (str[data_len - 1] == '\0')
1443 					data_len--;
1444 				audit_log_n_untrustedstring(ab, str, data_len);
1445 			}
1446 			audit_log_end(ab);
1447 		}
1448 		break;
1449 	case AUDIT_ADD_RULE:
1450 	case AUDIT_DEL_RULE:
1451 		if (data_len < sizeof(struct audit_rule_data))
1452 			return -EINVAL;
1453 		if (audit_enabled == AUDIT_LOCKED) {
1454 			audit_log_common_recv_msg(audit_context(), &ab,
1455 						  AUDIT_CONFIG_CHANGE);
1456 			audit_log_format(ab, " op=%s audit_enabled=%d res=0",
1457 					 msg_type == AUDIT_ADD_RULE ?
1458 						"add_rule" : "remove_rule",
1459 					 audit_enabled);
1460 			audit_log_end(ab);
1461 			return -EPERM;
1462 		}
1463 		err = audit_rule_change(msg_type, seq, data, data_len);
1464 		break;
1465 	case AUDIT_LIST_RULES:
1466 		err = audit_list_rules_send(skb, seq);
1467 		break;
1468 	case AUDIT_TRIM:
1469 		audit_trim_trees();
1470 		audit_log_common_recv_msg(audit_context(), &ab,
1471 					  AUDIT_CONFIG_CHANGE);
1472 		audit_log_format(ab, " op=trim res=1");
1473 		audit_log_end(ab);
1474 		break;
1475 	case AUDIT_MAKE_EQUIV: {
1476 		void *bufp = data;
1477 		u32 sizes[2];
1478 		size_t msglen = data_len;
1479 		char *old, *new;
1480 
1481 		err = -EINVAL;
1482 		if (msglen < 2 * sizeof(u32))
1483 			break;
1484 		memcpy(sizes, bufp, 2 * sizeof(u32));
1485 		bufp += 2 * sizeof(u32);
1486 		msglen -= 2 * sizeof(u32);
1487 		old = audit_unpack_string(&bufp, &msglen, sizes[0]);
1488 		if (IS_ERR(old)) {
1489 			err = PTR_ERR(old);
1490 			break;
1491 		}
1492 		new = audit_unpack_string(&bufp, &msglen, sizes[1]);
1493 		if (IS_ERR(new)) {
1494 			err = PTR_ERR(new);
1495 			kfree(old);
1496 			break;
1497 		}
1498 		/* OK, here comes... */
1499 		err = audit_tag_tree(old, new);
1500 
1501 		audit_log_common_recv_msg(audit_context(), &ab,
1502 					  AUDIT_CONFIG_CHANGE);
1503 		audit_log_format(ab, " op=make_equiv old=");
1504 		audit_log_untrustedstring(ab, old);
1505 		audit_log_format(ab, " new=");
1506 		audit_log_untrustedstring(ab, new);
1507 		audit_log_format(ab, " res=%d", !err);
1508 		audit_log_end(ab);
1509 		kfree(old);
1510 		kfree(new);
1511 		break;
1512 	}
1513 	case AUDIT_SIGNAL_INFO:
1514 		if (lsmprop_is_set(&audit_sig_lsm)) {
1515 			err = security_lsmprop_to_secctx(&audit_sig_lsm,
1516 							 &lsmctx, LSM_ID_UNDEF);
1517 			if (err < 0)
1518 				return err;
1519 		}
1520 		sig_data = kmalloc(struct_size(sig_data, ctx, lsmctx.len),
1521 				   GFP_KERNEL);
1522 		if (!sig_data) {
1523 			if (lsmprop_is_set(&audit_sig_lsm))
1524 				security_release_secctx(&lsmctx);
1525 			return -ENOMEM;
1526 		}
1527 		sig_data->uid = from_kuid(&init_user_ns, audit_sig_uid);
1528 		sig_data->pid = audit_sig_pid;
1529 		if (lsmprop_is_set(&audit_sig_lsm)) {
1530 			memcpy(sig_data->ctx, lsmctx.context, lsmctx.len);
1531 			security_release_secctx(&lsmctx);
1532 		}
1533 		audit_send_reply(skb, seq, AUDIT_SIGNAL_INFO, 0, 0,
1534 				 sig_data, struct_size(sig_data, ctx,
1535 						       lsmctx.len));
1536 		kfree(sig_data);
1537 		break;
1538 	case AUDIT_TTY_GET: {
1539 		struct audit_tty_status s;
1540 		unsigned int t;
1541 
1542 		t = READ_ONCE(current->signal->audit_tty);
1543 		s.enabled = t & AUDIT_TTY_ENABLE;
1544 		s.log_passwd = !!(t & AUDIT_TTY_LOG_PASSWD);
1545 
1546 		audit_send_reply(skb, seq, AUDIT_TTY_GET, 0, 0, &s, sizeof(s));
1547 		break;
1548 	}
1549 	case AUDIT_TTY_SET: {
1550 		struct audit_tty_status s, old;
1551 		struct audit_buffer	*ab;
1552 		unsigned int t;
1553 
1554 		memset(&s, 0, sizeof(s));
1555 		/* guard against past and future API changes */
1556 		memcpy(&s, data, min_t(size_t, sizeof(s), data_len));
1557 		/* check if new data is valid */
1558 		if ((s.enabled != 0 && s.enabled != 1) ||
1559 		    (s.log_passwd != 0 && s.log_passwd != 1))
1560 			err = -EINVAL;
1561 
1562 		if (err)
1563 			t = READ_ONCE(current->signal->audit_tty);
1564 		else {
1565 			t = s.enabled | (-s.log_passwd & AUDIT_TTY_LOG_PASSWD);
1566 			t = xchg(&current->signal->audit_tty, t);
1567 		}
1568 		old.enabled = t & AUDIT_TTY_ENABLE;
1569 		old.log_passwd = !!(t & AUDIT_TTY_LOG_PASSWD);
1570 
1571 		audit_log_common_recv_msg(audit_context(), &ab,
1572 					  AUDIT_CONFIG_CHANGE);
1573 		audit_log_format(ab, " op=tty_set old-enabled=%d new-enabled=%d"
1574 				 " old-log_passwd=%d new-log_passwd=%d res=%d",
1575 				 old.enabled, s.enabled, old.log_passwd,
1576 				 s.log_passwd, !err);
1577 		audit_log_end(ab);
1578 		break;
1579 	}
1580 	default:
1581 		err = -EINVAL;
1582 		break;
1583 	}
1584 
1585 	return err < 0 ? err : 0;
1586 }
1587 
1588 /**
1589  * audit_receive - receive messages from a netlink control socket
1590  * @skb: the message buffer
1591  *
1592  * Parse the provided skb and deal with any messages that may be present,
1593  * malformed skbs are discarded.
1594  */
1595 static void audit_receive(struct sk_buff *skb)
1596 {
1597 	struct nlmsghdr *nlh;
1598 	bool ack;
1599 	/*
1600 	 * len MUST be signed for nlmsg_next to be able to dec it below 0
1601 	 * if the nlmsg_len was not aligned
1602 	 */
1603 	int len;
1604 	int err;
1605 
1606 	nlh = nlmsg_hdr(skb);
1607 	len = skb->len;
1608 
1609 	audit_ctl_lock();
1610 	while (nlmsg_ok(nlh, len)) {
1611 		ack = nlh->nlmsg_flags & NLM_F_ACK;
1612 		err = audit_receive_msg(skb, nlh, &ack);
1613 
1614 		/* send an ack if the user asked for one and audit_receive_msg
1615 		 * didn't already do it, or if there was an error. */
1616 		if (ack || err)
1617 			netlink_ack(skb, nlh, err, NULL);
1618 
1619 		nlh = nlmsg_next(nlh, &len);
1620 	}
1621 	audit_ctl_unlock();
1622 
1623 	/* can't block with the ctrl lock, so penalize the sender now */
1624 	if (audit_backlog_limit &&
1625 	    (skb_queue_len(&audit_queue) > audit_backlog_limit)) {
1626 		DECLARE_WAITQUEUE(wait, current);
1627 
1628 		/* wake kauditd to try and flush the queue */
1629 		wake_up_interruptible(&kauditd_wait);
1630 
1631 		add_wait_queue_exclusive(&audit_backlog_wait, &wait);
1632 		set_current_state(TASK_UNINTERRUPTIBLE);
1633 		schedule_timeout(audit_backlog_wait_time);
1634 		remove_wait_queue(&audit_backlog_wait, &wait);
1635 	}
1636 }
1637 
1638 /* Log information about who is connecting to the audit multicast socket */
1639 static void audit_log_multicast(int group, const char *op, int err)
1640 {
1641 	const struct cred *cred;
1642 	struct tty_struct *tty;
1643 	char comm[sizeof(current->comm)];
1644 	struct audit_buffer *ab;
1645 
1646 	if (!audit_enabled)
1647 		return;
1648 
1649 	ab = audit_log_start(audit_context(), GFP_KERNEL, AUDIT_EVENT_LISTENER);
1650 	if (!ab)
1651 		return;
1652 
1653 	cred = current_cred();
1654 	tty = audit_get_tty();
1655 	audit_log_format(ab, "pid=%u uid=%u auid=%u tty=%s ses=%u",
1656 			 task_tgid_nr(current),
1657 			 from_kuid(&init_user_ns, cred->uid),
1658 			 from_kuid(&init_user_ns, audit_get_loginuid(current)),
1659 			 tty ? tty_name(tty) : "(none)",
1660 			 audit_get_sessionid(current));
1661 	audit_put_tty(tty);
1662 	audit_log_task_context(ab); /* subj= */
1663 	audit_log_format(ab, " comm=");
1664 	audit_log_untrustedstring(ab, get_task_comm(comm, current));
1665 	audit_log_d_path_exe(ab, current->mm); /* exe= */
1666 	audit_log_format(ab, " nl-mcgrp=%d op=%s res=%d", group, op, !err);
1667 	audit_log_end(ab);
1668 }
1669 
1670 /* Run custom bind function on netlink socket group connect or bind requests. */
1671 static int audit_multicast_bind(struct net *net, int group)
1672 {
1673 	int err = 0;
1674 
1675 	if (!capable(CAP_AUDIT_READ))
1676 		err = -EPERM;
1677 	audit_log_multicast(group, "connect", err);
1678 	return err;
1679 }
1680 
1681 static void audit_multicast_unbind(struct net *net, int group)
1682 {
1683 	audit_log_multicast(group, "disconnect", 0);
1684 }
1685 
1686 static int __net_init audit_net_init(struct net *net)
1687 {
1688 	struct netlink_kernel_cfg cfg = {
1689 		.input	= audit_receive,
1690 		.bind	= audit_multicast_bind,
1691 		.unbind	= audit_multicast_unbind,
1692 		.flags	= NL_CFG_F_NONROOT_RECV,
1693 		.groups	= AUDIT_NLGRP_MAX,
1694 	};
1695 
1696 	struct audit_net *aunet = net_generic(net, audit_net_id);
1697 
1698 	aunet->sk = netlink_kernel_create(net, NETLINK_AUDIT, &cfg);
1699 	if (aunet->sk == NULL) {
1700 		audit_panic("cannot initialize netlink socket in namespace");
1701 		return -ENOMEM;
1702 	}
1703 	/* limit the timeout in case auditd is blocked/stopped */
1704 	aunet->sk->sk_sndtimeo = HZ / 10;
1705 
1706 	return 0;
1707 }
1708 
1709 static void __net_exit audit_net_exit(struct net *net)
1710 {
1711 	struct audit_net *aunet = net_generic(net, audit_net_id);
1712 
1713 	/* NOTE: you would think that we would want to check the auditd
1714 	 * connection and potentially reset it here if it lives in this
1715 	 * namespace, but since the auditd connection tracking struct holds a
1716 	 * reference to this namespace (see auditd_set()) we are only ever
1717 	 * going to get here after that connection has been released */
1718 
1719 	netlink_kernel_release(aunet->sk);
1720 }
1721 
1722 static struct pernet_operations audit_net_ops __net_initdata = {
1723 	.init = audit_net_init,
1724 	.exit = audit_net_exit,
1725 	.id = &audit_net_id,
1726 	.size = sizeof(struct audit_net),
1727 };
1728 
1729 /* Initialize audit support at boot time. */
1730 static int __init audit_init(void)
1731 {
1732 	int i;
1733 
1734 	if (audit_initialized == AUDIT_DISABLED)
1735 		return 0;
1736 
1737 	audit_buffer_cache = KMEM_CACHE(audit_buffer, SLAB_PANIC);
1738 
1739 	skb_queue_head_init(&audit_queue);
1740 	skb_queue_head_init(&audit_retry_queue);
1741 	skb_queue_head_init(&audit_hold_queue);
1742 
1743 	for (i = 0; i < AUDIT_INODE_BUCKETS; i++)
1744 		INIT_LIST_HEAD(&audit_inode_hash[i]);
1745 
1746 	mutex_init(&audit_cmd_mutex.lock);
1747 	audit_cmd_mutex.owner = NULL;
1748 
1749 	pr_info("initializing netlink subsys (%s)\n",
1750 		str_enabled_disabled(audit_default));
1751 	register_pernet_subsys(&audit_net_ops);
1752 
1753 	audit_initialized = AUDIT_INITIALIZED;
1754 
1755 	kauditd_task = kthread_run(kauditd_thread, NULL, "kauditd");
1756 	if (IS_ERR(kauditd_task)) {
1757 		int err = PTR_ERR(kauditd_task);
1758 		panic("audit: failed to start the kauditd thread (%d)\n", err);
1759 	}
1760 
1761 	audit_log(NULL, GFP_KERNEL, AUDIT_KERNEL,
1762 		"state=initialized audit_enabled=%u res=1",
1763 		 audit_enabled);
1764 
1765 	return 0;
1766 }
1767 postcore_initcall(audit_init);
1768 
1769 /*
1770  * Process kernel command-line parameter at boot time.
1771  * audit={0|off} or audit={1|on}.
1772  */
1773 static int __init audit_enable(char *str)
1774 {
1775 	if (!strcasecmp(str, "off") || !strcmp(str, "0"))
1776 		audit_default = AUDIT_OFF;
1777 	else if (!strcasecmp(str, "on") || !strcmp(str, "1"))
1778 		audit_default = AUDIT_ON;
1779 	else {
1780 		pr_err("audit: invalid 'audit' parameter value (%s)\n", str);
1781 		audit_default = AUDIT_ON;
1782 	}
1783 
1784 	if (audit_default == AUDIT_OFF)
1785 		audit_initialized = AUDIT_DISABLED;
1786 	if (audit_set_enabled(audit_default))
1787 		pr_err("audit: error setting audit state (%d)\n",
1788 		       audit_default);
1789 
1790 	pr_info("%s\n", audit_default ?
1791 		"enabled (after initialization)" : "disabled (until reboot)");
1792 
1793 	return 1;
1794 }
1795 __setup("audit=", audit_enable);
1796 
1797 /* Process kernel command-line parameter at boot time.
1798  * audit_backlog_limit=<n> */
1799 static int __init audit_backlog_limit_set(char *str)
1800 {
1801 	u32 audit_backlog_limit_arg;
1802 
1803 	pr_info("audit_backlog_limit: ");
1804 	if (kstrtouint(str, 0, &audit_backlog_limit_arg)) {
1805 		pr_cont("using default of %u, unable to parse %s\n",
1806 			audit_backlog_limit, str);
1807 		return 1;
1808 	}
1809 
1810 	audit_backlog_limit = audit_backlog_limit_arg;
1811 	pr_cont("%d\n", audit_backlog_limit);
1812 
1813 	return 1;
1814 }
1815 __setup("audit_backlog_limit=", audit_backlog_limit_set);
1816 
1817 static void audit_buffer_free(struct audit_buffer *ab)
1818 {
1819 	struct sk_buff *skb;
1820 
1821 	if (!ab)
1822 		return;
1823 
1824 	while ((skb = skb_dequeue(&ab->skb_list)))
1825 		kfree_skb(skb);
1826 	kmem_cache_free(audit_buffer_cache, ab);
1827 }
1828 
1829 static struct audit_buffer *audit_buffer_alloc(struct audit_context *ctx,
1830 					       gfp_t gfp_mask, int type)
1831 {
1832 	struct audit_buffer *ab;
1833 
1834 	ab = kmem_cache_alloc(audit_buffer_cache, gfp_mask);
1835 	if (!ab)
1836 		return NULL;
1837 
1838 	skb_queue_head_init(&ab->skb_list);
1839 
1840 	ab->skb = nlmsg_new(AUDIT_BUFSIZ, gfp_mask);
1841 	if (!ab->skb)
1842 		goto err;
1843 
1844 	skb_queue_tail(&ab->skb_list, ab->skb);
1845 
1846 	if (!nlmsg_put(ab->skb, 0, 0, type, 0, 0))
1847 		goto err;
1848 
1849 	ab->ctx = ctx;
1850 	ab->gfp_mask = gfp_mask;
1851 
1852 	return ab;
1853 
1854 err:
1855 	audit_buffer_free(ab);
1856 	return NULL;
1857 }
1858 
1859 /**
1860  * audit_serial - compute a serial number for the audit record
1861  *
1862  * Compute a serial number for the audit record.  Audit records are
1863  * written to user-space as soon as they are generated, so a complete
1864  * audit record may be written in several pieces.  The timestamp of the
1865  * record and this serial number are used by the user-space tools to
1866  * determine which pieces belong to the same audit record.  The
1867  * (timestamp,serial) tuple is unique for each syscall and is live from
1868  * syscall entry to syscall exit.
1869  *
1870  * NOTE: Another possibility is to store the formatted records off the
1871  * audit context (for those records that have a context), and emit them
1872  * all at syscall exit.  However, this could delay the reporting of
1873  * significant errors until syscall exit (or never, if the system
1874  * halts).
1875  */
1876 unsigned int audit_serial(void)
1877 {
1878 	static atomic_t serial = ATOMIC_INIT(0);
1879 
1880 	return atomic_inc_return(&serial);
1881 }
1882 
1883 static inline void audit_get_stamp(struct audit_context *ctx,
1884 				   struct audit_stamp *stamp)
1885 {
1886 	if (!ctx || !auditsc_get_stamp(ctx, stamp)) {
1887 		ktime_get_coarse_real_ts64(&stamp->ctime);
1888 		stamp->serial = audit_serial();
1889 	}
1890 }
1891 
1892 /**
1893  * audit_log_start - obtain an audit buffer
1894  * @ctx: audit_context (may be NULL)
1895  * @gfp_mask: type of allocation
1896  * @type: audit message type
1897  *
1898  * Returns audit_buffer pointer on success or NULL on error.
1899  *
1900  * Obtain an audit buffer.  This routine does locking to obtain the
1901  * audit buffer, but then no locking is required for calls to
1902  * audit_log_*format.  If the task (ctx) is a task that is currently in a
1903  * syscall, then the syscall is marked as auditable and an audit record
1904  * will be written at syscall exit.  If there is no associated task, then
1905  * task context (ctx) should be NULL.
1906  */
1907 struct audit_buffer *audit_log_start(struct audit_context *ctx, gfp_t gfp_mask,
1908 				     int type)
1909 {
1910 	struct audit_buffer *ab;
1911 
1912 	if (audit_initialized != AUDIT_INITIALIZED)
1913 		return NULL;
1914 
1915 	if (unlikely(!audit_filter(type, AUDIT_FILTER_EXCLUDE)))
1916 		return NULL;
1917 
1918 	/* NOTE: don't ever fail/sleep on these two conditions:
1919 	 * 1. auditd generated record - since we need auditd to drain the
1920 	 *    queue; also, when we are checking for auditd, compare PIDs using
1921 	 *    task_tgid_vnr() since auditd_pid is set in audit_receive_msg()
1922 	 *    using a PID anchored in the caller's namespace
1923 	 * 2. generator holding the audit_cmd_mutex - we don't want to block
1924 	 *    while holding the mutex, although we do penalize the sender
1925 	 *    later in audit_receive() when it is safe to block
1926 	 */
1927 	if (!(auditd_test_task(current) || audit_ctl_owner_current())) {
1928 		long stime = audit_backlog_wait_time;
1929 
1930 		while (audit_backlog_limit &&
1931 		       (skb_queue_len(&audit_queue) > audit_backlog_limit)) {
1932 			/* wake kauditd to try and flush the queue */
1933 			wake_up_interruptible(&kauditd_wait);
1934 
1935 			/* sleep if we are allowed and we haven't exhausted our
1936 			 * backlog wait limit */
1937 			if (gfpflags_allow_blocking(gfp_mask) && (stime > 0)) {
1938 				long rtime = stime;
1939 
1940 				DECLARE_WAITQUEUE(wait, current);
1941 
1942 				add_wait_queue_exclusive(&audit_backlog_wait,
1943 							 &wait);
1944 				set_current_state(TASK_UNINTERRUPTIBLE);
1945 				stime = schedule_timeout(rtime);
1946 				atomic_add(rtime - stime, &audit_backlog_wait_time_actual);
1947 				remove_wait_queue(&audit_backlog_wait, &wait);
1948 			} else {
1949 				if (audit_rate_check() && printk_ratelimit())
1950 					pr_warn("audit_backlog=%d > audit_backlog_limit=%d\n",
1951 						skb_queue_len(&audit_queue),
1952 						audit_backlog_limit);
1953 				audit_log_lost("backlog limit exceeded");
1954 				return NULL;
1955 			}
1956 		}
1957 	}
1958 
1959 	ab = audit_buffer_alloc(ctx, gfp_mask, type);
1960 	if (!ab) {
1961 		audit_log_lost("out of memory in audit_log_start");
1962 		return NULL;
1963 	}
1964 
1965 	audit_get_stamp(ab->ctx, &ab->stamp);
1966 	/* cancel dummy context to enable supporting records */
1967 	if (ctx)
1968 		ctx->dummy = 0;
1969 	audit_log_format(ab, "audit(%llu.%03lu:%u): ",
1970 			 (unsigned long long)ab->stamp.ctime.tv_sec,
1971 			 ab->stamp.ctime.tv_nsec/1000000,
1972 			 ab->stamp.serial);
1973 
1974 	return ab;
1975 }
1976 
1977 /**
1978  * audit_expand - expand skb in the audit buffer
1979  * @ab: audit_buffer
1980  * @extra: space to add at tail of the skb
1981  *
1982  * Returns 0 (no space) on failed expansion, or available space if
1983  * successful.
1984  */
1985 static inline int audit_expand(struct audit_buffer *ab, int extra)
1986 {
1987 	struct sk_buff *skb = ab->skb;
1988 	int oldtail = skb_tailroom(skb);
1989 	int ret = pskb_expand_head(skb, 0, extra, ab->gfp_mask);
1990 	int newtail = skb_tailroom(skb);
1991 
1992 	if (ret < 0) {
1993 		audit_log_lost("out of memory in audit_expand");
1994 		return 0;
1995 	}
1996 
1997 	skb->truesize += newtail - oldtail;
1998 	return newtail;
1999 }
2000 
2001 /*
2002  * Format an audit message into the audit buffer.  If there isn't enough
2003  * room in the audit buffer, more room will be allocated and vsnprint
2004  * will be called a second time.  Currently, we assume that a printk
2005  * can't format message larger than 1024 bytes, so we don't either.
2006  */
2007 static __printf(2, 0)
2008 void audit_log_vformat(struct audit_buffer *ab, const char *fmt, va_list args)
2009 {
2010 	int len, avail;
2011 	struct sk_buff *skb;
2012 	va_list args2;
2013 
2014 	if (!ab)
2015 		return;
2016 
2017 	BUG_ON(!ab->skb);
2018 	skb = ab->skb;
2019 	avail = skb_tailroom(skb);
2020 	if (avail == 0) {
2021 		avail = audit_expand(ab, AUDIT_BUFSIZ);
2022 		if (!avail)
2023 			goto out;
2024 	}
2025 	va_copy(args2, args);
2026 	len = vsnprintf(skb_tail_pointer(skb), avail, fmt, args);
2027 	if (len >= avail) {
2028 		/* The printk buffer is 1024 bytes long, so if we get
2029 		 * here and AUDIT_BUFSIZ is at least 1024, then we can
2030 		 * log everything that printk could have logged. */
2031 		avail = audit_expand(ab,
2032 			max_t(unsigned, AUDIT_BUFSIZ, 1+len-avail));
2033 		if (!avail)
2034 			goto out_va_end;
2035 		len = vsnprintf(skb_tail_pointer(skb), avail, fmt, args2);
2036 	}
2037 	if (len > 0)
2038 		skb_put(skb, len);
2039 out_va_end:
2040 	va_end(args2);
2041 out:
2042 	return;
2043 }
2044 
2045 /**
2046  * audit_log_format - format a message into the audit buffer.
2047  * @ab: audit_buffer
2048  * @fmt: format string
2049  * @...: optional parameters matching @fmt string
2050  *
2051  * All the work is done in audit_log_vformat.
2052  */
2053 void audit_log_format(struct audit_buffer *ab, const char *fmt, ...)
2054 {
2055 	va_list args;
2056 
2057 	if (!ab)
2058 		return;
2059 	va_start(args, fmt);
2060 	audit_log_vformat(ab, fmt, args);
2061 	va_end(args);
2062 }
2063 
2064 /**
2065  * audit_log_n_hex - convert a buffer to hex and append it to the audit skb
2066  * @ab: the audit_buffer
2067  * @buf: buffer to convert to hex
2068  * @len: length of @buf to be converted
2069  *
2070  * No return value; failure to expand is silently ignored.
2071  *
2072  * This function will take the passed buf and convert it into a string of
2073  * ascii hex digits. The new string is placed onto the skb.
2074  */
2075 void audit_log_n_hex(struct audit_buffer *ab, const unsigned char *buf,
2076 		size_t len)
2077 {
2078 	int i, avail, new_len;
2079 	unsigned char *ptr;
2080 	struct sk_buff *skb;
2081 
2082 	if (!ab)
2083 		return;
2084 
2085 	BUG_ON(!ab->skb);
2086 	skb = ab->skb;
2087 	avail = skb_tailroom(skb);
2088 	new_len = len<<1;
2089 	if (new_len >= avail) {
2090 		/* Round the buffer request up to the next multiple */
2091 		new_len = AUDIT_BUFSIZ*(((new_len-avail)/AUDIT_BUFSIZ) + 1);
2092 		avail = audit_expand(ab, new_len);
2093 		if (!avail)
2094 			return;
2095 	}
2096 
2097 	ptr = skb_tail_pointer(skb);
2098 	for (i = 0; i < len; i++)
2099 		ptr = hex_byte_pack_upper(ptr, buf[i]);
2100 	*ptr = 0;
2101 	skb_put(skb, len << 1); /* new string is twice the old string */
2102 }
2103 
2104 /*
2105  * Format a string of no more than slen characters into the audit buffer,
2106  * enclosed in quote marks.
2107  */
2108 void audit_log_n_string(struct audit_buffer *ab, const char *string,
2109 			size_t slen)
2110 {
2111 	int avail, new_len;
2112 	unsigned char *ptr;
2113 	struct sk_buff *skb;
2114 
2115 	if (!ab)
2116 		return;
2117 
2118 	BUG_ON(!ab->skb);
2119 	skb = ab->skb;
2120 	avail = skb_tailroom(skb);
2121 	new_len = slen + 3;	/* enclosing quotes + null terminator */
2122 	if (new_len > avail) {
2123 		avail = audit_expand(ab, new_len);
2124 		if (!avail)
2125 			return;
2126 	}
2127 	ptr = skb_tail_pointer(skb);
2128 	*ptr++ = '"';
2129 	memcpy(ptr, string, slen);
2130 	ptr += slen;
2131 	*ptr++ = '"';
2132 	*ptr = 0;
2133 	skb_put(skb, slen + 2);	/* don't include null terminator */
2134 }
2135 
2136 /**
2137  * audit_string_contains_control - does a string need to be logged in hex
2138  * @string: string to be checked
2139  * @len: max length of the string to check
2140  */
2141 bool audit_string_contains_control(const char *string, size_t len)
2142 {
2143 	const unsigned char *p;
2144 	for (p = string; p < (const unsigned char *)string + len; p++) {
2145 		if (*p == '"' || *p < 0x21 || *p > 0x7e)
2146 			return true;
2147 	}
2148 	return false;
2149 }
2150 
2151 /**
2152  * audit_log_n_untrustedstring - log a string that may contain random characters
2153  * @ab: audit_buffer
2154  * @string: string to be logged
2155  * @len: length of string (not including trailing null)
2156  *
2157  * This code will escape a string that is passed to it if the string
2158  * contains a control character, unprintable character, double quote mark,
2159  * or a space. Unescaped strings will start and end with a double quote mark.
2160  * Strings that are escaped are printed in hex (2 digits per char).
2161  *
2162  * The caller specifies the number of characters in the string to log, which may
2163  * or may not be the entire string.
2164  */
2165 void audit_log_n_untrustedstring(struct audit_buffer *ab, const char *string,
2166 				 size_t len)
2167 {
2168 	if (audit_string_contains_control(string, len))
2169 		audit_log_n_hex(ab, string, len);
2170 	else
2171 		audit_log_n_string(ab, string, len);
2172 }
2173 
2174 /**
2175  * audit_log_untrustedstring - log a string that may contain random characters
2176  * @ab: audit_buffer
2177  * @string: string to be logged
2178  *
2179  * Same as audit_log_n_untrustedstring(), except that strlen is used to
2180  * determine string length.
2181  */
2182 void audit_log_untrustedstring(struct audit_buffer *ab, const char *string)
2183 {
2184 	audit_log_n_untrustedstring(ab, string, strlen(string));
2185 }
2186 
2187 /* This is a helper-function to print the escaped d_path */
2188 void audit_log_d_path(struct audit_buffer *ab, const char *prefix,
2189 		      const struct path *path)
2190 {
2191 	char *p, *pathname;
2192 
2193 	if (prefix)
2194 		audit_log_format(ab, "%s", prefix);
2195 
2196 	/* We will allow 11 spaces for ' (deleted)' to be appended */
2197 	pathname = kmalloc(PATH_MAX+11, ab->gfp_mask);
2198 	if (!pathname) {
2199 		audit_log_format(ab, "\"<no_memory>\"");
2200 		return;
2201 	}
2202 	p = d_path(path, pathname, PATH_MAX+11);
2203 	if (IS_ERR(p)) { /* Should never happen since we send PATH_MAX */
2204 		/* FIXME: can we save some information here? */
2205 		audit_log_format(ab, "\"<too_long>\"");
2206 	} else
2207 		audit_log_untrustedstring(ab, p);
2208 	kfree(pathname);
2209 }
2210 
2211 void audit_log_session_info(struct audit_buffer *ab)
2212 {
2213 	unsigned int sessionid = audit_get_sessionid(current);
2214 	uid_t auid = from_kuid(&init_user_ns, audit_get_loginuid(current));
2215 
2216 	audit_log_format(ab, "auid=%u ses=%u", auid, sessionid);
2217 }
2218 
2219 void audit_log_key(struct audit_buffer *ab, char *key)
2220 {
2221 	audit_log_format(ab, " key=");
2222 	if (key)
2223 		audit_log_untrustedstring(ab, key);
2224 	else
2225 		audit_log_format(ab, "(null)");
2226 }
2227 
2228 /**
2229  * audit_buffer_aux_new - Add an aux record buffer to the skb list
2230  * @ab: audit_buffer
2231  * @type: message type
2232  *
2233  * Aux records are allocated and added to the skb list of
2234  * the "main" record. The ab->skb is reset to point to the
2235  * aux record on its creation. When the aux record in complete
2236  * ab->skb has to be reset to point to the "main" record.
2237  * This allows the audit_log_ functions to be ignorant of
2238  * which kind of record it is logging to. It also avoids adding
2239  * special data for aux records.
2240  *
2241  * On success ab->skb will point to the new aux record.
2242  * Returns 0 on success, -ENOMEM should allocation fail.
2243  */
2244 static int audit_buffer_aux_new(struct audit_buffer *ab, int type)
2245 {
2246 	WARN_ON(ab->skb != skb_peek(&ab->skb_list));
2247 
2248 	ab->skb = nlmsg_new(AUDIT_BUFSIZ, ab->gfp_mask);
2249 	if (!ab->skb)
2250 		goto err;
2251 	if (!nlmsg_put(ab->skb, 0, 0, type, 0, 0))
2252 		goto err;
2253 	skb_queue_tail(&ab->skb_list, ab->skb);
2254 
2255 	audit_log_format(ab, "audit(%llu.%03lu:%u): ",
2256 			 (unsigned long long)ab->stamp.ctime.tv_sec,
2257 			 ab->stamp.ctime.tv_nsec/1000000,
2258 			 ab->stamp.serial);
2259 
2260 	return 0;
2261 
2262 err:
2263 	kfree_skb(ab->skb);
2264 	ab->skb = skb_peek(&ab->skb_list);
2265 	return -ENOMEM;
2266 }
2267 
2268 /**
2269  * audit_buffer_aux_end - Switch back to the "main" record from an aux record
2270  * @ab: audit_buffer
2271  *
2272  * Restores the "main" audit record to ab->skb.
2273  */
2274 static void audit_buffer_aux_end(struct audit_buffer *ab)
2275 {
2276 	ab->skb = skb_peek(&ab->skb_list);
2277 }
2278 
2279 /**
2280  * audit_log_subj_ctx - Add LSM subject information
2281  * @ab: audit_buffer
2282  * @prop: LSM subject properties.
2283  *
2284  * Add a subj= field and, if necessary, a AUDIT_MAC_TASK_CONTEXTS record.
2285  */
2286 int audit_log_subj_ctx(struct audit_buffer *ab, struct lsm_prop *prop)
2287 {
2288 	struct lsm_context ctx;
2289 	char *space = "";
2290 	int error;
2291 	int i;
2292 
2293 	security_current_getlsmprop_subj(prop);
2294 	if (!lsmprop_is_set(prop))
2295 		return 0;
2296 
2297 	if (audit_subj_secctx_cnt < 2) {
2298 		error = security_lsmprop_to_secctx(prop, &ctx, LSM_ID_UNDEF);
2299 		if (error < 0) {
2300 			if (error != -EINVAL)
2301 				goto error_path;
2302 			return 0;
2303 		}
2304 		audit_log_format(ab, " subj=%s", ctx.context);
2305 		security_release_secctx(&ctx);
2306 		return 0;
2307 	}
2308 	/* Multiple LSMs provide contexts. Include an aux record. */
2309 	audit_log_format(ab, " subj=?");
2310 	error = audit_buffer_aux_new(ab, AUDIT_MAC_TASK_CONTEXTS);
2311 	if (error)
2312 		goto error_path;
2313 
2314 	for (i = 0; i < audit_subj_secctx_cnt; i++) {
2315 		error = security_lsmprop_to_secctx(prop, &ctx,
2316 						   audit_subj_lsms[i]->id);
2317 		if (error < 0) {
2318 			/*
2319 			 * Don't print anything. An LSM like BPF could
2320 			 * claim to support contexts, but only do so under
2321 			 * certain conditions.
2322 			 */
2323 			if (error == -EOPNOTSUPP)
2324 				continue;
2325 			if (error != -EINVAL)
2326 				audit_panic("error in audit_log_subj_ctx");
2327 		} else {
2328 			audit_log_format(ab, "%ssubj_%s=%s", space,
2329 					 audit_subj_lsms[i]->name, ctx.context);
2330 			space = " ";
2331 			security_release_secctx(&ctx);
2332 		}
2333 	}
2334 	audit_buffer_aux_end(ab);
2335 	return 0;
2336 
2337 error_path:
2338 	audit_panic("error in audit_log_subj_ctx");
2339 	return error;
2340 }
2341 EXPORT_SYMBOL(audit_log_subj_ctx);
2342 
2343 int audit_log_task_context(struct audit_buffer *ab)
2344 {
2345 	struct lsm_prop prop;
2346 
2347 	security_current_getlsmprop_subj(&prop);
2348 	return audit_log_subj_ctx(ab, &prop);
2349 }
2350 EXPORT_SYMBOL(audit_log_task_context);
2351 
2352 int audit_log_obj_ctx(struct audit_buffer *ab, struct lsm_prop *prop)
2353 {
2354 	int i;
2355 	int rc;
2356 	int error = 0;
2357 	char *space = "";
2358 	struct lsm_context ctx;
2359 
2360 	if (audit_obj_secctx_cnt < 2) {
2361 		error = security_lsmprop_to_secctx(prop, &ctx, LSM_ID_UNDEF);
2362 		if (error < 0) {
2363 			if (error != -EINVAL)
2364 				goto error_path;
2365 			return error;
2366 		}
2367 		audit_log_format(ab, " obj=%s", ctx.context);
2368 		security_release_secctx(&ctx);
2369 		return 0;
2370 	}
2371 	audit_log_format(ab, " obj=?");
2372 	error = audit_buffer_aux_new(ab, AUDIT_MAC_OBJ_CONTEXTS);
2373 	if (error)
2374 		goto error_path;
2375 
2376 	for (i = 0; i < audit_obj_secctx_cnt; i++) {
2377 		rc = security_lsmprop_to_secctx(prop, &ctx,
2378 						audit_obj_lsms[i]->id);
2379 		if (rc < 0) {
2380 			audit_log_format(ab, "%sobj_%s=?", space,
2381 					 audit_obj_lsms[i]->name);
2382 			if (rc != -EINVAL)
2383 				audit_panic("error in audit_log_obj_ctx");
2384 			error = rc;
2385 		} else {
2386 			audit_log_format(ab, "%sobj_%s=%s", space,
2387 					 audit_obj_lsms[i]->name, ctx.context);
2388 			security_release_secctx(&ctx);
2389 		}
2390 		space = " ";
2391 	}
2392 
2393 	audit_buffer_aux_end(ab);
2394 	return error;
2395 
2396 error_path:
2397 	audit_panic("error in audit_log_obj_ctx");
2398 	return error;
2399 }
2400 
2401 void audit_log_d_path_exe(struct audit_buffer *ab,
2402 			  struct mm_struct *mm)
2403 {
2404 	struct file *exe_file;
2405 
2406 	if (!mm)
2407 		goto out_null;
2408 
2409 	exe_file = get_mm_exe_file(mm);
2410 	if (!exe_file)
2411 		goto out_null;
2412 
2413 	audit_log_d_path(ab, " exe=", &exe_file->f_path);
2414 	fput(exe_file);
2415 	return;
2416 out_null:
2417 	audit_log_format(ab, " exe=(null)");
2418 }
2419 
2420 struct tty_struct *audit_get_tty(void)
2421 {
2422 	struct tty_struct *tty = NULL;
2423 	unsigned long flags;
2424 
2425 	spin_lock_irqsave(&current->sighand->siglock, flags);
2426 	if (current->signal)
2427 		tty = tty_kref_get(current->signal->tty);
2428 	spin_unlock_irqrestore(&current->sighand->siglock, flags);
2429 	return tty;
2430 }
2431 
2432 void audit_put_tty(struct tty_struct *tty)
2433 {
2434 	tty_kref_put(tty);
2435 }
2436 
2437 void audit_log_task_info(struct audit_buffer *ab)
2438 {
2439 	const struct cred *cred;
2440 	char comm[sizeof(current->comm)];
2441 	struct tty_struct *tty;
2442 
2443 	if (!ab)
2444 		return;
2445 
2446 	cred = current_cred();
2447 	tty = audit_get_tty();
2448 	audit_log_format(ab,
2449 			 " ppid=%d pid=%d auid=%u uid=%u gid=%u"
2450 			 " euid=%u suid=%u fsuid=%u"
2451 			 " egid=%u sgid=%u fsgid=%u tty=%s ses=%u",
2452 			 task_ppid_nr(current),
2453 			 task_tgid_nr(current),
2454 			 from_kuid(&init_user_ns, audit_get_loginuid(current)),
2455 			 from_kuid(&init_user_ns, cred->uid),
2456 			 from_kgid(&init_user_ns, cred->gid),
2457 			 from_kuid(&init_user_ns, cred->euid),
2458 			 from_kuid(&init_user_ns, cred->suid),
2459 			 from_kuid(&init_user_ns, cred->fsuid),
2460 			 from_kgid(&init_user_ns, cred->egid),
2461 			 from_kgid(&init_user_ns, cred->sgid),
2462 			 from_kgid(&init_user_ns, cred->fsgid),
2463 			 tty ? tty_name(tty) : "(none)",
2464 			 audit_get_sessionid(current));
2465 	audit_put_tty(tty);
2466 	audit_log_format(ab, " comm=");
2467 	audit_log_untrustedstring(ab, get_task_comm(comm, current));
2468 	audit_log_d_path_exe(ab, current->mm);
2469 	audit_log_task_context(ab);
2470 }
2471 EXPORT_SYMBOL(audit_log_task_info);
2472 
2473 /**
2474  * audit_log_path_denied - report a path restriction denial
2475  * @type: audit message type (AUDIT_ANOM_LINK, AUDIT_ANOM_CREAT, etc)
2476  * @operation: specific operation name
2477  */
2478 void audit_log_path_denied(int type, const char *operation)
2479 {
2480 	struct audit_buffer *ab;
2481 
2482 	if (!audit_enabled)
2483 		return;
2484 
2485 	/* Generate log with subject, operation, outcome. */
2486 	ab = audit_log_start(audit_context(), GFP_KERNEL, type);
2487 	if (!ab)
2488 		return;
2489 	audit_log_format(ab, "op=%s", operation);
2490 	audit_log_task_info(ab);
2491 	audit_log_format(ab, " res=0");
2492 	audit_log_end(ab);
2493 }
2494 
2495 int audit_log_nf_skb(struct audit_buffer *ab,
2496 		     const struct sk_buff *skb, u8 nfproto)
2497 {
2498 	/* find the IP protocol in the case of NFPROTO_BRIDGE */
2499 	if (nfproto == NFPROTO_BRIDGE) {
2500 		switch (eth_hdr(skb)->h_proto) {
2501 		case htons(ETH_P_IP):
2502 			nfproto = NFPROTO_IPV4;
2503 			break;
2504 		case htons(ETH_P_IPV6):
2505 			nfproto = NFPROTO_IPV6;
2506 			break;
2507 		default:
2508 			goto unknown_proto;
2509 		}
2510 	}
2511 
2512 	switch (nfproto) {
2513 	case NFPROTO_IPV4: {
2514 		struct iphdr iph;
2515 		const struct iphdr *ih;
2516 
2517 		ih = skb_header_pointer(skb, skb_network_offset(skb),
2518 					sizeof(iph), &iph);
2519 		if (!ih)
2520 			return -ENOMEM;
2521 
2522 		switch (ih->protocol) {
2523 		case IPPROTO_TCP: {
2524 			struct tcphdr _tcph;
2525 			const struct tcphdr *th;
2526 
2527 			th = skb_header_pointer(skb, skb_transport_offset(skb),
2528 						sizeof(_tcph), &_tcph);
2529 			if (!th)
2530 				return -ENOMEM;
2531 
2532 			audit_log_format(ab, " saddr=%pI4 daddr=%pI4 proto=%hhu sport=%hu dport=%hu",
2533 					 &ih->saddr, &ih->daddr, ih->protocol,
2534 					 ntohs(th->source), ntohs(th->dest));
2535 			break;
2536 		}
2537 		case IPPROTO_UDP:
2538 		case IPPROTO_UDPLITE: {
2539 			struct udphdr _udph;
2540 			const struct udphdr *uh;
2541 
2542 			uh = skb_header_pointer(skb, skb_transport_offset(skb),
2543 						sizeof(_udph), &_udph);
2544 			if (!uh)
2545 				return -ENOMEM;
2546 
2547 			audit_log_format(ab, " saddr=%pI4 daddr=%pI4 proto=%hhu sport=%hu dport=%hu",
2548 					 &ih->saddr, &ih->daddr, ih->protocol,
2549 					 ntohs(uh->source), ntohs(uh->dest));
2550 			break;
2551 		}
2552 		case IPPROTO_SCTP: {
2553 			struct sctphdr _sctph;
2554 			const struct sctphdr *sh;
2555 
2556 			sh = skb_header_pointer(skb, skb_transport_offset(skb),
2557 						sizeof(_sctph), &_sctph);
2558 			if (!sh)
2559 				return -ENOMEM;
2560 
2561 			audit_log_format(ab, " saddr=%pI4 daddr=%pI4 proto=%hhu sport=%hu dport=%hu",
2562 					 &ih->saddr, &ih->daddr, ih->protocol,
2563 					 ntohs(sh->source), ntohs(sh->dest));
2564 			break;
2565 		}
2566 		default:
2567 			audit_log_format(ab, " saddr=%pI4 daddr=%pI4 proto=%hhu",
2568 					 &ih->saddr, &ih->daddr, ih->protocol);
2569 		}
2570 
2571 		break;
2572 	}
2573 	case NFPROTO_IPV6: {
2574 		struct ipv6hdr iph;
2575 		const struct ipv6hdr *ih;
2576 		u8 nexthdr;
2577 		__be16 frag_off;
2578 
2579 		ih = skb_header_pointer(skb, skb_network_offset(skb),
2580 					sizeof(iph), &iph);
2581 		if (!ih)
2582 			return -ENOMEM;
2583 
2584 		nexthdr = ih->nexthdr;
2585 		ipv6_skip_exthdr(skb, skb_network_offset(skb) + sizeof(iph),
2586 				 &nexthdr, &frag_off);
2587 
2588 		switch (nexthdr) {
2589 		case IPPROTO_TCP: {
2590 			struct tcphdr _tcph;
2591 			const struct tcphdr *th;
2592 
2593 			th = skb_header_pointer(skb, skb_transport_offset(skb),
2594 						sizeof(_tcph), &_tcph);
2595 			if (!th)
2596 				return -ENOMEM;
2597 
2598 			audit_log_format(ab, " saddr=%pI6c daddr=%pI6c proto=%hhu sport=%hu dport=%hu",
2599 					 &ih->saddr, &ih->daddr, nexthdr,
2600 					 ntohs(th->source), ntohs(th->dest));
2601 			break;
2602 		}
2603 		case IPPROTO_UDP:
2604 		case IPPROTO_UDPLITE: {
2605 			struct udphdr _udph;
2606 			const struct udphdr *uh;
2607 
2608 			uh = skb_header_pointer(skb, skb_transport_offset(skb),
2609 						sizeof(_udph), &_udph);
2610 			if (!uh)
2611 				return -ENOMEM;
2612 
2613 			audit_log_format(ab, " saddr=%pI6c daddr=%pI6c proto=%hhu sport=%hu dport=%hu",
2614 					 &ih->saddr, &ih->daddr, nexthdr,
2615 					 ntohs(uh->source), ntohs(uh->dest));
2616 			break;
2617 		}
2618 		case IPPROTO_SCTP: {
2619 			struct sctphdr _sctph;
2620 			const struct sctphdr *sh;
2621 
2622 			sh = skb_header_pointer(skb, skb_transport_offset(skb),
2623 						sizeof(_sctph), &_sctph);
2624 			if (!sh)
2625 				return -ENOMEM;
2626 
2627 			audit_log_format(ab, " saddr=%pI6c daddr=%pI6c proto=%hhu sport=%hu dport=%hu",
2628 					 &ih->saddr, &ih->daddr, nexthdr,
2629 					 ntohs(sh->source), ntohs(sh->dest));
2630 			break;
2631 		}
2632 		default:
2633 			audit_log_format(ab, " saddr=%pI6c daddr=%pI6c proto=%hhu",
2634 					 &ih->saddr, &ih->daddr, nexthdr);
2635 		}
2636 
2637 		break;
2638 	}
2639 	default:
2640 		goto unknown_proto;
2641 	}
2642 
2643 	return 0;
2644 
2645 unknown_proto:
2646 	audit_log_format(ab, " saddr=? daddr=? proto=?");
2647 	return -EPFNOSUPPORT;
2648 }
2649 EXPORT_SYMBOL(audit_log_nf_skb);
2650 
2651 /* global counter which is incremented every time something logs in */
2652 static atomic_t session_id = ATOMIC_INIT(0);
2653 
2654 static int audit_set_loginuid_perm(kuid_t loginuid)
2655 {
2656 	/* if we are unset, we don't need privs */
2657 	if (!audit_loginuid_set(current))
2658 		return 0;
2659 	/* if AUDIT_FEATURE_LOGINUID_IMMUTABLE means never ever allow a change*/
2660 	if (is_audit_feature_set(AUDIT_FEATURE_LOGINUID_IMMUTABLE))
2661 		return -EPERM;
2662 	/* it is set, you need permission */
2663 	if (!capable(CAP_AUDIT_CONTROL))
2664 		return -EPERM;
2665 	/* reject if this is not an unset and we don't allow that */
2666 	if (is_audit_feature_set(AUDIT_FEATURE_ONLY_UNSET_LOGINUID)
2667 				 && uid_valid(loginuid))
2668 		return -EPERM;
2669 	return 0;
2670 }
2671 
2672 static void audit_log_set_loginuid(kuid_t koldloginuid, kuid_t kloginuid,
2673 				   unsigned int oldsessionid,
2674 				   unsigned int sessionid, int rc)
2675 {
2676 	struct audit_buffer *ab;
2677 	uid_t uid, oldloginuid, loginuid;
2678 	struct tty_struct *tty;
2679 
2680 	if (!audit_enabled)
2681 		return;
2682 
2683 	ab = audit_log_start(audit_context(), GFP_KERNEL, AUDIT_LOGIN);
2684 	if (!ab)
2685 		return;
2686 
2687 	uid = from_kuid(&init_user_ns, task_uid(current));
2688 	oldloginuid = from_kuid(&init_user_ns, koldloginuid);
2689 	loginuid = from_kuid(&init_user_ns, kloginuid);
2690 	tty = audit_get_tty();
2691 
2692 	audit_log_format(ab, "pid=%d uid=%u", task_tgid_nr(current), uid);
2693 	audit_log_task_context(ab);
2694 	audit_log_format(ab, " old-auid=%u auid=%u tty=%s old-ses=%u ses=%u res=%d",
2695 			 oldloginuid, loginuid, tty ? tty_name(tty) : "(none)",
2696 			 oldsessionid, sessionid, !rc);
2697 	audit_put_tty(tty);
2698 	audit_log_end(ab);
2699 }
2700 
2701 /**
2702  * audit_set_loginuid - set current task's loginuid
2703  * @loginuid: loginuid value
2704  *
2705  * Returns 0.
2706  *
2707  * Called (set) from fs/proc/base.c::proc_loginuid_write().
2708  */
2709 int audit_set_loginuid(kuid_t loginuid)
2710 {
2711 	unsigned int oldsessionid, sessionid = AUDIT_SID_UNSET;
2712 	kuid_t oldloginuid;
2713 	int rc;
2714 
2715 	oldloginuid = audit_get_loginuid(current);
2716 	oldsessionid = audit_get_sessionid(current);
2717 
2718 	rc = audit_set_loginuid_perm(loginuid);
2719 	if (rc)
2720 		goto out;
2721 
2722 	/* are we setting or clearing? */
2723 	if (uid_valid(loginuid)) {
2724 		sessionid = (unsigned int)atomic_inc_return(&session_id);
2725 		if (unlikely(sessionid == AUDIT_SID_UNSET))
2726 			sessionid = (unsigned int)atomic_inc_return(&session_id);
2727 	}
2728 
2729 	current->sessionid = sessionid;
2730 	current->loginuid = loginuid;
2731 out:
2732 	audit_log_set_loginuid(oldloginuid, loginuid, oldsessionid, sessionid, rc);
2733 	return rc;
2734 }
2735 
2736 /**
2737  * audit_signal_info - record signal info for shutting down audit subsystem
2738  * @sig: signal value
2739  * @t: task being signaled
2740  *
2741  * If the audit subsystem is being terminated, record the task (pid)
2742  * and uid that is doing that.
2743  */
2744 int audit_signal_info(int sig, struct task_struct *t)
2745 {
2746 	kuid_t uid = current_uid(), auid;
2747 
2748 	if (auditd_test_task(t) &&
2749 	    (sig == SIGTERM || sig == SIGHUP ||
2750 	     sig == SIGUSR1 || sig == SIGUSR2)) {
2751 		audit_sig_pid = task_tgid_nr(current);
2752 		auid = audit_get_loginuid(current);
2753 		if (uid_valid(auid))
2754 			audit_sig_uid = auid;
2755 		else
2756 			audit_sig_uid = uid;
2757 		security_current_getlsmprop_subj(&audit_sig_lsm);
2758 	}
2759 
2760 	return audit_signal_info_syscall(t);
2761 }
2762 
2763 /**
2764  * __audit_log_end - enqueue one audit record
2765  * @skb: the buffer to send
2766  */
2767 static void __audit_log_end(struct sk_buff *skb)
2768 {
2769 	struct nlmsghdr *nlh;
2770 
2771 	if (audit_rate_check()) {
2772 		/* setup the netlink header, see the comments in
2773 		 * kauditd_send_multicast_skb() for length quirks */
2774 		nlh = nlmsg_hdr(skb);
2775 		nlh->nlmsg_len = skb->len - NLMSG_HDRLEN;
2776 
2777 		/* queue the netlink packet */
2778 		skb_queue_tail(&audit_queue, skb);
2779 	} else {
2780 		audit_log_lost("rate limit exceeded");
2781 		kfree_skb(skb);
2782 	}
2783 }
2784 
2785 /**
2786  * audit_log_end - end one audit record
2787  * @ab: the audit_buffer
2788  *
2789  * We can not do a netlink send inside an irq context because it blocks (last
2790  * arg, flags, is not set to MSG_DONTWAIT), so the audit buffer is placed on a
2791  * queue and a kthread is scheduled to remove them from the queue outside the
2792  * irq context.  May be called in any context.
2793  */
2794 void audit_log_end(struct audit_buffer *ab)
2795 {
2796 	struct sk_buff *skb;
2797 
2798 	if (!ab)
2799 		return;
2800 
2801 	while ((skb = skb_dequeue(&ab->skb_list)))
2802 		__audit_log_end(skb);
2803 
2804 	/* poke the kauditd thread */
2805 	wake_up_interruptible(&kauditd_wait);
2806 
2807 	audit_buffer_free(ab);
2808 }
2809 
2810 /**
2811  * audit_log - Log an audit record
2812  * @ctx: audit context
2813  * @gfp_mask: type of allocation
2814  * @type: audit message type
2815  * @fmt: format string to use
2816  * @...: variable parameters matching the format string
2817  *
2818  * This is a convenience function that calls audit_log_start,
2819  * audit_log_vformat, and audit_log_end.  It may be called
2820  * in any context.
2821  */
2822 void audit_log(struct audit_context *ctx, gfp_t gfp_mask, int type,
2823 	       const char *fmt, ...)
2824 {
2825 	struct audit_buffer *ab;
2826 	va_list args;
2827 
2828 	ab = audit_log_start(ctx, gfp_mask, type);
2829 	if (ab) {
2830 		va_start(args, fmt);
2831 		audit_log_vformat(ab, fmt, args);
2832 		va_end(args);
2833 		audit_log_end(ab);
2834 	}
2835 }
2836 
2837 EXPORT_SYMBOL(audit_log_start);
2838 EXPORT_SYMBOL(audit_log_end);
2839 EXPORT_SYMBOL(audit_log_format);
2840 EXPORT_SYMBOL(audit_log);
2841