af_unix: Add sockaddr length checks before accessing sa_family in bind and connect...
[linux/fpc-iii.git] / kernel / audit.c
blobdd2c339c8eb987b6589eccdb432950acc49a2bb4
1 /* audit.c -- Auditing support
2 * Gateway between the kernel (e.g., selinux) and the user-space audit daemon.
3 * System-call specific features have moved to auditsc.c
5 * Copyright 2003-2007 Red Hat Inc., Durham, North Carolina.
6 * All Rights Reserved.
8 * This program is free software; you can redistribute it and/or modify
9 * it under the terms of the GNU General Public License as published by
10 * the Free Software Foundation; either version 2 of the License, or
11 * (at your option) any later version.
13 * This program is distributed in the hope that it will be useful,
14 * but WITHOUT ANY WARRANTY; without even the implied warranty of
15 * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
16 * GNU General Public License for more details.
18 * You should have received a copy of the GNU General Public License
19 * along with this program; if not, write to the Free Software
20 * Foundation, Inc., 59 Temple Place, Suite 330, Boston, MA 02111-1307 USA
22 * Written by Rickard E. (Rik) Faith <faith@redhat.com>
24 * Goals: 1) Integrate fully with Security Modules.
25 * 2) Minimal run-time overhead:
26 * a) Minimal when syscall auditing is disabled (audit_enable=0).
27 * b) Small when syscall auditing is enabled and no audit record
28 * is generated (defer as much work as possible to record
29 * generation time):
30 * i) context is allocated,
31 * ii) names from getname are stored without a copy, and
32 * iii) inode information stored from path_lookup.
33 * 3) Ability to disable syscall auditing at boot time (audit=0).
34 * 4) Usable by other parts of the kernel (if audit_log* is called,
35 * then a syscall record will be generated automatically for the
36 * current syscall).
37 * 5) Netlink interface to user-space.
38 * 6) Support low-overhead kernel-based filtering to minimize the
39 * information that must be passed to user-space.
41 * Example user-space utilities: http://people.redhat.com/sgrubb/audit/
44 #define pr_fmt(fmt) KBUILD_MODNAME ": " fmt
46 #include <linux/file.h>
47 #include <linux/init.h>
48 #include <linux/types.h>
49 #include <linux/atomic.h>
50 #include <linux/mm.h>
51 #include <linux/export.h>
52 #include <linux/slab.h>
53 #include <linux/err.h>
54 #include <linux/kthread.h>
55 #include <linux/kernel.h>
56 #include <linux/syscalls.h>
57 #include <linux/spinlock.h>
58 #include <linux/rcupdate.h>
59 #include <linux/mutex.h>
60 #include <linux/gfp.h>
62 #include <linux/audit.h>
64 #include <net/sock.h>
65 #include <net/netlink.h>
66 #include <linux/skbuff.h>
67 #ifdef CONFIG_SECURITY
68 #include <linux/security.h>
69 #endif
70 #include <linux/freezer.h>
71 #include <linux/pid_namespace.h>
72 #include <net/netns/generic.h>
74 #include "audit.h"
76 /* No auditing will take place until audit_initialized == AUDIT_INITIALIZED.
77 * (Initialization happens after skb_init is called.) */
78 #define AUDIT_DISABLED -1
79 #define AUDIT_UNINITIALIZED 0
80 #define AUDIT_INITIALIZED 1
81 static int audit_initialized;
83 #define AUDIT_OFF 0
84 #define AUDIT_ON 1
85 #define AUDIT_LOCKED 2
86 u32 audit_enabled;
87 u32 audit_ever_enabled;
89 EXPORT_SYMBOL_GPL(audit_enabled);
91 /* Default state when kernel boots without any parameters. */
92 static u32 audit_default;
94 /* If auditing cannot proceed, audit_failure selects what happens. */
95 static u32 audit_failure = AUDIT_FAIL_PRINTK;
97 /* private audit network namespace index */
98 static unsigned int audit_net_id;
101 * struct audit_net - audit private network namespace data
102 * @sk: communication socket
104 struct audit_net {
105 struct sock *sk;
109 * struct auditd_connection - kernel/auditd connection state
110 * @pid: auditd PID
111 * @portid: netlink portid
112 * @net: the associated network namespace
113 * @rcu: RCU head
115 * Description:
116 * This struct is RCU protected; you must either hold the RCU lock for reading
117 * or the associated spinlock for writing.
119 static struct auditd_connection {
120 int pid;
121 u32 portid;
122 struct net *net;
123 struct rcu_head rcu;
124 } *auditd_conn = NULL;
125 static DEFINE_SPINLOCK(auditd_conn_lock);
127 /* If audit_rate_limit is non-zero, limit the rate of sending audit records
128 * to that number per second. This prevents DoS attacks, but results in
129 * audit records being dropped. */
130 static u32 audit_rate_limit;
132 /* Number of outstanding audit_buffers allowed.
133 * When set to zero, this means unlimited. */
134 static u32 audit_backlog_limit = 64;
135 #define AUDIT_BACKLOG_WAIT_TIME (60 * HZ)
136 static u32 audit_backlog_wait_time = AUDIT_BACKLOG_WAIT_TIME;
138 /* The identity of the user shutting down the audit system. */
139 kuid_t audit_sig_uid = INVALID_UID;
140 pid_t audit_sig_pid = -1;
141 u32 audit_sig_sid = 0;
143 /* Records can be lost in several ways:
144 0) [suppressed in audit_alloc]
145 1) out of memory in audit_log_start [kmalloc of struct audit_buffer]
146 2) out of memory in audit_log_move [alloc_skb]
147 3) suppressed due to audit_rate_limit
148 4) suppressed due to audit_backlog_limit
150 static atomic_t audit_lost = ATOMIC_INIT(0);
152 /* Hash for inode-based rules */
153 struct list_head audit_inode_hash[AUDIT_INODE_BUCKETS];
155 /* The audit_freelist is a list of pre-allocated audit buffers (if more
156 * than AUDIT_MAXFREE are in use, the audit buffer is freed instead of
157 * being placed on the freelist). */
158 static DEFINE_SPINLOCK(audit_freelist_lock);
159 static int audit_freelist_count;
160 static LIST_HEAD(audit_freelist);
162 /* queue msgs to send via kauditd_task */
163 static struct sk_buff_head audit_queue;
164 /* queue msgs due to temporary unicast send problems */
165 static struct sk_buff_head audit_retry_queue;
166 /* queue msgs waiting for new auditd connection */
167 static struct sk_buff_head audit_hold_queue;
169 /* queue servicing thread */
170 static struct task_struct *kauditd_task;
171 static DECLARE_WAIT_QUEUE_HEAD(kauditd_wait);
173 /* waitqueue for callers who are blocked on the audit backlog */
174 static DECLARE_WAIT_QUEUE_HEAD(audit_backlog_wait);
176 static struct audit_features af = {.vers = AUDIT_FEATURE_VERSION,
177 .mask = -1,
178 .features = 0,
179 .lock = 0,};
181 static char *audit_feature_names[2] = {
182 "only_unset_loginuid",
183 "loginuid_immutable",
187 /* Serialize requests from userspace. */
188 DEFINE_MUTEX(audit_cmd_mutex);
190 /* AUDIT_BUFSIZ is the size of the temporary buffer used for formatting
191 * audit records. Since printk uses a 1024 byte buffer, this buffer
192 * should be at least that large. */
193 #define AUDIT_BUFSIZ 1024
195 /* AUDIT_MAXFREE is the number of empty audit_buffers we keep on the
196 * audit_freelist. Doing so eliminates many kmalloc/kfree calls. */
197 #define AUDIT_MAXFREE (2*NR_CPUS)
199 /* The audit_buffer is used when formatting an audit record. The caller
200 * locks briefly to get the record off the freelist or to allocate the
201 * buffer, and locks briefly to send the buffer to the netlink layer or
202 * to place it on a transmit queue. Multiple audit_buffers can be in
203 * use simultaneously. */
204 struct audit_buffer {
205 struct list_head list;
206 struct sk_buff *skb; /* formatted skb ready to send */
207 struct audit_context *ctx; /* NULL or associated context */
208 gfp_t gfp_mask;
211 struct audit_reply {
212 __u32 portid;
213 struct net *net;
214 struct sk_buff *skb;
218 * auditd_test_task - Check to see if a given task is an audit daemon
219 * @task: the task to check
221 * Description:
222 * Return 1 if the task is a registered audit daemon, 0 otherwise.
224 int auditd_test_task(const struct task_struct *task)
226 int rc;
227 struct auditd_connection *ac;
229 rcu_read_lock();
230 ac = rcu_dereference(auditd_conn);
231 rc = (ac && ac->pid == task->tgid ? 1 : 0);
232 rcu_read_unlock();
234 return rc;
238 * auditd_pid_vnr - Return the auditd PID relative to the namespace
240 * Description:
241 * Returns the PID in relation to the namespace, 0 on failure.
243 static pid_t auditd_pid_vnr(void)
245 pid_t pid;
246 const struct auditd_connection *ac;
248 rcu_read_lock();
249 ac = rcu_dereference(auditd_conn);
250 if (!ac)
251 pid = 0;
252 else
253 pid = ac->pid;
254 rcu_read_unlock();
256 return pid;
260 * audit_get_sk - Return the audit socket for the given network namespace
261 * @net: the destination network namespace
263 * Description:
264 * Returns the sock pointer if valid, NULL otherwise. The caller must ensure
265 * that a reference is held for the network namespace while the sock is in use.
267 static struct sock *audit_get_sk(const struct net *net)
269 struct audit_net *aunet;
271 if (!net)
272 return NULL;
274 aunet = net_generic(net, audit_net_id);
275 return aunet->sk;
278 static void audit_set_portid(struct audit_buffer *ab, __u32 portid)
280 if (ab) {
281 struct nlmsghdr *nlh = nlmsg_hdr(ab->skb);
282 nlh->nlmsg_pid = portid;
286 void audit_panic(const char *message)
288 switch (audit_failure) {
289 case AUDIT_FAIL_SILENT:
290 break;
291 case AUDIT_FAIL_PRINTK:
292 if (printk_ratelimit())
293 pr_err("%s\n", message);
294 break;
295 case AUDIT_FAIL_PANIC:
296 panic("audit: %s\n", message);
297 break;
301 static inline int audit_rate_check(void)
303 static unsigned long last_check = 0;
304 static int messages = 0;
305 static DEFINE_SPINLOCK(lock);
306 unsigned long flags;
307 unsigned long now;
308 unsigned long elapsed;
309 int retval = 0;
311 if (!audit_rate_limit) return 1;
313 spin_lock_irqsave(&lock, flags);
314 if (++messages < audit_rate_limit) {
315 retval = 1;
316 } else {
317 now = jiffies;
318 elapsed = now - last_check;
319 if (elapsed > HZ) {
320 last_check = now;
321 messages = 0;
322 retval = 1;
325 spin_unlock_irqrestore(&lock, flags);
327 return retval;
331 * audit_log_lost - conditionally log lost audit message event
332 * @message: the message stating reason for lost audit message
334 * Emit at least 1 message per second, even if audit_rate_check is
335 * throttling.
336 * Always increment the lost messages counter.
338 void audit_log_lost(const char *message)
340 static unsigned long last_msg = 0;
341 static DEFINE_SPINLOCK(lock);
342 unsigned long flags;
343 unsigned long now;
344 int print;
346 atomic_inc(&audit_lost);
348 print = (audit_failure == AUDIT_FAIL_PANIC || !audit_rate_limit);
350 if (!print) {
351 spin_lock_irqsave(&lock, flags);
352 now = jiffies;
353 if (now - last_msg > HZ) {
354 print = 1;
355 last_msg = now;
357 spin_unlock_irqrestore(&lock, flags);
360 if (print) {
361 if (printk_ratelimit())
362 pr_warn("audit_lost=%u audit_rate_limit=%u audit_backlog_limit=%u\n",
363 atomic_read(&audit_lost),
364 audit_rate_limit,
365 audit_backlog_limit);
366 audit_panic(message);
370 static int audit_log_config_change(char *function_name, u32 new, u32 old,
371 int allow_changes)
373 struct audit_buffer *ab;
374 int rc = 0;
376 ab = audit_log_start(NULL, GFP_KERNEL, AUDIT_CONFIG_CHANGE);
377 if (unlikely(!ab))
378 return rc;
379 audit_log_format(ab, "%s=%u old=%u", function_name, new, old);
380 audit_log_session_info(ab);
381 rc = audit_log_task_context(ab);
382 if (rc)
383 allow_changes = 0; /* Something weird, deny request */
384 audit_log_format(ab, " res=%d", allow_changes);
385 audit_log_end(ab);
386 return rc;
389 static int audit_do_config_change(char *function_name, u32 *to_change, u32 new)
391 int allow_changes, rc = 0;
392 u32 old = *to_change;
394 /* check if we are locked */
395 if (audit_enabled == AUDIT_LOCKED)
396 allow_changes = 0;
397 else
398 allow_changes = 1;
400 if (audit_enabled != AUDIT_OFF) {
401 rc = audit_log_config_change(function_name, new, old, allow_changes);
402 if (rc)
403 allow_changes = 0;
406 /* If we are allowed, make the change */
407 if (allow_changes == 1)
408 *to_change = new;
409 /* Not allowed, update reason */
410 else if (rc == 0)
411 rc = -EPERM;
412 return rc;
415 static int audit_set_rate_limit(u32 limit)
417 return audit_do_config_change("audit_rate_limit", &audit_rate_limit, limit);
420 static int audit_set_backlog_limit(u32 limit)
422 return audit_do_config_change("audit_backlog_limit", &audit_backlog_limit, limit);
425 static int audit_set_backlog_wait_time(u32 timeout)
427 return audit_do_config_change("audit_backlog_wait_time",
428 &audit_backlog_wait_time, timeout);
431 static int audit_set_enabled(u32 state)
433 int rc;
434 if (state > AUDIT_LOCKED)
435 return -EINVAL;
437 rc = audit_do_config_change("audit_enabled", &audit_enabled, state);
438 if (!rc)
439 audit_ever_enabled |= !!state;
441 return rc;
444 static int audit_set_failure(u32 state)
446 if (state != AUDIT_FAIL_SILENT
447 && state != AUDIT_FAIL_PRINTK
448 && state != AUDIT_FAIL_PANIC)
449 return -EINVAL;
451 return audit_do_config_change("audit_failure", &audit_failure, state);
455 * auditd_conn_free - RCU helper to release an auditd connection struct
456 * @rcu: RCU head
458 * Description:
459 * Drop any references inside the auditd connection tracking struct and free
460 * the memory.
462 static void auditd_conn_free(struct rcu_head *rcu)
464 struct auditd_connection *ac;
466 ac = container_of(rcu, struct auditd_connection, rcu);
467 put_net(ac->net);
468 kfree(ac);
472 * auditd_set - Set/Reset the auditd connection state
473 * @pid: auditd PID
474 * @portid: auditd netlink portid
475 * @net: auditd network namespace pointer
477 * Description:
478 * This function will obtain and drop network namespace references as
479 * necessary. Returns zero on success, negative values on failure.
481 static int auditd_set(int pid, u32 portid, struct net *net)
483 unsigned long flags;
484 struct auditd_connection *ac_old, *ac_new;
486 if (!pid || !net)
487 return -EINVAL;
489 ac_new = kzalloc(sizeof(*ac_new), GFP_KERNEL);
490 if (!ac_new)
491 return -ENOMEM;
492 ac_new->pid = pid;
493 ac_new->portid = portid;
494 ac_new->net = get_net(net);
496 spin_lock_irqsave(&auditd_conn_lock, flags);
497 ac_old = rcu_dereference_protected(auditd_conn,
498 lockdep_is_held(&auditd_conn_lock));
499 rcu_assign_pointer(auditd_conn, ac_new);
500 spin_unlock_irqrestore(&auditd_conn_lock, flags);
502 if (ac_old)
503 call_rcu(&ac_old->rcu, auditd_conn_free);
505 return 0;
509 * kauditd_print_skb - Print the audit record to the ring buffer
510 * @skb: audit record
512 * Whatever the reason, this packet may not make it to the auditd connection
513 * so write it via printk so the information isn't completely lost.
515 static void kauditd_printk_skb(struct sk_buff *skb)
517 struct nlmsghdr *nlh = nlmsg_hdr(skb);
518 char *data = nlmsg_data(nlh);
520 if (nlh->nlmsg_type != AUDIT_EOE && printk_ratelimit())
521 pr_notice("type=%d %s\n", nlh->nlmsg_type, data);
525 * kauditd_rehold_skb - Handle a audit record send failure in the hold queue
526 * @skb: audit record
528 * Description:
529 * This should only be used by the kauditd_thread when it fails to flush the
530 * hold queue.
532 static void kauditd_rehold_skb(struct sk_buff *skb)
534 /* put the record back in the queue at the same place */
535 skb_queue_head(&audit_hold_queue, skb);
539 * kauditd_hold_skb - Queue an audit record, waiting for auditd
540 * @skb: audit record
542 * Description:
543 * Queue the audit record, waiting for an instance of auditd. When this
544 * function is called we haven't given up yet on sending the record, but things
545 * are not looking good. The first thing we want to do is try to write the
546 * record via printk and then see if we want to try and hold on to the record
547 * and queue it, if we have room. If we want to hold on to the record, but we
548 * don't have room, record a record lost message.
550 static void kauditd_hold_skb(struct sk_buff *skb)
552 /* at this point it is uncertain if we will ever send this to auditd so
553 * try to send the message via printk before we go any further */
554 kauditd_printk_skb(skb);
556 /* can we just silently drop the message? */
557 if (!audit_default) {
558 kfree_skb(skb);
559 return;
562 /* if we have room, queue the message */
563 if (!audit_backlog_limit ||
564 skb_queue_len(&audit_hold_queue) < audit_backlog_limit) {
565 skb_queue_tail(&audit_hold_queue, skb);
566 return;
569 /* we have no other options - drop the message */
570 audit_log_lost("kauditd hold queue overflow");
571 kfree_skb(skb);
575 * kauditd_retry_skb - Queue an audit record, attempt to send again to auditd
576 * @skb: audit record
578 * Description:
579 * Not as serious as kauditd_hold_skb() as we still have a connected auditd,
580 * but for some reason we are having problems sending it audit records so
581 * queue the given record and attempt to resend.
583 static void kauditd_retry_skb(struct sk_buff *skb)
585 /* NOTE: because records should only live in the retry queue for a
586 * short period of time, before either being sent or moved to the hold
587 * queue, we don't currently enforce a limit on this queue */
588 skb_queue_tail(&audit_retry_queue, skb);
592 * auditd_reset - Disconnect the auditd connection
594 * Description:
595 * Break the auditd/kauditd connection and move all the queued records into the
596 * hold queue in case auditd reconnects.
598 static void auditd_reset(void)
600 unsigned long flags;
601 struct sk_buff *skb;
602 struct auditd_connection *ac_old;
604 /* if it isn't already broken, break the connection */
605 spin_lock_irqsave(&auditd_conn_lock, flags);
606 ac_old = rcu_dereference_protected(auditd_conn,
607 lockdep_is_held(&auditd_conn_lock));
608 rcu_assign_pointer(auditd_conn, NULL);
609 spin_unlock_irqrestore(&auditd_conn_lock, flags);
611 if (ac_old)
612 call_rcu(&ac_old->rcu, auditd_conn_free);
614 /* flush all of the main and retry queues to the hold queue */
615 while ((skb = skb_dequeue(&audit_retry_queue)))
616 kauditd_hold_skb(skb);
617 while ((skb = skb_dequeue(&audit_queue)))
618 kauditd_hold_skb(skb);
622 * auditd_send_unicast_skb - Send a record via unicast to auditd
623 * @skb: audit record
625 * Description:
626 * Send a skb to the audit daemon, returns positive/zero values on success and
627 * negative values on failure; in all cases the skb will be consumed by this
628 * function. If the send results in -ECONNREFUSED the connection with auditd
629 * will be reset. This function may sleep so callers should not hold any locks
630 * where this would cause a problem.
632 static int auditd_send_unicast_skb(struct sk_buff *skb)
634 int rc;
635 u32 portid;
636 struct net *net;
637 struct sock *sk;
638 struct auditd_connection *ac;
640 /* NOTE: we can't call netlink_unicast while in the RCU section so
641 * take a reference to the network namespace and grab local
642 * copies of the namespace, the sock, and the portid; the
643 * namespace and sock aren't going to go away while we hold a
644 * reference and if the portid does become invalid after the RCU
645 * section netlink_unicast() should safely return an error */
647 rcu_read_lock();
648 ac = rcu_dereference(auditd_conn);
649 if (!ac) {
650 rcu_read_unlock();
651 rc = -ECONNREFUSED;
652 goto err;
654 net = get_net(ac->net);
655 sk = audit_get_sk(net);
656 portid = ac->portid;
657 rcu_read_unlock();
659 rc = netlink_unicast(sk, skb, portid, 0);
660 put_net(net);
661 if (rc < 0)
662 goto err;
664 return rc;
666 err:
667 if (rc == -ECONNREFUSED)
668 auditd_reset();
669 return rc;
673 * kauditd_send_queue - Helper for kauditd_thread to flush skb queues
674 * @sk: the sending sock
675 * @portid: the netlink destination
676 * @queue: the skb queue to process
677 * @retry_limit: limit on number of netlink unicast failures
678 * @skb_hook: per-skb hook for additional processing
679 * @err_hook: hook called if the skb fails the netlink unicast send
681 * Description:
682 * Run through the given queue and attempt to send the audit records to auditd,
683 * returns zero on success, negative values on failure. It is up to the caller
684 * to ensure that the @sk is valid for the duration of this function.
687 static int kauditd_send_queue(struct sock *sk, u32 portid,
688 struct sk_buff_head *queue,
689 unsigned int retry_limit,
690 void (*skb_hook)(struct sk_buff *skb),
691 void (*err_hook)(struct sk_buff *skb))
693 int rc = 0;
694 struct sk_buff *skb;
695 static unsigned int failed = 0;
697 /* NOTE: kauditd_thread takes care of all our locking, we just use
698 * the netlink info passed to us (e.g. sk and portid) */
700 while ((skb = skb_dequeue(queue))) {
701 /* call the skb_hook for each skb we touch */
702 if (skb_hook)
703 (*skb_hook)(skb);
705 /* can we send to anyone via unicast? */
706 if (!sk) {
707 if (err_hook)
708 (*err_hook)(skb);
709 continue;
712 /* grab an extra skb reference in case of error */
713 skb_get(skb);
714 rc = netlink_unicast(sk, skb, portid, 0);
715 if (rc < 0) {
716 /* fatal failure for our queue flush attempt? */
717 if (++failed >= retry_limit ||
718 rc == -ECONNREFUSED || rc == -EPERM) {
719 /* yes - error processing for the queue */
720 sk = NULL;
721 if (err_hook)
722 (*err_hook)(skb);
723 if (!skb_hook)
724 goto out;
725 /* keep processing with the skb_hook */
726 continue;
727 } else
728 /* no - requeue to preserve ordering */
729 skb_queue_head(queue, skb);
730 } else {
731 /* it worked - drop the extra reference and continue */
732 consume_skb(skb);
733 failed = 0;
737 out:
738 return (rc >= 0 ? 0 : rc);
742 * kauditd_send_multicast_skb - Send a record to any multicast listeners
743 * @skb: audit record
745 * Description:
746 * Write a multicast message to anyone listening in the initial network
747 * namespace. This function doesn't consume an skb as might be expected since
748 * it has to copy it anyways.
750 static void kauditd_send_multicast_skb(struct sk_buff *skb)
752 struct sk_buff *copy;
753 struct sock *sock = audit_get_sk(&init_net);
754 struct nlmsghdr *nlh;
756 /* NOTE: we are not taking an additional reference for init_net since
757 * we don't have to worry about it going away */
759 if (!netlink_has_listeners(sock, AUDIT_NLGRP_READLOG))
760 return;
763 * The seemingly wasteful skb_copy() rather than bumping the refcount
764 * using skb_get() is necessary because non-standard mods are made to
765 * the skb by the original kaudit unicast socket send routine. The
766 * existing auditd daemon assumes this breakage. Fixing this would
767 * require co-ordinating a change in the established protocol between
768 * the kaudit kernel subsystem and the auditd userspace code. There is
769 * no reason for new multicast clients to continue with this
770 * non-compliance.
772 copy = skb_copy(skb, GFP_KERNEL);
773 if (!copy)
774 return;
775 nlh = nlmsg_hdr(copy);
776 nlh->nlmsg_len = skb->len;
778 nlmsg_multicast(sock, copy, 0, AUDIT_NLGRP_READLOG, GFP_KERNEL);
782 * kauditd_thread - Worker thread to send audit records to userspace
783 * @dummy: unused
785 static int kauditd_thread(void *dummy)
787 int rc;
788 u32 portid = 0;
789 struct net *net = NULL;
790 struct sock *sk = NULL;
791 struct auditd_connection *ac;
793 #define UNICAST_RETRIES 5
795 set_freezable();
796 while (!kthread_should_stop()) {
797 /* NOTE: see the lock comments in auditd_send_unicast_skb() */
798 rcu_read_lock();
799 ac = rcu_dereference(auditd_conn);
800 if (!ac) {
801 rcu_read_unlock();
802 goto main_queue;
804 net = get_net(ac->net);
805 sk = audit_get_sk(net);
806 portid = ac->portid;
807 rcu_read_unlock();
809 /* attempt to flush the hold queue */
810 rc = kauditd_send_queue(sk, portid,
811 &audit_hold_queue, UNICAST_RETRIES,
812 NULL, kauditd_rehold_skb);
813 if (rc < 0) {
814 sk = NULL;
815 auditd_reset();
816 goto main_queue;
819 /* attempt to flush the retry queue */
820 rc = kauditd_send_queue(sk, portid,
821 &audit_retry_queue, UNICAST_RETRIES,
822 NULL, kauditd_hold_skb);
823 if (rc < 0) {
824 sk = NULL;
825 auditd_reset();
826 goto main_queue;
829 main_queue:
830 /* process the main queue - do the multicast send and attempt
831 * unicast, dump failed record sends to the retry queue; if
832 * sk == NULL due to previous failures we will just do the
833 * multicast send and move the record to the retry queue */
834 rc = kauditd_send_queue(sk, portid, &audit_queue, 1,
835 kauditd_send_multicast_skb,
836 kauditd_retry_skb);
837 if (sk == NULL || rc < 0)
838 auditd_reset();
839 sk = NULL;
841 /* drop our netns reference, no auditd sends past this line */
842 if (net) {
843 put_net(net);
844 net = NULL;
847 /* we have processed all the queues so wake everyone */
848 wake_up(&audit_backlog_wait);
850 /* NOTE: we want to wake up if there is anything on the queue,
851 * regardless of if an auditd is connected, as we need to
852 * do the multicast send and rotate records from the
853 * main queue to the retry/hold queues */
854 wait_event_freezable(kauditd_wait,
855 (skb_queue_len(&audit_queue) ? 1 : 0));
858 return 0;
861 int audit_send_list(void *_dest)
863 struct audit_netlink_list *dest = _dest;
864 struct sk_buff *skb;
865 struct sock *sk = audit_get_sk(dest->net);
867 /* wait for parent to finish and send an ACK */
868 mutex_lock(&audit_cmd_mutex);
869 mutex_unlock(&audit_cmd_mutex);
871 while ((skb = __skb_dequeue(&dest->q)) != NULL)
872 netlink_unicast(sk, skb, dest->portid, 0);
874 put_net(dest->net);
875 kfree(dest);
877 return 0;
880 struct sk_buff *audit_make_reply(__u32 portid, int seq, int type, int done,
881 int multi, const void *payload, int size)
883 struct sk_buff *skb;
884 struct nlmsghdr *nlh;
885 void *data;
886 int flags = multi ? NLM_F_MULTI : 0;
887 int t = done ? NLMSG_DONE : type;
889 skb = nlmsg_new(size, GFP_KERNEL);
890 if (!skb)
891 return NULL;
893 nlh = nlmsg_put(skb, portid, seq, t, size, flags);
894 if (!nlh)
895 goto out_kfree_skb;
896 data = nlmsg_data(nlh);
897 memcpy(data, payload, size);
898 return skb;
900 out_kfree_skb:
901 kfree_skb(skb);
902 return NULL;
905 static int audit_send_reply_thread(void *arg)
907 struct audit_reply *reply = (struct audit_reply *)arg;
908 struct sock *sk = audit_get_sk(reply->net);
910 mutex_lock(&audit_cmd_mutex);
911 mutex_unlock(&audit_cmd_mutex);
913 /* Ignore failure. It'll only happen if the sender goes away,
914 because our timeout is set to infinite. */
915 netlink_unicast(sk, reply->skb, reply->portid, 0);
916 put_net(reply->net);
917 kfree(reply);
918 return 0;
922 * audit_send_reply - send an audit reply message via netlink
923 * @request_skb: skb of request we are replying to (used to target the reply)
924 * @seq: sequence number
925 * @type: audit message type
926 * @done: done (last) flag
927 * @multi: multi-part message flag
928 * @payload: payload data
929 * @size: payload size
931 * Allocates an skb, builds the netlink message, and sends it to the port id.
932 * No failure notifications.
934 static void audit_send_reply(struct sk_buff *request_skb, int seq, int type, int done,
935 int multi, const void *payload, int size)
937 u32 portid = NETLINK_CB(request_skb).portid;
938 struct net *net = sock_net(NETLINK_CB(request_skb).sk);
939 struct sk_buff *skb;
940 struct task_struct *tsk;
941 struct audit_reply *reply = kmalloc(sizeof(struct audit_reply),
942 GFP_KERNEL);
944 if (!reply)
945 return;
947 skb = audit_make_reply(portid, seq, type, done, multi, payload, size);
948 if (!skb)
949 goto out;
951 reply->net = get_net(net);
952 reply->portid = portid;
953 reply->skb = skb;
955 tsk = kthread_run(audit_send_reply_thread, reply, "audit_send_reply");
956 if (!IS_ERR(tsk))
957 return;
958 kfree_skb(skb);
959 out:
960 kfree(reply);
964 * Check for appropriate CAP_AUDIT_ capabilities on incoming audit
965 * control messages.
967 static int audit_netlink_ok(struct sk_buff *skb, u16 msg_type)
969 int err = 0;
971 /* Only support initial user namespace for now. */
973 * We return ECONNREFUSED because it tricks userspace into thinking
974 * that audit was not configured into the kernel. Lots of users
975 * configure their PAM stack (because that's what the distro does)
976 * to reject login if unable to send messages to audit. If we return
977 * ECONNREFUSED the PAM stack thinks the kernel does not have audit
978 * configured in and will let login proceed. If we return EPERM
979 * userspace will reject all logins. This should be removed when we
980 * support non init namespaces!!
982 if (current_user_ns() != &init_user_ns)
983 return -ECONNREFUSED;
985 switch (msg_type) {
986 case AUDIT_LIST:
987 case AUDIT_ADD:
988 case AUDIT_DEL:
989 return -EOPNOTSUPP;
990 case AUDIT_GET:
991 case AUDIT_SET:
992 case AUDIT_GET_FEATURE:
993 case AUDIT_SET_FEATURE:
994 case AUDIT_LIST_RULES:
995 case AUDIT_ADD_RULE:
996 case AUDIT_DEL_RULE:
997 case AUDIT_SIGNAL_INFO:
998 case AUDIT_TTY_GET:
999 case AUDIT_TTY_SET:
1000 case AUDIT_TRIM:
1001 case AUDIT_MAKE_EQUIV:
1002 /* Only support auditd and auditctl in initial pid namespace
1003 * for now. */
1004 if (task_active_pid_ns(current) != &init_pid_ns)
1005 return -EPERM;
1007 if (!netlink_capable(skb, CAP_AUDIT_CONTROL))
1008 err = -EPERM;
1009 break;
1010 case AUDIT_USER:
1011 case AUDIT_FIRST_USER_MSG ... AUDIT_LAST_USER_MSG:
1012 case AUDIT_FIRST_USER_MSG2 ... AUDIT_LAST_USER_MSG2:
1013 if (!netlink_capable(skb, CAP_AUDIT_WRITE))
1014 err = -EPERM;
1015 break;
1016 default: /* bad msg */
1017 err = -EINVAL;
1020 return err;
1023 static void audit_log_common_recv_msg(struct audit_buffer **ab, u16 msg_type)
1025 uid_t uid = from_kuid(&init_user_ns, current_uid());
1026 pid_t pid = task_tgid_nr(current);
1028 if (!audit_enabled && msg_type != AUDIT_USER_AVC) {
1029 *ab = NULL;
1030 return;
1033 *ab = audit_log_start(NULL, GFP_KERNEL, msg_type);
1034 if (unlikely(!*ab))
1035 return;
1036 audit_log_format(*ab, "pid=%d uid=%u", pid, uid);
1037 audit_log_session_info(*ab);
1038 audit_log_task_context(*ab);
1041 int is_audit_feature_set(int i)
1043 return af.features & AUDIT_FEATURE_TO_MASK(i);
1047 static int audit_get_feature(struct sk_buff *skb)
1049 u32 seq;
1051 seq = nlmsg_hdr(skb)->nlmsg_seq;
1053 audit_send_reply(skb, seq, AUDIT_GET_FEATURE, 0, 0, &af, sizeof(af));
1055 return 0;
1058 static void audit_log_feature_change(int which, u32 old_feature, u32 new_feature,
1059 u32 old_lock, u32 new_lock, int res)
1061 struct audit_buffer *ab;
1063 if (audit_enabled == AUDIT_OFF)
1064 return;
1066 ab = audit_log_start(NULL, GFP_KERNEL, AUDIT_FEATURE_CHANGE);
1067 audit_log_task_info(ab, current);
1068 audit_log_format(ab, " feature=%s old=%u new=%u old_lock=%u new_lock=%u res=%d",
1069 audit_feature_names[which], !!old_feature, !!new_feature,
1070 !!old_lock, !!new_lock, res);
1071 audit_log_end(ab);
1074 static int audit_set_feature(struct sk_buff *skb)
1076 struct audit_features *uaf;
1077 int i;
1079 BUILD_BUG_ON(AUDIT_LAST_FEATURE + 1 > ARRAY_SIZE(audit_feature_names));
1080 uaf = nlmsg_data(nlmsg_hdr(skb));
1082 /* if there is ever a version 2 we should handle that here */
1084 for (i = 0; i <= AUDIT_LAST_FEATURE; i++) {
1085 u32 feature = AUDIT_FEATURE_TO_MASK(i);
1086 u32 old_feature, new_feature, old_lock, new_lock;
1088 /* if we are not changing this feature, move along */
1089 if (!(feature & uaf->mask))
1090 continue;
1092 old_feature = af.features & feature;
1093 new_feature = uaf->features & feature;
1094 new_lock = (uaf->lock | af.lock) & feature;
1095 old_lock = af.lock & feature;
1097 /* are we changing a locked feature? */
1098 if (old_lock && (new_feature != old_feature)) {
1099 audit_log_feature_change(i, old_feature, new_feature,
1100 old_lock, new_lock, 0);
1101 return -EPERM;
1104 /* nothing invalid, do the changes */
1105 for (i = 0; i <= AUDIT_LAST_FEATURE; i++) {
1106 u32 feature = AUDIT_FEATURE_TO_MASK(i);
1107 u32 old_feature, new_feature, old_lock, new_lock;
1109 /* if we are not changing this feature, move along */
1110 if (!(feature & uaf->mask))
1111 continue;
1113 old_feature = af.features & feature;
1114 new_feature = uaf->features & feature;
1115 old_lock = af.lock & feature;
1116 new_lock = (uaf->lock | af.lock) & feature;
1118 if (new_feature != old_feature)
1119 audit_log_feature_change(i, old_feature, new_feature,
1120 old_lock, new_lock, 1);
1122 if (new_feature)
1123 af.features |= feature;
1124 else
1125 af.features &= ~feature;
1126 af.lock |= new_lock;
1129 return 0;
1132 static int audit_replace(pid_t pid)
1134 struct sk_buff *skb;
1136 skb = audit_make_reply(0, 0, AUDIT_REPLACE, 0, 0, &pid, sizeof(pid));
1137 if (!skb)
1138 return -ENOMEM;
1139 return auditd_send_unicast_skb(skb);
1142 static int audit_receive_msg(struct sk_buff *skb, struct nlmsghdr *nlh)
1144 u32 seq;
1145 void *data;
1146 int err;
1147 struct audit_buffer *ab;
1148 u16 msg_type = nlh->nlmsg_type;
1149 struct audit_sig_info *sig_data;
1150 char *ctx = NULL;
1151 u32 len;
1153 err = audit_netlink_ok(skb, msg_type);
1154 if (err)
1155 return err;
1157 seq = nlh->nlmsg_seq;
1158 data = nlmsg_data(nlh);
1160 switch (msg_type) {
1161 case AUDIT_GET: {
1162 struct audit_status s;
1163 memset(&s, 0, sizeof(s));
1164 s.enabled = audit_enabled;
1165 s.failure = audit_failure;
1166 s.pid = auditd_pid_vnr();
1167 s.rate_limit = audit_rate_limit;
1168 s.backlog_limit = audit_backlog_limit;
1169 s.lost = atomic_read(&audit_lost);
1170 s.backlog = skb_queue_len(&audit_queue);
1171 s.feature_bitmap = AUDIT_FEATURE_BITMAP_ALL;
1172 s.backlog_wait_time = audit_backlog_wait_time;
1173 audit_send_reply(skb, seq, AUDIT_GET, 0, 0, &s, sizeof(s));
1174 break;
1176 case AUDIT_SET: {
1177 struct audit_status s;
1178 memset(&s, 0, sizeof(s));
1179 /* guard against past and future API changes */
1180 memcpy(&s, data, min_t(size_t, sizeof(s), nlmsg_len(nlh)));
1181 if (s.mask & AUDIT_STATUS_ENABLED) {
1182 err = audit_set_enabled(s.enabled);
1183 if (err < 0)
1184 return err;
1186 if (s.mask & AUDIT_STATUS_FAILURE) {
1187 err = audit_set_failure(s.failure);
1188 if (err < 0)
1189 return err;
1191 if (s.mask & AUDIT_STATUS_PID) {
1192 /* NOTE: we are using task_tgid_vnr() below because
1193 * the s.pid value is relative to the namespace
1194 * of the caller; at present this doesn't matter
1195 * much since you can really only run auditd
1196 * from the initial pid namespace, but something
1197 * to keep in mind if this changes */
1198 int new_pid = s.pid;
1199 pid_t auditd_pid;
1200 pid_t requesting_pid = task_tgid_vnr(current);
1202 /* test the auditd connection */
1203 audit_replace(requesting_pid);
1205 auditd_pid = auditd_pid_vnr();
1206 /* only the current auditd can unregister itself */
1207 if ((!new_pid) && (requesting_pid != auditd_pid)) {
1208 audit_log_config_change("audit_pid", new_pid,
1209 auditd_pid, 0);
1210 return -EACCES;
1212 /* replacing a healthy auditd is not allowed */
1213 if (auditd_pid && new_pid) {
1214 audit_log_config_change("audit_pid", new_pid,
1215 auditd_pid, 0);
1216 return -EEXIST;
1219 if (new_pid) {
1220 /* register a new auditd connection */
1221 err = auditd_set(new_pid,
1222 NETLINK_CB(skb).portid,
1223 sock_net(NETLINK_CB(skb).sk));
1224 if (audit_enabled != AUDIT_OFF)
1225 audit_log_config_change("audit_pid",
1226 new_pid,
1227 auditd_pid,
1228 err ? 0 : 1);
1229 if (err)
1230 return err;
1232 /* try to process any backlog */
1233 wake_up_interruptible(&kauditd_wait);
1234 } else {
1235 if (audit_enabled != AUDIT_OFF)
1236 audit_log_config_change("audit_pid",
1237 new_pid,
1238 auditd_pid, 1);
1240 /* unregister the auditd connection */
1241 auditd_reset();
1244 if (s.mask & AUDIT_STATUS_RATE_LIMIT) {
1245 err = audit_set_rate_limit(s.rate_limit);
1246 if (err < 0)
1247 return err;
1249 if (s.mask & AUDIT_STATUS_BACKLOG_LIMIT) {
1250 err = audit_set_backlog_limit(s.backlog_limit);
1251 if (err < 0)
1252 return err;
1254 if (s.mask & AUDIT_STATUS_BACKLOG_WAIT_TIME) {
1255 if (sizeof(s) > (size_t)nlh->nlmsg_len)
1256 return -EINVAL;
1257 if (s.backlog_wait_time > 10*AUDIT_BACKLOG_WAIT_TIME)
1258 return -EINVAL;
1259 err = audit_set_backlog_wait_time(s.backlog_wait_time);
1260 if (err < 0)
1261 return err;
1263 if (s.mask == AUDIT_STATUS_LOST) {
1264 u32 lost = atomic_xchg(&audit_lost, 0);
1266 audit_log_config_change("lost", 0, lost, 1);
1267 return lost;
1269 break;
1271 case AUDIT_GET_FEATURE:
1272 err = audit_get_feature(skb);
1273 if (err)
1274 return err;
1275 break;
1276 case AUDIT_SET_FEATURE:
1277 err = audit_set_feature(skb);
1278 if (err)
1279 return err;
1280 break;
1281 case AUDIT_USER:
1282 case AUDIT_FIRST_USER_MSG ... AUDIT_LAST_USER_MSG:
1283 case AUDIT_FIRST_USER_MSG2 ... AUDIT_LAST_USER_MSG2:
1284 if (!audit_enabled && msg_type != AUDIT_USER_AVC)
1285 return 0;
1287 err = audit_filter(msg_type, AUDIT_FILTER_USER);
1288 if (err == 1) { /* match or error */
1289 err = 0;
1290 if (msg_type == AUDIT_USER_TTY) {
1291 err = tty_audit_push();
1292 if (err)
1293 break;
1295 audit_log_common_recv_msg(&ab, msg_type);
1296 if (msg_type != AUDIT_USER_TTY)
1297 audit_log_format(ab, " msg='%.*s'",
1298 AUDIT_MESSAGE_TEXT_MAX,
1299 (char *)data);
1300 else {
1301 int size;
1303 audit_log_format(ab, " data=");
1304 size = nlmsg_len(nlh);
1305 if (size > 0 &&
1306 ((unsigned char *)data)[size - 1] == '\0')
1307 size--;
1308 audit_log_n_untrustedstring(ab, data, size);
1310 audit_set_portid(ab, NETLINK_CB(skb).portid);
1311 audit_log_end(ab);
1313 break;
1314 case AUDIT_ADD_RULE:
1315 case AUDIT_DEL_RULE:
1316 if (nlmsg_len(nlh) < sizeof(struct audit_rule_data))
1317 return -EINVAL;
1318 if (audit_enabled == AUDIT_LOCKED) {
1319 audit_log_common_recv_msg(&ab, AUDIT_CONFIG_CHANGE);
1320 audit_log_format(ab, " audit_enabled=%d res=0", audit_enabled);
1321 audit_log_end(ab);
1322 return -EPERM;
1324 err = audit_rule_change(msg_type, NETLINK_CB(skb).portid,
1325 seq, data, nlmsg_len(nlh));
1326 break;
1327 case AUDIT_LIST_RULES:
1328 err = audit_list_rules_send(skb, seq);
1329 break;
1330 case AUDIT_TRIM:
1331 audit_trim_trees();
1332 audit_log_common_recv_msg(&ab, AUDIT_CONFIG_CHANGE);
1333 audit_log_format(ab, " op=trim res=1");
1334 audit_log_end(ab);
1335 break;
1336 case AUDIT_MAKE_EQUIV: {
1337 void *bufp = data;
1338 u32 sizes[2];
1339 size_t msglen = nlmsg_len(nlh);
1340 char *old, *new;
1342 err = -EINVAL;
1343 if (msglen < 2 * sizeof(u32))
1344 break;
1345 memcpy(sizes, bufp, 2 * sizeof(u32));
1346 bufp += 2 * sizeof(u32);
1347 msglen -= 2 * sizeof(u32);
1348 old = audit_unpack_string(&bufp, &msglen, sizes[0]);
1349 if (IS_ERR(old)) {
1350 err = PTR_ERR(old);
1351 break;
1353 new = audit_unpack_string(&bufp, &msglen, sizes[1]);
1354 if (IS_ERR(new)) {
1355 err = PTR_ERR(new);
1356 kfree(old);
1357 break;
1359 /* OK, here comes... */
1360 err = audit_tag_tree(old, new);
1362 audit_log_common_recv_msg(&ab, AUDIT_CONFIG_CHANGE);
1364 audit_log_format(ab, " op=make_equiv old=");
1365 audit_log_untrustedstring(ab, old);
1366 audit_log_format(ab, " new=");
1367 audit_log_untrustedstring(ab, new);
1368 audit_log_format(ab, " res=%d", !err);
1369 audit_log_end(ab);
1370 kfree(old);
1371 kfree(new);
1372 break;
1374 case AUDIT_SIGNAL_INFO:
1375 len = 0;
1376 if (audit_sig_sid) {
1377 err = security_secid_to_secctx(audit_sig_sid, &ctx, &len);
1378 if (err)
1379 return err;
1381 sig_data = kmalloc(sizeof(*sig_data) + len, GFP_KERNEL);
1382 if (!sig_data) {
1383 if (audit_sig_sid)
1384 security_release_secctx(ctx, len);
1385 return -ENOMEM;
1387 sig_data->uid = from_kuid(&init_user_ns, audit_sig_uid);
1388 sig_data->pid = audit_sig_pid;
1389 if (audit_sig_sid) {
1390 memcpy(sig_data->ctx, ctx, len);
1391 security_release_secctx(ctx, len);
1393 audit_send_reply(skb, seq, AUDIT_SIGNAL_INFO, 0, 0,
1394 sig_data, sizeof(*sig_data) + len);
1395 kfree(sig_data);
1396 break;
1397 case AUDIT_TTY_GET: {
1398 struct audit_tty_status s;
1399 unsigned int t;
1401 t = READ_ONCE(current->signal->audit_tty);
1402 s.enabled = t & AUDIT_TTY_ENABLE;
1403 s.log_passwd = !!(t & AUDIT_TTY_LOG_PASSWD);
1405 audit_send_reply(skb, seq, AUDIT_TTY_GET, 0, 0, &s, sizeof(s));
1406 break;
1408 case AUDIT_TTY_SET: {
1409 struct audit_tty_status s, old;
1410 struct audit_buffer *ab;
1411 unsigned int t;
1413 memset(&s, 0, sizeof(s));
1414 /* guard against past and future API changes */
1415 memcpy(&s, data, min_t(size_t, sizeof(s), nlmsg_len(nlh)));
1416 /* check if new data is valid */
1417 if ((s.enabled != 0 && s.enabled != 1) ||
1418 (s.log_passwd != 0 && s.log_passwd != 1))
1419 err = -EINVAL;
1421 if (err)
1422 t = READ_ONCE(current->signal->audit_tty);
1423 else {
1424 t = s.enabled | (-s.log_passwd & AUDIT_TTY_LOG_PASSWD);
1425 t = xchg(&current->signal->audit_tty, t);
1427 old.enabled = t & AUDIT_TTY_ENABLE;
1428 old.log_passwd = !!(t & AUDIT_TTY_LOG_PASSWD);
1430 audit_log_common_recv_msg(&ab, AUDIT_CONFIG_CHANGE);
1431 audit_log_format(ab, " op=tty_set old-enabled=%d new-enabled=%d"
1432 " old-log_passwd=%d new-log_passwd=%d res=%d",
1433 old.enabled, s.enabled, old.log_passwd,
1434 s.log_passwd, !err);
1435 audit_log_end(ab);
1436 break;
1438 default:
1439 err = -EINVAL;
1440 break;
1443 return err < 0 ? err : 0;
1447 * Get message from skb. Each message is processed by audit_receive_msg.
1448 * Malformed skbs with wrong length are discarded silently.
1450 static void audit_receive_skb(struct sk_buff *skb)
1452 struct nlmsghdr *nlh;
1454 * len MUST be signed for nlmsg_next to be able to dec it below 0
1455 * if the nlmsg_len was not aligned
1457 int len;
1458 int err;
1460 nlh = nlmsg_hdr(skb);
1461 len = skb->len;
1463 while (nlmsg_ok(nlh, len)) {
1464 err = audit_receive_msg(skb, nlh);
1465 /* if err or if this message says it wants a response */
1466 if (err || (nlh->nlmsg_flags & NLM_F_ACK))
1467 netlink_ack(skb, nlh, err);
1469 nlh = nlmsg_next(nlh, &len);
1473 /* Receive messages from netlink socket. */
1474 static void audit_receive(struct sk_buff *skb)
1476 mutex_lock(&audit_cmd_mutex);
1477 audit_receive_skb(skb);
1478 mutex_unlock(&audit_cmd_mutex);
1481 /* Run custom bind function on netlink socket group connect or bind requests. */
1482 static int audit_bind(struct net *net, int group)
1484 if (!capable(CAP_AUDIT_READ))
1485 return -EPERM;
1487 return 0;
1490 static int __net_init audit_net_init(struct net *net)
1492 struct netlink_kernel_cfg cfg = {
1493 .input = audit_receive,
1494 .bind = audit_bind,
1495 .flags = NL_CFG_F_NONROOT_RECV,
1496 .groups = AUDIT_NLGRP_MAX,
1499 struct audit_net *aunet = net_generic(net, audit_net_id);
1501 aunet->sk = netlink_kernel_create(net, NETLINK_AUDIT, &cfg);
1502 if (aunet->sk == NULL) {
1503 audit_panic("cannot initialize netlink socket in namespace");
1504 return -ENOMEM;
1506 aunet->sk->sk_sndtimeo = MAX_SCHEDULE_TIMEOUT;
1508 return 0;
1511 static void __net_exit audit_net_exit(struct net *net)
1513 struct audit_net *aunet = net_generic(net, audit_net_id);
1515 /* NOTE: you would think that we would want to check the auditd
1516 * connection and potentially reset it here if it lives in this
1517 * namespace, but since the auditd connection tracking struct holds a
1518 * reference to this namespace (see auditd_set()) we are only ever
1519 * going to get here after that connection has been released */
1521 netlink_kernel_release(aunet->sk);
1524 static struct pernet_operations audit_net_ops __net_initdata = {
1525 .init = audit_net_init,
1526 .exit = audit_net_exit,
1527 .id = &audit_net_id,
1528 .size = sizeof(struct audit_net),
1531 /* Initialize audit support at boot time. */
1532 static int __init audit_init(void)
1534 int i;
1536 if (audit_initialized == AUDIT_DISABLED)
1537 return 0;
1539 skb_queue_head_init(&audit_queue);
1540 skb_queue_head_init(&audit_retry_queue);
1541 skb_queue_head_init(&audit_hold_queue);
1543 for (i = 0; i < AUDIT_INODE_BUCKETS; i++)
1544 INIT_LIST_HEAD(&audit_inode_hash[i]);
1546 pr_info("initializing netlink subsys (%s)\n",
1547 audit_default ? "enabled" : "disabled");
1548 register_pernet_subsys(&audit_net_ops);
1550 audit_initialized = AUDIT_INITIALIZED;
1551 audit_enabled = audit_default;
1552 audit_ever_enabled |= !!audit_default;
1554 kauditd_task = kthread_run(kauditd_thread, NULL, "kauditd");
1555 if (IS_ERR(kauditd_task)) {
1556 int err = PTR_ERR(kauditd_task);
1557 panic("audit: failed to start the kauditd thread (%d)\n", err);
1560 audit_log(NULL, GFP_KERNEL, AUDIT_KERNEL,
1561 "state=initialized audit_enabled=%u res=1",
1562 audit_enabled);
1564 return 0;
1566 __initcall(audit_init);
1568 /* Process kernel command-line parameter at boot time. audit=0 or audit=1. */
1569 static int __init audit_enable(char *str)
1571 audit_default = !!simple_strtol(str, NULL, 0);
1572 if (!audit_default)
1573 audit_initialized = AUDIT_DISABLED;
1575 pr_info("%s\n", audit_default ?
1576 "enabled (after initialization)" : "disabled (until reboot)");
1578 return 1;
1580 __setup("audit=", audit_enable);
1582 /* Process kernel command-line parameter at boot time.
1583 * audit_backlog_limit=<n> */
1584 static int __init audit_backlog_limit_set(char *str)
1586 u32 audit_backlog_limit_arg;
1588 pr_info("audit_backlog_limit: ");
1589 if (kstrtouint(str, 0, &audit_backlog_limit_arg)) {
1590 pr_cont("using default of %u, unable to parse %s\n",
1591 audit_backlog_limit, str);
1592 return 1;
1595 audit_backlog_limit = audit_backlog_limit_arg;
1596 pr_cont("%d\n", audit_backlog_limit);
1598 return 1;
1600 __setup("audit_backlog_limit=", audit_backlog_limit_set);
1602 static void audit_buffer_free(struct audit_buffer *ab)
1604 unsigned long flags;
1606 if (!ab)
1607 return;
1609 kfree_skb(ab->skb);
1610 spin_lock_irqsave(&audit_freelist_lock, flags);
1611 if (audit_freelist_count > AUDIT_MAXFREE)
1612 kfree(ab);
1613 else {
1614 audit_freelist_count++;
1615 list_add(&ab->list, &audit_freelist);
1617 spin_unlock_irqrestore(&audit_freelist_lock, flags);
1620 static struct audit_buffer * audit_buffer_alloc(struct audit_context *ctx,
1621 gfp_t gfp_mask, int type)
1623 unsigned long flags;
1624 struct audit_buffer *ab = NULL;
1625 struct nlmsghdr *nlh;
1627 spin_lock_irqsave(&audit_freelist_lock, flags);
1628 if (!list_empty(&audit_freelist)) {
1629 ab = list_entry(audit_freelist.next,
1630 struct audit_buffer, list);
1631 list_del(&ab->list);
1632 --audit_freelist_count;
1634 spin_unlock_irqrestore(&audit_freelist_lock, flags);
1636 if (!ab) {
1637 ab = kmalloc(sizeof(*ab), gfp_mask);
1638 if (!ab)
1639 goto err;
1642 ab->ctx = ctx;
1643 ab->gfp_mask = gfp_mask;
1645 ab->skb = nlmsg_new(AUDIT_BUFSIZ, gfp_mask);
1646 if (!ab->skb)
1647 goto err;
1649 nlh = nlmsg_put(ab->skb, 0, 0, type, 0, 0);
1650 if (!nlh)
1651 goto out_kfree_skb;
1653 return ab;
1655 out_kfree_skb:
1656 kfree_skb(ab->skb);
1657 ab->skb = NULL;
1658 err:
1659 audit_buffer_free(ab);
1660 return NULL;
1664 * audit_serial - compute a serial number for the audit record
1666 * Compute a serial number for the audit record. Audit records are
1667 * written to user-space as soon as they are generated, so a complete
1668 * audit record may be written in several pieces. The timestamp of the
1669 * record and this serial number are used by the user-space tools to
1670 * determine which pieces belong to the same audit record. The
1671 * (timestamp,serial) tuple is unique for each syscall and is live from
1672 * syscall entry to syscall exit.
1674 * NOTE: Another possibility is to store the formatted records off the
1675 * audit context (for those records that have a context), and emit them
1676 * all at syscall exit. However, this could delay the reporting of
1677 * significant errors until syscall exit (or never, if the system
1678 * halts).
1680 unsigned int audit_serial(void)
1682 static atomic_t serial = ATOMIC_INIT(0);
1684 return atomic_add_return(1, &serial);
1687 static inline void audit_get_stamp(struct audit_context *ctx,
1688 struct timespec *t, unsigned int *serial)
1690 if (!ctx || !auditsc_get_stamp(ctx, t, serial)) {
1691 *t = CURRENT_TIME;
1692 *serial = audit_serial();
1697 * audit_log_start - obtain an audit buffer
1698 * @ctx: audit_context (may be NULL)
1699 * @gfp_mask: type of allocation
1700 * @type: audit message type
1702 * Returns audit_buffer pointer on success or NULL on error.
1704 * Obtain an audit buffer. This routine does locking to obtain the
1705 * audit buffer, but then no locking is required for calls to
1706 * audit_log_*format. If the task (ctx) is a task that is currently in a
1707 * syscall, then the syscall is marked as auditable and an audit record
1708 * will be written at syscall exit. If there is no associated task, then
1709 * task context (ctx) should be NULL.
1711 struct audit_buffer *audit_log_start(struct audit_context *ctx, gfp_t gfp_mask,
1712 int type)
1714 struct audit_buffer *ab;
1715 struct timespec t;
1716 unsigned int uninitialized_var(serial);
1718 if (audit_initialized != AUDIT_INITIALIZED)
1719 return NULL;
1721 if (unlikely(!audit_filter(type, AUDIT_FILTER_TYPE)))
1722 return NULL;
1724 /* NOTE: don't ever fail/sleep on these two conditions:
1725 * 1. auditd generated record - since we need auditd to drain the
1726 * queue; also, when we are checking for auditd, compare PIDs using
1727 * task_tgid_vnr() since auditd_pid is set in audit_receive_msg()
1728 * using a PID anchored in the caller's namespace
1729 * 2. generator holding the audit_cmd_mutex - we don't want to block
1730 * while holding the mutex */
1731 if (!(auditd_test_task(current) ||
1732 (current == __mutex_owner(&audit_cmd_mutex)))) {
1733 long stime = audit_backlog_wait_time;
1735 while (audit_backlog_limit &&
1736 (skb_queue_len(&audit_queue) > audit_backlog_limit)) {
1737 /* wake kauditd to try and flush the queue */
1738 wake_up_interruptible(&kauditd_wait);
1740 /* sleep if we are allowed and we haven't exhausted our
1741 * backlog wait limit */
1742 if (gfpflags_allow_blocking(gfp_mask) && (stime > 0)) {
1743 DECLARE_WAITQUEUE(wait, current);
1745 add_wait_queue_exclusive(&audit_backlog_wait,
1746 &wait);
1747 set_current_state(TASK_UNINTERRUPTIBLE);
1748 stime = schedule_timeout(stime);
1749 remove_wait_queue(&audit_backlog_wait, &wait);
1750 } else {
1751 if (audit_rate_check() && printk_ratelimit())
1752 pr_warn("audit_backlog=%d > audit_backlog_limit=%d\n",
1753 skb_queue_len(&audit_queue),
1754 audit_backlog_limit);
1755 audit_log_lost("backlog limit exceeded");
1756 return NULL;
1761 ab = audit_buffer_alloc(ctx, gfp_mask, type);
1762 if (!ab) {
1763 audit_log_lost("out of memory in audit_log_start");
1764 return NULL;
1767 audit_get_stamp(ab->ctx, &t, &serial);
1768 audit_log_format(ab, "audit(%lu.%03lu:%u): ",
1769 t.tv_sec, t.tv_nsec/1000000, serial);
1771 return ab;
1775 * audit_expand - expand skb in the audit buffer
1776 * @ab: audit_buffer
1777 * @extra: space to add at tail of the skb
1779 * Returns 0 (no space) on failed expansion, or available space if
1780 * successful.
1782 static inline int audit_expand(struct audit_buffer *ab, int extra)
1784 struct sk_buff *skb = ab->skb;
1785 int oldtail = skb_tailroom(skb);
1786 int ret = pskb_expand_head(skb, 0, extra, ab->gfp_mask);
1787 int newtail = skb_tailroom(skb);
1789 if (ret < 0) {
1790 audit_log_lost("out of memory in audit_expand");
1791 return 0;
1794 skb->truesize += newtail - oldtail;
1795 return newtail;
1799 * Format an audit message into the audit buffer. If there isn't enough
1800 * room in the audit buffer, more room will be allocated and vsnprint
1801 * will be called a second time. Currently, we assume that a printk
1802 * can't format message larger than 1024 bytes, so we don't either.
1804 static void audit_log_vformat(struct audit_buffer *ab, const char *fmt,
1805 va_list args)
1807 int len, avail;
1808 struct sk_buff *skb;
1809 va_list args2;
1811 if (!ab)
1812 return;
1814 BUG_ON(!ab->skb);
1815 skb = ab->skb;
1816 avail = skb_tailroom(skb);
1817 if (avail == 0) {
1818 avail = audit_expand(ab, AUDIT_BUFSIZ);
1819 if (!avail)
1820 goto out;
1822 va_copy(args2, args);
1823 len = vsnprintf(skb_tail_pointer(skb), avail, fmt, args);
1824 if (len >= avail) {
1825 /* The printk buffer is 1024 bytes long, so if we get
1826 * here and AUDIT_BUFSIZ is at least 1024, then we can
1827 * log everything that printk could have logged. */
1828 avail = audit_expand(ab,
1829 max_t(unsigned, AUDIT_BUFSIZ, 1+len-avail));
1830 if (!avail)
1831 goto out_va_end;
1832 len = vsnprintf(skb_tail_pointer(skb), avail, fmt, args2);
1834 if (len > 0)
1835 skb_put(skb, len);
1836 out_va_end:
1837 va_end(args2);
1838 out:
1839 return;
1843 * audit_log_format - format a message into the audit buffer.
1844 * @ab: audit_buffer
1845 * @fmt: format string
1846 * @...: optional parameters matching @fmt string
1848 * All the work is done in audit_log_vformat.
1850 void audit_log_format(struct audit_buffer *ab, const char *fmt, ...)
1852 va_list args;
1854 if (!ab)
1855 return;
1856 va_start(args, fmt);
1857 audit_log_vformat(ab, fmt, args);
1858 va_end(args);
1862 * audit_log_hex - convert a buffer to hex and append it to the audit skb
1863 * @ab: the audit_buffer
1864 * @buf: buffer to convert to hex
1865 * @len: length of @buf to be converted
1867 * No return value; failure to expand is silently ignored.
1869 * This function will take the passed buf and convert it into a string of
1870 * ascii hex digits. The new string is placed onto the skb.
1872 void audit_log_n_hex(struct audit_buffer *ab, const unsigned char *buf,
1873 size_t len)
1875 int i, avail, new_len;
1876 unsigned char *ptr;
1877 struct sk_buff *skb;
1879 if (!ab)
1880 return;
1882 BUG_ON(!ab->skb);
1883 skb = ab->skb;
1884 avail = skb_tailroom(skb);
1885 new_len = len<<1;
1886 if (new_len >= avail) {
1887 /* Round the buffer request up to the next multiple */
1888 new_len = AUDIT_BUFSIZ*(((new_len-avail)/AUDIT_BUFSIZ) + 1);
1889 avail = audit_expand(ab, new_len);
1890 if (!avail)
1891 return;
1894 ptr = skb_tail_pointer(skb);
1895 for (i = 0; i < len; i++)
1896 ptr = hex_byte_pack_upper(ptr, buf[i]);
1897 *ptr = 0;
1898 skb_put(skb, len << 1); /* new string is twice the old string */
1902 * Format a string of no more than slen characters into the audit buffer,
1903 * enclosed in quote marks.
1905 void audit_log_n_string(struct audit_buffer *ab, const char *string,
1906 size_t slen)
1908 int avail, new_len;
1909 unsigned char *ptr;
1910 struct sk_buff *skb;
1912 if (!ab)
1913 return;
1915 BUG_ON(!ab->skb);
1916 skb = ab->skb;
1917 avail = skb_tailroom(skb);
1918 new_len = slen + 3; /* enclosing quotes + null terminator */
1919 if (new_len > avail) {
1920 avail = audit_expand(ab, new_len);
1921 if (!avail)
1922 return;
1924 ptr = skb_tail_pointer(skb);
1925 *ptr++ = '"';
1926 memcpy(ptr, string, slen);
1927 ptr += slen;
1928 *ptr++ = '"';
1929 *ptr = 0;
1930 skb_put(skb, slen + 2); /* don't include null terminator */
1934 * audit_string_contains_control - does a string need to be logged in hex
1935 * @string: string to be checked
1936 * @len: max length of the string to check
1938 bool audit_string_contains_control(const char *string, size_t len)
1940 const unsigned char *p;
1941 for (p = string; p < (const unsigned char *)string + len; p++) {
1942 if (*p == '"' || *p < 0x21 || *p > 0x7e)
1943 return true;
1945 return false;
1949 * audit_log_n_untrustedstring - log a string that may contain random characters
1950 * @ab: audit_buffer
1951 * @len: length of string (not including trailing null)
1952 * @string: string to be logged
1954 * This code will escape a string that is passed to it if the string
1955 * contains a control character, unprintable character, double quote mark,
1956 * or a space. Unescaped strings will start and end with a double quote mark.
1957 * Strings that are escaped are printed in hex (2 digits per char).
1959 * The caller specifies the number of characters in the string to log, which may
1960 * or may not be the entire string.
1962 void audit_log_n_untrustedstring(struct audit_buffer *ab, const char *string,
1963 size_t len)
1965 if (audit_string_contains_control(string, len))
1966 audit_log_n_hex(ab, string, len);
1967 else
1968 audit_log_n_string(ab, string, len);
1972 * audit_log_untrustedstring - log a string that may contain random characters
1973 * @ab: audit_buffer
1974 * @string: string to be logged
1976 * Same as audit_log_n_untrustedstring(), except that strlen is used to
1977 * determine string length.
1979 void audit_log_untrustedstring(struct audit_buffer *ab, const char *string)
1981 audit_log_n_untrustedstring(ab, string, strlen(string));
1984 /* This is a helper-function to print the escaped d_path */
1985 void audit_log_d_path(struct audit_buffer *ab, const char *prefix,
1986 const struct path *path)
1988 char *p, *pathname;
1990 if (prefix)
1991 audit_log_format(ab, "%s", prefix);
1993 /* We will allow 11 spaces for ' (deleted)' to be appended */
1994 pathname = kmalloc(PATH_MAX+11, ab->gfp_mask);
1995 if (!pathname) {
1996 audit_log_string(ab, "<no_memory>");
1997 return;
1999 p = d_path(path, pathname, PATH_MAX+11);
2000 if (IS_ERR(p)) { /* Should never happen since we send PATH_MAX */
2001 /* FIXME: can we save some information here? */
2002 audit_log_string(ab, "<too_long>");
2003 } else
2004 audit_log_untrustedstring(ab, p);
2005 kfree(pathname);
2008 void audit_log_session_info(struct audit_buffer *ab)
2010 unsigned int sessionid = audit_get_sessionid(current);
2011 uid_t auid = from_kuid(&init_user_ns, audit_get_loginuid(current));
2013 audit_log_format(ab, " auid=%u ses=%u", auid, sessionid);
2016 void audit_log_key(struct audit_buffer *ab, char *key)
2018 audit_log_format(ab, " key=");
2019 if (key)
2020 audit_log_untrustedstring(ab, key);
2021 else
2022 audit_log_format(ab, "(null)");
2025 void audit_log_cap(struct audit_buffer *ab, char *prefix, kernel_cap_t *cap)
2027 int i;
2029 audit_log_format(ab, " %s=", prefix);
2030 CAP_FOR_EACH_U32(i) {
2031 audit_log_format(ab, "%08x",
2032 cap->cap[CAP_LAST_U32 - i]);
2036 static void audit_log_fcaps(struct audit_buffer *ab, struct audit_names *name)
2038 kernel_cap_t *perm = &name->fcap.permitted;
2039 kernel_cap_t *inh = &name->fcap.inheritable;
2040 int log = 0;
2042 if (!cap_isclear(*perm)) {
2043 audit_log_cap(ab, "cap_fp", perm);
2044 log = 1;
2046 if (!cap_isclear(*inh)) {
2047 audit_log_cap(ab, "cap_fi", inh);
2048 log = 1;
2051 if (log)
2052 audit_log_format(ab, " cap_fe=%d cap_fver=%x",
2053 name->fcap.fE, name->fcap_ver);
2056 static inline int audit_copy_fcaps(struct audit_names *name,
2057 const struct dentry *dentry)
2059 struct cpu_vfs_cap_data caps;
2060 int rc;
2062 if (!dentry)
2063 return 0;
2065 rc = get_vfs_caps_from_disk(dentry, &caps);
2066 if (rc)
2067 return rc;
2069 name->fcap.permitted = caps.permitted;
2070 name->fcap.inheritable = caps.inheritable;
2071 name->fcap.fE = !!(caps.magic_etc & VFS_CAP_FLAGS_EFFECTIVE);
2072 name->fcap_ver = (caps.magic_etc & VFS_CAP_REVISION_MASK) >>
2073 VFS_CAP_REVISION_SHIFT;
2075 return 0;
2078 /* Copy inode data into an audit_names. */
2079 void audit_copy_inode(struct audit_names *name, const struct dentry *dentry,
2080 struct inode *inode)
2082 name->ino = inode->i_ino;
2083 name->dev = inode->i_sb->s_dev;
2084 name->mode = inode->i_mode;
2085 name->uid = inode->i_uid;
2086 name->gid = inode->i_gid;
2087 name->rdev = inode->i_rdev;
2088 security_inode_getsecid(inode, &name->osid);
2089 audit_copy_fcaps(name, dentry);
2093 * audit_log_name - produce AUDIT_PATH record from struct audit_names
2094 * @context: audit_context for the task
2095 * @n: audit_names structure with reportable details
2096 * @path: optional path to report instead of audit_names->name
2097 * @record_num: record number to report when handling a list of names
2098 * @call_panic: optional pointer to int that will be updated if secid fails
2100 void audit_log_name(struct audit_context *context, struct audit_names *n,
2101 const struct path *path, int record_num, int *call_panic)
2103 struct audit_buffer *ab;
2104 ab = audit_log_start(context, GFP_KERNEL, AUDIT_PATH);
2105 if (!ab)
2106 return;
2108 audit_log_format(ab, "item=%d", record_num);
2110 if (path)
2111 audit_log_d_path(ab, " name=", path);
2112 else if (n->name) {
2113 switch (n->name_len) {
2114 case AUDIT_NAME_FULL:
2115 /* log the full path */
2116 audit_log_format(ab, " name=");
2117 audit_log_untrustedstring(ab, n->name->name);
2118 break;
2119 case 0:
2120 /* name was specified as a relative path and the
2121 * directory component is the cwd */
2122 audit_log_d_path(ab, " name=", &context->pwd);
2123 break;
2124 default:
2125 /* log the name's directory component */
2126 audit_log_format(ab, " name=");
2127 audit_log_n_untrustedstring(ab, n->name->name,
2128 n->name_len);
2130 } else
2131 audit_log_format(ab, " name=(null)");
2133 if (n->ino != AUDIT_INO_UNSET)
2134 audit_log_format(ab, " inode=%lu"
2135 " dev=%02x:%02x mode=%#ho"
2136 " ouid=%u ogid=%u rdev=%02x:%02x",
2137 n->ino,
2138 MAJOR(n->dev),
2139 MINOR(n->dev),
2140 n->mode,
2141 from_kuid(&init_user_ns, n->uid),
2142 from_kgid(&init_user_ns, n->gid),
2143 MAJOR(n->rdev),
2144 MINOR(n->rdev));
2145 if (n->osid != 0) {
2146 char *ctx = NULL;
2147 u32 len;
2148 if (security_secid_to_secctx(
2149 n->osid, &ctx, &len)) {
2150 audit_log_format(ab, " osid=%u", n->osid);
2151 if (call_panic)
2152 *call_panic = 2;
2153 } else {
2154 audit_log_format(ab, " obj=%s", ctx);
2155 security_release_secctx(ctx, len);
2159 /* log the audit_names record type */
2160 audit_log_format(ab, " nametype=");
2161 switch(n->type) {
2162 case AUDIT_TYPE_NORMAL:
2163 audit_log_format(ab, "NORMAL");
2164 break;
2165 case AUDIT_TYPE_PARENT:
2166 audit_log_format(ab, "PARENT");
2167 break;
2168 case AUDIT_TYPE_CHILD_DELETE:
2169 audit_log_format(ab, "DELETE");
2170 break;
2171 case AUDIT_TYPE_CHILD_CREATE:
2172 audit_log_format(ab, "CREATE");
2173 break;
2174 default:
2175 audit_log_format(ab, "UNKNOWN");
2176 break;
2179 audit_log_fcaps(ab, n);
2180 audit_log_end(ab);
2183 int audit_log_task_context(struct audit_buffer *ab)
2185 char *ctx = NULL;
2186 unsigned len;
2187 int error;
2188 u32 sid;
2190 security_task_getsecid(current, &sid);
2191 if (!sid)
2192 return 0;
2194 error = security_secid_to_secctx(sid, &ctx, &len);
2195 if (error) {
2196 if (error != -EINVAL)
2197 goto error_path;
2198 return 0;
2201 audit_log_format(ab, " subj=%s", ctx);
2202 security_release_secctx(ctx, len);
2203 return 0;
2205 error_path:
2206 audit_panic("error in audit_log_task_context");
2207 return error;
2209 EXPORT_SYMBOL(audit_log_task_context);
2211 void audit_log_d_path_exe(struct audit_buffer *ab,
2212 struct mm_struct *mm)
2214 struct file *exe_file;
2216 if (!mm)
2217 goto out_null;
2219 exe_file = get_mm_exe_file(mm);
2220 if (!exe_file)
2221 goto out_null;
2223 audit_log_d_path(ab, " exe=", &exe_file->f_path);
2224 fput(exe_file);
2225 return;
2226 out_null:
2227 audit_log_format(ab, " exe=(null)");
2230 struct tty_struct *audit_get_tty(struct task_struct *tsk)
2232 struct tty_struct *tty = NULL;
2233 unsigned long flags;
2235 spin_lock_irqsave(&tsk->sighand->siglock, flags);
2236 if (tsk->signal)
2237 tty = tty_kref_get(tsk->signal->tty);
2238 spin_unlock_irqrestore(&tsk->sighand->siglock, flags);
2239 return tty;
2242 void audit_put_tty(struct tty_struct *tty)
2244 tty_kref_put(tty);
2247 void audit_log_task_info(struct audit_buffer *ab, struct task_struct *tsk)
2249 const struct cred *cred;
2250 char comm[sizeof(tsk->comm)];
2251 struct tty_struct *tty;
2253 if (!ab)
2254 return;
2256 /* tsk == current */
2257 cred = current_cred();
2258 tty = audit_get_tty(tsk);
2259 audit_log_format(ab,
2260 " ppid=%d pid=%d auid=%u uid=%u gid=%u"
2261 " euid=%u suid=%u fsuid=%u"
2262 " egid=%u sgid=%u fsgid=%u tty=%s ses=%u",
2263 task_ppid_nr(tsk),
2264 task_tgid_nr(tsk),
2265 from_kuid(&init_user_ns, audit_get_loginuid(tsk)),
2266 from_kuid(&init_user_ns, cred->uid),
2267 from_kgid(&init_user_ns, cred->gid),
2268 from_kuid(&init_user_ns, cred->euid),
2269 from_kuid(&init_user_ns, cred->suid),
2270 from_kuid(&init_user_ns, cred->fsuid),
2271 from_kgid(&init_user_ns, cred->egid),
2272 from_kgid(&init_user_ns, cred->sgid),
2273 from_kgid(&init_user_ns, cred->fsgid),
2274 tty ? tty_name(tty) : "(none)",
2275 audit_get_sessionid(tsk));
2276 audit_put_tty(tty);
2277 audit_log_format(ab, " comm=");
2278 audit_log_untrustedstring(ab, get_task_comm(comm, tsk));
2279 audit_log_d_path_exe(ab, tsk->mm);
2280 audit_log_task_context(ab);
2282 EXPORT_SYMBOL(audit_log_task_info);
2285 * audit_log_link_denied - report a link restriction denial
2286 * @operation: specific link operation
2287 * @link: the path that triggered the restriction
2289 void audit_log_link_denied(const char *operation, const struct path *link)
2291 struct audit_buffer *ab;
2292 struct audit_names *name;
2294 name = kzalloc(sizeof(*name), GFP_NOFS);
2295 if (!name)
2296 return;
2298 /* Generate AUDIT_ANOM_LINK with subject, operation, outcome. */
2299 ab = audit_log_start(current->audit_context, GFP_KERNEL,
2300 AUDIT_ANOM_LINK);
2301 if (!ab)
2302 goto out;
2303 audit_log_format(ab, "op=%s", operation);
2304 audit_log_task_info(ab, current);
2305 audit_log_format(ab, " res=0");
2306 audit_log_end(ab);
2308 /* Generate AUDIT_PATH record with object. */
2309 name->type = AUDIT_TYPE_NORMAL;
2310 audit_copy_inode(name, link->dentry, d_backing_inode(link->dentry));
2311 audit_log_name(current->audit_context, name, link, 0, NULL);
2312 out:
2313 kfree(name);
2317 * audit_log_end - end one audit record
2318 * @ab: the audit_buffer
2320 * We can not do a netlink send inside an irq context because it blocks (last
2321 * arg, flags, is not set to MSG_DONTWAIT), so the audit buffer is placed on a
2322 * queue and a tasklet is scheduled to remove them from the queue outside the
2323 * irq context. May be called in any context.
2325 void audit_log_end(struct audit_buffer *ab)
2327 struct sk_buff *skb;
2328 struct nlmsghdr *nlh;
2330 if (!ab)
2331 return;
2333 if (audit_rate_check()) {
2334 skb = ab->skb;
2335 ab->skb = NULL;
2337 /* setup the netlink header, see the comments in
2338 * kauditd_send_multicast_skb() for length quirks */
2339 nlh = nlmsg_hdr(skb);
2340 nlh->nlmsg_len = skb->len - NLMSG_HDRLEN;
2342 /* queue the netlink packet and poke the kauditd thread */
2343 skb_queue_tail(&audit_queue, skb);
2344 wake_up_interruptible(&kauditd_wait);
2345 } else
2346 audit_log_lost("rate limit exceeded");
2348 audit_buffer_free(ab);
2352 * audit_log - Log an audit record
2353 * @ctx: audit context
2354 * @gfp_mask: type of allocation
2355 * @type: audit message type
2356 * @fmt: format string to use
2357 * @...: variable parameters matching the format string
2359 * This is a convenience function that calls audit_log_start,
2360 * audit_log_vformat, and audit_log_end. It may be called
2361 * in any context.
2363 void audit_log(struct audit_context *ctx, gfp_t gfp_mask, int type,
2364 const char *fmt, ...)
2366 struct audit_buffer *ab;
2367 va_list args;
2369 ab = audit_log_start(ctx, gfp_mask, type);
2370 if (ab) {
2371 va_start(args, fmt);
2372 audit_log_vformat(ab, fmt, args);
2373 va_end(args);
2374 audit_log_end(ab);
2378 #ifdef CONFIG_SECURITY
2380 * audit_log_secctx - Converts and logs SELinux context
2381 * @ab: audit_buffer
2382 * @secid: security number
2384 * This is a helper function that calls security_secid_to_secctx to convert
2385 * secid to secctx and then adds the (converted) SELinux context to the audit
2386 * log by calling audit_log_format, thus also preventing leak of internal secid
2387 * to userspace. If secid cannot be converted audit_panic is called.
2389 void audit_log_secctx(struct audit_buffer *ab, u32 secid)
2391 u32 len;
2392 char *secctx;
2394 if (security_secid_to_secctx(secid, &secctx, &len)) {
2395 audit_panic("Cannot convert secid to context");
2396 } else {
2397 audit_log_format(ab, " obj=%s", secctx);
2398 security_release_secctx(secctx, len);
2401 EXPORT_SYMBOL(audit_log_secctx);
2402 #endif
2404 EXPORT_SYMBOL(audit_log_start);
2405 EXPORT_SYMBOL(audit_log_end);
2406 EXPORT_SYMBOL(audit_log_format);
2407 EXPORT_SYMBOL(audit_log);