allow coexistance of N build and AC build.
[tomato.git] / release / src-rt-6.x / linux / linux-2.6 / kernel / audit.c
blob02c51c41bf8639573c1ad69e274aad3c1d4f1095
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
5 * Copyright 2003-2007 Red Hat Inc., Durham, North Carolina.
6 * All Rights Reserved.
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.
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.
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
22 * Written by Rickard E. (Rik) Faith <faith@redhat.com>
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.
41 * Example user-space utilities: http://people.redhat.com/sgrubb/audit/
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>
52 #include <linux/audit.h>
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 #include <linux/inotify.h>
60 #include <linux/freezer.h>
62 #include "audit.h"
64 /* No auditing will take place until audit_initialized != 0.
65 * (Initialization happens after skb_init is called.) */
66 static int audit_initialized;
68 /* 0 - no auditing
69 * 1 - auditing enabled
70 * 2 - auditing enabled and configuration is locked/unchangeable. */
71 int audit_enabled;
73 /* Default state when kernel boots without any parameters. */
74 static int audit_default;
76 /* If auditing cannot proceed, audit_failure selects what happens. */
77 static int audit_failure = AUDIT_FAIL_PRINTK;
79 /* If audit records are to be written to the netlink socket, audit_pid
80 * contains the (non-zero) pid. */
81 int audit_pid;
83 /* If audit_rate_limit is non-zero, limit the rate of sending audit records
84 * to that number per second. This prevents DoS attacks, but results in
85 * audit records being dropped. */
86 static int audit_rate_limit;
88 /* Number of outstanding audit_buffers allowed. */
89 static int audit_backlog_limit = 64;
90 static int audit_backlog_wait_time = 60 * HZ;
91 static int audit_backlog_wait_overflow = 0;
93 /* The identity of the user shutting down the audit system. */
94 uid_t audit_sig_uid = -1;
95 pid_t audit_sig_pid = -1;
96 u32 audit_sig_sid = 0;
98 /* Records can be lost in several ways:
99 0) [suppressed in audit_alloc]
100 1) out of memory in audit_log_start [kmalloc of struct audit_buffer]
101 2) out of memory in audit_log_move [alloc_skb]
102 3) suppressed due to audit_rate_limit
103 4) suppressed due to audit_backlog_limit
105 static atomic_t audit_lost = ATOMIC_INIT(0);
107 /* The netlink socket. */
108 static struct sock *audit_sock;
110 /* Inotify handle. */
111 struct inotify_handle *audit_ih;
113 /* Hash for inode-based rules */
114 struct list_head audit_inode_hash[AUDIT_INODE_BUCKETS];
116 /* The audit_freelist is a list of pre-allocated audit buffers (if more
117 * than AUDIT_MAXFREE are in use, the audit buffer is freed instead of
118 * being placed on the freelist). */
119 static DEFINE_SPINLOCK(audit_freelist_lock);
120 static int audit_freelist_count;
121 static LIST_HEAD(audit_freelist);
123 static struct sk_buff_head audit_skb_queue;
124 static struct task_struct *kauditd_task;
125 static DECLARE_WAIT_QUEUE_HEAD(kauditd_wait);
126 static DECLARE_WAIT_QUEUE_HEAD(audit_backlog_wait);
128 /* Serialize requests from userspace. */
129 static DEFINE_MUTEX(audit_cmd_mutex);
131 /* AUDIT_BUFSIZ is the size of the temporary buffer used for formatting
132 * audit records. Since printk uses a 1024 byte buffer, this buffer
133 * should be at least that large. */
134 #define AUDIT_BUFSIZ 1024
136 /* AUDIT_MAXFREE is the number of empty audit_buffers we keep on the
137 * audit_freelist. Doing so eliminates many kmalloc/kfree calls. */
138 #define AUDIT_MAXFREE (2*NR_CPUS)
140 /* The audit_buffer is used when formatting an audit record. The caller
141 * locks briefly to get the record off the freelist or to allocate the
142 * buffer, and locks briefly to send the buffer to the netlink layer or
143 * to place it on a transmit queue. Multiple audit_buffers can be in
144 * use simultaneously. */
145 struct audit_buffer {
146 struct list_head list;
147 struct sk_buff *skb; /* formatted skb ready to send */
148 struct audit_context *ctx; /* NULL or associated context */
149 gfp_t gfp_mask;
152 static void audit_set_pid(struct audit_buffer *ab, pid_t pid)
154 struct nlmsghdr *nlh = nlmsg_hdr(ab->skb);
155 nlh->nlmsg_pid = pid;
158 void audit_panic(const char *message)
160 switch (audit_failure)
162 case AUDIT_FAIL_SILENT:
163 break;
164 case AUDIT_FAIL_PRINTK:
165 printk(KERN_ERR "audit: %s\n", message);
166 break;
167 case AUDIT_FAIL_PANIC:
168 panic("audit: %s\n", message);
169 break;
173 static inline int audit_rate_check(void)
175 static unsigned long last_check = 0;
176 static int messages = 0;
177 static DEFINE_SPINLOCK(lock);
178 unsigned long flags;
179 unsigned long now;
180 unsigned long elapsed;
181 int retval = 0;
183 if (!audit_rate_limit) return 1;
185 spin_lock_irqsave(&lock, flags);
186 if (++messages < audit_rate_limit) {
187 retval = 1;
188 } else {
189 now = jiffies;
190 elapsed = now - last_check;
191 if (elapsed > HZ) {
192 last_check = now;
193 messages = 0;
194 retval = 1;
197 spin_unlock_irqrestore(&lock, flags);
199 return retval;
203 * audit_log_lost - conditionally log lost audit message event
204 * @message: the message stating reason for lost audit message
206 * Emit at least 1 message per second, even if audit_rate_check is
207 * throttling.
208 * Always increment the lost messages counter.
210 void audit_log_lost(const char *message)
212 static unsigned long last_msg = 0;
213 static DEFINE_SPINLOCK(lock);
214 unsigned long flags;
215 unsigned long now;
216 int print;
218 atomic_inc(&audit_lost);
220 print = (audit_failure == AUDIT_FAIL_PANIC || !audit_rate_limit);
222 if (!print) {
223 spin_lock_irqsave(&lock, flags);
224 now = jiffies;
225 if (now - last_msg > HZ) {
226 print = 1;
227 last_msg = now;
229 spin_unlock_irqrestore(&lock, flags);
232 if (print) {
233 printk(KERN_WARNING
234 "audit: audit_lost=%d audit_rate_limit=%d audit_backlog_limit=%d\n",
235 atomic_read(&audit_lost),
236 audit_rate_limit,
237 audit_backlog_limit);
238 audit_panic(message);
242 static int audit_set_rate_limit(int limit, uid_t loginuid, u32 sid)
244 int res, rc = 0, old = audit_rate_limit;
246 /* check if we are locked */
247 if (audit_enabled == 2)
248 res = 0;
249 else
250 res = 1;
252 if (sid) {
253 char *ctx = NULL;
254 u32 len;
255 if ((rc = selinux_sid_to_string(sid, &ctx, &len)) == 0) {
256 audit_log(NULL, GFP_KERNEL, AUDIT_CONFIG_CHANGE,
257 "audit_rate_limit=%d old=%d by auid=%u"
258 " subj=%s res=%d",
259 limit, old, loginuid, ctx, res);
260 kfree(ctx);
261 } else
262 res = 0; /* Something weird, deny request */
264 audit_log(NULL, GFP_KERNEL, AUDIT_CONFIG_CHANGE,
265 "audit_rate_limit=%d old=%d by auid=%u res=%d",
266 limit, old, loginuid, res);
268 /* If we are allowed, make the change */
269 if (res == 1)
270 audit_rate_limit = limit;
271 /* Not allowed, update reason */
272 else if (rc == 0)
273 rc = -EPERM;
274 return rc;
277 static int audit_set_backlog_limit(int limit, uid_t loginuid, u32 sid)
279 int res, rc = 0, old = audit_backlog_limit;
281 /* check if we are locked */
282 if (audit_enabled == 2)
283 res = 0;
284 else
285 res = 1;
287 if (sid) {
288 char *ctx = NULL;
289 u32 len;
290 if ((rc = selinux_sid_to_string(sid, &ctx, &len)) == 0) {
291 audit_log(NULL, GFP_KERNEL, AUDIT_CONFIG_CHANGE,
292 "audit_backlog_limit=%d old=%d by auid=%u"
293 " subj=%s res=%d",
294 limit, old, loginuid, ctx, res);
295 kfree(ctx);
296 } else
297 res = 0; /* Something weird, deny request */
299 audit_log(NULL, GFP_KERNEL, AUDIT_CONFIG_CHANGE,
300 "audit_backlog_limit=%d old=%d by auid=%u res=%d",
301 limit, old, loginuid, res);
303 /* If we are allowed, make the change */
304 if (res == 1)
305 audit_backlog_limit = limit;
306 /* Not allowed, update reason */
307 else if (rc == 0)
308 rc = -EPERM;
309 return rc;
312 static int audit_set_enabled(int state, uid_t loginuid, u32 sid)
314 int res, rc = 0, old = audit_enabled;
316 if (state < 0 || state > 2)
317 return -EINVAL;
319 /* check if we are locked */
320 if (audit_enabled == 2)
321 res = 0;
322 else
323 res = 1;
325 if (sid) {
326 char *ctx = NULL;
327 u32 len;
328 if ((rc = selinux_sid_to_string(sid, &ctx, &len)) == 0) {
329 audit_log(NULL, GFP_KERNEL, AUDIT_CONFIG_CHANGE,
330 "audit_enabled=%d old=%d by auid=%u"
331 " subj=%s res=%d",
332 state, old, loginuid, ctx, res);
333 kfree(ctx);
334 } else
335 res = 0; /* Something weird, deny request */
337 audit_log(NULL, GFP_KERNEL, AUDIT_CONFIG_CHANGE,
338 "audit_enabled=%d old=%d by auid=%u res=%d",
339 state, old, loginuid, res);
341 /* If we are allowed, make the change */
342 if (res == 1)
343 audit_enabled = state;
344 /* Not allowed, update reason */
345 else if (rc == 0)
346 rc = -EPERM;
347 return rc;
350 static int audit_set_failure(int state, uid_t loginuid, u32 sid)
352 int res, rc = 0, old = audit_failure;
354 if (state != AUDIT_FAIL_SILENT
355 && state != AUDIT_FAIL_PRINTK
356 && state != AUDIT_FAIL_PANIC)
357 return -EINVAL;
359 /* check if we are locked */
360 if (audit_enabled == 2)
361 res = 0;
362 else
363 res = 1;
365 if (sid) {
366 char *ctx = NULL;
367 u32 len;
368 if ((rc = selinux_sid_to_string(sid, &ctx, &len)) == 0) {
369 audit_log(NULL, GFP_KERNEL, AUDIT_CONFIG_CHANGE,
370 "audit_failure=%d old=%d by auid=%u"
371 " subj=%s res=%d",
372 state, old, loginuid, ctx, res);
373 kfree(ctx);
374 } else
375 res = 0; /* Something weird, deny request */
377 audit_log(NULL, GFP_KERNEL, AUDIT_CONFIG_CHANGE,
378 "audit_failure=%d old=%d by auid=%u res=%d",
379 state, old, loginuid, res);
381 /* If we are allowed, make the change */
382 if (res == 1)
383 audit_failure = state;
384 /* Not allowed, update reason */
385 else if (rc == 0)
386 rc = -EPERM;
387 return rc;
390 static int kauditd_thread(void *dummy)
392 struct sk_buff *skb;
394 while (!kthread_should_stop()) {
395 skb = skb_dequeue(&audit_skb_queue);
396 wake_up(&audit_backlog_wait);
397 if (skb) {
398 if (audit_pid) {
399 int err = netlink_unicast(audit_sock, skb, audit_pid, 0);
400 if (err < 0) {
401 BUG_ON(err != -ECONNREFUSED); /* Shoudn't happen */
402 printk(KERN_ERR "audit: *NO* daemon at audit_pid=%d\n", audit_pid);
403 audit_pid = 0;
405 } else {
406 printk(KERN_NOTICE "%s\n", skb->data + NLMSG_SPACE(0));
407 kfree_skb(skb);
409 } else {
410 DECLARE_WAITQUEUE(wait, current);
411 set_current_state(TASK_INTERRUPTIBLE);
412 add_wait_queue(&kauditd_wait, &wait);
414 if (!skb_queue_len(&audit_skb_queue)) {
415 try_to_freeze();
416 schedule();
419 __set_current_state(TASK_RUNNING);
420 remove_wait_queue(&kauditd_wait, &wait);
423 return 0;
426 int audit_send_list(void *_dest)
428 struct audit_netlink_list *dest = _dest;
429 int pid = dest->pid;
430 struct sk_buff *skb;
432 /* wait for parent to finish and send an ACK */
433 mutex_lock(&audit_cmd_mutex);
434 mutex_unlock(&audit_cmd_mutex);
436 while ((skb = __skb_dequeue(&dest->q)) != NULL)
437 netlink_unicast(audit_sock, skb, pid, 0);
439 kfree(dest);
441 return 0;
444 struct sk_buff *audit_make_reply(int pid, int seq, int type, int done,
445 int multi, void *payload, int size)
447 struct sk_buff *skb;
448 struct nlmsghdr *nlh;
449 int len = NLMSG_SPACE(size);
450 void *data;
451 int flags = multi ? NLM_F_MULTI : 0;
452 int t = done ? NLMSG_DONE : type;
454 skb = alloc_skb(len, GFP_KERNEL);
455 if (!skb)
456 return NULL;
458 nlh = NLMSG_PUT(skb, pid, seq, t, size);
459 nlh->nlmsg_flags = flags;
460 data = NLMSG_DATA(nlh);
461 memcpy(data, payload, size);
462 return skb;
464 nlmsg_failure: /* Used by NLMSG_PUT */
465 if (skb)
466 kfree_skb(skb);
467 return NULL;
471 * audit_send_reply - send an audit reply message via netlink
472 * @pid: process id to send reply to
473 * @seq: sequence number
474 * @type: audit message type
475 * @done: done (last) flag
476 * @multi: multi-part message flag
477 * @payload: payload data
478 * @size: payload size
480 * Allocates an skb, builds the netlink message, and sends it to the pid.
481 * No failure notifications.
483 void audit_send_reply(int pid, int seq, int type, int done, int multi,
484 void *payload, int size)
486 struct sk_buff *skb;
487 skb = audit_make_reply(pid, seq, type, done, multi, payload, size);
488 if (!skb)
489 return;
490 /* Ignore failure. It'll only happen if the sender goes away,
491 because our timeout is set to infinite. */
492 netlink_unicast(audit_sock, skb, pid, 0);
493 return;
497 * Check for appropriate CAP_AUDIT_ capabilities on incoming audit
498 * control messages.
500 static int audit_netlink_ok(struct sk_buff *skb, u16 msg_type)
502 int err = 0;
504 switch (msg_type) {
505 case AUDIT_GET:
506 case AUDIT_LIST:
507 case AUDIT_LIST_RULES:
508 case AUDIT_SET:
509 case AUDIT_ADD:
510 case AUDIT_ADD_RULE:
511 case AUDIT_DEL:
512 case AUDIT_DEL_RULE:
513 case AUDIT_SIGNAL_INFO:
514 if (security_netlink_recv(skb, CAP_AUDIT_CONTROL))
515 err = -EPERM;
516 break;
517 case AUDIT_USER:
518 case AUDIT_FIRST_USER_MSG ... AUDIT_LAST_USER_MSG:
519 case AUDIT_FIRST_USER_MSG2 ... AUDIT_LAST_USER_MSG2:
520 if (security_netlink_recv(skb, CAP_AUDIT_WRITE))
521 err = -EPERM;
522 break;
523 default: /* bad msg */
524 err = -EINVAL;
527 return err;
530 static int audit_receive_msg(struct sk_buff *skb, struct nlmsghdr *nlh)
532 u32 uid, pid, seq, sid;
533 void *data;
534 struct audit_status *status_get, status_set;
535 int err;
536 struct audit_buffer *ab;
537 u16 msg_type = nlh->nlmsg_type;
538 uid_t loginuid; /* loginuid of sender */
539 struct audit_sig_info *sig_data;
540 char *ctx;
541 u32 len;
543 err = audit_netlink_ok(skb, msg_type);
544 if (err)
545 return err;
547 /* As soon as there's any sign of userspace auditd,
548 * start kauditd to talk to it */
549 if (!kauditd_task)
550 kauditd_task = kthread_run(kauditd_thread, NULL, "kauditd");
551 if (IS_ERR(kauditd_task)) {
552 err = PTR_ERR(kauditd_task);
553 kauditd_task = NULL;
554 return err;
557 pid = NETLINK_CREDS(skb)->pid;
558 uid = NETLINK_CREDS(skb)->uid;
559 loginuid = NETLINK_CB(skb).loginuid;
560 sid = NETLINK_CB(skb).sid;
561 seq = nlh->nlmsg_seq;
562 data = NLMSG_DATA(nlh);
564 switch (msg_type) {
565 case AUDIT_GET:
566 status_set.enabled = audit_enabled;
567 status_set.failure = audit_failure;
568 status_set.pid = audit_pid;
569 status_set.rate_limit = audit_rate_limit;
570 status_set.backlog_limit = audit_backlog_limit;
571 status_set.lost = atomic_read(&audit_lost);
572 status_set.backlog = skb_queue_len(&audit_skb_queue);
573 audit_send_reply(NETLINK_CB(skb).pid, seq, AUDIT_GET, 0, 0,
574 &status_set, sizeof(status_set));
575 break;
576 case AUDIT_SET:
577 if (nlh->nlmsg_len < sizeof(struct audit_status))
578 return -EINVAL;
579 status_get = (struct audit_status *)data;
580 if (status_get->mask & AUDIT_STATUS_ENABLED) {
581 err = audit_set_enabled(status_get->enabled,
582 loginuid, sid);
583 if (err < 0) return err;
585 if (status_get->mask & AUDIT_STATUS_FAILURE) {
586 err = audit_set_failure(status_get->failure,
587 loginuid, sid);
588 if (err < 0) return err;
590 if (status_get->mask & AUDIT_STATUS_PID) {
591 int old = audit_pid;
592 if (sid) {
593 if ((err = selinux_sid_to_string(
594 sid, &ctx, &len)))
595 return err;
596 else
597 audit_log(NULL, GFP_KERNEL,
598 AUDIT_CONFIG_CHANGE,
599 "audit_pid=%d old=%d by auid=%u subj=%s",
600 status_get->pid, old,
601 loginuid, ctx);
602 kfree(ctx);
603 } else
604 audit_log(NULL, GFP_KERNEL, AUDIT_CONFIG_CHANGE,
605 "audit_pid=%d old=%d by auid=%u",
606 status_get->pid, old, loginuid);
607 audit_pid = status_get->pid;
609 if (status_get->mask & AUDIT_STATUS_RATE_LIMIT)
610 err = audit_set_rate_limit(status_get->rate_limit,
611 loginuid, sid);
612 if (status_get->mask & AUDIT_STATUS_BACKLOG_LIMIT)
613 err = audit_set_backlog_limit(status_get->backlog_limit,
614 loginuid, sid);
615 break;
616 case AUDIT_USER:
617 case AUDIT_FIRST_USER_MSG ... AUDIT_LAST_USER_MSG:
618 case AUDIT_FIRST_USER_MSG2 ... AUDIT_LAST_USER_MSG2:
619 if (!audit_enabled && msg_type != AUDIT_USER_AVC)
620 return 0;
622 err = audit_filter_user(&NETLINK_CB(skb), msg_type);
623 if (err == 1) {
624 err = 0;
625 ab = audit_log_start(NULL, GFP_KERNEL, msg_type);
626 if (ab) {
627 audit_log_format(ab,
628 "user pid=%d uid=%u auid=%u",
629 pid, uid, loginuid);
630 if (sid) {
631 if (selinux_sid_to_string(
632 sid, &ctx, &len)) {
633 audit_log_format(ab,
634 " ssid=%u", sid);
635 /* Maybe call audit_panic? */
636 } else
637 audit_log_format(ab,
638 " subj=%s", ctx);
639 kfree(ctx);
641 audit_log_format(ab, " msg='%.1024s'",
642 (char *)data);
643 audit_set_pid(ab, pid);
644 audit_log_end(ab);
647 break;
648 case AUDIT_ADD:
649 case AUDIT_DEL:
650 if (nlmsg_len(nlh) < sizeof(struct audit_rule))
651 return -EINVAL;
652 if (audit_enabled == 2) {
653 ab = audit_log_start(NULL, GFP_KERNEL,
654 AUDIT_CONFIG_CHANGE);
655 if (ab) {
656 audit_log_format(ab,
657 "pid=%d uid=%u auid=%u",
658 pid, uid, loginuid);
659 if (sid) {
660 if (selinux_sid_to_string(
661 sid, &ctx, &len)) {
662 audit_log_format(ab,
663 " ssid=%u", sid);
664 /* Maybe call audit_panic? */
665 } else
666 audit_log_format(ab,
667 " subj=%s", ctx);
668 kfree(ctx);
670 audit_log_format(ab, " audit_enabled=%d res=0",
671 audit_enabled);
672 audit_log_end(ab);
674 return -EPERM;
676 /* fallthrough */
677 case AUDIT_LIST:
678 err = audit_receive_filter(nlh->nlmsg_type, NETLINK_CB(skb).pid,
679 uid, seq, data, nlmsg_len(nlh),
680 loginuid, sid);
681 break;
682 case AUDIT_ADD_RULE:
683 case AUDIT_DEL_RULE:
684 if (nlmsg_len(nlh) < sizeof(struct audit_rule_data))
685 return -EINVAL;
686 if (audit_enabled == 2) {
687 ab = audit_log_start(NULL, GFP_KERNEL,
688 AUDIT_CONFIG_CHANGE);
689 if (ab) {
690 audit_log_format(ab,
691 "pid=%d uid=%u auid=%u",
692 pid, uid, loginuid);
693 if (sid) {
694 if (selinux_sid_to_string(
695 sid, &ctx, &len)) {
696 audit_log_format(ab,
697 " ssid=%u", sid);
698 /* Maybe call audit_panic? */
699 } else
700 audit_log_format(ab,
701 " subj=%s", ctx);
702 kfree(ctx);
704 audit_log_format(ab, " audit_enabled=%d res=0",
705 audit_enabled);
706 audit_log_end(ab);
708 return -EPERM;
710 /* fallthrough */
711 case AUDIT_LIST_RULES:
712 err = audit_receive_filter(nlh->nlmsg_type, NETLINK_CB(skb).pid,
713 uid, seq, data, nlmsg_len(nlh),
714 loginuid, sid);
715 break;
716 case AUDIT_SIGNAL_INFO:
717 err = selinux_sid_to_string(audit_sig_sid, &ctx, &len);
718 if (err)
719 return err;
720 sig_data = kmalloc(sizeof(*sig_data) + len, GFP_KERNEL);
721 if (!sig_data) {
722 kfree(ctx);
723 return -ENOMEM;
725 sig_data->uid = audit_sig_uid;
726 sig_data->pid = audit_sig_pid;
727 memcpy(sig_data->ctx, ctx, len);
728 kfree(ctx);
729 audit_send_reply(NETLINK_CB(skb).pid, seq, AUDIT_SIGNAL_INFO,
730 0, 0, sig_data, sizeof(*sig_data) + len);
731 kfree(sig_data);
732 break;
733 default:
734 err = -EINVAL;
735 break;
738 return err < 0 ? err : 0;
742 * Get message from skb (based on rtnetlink_rcv_skb). Each message is
743 * processed by audit_receive_msg. Malformed skbs with wrong length are
744 * discarded silently.
746 static void audit_receive_skb(struct sk_buff *skb)
748 int err;
749 struct nlmsghdr *nlh;
750 u32 rlen;
752 while (skb->len >= NLMSG_SPACE(0)) {
753 nlh = nlmsg_hdr(skb);
754 if (nlh->nlmsg_len < sizeof(*nlh) || skb->len < nlh->nlmsg_len)
755 return;
756 rlen = NLMSG_ALIGN(nlh->nlmsg_len);
757 if (rlen > skb->len)
758 rlen = skb->len;
759 if ((err = audit_receive_msg(skb, nlh))) {
760 netlink_ack(skb, nlh, err);
761 } else if (nlh->nlmsg_flags & NLM_F_ACK)
762 netlink_ack(skb, nlh, 0);
763 skb_pull(skb, rlen);
767 /* Receive messages from netlink socket. */
768 static void audit_receive(struct sk_buff *skb)
770 mutex_lock(&audit_cmd_mutex);
771 audit_receive_skb(skb);
772 mutex_unlock(&audit_cmd_mutex);
775 #ifdef CONFIG_AUDITSYSCALL
776 static const struct inotify_operations audit_inotify_ops = {
777 .handle_event = audit_handle_ievent,
778 .destroy_watch = audit_free_parent,
780 #endif
782 /* Initialize audit support at boot time. */
783 static int __init audit_init(void)
785 int i;
787 printk(KERN_INFO "audit: initializing netlink socket (%s)\n",
788 audit_default ? "enabled" : "disabled");
789 audit_sock = netlink_kernel_create(NETLINK_AUDIT, 0, audit_receive,
790 NULL, THIS_MODULE);
791 if (!audit_sock)
792 audit_panic("cannot initialize netlink socket");
793 else
794 audit_sock->sk_sndtimeo = MAX_SCHEDULE_TIMEOUT;
796 skb_queue_head_init(&audit_skb_queue);
797 audit_initialized = 1;
798 audit_enabled = audit_default;
800 /* Register the callback with selinux. This callback will be invoked
801 * when a new policy is loaded. */
802 selinux_audit_set_callback(&selinux_audit_rule_update);
804 audit_log(NULL, GFP_KERNEL, AUDIT_KERNEL, "initialized");
806 #ifdef CONFIG_AUDITSYSCALL
807 audit_ih = inotify_init(&audit_inotify_ops);
808 if (IS_ERR(audit_ih))
809 audit_panic("cannot initialize inotify handle");
810 #endif
812 for (i = 0; i < AUDIT_INODE_BUCKETS; i++)
813 INIT_LIST_HEAD(&audit_inode_hash[i]);
815 return 0;
817 __initcall(audit_init);
819 /* Process kernel command-line parameter at boot time. audit=0 or audit=1. */
820 static int __init audit_enable(char *str)
822 audit_default = !!simple_strtol(str, NULL, 0);
823 printk(KERN_INFO "audit: %s%s\n",
824 audit_default ? "enabled" : "disabled",
825 audit_initialized ? "" : " (after initialization)");
826 if (audit_initialized)
827 audit_enabled = audit_default;
828 return 1;
831 __setup("audit=", audit_enable);
833 static void audit_buffer_free(struct audit_buffer *ab)
835 unsigned long flags;
837 if (!ab)
838 return;
840 if (ab->skb)
841 kfree_skb(ab->skb);
843 spin_lock_irqsave(&audit_freelist_lock, flags);
844 if (audit_freelist_count > AUDIT_MAXFREE)
845 kfree(ab);
846 else {
847 audit_freelist_count++;
848 list_add(&ab->list, &audit_freelist);
850 spin_unlock_irqrestore(&audit_freelist_lock, flags);
853 static struct audit_buffer * audit_buffer_alloc(struct audit_context *ctx,
854 gfp_t gfp_mask, int type)
856 unsigned long flags;
857 struct audit_buffer *ab = NULL;
858 struct nlmsghdr *nlh;
860 spin_lock_irqsave(&audit_freelist_lock, flags);
861 if (!list_empty(&audit_freelist)) {
862 ab = list_entry(audit_freelist.next,
863 struct audit_buffer, list);
864 list_del(&ab->list);
865 --audit_freelist_count;
867 spin_unlock_irqrestore(&audit_freelist_lock, flags);
869 if (!ab) {
870 ab = kmalloc(sizeof(*ab), gfp_mask);
871 if (!ab)
872 goto err;
875 ab->skb = alloc_skb(AUDIT_BUFSIZ, gfp_mask);
876 if (!ab->skb)
877 goto err;
879 ab->ctx = ctx;
880 ab->gfp_mask = gfp_mask;
881 nlh = (struct nlmsghdr *)skb_put(ab->skb, NLMSG_SPACE(0));
882 nlh->nlmsg_type = type;
883 nlh->nlmsg_flags = 0;
884 nlh->nlmsg_pid = 0;
885 nlh->nlmsg_seq = 0;
886 return ab;
887 err:
888 audit_buffer_free(ab);
889 return NULL;
893 * audit_serial - compute a serial number for the audit record
895 * Compute a serial number for the audit record. Audit records are
896 * written to user-space as soon as they are generated, so a complete
897 * audit record may be written in several pieces. The timestamp of the
898 * record and this serial number are used by the user-space tools to
899 * determine which pieces belong to the same audit record. The
900 * (timestamp,serial) tuple is unique for each syscall and is live from
901 * syscall entry to syscall exit.
903 * NOTE: Another possibility is to store the formatted records off the
904 * audit context (for those records that have a context), and emit them
905 * all at syscall exit. However, this could delay the reporting of
906 * significant errors until syscall exit (or never, if the system
907 * halts).
909 unsigned int audit_serial(void)
911 static DEFINE_SPINLOCK(serial_lock);
912 static unsigned int serial = 0;
914 unsigned long flags;
915 unsigned int ret;
917 spin_lock_irqsave(&serial_lock, flags);
918 do {
919 ret = ++serial;
920 } while (unlikely(!ret));
921 spin_unlock_irqrestore(&serial_lock, flags);
923 return ret;
926 static inline void audit_get_stamp(struct audit_context *ctx,
927 struct timespec *t, unsigned int *serial)
929 if (ctx)
930 auditsc_get_stamp(ctx, t, serial);
931 else {
932 *t = CURRENT_TIME;
933 *serial = audit_serial();
937 /* Obtain an audit buffer. This routine does locking to obtain the
938 * audit buffer, but then no locking is required for calls to
939 * audit_log_*format. If the tsk is a task that is currently in a
940 * syscall, then the syscall is marked as auditable and an audit record
941 * will be written at syscall exit. If there is no associated task, tsk
942 * should be NULL. */
945 * audit_log_start - obtain an audit buffer
946 * @ctx: audit_context (may be NULL)
947 * @gfp_mask: type of allocation
948 * @type: audit message type
950 * Returns audit_buffer pointer on success or NULL on error.
952 * Obtain an audit buffer. This routine does locking to obtain the
953 * audit buffer, but then no locking is required for calls to
954 * audit_log_*format. If the task (ctx) is a task that is currently in a
955 * syscall, then the syscall is marked as auditable and an audit record
956 * will be written at syscall exit. If there is no associated task, then
957 * task context (ctx) should be NULL.
959 struct audit_buffer *audit_log_start(struct audit_context *ctx, gfp_t gfp_mask,
960 int type)
962 struct audit_buffer *ab = NULL;
963 struct timespec t;
964 unsigned int serial;
965 int reserve;
966 unsigned long timeout_start = jiffies;
968 if (!audit_initialized)
969 return NULL;
971 if (unlikely(audit_filter_type(type)))
972 return NULL;
974 if (gfp_mask & __GFP_WAIT)
975 reserve = 0;
976 else
977 reserve = 5; /* Allow atomic callers to go up to five
978 entries over the normal backlog limit */
980 while (audit_backlog_limit
981 && skb_queue_len(&audit_skb_queue) > audit_backlog_limit + reserve) {
982 if (gfp_mask & __GFP_WAIT && audit_backlog_wait_time
983 && time_before(jiffies, timeout_start + audit_backlog_wait_time)) {
985 /* Wait for auditd to drain the queue a little */
986 DECLARE_WAITQUEUE(wait, current);
987 set_current_state(TASK_INTERRUPTIBLE);
988 add_wait_queue(&audit_backlog_wait, &wait);
990 if (audit_backlog_limit &&
991 skb_queue_len(&audit_skb_queue) > audit_backlog_limit)
992 schedule_timeout(timeout_start + audit_backlog_wait_time - jiffies);
994 __set_current_state(TASK_RUNNING);
995 remove_wait_queue(&audit_backlog_wait, &wait);
996 continue;
998 if (audit_rate_check())
999 printk(KERN_WARNING
1000 "audit: audit_backlog=%d > "
1001 "audit_backlog_limit=%d\n",
1002 skb_queue_len(&audit_skb_queue),
1003 audit_backlog_limit);
1004 audit_log_lost("backlog limit exceeded");
1005 audit_backlog_wait_time = audit_backlog_wait_overflow;
1006 wake_up(&audit_backlog_wait);
1007 return NULL;
1010 ab = audit_buffer_alloc(ctx, gfp_mask, type);
1011 if (!ab) {
1012 audit_log_lost("out of memory in audit_log_start");
1013 return NULL;
1016 audit_get_stamp(ab->ctx, &t, &serial);
1018 audit_log_format(ab, "audit(%lu.%03lu:%u): ",
1019 t.tv_sec, t.tv_nsec/1000000, serial);
1020 return ab;
1024 * audit_expand - expand skb in the audit buffer
1025 * @ab: audit_buffer
1026 * @extra: space to add at tail of the skb
1028 * Returns 0 (no space) on failed expansion, or available space if
1029 * successful.
1031 static inline int audit_expand(struct audit_buffer *ab, int extra)
1033 struct sk_buff *skb = ab->skb;
1034 int oldtail = skb_tailroom(skb);
1035 int ret = pskb_expand_head(skb, 0, extra, ab->gfp_mask);
1036 int newtail = skb_tailroom(skb);
1038 if (ret < 0) {
1039 audit_log_lost("out of memory in audit_expand");
1040 return 0;
1043 skb->truesize += newtail - oldtail;
1044 return newtail;
1048 * Format an audit message into the audit buffer. If there isn't enough
1049 * room in the audit buffer, more room will be allocated and vsnprint
1050 * will be called a second time. Currently, we assume that a printk
1051 * can't format message larger than 1024 bytes, so we don't either.
1053 static void audit_log_vformat(struct audit_buffer *ab, const char *fmt,
1054 va_list args)
1056 int len, avail;
1057 struct sk_buff *skb;
1058 va_list args2;
1060 if (!ab)
1061 return;
1063 BUG_ON(!ab->skb);
1064 skb = ab->skb;
1065 avail = skb_tailroom(skb);
1066 if (avail == 0) {
1067 avail = audit_expand(ab, AUDIT_BUFSIZ);
1068 if (!avail)
1069 goto out;
1071 va_copy(args2, args);
1072 len = vsnprintf(skb_tail_pointer(skb), avail, fmt, args);
1073 if (len >= avail) {
1074 /* The printk buffer is 1024 bytes long, so if we get
1075 * here and AUDIT_BUFSIZ is at least 1024, then we can
1076 * log everything that printk could have logged. */
1077 avail = audit_expand(ab,
1078 max_t(unsigned, AUDIT_BUFSIZ, 1+len-avail));
1079 if (!avail)
1080 goto out;
1081 len = vsnprintf(skb_tail_pointer(skb), avail, fmt, args2);
1083 if (len > 0)
1084 skb_put(skb, len);
1085 out:
1086 return;
1090 * audit_log_format - format a message into the audit buffer.
1091 * @ab: audit_buffer
1092 * @fmt: format string
1093 * @...: optional parameters matching @fmt string
1095 * All the work is done in audit_log_vformat.
1097 void audit_log_format(struct audit_buffer *ab, const char *fmt, ...)
1099 va_list args;
1101 if (!ab)
1102 return;
1103 va_start(args, fmt);
1104 audit_log_vformat(ab, fmt, args);
1105 va_end(args);
1109 * audit_log_hex - convert a buffer to hex and append it to the audit skb
1110 * @ab: the audit_buffer
1111 * @buf: buffer to convert to hex
1112 * @len: length of @buf to be converted
1114 * No return value; failure to expand is silently ignored.
1116 * This function will take the passed buf and convert it into a string of
1117 * ascii hex digits. The new string is placed onto the skb.
1119 void audit_log_hex(struct audit_buffer *ab, const unsigned char *buf,
1120 size_t len)
1122 int i, avail, new_len;
1123 unsigned char *ptr;
1124 struct sk_buff *skb;
1125 static const unsigned char *hex = "0123456789ABCDEF";
1127 if (!ab)
1128 return;
1130 BUG_ON(!ab->skb);
1131 skb = ab->skb;
1132 avail = skb_tailroom(skb);
1133 new_len = len<<1;
1134 if (new_len >= avail) {
1135 /* Round the buffer request up to the next multiple */
1136 new_len = AUDIT_BUFSIZ*(((new_len-avail)/AUDIT_BUFSIZ) + 1);
1137 avail = audit_expand(ab, new_len);
1138 if (!avail)
1139 return;
1142 ptr = skb_tail_pointer(skb);
1143 for (i=0; i<len; i++) {
1144 *ptr++ = hex[(buf[i] & 0xF0)>>4]; /* Upper nibble */
1145 *ptr++ = hex[buf[i] & 0x0F]; /* Lower nibble */
1147 *ptr = 0;
1148 skb_put(skb, len << 1); /* new string is twice the old string */
1152 * Format a string of no more than slen characters into the audit buffer,
1153 * enclosed in quote marks.
1155 static void audit_log_n_string(struct audit_buffer *ab, size_t slen,
1156 const char *string)
1158 int avail, new_len;
1159 unsigned char *ptr;
1160 struct sk_buff *skb;
1162 if (!ab)
1163 return;
1165 BUG_ON(!ab->skb);
1166 skb = ab->skb;
1167 avail = skb_tailroom(skb);
1168 new_len = slen + 3; /* enclosing quotes + null terminator */
1169 if (new_len > avail) {
1170 avail = audit_expand(ab, new_len);
1171 if (!avail)
1172 return;
1174 ptr = skb_tail_pointer(skb);
1175 *ptr++ = '"';
1176 memcpy(ptr, string, slen);
1177 ptr += slen;
1178 *ptr++ = '"';
1179 *ptr = 0;
1180 skb_put(skb, slen + 2); /* don't include null terminator */
1184 * audit_log_n_unstrustedstring - log a string that may contain random characters
1185 * @ab: audit_buffer
1186 * @len: lenth of string (not including trailing null)
1187 * @string: string to be logged
1189 * This code will escape a string that is passed to it if the string
1190 * contains a control character, unprintable character, double quote mark,
1191 * or a space. Unescaped strings will start and end with a double quote mark.
1192 * Strings that are escaped are printed in hex (2 digits per char).
1194 * The caller specifies the number of characters in the string to log, which may
1195 * or may not be the entire string.
1197 const char *audit_log_n_untrustedstring(struct audit_buffer *ab, size_t len,
1198 const char *string)
1200 const unsigned char *p = string;
1202 while (*p) {
1203 if (*p == '"' || *p < 0x21 || *p > 0x7f) {
1204 audit_log_hex(ab, string, len);
1205 return string + len + 1;
1207 p++;
1209 audit_log_n_string(ab, len, string);
1210 return p + 1;
1214 * audit_log_unstrustedstring - log a string that may contain random characters
1215 * @ab: audit_buffer
1216 * @string: string to be logged
1218 * Same as audit_log_n_unstrustedstring(), except that strlen is used to
1219 * determine string length.
1221 const char *audit_log_untrustedstring(struct audit_buffer *ab, const char *string)
1223 return audit_log_n_untrustedstring(ab, strlen(string), string);
1226 /* This is a helper-function to print the escaped d_path */
1227 void audit_log_d_path(struct audit_buffer *ab, const char *prefix,
1228 struct dentry *dentry, struct vfsmount *vfsmnt)
1230 char *p, *path;
1232 if (prefix)
1233 audit_log_format(ab, " %s", prefix);
1235 /* We will allow 11 spaces for ' (deleted)' to be appended */
1236 path = kmalloc(PATH_MAX+11, ab->gfp_mask);
1237 if (!path) {
1238 audit_log_format(ab, "<no memory>");
1239 return;
1241 p = d_path(dentry, vfsmnt, path, PATH_MAX+11);
1242 if (IS_ERR(p)) { /* Should never happen since we send PATH_MAX */
1243 /* FIXME: can we save some information here? */
1244 audit_log_format(ab, "<too long>");
1245 } else
1246 audit_log_untrustedstring(ab, p);
1247 kfree(path);
1251 * audit_log_end - end one audit record
1252 * @ab: the audit_buffer
1254 * The netlink_* functions cannot be called inside an irq context, so
1255 * the audit buffer is placed on a queue and a tasklet is scheduled to
1256 * remove them from the queue outside the irq context. May be called in
1257 * any context.
1259 void audit_log_end(struct audit_buffer *ab)
1261 if (!ab)
1262 return;
1263 if (!audit_rate_check()) {
1264 audit_log_lost("rate limit exceeded");
1265 } else {
1266 if (audit_pid) {
1267 struct nlmsghdr *nlh = nlmsg_hdr(ab->skb);
1268 nlh->nlmsg_len = ab->skb->len - NLMSG_SPACE(0);
1269 skb_queue_tail(&audit_skb_queue, ab->skb);
1270 ab->skb = NULL;
1271 wake_up_interruptible(&kauditd_wait);
1272 } else {
1273 printk(KERN_NOTICE "%s\n", ab->skb->data + NLMSG_SPACE(0));
1276 audit_buffer_free(ab);
1280 * audit_log - Log an audit record
1281 * @ctx: audit context
1282 * @gfp_mask: type of allocation
1283 * @type: audit message type
1284 * @fmt: format string to use
1285 * @...: variable parameters matching the format string
1287 * This is a convenience function that calls audit_log_start,
1288 * audit_log_vformat, and audit_log_end. It may be called
1289 * in any context.
1291 void audit_log(struct audit_context *ctx, gfp_t gfp_mask, int type,
1292 const char *fmt, ...)
1294 struct audit_buffer *ab;
1295 va_list args;
1297 ab = audit_log_start(ctx, gfp_mask, type);
1298 if (ab) {
1299 va_start(args, fmt);
1300 audit_log_vformat(ab, fmt, args);
1301 va_end(args);
1302 audit_log_end(ab);
1306 EXPORT_SYMBOL(audit_log_start);
1307 EXPORT_SYMBOL(audit_log_end);
1308 EXPORT_SYMBOL(audit_log_format);
1309 EXPORT_SYMBOL(audit_log);