]> git.karo-electronics.de Git - karo-tx-linux.git/blob - kernel/audit.c
audit: Use current instead of NETLINK_CREDS() in audit_filter
[karo-tx-linux.git] / 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-2007 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 Security Modules.
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 <linux/atomic.h>
47 #include <linux/mm.h>
48 #include <linux/export.h>
49 #include <linux/slab.h>
50 #include <linux/err.h>
51 #include <linux/kthread.h>
52
53 #include <linux/audit.h>
54
55 #include <net/sock.h>
56 #include <net/netlink.h>
57 #include <linux/skbuff.h>
58 #ifdef CONFIG_SECURITY
59 #include <linux/security.h>
60 #endif
61 #include <linux/netlink.h>
62 #include <linux/freezer.h>
63 #include <linux/tty.h>
64 #include <linux/pid_namespace.h>
65
66 #include "audit.h"
67
68 /* No auditing will take place until audit_initialized == AUDIT_INITIALIZED.
69  * (Initialization happens after skb_init is called.) */
70 #define AUDIT_DISABLED          -1
71 #define AUDIT_UNINITIALIZED     0
72 #define AUDIT_INITIALIZED       1
73 static int      audit_initialized;
74
75 #define AUDIT_OFF       0
76 #define AUDIT_ON        1
77 #define AUDIT_LOCKED    2
78 int             audit_enabled;
79 int             audit_ever_enabled;
80
81 EXPORT_SYMBOL_GPL(audit_enabled);
82
83 /* Default state when kernel boots without any parameters. */
84 static int      audit_default;
85
86 /* If auditing cannot proceed, audit_failure selects what happens. */
87 static int      audit_failure = AUDIT_FAIL_PRINTK;
88
89 /*
90  * If audit records are to be written to the netlink socket, audit_pid
91  * contains the pid of the auditd process and audit_nlk_pid contains
92  * the pid to use to send netlink messages to that process.
93  */
94 int             audit_pid;
95 static int      audit_nlk_pid;
96
97 /* If audit_rate_limit is non-zero, limit the rate of sending audit records
98  * to that number per second.  This prevents DoS attacks, but results in
99  * audit records being dropped. */
100 static int      audit_rate_limit;
101
102 /* Number of outstanding audit_buffers allowed. */
103 static int      audit_backlog_limit = 64;
104 static int      audit_backlog_wait_time = 60 * HZ;
105 static int      audit_backlog_wait_overflow = 0;
106
107 /* The identity of the user shutting down the audit system. */
108 uid_t           audit_sig_uid = -1;
109 pid_t           audit_sig_pid = -1;
110 u32             audit_sig_sid = 0;
111
112 /* Records can be lost in several ways:
113    0) [suppressed in audit_alloc]
114    1) out of memory in audit_log_start [kmalloc of struct audit_buffer]
115    2) out of memory in audit_log_move [alloc_skb]
116    3) suppressed due to audit_rate_limit
117    4) suppressed due to audit_backlog_limit
118 */
119 static atomic_t    audit_lost = ATOMIC_INIT(0);
120
121 /* The netlink socket. */
122 static struct sock *audit_sock;
123
124 /* Hash for inode-based rules */
125 struct list_head audit_inode_hash[AUDIT_INODE_BUCKETS];
126
127 /* The audit_freelist is a list of pre-allocated audit buffers (if more
128  * than AUDIT_MAXFREE are in use, the audit buffer is freed instead of
129  * being placed on the freelist). */
130 static DEFINE_SPINLOCK(audit_freelist_lock);
131 static int         audit_freelist_count;
132 static LIST_HEAD(audit_freelist);
133
134 static struct sk_buff_head audit_skb_queue;
135 /* queue of skbs to send to auditd when/if it comes back */
136 static struct sk_buff_head audit_skb_hold_queue;
137 static struct task_struct *kauditd_task;
138 static DECLARE_WAIT_QUEUE_HEAD(kauditd_wait);
139 static DECLARE_WAIT_QUEUE_HEAD(audit_backlog_wait);
140
141 /* Serialize requests from userspace. */
142 DEFINE_MUTEX(audit_cmd_mutex);
143
144 /* AUDIT_BUFSIZ is the size of the temporary buffer used for formatting
145  * audit records.  Since printk uses a 1024 byte buffer, this buffer
146  * should be at least that large. */
147 #define AUDIT_BUFSIZ 1024
148
149 /* AUDIT_MAXFREE is the number of empty audit_buffers we keep on the
150  * audit_freelist.  Doing so eliminates many kmalloc/kfree calls. */
151 #define AUDIT_MAXFREE  (2*NR_CPUS)
152
153 /* The audit_buffer is used when formatting an audit record.  The caller
154  * locks briefly to get the record off the freelist or to allocate the
155  * buffer, and locks briefly to send the buffer to the netlink layer or
156  * to place it on a transmit queue.  Multiple audit_buffers can be in
157  * use simultaneously. */
158 struct audit_buffer {
159         struct list_head     list;
160         struct sk_buff       *skb;      /* formatted skb ready to send */
161         struct audit_context *ctx;      /* NULL or associated context */
162         gfp_t                gfp_mask;
163 };
164
165 struct audit_reply {
166         int pid;
167         struct sk_buff *skb;
168 };
169
170 static void audit_set_pid(struct audit_buffer *ab, pid_t pid)
171 {
172         if (ab) {
173                 struct nlmsghdr *nlh = nlmsg_hdr(ab->skb);
174                 nlh->nlmsg_pid = pid;
175         }
176 }
177
178 void audit_panic(const char *message)
179 {
180         switch (audit_failure)
181         {
182         case AUDIT_FAIL_SILENT:
183                 break;
184         case AUDIT_FAIL_PRINTK:
185                 if (printk_ratelimit())
186                         printk(KERN_ERR "audit: %s\n", message);
187                 break;
188         case AUDIT_FAIL_PANIC:
189                 /* test audit_pid since printk is always losey, why bother? */
190                 if (audit_pid)
191                         panic("audit: %s\n", message);
192                 break;
193         }
194 }
195
196 static inline int audit_rate_check(void)
197 {
198         static unsigned long    last_check = 0;
199         static int              messages   = 0;
200         static DEFINE_SPINLOCK(lock);
201         unsigned long           flags;
202         unsigned long           now;
203         unsigned long           elapsed;
204         int                     retval     = 0;
205
206         if (!audit_rate_limit) return 1;
207
208         spin_lock_irqsave(&lock, flags);
209         if (++messages < audit_rate_limit) {
210                 retval = 1;
211         } else {
212                 now     = jiffies;
213                 elapsed = now - last_check;
214                 if (elapsed > HZ) {
215                         last_check = now;
216                         messages   = 0;
217                         retval     = 1;
218                 }
219         }
220         spin_unlock_irqrestore(&lock, flags);
221
222         return retval;
223 }
224
225 /**
226  * audit_log_lost - conditionally log lost audit message event
227  * @message: the message stating reason for lost audit message
228  *
229  * Emit at least 1 message per second, even if audit_rate_check is
230  * throttling.
231  * Always increment the lost messages counter.
232 */
233 void audit_log_lost(const char *message)
234 {
235         static unsigned long    last_msg = 0;
236         static DEFINE_SPINLOCK(lock);
237         unsigned long           flags;
238         unsigned long           now;
239         int                     print;
240
241         atomic_inc(&audit_lost);
242
243         print = (audit_failure == AUDIT_FAIL_PANIC || !audit_rate_limit);
244
245         if (!print) {
246                 spin_lock_irqsave(&lock, flags);
247                 now = jiffies;
248                 if (now - last_msg > HZ) {
249                         print = 1;
250                         last_msg = now;
251                 }
252                 spin_unlock_irqrestore(&lock, flags);
253         }
254
255         if (print) {
256                 if (printk_ratelimit())
257                         printk(KERN_WARNING
258                                 "audit: audit_lost=%d audit_rate_limit=%d "
259                                 "audit_backlog_limit=%d\n",
260                                 atomic_read(&audit_lost),
261                                 audit_rate_limit,
262                                 audit_backlog_limit);
263                 audit_panic(message);
264         }
265 }
266
267 static int audit_log_config_change(char *function_name, int new, int old,
268                                    uid_t loginuid, u32 sessionid, u32 sid,
269                                    int allow_changes)
270 {
271         struct audit_buffer *ab;
272         int rc = 0;
273
274         ab = audit_log_start(NULL, GFP_KERNEL, AUDIT_CONFIG_CHANGE);
275         audit_log_format(ab, "%s=%d old=%d auid=%u ses=%u", function_name, new,
276                          old, loginuid, sessionid);
277         if (sid) {
278                 char *ctx = NULL;
279                 u32 len;
280
281                 rc = security_secid_to_secctx(sid, &ctx, &len);
282                 if (rc) {
283                         audit_log_format(ab, " sid=%u", sid);
284                         allow_changes = 0; /* Something weird, deny request */
285                 } else {
286                         audit_log_format(ab, " subj=%s", ctx);
287                         security_release_secctx(ctx, len);
288                 }
289         }
290         audit_log_format(ab, " res=%d", allow_changes);
291         audit_log_end(ab);
292         return rc;
293 }
294
295 static int audit_do_config_change(char *function_name, int *to_change,
296                                   int new, uid_t loginuid, u32 sessionid,
297                                   u32 sid)
298 {
299         int allow_changes, rc = 0, old = *to_change;
300
301         /* check if we are locked */
302         if (audit_enabled == AUDIT_LOCKED)
303                 allow_changes = 0;
304         else
305                 allow_changes = 1;
306
307         if (audit_enabled != AUDIT_OFF) {
308                 rc = audit_log_config_change(function_name, new, old, loginuid,
309                                              sessionid, sid, allow_changes);
310                 if (rc)
311                         allow_changes = 0;
312         }
313
314         /* If we are allowed, make the change */
315         if (allow_changes == 1)
316                 *to_change = new;
317         /* Not allowed, update reason */
318         else if (rc == 0)
319                 rc = -EPERM;
320         return rc;
321 }
322
323 static int audit_set_rate_limit(int limit, uid_t loginuid, u32 sessionid,
324                                 u32 sid)
325 {
326         return audit_do_config_change("audit_rate_limit", &audit_rate_limit,
327                                       limit, loginuid, sessionid, sid);
328 }
329
330 static int audit_set_backlog_limit(int limit, uid_t loginuid, u32 sessionid,
331                                    u32 sid)
332 {
333         return audit_do_config_change("audit_backlog_limit", &audit_backlog_limit,
334                                       limit, loginuid, sessionid, sid);
335 }
336
337 static int audit_set_enabled(int state, uid_t loginuid, u32 sessionid, u32 sid)
338 {
339         int rc;
340         if (state < AUDIT_OFF || state > AUDIT_LOCKED)
341                 return -EINVAL;
342
343         rc =  audit_do_config_change("audit_enabled", &audit_enabled, state,
344                                      loginuid, sessionid, sid);
345
346         if (!rc)
347                 audit_ever_enabled |= !!state;
348
349         return rc;
350 }
351
352 static int audit_set_failure(int state, uid_t loginuid, u32 sessionid, u32 sid)
353 {
354         if (state != AUDIT_FAIL_SILENT
355             && state != AUDIT_FAIL_PRINTK
356             && state != AUDIT_FAIL_PANIC)
357                 return -EINVAL;
358
359         return audit_do_config_change("audit_failure", &audit_failure, state,
360                                       loginuid, sessionid, sid);
361 }
362
363 /*
364  * Queue skbs to be sent to auditd when/if it comes back.  These skbs should
365  * already have been sent via prink/syslog and so if these messages are dropped
366  * it is not a huge concern since we already passed the audit_log_lost()
367  * notification and stuff.  This is just nice to get audit messages during
368  * boot before auditd is running or messages generated while auditd is stopped.
369  * This only holds messages is audit_default is set, aka booting with audit=1
370  * or building your kernel that way.
371  */
372 static void audit_hold_skb(struct sk_buff *skb)
373 {
374         if (audit_default &&
375             skb_queue_len(&audit_skb_hold_queue) < audit_backlog_limit)
376                 skb_queue_tail(&audit_skb_hold_queue, skb);
377         else
378                 kfree_skb(skb);
379 }
380
381 /*
382  * For one reason or another this nlh isn't getting delivered to the userspace
383  * audit daemon, just send it to printk.
384  */
385 static void audit_printk_skb(struct sk_buff *skb)
386 {
387         struct nlmsghdr *nlh = nlmsg_hdr(skb);
388         char *data = nlmsg_data(nlh);
389
390         if (nlh->nlmsg_type != AUDIT_EOE) {
391                 if (printk_ratelimit())
392                         printk(KERN_NOTICE "type=%d %s\n", nlh->nlmsg_type, data);
393                 else
394                         audit_log_lost("printk limit exceeded\n");
395         }
396
397         audit_hold_skb(skb);
398 }
399
400 static void kauditd_send_skb(struct sk_buff *skb)
401 {
402         int err;
403         /* take a reference in case we can't send it and we want to hold it */
404         skb_get(skb);
405         err = netlink_unicast(audit_sock, skb, audit_nlk_pid, 0);
406         if (err < 0) {
407                 BUG_ON(err != -ECONNREFUSED); /* Shouldn't happen */
408                 printk(KERN_ERR "audit: *NO* daemon at audit_pid=%d\n", audit_pid);
409                 audit_log_lost("auditd disappeared\n");
410                 audit_pid = 0;
411                 /* we might get lucky and get this in the next auditd */
412                 audit_hold_skb(skb);
413         } else
414                 /* drop the extra reference if sent ok */
415                 consume_skb(skb);
416 }
417
418 static int kauditd_thread(void *dummy)
419 {
420         struct sk_buff *skb;
421
422         set_freezable();
423         while (!kthread_should_stop()) {
424                 /*
425                  * if auditd just started drain the queue of messages already
426                  * sent to syslog/printk.  remember loss here is ok.  we already
427                  * called audit_log_lost() if it didn't go out normally.  so the
428                  * race between the skb_dequeue and the next check for audit_pid
429                  * doesn't matter.
430                  *
431                  * if you ever find kauditd to be too slow we can get a perf win
432                  * by doing our own locking and keeping better track if there
433                  * are messages in this queue.  I don't see the need now, but
434                  * in 5 years when I want to play with this again I'll see this
435                  * note and still have no friggin idea what i'm thinking today.
436                  */
437                 if (audit_default && audit_pid) {
438                         skb = skb_dequeue(&audit_skb_hold_queue);
439                         if (unlikely(skb)) {
440                                 while (skb && audit_pid) {
441                                         kauditd_send_skb(skb);
442                                         skb = skb_dequeue(&audit_skb_hold_queue);
443                                 }
444                         }
445                 }
446
447                 skb = skb_dequeue(&audit_skb_queue);
448                 wake_up(&audit_backlog_wait);
449                 if (skb) {
450                         if (audit_pid)
451                                 kauditd_send_skb(skb);
452                         else
453                                 audit_printk_skb(skb);
454                 } else {
455                         DECLARE_WAITQUEUE(wait, current);
456                         set_current_state(TASK_INTERRUPTIBLE);
457                         add_wait_queue(&kauditd_wait, &wait);
458
459                         if (!skb_queue_len(&audit_skb_queue)) {
460                                 try_to_freeze();
461                                 schedule();
462                         }
463
464                         __set_current_state(TASK_RUNNING);
465                         remove_wait_queue(&kauditd_wait, &wait);
466                 }
467         }
468         return 0;
469 }
470
471 static int audit_prepare_user_tty(pid_t pid, uid_t loginuid, u32 sessionid)
472 {
473         struct task_struct *tsk;
474         int err;
475
476         rcu_read_lock();
477         tsk = find_task_by_vpid(pid);
478         if (!tsk) {
479                 rcu_read_unlock();
480                 return -ESRCH;
481         }
482         get_task_struct(tsk);
483         rcu_read_unlock();
484         err = tty_audit_push_task(tsk, loginuid, sessionid);
485         put_task_struct(tsk);
486         return err;
487 }
488
489 int audit_send_list(void *_dest)
490 {
491         struct audit_netlink_list *dest = _dest;
492         int pid = dest->pid;
493         struct sk_buff *skb;
494
495         /* wait for parent to finish and send an ACK */
496         mutex_lock(&audit_cmd_mutex);
497         mutex_unlock(&audit_cmd_mutex);
498
499         while ((skb = __skb_dequeue(&dest->q)) != NULL)
500                 netlink_unicast(audit_sock, skb, pid, 0);
501
502         kfree(dest);
503
504         return 0;
505 }
506
507 struct sk_buff *audit_make_reply(int pid, int seq, int type, int done,
508                                  int multi, const void *payload, int size)
509 {
510         struct sk_buff  *skb;
511         struct nlmsghdr *nlh;
512         void            *data;
513         int             flags = multi ? NLM_F_MULTI : 0;
514         int             t     = done  ? NLMSG_DONE  : type;
515
516         skb = nlmsg_new(size, GFP_KERNEL);
517         if (!skb)
518                 return NULL;
519
520         nlh     = nlmsg_put(skb, pid, seq, t, size, flags);
521         if (!nlh)
522                 goto out_kfree_skb;
523         data = nlmsg_data(nlh);
524         memcpy(data, payload, size);
525         return skb;
526
527 out_kfree_skb:
528         kfree_skb(skb);
529         return NULL;
530 }
531
532 static int audit_send_reply_thread(void *arg)
533 {
534         struct audit_reply *reply = (struct audit_reply *)arg;
535
536         mutex_lock(&audit_cmd_mutex);
537         mutex_unlock(&audit_cmd_mutex);
538
539         /* Ignore failure. It'll only happen if the sender goes away,
540            because our timeout is set to infinite. */
541         netlink_unicast(audit_sock, reply->skb, reply->pid, 0);
542         kfree(reply);
543         return 0;
544 }
545 /**
546  * audit_send_reply - send an audit reply message via netlink
547  * @pid: process id to send reply to
548  * @seq: sequence number
549  * @type: audit message type
550  * @done: done (last) flag
551  * @multi: multi-part message flag
552  * @payload: payload data
553  * @size: payload size
554  *
555  * Allocates an skb, builds the netlink message, and sends it to the pid.
556  * No failure notifications.
557  */
558 static void audit_send_reply(int pid, int seq, int type, int done, int multi,
559                              const void *payload, int size)
560 {
561         struct sk_buff *skb;
562         struct task_struct *tsk;
563         struct audit_reply *reply = kmalloc(sizeof(struct audit_reply),
564                                             GFP_KERNEL);
565
566         if (!reply)
567                 return;
568
569         skb = audit_make_reply(pid, seq, type, done, multi, payload, size);
570         if (!skb)
571                 goto out;
572
573         reply->pid = pid;
574         reply->skb = skb;
575
576         tsk = kthread_run(audit_send_reply_thread, reply, "audit_send_reply");
577         if (!IS_ERR(tsk))
578                 return;
579         kfree_skb(skb);
580 out:
581         kfree(reply);
582 }
583
584 /*
585  * Check for appropriate CAP_AUDIT_ capabilities on incoming audit
586  * control messages.
587  */
588 static int audit_netlink_ok(struct sk_buff *skb, u16 msg_type)
589 {
590         int err = 0;
591
592         /* Only support the initial namespaces for now. */
593         if ((current_user_ns() != &init_user_ns) ||
594             (task_active_pid_ns(current) != &init_pid_ns))
595                 return -EPERM;
596
597         switch (msg_type) {
598         case AUDIT_GET:
599         case AUDIT_LIST:
600         case AUDIT_LIST_RULES:
601         case AUDIT_SET:
602         case AUDIT_ADD:
603         case AUDIT_ADD_RULE:
604         case AUDIT_DEL:
605         case AUDIT_DEL_RULE:
606         case AUDIT_SIGNAL_INFO:
607         case AUDIT_TTY_GET:
608         case AUDIT_TTY_SET:
609         case AUDIT_TRIM:
610         case AUDIT_MAKE_EQUIV:
611                 if (!capable(CAP_AUDIT_CONTROL))
612                         err = -EPERM;
613                 break;
614         case AUDIT_USER:
615         case AUDIT_FIRST_USER_MSG ... AUDIT_LAST_USER_MSG:
616         case AUDIT_FIRST_USER_MSG2 ... AUDIT_LAST_USER_MSG2:
617                 if (!capable(CAP_AUDIT_WRITE))
618                         err = -EPERM;
619                 break;
620         default:  /* bad msg */
621                 err = -EINVAL;
622         }
623
624         return err;
625 }
626
627 static int audit_log_common_recv_msg(struct audit_buffer **ab, u16 msg_type,
628                                      u32 pid, u32 uid, uid_t auid, u32 ses,
629                                      u32 sid)
630 {
631         int rc = 0;
632         char *ctx = NULL;
633         u32 len;
634
635         if (!audit_enabled) {
636                 *ab = NULL;
637                 return rc;
638         }
639
640         *ab = audit_log_start(NULL, GFP_KERNEL, msg_type);
641         audit_log_format(*ab, "pid=%d uid=%u auid=%u ses=%u",
642                          pid, uid, auid, ses);
643         if (sid) {
644                 rc = security_secid_to_secctx(sid, &ctx, &len);
645                 if (rc)
646                         audit_log_format(*ab, " ssid=%u", sid);
647                 else {
648                         audit_log_format(*ab, " subj=%s", ctx);
649                         security_release_secctx(ctx, len);
650                 }
651         }
652
653         return rc;
654 }
655
656 static int audit_receive_msg(struct sk_buff *skb, struct nlmsghdr *nlh)
657 {
658         u32                     uid, pid, seq, sid;
659         void                    *data;
660         struct audit_status     *status_get, status_set;
661         int                     err;
662         struct audit_buffer     *ab;
663         u16                     msg_type = nlh->nlmsg_type;
664         uid_t                   loginuid; /* loginuid of sender */
665         u32                     sessionid;
666         struct audit_sig_info   *sig_data;
667         char                    *ctx = NULL;
668         u32                     len;
669
670         err = audit_netlink_ok(skb, msg_type);
671         if (err)
672                 return err;
673
674         /* As soon as there's any sign of userspace auditd,
675          * start kauditd to talk to it */
676         if (!kauditd_task)
677                 kauditd_task = kthread_run(kauditd_thread, NULL, "kauditd");
678         if (IS_ERR(kauditd_task)) {
679                 err = PTR_ERR(kauditd_task);
680                 kauditd_task = NULL;
681                 return err;
682         }
683
684         pid  = NETLINK_CREDS(skb)->pid;
685         uid  = NETLINK_CREDS(skb)->uid;
686         loginuid = audit_get_loginuid(current);
687         sessionid = audit_get_sessionid(current);
688         security_task_getsecid(current, &sid);
689         seq  = nlh->nlmsg_seq;
690         data = nlmsg_data(nlh);
691
692         switch (msg_type) {
693         case AUDIT_GET:
694                 status_set.enabled       = audit_enabled;
695                 status_set.failure       = audit_failure;
696                 status_set.pid           = audit_pid;
697                 status_set.rate_limit    = audit_rate_limit;
698                 status_set.backlog_limit = audit_backlog_limit;
699                 status_set.lost          = atomic_read(&audit_lost);
700                 status_set.backlog       = skb_queue_len(&audit_skb_queue);
701                 audit_send_reply(NETLINK_CB(skb).pid, seq, AUDIT_GET, 0, 0,
702                                  &status_set, sizeof(status_set));
703                 break;
704         case AUDIT_SET:
705                 if (nlh->nlmsg_len < sizeof(struct audit_status))
706                         return -EINVAL;
707                 status_get   = (struct audit_status *)data;
708                 if (status_get->mask & AUDIT_STATUS_ENABLED) {
709                         err = audit_set_enabled(status_get->enabled,
710                                                 loginuid, sessionid, sid);
711                         if (err < 0)
712                                 return err;
713                 }
714                 if (status_get->mask & AUDIT_STATUS_FAILURE) {
715                         err = audit_set_failure(status_get->failure,
716                                                 loginuid, sessionid, sid);
717                         if (err < 0)
718                                 return err;
719                 }
720                 if (status_get->mask & AUDIT_STATUS_PID) {
721                         int new_pid = status_get->pid;
722
723                         if (audit_enabled != AUDIT_OFF)
724                                 audit_log_config_change("audit_pid", new_pid,
725                                                         audit_pid, loginuid,
726                                                         sessionid, sid, 1);
727
728                         audit_pid = new_pid;
729                         audit_nlk_pid = NETLINK_CB(skb).pid;
730                 }
731                 if (status_get->mask & AUDIT_STATUS_RATE_LIMIT) {
732                         err = audit_set_rate_limit(status_get->rate_limit,
733                                                    loginuid, sessionid, sid);
734                         if (err < 0)
735                                 return err;
736                 }
737                 if (status_get->mask & AUDIT_STATUS_BACKLOG_LIMIT)
738                         err = audit_set_backlog_limit(status_get->backlog_limit,
739                                                       loginuid, sessionid, sid);
740                 break;
741         case AUDIT_USER:
742         case AUDIT_FIRST_USER_MSG ... AUDIT_LAST_USER_MSG:
743         case AUDIT_FIRST_USER_MSG2 ... AUDIT_LAST_USER_MSG2:
744                 if (!audit_enabled && msg_type != AUDIT_USER_AVC)
745                         return 0;
746
747                 err = audit_filter_user();
748                 if (err == 1) {
749                         err = 0;
750                         if (msg_type == AUDIT_USER_TTY) {
751                                 err = audit_prepare_user_tty(pid, loginuid,
752                                                              sessionid);
753                                 if (err)
754                                         break;
755                         }
756                         audit_log_common_recv_msg(&ab, msg_type, pid, uid,
757                                                   loginuid, sessionid, sid);
758
759                         if (msg_type != AUDIT_USER_TTY)
760                                 audit_log_format(ab, " msg='%.1024s'",
761                                                  (char *)data);
762                         else {
763                                 int size;
764
765                                 audit_log_format(ab, " msg=");
766                                 size = nlmsg_len(nlh);
767                                 if (size > 0 &&
768                                     ((unsigned char *)data)[size - 1] == '\0')
769                                         size--;
770                                 audit_log_n_untrustedstring(ab, data, size);
771                         }
772                         audit_set_pid(ab, pid);
773                         audit_log_end(ab);
774                 }
775                 break;
776         case AUDIT_ADD:
777         case AUDIT_DEL:
778                 if (nlmsg_len(nlh) < sizeof(struct audit_rule))
779                         return -EINVAL;
780                 if (audit_enabled == AUDIT_LOCKED) {
781                         audit_log_common_recv_msg(&ab, AUDIT_CONFIG_CHANGE, pid,
782                                                   uid, loginuid, sessionid, sid);
783
784                         audit_log_format(ab, " audit_enabled=%d res=0",
785                                          audit_enabled);
786                         audit_log_end(ab);
787                         return -EPERM;
788                 }
789                 /* fallthrough */
790         case AUDIT_LIST:
791                 err = audit_receive_filter(msg_type, NETLINK_CB(skb).pid,
792                                            uid, seq, data, nlmsg_len(nlh),
793                                            loginuid, sessionid, sid);
794                 break;
795         case AUDIT_ADD_RULE:
796         case AUDIT_DEL_RULE:
797                 if (nlmsg_len(nlh) < sizeof(struct audit_rule_data))
798                         return -EINVAL;
799                 if (audit_enabled == AUDIT_LOCKED) {
800                         audit_log_common_recv_msg(&ab, AUDIT_CONFIG_CHANGE, pid,
801                                                   uid, loginuid, sessionid, sid);
802
803                         audit_log_format(ab, " audit_enabled=%d res=0",
804                                          audit_enabled);
805                         audit_log_end(ab);
806                         return -EPERM;
807                 }
808                 /* fallthrough */
809         case AUDIT_LIST_RULES:
810                 err = audit_receive_filter(msg_type, NETLINK_CB(skb).pid,
811                                            uid, seq, data, nlmsg_len(nlh),
812                                            loginuid, sessionid, sid);
813                 break;
814         case AUDIT_TRIM:
815                 audit_trim_trees();
816
817                 audit_log_common_recv_msg(&ab, AUDIT_CONFIG_CHANGE, pid,
818                                           uid, loginuid, sessionid, sid);
819
820                 audit_log_format(ab, " op=trim res=1");
821                 audit_log_end(ab);
822                 break;
823         case AUDIT_MAKE_EQUIV: {
824                 void *bufp = data;
825                 u32 sizes[2];
826                 size_t msglen = nlmsg_len(nlh);
827                 char *old, *new;
828
829                 err = -EINVAL;
830                 if (msglen < 2 * sizeof(u32))
831                         break;
832                 memcpy(sizes, bufp, 2 * sizeof(u32));
833                 bufp += 2 * sizeof(u32);
834                 msglen -= 2 * sizeof(u32);
835                 old = audit_unpack_string(&bufp, &msglen, sizes[0]);
836                 if (IS_ERR(old)) {
837                         err = PTR_ERR(old);
838                         break;
839                 }
840                 new = audit_unpack_string(&bufp, &msglen, sizes[1]);
841                 if (IS_ERR(new)) {
842                         err = PTR_ERR(new);
843                         kfree(old);
844                         break;
845                 }
846                 /* OK, here comes... */
847                 err = audit_tag_tree(old, new);
848
849                 audit_log_common_recv_msg(&ab, AUDIT_CONFIG_CHANGE, pid,
850                                           uid, loginuid, sessionid, sid);
851
852                 audit_log_format(ab, " op=make_equiv old=");
853                 audit_log_untrustedstring(ab, old);
854                 audit_log_format(ab, " new=");
855                 audit_log_untrustedstring(ab, new);
856                 audit_log_format(ab, " res=%d", !err);
857                 audit_log_end(ab);
858                 kfree(old);
859                 kfree(new);
860                 break;
861         }
862         case AUDIT_SIGNAL_INFO:
863                 len = 0;
864                 if (audit_sig_sid) {
865                         err = security_secid_to_secctx(audit_sig_sid, &ctx, &len);
866                         if (err)
867                                 return err;
868                 }
869                 sig_data = kmalloc(sizeof(*sig_data) + len, GFP_KERNEL);
870                 if (!sig_data) {
871                         if (audit_sig_sid)
872                                 security_release_secctx(ctx, len);
873                         return -ENOMEM;
874                 }
875                 sig_data->uid = audit_sig_uid;
876                 sig_data->pid = audit_sig_pid;
877                 if (audit_sig_sid) {
878                         memcpy(sig_data->ctx, ctx, len);
879                         security_release_secctx(ctx, len);
880                 }
881                 audit_send_reply(NETLINK_CB(skb).pid, seq, AUDIT_SIGNAL_INFO,
882                                 0, 0, sig_data, sizeof(*sig_data) + len);
883                 kfree(sig_data);
884                 break;
885         case AUDIT_TTY_GET: {
886                 struct audit_tty_status s;
887                 struct task_struct *tsk;
888                 unsigned long flags;
889
890                 rcu_read_lock();
891                 tsk = find_task_by_vpid(pid);
892                 if (tsk && lock_task_sighand(tsk, &flags)) {
893                         s.enabled = tsk->signal->audit_tty != 0;
894                         unlock_task_sighand(tsk, &flags);
895                 } else
896                         err = -ESRCH;
897                 rcu_read_unlock();
898
899                 if (!err)
900                         audit_send_reply(NETLINK_CB(skb).pid, seq,
901                                          AUDIT_TTY_GET, 0, 0, &s, sizeof(s));
902                 break;
903         }
904         case AUDIT_TTY_SET: {
905                 struct audit_tty_status *s;
906                 struct task_struct *tsk;
907                 unsigned long flags;
908
909                 if (nlh->nlmsg_len < sizeof(struct audit_tty_status))
910                         return -EINVAL;
911                 s = data;
912                 if (s->enabled != 0 && s->enabled != 1)
913                         return -EINVAL;
914                 rcu_read_lock();
915                 tsk = find_task_by_vpid(pid);
916                 if (tsk && lock_task_sighand(tsk, &flags)) {
917                         tsk->signal->audit_tty = s->enabled != 0;
918                         unlock_task_sighand(tsk, &flags);
919                 } else
920                         err = -ESRCH;
921                 rcu_read_unlock();
922                 break;
923         }
924         default:
925                 err = -EINVAL;
926                 break;
927         }
928
929         return err < 0 ? err : 0;
930 }
931
932 /*
933  * Get message from skb.  Each message is processed by audit_receive_msg.
934  * Malformed skbs with wrong length are discarded silently.
935  */
936 static void audit_receive_skb(struct sk_buff *skb)
937 {
938         struct nlmsghdr *nlh;
939         /*
940          * len MUST be signed for NLMSG_NEXT to be able to dec it below 0
941          * if the nlmsg_len was not aligned
942          */
943         int len;
944         int err;
945
946         nlh = nlmsg_hdr(skb);
947         len = skb->len;
948
949         while (NLMSG_OK(nlh, len)) {
950                 err = audit_receive_msg(skb, nlh);
951                 /* if err or if this message says it wants a response */
952                 if (err || (nlh->nlmsg_flags & NLM_F_ACK))
953                         netlink_ack(skb, nlh, err);
954
955                 nlh = NLMSG_NEXT(nlh, len);
956         }
957 }
958
959 /* Receive messages from netlink socket. */
960 static void audit_receive(struct sk_buff  *skb)
961 {
962         mutex_lock(&audit_cmd_mutex);
963         audit_receive_skb(skb);
964         mutex_unlock(&audit_cmd_mutex);
965 }
966
967 /* Initialize audit support at boot time. */
968 static int __init audit_init(void)
969 {
970         int i;
971         struct netlink_kernel_cfg cfg = {
972                 .input  = audit_receive,
973         };
974
975         if (audit_initialized == AUDIT_DISABLED)
976                 return 0;
977
978         printk(KERN_INFO "audit: initializing netlink socket (%s)\n",
979                audit_default ? "enabled" : "disabled");
980         audit_sock = netlink_kernel_create(&init_net, NETLINK_AUDIT,
981                                            THIS_MODULE, &cfg);
982         if (!audit_sock)
983                 audit_panic("cannot initialize netlink socket");
984         else
985                 audit_sock->sk_sndtimeo = MAX_SCHEDULE_TIMEOUT;
986
987         skb_queue_head_init(&audit_skb_queue);
988         skb_queue_head_init(&audit_skb_hold_queue);
989         audit_initialized = AUDIT_INITIALIZED;
990         audit_enabled = audit_default;
991         audit_ever_enabled |= !!audit_default;
992
993         audit_log(NULL, GFP_KERNEL, AUDIT_KERNEL, "initialized");
994
995         for (i = 0; i < AUDIT_INODE_BUCKETS; i++)
996                 INIT_LIST_HEAD(&audit_inode_hash[i]);
997
998         return 0;
999 }
1000 __initcall(audit_init);
1001
1002 /* Process kernel command-line parameter at boot time.  audit=0 or audit=1. */
1003 static int __init audit_enable(char *str)
1004 {
1005         audit_default = !!simple_strtol(str, NULL, 0);
1006         if (!audit_default)
1007                 audit_initialized = AUDIT_DISABLED;
1008
1009         printk(KERN_INFO "audit: %s", audit_default ? "enabled" : "disabled");
1010
1011         if (audit_initialized == AUDIT_INITIALIZED) {
1012                 audit_enabled = audit_default;
1013                 audit_ever_enabled |= !!audit_default;
1014         } else if (audit_initialized == AUDIT_UNINITIALIZED) {
1015                 printk(" (after initialization)");
1016         } else {
1017                 printk(" (until reboot)");
1018         }
1019         printk("\n");
1020
1021         return 1;
1022 }
1023
1024 __setup("audit=", audit_enable);
1025
1026 static void audit_buffer_free(struct audit_buffer *ab)
1027 {
1028         unsigned long flags;
1029
1030         if (!ab)
1031                 return;
1032
1033         if (ab->skb)
1034                 kfree_skb(ab->skb);
1035
1036         spin_lock_irqsave(&audit_freelist_lock, flags);
1037         if (audit_freelist_count > AUDIT_MAXFREE)
1038                 kfree(ab);
1039         else {
1040                 audit_freelist_count++;
1041                 list_add(&ab->list, &audit_freelist);
1042         }
1043         spin_unlock_irqrestore(&audit_freelist_lock, flags);
1044 }
1045
1046 static struct audit_buffer * audit_buffer_alloc(struct audit_context *ctx,
1047                                                 gfp_t gfp_mask, int type)
1048 {
1049         unsigned long flags;
1050         struct audit_buffer *ab = NULL;
1051         struct nlmsghdr *nlh;
1052
1053         spin_lock_irqsave(&audit_freelist_lock, flags);
1054         if (!list_empty(&audit_freelist)) {
1055                 ab = list_entry(audit_freelist.next,
1056                                 struct audit_buffer, list);
1057                 list_del(&ab->list);
1058                 --audit_freelist_count;
1059         }
1060         spin_unlock_irqrestore(&audit_freelist_lock, flags);
1061
1062         if (!ab) {
1063                 ab = kmalloc(sizeof(*ab), gfp_mask);
1064                 if (!ab)
1065                         goto err;
1066         }
1067
1068         ab->ctx = ctx;
1069         ab->gfp_mask = gfp_mask;
1070
1071         ab->skb = nlmsg_new(AUDIT_BUFSIZ, gfp_mask);
1072         if (!ab->skb)
1073                 goto err;
1074
1075         nlh = nlmsg_put(ab->skb, 0, 0, type, 0, 0);
1076         if (!nlh)
1077                 goto out_kfree_skb;
1078
1079         return ab;
1080
1081 out_kfree_skb:
1082         kfree_skb(ab->skb);
1083         ab->skb = NULL;
1084 err:
1085         audit_buffer_free(ab);
1086         return NULL;
1087 }
1088
1089 /**
1090  * audit_serial - compute a serial number for the audit record
1091  *
1092  * Compute a serial number for the audit record.  Audit records are
1093  * written to user-space as soon as they are generated, so a complete
1094  * audit record may be written in several pieces.  The timestamp of the
1095  * record and this serial number are used by the user-space tools to
1096  * determine which pieces belong to the same audit record.  The
1097  * (timestamp,serial) tuple is unique for each syscall and is live from
1098  * syscall entry to syscall exit.
1099  *
1100  * NOTE: Another possibility is to store the formatted records off the
1101  * audit context (for those records that have a context), and emit them
1102  * all at syscall exit.  However, this could delay the reporting of
1103  * significant errors until syscall exit (or never, if the system
1104  * halts).
1105  */
1106 unsigned int audit_serial(void)
1107 {
1108         static DEFINE_SPINLOCK(serial_lock);
1109         static unsigned int serial = 0;
1110
1111         unsigned long flags;
1112         unsigned int ret;
1113
1114         spin_lock_irqsave(&serial_lock, flags);
1115         do {
1116                 ret = ++serial;
1117         } while (unlikely(!ret));
1118         spin_unlock_irqrestore(&serial_lock, flags);
1119
1120         return ret;
1121 }
1122
1123 static inline void audit_get_stamp(struct audit_context *ctx,
1124                                    struct timespec *t, unsigned int *serial)
1125 {
1126         if (!ctx || !auditsc_get_stamp(ctx, t, serial)) {
1127                 *t = CURRENT_TIME;
1128                 *serial = audit_serial();
1129         }
1130 }
1131
1132 /* Obtain an audit buffer.  This routine does locking to obtain the
1133  * audit buffer, but then no locking is required for calls to
1134  * audit_log_*format.  If the tsk is a task that is currently in a
1135  * syscall, then the syscall is marked as auditable and an audit record
1136  * will be written at syscall exit.  If there is no associated task, tsk
1137  * should be NULL. */
1138
1139 /**
1140  * audit_log_start - obtain an audit buffer
1141  * @ctx: audit_context (may be NULL)
1142  * @gfp_mask: type of allocation
1143  * @type: audit message type
1144  *
1145  * Returns audit_buffer pointer on success or NULL on error.
1146  *
1147  * Obtain an audit buffer.  This routine does locking to obtain the
1148  * audit buffer, but then no locking is required for calls to
1149  * audit_log_*format.  If the task (ctx) is a task that is currently in a
1150  * syscall, then the syscall is marked as auditable and an audit record
1151  * will be written at syscall exit.  If there is no associated task, then
1152  * task context (ctx) should be NULL.
1153  */
1154 struct audit_buffer *audit_log_start(struct audit_context *ctx, gfp_t gfp_mask,
1155                                      int type)
1156 {
1157         struct audit_buffer     *ab     = NULL;
1158         struct timespec         t;
1159         unsigned int            uninitialized_var(serial);
1160         int reserve;
1161         unsigned long timeout_start = jiffies;
1162
1163         if (audit_initialized != AUDIT_INITIALIZED)
1164                 return NULL;
1165
1166         if (unlikely(audit_filter_type(type)))
1167                 return NULL;
1168
1169         if (gfp_mask & __GFP_WAIT)
1170                 reserve = 0;
1171         else
1172                 reserve = 5; /* Allow atomic callers to go up to five
1173                                 entries over the normal backlog limit */
1174
1175         while (audit_backlog_limit
1176                && skb_queue_len(&audit_skb_queue) > audit_backlog_limit + reserve) {
1177                 if (gfp_mask & __GFP_WAIT && audit_backlog_wait_time
1178                     && time_before(jiffies, timeout_start + audit_backlog_wait_time)) {
1179
1180                         /* Wait for auditd to drain the queue a little */
1181                         DECLARE_WAITQUEUE(wait, current);
1182                         set_current_state(TASK_INTERRUPTIBLE);
1183                         add_wait_queue(&audit_backlog_wait, &wait);
1184
1185                         if (audit_backlog_limit &&
1186                             skb_queue_len(&audit_skb_queue) > audit_backlog_limit)
1187                                 schedule_timeout(timeout_start + audit_backlog_wait_time - jiffies);
1188
1189                         __set_current_state(TASK_RUNNING);
1190                         remove_wait_queue(&audit_backlog_wait, &wait);
1191                         continue;
1192                 }
1193                 if (audit_rate_check() && printk_ratelimit())
1194                         printk(KERN_WARNING
1195                                "audit: audit_backlog=%d > "
1196                                "audit_backlog_limit=%d\n",
1197                                skb_queue_len(&audit_skb_queue),
1198                                audit_backlog_limit);
1199                 audit_log_lost("backlog limit exceeded");
1200                 audit_backlog_wait_time = audit_backlog_wait_overflow;
1201                 wake_up(&audit_backlog_wait);
1202                 return NULL;
1203         }
1204
1205         ab = audit_buffer_alloc(ctx, gfp_mask, type);
1206         if (!ab) {
1207                 audit_log_lost("out of memory in audit_log_start");
1208                 return NULL;
1209         }
1210
1211         audit_get_stamp(ab->ctx, &t, &serial);
1212
1213         audit_log_format(ab, "audit(%lu.%03lu:%u): ",
1214                          t.tv_sec, t.tv_nsec/1000000, serial);
1215         return ab;
1216 }
1217
1218 /**
1219  * audit_expand - expand skb in the audit buffer
1220  * @ab: audit_buffer
1221  * @extra: space to add at tail of the skb
1222  *
1223  * Returns 0 (no space) on failed expansion, or available space if
1224  * successful.
1225  */
1226 static inline int audit_expand(struct audit_buffer *ab, int extra)
1227 {
1228         struct sk_buff *skb = ab->skb;
1229         int oldtail = skb_tailroom(skb);
1230         int ret = pskb_expand_head(skb, 0, extra, ab->gfp_mask);
1231         int newtail = skb_tailroom(skb);
1232
1233         if (ret < 0) {
1234                 audit_log_lost("out of memory in audit_expand");
1235                 return 0;
1236         }
1237
1238         skb->truesize += newtail - oldtail;
1239         return newtail;
1240 }
1241
1242 /*
1243  * Format an audit message into the audit buffer.  If there isn't enough
1244  * room in the audit buffer, more room will be allocated and vsnprint
1245  * will be called a second time.  Currently, we assume that a printk
1246  * can't format message larger than 1024 bytes, so we don't either.
1247  */
1248 static void audit_log_vformat(struct audit_buffer *ab, const char *fmt,
1249                               va_list args)
1250 {
1251         int len, avail;
1252         struct sk_buff *skb;
1253         va_list args2;
1254
1255         if (!ab)
1256                 return;
1257
1258         BUG_ON(!ab->skb);
1259         skb = ab->skb;
1260         avail = skb_tailroom(skb);
1261         if (avail == 0) {
1262                 avail = audit_expand(ab, AUDIT_BUFSIZ);
1263                 if (!avail)
1264                         goto out;
1265         }
1266         va_copy(args2, args);
1267         len = vsnprintf(skb_tail_pointer(skb), avail, fmt, args);
1268         if (len >= avail) {
1269                 /* The printk buffer is 1024 bytes long, so if we get
1270                  * here and AUDIT_BUFSIZ is at least 1024, then we can
1271                  * log everything that printk could have logged. */
1272                 avail = audit_expand(ab,
1273                         max_t(unsigned, AUDIT_BUFSIZ, 1+len-avail));
1274                 if (!avail)
1275                         goto out_va_end;
1276                 len = vsnprintf(skb_tail_pointer(skb), avail, fmt, args2);
1277         }
1278         if (len > 0)
1279                 skb_put(skb, len);
1280 out_va_end:
1281         va_end(args2);
1282 out:
1283         return;
1284 }
1285
1286 /**
1287  * audit_log_format - format a message into the audit buffer.
1288  * @ab: audit_buffer
1289  * @fmt: format string
1290  * @...: optional parameters matching @fmt string
1291  *
1292  * All the work is done in audit_log_vformat.
1293  */
1294 void audit_log_format(struct audit_buffer *ab, const char *fmt, ...)
1295 {
1296         va_list args;
1297
1298         if (!ab)
1299                 return;
1300         va_start(args, fmt);
1301         audit_log_vformat(ab, fmt, args);
1302         va_end(args);
1303 }
1304
1305 /**
1306  * audit_log_hex - convert a buffer to hex and append it to the audit skb
1307  * @ab: the audit_buffer
1308  * @buf: buffer to convert to hex
1309  * @len: length of @buf to be converted
1310  *
1311  * No return value; failure to expand is silently ignored.
1312  *
1313  * This function will take the passed buf and convert it into a string of
1314  * ascii hex digits. The new string is placed onto the skb.
1315  */
1316 void audit_log_n_hex(struct audit_buffer *ab, const unsigned char *buf,
1317                 size_t len)
1318 {
1319         int i, avail, new_len;
1320         unsigned char *ptr;
1321         struct sk_buff *skb;
1322         static const unsigned char *hex = "0123456789ABCDEF";
1323
1324         if (!ab)
1325                 return;
1326
1327         BUG_ON(!ab->skb);
1328         skb = ab->skb;
1329         avail = skb_tailroom(skb);
1330         new_len = len<<1;
1331         if (new_len >= avail) {
1332                 /* Round the buffer request up to the next multiple */
1333                 new_len = AUDIT_BUFSIZ*(((new_len-avail)/AUDIT_BUFSIZ) + 1);
1334                 avail = audit_expand(ab, new_len);
1335                 if (!avail)
1336                         return;
1337         }
1338
1339         ptr = skb_tail_pointer(skb);
1340         for (i=0; i<len; i++) {
1341                 *ptr++ = hex[(buf[i] & 0xF0)>>4]; /* Upper nibble */
1342                 *ptr++ = hex[buf[i] & 0x0F];      /* Lower nibble */
1343         }
1344         *ptr = 0;
1345         skb_put(skb, len << 1); /* new string is twice the old string */
1346 }
1347
1348 /*
1349  * Format a string of no more than slen characters into the audit buffer,
1350  * enclosed in quote marks.
1351  */
1352 void audit_log_n_string(struct audit_buffer *ab, const char *string,
1353                         size_t slen)
1354 {
1355         int avail, new_len;
1356         unsigned char *ptr;
1357         struct sk_buff *skb;
1358
1359         if (!ab)
1360                 return;
1361
1362         BUG_ON(!ab->skb);
1363         skb = ab->skb;
1364         avail = skb_tailroom(skb);
1365         new_len = slen + 3;     /* enclosing quotes + null terminator */
1366         if (new_len > avail) {
1367                 avail = audit_expand(ab, new_len);
1368                 if (!avail)
1369                         return;
1370         }
1371         ptr = skb_tail_pointer(skb);
1372         *ptr++ = '"';
1373         memcpy(ptr, string, slen);
1374         ptr += slen;
1375         *ptr++ = '"';
1376         *ptr = 0;
1377         skb_put(skb, slen + 2); /* don't include null terminator */
1378 }
1379
1380 /**
1381  * audit_string_contains_control - does a string need to be logged in hex
1382  * @string: string to be checked
1383  * @len: max length of the string to check
1384  */
1385 int audit_string_contains_control(const char *string, size_t len)
1386 {
1387         const unsigned char *p;
1388         for (p = string; p < (const unsigned char *)string + len; p++) {
1389                 if (*p == '"' || *p < 0x21 || *p > 0x7e)
1390                         return 1;
1391         }
1392         return 0;
1393 }
1394
1395 /**
1396  * audit_log_n_untrustedstring - log a string that may contain random characters
1397  * @ab: audit_buffer
1398  * @len: length of string (not including trailing null)
1399  * @string: string to be logged
1400  *
1401  * This code will escape a string that is passed to it if the string
1402  * contains a control character, unprintable character, double quote mark,
1403  * or a space. Unescaped strings will start and end with a double quote mark.
1404  * Strings that are escaped are printed in hex (2 digits per char).
1405  *
1406  * The caller specifies the number of characters in the string to log, which may
1407  * or may not be the entire string.
1408  */
1409 void audit_log_n_untrustedstring(struct audit_buffer *ab, const char *string,
1410                                  size_t len)
1411 {
1412         if (audit_string_contains_control(string, len))
1413                 audit_log_n_hex(ab, string, len);
1414         else
1415                 audit_log_n_string(ab, string, len);
1416 }
1417
1418 /**
1419  * audit_log_untrustedstring - log a string that may contain random characters
1420  * @ab: audit_buffer
1421  * @string: string to be logged
1422  *
1423  * Same as audit_log_n_untrustedstring(), except that strlen is used to
1424  * determine string length.
1425  */
1426 void audit_log_untrustedstring(struct audit_buffer *ab, const char *string)
1427 {
1428         audit_log_n_untrustedstring(ab, string, strlen(string));
1429 }
1430
1431 /* This is a helper-function to print the escaped d_path */
1432 void audit_log_d_path(struct audit_buffer *ab, const char *prefix,
1433                       const struct path *path)
1434 {
1435         char *p, *pathname;
1436
1437         if (prefix)
1438                 audit_log_format(ab, "%s", prefix);
1439
1440         /* We will allow 11 spaces for ' (deleted)' to be appended */
1441         pathname = kmalloc(PATH_MAX+11, ab->gfp_mask);
1442         if (!pathname) {
1443                 audit_log_string(ab, "<no_memory>");
1444                 return;
1445         }
1446         p = d_path(path, pathname, PATH_MAX+11);
1447         if (IS_ERR(p)) { /* Should never happen since we send PATH_MAX */
1448                 /* FIXME: can we save some information here? */
1449                 audit_log_string(ab, "<too_long>");
1450         } else
1451                 audit_log_untrustedstring(ab, p);
1452         kfree(pathname);
1453 }
1454
1455 void audit_log_key(struct audit_buffer *ab, char *key)
1456 {
1457         audit_log_format(ab, " key=");
1458         if (key)
1459                 audit_log_untrustedstring(ab, key);
1460         else
1461                 audit_log_format(ab, "(null)");
1462 }
1463
1464 /**
1465  * audit_log_link_denied - report a link restriction denial
1466  * @operation: specific link opreation
1467  * @link: the path that triggered the restriction
1468  */
1469 void audit_log_link_denied(const char *operation, struct path *link)
1470 {
1471         struct audit_buffer *ab;
1472
1473         ab = audit_log_start(current->audit_context, GFP_KERNEL,
1474                              AUDIT_ANOM_LINK);
1475         audit_log_format(ab, "op=%s action=denied", operation);
1476         audit_log_format(ab, " pid=%d comm=", current->pid);
1477         audit_log_untrustedstring(ab, current->comm);
1478         audit_log_d_path(ab, " path=", link);
1479         audit_log_format(ab, " dev=");
1480         audit_log_untrustedstring(ab, link->dentry->d_inode->i_sb->s_id);
1481         audit_log_format(ab, " ino=%lu", link->dentry->d_inode->i_ino);
1482         audit_log_end(ab);
1483 }
1484
1485 /**
1486  * audit_log_end - end one audit record
1487  * @ab: the audit_buffer
1488  *
1489  * The netlink_* functions cannot be called inside an irq context, so
1490  * the audit buffer is placed on a queue and a tasklet is scheduled to
1491  * remove them from the queue outside the irq context.  May be called in
1492  * any context.
1493  */
1494 void audit_log_end(struct audit_buffer *ab)
1495 {
1496         if (!ab)
1497                 return;
1498         if (!audit_rate_check()) {
1499                 audit_log_lost("rate limit exceeded");
1500         } else {
1501                 struct nlmsghdr *nlh = nlmsg_hdr(ab->skb);
1502                 nlh->nlmsg_len = ab->skb->len - NLMSG_SPACE(0);
1503
1504                 if (audit_pid) {
1505                         skb_queue_tail(&audit_skb_queue, ab->skb);
1506                         wake_up_interruptible(&kauditd_wait);
1507                 } else {
1508                         audit_printk_skb(ab->skb);
1509                 }
1510                 ab->skb = NULL;
1511         }
1512         audit_buffer_free(ab);
1513 }
1514
1515 /**
1516  * audit_log - Log an audit record
1517  * @ctx: audit context
1518  * @gfp_mask: type of allocation
1519  * @type: audit message type
1520  * @fmt: format string to use
1521  * @...: variable parameters matching the format string
1522  *
1523  * This is a convenience function that calls audit_log_start,
1524  * audit_log_vformat, and audit_log_end.  It may be called
1525  * in any context.
1526  */
1527 void audit_log(struct audit_context *ctx, gfp_t gfp_mask, int type,
1528                const char *fmt, ...)
1529 {
1530         struct audit_buffer *ab;
1531         va_list args;
1532
1533         ab = audit_log_start(ctx, gfp_mask, type);
1534         if (ab) {
1535                 va_start(args, fmt);
1536                 audit_log_vformat(ab, fmt, args);
1537                 va_end(args);
1538                 audit_log_end(ab);
1539         }
1540 }
1541
1542 #ifdef CONFIG_SECURITY
1543 /**
1544  * audit_log_secctx - Converts and logs SELinux context
1545  * @ab: audit_buffer
1546  * @secid: security number
1547  *
1548  * This is a helper function that calls security_secid_to_secctx to convert
1549  * secid to secctx and then adds the (converted) SELinux context to the audit
1550  * log by calling audit_log_format, thus also preventing leak of internal secid
1551  * to userspace. If secid cannot be converted audit_panic is called.
1552  */
1553 void audit_log_secctx(struct audit_buffer *ab, u32 secid)
1554 {
1555         u32 len;
1556         char *secctx;
1557
1558         if (security_secid_to_secctx(secid, &secctx, &len)) {
1559                 audit_panic("Cannot convert secid to context");
1560         } else {
1561                 audit_log_format(ab, " obj=%s", secctx);
1562                 security_release_secctx(secctx, len);
1563         }
1564 }
1565 EXPORT_SYMBOL(audit_log_secctx);
1566 #endif
1567
1568 EXPORT_SYMBOL(audit_log_start);
1569 EXPORT_SYMBOL(audit_log_end);
1570 EXPORT_SYMBOL(audit_log_format);
1571 EXPORT_SYMBOL(audit_log);