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