[PATCH] Don't pass boot parameters to argv_init[]
[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/types.h>
46 #include <asm/atomic.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 <net/netlink.h>
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.) */
61 static int      audit_initialized;
62
63 /* No syscall auditing will take place unless audit_enabled != 0. */
64 int             audit_enabled;
65
66 /* Default state when kernel boots without any parameters. */
67 static int      audit_default;
68
69 /* If auditing cannot proceed, audit_failure selects what happens. */
70 static 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. */
74 int             audit_pid;
75
76 /* If audit_rate_limit is non-zero, limit the rate of sending audit records
77  * to that number per second.  This prevents DoS attacks, but results in
78  * audit records being dropped. */
79 static int      audit_rate_limit;
80
81 /* Number of outstanding audit_buffers allowed. */
82 static int      audit_backlog_limit = 64;
83 static int      audit_backlog_wait_time = 60 * HZ;
84 static int      audit_backlog_wait_overflow = 0;
85
86 /* The identity of the user shutting down the audit system. */
87 uid_t           audit_sig_uid = -1;
88 pid_t           audit_sig_pid = -1;
89
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 */
97 static atomic_t    audit_lost = ATOMIC_INIT(0);
98
99 /* The netlink socket. */
100 static struct sock *audit_sock;
101
102 /* The audit_freelist 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_freelist_lock);
106 static int         audit_freelist_count;
107 static LIST_HEAD(audit_freelist);
108
109 static struct sk_buff_head audit_skb_queue;
110 static struct task_struct *kauditd_task;
111 static DECLARE_WAIT_QUEUE_HEAD(kauditd_wait);
112 static DECLARE_WAIT_QUEUE_HEAD(audit_backlog_wait);
113
114 /* The netlink socket is only to be read by 1 CPU, which lets us assume
115  * that list additions and deletions never happen simultaneously in
116  * auditsc.c */
117 DEFINE_MUTEX(audit_netlink_mutex);
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. */
133 struct audit_buffer {
134         struct list_head     list;
135         struct sk_buff       *skb;      /* formatted skb ready to send */
136         struct audit_context *ctx;      /* NULL or associated context */
137         gfp_t                gfp_mask;
138 };
139
140 static 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
146 void audit_panic(const char *message)
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
161 static 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
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 */
198 void 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
222                        "audit: audit_lost=%d audit_rate_limit=%d audit_backlog_limit=%d\n",
223                        atomic_read(&audit_lost),
224                        audit_rate_limit,
225                        audit_backlog_limit);
226                 audit_panic(message);
227         }
228 }
229
230 static int audit_set_rate_limit(int limit, uid_t loginuid)
231 {
232         int old          = audit_rate_limit;
233         audit_rate_limit = limit;
234         audit_log(NULL, GFP_KERNEL, AUDIT_CONFIG_CHANGE, 
235                         "audit_rate_limit=%d old=%d by auid=%u",
236                         audit_rate_limit, old, loginuid);
237         return old;
238 }
239
240 static int audit_set_backlog_limit(int limit, uid_t loginuid)
241 {
242         int old          = audit_backlog_limit;
243         audit_backlog_limit = limit;
244         audit_log(NULL, GFP_KERNEL, AUDIT_CONFIG_CHANGE,
245                         "audit_backlog_limit=%d old=%d by auid=%u",
246                         audit_backlog_limit, old, loginuid);
247         return old;
248 }
249
250 static int audit_set_enabled(int state, uid_t loginuid)
251 {
252         int old          = audit_enabled;
253         if (state != 0 && state != 1)
254                 return -EINVAL;
255         audit_enabled = state;
256         audit_log(NULL, GFP_KERNEL, AUDIT_CONFIG_CHANGE,
257                         "audit_enabled=%d old=%d by auid=%u",
258                         audit_enabled, old, loginuid);
259         return old;
260 }
261
262 static int audit_set_failure(int state, uid_t loginuid)
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;
270         audit_log(NULL, GFP_KERNEL, AUDIT_CONFIG_CHANGE,
271                         "audit_failure=%d old=%d by auid=%u",
272                         audit_failure, old, loginuid);
273         return old;
274 }
275
276 static int kauditd_thread(void *dummy)
277 {
278         struct sk_buff *skb;
279
280         while (1) {
281                 skb = skb_dequeue(&audit_skb_queue);
282                 wake_up(&audit_backlog_wait);
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 {
292                                 printk(KERN_NOTICE "%s\n", skb->data + NLMSG_SPACE(0));
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
300                         if (!skb_queue_len(&audit_skb_queue)) {
301                                 try_to_freeze();
302                                 schedule();
303                         }
304
305                         __set_current_state(TASK_RUNNING);
306                         remove_wait_queue(&kauditd_wait, &wait);
307                 }
308         }
309         return 0;
310 }
311
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  */
325 void 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)
337                 return;
338
339         nlh              = NLMSG_PUT(skb, pid, seq, t, size);
340         nlh->nlmsg_flags = flags;
341         data             = NLMSG_DATA(nlh);
342         memcpy(data, payload, size);
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);
347         return;
348
349 nlmsg_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  */
358 static 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:
365         case AUDIT_LIST_RULES:
366         case AUDIT_SET:
367         case AUDIT_ADD:
368         case AUDIT_ADD_RULE:
369         case AUDIT_DEL:
370         case AUDIT_DEL_RULE:
371         case AUDIT_SIGNAL_INFO:
372                 if (!cap_raised(eff_cap, CAP_AUDIT_CONTROL))
373                         err = -EPERM;
374                 break;
375         case AUDIT_USER:
376         case AUDIT_FIRST_USER_MSG...AUDIT_LAST_USER_MSG:
377         case AUDIT_FIRST_USER_MSG2...AUDIT_LAST_USER_MSG2:
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
388 static 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;
394         struct audit_buffer     *ab;
395         u16                     msg_type = nlh->nlmsg_type;
396         uid_t                   loginuid; /* loginuid of sender */
397         struct audit_sig_info   sig_data;
398
399         err = audit_netlink_ok(NETLINK_CB(skb).eff_cap, msg_type);
400         if (err)
401                 return err;
402
403         /* As soon as there's any sign of userspace auditd,
404          * start kauditd to talk to it */
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
413         pid  = NETLINK_CREDS(skb)->pid;
414         uid  = NETLINK_CREDS(skb)->uid;
415         loginuid = NETLINK_CB(skb).loginuid;
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);
427                 status_set.backlog       = skb_queue_len(&audit_skb_queue);
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) {
436                         err = audit_set_enabled(status_get->enabled, loginuid);
437                         if (err < 0) return err;
438                 }
439                 if (status_get->mask & AUDIT_STATUS_FAILURE) {
440                         err = audit_set_failure(status_get->failure, loginuid);
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;
446                         audit_log(NULL, GFP_KERNEL, AUDIT_CONFIG_CHANGE,
447                                 "audit_pid=%d old=%d by auid=%u",
448                                   audit_pid, old, loginuid);
449                 }
450                 if (status_get->mask & AUDIT_STATUS_RATE_LIMIT)
451                         audit_set_rate_limit(status_get->rate_limit, loginuid);
452                 if (status_get->mask & AUDIT_STATUS_BACKLOG_LIMIT)
453                         audit_set_backlog_limit(status_get->backlog_limit,
454                                                         loginuid);
455                 break;
456         case AUDIT_USER:
457         case AUDIT_FIRST_USER_MSG...AUDIT_LAST_USER_MSG:
458         case AUDIT_FIRST_USER_MSG2...AUDIT_LAST_USER_MSG2:
459                 if (!audit_enabled && msg_type != AUDIT_USER_AVC)
460                         return 0;
461
462                 err = audit_filter_user(&NETLINK_CB(skb), msg_type);
463                 if (err == 1) {
464                         err = 0;
465                         ab = audit_log_start(NULL, GFP_KERNEL, msg_type);
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                         }
473                 }
474                 break;
475         case AUDIT_ADD:
476         case AUDIT_DEL:
477                 if (nlmsg_len(nlh) < sizeof(struct audit_rule))
478                         return -EINVAL;
479                 /* fallthrough */
480         case AUDIT_LIST:
481                 err = audit_receive_filter(nlh->nlmsg_type, NETLINK_CB(skb).pid,
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);
494                 break;
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;
501         default:
502                 err = -EINVAL;
503                 break;
504         }
505
506         return err < 0 ? err : 0;
507 }
508
509 /*
510  * Get message from skb (based on rtnetlink_rcv_skb).  Each message is
511  * processed by audit_receive_msg.  Malformed skbs with wrong length are
512  * discarded silently.
513  */
514 static void audit_receive_skb(struct sk_buff *skb)
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)
523                         return;
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         }
533 }
534
535 /* Receive messages from netlink socket. */
536 static void audit_receive(struct sock *sk, int length)
537 {
538         struct sk_buff  *skb;
539         unsigned int qlen;
540
541         mutex_lock(&audit_netlink_mutex);
542
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);
547         }
548         mutex_unlock(&audit_netlink_mutex);
549 }
550
551
552 /* Initialize audit support at boot time. */
553 static int __init audit_init(void)
554 {
555         printk(KERN_INFO "audit: initializing netlink socket (%s)\n",
556                audit_default ? "enabled" : "disabled");
557         audit_sock = netlink_kernel_create(NETLINK_AUDIT, 0, audit_receive,
558                                            THIS_MODULE);
559         if (!audit_sock)
560                 audit_panic("cannot initialize netlink socket");
561         else
562                 audit_sock->sk_sndtimeo = MAX_SCHEDULE_TIMEOUT;
563
564         skb_queue_head_init(&audit_skb_queue);
565         audit_initialized = 1;
566         audit_enabled = audit_default;
567         audit_log(NULL, GFP_KERNEL, AUDIT_KERNEL, "initialized");
568         return 0;
569 }
570 __initcall(audit_init);
571
572 /* Process kernel command-line parameter at boot time.  audit=0 or audit=1. */
573 static int __init audit_enable(char *str)
574 {
575         audit_default = !!simple_strtol(str, NULL, 0);
576         printk(KERN_INFO "audit: %s%s\n",
577                audit_default ? "enabled" : "disabled",
578                audit_initialized ? "" : " (after initialization)");
579         if (audit_initialized)
580                 audit_enabled = audit_default;
581         return 1;
582 }
583
584 __setup("audit=", audit_enable);
585
586 static void audit_buffer_free(struct audit_buffer *ab)
587 {
588         unsigned long flags;
589
590         if (!ab)
591                 return;
592
593         if (ab->skb)
594                 kfree_skb(ab->skb);
595
596         spin_lock_irqsave(&audit_freelist_lock, flags);
597         if (++audit_freelist_count > AUDIT_MAXFREE)
598                 kfree(ab);
599         else
600                 list_add(&ab->list, &audit_freelist);
601         spin_unlock_irqrestore(&audit_freelist_lock, flags);
602 }
603
604 static struct audit_buffer * audit_buffer_alloc(struct audit_context *ctx,
605                                                 gfp_t gfp_mask, int type)
606 {
607         unsigned long flags;
608         struct audit_buffer *ab = NULL;
609         struct nlmsghdr *nlh;
610
611         spin_lock_irqsave(&audit_freelist_lock, flags);
612         if (!list_empty(&audit_freelist)) {
613                 ab = list_entry(audit_freelist.next,
614                                 struct audit_buffer, list);
615                 list_del(&ab->list);
616                 --audit_freelist_count;
617         }
618         spin_unlock_irqrestore(&audit_freelist_lock, flags);
619
620         if (!ab) {
621                 ab = kmalloc(sizeof(*ab), gfp_mask);
622                 if (!ab)
623                         goto err;
624         }
625
626         ab->skb = alloc_skb(AUDIT_BUFSIZ, gfp_mask);
627         if (!ab->skb)
628                 goto err;
629
630         ab->ctx = ctx;
631         ab->gfp_mask = gfp_mask;
632         nlh = (struct nlmsghdr *)skb_put(ab->skb, NLMSG_SPACE(0));
633         nlh->nlmsg_type = type;
634         nlh->nlmsg_flags = 0;
635         nlh->nlmsg_pid = 0;
636         nlh->nlmsg_seq = 0;
637         return ab;
638 err:
639         audit_buffer_free(ab);
640         return NULL;
641 }
642
643 /**
644  * audit_serial - compute a serial number for the audit record
645  *
646  * Compute a serial number for the audit record.  Audit records are
647  * written to user-space as soon as they are generated, so a complete
648  * audit record may be written in several pieces.  The timestamp of the
649  * record and this serial number are used by the user-space tools to
650  * determine which pieces belong to the same audit record.  The
651  * (timestamp,serial) tuple is unique for each syscall and is live from
652  * syscall entry to syscall exit.
653  *
654  * NOTE: Another possibility is to store the formatted records off the
655  * audit context (for those records that have a context), and emit them
656  * all at syscall exit.  However, this could delay the reporting of
657  * significant errors until syscall exit (or never, if the system
658  * halts).
659  */
660 unsigned int audit_serial(void)
661 {
662         static spinlock_t serial_lock = SPIN_LOCK_UNLOCKED;
663         static unsigned int serial = 0;
664
665         unsigned long flags;
666         unsigned int ret;
667
668         spin_lock_irqsave(&serial_lock, flags);
669         do {
670                 ret = ++serial;
671         } while (unlikely(!ret));
672         spin_unlock_irqrestore(&serial_lock, flags);
673
674         return ret;
675 }
676
677 static inline void audit_get_stamp(struct audit_context *ctx, 
678                                    struct timespec *t, unsigned int *serial)
679 {
680         if (ctx)
681                 auditsc_get_stamp(ctx, t, serial);
682         else {
683                 *t = CURRENT_TIME;
684                 *serial = audit_serial();
685         }
686 }
687
688 /* Obtain an audit buffer.  This routine does locking to obtain the
689  * audit buffer, but then no locking is required for calls to
690  * audit_log_*format.  If the tsk is a task that is currently in a
691  * syscall, then the syscall is marked as auditable and an audit record
692  * will be written at syscall exit.  If there is no associated task, tsk
693  * should be NULL. */
694
695 /**
696  * audit_log_start - obtain an audit buffer
697  * @ctx: audit_context (may be NULL)
698  * @gfp_mask: type of allocation
699  * @type: audit message type
700  *
701  * Returns audit_buffer pointer on success or NULL on error.
702  *
703  * Obtain an audit buffer.  This routine does locking to obtain the
704  * audit buffer, but then no locking is required for calls to
705  * audit_log_*format.  If the task (ctx) is a task that is currently in a
706  * syscall, then the syscall is marked as auditable and an audit record
707  * will be written at syscall exit.  If there is no associated task, then
708  * task context (ctx) should be NULL.
709  */
710 struct audit_buffer *audit_log_start(struct audit_context *ctx, gfp_t gfp_mask,
711                                      int type)
712 {
713         struct audit_buffer     *ab     = NULL;
714         struct timespec         t;
715         unsigned int            serial;
716         int reserve;
717         unsigned long timeout_start = jiffies;
718
719         if (!audit_initialized)
720                 return NULL;
721
722         if (unlikely(audit_filter_type(type)))
723                 return NULL;
724
725         if (gfp_mask & __GFP_WAIT)
726                 reserve = 0;
727         else
728                 reserve = 5; /* Allow atomic callers to go up to five 
729                                 entries over the normal backlog limit */
730
731         while (audit_backlog_limit
732                && skb_queue_len(&audit_skb_queue) > audit_backlog_limit + reserve) {
733                 if (gfp_mask & __GFP_WAIT && audit_backlog_wait_time
734                     && time_before(jiffies, timeout_start + audit_backlog_wait_time)) {
735
736                         /* Wait for auditd to drain the queue a little */
737                         DECLARE_WAITQUEUE(wait, current);
738                         set_current_state(TASK_INTERRUPTIBLE);
739                         add_wait_queue(&audit_backlog_wait, &wait);
740
741                         if (audit_backlog_limit &&
742                             skb_queue_len(&audit_skb_queue) > audit_backlog_limit)
743                                 schedule_timeout(timeout_start + audit_backlog_wait_time - jiffies);
744
745                         __set_current_state(TASK_RUNNING);
746                         remove_wait_queue(&audit_backlog_wait, &wait);
747                         continue;
748                 }
749                 if (audit_rate_check())
750                         printk(KERN_WARNING
751                                "audit: audit_backlog=%d > "
752                                "audit_backlog_limit=%d\n",
753                                skb_queue_len(&audit_skb_queue),
754                                audit_backlog_limit);
755                 audit_log_lost("backlog limit exceeded");
756                 audit_backlog_wait_time = audit_backlog_wait_overflow;
757                 wake_up(&audit_backlog_wait);
758                 return NULL;
759         }
760
761         ab = audit_buffer_alloc(ctx, gfp_mask, type);
762         if (!ab) {
763                 audit_log_lost("out of memory in audit_log_start");
764                 return NULL;
765         }
766
767         audit_get_stamp(ab->ctx, &t, &serial);
768
769         audit_log_format(ab, "audit(%lu.%03lu:%u): ",
770                          t.tv_sec, t.tv_nsec/1000000, serial);
771         return ab;
772 }
773
774 /**
775  * audit_expand - expand skb in the audit buffer
776  * @ab: audit_buffer
777  * @extra: space to add at tail of the skb
778  *
779  * Returns 0 (no space) on failed expansion, or available space if
780  * successful.
781  */
782 static inline int audit_expand(struct audit_buffer *ab, int extra)
783 {
784         struct sk_buff *skb = ab->skb;
785         int ret = pskb_expand_head(skb, skb_headroom(skb), extra,
786                                    ab->gfp_mask);
787         if (ret < 0) {
788                 audit_log_lost("out of memory in audit_expand");
789                 return 0;
790         }
791         return skb_tailroom(skb);
792 }
793
794 /*
795  * Format an audit message into the audit buffer.  If there isn't enough
796  * room in the audit buffer, more room will be allocated and vsnprint
797  * will be called a second time.  Currently, we assume that a printk
798  * can't format message larger than 1024 bytes, so we don't either.
799  */
800 static void audit_log_vformat(struct audit_buffer *ab, const char *fmt,
801                               va_list args)
802 {
803         int len, avail;
804         struct sk_buff *skb;
805         va_list args2;
806
807         if (!ab)
808                 return;
809
810         BUG_ON(!ab->skb);
811         skb = ab->skb;
812         avail = skb_tailroom(skb);
813         if (avail == 0) {
814                 avail = audit_expand(ab, AUDIT_BUFSIZ);
815                 if (!avail)
816                         goto out;
817         }
818         va_copy(args2, args);
819         len = vsnprintf(skb->tail, avail, fmt, args);
820         if (len >= avail) {
821                 /* The printk buffer is 1024 bytes long, so if we get
822                  * here and AUDIT_BUFSIZ is at least 1024, then we can
823                  * log everything that printk could have logged. */
824                 avail = audit_expand(ab,
825                         max_t(unsigned, AUDIT_BUFSIZ, 1+len-avail));
826                 if (!avail)
827                         goto out;
828                 len = vsnprintf(skb->tail, avail, fmt, args2);
829         }
830         if (len > 0)
831                 skb_put(skb, len);
832 out:
833         return;
834 }
835
836 /**
837  * audit_log_format - format a message into the audit buffer.
838  * @ab: audit_buffer
839  * @fmt: format string
840  * @...: optional parameters matching @fmt string
841  *
842  * All the work is done in audit_log_vformat.
843  */
844 void audit_log_format(struct audit_buffer *ab, const char *fmt, ...)
845 {
846         va_list args;
847
848         if (!ab)
849                 return;
850         va_start(args, fmt);
851         audit_log_vformat(ab, fmt, args);
852         va_end(args);
853 }
854
855 /**
856  * audit_log_hex - convert a buffer to hex and append it to the audit skb
857  * @ab: the audit_buffer
858  * @buf: buffer to convert to hex
859  * @len: length of @buf to be converted
860  *
861  * No return value; failure to expand is silently ignored.
862  *
863  * This function will take the passed buf and convert it into a string of
864  * ascii hex digits. The new string is placed onto the skb.
865  */
866 void audit_log_hex(struct audit_buffer *ab, const unsigned char *buf,
867                 size_t len)
868 {
869         int i, avail, new_len;
870         unsigned char *ptr;
871         struct sk_buff *skb;
872         static const unsigned char *hex = "0123456789ABCDEF";
873
874         BUG_ON(!ab->skb);
875         skb = ab->skb;
876         avail = skb_tailroom(skb);
877         new_len = len<<1;
878         if (new_len >= avail) {
879                 /* Round the buffer request up to the next multiple */
880                 new_len = AUDIT_BUFSIZ*(((new_len-avail)/AUDIT_BUFSIZ) + 1);
881                 avail = audit_expand(ab, new_len);
882                 if (!avail)
883                         return;
884         }
885
886         ptr = skb->tail;
887         for (i=0; i<len; i++) {
888                 *ptr++ = hex[(buf[i] & 0xF0)>>4]; /* Upper nibble */
889                 *ptr++ = hex[buf[i] & 0x0F];      /* Lower nibble */
890         }
891         *ptr = 0;
892         skb_put(skb, len << 1); /* new string is twice the old string */
893 }
894
895 /**
896  * audit_log_unstrustedstring - log a string that may contain random characters
897  * @ab: audit_buffer
898  * @string: string to be logged
899  *
900  * This code will escape a string that is passed to it if the string
901  * contains a control character, unprintable character, double quote mark,
902  * or a space. Unescaped strings will start and end with a double quote mark.
903  * Strings that are escaped are printed in hex (2 digits per char).
904  */
905 void audit_log_untrustedstring(struct audit_buffer *ab, const char *string)
906 {
907         const unsigned char *p = string;
908
909         while (*p) {
910                 if (*p == '"' || *p < 0x21 || *p > 0x7f) {
911                         audit_log_hex(ab, string, strlen(string));
912                         return;
913                 }
914                 p++;
915         }
916         audit_log_format(ab, "\"%s\"", string);
917 }
918
919 /* This is a helper-function to print the escaped d_path */
920 void audit_log_d_path(struct audit_buffer *ab, const char *prefix,
921                       struct dentry *dentry, struct vfsmount *vfsmnt)
922 {
923         char *p, *path;
924
925         if (prefix)
926                 audit_log_format(ab, " %s", prefix);
927
928         /* We will allow 11 spaces for ' (deleted)' to be appended */
929         path = kmalloc(PATH_MAX+11, ab->gfp_mask);
930         if (!path) {
931                 audit_log_format(ab, "<no memory>");
932                 return;
933         }
934         p = d_path(dentry, vfsmnt, path, PATH_MAX+11);
935         if (IS_ERR(p)) { /* Should never happen since we send PATH_MAX */
936                 /* FIXME: can we save some information here? */
937                 audit_log_format(ab, "<too long>");
938         } else 
939                 audit_log_untrustedstring(ab, p);
940         kfree(path);
941 }
942
943 /**
944  * audit_log_end - end one audit record
945  * @ab: the audit_buffer
946  *
947  * The netlink_* functions cannot be called inside an irq context, so
948  * the audit buffer is placed on a queue and a tasklet is scheduled to
949  * remove them from the queue outside the irq context.  May be called in
950  * any context.
951  */
952 void audit_log_end(struct audit_buffer *ab)
953 {
954         if (!ab)
955                 return;
956         if (!audit_rate_check()) {
957                 audit_log_lost("rate limit exceeded");
958         } else {
959                 if (audit_pid) {
960                         struct nlmsghdr *nlh = (struct nlmsghdr *)ab->skb->data;
961                         nlh->nlmsg_len = ab->skb->len - NLMSG_SPACE(0);
962                         skb_queue_tail(&audit_skb_queue, ab->skb);
963                         ab->skb = NULL;
964                         wake_up_interruptible(&kauditd_wait);
965                 } else {
966                         printk(KERN_NOTICE "%s\n", ab->skb->data + NLMSG_SPACE(0));
967                 }
968         }
969         audit_buffer_free(ab);
970 }
971
972 /**
973  * audit_log - Log an audit record
974  * @ctx: audit context
975  * @gfp_mask: type of allocation
976  * @type: audit message type
977  * @fmt: format string to use
978  * @...: variable parameters matching the format string
979  *
980  * This is a convenience function that calls audit_log_start,
981  * audit_log_vformat, and audit_log_end.  It may be called
982  * in any context.
983  */
984 void audit_log(struct audit_context *ctx, gfp_t gfp_mask, int type, 
985                const char *fmt, ...)
986 {
987         struct audit_buffer *ab;
988         va_list args;
989
990         ab = audit_log_start(ctx, gfp_mask, type);
991         if (ab) {
992                 va_start(args, fmt);
993                 audit_log_vformat(ab, fmt, args);
994                 va_end(args);
995                 audit_log_end(ab);
996         }
997 }
998
999 EXPORT_SYMBOL(audit_log_start);
1000 EXPORT_SYMBOL(audit_log_end);
1001 EXPORT_SYMBOL(audit_log_format);
1002 EXPORT_SYMBOL(audit_log);