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