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