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