netns: avoid disabling irq for netns id
[GitHub/MotorolaMobilityLLC/kernel-slsi.git] / kernel / audit.c
CommitLineData
85c8721f 1/* audit.c -- Auditing support
1da177e4
LT
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 *
6a01b07f 5 * Copyright 2003-2007 Red Hat Inc., Durham, North Carolina.
1da177e4
LT
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 *
d7a96f3a 24 * Goals: 1) Integrate fully with Security Modules.
1da177e4
LT
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 *
85c8721f 41 * Example user-space utilities: http://people.redhat.com/sgrubb/audit/
1da177e4
LT
42 */
43
d957f7b7
JP
44#define pr_fmt(fmt) KBUILD_MODNAME ": " fmt
45
5b282552 46#include <linux/file.h>
1da177e4 47#include <linux/init.h>
7153e402 48#include <linux/types.h>
60063497 49#include <linux/atomic.h>
1da177e4 50#include <linux/mm.h>
9984de1a 51#include <linux/export.h>
5a0e3ad6 52#include <linux/slab.h>
b7d11258
DW
53#include <linux/err.h>
54#include <linux/kthread.h>
46e959ea 55#include <linux/kernel.h>
b24a30a7 56#include <linux/syscalls.h>
1da177e4
LT
57
58#include <linux/audit.h>
59
60#include <net/sock.h>
93315ed6 61#include <net/netlink.h>
1da177e4 62#include <linux/skbuff.h>
131ad62d
MDF
63#ifdef CONFIG_SECURITY
64#include <linux/security.h>
65#endif
7dfb7103 66#include <linux/freezer.h>
34e36d8e 67#include <linux/pid_namespace.h>
33faba7f 68#include <net/netns/generic.h>
3dc7e315
DG
69
70#include "audit.h"
1da177e4 71
a3f07114 72/* No auditing will take place until audit_initialized == AUDIT_INITIALIZED.
1da177e4 73 * (Initialization happens after skb_init is called.) */
a3f07114
EP
74#define AUDIT_DISABLED -1
75#define AUDIT_UNINITIALIZED 0
76#define AUDIT_INITIALIZED 1
1da177e4
LT
77static int audit_initialized;
78
1a6b9f23
EP
79#define AUDIT_OFF 0
80#define AUDIT_ON 1
81#define AUDIT_LOCKED 2
3e1d0bb6
JP
82u32 audit_enabled;
83u32 audit_ever_enabled;
1da177e4 84
ae9d67af
JE
85EXPORT_SYMBOL_GPL(audit_enabled);
86
1da177e4 87/* Default state when kernel boots without any parameters. */
3e1d0bb6 88static u32 audit_default;
1da177e4
LT
89
90/* If auditing cannot proceed, audit_failure selects what happens. */
3e1d0bb6 91static u32 audit_failure = AUDIT_FAIL_PRINTK;
1da177e4 92
75c0371a
PE
93/*
94 * If audit records are to be written to the netlink socket, audit_pid
15e47304
EB
95 * contains the pid of the auditd process and audit_nlk_portid contains
96 * the portid to use to send netlink messages to that process.
75c0371a 97 */
c2f0c7c3 98int audit_pid;
f9441639 99static __u32 audit_nlk_portid;
1da177e4 100
b0dd25a8 101/* If audit_rate_limit is non-zero, limit the rate of sending audit records
1da177e4
LT
102 * to that number per second. This prevents DoS attacks, but results in
103 * audit records being dropped. */
3e1d0bb6 104static u32 audit_rate_limit;
1da177e4 105
40c0775e
RGB
106/* Number of outstanding audit_buffers allowed.
107 * When set to zero, this means unlimited. */
3e1d0bb6 108static u32 audit_backlog_limit = 64;
e789e561 109#define AUDIT_BACKLOG_WAIT_TIME (60 * HZ)
3e1d0bb6 110static u32 audit_backlog_wait_time = AUDIT_BACKLOG_WAIT_TIME;
1da177e4 111
c2f0c7c3 112/* The identity of the user shutting down the audit system. */
cca080d9 113kuid_t audit_sig_uid = INVALID_UID;
c2f0c7c3 114pid_t audit_sig_pid = -1;
e1396065 115u32 audit_sig_sid = 0;
c2f0c7c3 116
1da177e4
LT
117/* Records can be lost in several ways:
118 0) [suppressed in audit_alloc]
119 1) out of memory in audit_log_start [kmalloc of struct audit_buffer]
120 2) out of memory in audit_log_move [alloc_skb]
121 3) suppressed due to audit_rate_limit
122 4) suppressed due to audit_backlog_limit
123*/
124static atomic_t audit_lost = ATOMIC_INIT(0);
125
126/* The netlink socket. */
127static struct sock *audit_sock;
c0a8d9b0 128static int audit_net_id;
1da177e4 129
f368c07d
AG
130/* Hash for inode-based rules */
131struct list_head audit_inode_hash[AUDIT_INODE_BUCKETS];
132
b7d11258 133/* The audit_freelist is a list of pre-allocated audit buffers (if more
1da177e4
LT
134 * than AUDIT_MAXFREE are in use, the audit buffer is freed instead of
135 * being placed on the freelist). */
1da177e4 136static DEFINE_SPINLOCK(audit_freelist_lock);
b0dd25a8 137static int audit_freelist_count;
1da177e4
LT
138static LIST_HEAD(audit_freelist);
139
c6480207 140/* queue msgs to send via kauditd_task */
af8b824f 141static struct sk_buff_head audit_queue;
c6480207
PM
142/* queue msgs due to temporary unicast send problems */
143static struct sk_buff_head audit_retry_queue;
144/* queue msgs waiting for new auditd connection */
af8b824f 145static struct sk_buff_head audit_hold_queue;
c6480207
PM
146
147/* queue servicing thread */
b7d11258
DW
148static struct task_struct *kauditd_task;
149static DECLARE_WAIT_QUEUE_HEAD(kauditd_wait);
c6480207
PM
150
151/* waitqueue for callers who are blocked on the audit backlog */
9ad9ad38 152static DECLARE_WAIT_QUEUE_HEAD(audit_backlog_wait);
1da177e4 153
b0fed402
EP
154static struct audit_features af = {.vers = AUDIT_FEATURE_VERSION,
155 .mask = -1,
156 .features = 0,
157 .lock = 0,};
158
21b85c31 159static char *audit_feature_names[2] = {
d040e5af 160 "only_unset_loginuid",
21b85c31 161 "loginuid_immutable",
b0fed402
EP
162};
163
164
f368c07d 165/* Serialize requests from userspace. */
916d7576 166DEFINE_MUTEX(audit_cmd_mutex);
1da177e4
LT
167
168/* AUDIT_BUFSIZ is the size of the temporary buffer used for formatting
169 * audit records. Since printk uses a 1024 byte buffer, this buffer
170 * should be at least that large. */
171#define AUDIT_BUFSIZ 1024
172
173/* AUDIT_MAXFREE is the number of empty audit_buffers we keep on the
174 * audit_freelist. Doing so eliminates many kmalloc/kfree calls. */
175#define AUDIT_MAXFREE (2*NR_CPUS)
176
177/* The audit_buffer is used when formatting an audit record. The caller
178 * locks briefly to get the record off the freelist or to allocate the
179 * buffer, and locks briefly to send the buffer to the netlink layer or
180 * to place it on a transmit queue. Multiple audit_buffers can be in
181 * use simultaneously. */
182struct audit_buffer {
183 struct list_head list;
8fc6115c 184 struct sk_buff *skb; /* formatted skb ready to send */
1da177e4 185 struct audit_context *ctx; /* NULL or associated context */
9796fdd8 186 gfp_t gfp_mask;
1da177e4
LT
187};
188
f09ac9db 189struct audit_reply {
f9441639 190 __u32 portid;
638a0fd2 191 struct net *net;
f09ac9db
EP
192 struct sk_buff *skb;
193};
194
f9441639 195static void audit_set_portid(struct audit_buffer *ab, __u32 portid)
c0404993 196{
50397bd1
EP
197 if (ab) {
198 struct nlmsghdr *nlh = nlmsg_hdr(ab->skb);
f9441639 199 nlh->nlmsg_pid = portid;
50397bd1 200 }
c0404993
SG
201}
202
8c8570fb 203void audit_panic(const char *message)
1da177e4 204{
d957f7b7 205 switch (audit_failure) {
1da177e4
LT
206 case AUDIT_FAIL_SILENT:
207 break;
208 case AUDIT_FAIL_PRINTK:
320f1b1e 209 if (printk_ratelimit())
d957f7b7 210 pr_err("%s\n", message);
1da177e4
LT
211 break;
212 case AUDIT_FAIL_PANIC:
b29ee87e
EP
213 /* test audit_pid since printk is always losey, why bother? */
214 if (audit_pid)
215 panic("audit: %s\n", message);
1da177e4
LT
216 break;
217 }
218}
219
220static inline int audit_rate_check(void)
221{
222 static unsigned long last_check = 0;
223 static int messages = 0;
224 static DEFINE_SPINLOCK(lock);
225 unsigned long flags;
226 unsigned long now;
227 unsigned long elapsed;
228 int retval = 0;
229
230 if (!audit_rate_limit) return 1;
231
232 spin_lock_irqsave(&lock, flags);
233 if (++messages < audit_rate_limit) {
234 retval = 1;
235 } else {
236 now = jiffies;
237 elapsed = now - last_check;
238 if (elapsed > HZ) {
239 last_check = now;
240 messages = 0;
241 retval = 1;
242 }
243 }
244 spin_unlock_irqrestore(&lock, flags);
245
246 return retval;
247}
248
b0dd25a8
RD
249/**
250 * audit_log_lost - conditionally log lost audit message event
251 * @message: the message stating reason for lost audit message
252 *
253 * Emit at least 1 message per second, even if audit_rate_check is
254 * throttling.
255 * Always increment the lost messages counter.
256*/
1da177e4
LT
257void audit_log_lost(const char *message)
258{
259 static unsigned long last_msg = 0;
260 static DEFINE_SPINLOCK(lock);
261 unsigned long flags;
262 unsigned long now;
263 int print;
264
265 atomic_inc(&audit_lost);
266
267 print = (audit_failure == AUDIT_FAIL_PANIC || !audit_rate_limit);
268
269 if (!print) {
270 spin_lock_irqsave(&lock, flags);
271 now = jiffies;
272 if (now - last_msg > HZ) {
273 print = 1;
274 last_msg = now;
275 }
276 spin_unlock_irqrestore(&lock, flags);
277 }
278
279 if (print) {
320f1b1e 280 if (printk_ratelimit())
3e1d0bb6 281 pr_warn("audit_lost=%u audit_rate_limit=%u audit_backlog_limit=%u\n",
320f1b1e
EP
282 atomic_read(&audit_lost),
283 audit_rate_limit,
284 audit_backlog_limit);
1da177e4
LT
285 audit_panic(message);
286 }
1da177e4
LT
287}
288
3e1d0bb6 289static int audit_log_config_change(char *function_name, u32 new, u32 old,
2532386f 290 int allow_changes)
1da177e4 291{
1a6b9f23
EP
292 struct audit_buffer *ab;
293 int rc = 0;
ce29b682 294
1a6b9f23 295 ab = audit_log_start(NULL, GFP_KERNEL, AUDIT_CONFIG_CHANGE);
0644ec0c
KC
296 if (unlikely(!ab))
297 return rc;
3e1d0bb6 298 audit_log_format(ab, "%s=%u old=%u", function_name, new, old);
4d3fb709 299 audit_log_session_info(ab);
b122c376
EP
300 rc = audit_log_task_context(ab);
301 if (rc)
302 allow_changes = 0; /* Something weird, deny request */
1a6b9f23
EP
303 audit_log_format(ab, " res=%d", allow_changes);
304 audit_log_end(ab);
6a01b07f 305 return rc;
1da177e4
LT
306}
307
3e1d0bb6 308static int audit_do_config_change(char *function_name, u32 *to_change, u32 new)
1da177e4 309{
3e1d0bb6
JP
310 int allow_changes, rc = 0;
311 u32 old = *to_change;
6a01b07f
SG
312
313 /* check if we are locked */
1a6b9f23
EP
314 if (audit_enabled == AUDIT_LOCKED)
315 allow_changes = 0;
6a01b07f 316 else
1a6b9f23 317 allow_changes = 1;
ce29b682 318
1a6b9f23 319 if (audit_enabled != AUDIT_OFF) {
dc9eb698 320 rc = audit_log_config_change(function_name, new, old, allow_changes);
1a6b9f23
EP
321 if (rc)
322 allow_changes = 0;
6a01b07f 323 }
6a01b07f
SG
324
325 /* If we are allowed, make the change */
1a6b9f23
EP
326 if (allow_changes == 1)
327 *to_change = new;
6a01b07f
SG
328 /* Not allowed, update reason */
329 else if (rc == 0)
330 rc = -EPERM;
331 return rc;
1da177e4
LT
332}
333
3e1d0bb6 334static int audit_set_rate_limit(u32 limit)
1da177e4 335{
dc9eb698 336 return audit_do_config_change("audit_rate_limit", &audit_rate_limit, limit);
1a6b9f23 337}
ce29b682 338
3e1d0bb6 339static int audit_set_backlog_limit(u32 limit)
1a6b9f23 340{
dc9eb698 341 return audit_do_config_change("audit_backlog_limit", &audit_backlog_limit, limit);
1a6b9f23 342}
6a01b07f 343
3e1d0bb6 344static int audit_set_backlog_wait_time(u32 timeout)
51cc83f0
RGB
345{
346 return audit_do_config_change("audit_backlog_wait_time",
31975424 347 &audit_backlog_wait_time, timeout);
51cc83f0
RGB
348}
349
3e1d0bb6 350static int audit_set_enabled(u32 state)
1a6b9f23 351{
b593d384 352 int rc;
724e7bfc 353 if (state > AUDIT_LOCKED)
1a6b9f23 354 return -EINVAL;
6a01b07f 355
dc9eb698 356 rc = audit_do_config_change("audit_enabled", &audit_enabled, state);
b593d384
EP
357 if (!rc)
358 audit_ever_enabled |= !!state;
359
360 return rc;
1da177e4
LT
361}
362
3e1d0bb6 363static int audit_set_failure(u32 state)
1da177e4 364{
1da177e4
LT
365 if (state != AUDIT_FAIL_SILENT
366 && state != AUDIT_FAIL_PRINTK
367 && state != AUDIT_FAIL_PANIC)
368 return -EINVAL;
ce29b682 369
dc9eb698 370 return audit_do_config_change("audit_failure", &audit_failure, state);
1da177e4
LT
371}
372
038cbcf6
EP
373/*
374 * For one reason or another this nlh isn't getting delivered to the userspace
375 * audit daemon, just send it to printk.
376 */
af8b824f 377static void kauditd_printk_skb(struct sk_buff *skb)
038cbcf6
EP
378{
379 struct nlmsghdr *nlh = nlmsg_hdr(skb);
c64e66c6 380 char *data = nlmsg_data(nlh);
038cbcf6
EP
381
382 if (nlh->nlmsg_type != AUDIT_EOE) {
383 if (printk_ratelimit())
d957f7b7 384 pr_notice("type=%d %s\n", nlh->nlmsg_type, data);
038cbcf6 385 else
f1283527 386 audit_log_lost("printk limit exceeded");
038cbcf6 387 }
c6480207
PM
388}
389
390/**
391 * kauditd_hold_skb - Queue an audit record, waiting for auditd
392 * @skb: audit record
393 *
394 * Description:
395 * Queue the audit record, waiting for an instance of auditd. When this
396 * function is called we haven't given up yet on sending the record, but things
397 * are not looking good. The first thing we want to do is try to write the
398 * record via printk and then see if we want to try and hold on to the record
399 * and queue it, if we have room. If we want to hold on to the record, but we
400 * don't have room, record a record lost message.
401 */
402static void kauditd_hold_skb(struct sk_buff *skb)
403{
404 /* at this point it is uncertain if we will ever send this to auditd so
405 * try to send the message via printk before we go any further */
406 kauditd_printk_skb(skb);
407
408 /* can we just silently drop the message? */
409 if (!audit_default) {
410 kfree_skb(skb);
411 return;
412 }
413
414 /* if we have room, queue the message */
415 if (!audit_backlog_limit ||
416 skb_queue_len(&audit_hold_queue) < audit_backlog_limit) {
417 skb_queue_tail(&audit_hold_queue, skb);
418 return;
419 }
038cbcf6 420
c6480207
PM
421 /* we have no other options - drop the message */
422 audit_log_lost("kauditd hold queue overflow");
423 kfree_skb(skb);
038cbcf6
EP
424}
425
c6480207
PM
426/**
427 * kauditd_retry_skb - Queue an audit record, attempt to send again to auditd
428 * @skb: audit record
429 *
430 * Description:
431 * Not as serious as kauditd_hold_skb() as we still have a connected auditd,
432 * but for some reason we are having problems sending it audit records so
433 * queue the given record and attempt to resend.
434 */
435static void kauditd_retry_skb(struct sk_buff *skb)
f3d357b0 436{
c6480207
PM
437 /* NOTE: because records should only live in the retry queue for a
438 * short period of time, before either being sent or moved to the hold
439 * queue, we don't currently enforce a limit on this queue */
440 skb_queue_tail(&audit_retry_queue, skb);
441}
32a1dbae 442
c6480207
PM
443/**
444 * auditd_reset - Disconnect the auditd connection
445 *
446 * Description:
447 * Break the auditd/kauditd connection and move all the records in the retry
448 * queue into the hold queue in case auditd reconnects.
449 */
450static void auditd_reset(void)
451{
452 struct sk_buff *skb;
453
454 /* break the connection */
455 audit_pid = 0;
456 audit_sock = NULL;
457
458 /* flush all of the retry queue to the hold queue */
459 while ((skb = skb_dequeue(&audit_retry_queue)))
460 kauditd_hold_skb(skb);
461}
462
463/**
464 * kauditd_send_unicast_skb - Send a record via unicast to auditd
465 * @skb: audit record
466 */
467static int kauditd_send_unicast_skb(struct sk_buff *skb)
468{
469 int rc;
470
6c54e789
PM
471 /* if we know nothing is connected, don't even try the netlink call */
472 if (!audit_pid)
473 return -ECONNREFUSED;
474
c6480207 475 /* get an extra skb reference in case we fail to send */
f3d357b0 476 skb_get(skb);
c6480207
PM
477 rc = netlink_unicast(audit_sock, skb, audit_nlk_portid, 0);
478 if (rc >= 0) {
70d4bf6d 479 consume_skb(skb);
c6480207
PM
480 rc = 0;
481 }
482
483 return rc;
f3d357b0
EP
484}
485
451f9216 486/*
c6480207
PM
487 * kauditd_send_multicast_skb - Send a record to any multicast listeners
488 * @skb: audit record
451f9216 489 *
c6480207 490 * Description:
451f9216
RGB
491 * This function doesn't consume an skb as might be expected since it has to
492 * copy it anyways.
493 */
c6480207 494static void kauditd_send_multicast_skb(struct sk_buff *skb)
451f9216 495{
c6480207
PM
496 struct sk_buff *copy;
497 struct audit_net *aunet = net_generic(&init_net, audit_net_id);
498 struct sock *sock = aunet->nlsk;
499 struct nlmsghdr *nlh;
451f9216 500
7f74ecd7
RGB
501 if (!netlink_has_listeners(sock, AUDIT_NLGRP_READLOG))
502 return;
503
451f9216
RGB
504 /*
505 * The seemingly wasteful skb_copy() rather than bumping the refcount
506 * using skb_get() is necessary because non-standard mods are made to
507 * the skb by the original kaudit unicast socket send routine. The
508 * existing auditd daemon assumes this breakage. Fixing this would
509 * require co-ordinating a change in the established protocol between
510 * the kaudit kernel subsystem and the auditd userspace code. There is
511 * no reason for new multicast clients to continue with this
512 * non-compliance.
513 */
c6480207 514 copy = skb_copy(skb, GFP_KERNEL);
451f9216
RGB
515 if (!copy)
516 return;
c6480207
PM
517 nlh = nlmsg_hdr(copy);
518 nlh->nlmsg_len = skb->len;
451f9216 519
c6480207 520 nlmsg_multicast(sock, copy, 0, AUDIT_NLGRP_READLOG, GFP_KERNEL);
451f9216
RGB
521}
522
c6480207
PM
523/**
524 * kauditd_wake_condition - Return true when it is time to wake kauditd_thread
b551d1d9 525 *
c6480207
PM
526 * Description:
527 * This function is for use by the wait_event_freezable() call in
528 * kauditd_thread().
b551d1d9 529 */
c6480207 530static int kauditd_wake_condition(void)
b7d11258 531{
c6480207
PM
532 static int pid_last = 0;
533 int rc;
534 int pid = audit_pid;
b551d1d9 535
c6480207
PM
536 /* wake on new messages or a change in the connected auditd */
537 rc = skb_queue_len(&audit_queue) || (pid && pid != pid_last);
538 if (rc)
539 pid_last = pid;
b551d1d9 540
c6480207 541 return rc;
b551d1d9
RGB
542}
543
97a41e26 544static int kauditd_thread(void *dummy)
b7d11258 545{
c6480207
PM
546 int rc;
547 int auditd = 0;
548 int reschedule = 0;
4aa83872
PM
549 struct sk_buff *skb;
550 struct nlmsghdr *nlh;
551
c6480207
PM
552#define UNICAST_RETRIES 5
553#define AUDITD_BAD(x,y) \
554 ((x) == -ECONNREFUSED || (x) == -EPERM || ++(y) >= UNICAST_RETRIES)
555
556 /* NOTE: we do invalidate the auditd connection flag on any sending
557 * errors, but we only "restore" the connection flag at specific places
558 * in the loop in order to help ensure proper ordering of audit
559 * records */
560
83144186 561 set_freezable();
4899b8b1 562 while (!kthread_should_stop()) {
c6480207
PM
563 /* NOTE: possible area for future improvement is to look at
564 * the hold and retry queues, since only this thread
565 * has access to these queues we might be able to do
566 * our own queuing and skip some/all of the locking */
567
568 /* NOTE: it might be a fun experiment to split the hold and
569 * retry queue handling to another thread, but the
570 * synchronization issues and other overhead might kill
571 * any performance gains */
572
573 /* attempt to flush the hold queue */
574 while (auditd && (skb = skb_dequeue(&audit_hold_queue))) {
575 rc = kauditd_send_unicast_skb(skb);
576 if (rc) {
577 /* requeue to the same spot */
578 skb_queue_head(&audit_hold_queue, skb);
579
580 auditd = 0;
581 if (AUDITD_BAD(rc, reschedule)) {
582 auditd_reset();
583 reschedule = 0;
584 }
585 } else
586 /* we were able to send successfully */
587 reschedule = 0;
588 }
589
590 /* attempt to flush the retry queue */
591 while (auditd && (skb = skb_dequeue(&audit_retry_queue))) {
592 rc = kauditd_send_unicast_skb(skb);
593 if (rc) {
594 auditd = 0;
595 if (AUDITD_BAD(rc, reschedule)) {
596 kauditd_hold_skb(skb);
597 auditd_reset();
598 reschedule = 0;
599 } else
600 /* temporary problem (we hope), queue
601 * to the same spot and retry */
602 skb_queue_head(&audit_retry_queue, skb);
603 } else
604 /* we were able to send successfully */
605 reschedule = 0;
606 }
f3d357b0 607
c6480207
PM
608 /* standard queue processing, try to be as quick as possible */
609quick_loop:
af8b824f 610 skb = skb_dequeue(&audit_queue);
b7d11258 611 if (skb) {
c6480207
PM
612 /* setup the netlink header, see the comments in
613 * kauditd_send_multicast_skb() for length quirks */
4aa83872 614 nlh = nlmsg_hdr(skb);
c6480207
PM
615 nlh->nlmsg_len = skb->len - NLMSG_HDRLEN;
616
617 /* attempt to send to any multicast listeners */
618 kauditd_send_multicast_skb(skb);
619
620 /* attempt to send to auditd, queue on failure */
621 if (auditd) {
622 rc = kauditd_send_unicast_skb(skb);
623 if (rc) {
624 auditd = 0;
625 if (AUDITD_BAD(rc, reschedule)) {
626 auditd_reset();
627 reschedule = 0;
628 }
629
630 /* move to the retry queue */
631 kauditd_retry_skb(skb);
632 } else
633 /* everything is working so go fast! */
634 goto quick_loop;
635 } else if (reschedule)
636 /* we are currently having problems, move to
637 * the retry queue */
638 kauditd_retry_skb(skb);
038cbcf6 639 else
c6480207
PM
640 /* dump the message via printk and hold it */
641 kauditd_hold_skb(skb);
4aa83872 642 } else {
c6480207 643 /* we have flushed the backlog so wake everyone */
4aa83872 644 wake_up(&audit_backlog_wait);
c6480207
PM
645
646 /* if everything is okay with auditd (if present), go
647 * to sleep until there is something new in the queue
648 * or we have a change in the connected auditd;
649 * otherwise simply reschedule to give things a chance
650 * to recover */
651 if (reschedule) {
652 set_current_state(TASK_INTERRUPTIBLE);
653 schedule();
654 } else
655 wait_event_freezable(kauditd_wait,
656 kauditd_wake_condition());
657
658 /* update the auditd connection status */
659 auditd = (audit_pid ? 1 : 0);
3320c513 660 }
b7d11258 661 }
c6480207 662
4899b8b1 663 return 0;
b7d11258
DW
664}
665
9044e6bc
AV
666int audit_send_list(void *_dest)
667{
668 struct audit_netlink_list *dest = _dest;
9044e6bc 669 struct sk_buff *skb;
48095d99 670 struct net *net = dest->net;
33faba7f 671 struct audit_net *aunet = net_generic(net, audit_net_id);
9044e6bc
AV
672
673 /* wait for parent to finish and send an ACK */
f368c07d
AG
674 mutex_lock(&audit_cmd_mutex);
675 mutex_unlock(&audit_cmd_mutex);
9044e6bc
AV
676
677 while ((skb = __skb_dequeue(&dest->q)) != NULL)
33faba7f 678 netlink_unicast(aunet->nlsk, skb, dest->portid, 0);
9044e6bc 679
48095d99 680 put_net(net);
9044e6bc
AV
681 kfree(dest);
682
683 return 0;
684}
685
f9441639 686struct sk_buff *audit_make_reply(__u32 portid, int seq, int type, int done,
b8800aa5 687 int multi, const void *payload, int size)
9044e6bc
AV
688{
689 struct sk_buff *skb;
690 struct nlmsghdr *nlh;
9044e6bc
AV
691 void *data;
692 int flags = multi ? NLM_F_MULTI : 0;
693 int t = done ? NLMSG_DONE : type;
694
ee080e6c 695 skb = nlmsg_new(size, GFP_KERNEL);
9044e6bc
AV
696 if (!skb)
697 return NULL;
698
f9441639 699 nlh = nlmsg_put(skb, portid, seq, t, size, flags);
c64e66c6
DM
700 if (!nlh)
701 goto out_kfree_skb;
702 data = nlmsg_data(nlh);
9044e6bc
AV
703 memcpy(data, payload, size);
704 return skb;
705
c64e66c6
DM
706out_kfree_skb:
707 kfree_skb(skb);
9044e6bc
AV
708 return NULL;
709}
710
f09ac9db
EP
711static int audit_send_reply_thread(void *arg)
712{
713 struct audit_reply *reply = (struct audit_reply *)arg;
48095d99 714 struct net *net = reply->net;
33faba7f 715 struct audit_net *aunet = net_generic(net, audit_net_id);
f09ac9db
EP
716
717 mutex_lock(&audit_cmd_mutex);
718 mutex_unlock(&audit_cmd_mutex);
719
720 /* Ignore failure. It'll only happen if the sender goes away,
721 because our timeout is set to infinite. */
33faba7f 722 netlink_unicast(aunet->nlsk , reply->skb, reply->portid, 0);
48095d99 723 put_net(net);
f09ac9db
EP
724 kfree(reply);
725 return 0;
726}
c6480207 727
b0dd25a8
RD
728/**
729 * audit_send_reply - send an audit reply message via netlink
d211f177 730 * @request_skb: skb of request we are replying to (used to target the reply)
b0dd25a8
RD
731 * @seq: sequence number
732 * @type: audit message type
733 * @done: done (last) flag
734 * @multi: multi-part message flag
735 * @payload: payload data
736 * @size: payload size
737 *
f9441639 738 * Allocates an skb, builds the netlink message, and sends it to the port id.
b0dd25a8
RD
739 * No failure notifications.
740 */
6f285b19 741static void audit_send_reply(struct sk_buff *request_skb, int seq, int type, int done,
f9441639 742 int multi, const void *payload, int size)
1da177e4 743{
6f285b19
EB
744 u32 portid = NETLINK_CB(request_skb).portid;
745 struct net *net = sock_net(NETLINK_CB(request_skb).sk);
f09ac9db
EP
746 struct sk_buff *skb;
747 struct task_struct *tsk;
748 struct audit_reply *reply = kmalloc(sizeof(struct audit_reply),
749 GFP_KERNEL);
750
751 if (!reply)
752 return;
753
f9441639 754 skb = audit_make_reply(portid, seq, type, done, multi, payload, size);
1da177e4 755 if (!skb)
fcaf1eb8 756 goto out;
f09ac9db 757
6f285b19 758 reply->net = get_net(net);
f9441639 759 reply->portid = portid;
f09ac9db
EP
760 reply->skb = skb;
761
762 tsk = kthread_run(audit_send_reply_thread, reply, "audit_send_reply");
fcaf1eb8
AM
763 if (!IS_ERR(tsk))
764 return;
765 kfree_skb(skb);
766out:
767 kfree(reply);
1da177e4
LT
768}
769
770/*
771 * Check for appropriate CAP_AUDIT_ capabilities on incoming audit
772 * control messages.
773 */
c7bdb545 774static int audit_netlink_ok(struct sk_buff *skb, u16 msg_type)
1da177e4
LT
775{
776 int err = 0;
777
5a3cb3b6 778 /* Only support initial user namespace for now. */
aa4af831
EP
779 /*
780 * We return ECONNREFUSED because it tricks userspace into thinking
781 * that audit was not configured into the kernel. Lots of users
782 * configure their PAM stack (because that's what the distro does)
783 * to reject login if unable to send messages to audit. If we return
784 * ECONNREFUSED the PAM stack thinks the kernel does not have audit
785 * configured in and will let login proceed. If we return EPERM
786 * userspace will reject all logins. This should be removed when we
787 * support non init namespaces!!
788 */
0b747172 789 if (current_user_ns() != &init_user_ns)
aa4af831 790 return -ECONNREFUSED;
34e36d8e 791
1da177e4 792 switch (msg_type) {
1da177e4 793 case AUDIT_LIST:
1da177e4
LT
794 case AUDIT_ADD:
795 case AUDIT_DEL:
18900909
EP
796 return -EOPNOTSUPP;
797 case AUDIT_GET:
798 case AUDIT_SET:
b0fed402
EP
799 case AUDIT_GET_FEATURE:
800 case AUDIT_SET_FEATURE:
18900909
EP
801 case AUDIT_LIST_RULES:
802 case AUDIT_ADD_RULE:
93315ed6 803 case AUDIT_DEL_RULE:
c2f0c7c3 804 case AUDIT_SIGNAL_INFO:
522ed776
MT
805 case AUDIT_TTY_GET:
806 case AUDIT_TTY_SET:
74c3cbe3
AV
807 case AUDIT_TRIM:
808 case AUDIT_MAKE_EQUIV:
5a3cb3b6
RGB
809 /* Only support auditd and auditctl in initial pid namespace
810 * for now. */
5985de67 811 if (task_active_pid_ns(current) != &init_pid_ns)
5a3cb3b6
RGB
812 return -EPERM;
813
90f62cf3 814 if (!netlink_capable(skb, CAP_AUDIT_CONTROL))
1da177e4
LT
815 err = -EPERM;
816 break;
05474106 817 case AUDIT_USER:
039b6b3e
RD
818 case AUDIT_FIRST_USER_MSG ... AUDIT_LAST_USER_MSG:
819 case AUDIT_FIRST_USER_MSG2 ... AUDIT_LAST_USER_MSG2:
90f62cf3 820 if (!netlink_capable(skb, CAP_AUDIT_WRITE))
1da177e4
LT
821 err = -EPERM;
822 break;
823 default: /* bad msg */
824 err = -EINVAL;
825 }
826
827 return err;
828}
829
233a6866 830static void audit_log_common_recv_msg(struct audit_buffer **ab, u16 msg_type)
50397bd1 831{
dc9eb698 832 uid_t uid = from_kuid(&init_user_ns, current_uid());
f1dc4867 833 pid_t pid = task_tgid_nr(current);
50397bd1 834
0868a5e1 835 if (!audit_enabled && msg_type != AUDIT_USER_AVC) {
50397bd1 836 *ab = NULL;
233a6866 837 return;
50397bd1
EP
838 }
839
840 *ab = audit_log_start(NULL, GFP_KERNEL, msg_type);
0644ec0c 841 if (unlikely(!*ab))
233a6866 842 return;
f1dc4867 843 audit_log_format(*ab, "pid=%d uid=%u", pid, uid);
4d3fb709 844 audit_log_session_info(*ab);
b122c376 845 audit_log_task_context(*ab);
50397bd1
EP
846}
847
b0fed402
EP
848int is_audit_feature_set(int i)
849{
850 return af.features & AUDIT_FEATURE_TO_MASK(i);
851}
852
853
854static int audit_get_feature(struct sk_buff *skb)
855{
856 u32 seq;
857
858 seq = nlmsg_hdr(skb)->nlmsg_seq;
859
9ef91514 860 audit_send_reply(skb, seq, AUDIT_GET_FEATURE, 0, 0, &af, sizeof(af));
b0fed402
EP
861
862 return 0;
863}
864
865static void audit_log_feature_change(int which, u32 old_feature, u32 new_feature,
866 u32 old_lock, u32 new_lock, int res)
867{
868 struct audit_buffer *ab;
869
b6c50fe0
G
870 if (audit_enabled == AUDIT_OFF)
871 return;
872
b0fed402 873 ab = audit_log_start(NULL, GFP_KERNEL, AUDIT_FEATURE_CHANGE);
ad2ac263 874 audit_log_task_info(ab, current);
897f1acb 875 audit_log_format(ab, " feature=%s old=%u new=%u old_lock=%u new_lock=%u res=%d",
b0fed402
EP
876 audit_feature_names[which], !!old_feature, !!new_feature,
877 !!old_lock, !!new_lock, res);
878 audit_log_end(ab);
879}
880
881static int audit_set_feature(struct sk_buff *skb)
882{
883 struct audit_features *uaf;
884 int i;
885
6eed9b26 886 BUILD_BUG_ON(AUDIT_LAST_FEATURE + 1 > ARRAY_SIZE(audit_feature_names));
b0fed402
EP
887 uaf = nlmsg_data(nlmsg_hdr(skb));
888
889 /* if there is ever a version 2 we should handle that here */
890
891 for (i = 0; i <= AUDIT_LAST_FEATURE; i++) {
892 u32 feature = AUDIT_FEATURE_TO_MASK(i);
893 u32 old_feature, new_feature, old_lock, new_lock;
894
895 /* if we are not changing this feature, move along */
896 if (!(feature & uaf->mask))
897 continue;
898
899 old_feature = af.features & feature;
900 new_feature = uaf->features & feature;
901 new_lock = (uaf->lock | af.lock) & feature;
902 old_lock = af.lock & feature;
903
904 /* are we changing a locked feature? */
4547b3bc 905 if (old_lock && (new_feature != old_feature)) {
b0fed402
EP
906 audit_log_feature_change(i, old_feature, new_feature,
907 old_lock, new_lock, 0);
908 return -EPERM;
909 }
910 }
911 /* nothing invalid, do the changes */
912 for (i = 0; i <= AUDIT_LAST_FEATURE; i++) {
913 u32 feature = AUDIT_FEATURE_TO_MASK(i);
914 u32 old_feature, new_feature, old_lock, new_lock;
915
916 /* if we are not changing this feature, move along */
917 if (!(feature & uaf->mask))
918 continue;
919
920 old_feature = af.features & feature;
921 new_feature = uaf->features & feature;
922 old_lock = af.lock & feature;
923 new_lock = (uaf->lock | af.lock) & feature;
924
925 if (new_feature != old_feature)
926 audit_log_feature_change(i, old_feature, new_feature,
927 old_lock, new_lock, 1);
928
929 if (new_feature)
930 af.features |= feature;
931 else
932 af.features &= ~feature;
933 af.lock |= new_lock;
934 }
935
936 return 0;
937}
938
133e1e5a
RGB
939static int audit_replace(pid_t pid)
940{
941 struct sk_buff *skb = audit_make_reply(0, 0, AUDIT_REPLACE, 0, 0,
942 &pid, sizeof(pid));
943
944 if (!skb)
945 return -ENOMEM;
946 return netlink_unicast(audit_sock, skb, audit_nlk_portid, 0);
947}
948
1da177e4
LT
949static int audit_receive_msg(struct sk_buff *skb, struct nlmsghdr *nlh)
950{
dc9eb698 951 u32 seq;
1da177e4 952 void *data;
1da177e4 953 int err;
c0404993 954 struct audit_buffer *ab;
1da177e4 955 u16 msg_type = nlh->nlmsg_type;
e1396065 956 struct audit_sig_info *sig_data;
50397bd1 957 char *ctx = NULL;
e1396065 958 u32 len;
1da177e4 959
c7bdb545 960 err = audit_netlink_ok(skb, msg_type);
1da177e4
LT
961 if (err)
962 return err;
963
1da177e4 964 seq = nlh->nlmsg_seq;
c64e66c6 965 data = nlmsg_data(nlh);
1da177e4
LT
966
967 switch (msg_type) {
09f883a9
RGB
968 case AUDIT_GET: {
969 struct audit_status s;
970 memset(&s, 0, sizeof(s));
971 s.enabled = audit_enabled;
972 s.failure = audit_failure;
973 s.pid = audit_pid;
974 s.rate_limit = audit_rate_limit;
975 s.backlog_limit = audit_backlog_limit;
976 s.lost = atomic_read(&audit_lost);
af8b824f 977 s.backlog = skb_queue_len(&audit_queue);
0288d718 978 s.feature_bitmap = AUDIT_FEATURE_BITMAP_ALL;
31975424 979 s.backlog_wait_time = audit_backlog_wait_time;
6f285b19 980 audit_send_reply(skb, seq, AUDIT_GET, 0, 0, &s, sizeof(s));
1da177e4 981 break;
09f883a9
RGB
982 }
983 case AUDIT_SET: {
984 struct audit_status s;
985 memset(&s, 0, sizeof(s));
986 /* guard against past and future API changes */
987 memcpy(&s, data, min_t(size_t, sizeof(s), nlmsg_len(nlh)));
988 if (s.mask & AUDIT_STATUS_ENABLED) {
989 err = audit_set_enabled(s.enabled);
20c6aaa3 990 if (err < 0)
991 return err;
1da177e4 992 }
09f883a9
RGB
993 if (s.mask & AUDIT_STATUS_FAILURE) {
994 err = audit_set_failure(s.failure);
20c6aaa3 995 if (err < 0)
996 return err;
1da177e4 997 }
09f883a9
RGB
998 if (s.mask & AUDIT_STATUS_PID) {
999 int new_pid = s.pid;
133e1e5a 1000 pid_t requesting_pid = task_tgid_vnr(current);
1a6b9f23 1001
935c9e7f
RGB
1002 if ((!new_pid) && (requesting_pid != audit_pid)) {
1003 audit_log_config_change("audit_pid", new_pid, audit_pid, 0);
34eab0a7 1004 return -EACCES;
935c9e7f 1005 }
133e1e5a 1006 if (audit_pid && new_pid &&
935c9e7f
RGB
1007 audit_replace(requesting_pid) != -ECONNREFUSED) {
1008 audit_log_config_change("audit_pid", new_pid, audit_pid, 0);
133e1e5a 1009 return -EEXIST;
935c9e7f 1010 }
1a6b9f23 1011 if (audit_enabled != AUDIT_OFF)
dc9eb698 1012 audit_log_config_change("audit_pid", new_pid, audit_pid, 1);
1a6b9f23 1013 audit_pid = new_pid;
15e47304 1014 audit_nlk_portid = NETLINK_CB(skb).portid;
de92fc97 1015 audit_sock = skb->sk;
6c54e789
PM
1016 if (!new_pid)
1017 auditd_reset();
e1d16621 1018 wake_up_interruptible(&kauditd_wait);
1da177e4 1019 }
09f883a9
RGB
1020 if (s.mask & AUDIT_STATUS_RATE_LIMIT) {
1021 err = audit_set_rate_limit(s.rate_limit);
20c6aaa3 1022 if (err < 0)
1023 return err;
1024 }
51cc83f0 1025 if (s.mask & AUDIT_STATUS_BACKLOG_LIMIT) {
09f883a9 1026 err = audit_set_backlog_limit(s.backlog_limit);
51cc83f0
RGB
1027 if (err < 0)
1028 return err;
1029 }
3f0c5fad
EP
1030 if (s.mask & AUDIT_STATUS_BACKLOG_WAIT_TIME) {
1031 if (sizeof(s) > (size_t)nlh->nlmsg_len)
1032 return -EINVAL;
724e7bfc 1033 if (s.backlog_wait_time > 10*AUDIT_BACKLOG_WAIT_TIME)
3f0c5fad
EP
1034 return -EINVAL;
1035 err = audit_set_backlog_wait_time(s.backlog_wait_time);
1036 if (err < 0)
1037 return err;
51cc83f0 1038 }
1da177e4 1039 break;
09f883a9 1040 }
b0fed402
EP
1041 case AUDIT_GET_FEATURE:
1042 err = audit_get_feature(skb);
1043 if (err)
1044 return err;
1045 break;
1046 case AUDIT_SET_FEATURE:
1047 err = audit_set_feature(skb);
1048 if (err)
1049 return err;
1050 break;
05474106 1051 case AUDIT_USER:
039b6b3e
RD
1052 case AUDIT_FIRST_USER_MSG ... AUDIT_LAST_USER_MSG:
1053 case AUDIT_FIRST_USER_MSG2 ... AUDIT_LAST_USER_MSG2:
4a4cd633
DW
1054 if (!audit_enabled && msg_type != AUDIT_USER_AVC)
1055 return 0;
1056
86b2efbe 1057 err = audit_filter(msg_type, AUDIT_FILTER_USER);
724e4fcc 1058 if (err == 1) { /* match or error */
4a4cd633 1059 err = 0;
522ed776 1060 if (msg_type == AUDIT_USER_TTY) {
37282a77 1061 err = tty_audit_push();
522ed776
MT
1062 if (err)
1063 break;
1064 }
1b7b533f 1065 mutex_unlock(&audit_cmd_mutex);
dc9eb698 1066 audit_log_common_recv_msg(&ab, msg_type);
50397bd1 1067 if (msg_type != AUDIT_USER_TTY)
b50eba7e
RGB
1068 audit_log_format(ab, " msg='%.*s'",
1069 AUDIT_MESSAGE_TEXT_MAX,
50397bd1
EP
1070 (char *)data);
1071 else {
1072 int size;
1073
f7616102 1074 audit_log_format(ab, " data=");
50397bd1 1075 size = nlmsg_len(nlh);
55ad2f8d
MT
1076 if (size > 0 &&
1077 ((unsigned char *)data)[size - 1] == '\0')
1078 size--;
b556f8ad 1079 audit_log_n_untrustedstring(ab, data, size);
4a4cd633 1080 }
f9441639 1081 audit_set_portid(ab, NETLINK_CB(skb).portid);
50397bd1 1082 audit_log_end(ab);
1b7b533f 1083 mutex_lock(&audit_cmd_mutex);
0f45aa18 1084 }
1da177e4 1085 break;
93315ed6
AG
1086 case AUDIT_ADD_RULE:
1087 case AUDIT_DEL_RULE:
1088 if (nlmsg_len(nlh) < sizeof(struct audit_rule_data))
1089 return -EINVAL;
1a6b9f23 1090 if (audit_enabled == AUDIT_LOCKED) {
dc9eb698
EP
1091 audit_log_common_recv_msg(&ab, AUDIT_CONFIG_CHANGE);
1092 audit_log_format(ab, " audit_enabled=%d res=0", audit_enabled);
50397bd1 1093 audit_log_end(ab);
6a01b07f
SG
1094 return -EPERM;
1095 }
ce0d9f04 1096 err = audit_rule_change(msg_type, NETLINK_CB(skb).portid,
dc9eb698 1097 seq, data, nlmsg_len(nlh));
1da177e4 1098 break;
ce0d9f04 1099 case AUDIT_LIST_RULES:
6f285b19 1100 err = audit_list_rules_send(skb, seq);
ce0d9f04 1101 break;
74c3cbe3
AV
1102 case AUDIT_TRIM:
1103 audit_trim_trees();
dc9eb698 1104 audit_log_common_recv_msg(&ab, AUDIT_CONFIG_CHANGE);
74c3cbe3
AV
1105 audit_log_format(ab, " op=trim res=1");
1106 audit_log_end(ab);
1107 break;
1108 case AUDIT_MAKE_EQUIV: {
1109 void *bufp = data;
1110 u32 sizes[2];
7719e437 1111 size_t msglen = nlmsg_len(nlh);
74c3cbe3
AV
1112 char *old, *new;
1113
1114 err = -EINVAL;
7719e437 1115 if (msglen < 2 * sizeof(u32))
74c3cbe3
AV
1116 break;
1117 memcpy(sizes, bufp, 2 * sizeof(u32));
1118 bufp += 2 * sizeof(u32);
7719e437
HH
1119 msglen -= 2 * sizeof(u32);
1120 old = audit_unpack_string(&bufp, &msglen, sizes[0]);
74c3cbe3
AV
1121 if (IS_ERR(old)) {
1122 err = PTR_ERR(old);
1123 break;
1124 }
7719e437 1125 new = audit_unpack_string(&bufp, &msglen, sizes[1]);
74c3cbe3
AV
1126 if (IS_ERR(new)) {
1127 err = PTR_ERR(new);
1128 kfree(old);
1129 break;
1130 }
1131 /* OK, here comes... */
1132 err = audit_tag_tree(old, new);
1133
dc9eb698 1134 audit_log_common_recv_msg(&ab, AUDIT_CONFIG_CHANGE);
50397bd1 1135
74c3cbe3
AV
1136 audit_log_format(ab, " op=make_equiv old=");
1137 audit_log_untrustedstring(ab, old);
1138 audit_log_format(ab, " new=");
1139 audit_log_untrustedstring(ab, new);
1140 audit_log_format(ab, " res=%d", !err);
1141 audit_log_end(ab);
1142 kfree(old);
1143 kfree(new);
1144 break;
1145 }
c2f0c7c3 1146 case AUDIT_SIGNAL_INFO:
939cbf26
EP
1147 len = 0;
1148 if (audit_sig_sid) {
1149 err = security_secid_to_secctx(audit_sig_sid, &ctx, &len);
1150 if (err)
1151 return err;
1152 }
e1396065
AV
1153 sig_data = kmalloc(sizeof(*sig_data) + len, GFP_KERNEL);
1154 if (!sig_data) {
939cbf26
EP
1155 if (audit_sig_sid)
1156 security_release_secctx(ctx, len);
e1396065
AV
1157 return -ENOMEM;
1158 }
cca080d9 1159 sig_data->uid = from_kuid(&init_user_ns, audit_sig_uid);
e1396065 1160 sig_data->pid = audit_sig_pid;
939cbf26
EP
1161 if (audit_sig_sid) {
1162 memcpy(sig_data->ctx, ctx, len);
1163 security_release_secctx(ctx, len);
1164 }
6f285b19
EB
1165 audit_send_reply(skb, seq, AUDIT_SIGNAL_INFO, 0, 0,
1166 sig_data, sizeof(*sig_data) + len);
e1396065 1167 kfree(sig_data);
c2f0c7c3 1168 break;
522ed776
MT
1169 case AUDIT_TTY_GET: {
1170 struct audit_tty_status s;
2e28d38a 1171 unsigned int t;
8aa14b64 1172
2e28d38a
PH
1173 t = READ_ONCE(current->signal->audit_tty);
1174 s.enabled = t & AUDIT_TTY_ENABLE;
1175 s.log_passwd = !!(t & AUDIT_TTY_LOG_PASSWD);
8aa14b64 1176
6f285b19 1177 audit_send_reply(skb, seq, AUDIT_TTY_GET, 0, 0, &s, sizeof(s));
522ed776
MT
1178 break;
1179 }
1180 case AUDIT_TTY_SET: {
a06e56b2 1181 struct audit_tty_status s, old;
a06e56b2 1182 struct audit_buffer *ab;
2e28d38a 1183 unsigned int t;
0e23bacc
EP
1184
1185 memset(&s, 0, sizeof(s));
1186 /* guard against past and future API changes */
1187 memcpy(&s, data, min_t(size_t, sizeof(s), nlmsg_len(nlh)));
1188 /* check if new data is valid */
1189 if ((s.enabled != 0 && s.enabled != 1) ||
1190 (s.log_passwd != 0 && s.log_passwd != 1))
1191 err = -EINVAL;
a06e56b2 1192
2e28d38a
PH
1193 if (err)
1194 t = READ_ONCE(current->signal->audit_tty);
1195 else {
1196 t = s.enabled | (-s.log_passwd & AUDIT_TTY_LOG_PASSWD);
1197 t = xchg(&current->signal->audit_tty, t);
0e23bacc 1198 }
2e28d38a
PH
1199 old.enabled = t & AUDIT_TTY_ENABLE;
1200 old.log_passwd = !!(t & AUDIT_TTY_LOG_PASSWD);
522ed776 1201
a06e56b2 1202 audit_log_common_recv_msg(&ab, AUDIT_CONFIG_CHANGE);
1ce319f1
EP
1203 audit_log_format(ab, " op=tty_set old-enabled=%d new-enabled=%d"
1204 " old-log_passwd=%d new-log_passwd=%d res=%d",
1205 old.enabled, s.enabled, old.log_passwd,
1206 s.log_passwd, !err);
a06e56b2 1207 audit_log_end(ab);
522ed776
MT
1208 break;
1209 }
1da177e4
LT
1210 default:
1211 err = -EINVAL;
1212 break;
1213 }
1214
1215 return err < 0 ? err : 0;
1216}
1217
b0dd25a8 1218/*
ea7ae60b
EP
1219 * Get message from skb. Each message is processed by audit_receive_msg.
1220 * Malformed skbs with wrong length are discarded silently.
b0dd25a8 1221 */
2a0a6ebe 1222static void audit_receive_skb(struct sk_buff *skb)
1da177e4 1223{
ea7ae60b
EP
1224 struct nlmsghdr *nlh;
1225 /*
94191213 1226 * len MUST be signed for nlmsg_next to be able to dec it below 0
ea7ae60b
EP
1227 * if the nlmsg_len was not aligned
1228 */
1229 int len;
1230 int err;
1231
1232 nlh = nlmsg_hdr(skb);
1233 len = skb->len;
1234
94191213 1235 while (nlmsg_ok(nlh, len)) {
ea7ae60b
EP
1236 err = audit_receive_msg(skb, nlh);
1237 /* if err or if this message says it wants a response */
1238 if (err || (nlh->nlmsg_flags & NLM_F_ACK))
1da177e4 1239 netlink_ack(skb, nlh, err);
ea7ae60b 1240
2851da57 1241 nlh = nlmsg_next(nlh, &len);
1da177e4 1242 }
1da177e4
LT
1243}
1244
1245/* Receive messages from netlink socket. */
cd40b7d3 1246static void audit_receive(struct sk_buff *skb)
1da177e4 1247{
f368c07d 1248 mutex_lock(&audit_cmd_mutex);
cd40b7d3 1249 audit_receive_skb(skb);
f368c07d 1250 mutex_unlock(&audit_cmd_mutex);
1da177e4
LT
1251}
1252
3a101b8d 1253/* Run custom bind function on netlink socket group connect or bind requests. */
023e2cfa 1254static int audit_bind(struct net *net, int group)
3a101b8d
RGB
1255{
1256 if (!capable(CAP_AUDIT_READ))
1257 return -EPERM;
1258
1259 return 0;
1260}
1261
33faba7f 1262static int __net_init audit_net_init(struct net *net)
1da177e4 1263{
a31f2d17
PNA
1264 struct netlink_kernel_cfg cfg = {
1265 .input = audit_receive,
3a101b8d 1266 .bind = audit_bind,
451f9216
RGB
1267 .flags = NL_CFG_F_NONROOT_RECV,
1268 .groups = AUDIT_NLGRP_MAX,
a31f2d17 1269 };
f368c07d 1270
33faba7f
RGB
1271 struct audit_net *aunet = net_generic(net, audit_net_id);
1272
33faba7f 1273 aunet->nlsk = netlink_kernel_create(net, NETLINK_AUDIT, &cfg);
11ee39eb 1274 if (aunet->nlsk == NULL) {
33faba7f 1275 audit_panic("cannot initialize netlink socket in namespace");
11ee39eb
G
1276 return -ENOMEM;
1277 }
1278 aunet->nlsk->sk_sndtimeo = MAX_SCHEDULE_TIMEOUT;
33faba7f
RGB
1279 return 0;
1280}
1281
1282static void __net_exit audit_net_exit(struct net *net)
1283{
1284 struct audit_net *aunet = net_generic(net, audit_net_id);
1285 struct sock *sock = aunet->nlsk;
c6480207
PM
1286 if (sock == audit_sock)
1287 auditd_reset();
33faba7f 1288
e231d54c 1289 RCU_INIT_POINTER(aunet->nlsk, NULL);
33faba7f
RGB
1290 synchronize_net();
1291 netlink_kernel_release(sock);
1292}
1293
8626877b 1294static struct pernet_operations audit_net_ops __net_initdata = {
33faba7f
RGB
1295 .init = audit_net_init,
1296 .exit = audit_net_exit,
1297 .id = &audit_net_id,
1298 .size = sizeof(struct audit_net),
1299};
1300
1301/* Initialize audit support at boot time. */
1302static int __init audit_init(void)
1303{
1304 int i;
1305
a3f07114
EP
1306 if (audit_initialized == AUDIT_DISABLED)
1307 return 0;
1308
d957f7b7
JP
1309 pr_info("initializing netlink subsys (%s)\n",
1310 audit_default ? "enabled" : "disabled");
33faba7f 1311 register_pernet_subsys(&audit_net_ops);
1da177e4 1312
af8b824f 1313 skb_queue_head_init(&audit_queue);
c6480207 1314 skb_queue_head_init(&audit_retry_queue);
af8b824f 1315 skb_queue_head_init(&audit_hold_queue);
a3f07114 1316 audit_initialized = AUDIT_INITIALIZED;
1da177e4 1317 audit_enabled = audit_default;
b593d384 1318 audit_ever_enabled |= !!audit_default;
3dc7e315 1319
f368c07d
AG
1320 for (i = 0; i < AUDIT_INODE_BUCKETS; i++)
1321 INIT_LIST_HEAD(&audit_inode_hash[i]);
f368c07d 1322
6c925564
PM
1323 kauditd_task = kthread_run(kauditd_thread, NULL, "kauditd");
1324 if (IS_ERR(kauditd_task)) {
1325 int err = PTR_ERR(kauditd_task);
1326 panic("audit: failed to start the kauditd thread (%d)\n", err);
1327 }
1328
1329 audit_log(NULL, GFP_KERNEL, AUDIT_KERNEL, "initialized");
1330
1da177e4
LT
1331 return 0;
1332}
1da177e4
LT
1333__initcall(audit_init);
1334
1335/* Process kernel command-line parameter at boot time. audit=0 or audit=1. */
1336static int __init audit_enable(char *str)
1337{
1338 audit_default = !!simple_strtol(str, NULL, 0);
a3f07114
EP
1339 if (!audit_default)
1340 audit_initialized = AUDIT_DISABLED;
1341
d957f7b7 1342 pr_info("%s\n", audit_default ?
d3ca0344 1343 "enabled (after initialization)" : "disabled (until reboot)");
a3f07114 1344
9b41046c 1345 return 1;
1da177e4 1346}
1da177e4
LT
1347__setup("audit=", audit_enable);
1348
f910fde7
RGB
1349/* Process kernel command-line parameter at boot time.
1350 * audit_backlog_limit=<n> */
1351static int __init audit_backlog_limit_set(char *str)
1352{
3e1d0bb6 1353 u32 audit_backlog_limit_arg;
d957f7b7 1354
f910fde7 1355 pr_info("audit_backlog_limit: ");
3e1d0bb6
JP
1356 if (kstrtouint(str, 0, &audit_backlog_limit_arg)) {
1357 pr_cont("using default of %u, unable to parse %s\n",
d957f7b7 1358 audit_backlog_limit, str);
f910fde7
RGB
1359 return 1;
1360 }
3e1d0bb6
JP
1361
1362 audit_backlog_limit = audit_backlog_limit_arg;
d957f7b7 1363 pr_cont("%d\n", audit_backlog_limit);
f910fde7
RGB
1364
1365 return 1;
1366}
1367__setup("audit_backlog_limit=", audit_backlog_limit_set);
1368
16e1904e
CW
1369static void audit_buffer_free(struct audit_buffer *ab)
1370{
1371 unsigned long flags;
1372
8fc6115c
CW
1373 if (!ab)
1374 return;
1375
d865e573 1376 kfree_skb(ab->skb);
16e1904e 1377 spin_lock_irqsave(&audit_freelist_lock, flags);
5d136a01 1378 if (audit_freelist_count > AUDIT_MAXFREE)
16e1904e 1379 kfree(ab);
5d136a01
SH
1380 else {
1381 audit_freelist_count++;
16e1904e 1382 list_add(&ab->list, &audit_freelist);
5d136a01 1383 }
16e1904e
CW
1384 spin_unlock_irqrestore(&audit_freelist_lock, flags);
1385}
1386
c0404993 1387static struct audit_buffer * audit_buffer_alloc(struct audit_context *ctx,
dd0fc66f 1388 gfp_t gfp_mask, int type)
16e1904e
CW
1389{
1390 unsigned long flags;
1391 struct audit_buffer *ab = NULL;
c0404993 1392 struct nlmsghdr *nlh;
16e1904e
CW
1393
1394 spin_lock_irqsave(&audit_freelist_lock, flags);
1395 if (!list_empty(&audit_freelist)) {
1396 ab = list_entry(audit_freelist.next,
1397 struct audit_buffer, list);
1398 list_del(&ab->list);
1399 --audit_freelist_count;
1400 }
1401 spin_unlock_irqrestore(&audit_freelist_lock, flags);
1402
1403 if (!ab) {
4332bdd3 1404 ab = kmalloc(sizeof(*ab), gfp_mask);
16e1904e 1405 if (!ab)
8fc6115c 1406 goto err;
16e1904e 1407 }
8fc6115c 1408
b7d11258 1409 ab->ctx = ctx;
9ad9ad38 1410 ab->gfp_mask = gfp_mask;
ee080e6c
EP
1411
1412 ab->skb = nlmsg_new(AUDIT_BUFSIZ, gfp_mask);
1413 if (!ab->skb)
c64e66c6 1414 goto err;
ee080e6c 1415
c64e66c6
DM
1416 nlh = nlmsg_put(ab->skb, 0, 0, type, 0, 0);
1417 if (!nlh)
1418 goto out_kfree_skb;
ee080e6c 1419
16e1904e 1420 return ab;
ee080e6c 1421
c64e66c6 1422out_kfree_skb:
ee080e6c
EP
1423 kfree_skb(ab->skb);
1424 ab->skb = NULL;
8fc6115c
CW
1425err:
1426 audit_buffer_free(ab);
1427 return NULL;
16e1904e 1428}
1da177e4 1429
b0dd25a8
RD
1430/**
1431 * audit_serial - compute a serial number for the audit record
1432 *
1433 * Compute a serial number for the audit record. Audit records are
bfb4496e
DW
1434 * written to user-space as soon as they are generated, so a complete
1435 * audit record may be written in several pieces. The timestamp of the
1436 * record and this serial number are used by the user-space tools to
1437 * determine which pieces belong to the same audit record. The
1438 * (timestamp,serial) tuple is unique for each syscall and is live from
1439 * syscall entry to syscall exit.
1440 *
bfb4496e
DW
1441 * NOTE: Another possibility is to store the formatted records off the
1442 * audit context (for those records that have a context), and emit them
1443 * all at syscall exit. However, this could delay the reporting of
1444 * significant errors until syscall exit (or never, if the system
b0dd25a8
RD
1445 * halts).
1446 */
bfb4496e
DW
1447unsigned int audit_serial(void)
1448{
01478d7d 1449 static atomic_t serial = ATOMIC_INIT(0);
d5b454f2 1450
01478d7d 1451 return atomic_add_return(1, &serial);
bfb4496e
DW
1452}
1453
5600b892 1454static inline void audit_get_stamp(struct audit_context *ctx,
bfb4496e
DW
1455 struct timespec *t, unsigned int *serial)
1456{
48887e63 1457 if (!ctx || !auditsc_get_stamp(ctx, t, serial)) {
bfb4496e
DW
1458 *t = CURRENT_TIME;
1459 *serial = audit_serial();
1460 }
1461}
1462
b0dd25a8
RD
1463/**
1464 * audit_log_start - obtain an audit buffer
1465 * @ctx: audit_context (may be NULL)
1466 * @gfp_mask: type of allocation
1467 * @type: audit message type
1468 *
1469 * Returns audit_buffer pointer on success or NULL on error.
1470 *
1471 * Obtain an audit buffer. This routine does locking to obtain the
1472 * audit buffer, but then no locking is required for calls to
1473 * audit_log_*format. If the task (ctx) is a task that is currently in a
1474 * syscall, then the syscall is marked as auditable and an audit record
1475 * will be written at syscall exit. If there is no associated task, then
1476 * task context (ctx) should be NULL.
1477 */
9796fdd8 1478struct audit_buffer *audit_log_start(struct audit_context *ctx, gfp_t gfp_mask,
9ad9ad38 1479 int type)
1da177e4 1480{
31975424
PM
1481 struct audit_buffer *ab;
1482 struct timespec t;
1483 unsigned int uninitialized_var(serial);
1da177e4 1484
a3f07114 1485 if (audit_initialized != AUDIT_INITIALIZED)
1da177e4
LT
1486 return NULL;
1487
86b2efbe 1488 if (unlikely(!audit_filter(type, AUDIT_FILTER_TYPE)))
c8edc80c
DK
1489 return NULL;
1490
a09cfa47
PM
1491 /* don't ever fail/sleep on these two conditions:
1492 * 1. auditd generated record - since we need auditd to drain the
1493 * queue; also, when we are checking for auditd, compare PIDs using
1494 * task_tgid_vnr() since auditd_pid is set in audit_receive_msg()
1495 * using a PID anchored in the caller's namespace
1496 * 2. audit command message - record types 1000 through 1099 inclusive
1497 * are command messages/records used to manage the kernel subsystem
1498 * and the audit userspace, blocking on these messages could cause
1499 * problems under load so don't do it (note: not all of these
1500 * command types are valid as record types, but it is quicker to
1501 * just check two ints than a series of ints in a if/switch stmt) */
1502 if (!((audit_pid && audit_pid == task_tgid_vnr(current)) ||
1503 (type >= 1000 && type <= 1099))) {
31975424
PM
1504 long sleep_time = audit_backlog_wait_time;
1505
1506 while (audit_backlog_limit &&
1507 (skb_queue_len(&audit_queue) > audit_backlog_limit)) {
1508 /* wake kauditd to try and flush the queue */
1509 wake_up_interruptible(&kauditd_wait);
1510
1511 /* sleep if we are allowed and we haven't exhausted our
1512 * backlog wait limit */
1513 if ((gfp_mask & __GFP_DIRECT_RECLAIM) &&
1514 (sleep_time > 0)) {
1515 DECLARE_WAITQUEUE(wait, current);
1516
1517 add_wait_queue_exclusive(&audit_backlog_wait,
1518 &wait);
1519 set_current_state(TASK_UNINTERRUPTIBLE);
1520 sleep_time = schedule_timeout(sleep_time);
1521 remove_wait_queue(&audit_backlog_wait, &wait);
1522 } else {
1523 if (audit_rate_check() && printk_ratelimit())
1524 pr_warn("audit_backlog=%d > audit_backlog_limit=%d\n",
1525 skb_queue_len(&audit_queue),
1526 audit_backlog_limit);
1527 audit_log_lost("backlog limit exceeded");
1528 return NULL;
8ac1c8d5 1529 }
9ad9ad38 1530 }
fb19b4c6
DW
1531 }
1532
9ad9ad38 1533 ab = audit_buffer_alloc(ctx, gfp_mask, type);
1da177e4
LT
1534 if (!ab) {
1535 audit_log_lost("out of memory in audit_log_start");
1536 return NULL;
1537 }
1538
bfb4496e 1539 audit_get_stamp(ab->ctx, &t, &serial);
1da177e4
LT
1540 audit_log_format(ab, "audit(%lu.%03lu:%u): ",
1541 t.tv_sec, t.tv_nsec/1000000, serial);
31975424 1542
1da177e4
LT
1543 return ab;
1544}
1545
8fc6115c 1546/**
5ac52f33 1547 * audit_expand - expand skb in the audit buffer
8fc6115c 1548 * @ab: audit_buffer
b0dd25a8 1549 * @extra: space to add at tail of the skb
8fc6115c
CW
1550 *
1551 * Returns 0 (no space) on failed expansion, or available space if
1552 * successful.
1553 */
e3b926b4 1554static inline int audit_expand(struct audit_buffer *ab, int extra)
8fc6115c 1555{
5ac52f33 1556 struct sk_buff *skb = ab->skb;
406a1d86
HX
1557 int oldtail = skb_tailroom(skb);
1558 int ret = pskb_expand_head(skb, 0, extra, ab->gfp_mask);
1559 int newtail = skb_tailroom(skb);
1560
5ac52f33
CW
1561 if (ret < 0) {
1562 audit_log_lost("out of memory in audit_expand");
8fc6115c 1563 return 0;
5ac52f33 1564 }
406a1d86
HX
1565
1566 skb->truesize += newtail - oldtail;
1567 return newtail;
8fc6115c 1568}
1da177e4 1569
b0dd25a8
RD
1570/*
1571 * Format an audit message into the audit buffer. If there isn't enough
1da177e4
LT
1572 * room in the audit buffer, more room will be allocated and vsnprint
1573 * will be called a second time. Currently, we assume that a printk
b0dd25a8
RD
1574 * can't format message larger than 1024 bytes, so we don't either.
1575 */
1da177e4
LT
1576static void audit_log_vformat(struct audit_buffer *ab, const char *fmt,
1577 va_list args)
1578{
1579 int len, avail;
5ac52f33 1580 struct sk_buff *skb;
eecb0a73 1581 va_list args2;
1da177e4
LT
1582
1583 if (!ab)
1584 return;
1585
5ac52f33
CW
1586 BUG_ON(!ab->skb);
1587 skb = ab->skb;
1588 avail = skb_tailroom(skb);
1589 if (avail == 0) {
e3b926b4 1590 avail = audit_expand(ab, AUDIT_BUFSIZ);
8fc6115c
CW
1591 if (!avail)
1592 goto out;
1da177e4 1593 }
eecb0a73 1594 va_copy(args2, args);
27a884dc 1595 len = vsnprintf(skb_tail_pointer(skb), avail, fmt, args);
1da177e4
LT
1596 if (len >= avail) {
1597 /* The printk buffer is 1024 bytes long, so if we get
1598 * here and AUDIT_BUFSIZ is at least 1024, then we can
1599 * log everything that printk could have logged. */
b0dd25a8
RD
1600 avail = audit_expand(ab,
1601 max_t(unsigned, AUDIT_BUFSIZ, 1+len-avail));
8fc6115c 1602 if (!avail)
a0e86bd4 1603 goto out_va_end;
27a884dc 1604 len = vsnprintf(skb_tail_pointer(skb), avail, fmt, args2);
1da177e4 1605 }
168b7173
SG
1606 if (len > 0)
1607 skb_put(skb, len);
a0e86bd4
JJ
1608out_va_end:
1609 va_end(args2);
8fc6115c
CW
1610out:
1611 return;
1da177e4
LT
1612}
1613
b0dd25a8
RD
1614/**
1615 * audit_log_format - format a message into the audit buffer.
1616 * @ab: audit_buffer
1617 * @fmt: format string
1618 * @...: optional parameters matching @fmt string
1619 *
1620 * All the work is done in audit_log_vformat.
1621 */
1da177e4
LT
1622void audit_log_format(struct audit_buffer *ab, const char *fmt, ...)
1623{
1624 va_list args;
1625
1626 if (!ab)
1627 return;
1628 va_start(args, fmt);
1629 audit_log_vformat(ab, fmt, args);
1630 va_end(args);
1631}
1632
b0dd25a8
RD
1633/**
1634 * audit_log_hex - convert a buffer to hex and append it to the audit skb
1635 * @ab: the audit_buffer
1636 * @buf: buffer to convert to hex
1637 * @len: length of @buf to be converted
1638 *
1639 * No return value; failure to expand is silently ignored.
1640 *
1641 * This function will take the passed buf and convert it into a string of
1642 * ascii hex digits. The new string is placed onto the skb.
1643 */
b556f8ad 1644void audit_log_n_hex(struct audit_buffer *ab, const unsigned char *buf,
168b7173 1645 size_t len)
83c7d091 1646{
168b7173
SG
1647 int i, avail, new_len;
1648 unsigned char *ptr;
1649 struct sk_buff *skb;
168b7173 1650
8ef2d304
AG
1651 if (!ab)
1652 return;
1653
168b7173
SG
1654 BUG_ON(!ab->skb);
1655 skb = ab->skb;
1656 avail = skb_tailroom(skb);
1657 new_len = len<<1;
1658 if (new_len >= avail) {
1659 /* Round the buffer request up to the next multiple */
1660 new_len = AUDIT_BUFSIZ*(((new_len-avail)/AUDIT_BUFSIZ) + 1);
1661 avail = audit_expand(ab, new_len);
1662 if (!avail)
1663 return;
1664 }
83c7d091 1665
27a884dc 1666 ptr = skb_tail_pointer(skb);
b8dbc324
JP
1667 for (i = 0; i < len; i++)
1668 ptr = hex_byte_pack_upper(ptr, buf[i]);
168b7173
SG
1669 *ptr = 0;
1670 skb_put(skb, len << 1); /* new string is twice the old string */
83c7d091 1671}
1672
9c937dcc
AG
1673/*
1674 * Format a string of no more than slen characters into the audit buffer,
1675 * enclosed in quote marks.
1676 */
b556f8ad
EP
1677void audit_log_n_string(struct audit_buffer *ab, const char *string,
1678 size_t slen)
9c937dcc
AG
1679{
1680 int avail, new_len;
1681 unsigned char *ptr;
1682 struct sk_buff *skb;
1683
8ef2d304
AG
1684 if (!ab)
1685 return;
1686
9c937dcc
AG
1687 BUG_ON(!ab->skb);
1688 skb = ab->skb;
1689 avail = skb_tailroom(skb);
1690 new_len = slen + 3; /* enclosing quotes + null terminator */
1691 if (new_len > avail) {
1692 avail = audit_expand(ab, new_len);
1693 if (!avail)
1694 return;
1695 }
27a884dc 1696 ptr = skb_tail_pointer(skb);
9c937dcc
AG
1697 *ptr++ = '"';
1698 memcpy(ptr, string, slen);
1699 ptr += slen;
1700 *ptr++ = '"';
1701 *ptr = 0;
1702 skb_put(skb, slen + 2); /* don't include null terminator */
1703}
1704
de6bbd1d
EP
1705/**
1706 * audit_string_contains_control - does a string need to be logged in hex
f706d5d2
DJ
1707 * @string: string to be checked
1708 * @len: max length of the string to check
de6bbd1d 1709 */
9fcf836b 1710bool audit_string_contains_control(const char *string, size_t len)
de6bbd1d
EP
1711{
1712 const unsigned char *p;
b3897f56 1713 for (p = string; p < (const unsigned char *)string + len; p++) {
1d6c9649 1714 if (*p == '"' || *p < 0x21 || *p > 0x7e)
9fcf836b 1715 return true;
de6bbd1d 1716 }
9fcf836b 1717 return false;
de6bbd1d
EP
1718}
1719
b0dd25a8 1720/**
522ed776 1721 * audit_log_n_untrustedstring - log a string that may contain random characters
b0dd25a8 1722 * @ab: audit_buffer
f706d5d2 1723 * @len: length of string (not including trailing null)
b0dd25a8
RD
1724 * @string: string to be logged
1725 *
1726 * This code will escape a string that is passed to it if the string
1727 * contains a control character, unprintable character, double quote mark,
168b7173 1728 * or a space. Unescaped strings will start and end with a double quote mark.
b0dd25a8 1729 * Strings that are escaped are printed in hex (2 digits per char).
9c937dcc
AG
1730 *
1731 * The caller specifies the number of characters in the string to log, which may
1732 * or may not be the entire string.
b0dd25a8 1733 */
b556f8ad
EP
1734void audit_log_n_untrustedstring(struct audit_buffer *ab, const char *string,
1735 size_t len)
83c7d091 1736{
de6bbd1d 1737 if (audit_string_contains_control(string, len))
b556f8ad 1738 audit_log_n_hex(ab, string, len);
de6bbd1d 1739 else
b556f8ad 1740 audit_log_n_string(ab, string, len);
83c7d091 1741}
1742
9c937dcc 1743/**
522ed776 1744 * audit_log_untrustedstring - log a string that may contain random characters
9c937dcc
AG
1745 * @ab: audit_buffer
1746 * @string: string to be logged
1747 *
522ed776 1748 * Same as audit_log_n_untrustedstring(), except that strlen is used to
9c937dcc
AG
1749 * determine string length.
1750 */
de6bbd1d 1751void audit_log_untrustedstring(struct audit_buffer *ab, const char *string)
9c937dcc 1752{
b556f8ad 1753 audit_log_n_untrustedstring(ab, string, strlen(string));
9c937dcc
AG
1754}
1755
168b7173 1756/* This is a helper-function to print the escaped d_path */
1da177e4 1757void audit_log_d_path(struct audit_buffer *ab, const char *prefix,
66b3fad3 1758 const struct path *path)
1da177e4 1759{
44707fdf 1760 char *p, *pathname;
1da177e4 1761
8fc6115c 1762 if (prefix)
c158a35c 1763 audit_log_format(ab, "%s", prefix);
1da177e4 1764
168b7173 1765 /* We will allow 11 spaces for ' (deleted)' to be appended */
44707fdf
JB
1766 pathname = kmalloc(PATH_MAX+11, ab->gfp_mask);
1767 if (!pathname) {
def57543 1768 audit_log_string(ab, "<no_memory>");
168b7173 1769 return;
1da177e4 1770 }
cf28b486 1771 p = d_path(path, pathname, PATH_MAX+11);
168b7173
SG
1772 if (IS_ERR(p)) { /* Should never happen since we send PATH_MAX */
1773 /* FIXME: can we save some information here? */
def57543 1774 audit_log_string(ab, "<too_long>");
5600b892 1775 } else
168b7173 1776 audit_log_untrustedstring(ab, p);
44707fdf 1777 kfree(pathname);
1da177e4
LT
1778}
1779
4d3fb709
EP
1780void audit_log_session_info(struct audit_buffer *ab)
1781{
4440e854 1782 unsigned int sessionid = audit_get_sessionid(current);
4d3fb709
EP
1783 uid_t auid = from_kuid(&init_user_ns, audit_get_loginuid(current));
1784
b8f89caa 1785 audit_log_format(ab, " auid=%u ses=%u", auid, sessionid);
4d3fb709
EP
1786}
1787
9d960985
EP
1788void audit_log_key(struct audit_buffer *ab, char *key)
1789{
1790 audit_log_format(ab, " key=");
1791 if (key)
1792 audit_log_untrustedstring(ab, key);
1793 else
1794 audit_log_format(ab, "(null)");
1795}
1796
b24a30a7
EP
1797void audit_log_cap(struct audit_buffer *ab, char *prefix, kernel_cap_t *cap)
1798{
1799 int i;
1800
1801 audit_log_format(ab, " %s=", prefix);
1802 CAP_FOR_EACH_U32(i) {
1803 audit_log_format(ab, "%08x",
7d8b6c63 1804 cap->cap[CAP_LAST_U32 - i]);
b24a30a7
EP
1805 }
1806}
1807
691e6d59 1808static void audit_log_fcaps(struct audit_buffer *ab, struct audit_names *name)
b24a30a7
EP
1809{
1810 kernel_cap_t *perm = &name->fcap.permitted;
1811 kernel_cap_t *inh = &name->fcap.inheritable;
1812 int log = 0;
1813
1814 if (!cap_isclear(*perm)) {
1815 audit_log_cap(ab, "cap_fp", perm);
1816 log = 1;
1817 }
1818 if (!cap_isclear(*inh)) {
1819 audit_log_cap(ab, "cap_fi", inh);
1820 log = 1;
1821 }
1822
1823 if (log)
1824 audit_log_format(ab, " cap_fe=%d cap_fver=%x",
1825 name->fcap.fE, name->fcap_ver);
1826}
1827
1828static inline int audit_copy_fcaps(struct audit_names *name,
1829 const struct dentry *dentry)
1830{
1831 struct cpu_vfs_cap_data caps;
1832 int rc;
1833
1834 if (!dentry)
1835 return 0;
1836
1837 rc = get_vfs_caps_from_disk(dentry, &caps);
1838 if (rc)
1839 return rc;
1840
1841 name->fcap.permitted = caps.permitted;
1842 name->fcap.inheritable = caps.inheritable;
1843 name->fcap.fE = !!(caps.magic_etc & VFS_CAP_FLAGS_EFFECTIVE);
1844 name->fcap_ver = (caps.magic_etc & VFS_CAP_REVISION_MASK) >>
1845 VFS_CAP_REVISION_SHIFT;
1846
1847 return 0;
1848}
1849
1850/* Copy inode data into an audit_names. */
1851void audit_copy_inode(struct audit_names *name, const struct dentry *dentry,
d6335d77 1852 struct inode *inode)
b24a30a7
EP
1853{
1854 name->ino = inode->i_ino;
1855 name->dev = inode->i_sb->s_dev;
1856 name->mode = inode->i_mode;
1857 name->uid = inode->i_uid;
1858 name->gid = inode->i_gid;
1859 name->rdev = inode->i_rdev;
1860 security_inode_getsecid(inode, &name->osid);
1861 audit_copy_fcaps(name, dentry);
1862}
1863
1864/**
1865 * audit_log_name - produce AUDIT_PATH record from struct audit_names
1866 * @context: audit_context for the task
1867 * @n: audit_names structure with reportable details
1868 * @path: optional path to report instead of audit_names->name
1869 * @record_num: record number to report when handling a list of names
1870 * @call_panic: optional pointer to int that will be updated if secid fails
1871 */
1872void audit_log_name(struct audit_context *context, struct audit_names *n,
1873 struct path *path, int record_num, int *call_panic)
1874{
1875 struct audit_buffer *ab;
1876 ab = audit_log_start(context, GFP_KERNEL, AUDIT_PATH);
1877 if (!ab)
1878 return;
1879
1880 audit_log_format(ab, "item=%d", record_num);
1881
1882 if (path)
1883 audit_log_d_path(ab, " name=", path);
1884 else if (n->name) {
1885 switch (n->name_len) {
1886 case AUDIT_NAME_FULL:
1887 /* log the full path */
1888 audit_log_format(ab, " name=");
1889 audit_log_untrustedstring(ab, n->name->name);
1890 break;
1891 case 0:
1892 /* name was specified as a relative path and the
1893 * directory component is the cwd */
1894 audit_log_d_path(ab, " name=", &context->pwd);
1895 break;
1896 default:
1897 /* log the name's directory component */
1898 audit_log_format(ab, " name=");
1899 audit_log_n_untrustedstring(ab, n->name->name,
1900 n->name_len);
1901 }
1902 } else
1903 audit_log_format(ab, " name=(null)");
1904
425afcff 1905 if (n->ino != AUDIT_INO_UNSET)
b24a30a7
EP
1906 audit_log_format(ab, " inode=%lu"
1907 " dev=%02x:%02x mode=%#ho"
1908 " ouid=%u ogid=%u rdev=%02x:%02x",
1909 n->ino,
1910 MAJOR(n->dev),
1911 MINOR(n->dev),
1912 n->mode,
1913 from_kuid(&init_user_ns, n->uid),
1914 from_kgid(&init_user_ns, n->gid),
1915 MAJOR(n->rdev),
1916 MINOR(n->rdev));
b24a30a7
EP
1917 if (n->osid != 0) {
1918 char *ctx = NULL;
1919 u32 len;
1920 if (security_secid_to_secctx(
1921 n->osid, &ctx, &len)) {
1922 audit_log_format(ab, " osid=%u", n->osid);
1923 if (call_panic)
1924 *call_panic = 2;
1925 } else {
1926 audit_log_format(ab, " obj=%s", ctx);
1927 security_release_secctx(ctx, len);
1928 }
1929 }
1930
d3aea84a
JL
1931 /* log the audit_names record type */
1932 audit_log_format(ab, " nametype=");
1933 switch(n->type) {
1934 case AUDIT_TYPE_NORMAL:
1935 audit_log_format(ab, "NORMAL");
1936 break;
1937 case AUDIT_TYPE_PARENT:
1938 audit_log_format(ab, "PARENT");
1939 break;
1940 case AUDIT_TYPE_CHILD_DELETE:
1941 audit_log_format(ab, "DELETE");
1942 break;
1943 case AUDIT_TYPE_CHILD_CREATE:
1944 audit_log_format(ab, "CREATE");
1945 break;
1946 default:
1947 audit_log_format(ab, "UNKNOWN");
1948 break;
1949 }
1950
b24a30a7
EP
1951 audit_log_fcaps(ab, n);
1952 audit_log_end(ab);
1953}
1954
1955int audit_log_task_context(struct audit_buffer *ab)
1956{
1957 char *ctx = NULL;
1958 unsigned len;
1959 int error;
1960 u32 sid;
1961
1962 security_task_getsecid(current, &sid);
1963 if (!sid)
1964 return 0;
1965
1966 error = security_secid_to_secctx(sid, &ctx, &len);
1967 if (error) {
1968 if (error != -EINVAL)
1969 goto error_path;
1970 return 0;
1971 }
1972
1973 audit_log_format(ab, " subj=%s", ctx);
1974 security_release_secctx(ctx, len);
1975 return 0;
1976
1977error_path:
1978 audit_panic("error in audit_log_task_context");
1979 return error;
1980}
1981EXPORT_SYMBOL(audit_log_task_context);
1982
4766b199
DB
1983void audit_log_d_path_exe(struct audit_buffer *ab,
1984 struct mm_struct *mm)
1985{
5b282552
DB
1986 struct file *exe_file;
1987
1988 if (!mm)
1989 goto out_null;
4766b199 1990
5b282552
DB
1991 exe_file = get_mm_exe_file(mm);
1992 if (!exe_file)
1993 goto out_null;
1994
1995 audit_log_d_path(ab, " exe=", &exe_file->f_path);
1996 fput(exe_file);
1997 return;
1998out_null:
1999 audit_log_format(ab, " exe=(null)");
4766b199
DB
2000}
2001
3f5be2da
RGB
2002struct tty_struct *audit_get_tty(struct task_struct *tsk)
2003{
2004 struct tty_struct *tty = NULL;
2005 unsigned long flags;
2006
2007 spin_lock_irqsave(&tsk->sighand->siglock, flags);
2008 if (tsk->signal)
2009 tty = tty_kref_get(tsk->signal->tty);
2010 spin_unlock_irqrestore(&tsk->sighand->siglock, flags);
2011 return tty;
2012}
2013
2014void audit_put_tty(struct tty_struct *tty)
2015{
2016 tty_kref_put(tty);
2017}
2018
b24a30a7
EP
2019void audit_log_task_info(struct audit_buffer *ab, struct task_struct *tsk)
2020{
2021 const struct cred *cred;
9eab339b 2022 char comm[sizeof(tsk->comm)];
db0a6fb5 2023 struct tty_struct *tty;
b24a30a7
EP
2024
2025 if (!ab)
2026 return;
2027
2028 /* tsk == current */
2029 cred = current_cred();
db0a6fb5 2030 tty = audit_get_tty(tsk);
b24a30a7 2031 audit_log_format(ab,
c92cdeb4 2032 " ppid=%d pid=%d auid=%u uid=%u gid=%u"
b24a30a7 2033 " euid=%u suid=%u fsuid=%u"
2f2ad101 2034 " egid=%u sgid=%u fsgid=%u tty=%s ses=%u",
c92cdeb4 2035 task_ppid_nr(tsk),
f1dc4867 2036 task_pid_nr(tsk),
b24a30a7
EP
2037 from_kuid(&init_user_ns, audit_get_loginuid(tsk)),
2038 from_kuid(&init_user_ns, cred->uid),
2039 from_kgid(&init_user_ns, cred->gid),
2040 from_kuid(&init_user_ns, cred->euid),
2041 from_kuid(&init_user_ns, cred->suid),
2042 from_kuid(&init_user_ns, cred->fsuid),
2043 from_kgid(&init_user_ns, cred->egid),
2044 from_kgid(&init_user_ns, cred->sgid),
2045 from_kgid(&init_user_ns, cred->fsgid),
db0a6fb5
RGB
2046 tty ? tty_name(tty) : "(none)",
2047 audit_get_sessionid(tsk));
2048 audit_put_tty(tty);
b24a30a7 2049 audit_log_format(ab, " comm=");
9eab339b 2050 audit_log_untrustedstring(ab, get_task_comm(comm, tsk));
4766b199 2051 audit_log_d_path_exe(ab, tsk->mm);
b24a30a7
EP
2052 audit_log_task_context(ab);
2053}
2054EXPORT_SYMBOL(audit_log_task_info);
2055
a51d9eaa
KC
2056/**
2057 * audit_log_link_denied - report a link restriction denial
22011964 2058 * @operation: specific link operation
a51d9eaa
KC
2059 * @link: the path that triggered the restriction
2060 */
2061void audit_log_link_denied(const char *operation, struct path *link)
2062{
2063 struct audit_buffer *ab;
b24a30a7
EP
2064 struct audit_names *name;
2065
2066 name = kzalloc(sizeof(*name), GFP_NOFS);
2067 if (!name)
2068 return;
a51d9eaa 2069
b24a30a7 2070 /* Generate AUDIT_ANOM_LINK with subject, operation, outcome. */
a51d9eaa
KC
2071 ab = audit_log_start(current->audit_context, GFP_KERNEL,
2072 AUDIT_ANOM_LINK);
d1c7d97a 2073 if (!ab)
b24a30a7
EP
2074 goto out;
2075 audit_log_format(ab, "op=%s", operation);
2076 audit_log_task_info(ab, current);
2077 audit_log_format(ab, " res=0");
a51d9eaa 2078 audit_log_end(ab);
b24a30a7
EP
2079
2080 /* Generate AUDIT_PATH record with object. */
2081 name->type = AUDIT_TYPE_NORMAL;
3b362157 2082 audit_copy_inode(name, link->dentry, d_backing_inode(link->dentry));
b24a30a7
EP
2083 audit_log_name(current->audit_context, name, link, 0, NULL);
2084out:
2085 kfree(name);
a51d9eaa
KC
2086}
2087
b0dd25a8
RD
2088/**
2089 * audit_log_end - end one audit record
2090 * @ab: the audit_buffer
2091 *
4aa83872
PM
2092 * We can not do a netlink send inside an irq context because it blocks (last
2093 * arg, flags, is not set to MSG_DONTWAIT), so the audit buffer is placed on a
2094 * queue and a tasklet is scheduled to remove them from the queue outside the
2095 * irq context. May be called in any context.
b0dd25a8 2096 */
b7d11258 2097void audit_log_end(struct audit_buffer *ab)
1da177e4 2098{
1da177e4
LT
2099 if (!ab)
2100 return;
2101 if (!audit_rate_check()) {
2102 audit_log_lost("rate limit exceeded");
2103 } else {
af8b824f 2104 skb_queue_tail(&audit_queue, ab->skb);
4aa83872 2105 wake_up_interruptible(&kauditd_wait);
f3d357b0 2106 ab->skb = NULL;
1da177e4 2107 }
16e1904e 2108 audit_buffer_free(ab);
1da177e4
LT
2109}
2110
b0dd25a8
RD
2111/**
2112 * audit_log - Log an audit record
2113 * @ctx: audit context
2114 * @gfp_mask: type of allocation
2115 * @type: audit message type
2116 * @fmt: format string to use
2117 * @...: variable parameters matching the format string
2118 *
2119 * This is a convenience function that calls audit_log_start,
2120 * audit_log_vformat, and audit_log_end. It may be called
2121 * in any context.
2122 */
5600b892 2123void audit_log(struct audit_context *ctx, gfp_t gfp_mask, int type,
9ad9ad38 2124 const char *fmt, ...)
1da177e4
LT
2125{
2126 struct audit_buffer *ab;
2127 va_list args;
2128
9ad9ad38 2129 ab = audit_log_start(ctx, gfp_mask, type);
1da177e4
LT
2130 if (ab) {
2131 va_start(args, fmt);
2132 audit_log_vformat(ab, fmt, args);
2133 va_end(args);
2134 audit_log_end(ab);
2135 }
2136}
bf45da97 2137
131ad62d
MDF
2138#ifdef CONFIG_SECURITY
2139/**
2140 * audit_log_secctx - Converts and logs SELinux context
2141 * @ab: audit_buffer
2142 * @secid: security number
2143 *
2144 * This is a helper function that calls security_secid_to_secctx to convert
2145 * secid to secctx and then adds the (converted) SELinux context to the audit
2146 * log by calling audit_log_format, thus also preventing leak of internal secid
2147 * to userspace. If secid cannot be converted audit_panic is called.
2148 */
2149void audit_log_secctx(struct audit_buffer *ab, u32 secid)
2150{
2151 u32 len;
2152 char *secctx;
2153
2154 if (security_secid_to_secctx(secid, &secctx, &len)) {
2155 audit_panic("Cannot convert secid to context");
2156 } else {
2157 audit_log_format(ab, " obj=%s", secctx);
2158 security_release_secctx(secctx, len);
2159 }
2160}
2161EXPORT_SYMBOL(audit_log_secctx);
2162#endif
2163
bf45da97 2164EXPORT_SYMBOL(audit_log_start);
2165EXPORT_SYMBOL(audit_log_end);
2166EXPORT_SYMBOL(audit_log_format);
2167EXPORT_SYMBOL(audit_log);