[PATCH] sem2mutex: audit_netlink_sem
[linux-2.6-block.git] / kernel / audit.c
CommitLineData
85c8721f 1/* audit.c -- Auditing support
1da177e4
LT
2 * Gateway between the kernel (e.g., selinux) and the user-space audit daemon.
3 * System-call specific features have moved to auditsc.c
4 *
5 * Copyright 2003-2004 Red Hat Inc., Durham, North Carolina.
6 * All Rights Reserved.
7 *
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.
12 *
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.
17 *
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
21 *
22 * Written by Rickard E. (Rik) Faith <faith@redhat.com>
23 *
24 * Goals: 1) Integrate fully with SELinux.
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.
40 *
85c8721f 41 * Example user-space utilities: http://people.redhat.com/sgrubb/audit/
1da177e4
LT
42 */
43
44#include <linux/init.h>
1da177e4 45#include <asm/types.h>
715b49ef 46#include <asm/atomic.h>
1da177e4
LT
47#include <linux/mm.h>
48#include <linux/module.h>
b7d11258
DW
49#include <linux/err.h>
50#include <linux/kthread.h>
1da177e4
LT
51
52#include <linux/audit.h>
53
54#include <net/sock.h>
93315ed6 55#include <net/netlink.h>
1da177e4
LT
56#include <linux/skbuff.h>
57#include <linux/netlink.h>
58
59/* No auditing will take place until audit_initialized != 0.
60 * (Initialization happens after skb_init is called.) */
61static int audit_initialized;
62
63/* No syscall auditing will take place unless audit_enabled != 0. */
64int audit_enabled;
65
66/* Default state when kernel boots without any parameters. */
67static int audit_default;
68
69/* If auditing cannot proceed, audit_failure selects what happens. */
70static int audit_failure = AUDIT_FAIL_PRINTK;
71
72/* If audit records are to be written to the netlink socket, audit_pid
73 * contains the (non-zero) pid. */
c2f0c7c3 74int audit_pid;
1da177e4 75
b0dd25a8 76/* If audit_rate_limit is non-zero, limit the rate of sending audit records
1da177e4
LT
77 * to that number per second. This prevents DoS attacks, but results in
78 * audit records being dropped. */
79static int audit_rate_limit;
80
81/* Number of outstanding audit_buffers allowed. */
82static int audit_backlog_limit = 64;
ac4cec44
DW
83static int audit_backlog_wait_time = 60 * HZ;
84static int audit_backlog_wait_overflow = 0;
1da177e4 85
c2f0c7c3
SG
86/* The identity of the user shutting down the audit system. */
87uid_t audit_sig_uid = -1;
88pid_t audit_sig_pid = -1;
89
1da177e4
LT
90/* Records can be lost in several ways:
91 0) [suppressed in audit_alloc]
92 1) out of memory in audit_log_start [kmalloc of struct audit_buffer]
93 2) out of memory in audit_log_move [alloc_skb]
94 3) suppressed due to audit_rate_limit
95 4) suppressed due to audit_backlog_limit
96*/
97static atomic_t audit_lost = ATOMIC_INIT(0);
98
99/* The netlink socket. */
100static struct sock *audit_sock;
101
b7d11258 102/* The audit_freelist is a list of pre-allocated audit buffers (if more
1da177e4
LT
103 * than AUDIT_MAXFREE are in use, the audit buffer is freed instead of
104 * being placed on the freelist). */
1da177e4 105static DEFINE_SPINLOCK(audit_freelist_lock);
b0dd25a8 106static int audit_freelist_count;
1da177e4
LT
107static LIST_HEAD(audit_freelist);
108
b7d11258
DW
109static struct sk_buff_head audit_skb_queue;
110static struct task_struct *kauditd_task;
111static DECLARE_WAIT_QUEUE_HEAD(kauditd_wait);
9ad9ad38 112static DECLARE_WAIT_QUEUE_HEAD(audit_backlog_wait);
1da177e4
LT
113
114/* The netlink socket is only to be read by 1 CPU, which lets us assume
23f32d18 115 * that list additions and deletions never happen simultaneously in
1da177e4 116 * auditsc.c */
5a0bbce5 117DEFINE_MUTEX(audit_netlink_mutex);
1da177e4
LT
118
119/* AUDIT_BUFSIZ is the size of the temporary buffer used for formatting
120 * audit records. Since printk uses a 1024 byte buffer, this buffer
121 * should be at least that large. */
122#define AUDIT_BUFSIZ 1024
123
124/* AUDIT_MAXFREE is the number of empty audit_buffers we keep on the
125 * audit_freelist. Doing so eliminates many kmalloc/kfree calls. */
126#define AUDIT_MAXFREE (2*NR_CPUS)
127
128/* The audit_buffer is used when formatting an audit record. The caller
129 * locks briefly to get the record off the freelist or to allocate the
130 * buffer, and locks briefly to send the buffer to the netlink layer or
131 * to place it on a transmit queue. Multiple audit_buffers can be in
132 * use simultaneously. */
133struct audit_buffer {
134 struct list_head list;
8fc6115c 135 struct sk_buff *skb; /* formatted skb ready to send */
1da177e4 136 struct audit_context *ctx; /* NULL or associated context */
9796fdd8 137 gfp_t gfp_mask;
1da177e4
LT
138};
139
c0404993
SG
140static void audit_set_pid(struct audit_buffer *ab, pid_t pid)
141{
142 struct nlmsghdr *nlh = (struct nlmsghdr *)ab->skb->data;
143 nlh->nlmsg_pid = pid;
144}
145
8c8570fb 146void audit_panic(const char *message)
1da177e4
LT
147{
148 switch (audit_failure)
149 {
150 case AUDIT_FAIL_SILENT:
151 break;
152 case AUDIT_FAIL_PRINTK:
153 printk(KERN_ERR "audit: %s\n", message);
154 break;
155 case AUDIT_FAIL_PANIC:
156 panic("audit: %s\n", message);
157 break;
158 }
159}
160
161static inline int audit_rate_check(void)
162{
163 static unsigned long last_check = 0;
164 static int messages = 0;
165 static DEFINE_SPINLOCK(lock);
166 unsigned long flags;
167 unsigned long now;
168 unsigned long elapsed;
169 int retval = 0;
170
171 if (!audit_rate_limit) return 1;
172
173 spin_lock_irqsave(&lock, flags);
174 if (++messages < audit_rate_limit) {
175 retval = 1;
176 } else {
177 now = jiffies;
178 elapsed = now - last_check;
179 if (elapsed > HZ) {
180 last_check = now;
181 messages = 0;
182 retval = 1;
183 }
184 }
185 spin_unlock_irqrestore(&lock, flags);
186
187 return retval;
188}
189
b0dd25a8
RD
190/**
191 * audit_log_lost - conditionally log lost audit message event
192 * @message: the message stating reason for lost audit message
193 *
194 * Emit at least 1 message per second, even if audit_rate_check is
195 * throttling.
196 * Always increment the lost messages counter.
197*/
1da177e4
LT
198void audit_log_lost(const char *message)
199{
200 static unsigned long last_msg = 0;
201 static DEFINE_SPINLOCK(lock);
202 unsigned long flags;
203 unsigned long now;
204 int print;
205
206 atomic_inc(&audit_lost);
207
208 print = (audit_failure == AUDIT_FAIL_PANIC || !audit_rate_limit);
209
210 if (!print) {
211 spin_lock_irqsave(&lock, flags);
212 now = jiffies;
213 if (now - last_msg > HZ) {
214 print = 1;
215 last_msg = now;
216 }
217 spin_unlock_irqrestore(&lock, flags);
218 }
219
220 if (print) {
221 printk(KERN_WARNING
b7d11258 222 "audit: audit_lost=%d audit_rate_limit=%d audit_backlog_limit=%d\n",
1da177e4 223 atomic_read(&audit_lost),
1da177e4
LT
224 audit_rate_limit,
225 audit_backlog_limit);
226 audit_panic(message);
227 }
1da177e4
LT
228}
229
c94c257c 230static int audit_set_rate_limit(int limit, uid_t loginuid)
1da177e4
LT
231{
232 int old = audit_rate_limit;
233 audit_rate_limit = limit;
9ad9ad38 234 audit_log(NULL, GFP_KERNEL, AUDIT_CONFIG_CHANGE,
bccf6ae0 235 "audit_rate_limit=%d old=%d by auid=%u",
c94c257c 236 audit_rate_limit, old, loginuid);
1da177e4
LT
237 return old;
238}
239
c94c257c 240static int audit_set_backlog_limit(int limit, uid_t loginuid)
1da177e4
LT
241{
242 int old = audit_backlog_limit;
243 audit_backlog_limit = limit;
9ad9ad38 244 audit_log(NULL, GFP_KERNEL, AUDIT_CONFIG_CHANGE,
bccf6ae0 245 "audit_backlog_limit=%d old=%d by auid=%u",
c94c257c 246 audit_backlog_limit, old, loginuid);
1da177e4
LT
247 return old;
248}
249
c94c257c 250static int audit_set_enabled(int state, uid_t loginuid)
1da177e4
LT
251{
252 int old = audit_enabled;
253 if (state != 0 && state != 1)
254 return -EINVAL;
255 audit_enabled = state;
9ad9ad38 256 audit_log(NULL, GFP_KERNEL, AUDIT_CONFIG_CHANGE,
bccf6ae0 257 "audit_enabled=%d old=%d by auid=%u",
c0404993 258 audit_enabled, old, loginuid);
1da177e4
LT
259 return old;
260}
261
c94c257c 262static int audit_set_failure(int state, uid_t loginuid)
1da177e4
LT
263{
264 int old = audit_failure;
265 if (state != AUDIT_FAIL_SILENT
266 && state != AUDIT_FAIL_PRINTK
267 && state != AUDIT_FAIL_PANIC)
268 return -EINVAL;
269 audit_failure = state;
9ad9ad38 270 audit_log(NULL, GFP_KERNEL, AUDIT_CONFIG_CHANGE,
bccf6ae0 271 "audit_failure=%d old=%d by auid=%u",
c0404993 272 audit_failure, old, loginuid);
1da177e4
LT
273 return old;
274}
275
97a41e26 276static int kauditd_thread(void *dummy)
b7d11258
DW
277{
278 struct sk_buff *skb;
279
280 while (1) {
281 skb = skb_dequeue(&audit_skb_queue);
9ad9ad38 282 wake_up(&audit_backlog_wait);
b7d11258
DW
283 if (skb) {
284 if (audit_pid) {
285 int err = netlink_unicast(audit_sock, skb, audit_pid, 0);
286 if (err < 0) {
287 BUG_ON(err != -ECONNREFUSED); /* Shoudn't happen */
288 printk(KERN_ERR "audit: *NO* daemon at audit_pid=%d\n", audit_pid);
289 audit_pid = 0;
290 }
291 } else {
e1b09eba 292 printk(KERN_NOTICE "%s\n", skb->data + NLMSG_SPACE(0));
b7d11258
DW
293 kfree_skb(skb);
294 }
295 } else {
296 DECLARE_WAITQUEUE(wait, current);
297 set_current_state(TASK_INTERRUPTIBLE);
298 add_wait_queue(&kauditd_wait, &wait);
299
7a4ae749
PO
300 if (!skb_queue_len(&audit_skb_queue)) {
301 try_to_freeze();
b7d11258 302 schedule();
7a4ae749 303 }
b7d11258
DW
304
305 __set_current_state(TASK_RUNNING);
306 remove_wait_queue(&kauditd_wait, &wait);
307 }
308 }
fe7752ba 309 return 0;
b7d11258
DW
310}
311
b0dd25a8
RD
312/**
313 * audit_send_reply - send an audit reply message via netlink
314 * @pid: process id to send reply to
315 * @seq: sequence number
316 * @type: audit message type
317 * @done: done (last) flag
318 * @multi: multi-part message flag
319 * @payload: payload data
320 * @size: payload size
321 *
322 * Allocates an skb, builds the netlink message, and sends it to the pid.
323 * No failure notifications.
324 */
1da177e4
LT
325void audit_send_reply(int pid, int seq, int type, int done, int multi,
326 void *payload, int size)
327{
328 struct sk_buff *skb;
329 struct nlmsghdr *nlh;
330 int len = NLMSG_SPACE(size);
331 void *data;
332 int flags = multi ? NLM_F_MULTI : 0;
333 int t = done ? NLMSG_DONE : type;
334
335 skb = alloc_skb(len, GFP_KERNEL);
336 if (!skb)
b7d11258 337 return;
1da177e4 338
b7d11258 339 nlh = NLMSG_PUT(skb, pid, seq, t, size);
1da177e4
LT
340 nlh->nlmsg_flags = flags;
341 data = NLMSG_DATA(nlh);
342 memcpy(data, payload, size);
b7d11258
DW
343
344 /* Ignore failure. It'll only happen if the sender goes away,
345 because our timeout is set to infinite. */
346 netlink_unicast(audit_sock, skb, pid, 0);
1da177e4
LT
347 return;
348
349nlmsg_failure: /* Used by NLMSG_PUT */
350 if (skb)
351 kfree_skb(skb);
352}
353
354/*
355 * Check for appropriate CAP_AUDIT_ capabilities on incoming audit
356 * control messages.
357 */
358static int audit_netlink_ok(kernel_cap_t eff_cap, u16 msg_type)
359{
360 int err = 0;
361
362 switch (msg_type) {
363 case AUDIT_GET:
364 case AUDIT_LIST:
93315ed6 365 case AUDIT_LIST_RULES:
1da177e4
LT
366 case AUDIT_SET:
367 case AUDIT_ADD:
93315ed6 368 case AUDIT_ADD_RULE:
1da177e4 369 case AUDIT_DEL:
93315ed6 370 case AUDIT_DEL_RULE:
c2f0c7c3 371 case AUDIT_SIGNAL_INFO:
1da177e4
LT
372 if (!cap_raised(eff_cap, CAP_AUDIT_CONTROL))
373 err = -EPERM;
374 break;
05474106 375 case AUDIT_USER:
209aba03 376 case AUDIT_FIRST_USER_MSG...AUDIT_LAST_USER_MSG:
90d526c0 377 case AUDIT_FIRST_USER_MSG2...AUDIT_LAST_USER_MSG2:
1da177e4
LT
378 if (!cap_raised(eff_cap, CAP_AUDIT_WRITE))
379 err = -EPERM;
380 break;
381 default: /* bad msg */
382 err = -EINVAL;
383 }
384
385 return err;
386}
387
388static int audit_receive_msg(struct sk_buff *skb, struct nlmsghdr *nlh)
389{
390 u32 uid, pid, seq;
391 void *data;
392 struct audit_status *status_get, status_set;
393 int err;
c0404993 394 struct audit_buffer *ab;
1da177e4 395 u16 msg_type = nlh->nlmsg_type;
c94c257c 396 uid_t loginuid; /* loginuid of sender */
c2f0c7c3 397 struct audit_sig_info sig_data;
1da177e4
LT
398
399 err = audit_netlink_ok(NETLINK_CB(skb).eff_cap, msg_type);
400 if (err)
401 return err;
402
b0dd25a8
RD
403 /* As soon as there's any sign of userspace auditd,
404 * start kauditd to talk to it */
b7d11258
DW
405 if (!kauditd_task)
406 kauditd_task = kthread_run(kauditd_thread, NULL, "kauditd");
407 if (IS_ERR(kauditd_task)) {
408 err = PTR_ERR(kauditd_task);
409 kauditd_task = NULL;
410 return err;
411 }
412
1da177e4
LT
413 pid = NETLINK_CREDS(skb)->pid;
414 uid = NETLINK_CREDS(skb)->uid;
c94c257c 415 loginuid = NETLINK_CB(skb).loginuid;
1da177e4
LT
416 seq = nlh->nlmsg_seq;
417 data = NLMSG_DATA(nlh);
418
419 switch (msg_type) {
420 case AUDIT_GET:
421 status_set.enabled = audit_enabled;
422 status_set.failure = audit_failure;
423 status_set.pid = audit_pid;
424 status_set.rate_limit = audit_rate_limit;
425 status_set.backlog_limit = audit_backlog_limit;
426 status_set.lost = atomic_read(&audit_lost);
b7d11258 427 status_set.backlog = skb_queue_len(&audit_skb_queue);
1da177e4
LT
428 audit_send_reply(NETLINK_CB(skb).pid, seq, AUDIT_GET, 0, 0,
429 &status_set, sizeof(status_set));
430 break;
431 case AUDIT_SET:
432 if (nlh->nlmsg_len < sizeof(struct audit_status))
433 return -EINVAL;
434 status_get = (struct audit_status *)data;
435 if (status_get->mask & AUDIT_STATUS_ENABLED) {
c94c257c 436 err = audit_set_enabled(status_get->enabled, loginuid);
1da177e4
LT
437 if (err < 0) return err;
438 }
439 if (status_get->mask & AUDIT_STATUS_FAILURE) {
c94c257c 440 err = audit_set_failure(status_get->failure, loginuid);
1da177e4
LT
441 if (err < 0) return err;
442 }
443 if (status_get->mask & AUDIT_STATUS_PID) {
444 int old = audit_pid;
445 audit_pid = status_get->pid;
9ad9ad38 446 audit_log(NULL, GFP_KERNEL, AUDIT_CONFIG_CHANGE,
bccf6ae0 447 "audit_pid=%d old=%d by auid=%u",
c94c257c 448 audit_pid, old, loginuid);
1da177e4
LT
449 }
450 if (status_get->mask & AUDIT_STATUS_RATE_LIMIT)
c94c257c 451 audit_set_rate_limit(status_get->rate_limit, loginuid);
1da177e4 452 if (status_get->mask & AUDIT_STATUS_BACKLOG_LIMIT)
c94c257c
SH
453 audit_set_backlog_limit(status_get->backlog_limit,
454 loginuid);
1da177e4 455 break;
05474106 456 case AUDIT_USER:
209aba03 457 case AUDIT_FIRST_USER_MSG...AUDIT_LAST_USER_MSG:
90d526c0 458 case AUDIT_FIRST_USER_MSG2...AUDIT_LAST_USER_MSG2:
4a4cd633
DW
459 if (!audit_enabled && msg_type != AUDIT_USER_AVC)
460 return 0;
461
5bb289b5 462 err = audit_filter_user(&NETLINK_CB(skb), msg_type);
4a4cd633
DW
463 if (err == 1) {
464 err = 0;
9ad9ad38 465 ab = audit_log_start(NULL, GFP_KERNEL, msg_type);
4a4cd633
DW
466 if (ab) {
467 audit_log_format(ab,
468 "user pid=%d uid=%u auid=%u msg='%.1024s'",
469 pid, uid, loginuid, (char *)data);
470 audit_set_pid(ab, pid);
471 audit_log_end(ab);
472 }
0f45aa18 473 }
1da177e4
LT
474 break;
475 case AUDIT_ADD:
476 case AUDIT_DEL:
93315ed6 477 if (nlmsg_len(nlh) < sizeof(struct audit_rule))
1da177e4
LT
478 return -EINVAL;
479 /* fallthrough */
480 case AUDIT_LIST:
1da177e4 481 err = audit_receive_filter(nlh->nlmsg_type, NETLINK_CB(skb).pid,
93315ed6
AG
482 uid, seq, data, nlmsg_len(nlh),
483 loginuid);
484 break;
485 case AUDIT_ADD_RULE:
486 case AUDIT_DEL_RULE:
487 if (nlmsg_len(nlh) < sizeof(struct audit_rule_data))
488 return -EINVAL;
489 /* fallthrough */
490 case AUDIT_LIST_RULES:
491 err = audit_receive_filter(nlh->nlmsg_type, NETLINK_CB(skb).pid,
492 uid, seq, data, nlmsg_len(nlh),
493 loginuid);
1da177e4 494 break;
c2f0c7c3
SG
495 case AUDIT_SIGNAL_INFO:
496 sig_data.uid = audit_sig_uid;
497 sig_data.pid = audit_sig_pid;
498 audit_send_reply(NETLINK_CB(skb).pid, seq, AUDIT_SIGNAL_INFO,
499 0, 0, &sig_data, sizeof(sig_data));
500 break;
1da177e4
LT
501 default:
502 err = -EINVAL;
503 break;
504 }
505
506 return err < 0 ? err : 0;
507}
508
b0dd25a8
RD
509/*
510 * Get message from skb (based on rtnetlink_rcv_skb). Each message is
1da177e4 511 * processed by audit_receive_msg. Malformed skbs with wrong length are
b0dd25a8
RD
512 * discarded silently.
513 */
2a0a6ebe 514static void audit_receive_skb(struct sk_buff *skb)
1da177e4
LT
515{
516 int err;
517 struct nlmsghdr *nlh;
518 u32 rlen;
519
520 while (skb->len >= NLMSG_SPACE(0)) {
521 nlh = (struct nlmsghdr *)skb->data;
522 if (nlh->nlmsg_len < sizeof(*nlh) || skb->len < nlh->nlmsg_len)
2a0a6ebe 523 return;
1da177e4
LT
524 rlen = NLMSG_ALIGN(nlh->nlmsg_len);
525 if (rlen > skb->len)
526 rlen = skb->len;
527 if ((err = audit_receive_msg(skb, nlh))) {
528 netlink_ack(skb, nlh, err);
529 } else if (nlh->nlmsg_flags & NLM_F_ACK)
530 netlink_ack(skb, nlh, 0);
531 skb_pull(skb, rlen);
532 }
1da177e4
LT
533}
534
535/* Receive messages from netlink socket. */
536static void audit_receive(struct sock *sk, int length)
537{
538 struct sk_buff *skb;
2a0a6ebe 539 unsigned int qlen;
1da177e4 540
5a0bbce5 541 mutex_lock(&audit_netlink_mutex);
1da177e4 542
2a0a6ebe
HX
543 for (qlen = skb_queue_len(&sk->sk_receive_queue); qlen; qlen--) {
544 skb = skb_dequeue(&sk->sk_receive_queue);
545 audit_receive_skb(skb);
546 kfree_skb(skb);
1da177e4 547 }
5a0bbce5 548 mutex_unlock(&audit_netlink_mutex);
1da177e4
LT
549}
550
1da177e4
LT
551
552/* Initialize audit support at boot time. */
553static int __init audit_init(void)
554{
555 printk(KERN_INFO "audit: initializing netlink socket (%s)\n",
556 audit_default ? "enabled" : "disabled");
06628607 557 audit_sock = netlink_kernel_create(NETLINK_AUDIT, 0, audit_receive,
4fdb3bb7 558 THIS_MODULE);
1da177e4
LT
559 if (!audit_sock)
560 audit_panic("cannot initialize netlink socket");
561
b7d11258
DW
562 audit_sock->sk_sndtimeo = MAX_SCHEDULE_TIMEOUT;
563 skb_queue_head_init(&audit_skb_queue);
1da177e4
LT
564 audit_initialized = 1;
565 audit_enabled = audit_default;
9ad9ad38 566 audit_log(NULL, GFP_KERNEL, AUDIT_KERNEL, "initialized");
1da177e4
LT
567 return 0;
568}
1da177e4
LT
569__initcall(audit_init);
570
571/* Process kernel command-line parameter at boot time. audit=0 or audit=1. */
572static int __init audit_enable(char *str)
573{
574 audit_default = !!simple_strtol(str, NULL, 0);
575 printk(KERN_INFO "audit: %s%s\n",
576 audit_default ? "enabled" : "disabled",
577 audit_initialized ? "" : " (after initialization)");
578 if (audit_initialized)
579 audit_enabled = audit_default;
580 return 0;
581}
582
583__setup("audit=", audit_enable);
584
16e1904e
CW
585static void audit_buffer_free(struct audit_buffer *ab)
586{
587 unsigned long flags;
588
8fc6115c
CW
589 if (!ab)
590 return;
591
5ac52f33
CW
592 if (ab->skb)
593 kfree_skb(ab->skb);
b7d11258 594
16e1904e
CW
595 spin_lock_irqsave(&audit_freelist_lock, flags);
596 if (++audit_freelist_count > AUDIT_MAXFREE)
597 kfree(ab);
598 else
599 list_add(&ab->list, &audit_freelist);
600 spin_unlock_irqrestore(&audit_freelist_lock, flags);
601}
602
c0404993 603static struct audit_buffer * audit_buffer_alloc(struct audit_context *ctx,
dd0fc66f 604 gfp_t gfp_mask, int type)
16e1904e
CW
605{
606 unsigned long flags;
607 struct audit_buffer *ab = NULL;
c0404993 608 struct nlmsghdr *nlh;
16e1904e
CW
609
610 spin_lock_irqsave(&audit_freelist_lock, flags);
611 if (!list_empty(&audit_freelist)) {
612 ab = list_entry(audit_freelist.next,
613 struct audit_buffer, list);
614 list_del(&ab->list);
615 --audit_freelist_count;
616 }
617 spin_unlock_irqrestore(&audit_freelist_lock, flags);
618
619 if (!ab) {
4332bdd3 620 ab = kmalloc(sizeof(*ab), gfp_mask);
16e1904e 621 if (!ab)
8fc6115c 622 goto err;
16e1904e 623 }
8fc6115c 624
4332bdd3 625 ab->skb = alloc_skb(AUDIT_BUFSIZ, gfp_mask);
5ac52f33 626 if (!ab->skb)
8fc6115c
CW
627 goto err;
628
b7d11258 629 ab->ctx = ctx;
9ad9ad38 630 ab->gfp_mask = gfp_mask;
c0404993
SG
631 nlh = (struct nlmsghdr *)skb_put(ab->skb, NLMSG_SPACE(0));
632 nlh->nlmsg_type = type;
633 nlh->nlmsg_flags = 0;
634 nlh->nlmsg_pid = 0;
635 nlh->nlmsg_seq = 0;
16e1904e 636 return ab;
8fc6115c
CW
637err:
638 audit_buffer_free(ab);
639 return NULL;
16e1904e 640}
1da177e4 641
b0dd25a8
RD
642/**
643 * audit_serial - compute a serial number for the audit record
644 *
645 * Compute a serial number for the audit record. Audit records are
bfb4496e
DW
646 * written to user-space as soon as they are generated, so a complete
647 * audit record may be written in several pieces. The timestamp of the
648 * record and this serial number are used by the user-space tools to
649 * determine which pieces belong to the same audit record. The
650 * (timestamp,serial) tuple is unique for each syscall and is live from
651 * syscall entry to syscall exit.
652 *
bfb4496e
DW
653 * NOTE: Another possibility is to store the formatted records off the
654 * audit context (for those records that have a context), and emit them
655 * all at syscall exit. However, this could delay the reporting of
656 * significant errors until syscall exit (or never, if the system
b0dd25a8
RD
657 * halts).
658 */
bfb4496e
DW
659unsigned int audit_serial(void)
660{
d5b454f2
DW
661 static spinlock_t serial_lock = SPIN_LOCK_UNLOCKED;
662 static unsigned int serial = 0;
663
664 unsigned long flags;
665 unsigned int ret;
bfb4496e 666
d5b454f2 667 spin_lock_irqsave(&serial_lock, flags);
bfb4496e 668 do {
ce625a80
DW
669 ret = ++serial;
670 } while (unlikely(!ret));
d5b454f2 671 spin_unlock_irqrestore(&serial_lock, flags);
bfb4496e 672
d5b454f2 673 return ret;
bfb4496e
DW
674}
675
676static inline void audit_get_stamp(struct audit_context *ctx,
677 struct timespec *t, unsigned int *serial)
678{
679 if (ctx)
680 auditsc_get_stamp(ctx, t, serial);
681 else {
682 *t = CURRENT_TIME;
683 *serial = audit_serial();
684 }
685}
686
1da177e4
LT
687/* Obtain an audit buffer. This routine does locking to obtain the
688 * audit buffer, but then no locking is required for calls to
689 * audit_log_*format. If the tsk is a task that is currently in a
690 * syscall, then the syscall is marked as auditable and an audit record
691 * will be written at syscall exit. If there is no associated task, tsk
692 * should be NULL. */
9ad9ad38 693
b0dd25a8
RD
694/**
695 * audit_log_start - obtain an audit buffer
696 * @ctx: audit_context (may be NULL)
697 * @gfp_mask: type of allocation
698 * @type: audit message type
699 *
700 * Returns audit_buffer pointer on success or NULL on error.
701 *
702 * Obtain an audit buffer. This routine does locking to obtain the
703 * audit buffer, but then no locking is required for calls to
704 * audit_log_*format. If the task (ctx) is a task that is currently in a
705 * syscall, then the syscall is marked as auditable and an audit record
706 * will be written at syscall exit. If there is no associated task, then
707 * task context (ctx) should be NULL.
708 */
9796fdd8 709struct audit_buffer *audit_log_start(struct audit_context *ctx, gfp_t gfp_mask,
9ad9ad38 710 int type)
1da177e4
LT
711{
712 struct audit_buffer *ab = NULL;
1da177e4 713 struct timespec t;
d812ddbb 714 unsigned int serial;
9ad9ad38 715 int reserve;
ac4cec44 716 unsigned long timeout_start = jiffies;
1da177e4
LT
717
718 if (!audit_initialized)
719 return NULL;
720
c8edc80c
DK
721 if (unlikely(audit_filter_type(type)))
722 return NULL;
723
9ad9ad38
DW
724 if (gfp_mask & __GFP_WAIT)
725 reserve = 0;
726 else
727 reserve = 5; /* Allow atomic callers to go up to five
728 entries over the normal backlog limit */
729
730 while (audit_backlog_limit
731 && skb_queue_len(&audit_skb_queue) > audit_backlog_limit + reserve) {
ac4cec44
DW
732 if (gfp_mask & __GFP_WAIT && audit_backlog_wait_time
733 && time_before(jiffies, timeout_start + audit_backlog_wait_time)) {
734
9ad9ad38
DW
735 /* Wait for auditd to drain the queue a little */
736 DECLARE_WAITQUEUE(wait, current);
737 set_current_state(TASK_INTERRUPTIBLE);
738 add_wait_queue(&audit_backlog_wait, &wait);
739
740 if (audit_backlog_limit &&
741 skb_queue_len(&audit_skb_queue) > audit_backlog_limit)
ac4cec44 742 schedule_timeout(timeout_start + audit_backlog_wait_time - jiffies);
9ad9ad38
DW
743
744 __set_current_state(TASK_RUNNING);
745 remove_wait_queue(&audit_backlog_wait, &wait);
ac4cec44 746 continue;
9ad9ad38 747 }
fb19b4c6
DW
748 if (audit_rate_check())
749 printk(KERN_WARNING
750 "audit: audit_backlog=%d > "
751 "audit_backlog_limit=%d\n",
752 skb_queue_len(&audit_skb_queue),
753 audit_backlog_limit);
754 audit_log_lost("backlog limit exceeded");
ac4cec44
DW
755 audit_backlog_wait_time = audit_backlog_wait_overflow;
756 wake_up(&audit_backlog_wait);
fb19b4c6
DW
757 return NULL;
758 }
759
9ad9ad38 760 ab = audit_buffer_alloc(ctx, gfp_mask, type);
1da177e4
LT
761 if (!ab) {
762 audit_log_lost("out of memory in audit_log_start");
763 return NULL;
764 }
765
bfb4496e 766 audit_get_stamp(ab->ctx, &t, &serial);
197c69c6 767
1da177e4
LT
768 audit_log_format(ab, "audit(%lu.%03lu:%u): ",
769 t.tv_sec, t.tv_nsec/1000000, serial);
770 return ab;
771}
772
8fc6115c 773/**
5ac52f33 774 * audit_expand - expand skb in the audit buffer
8fc6115c 775 * @ab: audit_buffer
b0dd25a8 776 * @extra: space to add at tail of the skb
8fc6115c
CW
777 *
778 * Returns 0 (no space) on failed expansion, or available space if
779 * successful.
780 */
e3b926b4 781static inline int audit_expand(struct audit_buffer *ab, int extra)
8fc6115c 782{
5ac52f33 783 struct sk_buff *skb = ab->skb;
e3b926b4 784 int ret = pskb_expand_head(skb, skb_headroom(skb), extra,
9ad9ad38 785 ab->gfp_mask);
5ac52f33
CW
786 if (ret < 0) {
787 audit_log_lost("out of memory in audit_expand");
8fc6115c 788 return 0;
5ac52f33
CW
789 }
790 return skb_tailroom(skb);
8fc6115c 791}
1da177e4 792
b0dd25a8
RD
793/*
794 * Format an audit message into the audit buffer. If there isn't enough
1da177e4
LT
795 * room in the audit buffer, more room will be allocated and vsnprint
796 * will be called a second time. Currently, we assume that a printk
b0dd25a8
RD
797 * can't format message larger than 1024 bytes, so we don't either.
798 */
1da177e4
LT
799static void audit_log_vformat(struct audit_buffer *ab, const char *fmt,
800 va_list args)
801{
802 int len, avail;
5ac52f33 803 struct sk_buff *skb;
eecb0a73 804 va_list args2;
1da177e4
LT
805
806 if (!ab)
807 return;
808
5ac52f33
CW
809 BUG_ON(!ab->skb);
810 skb = ab->skb;
811 avail = skb_tailroom(skb);
812 if (avail == 0) {
e3b926b4 813 avail = audit_expand(ab, AUDIT_BUFSIZ);
8fc6115c
CW
814 if (!avail)
815 goto out;
1da177e4 816 }
eecb0a73 817 va_copy(args2, args);
5ac52f33 818 len = vsnprintf(skb->tail, avail, fmt, args);
1da177e4
LT
819 if (len >= avail) {
820 /* The printk buffer is 1024 bytes long, so if we get
821 * here and AUDIT_BUFSIZ is at least 1024, then we can
822 * log everything that printk could have logged. */
b0dd25a8
RD
823 avail = audit_expand(ab,
824 max_t(unsigned, AUDIT_BUFSIZ, 1+len-avail));
8fc6115c
CW
825 if (!avail)
826 goto out;
eecb0a73 827 len = vsnprintf(skb->tail, avail, fmt, args2);
1da177e4 828 }
168b7173
SG
829 if (len > 0)
830 skb_put(skb, len);
8fc6115c
CW
831out:
832 return;
1da177e4
LT
833}
834
b0dd25a8
RD
835/**
836 * audit_log_format - format a message into the audit buffer.
837 * @ab: audit_buffer
838 * @fmt: format string
839 * @...: optional parameters matching @fmt string
840 *
841 * All the work is done in audit_log_vformat.
842 */
1da177e4
LT
843void audit_log_format(struct audit_buffer *ab, const char *fmt, ...)
844{
845 va_list args;
846
847 if (!ab)
848 return;
849 va_start(args, fmt);
850 audit_log_vformat(ab, fmt, args);
851 va_end(args);
852}
853
b0dd25a8
RD
854/**
855 * audit_log_hex - convert a buffer to hex and append it to the audit skb
856 * @ab: the audit_buffer
857 * @buf: buffer to convert to hex
858 * @len: length of @buf to be converted
859 *
860 * No return value; failure to expand is silently ignored.
861 *
862 * This function will take the passed buf and convert it into a string of
863 * ascii hex digits. The new string is placed onto the skb.
864 */
865void audit_log_hex(struct audit_buffer *ab, const unsigned char *buf,
168b7173 866 size_t len)
83c7d091 867{
168b7173
SG
868 int i, avail, new_len;
869 unsigned char *ptr;
870 struct sk_buff *skb;
871 static const unsigned char *hex = "0123456789ABCDEF";
872
873 BUG_ON(!ab->skb);
874 skb = ab->skb;
875 avail = skb_tailroom(skb);
876 new_len = len<<1;
877 if (new_len >= avail) {
878 /* Round the buffer request up to the next multiple */
879 new_len = AUDIT_BUFSIZ*(((new_len-avail)/AUDIT_BUFSIZ) + 1);
880 avail = audit_expand(ab, new_len);
881 if (!avail)
882 return;
883 }
83c7d091 884
168b7173
SG
885 ptr = skb->tail;
886 for (i=0; i<len; i++) {
887 *ptr++ = hex[(buf[i] & 0xF0)>>4]; /* Upper nibble */
888 *ptr++ = hex[buf[i] & 0x0F]; /* Lower nibble */
889 }
890 *ptr = 0;
891 skb_put(skb, len << 1); /* new string is twice the old string */
83c7d091 892}
893
b0dd25a8
RD
894/**
895 * audit_log_unstrustedstring - log a string that may contain random characters
896 * @ab: audit_buffer
897 * @string: string to be logged
898 *
899 * This code will escape a string that is passed to it if the string
900 * contains a control character, unprintable character, double quote mark,
168b7173 901 * or a space. Unescaped strings will start and end with a double quote mark.
b0dd25a8
RD
902 * Strings that are escaped are printed in hex (2 digits per char).
903 */
83c7d091 904void audit_log_untrustedstring(struct audit_buffer *ab, const char *string)
905{
81b7854d 906 const unsigned char *p = string;
83c7d091 907
908 while (*p) {
168b7173 909 if (*p == '"' || *p < 0x21 || *p > 0x7f) {
83c7d091 910 audit_log_hex(ab, string, strlen(string));
911 return;
912 }
913 p++;
914 }
915 audit_log_format(ab, "\"%s\"", string);
916}
917
168b7173 918/* This is a helper-function to print the escaped d_path */
1da177e4
LT
919void audit_log_d_path(struct audit_buffer *ab, const char *prefix,
920 struct dentry *dentry, struct vfsmount *vfsmnt)
921{
168b7173 922 char *p, *path;
1da177e4 923
8fc6115c
CW
924 if (prefix)
925 audit_log_format(ab, " %s", prefix);
1da177e4 926
168b7173 927 /* We will allow 11 spaces for ' (deleted)' to be appended */
9ad9ad38 928 path = kmalloc(PATH_MAX+11, ab->gfp_mask);
168b7173
SG
929 if (!path) {
930 audit_log_format(ab, "<no memory>");
931 return;
1da177e4 932 }
168b7173
SG
933 p = d_path(dentry, vfsmnt, path, PATH_MAX+11);
934 if (IS_ERR(p)) { /* Should never happen since we send PATH_MAX */
935 /* FIXME: can we save some information here? */
936 audit_log_format(ab, "<too long>");
937 } else
938 audit_log_untrustedstring(ab, p);
939 kfree(path);
1da177e4
LT
940}
941
b0dd25a8
RD
942/**
943 * audit_log_end - end one audit record
944 * @ab: the audit_buffer
945 *
946 * The netlink_* functions cannot be called inside an irq context, so
947 * the audit buffer is placed on a queue and a tasklet is scheduled to
1da177e4 948 * remove them from the queue outside the irq context. May be called in
b0dd25a8
RD
949 * any context.
950 */
b7d11258 951void audit_log_end(struct audit_buffer *ab)
1da177e4 952{
1da177e4
LT
953 if (!ab)
954 return;
955 if (!audit_rate_check()) {
956 audit_log_lost("rate limit exceeded");
957 } else {
b7d11258
DW
958 if (audit_pid) {
959 struct nlmsghdr *nlh = (struct nlmsghdr *)ab->skb->data;
960 nlh->nlmsg_len = ab->skb->len - NLMSG_SPACE(0);
961 skb_queue_tail(&audit_skb_queue, ab->skb);
962 ab->skb = NULL;
963 wake_up_interruptible(&kauditd_wait);
964 } else {
e1b09eba 965 printk(KERN_NOTICE "%s\n", ab->skb->data + NLMSG_SPACE(0));
b7d11258 966 }
1da177e4 967 }
16e1904e 968 audit_buffer_free(ab);
1da177e4
LT
969}
970
b0dd25a8
RD
971/**
972 * audit_log - Log an audit record
973 * @ctx: audit context
974 * @gfp_mask: type of allocation
975 * @type: audit message type
976 * @fmt: format string to use
977 * @...: variable parameters matching the format string
978 *
979 * This is a convenience function that calls audit_log_start,
980 * audit_log_vformat, and audit_log_end. It may be called
981 * in any context.
982 */
9796fdd8 983void audit_log(struct audit_context *ctx, gfp_t gfp_mask, int type,
9ad9ad38 984 const char *fmt, ...)
1da177e4
LT
985{
986 struct audit_buffer *ab;
987 va_list args;
988
9ad9ad38 989 ab = audit_log_start(ctx, gfp_mask, type);
1da177e4
LT
990 if (ab) {
991 va_start(args, fmt);
992 audit_log_vformat(ab, fmt, args);
993 va_end(args);
994 audit_log_end(ab);
995 }
996}