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