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