1 // SPDX-License-Identifier: GPL-2.0-or-later 2 /* audit.c -- Auditing support 3 * Gateway between the kernel (e.g., selinux) and the user-space audit daemon. 4 * System-call specific features have moved to auditsc.c 5 * 6 * Copyright 2003-2007 Red Hat Inc., Durham, North Carolina. 7 * All Rights Reserved. 8 * 9 * Written by Rickard E. (Rik) Faith <faith@redhat.com> 10 * 11 * Goals: 1) Integrate fully with Security Modules. 12 * 2) Minimal run-time overhead: 13 * a) Minimal when syscall auditing is disabled (audit_enable=0). 14 * b) Small when syscall auditing is enabled and no audit record 15 * is generated (defer as much work as possible to record 16 * generation time): 17 * i) context is allocated, 18 * ii) names from getname are stored without a copy, and 19 * iii) inode information stored from path_lookup. 20 * 3) Ability to disable syscall auditing at boot time (audit=0). 21 * 4) Usable by other parts of the kernel (if audit_log* is called, 22 * then a syscall record will be generated automatically for the 23 * current syscall). 24 * 5) Netlink interface to user-space. 25 * 6) Support low-overhead kernel-based filtering to minimize the 26 * information that must be passed to user-space. 27 * 28 * Audit userspace, documentation, tests, and bug/issue trackers: 29 * https://github.com/linux-audit 30 */ 31 32 #define pr_fmt(fmt) KBUILD_MODNAME ": " fmt 33 34 #include <linux/file.h> 35 #include <linux/init.h> 36 #include <linux/types.h> 37 #include <linux/atomic.h> 38 #include <linux/mm.h> 39 #include <linux/export.h> 40 #include <linux/slab.h> 41 #include <linux/err.h> 42 #include <linux/kthread.h> 43 #include <linux/kernel.h> 44 #include <linux/syscalls.h> 45 #include <linux/spinlock.h> 46 #include <linux/rcupdate.h> 47 #include <linux/mutex.h> 48 #include <linux/gfp.h> 49 #include <linux/pid.h> 50 51 #include <linux/audit.h> 52 53 #include <net/sock.h> 54 #include <net/netlink.h> 55 #include <linux/skbuff.h> 56 #include <linux/security.h> 57 #include <linux/lsm_hooks.h> 58 #include <linux/freezer.h> 59 #include <linux/pid_namespace.h> 60 #include <net/netns/generic.h> 61 62 #include "audit.h" 63 64 /* No auditing will take place until audit_initialized == AUDIT_INITIALIZED. 65 * (Initialization happens after skb_init is called.) */ 66 #define AUDIT_DISABLED -1 67 #define AUDIT_UNINITIALIZED 0 68 #define AUDIT_INITIALIZED 1 69 static int audit_initialized = AUDIT_UNINITIALIZED; 70 71 u32 audit_enabled = AUDIT_OFF; 72 bool audit_ever_enabled = !!AUDIT_OFF; 73 74 EXPORT_SYMBOL_GPL(audit_enabled); 75 76 /* Default state when kernel boots without any parameters. */ 77 static u32 audit_default = AUDIT_OFF; 78 79 /* If auditing cannot proceed, audit_failure selects what happens. */ 80 static u32 audit_failure = AUDIT_FAIL_PRINTK; 81 82 /* private audit network namespace index */ 83 static unsigned int audit_net_id; 84 85 /* Number of modules that provide a security context. 86 List of lsms that provide a security context */ 87 static u32 audit_subj_secctx_cnt; 88 static u32 audit_obj_secctx_cnt; 89 static const struct lsm_id *audit_subj_lsms[MAX_LSM_COUNT]; 90 static const struct lsm_id *audit_obj_lsms[MAX_LSM_COUNT]; 91 92 /** 93 * struct audit_net - audit private network namespace data 94 * @sk: communication socket 95 */ 96 struct audit_net { 97 struct sock *sk; 98 }; 99 100 /** 101 * struct auditd_connection - kernel/auditd connection state 102 * @pid: auditd PID 103 * @portid: netlink portid 104 * @net: the associated network namespace 105 * @rcu: RCU head 106 * 107 * Description: 108 * This struct is RCU protected; you must either hold the RCU lock for reading 109 * or the associated spinlock for writing. 110 */ 111 struct auditd_connection { 112 struct pid *pid; 113 u32 portid; 114 struct net *net; 115 struct rcu_head rcu; 116 }; 117 static struct auditd_connection __rcu *auditd_conn; 118 static DEFINE_SPINLOCK(auditd_conn_lock); 119 120 /* If audit_rate_limit is non-zero, limit the rate of sending audit records 121 * to that number per second. This prevents DoS attacks, but results in 122 * audit records being dropped. */ 123 static u32 audit_rate_limit; 124 125 /* Number of outstanding audit_buffers allowed. 126 * When set to zero, this means unlimited. */ 127 static u32 audit_backlog_limit = 64; 128 #define AUDIT_BACKLOG_WAIT_TIME (60 * HZ) 129 static u32 audit_backlog_wait_time = AUDIT_BACKLOG_WAIT_TIME; 130 131 /* The identity of the user shutting down the audit system. */ 132 static kuid_t audit_sig_uid = INVALID_UID; 133 static pid_t audit_sig_pid = -1; 134 static struct lsm_prop audit_sig_lsm; 135 136 /* Records can be lost in several ways: 137 0) [suppressed in audit_alloc] 138 1) out of memory in audit_log_start [kmalloc of struct audit_buffer] 139 2) out of memory in audit_log_move [alloc_skb] 140 3) suppressed due to audit_rate_limit 141 4) suppressed due to audit_backlog_limit 142 */ 143 static atomic_t audit_lost = ATOMIC_INIT(0); 144 145 /* Monotonically increasing sum of time the kernel has spent 146 * waiting while the backlog limit is exceeded. 147 */ 148 static atomic_t audit_backlog_wait_time_actual = ATOMIC_INIT(0); 149 150 /* Hash for inode-based rules */ 151 struct list_head audit_inode_hash[AUDIT_INODE_BUCKETS]; 152 153 static struct kmem_cache *audit_buffer_cache; 154 155 /* queue msgs to send via kauditd_task */ 156 static struct sk_buff_head audit_queue; 157 /* queue msgs due to temporary unicast send problems */ 158 static struct sk_buff_head audit_retry_queue; 159 /* queue msgs waiting for new auditd connection */ 160 static struct sk_buff_head audit_hold_queue; 161 162 /* queue servicing thread */ 163 static struct task_struct *kauditd_task; 164 static DECLARE_WAIT_QUEUE_HEAD(kauditd_wait); 165 166 /* waitqueue for callers who are blocked on the audit backlog */ 167 static DECLARE_WAIT_QUEUE_HEAD(audit_backlog_wait); 168 169 static struct audit_features af = {.vers = AUDIT_FEATURE_VERSION, 170 .mask = -1, 171 .features = 0, 172 .lock = 0,}; 173 174 static char *audit_feature_names[2] = { 175 "only_unset_loginuid", 176 "loginuid_immutable", 177 }; 178 179 /** 180 * struct audit_ctl_mutex - serialize requests from userspace 181 * @lock: the mutex used for locking 182 * @owner: the task which owns the lock 183 * 184 * Description: 185 * This is the lock struct used to ensure we only process userspace requests 186 * in an orderly fashion. We can't simply use a mutex/lock here because we 187 * need to track lock ownership so we don't end up blocking the lock owner in 188 * audit_log_start() or similar. 189 */ 190 static struct audit_ctl_mutex { 191 struct mutex lock; 192 void *owner; 193 } audit_cmd_mutex; 194 195 /* AUDIT_BUFSIZ is the size of the temporary buffer used for formatting 196 * audit records. Since printk uses a 1024 byte buffer, this buffer 197 * should be at least that large. */ 198 #define AUDIT_BUFSIZ 1024 199 200 /* The audit_buffer is used when formatting an audit record. The caller 201 * locks briefly to get the record off the freelist or to allocate the 202 * buffer, and locks briefly to send the buffer to the netlink layer or 203 * to place it on a transmit queue. Multiple audit_buffers can be in 204 * use simultaneously. */ 205 struct audit_buffer { 206 struct sk_buff *skb; /* the skb for audit_log functions */ 207 struct sk_buff_head skb_list; /* formatted skbs, ready to send */ 208 struct audit_context *ctx; /* NULL or associated context */ 209 struct audit_stamp stamp; /* audit stamp for these records */ 210 gfp_t gfp_mask; 211 }; 212 213 struct audit_reply { 214 __u32 portid; 215 struct net *net; 216 struct sk_buff *skb; 217 }; 218 219 /** 220 * auditd_test_task - Check to see if a given task is an audit daemon 221 * @task: the task to check 222 * 223 * Description: 224 * Return 1 if the task is a registered audit daemon, 0 otherwise. 225 */ 226 int auditd_test_task(struct task_struct *task) 227 { 228 int rc; 229 struct auditd_connection *ac; 230 231 rcu_read_lock(); 232 ac = rcu_dereference(auditd_conn); 233 rc = (ac && ac->pid == task_tgid(task) ? 1 : 0); 234 rcu_read_unlock(); 235 236 return rc; 237 } 238 239 /** 240 * audit_ctl_lock - Take the audit control lock 241 */ 242 void audit_ctl_lock(void) 243 { 244 mutex_lock(&audit_cmd_mutex.lock); 245 audit_cmd_mutex.owner = current; 246 } 247 248 /** 249 * audit_ctl_unlock - Drop the audit control lock 250 */ 251 void audit_ctl_unlock(void) 252 { 253 audit_cmd_mutex.owner = NULL; 254 mutex_unlock(&audit_cmd_mutex.lock); 255 } 256 257 /** 258 * audit_ctl_owner_current - Test to see if the current task owns the lock 259 * 260 * Description: 261 * Return true if the current task owns the audit control lock, false if it 262 * doesn't own the lock. 263 */ 264 static bool audit_ctl_owner_current(void) 265 { 266 return (current == audit_cmd_mutex.owner); 267 } 268 269 /** 270 * auditd_pid_vnr - Return the auditd PID relative to the namespace 271 * 272 * Description: 273 * Returns the PID in relation to the namespace, 0 on failure. 274 */ 275 static pid_t auditd_pid_vnr(void) 276 { 277 pid_t pid; 278 const struct auditd_connection *ac; 279 280 rcu_read_lock(); 281 ac = rcu_dereference(auditd_conn); 282 if (!ac || !ac->pid) 283 pid = 0; 284 else 285 pid = pid_vnr(ac->pid); 286 rcu_read_unlock(); 287 288 return pid; 289 } 290 291 /** 292 * audit_cfg_lsm - Identify a security module as providing a secctx. 293 * @lsmid: LSM identity 294 * @flags: which contexts are provided 295 * 296 * Description: 297 * Increments the count of the security modules providing a secctx. 298 * If the LSM id is already in the list leave it alone. 299 */ 300 void audit_cfg_lsm(const struct lsm_id *lsmid, int flags) 301 { 302 int i; 303 304 if (flags & AUDIT_CFG_LSM_SECCTX_SUBJECT) { 305 for (i = 0 ; i < audit_subj_secctx_cnt; i++) 306 if (audit_subj_lsms[i] == lsmid) 307 return; 308 audit_subj_lsms[audit_subj_secctx_cnt++] = lsmid; 309 } 310 if (flags & AUDIT_CFG_LSM_SECCTX_OBJECT) { 311 for (i = 0 ; i < audit_obj_secctx_cnt; i++) 312 if (audit_obj_lsms[i] == lsmid) 313 return; 314 audit_obj_lsms[audit_obj_secctx_cnt++] = lsmid; 315 } 316 } 317 318 /** 319 * audit_get_sk - Return the audit socket for the given network namespace 320 * @net: the destination network namespace 321 * 322 * Description: 323 * Returns the sock pointer if valid, NULL otherwise. The caller must ensure 324 * that a reference is held for the network namespace while the sock is in use. 325 */ 326 static struct sock *audit_get_sk(const struct net *net) 327 { 328 struct audit_net *aunet; 329 330 if (!net) 331 return NULL; 332 333 aunet = net_generic(net, audit_net_id); 334 return aunet->sk; 335 } 336 337 void audit_panic(const char *message) 338 { 339 switch (audit_failure) { 340 case AUDIT_FAIL_SILENT: 341 break; 342 case AUDIT_FAIL_PRINTK: 343 if (printk_ratelimit()) 344 pr_err("%s\n", message); 345 break; 346 case AUDIT_FAIL_PANIC: 347 panic("audit: %s\n", message); 348 break; 349 } 350 } 351 352 static inline int audit_rate_check(void) 353 { 354 static unsigned long last_check = 0; 355 static int messages = 0; 356 static DEFINE_SPINLOCK(lock); 357 unsigned long flags; 358 unsigned long now; 359 int retval = 0; 360 361 if (!audit_rate_limit) 362 return 1; 363 364 spin_lock_irqsave(&lock, flags); 365 if (++messages < audit_rate_limit) { 366 retval = 1; 367 } else { 368 now = jiffies; 369 if (time_after(now, last_check + HZ)) { 370 last_check = now; 371 messages = 0; 372 retval = 1; 373 } 374 } 375 spin_unlock_irqrestore(&lock, flags); 376 377 return retval; 378 } 379 380 /** 381 * audit_log_lost - conditionally log lost audit message event 382 * @message: the message stating reason for lost audit message 383 * 384 * Emit at least 1 message per second, even if audit_rate_check is 385 * throttling. 386 * Always increment the lost messages counter. 387 */ 388 void audit_log_lost(const char *message) 389 { 390 static unsigned long last_msg = 0; 391 static DEFINE_SPINLOCK(lock); 392 unsigned long flags; 393 unsigned long now; 394 int print; 395 396 atomic_inc(&audit_lost); 397 398 print = (audit_failure == AUDIT_FAIL_PANIC || !audit_rate_limit); 399 400 if (!print) { 401 spin_lock_irqsave(&lock, flags); 402 now = jiffies; 403 if (time_after(now, last_msg + HZ)) { 404 print = 1; 405 last_msg = now; 406 } 407 spin_unlock_irqrestore(&lock, flags); 408 } 409 410 if (print) { 411 if (printk_ratelimit()) 412 pr_warn("audit_lost=%u audit_rate_limit=%u audit_backlog_limit=%u\n", 413 atomic_read(&audit_lost), 414 audit_rate_limit, 415 audit_backlog_limit); 416 audit_panic(message); 417 } 418 } 419 420 static int audit_log_config_change(char *function_name, u32 new, u32 old, 421 int allow_changes) 422 { 423 struct audit_buffer *ab; 424 int rc = 0; 425 426 ab = audit_log_start(audit_context(), GFP_KERNEL, AUDIT_CONFIG_CHANGE); 427 if (unlikely(!ab)) 428 return rc; 429 audit_log_format(ab, "op=set %s=%u old=%u ", function_name, new, old); 430 audit_log_session_info(ab); 431 rc = audit_log_task_context(ab); 432 if (rc) 433 allow_changes = 0; /* Something weird, deny request */ 434 audit_log_format(ab, " res=%d", allow_changes); 435 audit_log_end(ab); 436 return rc; 437 } 438 439 static int audit_do_config_change(char *function_name, u32 *to_change, u32 new) 440 { 441 int allow_changes, rc = 0; 442 u32 old = *to_change; 443 444 /* check if we are locked */ 445 if (audit_enabled == AUDIT_LOCKED) 446 allow_changes = 0; 447 else 448 allow_changes = 1; 449 450 if (audit_enabled != AUDIT_OFF) { 451 rc = audit_log_config_change(function_name, new, old, allow_changes); 452 if (rc) 453 allow_changes = 0; 454 } 455 456 /* If we are allowed, make the change */ 457 if (allow_changes == 1) 458 *to_change = new; 459 /* Not allowed, update reason */ 460 else if (rc == 0) 461 rc = -EPERM; 462 return rc; 463 } 464 465 static int audit_set_rate_limit(u32 limit) 466 { 467 return audit_do_config_change("audit_rate_limit", &audit_rate_limit, limit); 468 } 469 470 static int audit_set_backlog_limit(u32 limit) 471 { 472 return audit_do_config_change("audit_backlog_limit", &audit_backlog_limit, limit); 473 } 474 475 static int audit_set_backlog_wait_time(u32 timeout) 476 { 477 return audit_do_config_change("audit_backlog_wait_time", 478 &audit_backlog_wait_time, timeout); 479 } 480 481 static int audit_set_enabled(u32 state) 482 { 483 int rc; 484 if (state > AUDIT_LOCKED) 485 return -EINVAL; 486 487 rc = audit_do_config_change("audit_enabled", &audit_enabled, state); 488 if (!rc) 489 audit_ever_enabled |= !!state; 490 491 return rc; 492 } 493 494 static int audit_set_failure(u32 state) 495 { 496 if (state != AUDIT_FAIL_SILENT 497 && state != AUDIT_FAIL_PRINTK 498 && state != AUDIT_FAIL_PANIC) 499 return -EINVAL; 500 501 return audit_do_config_change("audit_failure", &audit_failure, state); 502 } 503 504 /** 505 * auditd_conn_free - RCU helper to release an auditd connection struct 506 * @rcu: RCU head 507 * 508 * Description: 509 * Drop any references inside the auditd connection tracking struct and free 510 * the memory. 511 */ 512 static void auditd_conn_free(struct rcu_head *rcu) 513 { 514 struct auditd_connection *ac; 515 516 ac = container_of(rcu, struct auditd_connection, rcu); 517 put_pid(ac->pid); 518 put_net(ac->net); 519 kfree(ac); 520 } 521 522 /** 523 * auditd_set - Set/Reset the auditd connection state 524 * @pid: auditd PID 525 * @portid: auditd netlink portid 526 * @net: auditd network namespace pointer 527 * @skb: the netlink command from the audit daemon 528 * @ack: netlink ack flag, cleared if ack'd here 529 * 530 * Description: 531 * This function will obtain and drop network namespace references as 532 * necessary. Returns zero on success, negative values on failure. 533 */ 534 static int auditd_set(struct pid *pid, u32 portid, struct net *net, 535 struct sk_buff *skb, bool *ack) 536 { 537 unsigned long flags; 538 struct auditd_connection *ac_old, *ac_new; 539 struct nlmsghdr *nlh; 540 541 if (!pid || !net) 542 return -EINVAL; 543 544 ac_new = kzalloc(sizeof(*ac_new), GFP_KERNEL); 545 if (!ac_new) 546 return -ENOMEM; 547 ac_new->pid = get_pid(pid); 548 ac_new->portid = portid; 549 ac_new->net = get_net(net); 550 551 /* send the ack now to avoid a race with the queue backlog */ 552 if (*ack) { 553 nlh = nlmsg_hdr(skb); 554 netlink_ack(skb, nlh, 0, NULL); 555 *ack = false; 556 } 557 558 spin_lock_irqsave(&auditd_conn_lock, flags); 559 ac_old = rcu_dereference_protected(auditd_conn, 560 lockdep_is_held(&auditd_conn_lock)); 561 rcu_assign_pointer(auditd_conn, ac_new); 562 spin_unlock_irqrestore(&auditd_conn_lock, flags); 563 564 if (ac_old) 565 call_rcu(&ac_old->rcu, auditd_conn_free); 566 567 return 0; 568 } 569 570 /** 571 * kauditd_printk_skb - Print the audit record to the ring buffer 572 * @skb: audit record 573 * 574 * Whatever the reason, this packet may not make it to the auditd connection 575 * so write it via printk so the information isn't completely lost. 576 */ 577 static void kauditd_printk_skb(struct sk_buff *skb) 578 { 579 struct nlmsghdr *nlh = nlmsg_hdr(skb); 580 char *data = nlmsg_data(nlh); 581 582 if (nlh->nlmsg_type != AUDIT_EOE && printk_ratelimit()) 583 pr_notice("type=%d %s\n", nlh->nlmsg_type, data); 584 } 585 586 /** 587 * kauditd_rehold_skb - Handle a audit record send failure in the hold queue 588 * @skb: audit record 589 * @error: error code (unused) 590 * 591 * Description: 592 * This should only be used by the kauditd_thread when it fails to flush the 593 * hold queue. 594 */ 595 static void kauditd_rehold_skb(struct sk_buff *skb, __always_unused int error) 596 { 597 /* put the record back in the queue */ 598 skb_queue_tail(&audit_hold_queue, skb); 599 } 600 601 /** 602 * kauditd_hold_skb - Queue an audit record, waiting for auditd 603 * @skb: audit record 604 * @error: error code 605 * 606 * Description: 607 * Queue the audit record, waiting for an instance of auditd. When this 608 * function is called we haven't given up yet on sending the record, but things 609 * are not looking good. The first thing we want to do is try to write the 610 * record via printk and then see if we want to try and hold on to the record 611 * and queue it, if we have room. If we want to hold on to the record, but we 612 * don't have room, record a record lost message. 613 */ 614 static void kauditd_hold_skb(struct sk_buff *skb, int error) 615 { 616 /* at this point it is uncertain if we will ever send this to auditd so 617 * try to send the message via printk before we go any further */ 618 kauditd_printk_skb(skb); 619 620 /* can we just silently drop the message? */ 621 if (!audit_default) 622 goto drop; 623 624 /* the hold queue is only for when the daemon goes away completely, 625 * not -EAGAIN failures; if we are in a -EAGAIN state requeue the 626 * record on the retry queue unless it's full, in which case drop it 627 */ 628 if (error == -EAGAIN) { 629 if (!audit_backlog_limit || 630 skb_queue_len(&audit_retry_queue) < audit_backlog_limit) { 631 skb_queue_tail(&audit_retry_queue, skb); 632 return; 633 } 634 audit_log_lost("kauditd retry queue overflow"); 635 goto drop; 636 } 637 638 /* if we have room in the hold queue, queue the message */ 639 if (!audit_backlog_limit || 640 skb_queue_len(&audit_hold_queue) < audit_backlog_limit) { 641 skb_queue_tail(&audit_hold_queue, skb); 642 return; 643 } 644 645 /* we have no other options - drop the message */ 646 audit_log_lost("kauditd hold queue overflow"); 647 drop: 648 kfree_skb(skb); 649 } 650 651 /** 652 * kauditd_retry_skb - Queue an audit record, attempt to send again to auditd 653 * @skb: audit record 654 * @error: error code (unused) 655 * 656 * Description: 657 * Not as serious as kauditd_hold_skb() as we still have a connected auditd, 658 * but for some reason we are having problems sending it audit records so 659 * queue the given record and attempt to resend. 660 */ 661 static void kauditd_retry_skb(struct sk_buff *skb, __always_unused int error) 662 { 663 if (!audit_backlog_limit || 664 skb_queue_len(&audit_retry_queue) < audit_backlog_limit) { 665 skb_queue_tail(&audit_retry_queue, skb); 666 return; 667 } 668 669 /* we have to drop the record, send it via printk as a last effort */ 670 kauditd_printk_skb(skb); 671 audit_log_lost("kauditd retry queue overflow"); 672 kfree_skb(skb); 673 } 674 675 /** 676 * auditd_reset - Disconnect the auditd connection 677 * @ac: auditd connection state 678 * 679 * Description: 680 * Break the auditd/kauditd connection and move all the queued records into the 681 * hold queue in case auditd reconnects. It is important to note that the @ac 682 * pointer should never be dereferenced inside this function as it may be NULL 683 * or invalid, you can only compare the memory address! If @ac is NULL then 684 * the connection will always be reset. 685 */ 686 static void auditd_reset(const struct auditd_connection *ac) 687 { 688 unsigned long flags; 689 struct sk_buff *skb; 690 struct auditd_connection *ac_old; 691 692 /* if it isn't already broken, break the connection */ 693 spin_lock_irqsave(&auditd_conn_lock, flags); 694 ac_old = rcu_dereference_protected(auditd_conn, 695 lockdep_is_held(&auditd_conn_lock)); 696 if (ac && ac != ac_old) { 697 /* someone already registered a new auditd connection */ 698 spin_unlock_irqrestore(&auditd_conn_lock, flags); 699 return; 700 } 701 rcu_assign_pointer(auditd_conn, NULL); 702 spin_unlock_irqrestore(&auditd_conn_lock, flags); 703 704 if (ac_old) 705 call_rcu(&ac_old->rcu, auditd_conn_free); 706 707 /* flush the retry queue to the hold queue, but don't touch the main 708 * queue since we need to process that normally for multicast */ 709 while ((skb = skb_dequeue(&audit_retry_queue))) 710 kauditd_hold_skb(skb, -ECONNREFUSED); 711 } 712 713 /** 714 * auditd_send_unicast_skb - Send a record via unicast to auditd 715 * @skb: audit record 716 * 717 * Description: 718 * Send a skb to the audit daemon, returns positive/zero values on success and 719 * negative values on failure; in all cases the skb will be consumed by this 720 * function. If the send results in -ECONNREFUSED the connection with auditd 721 * will be reset. This function may sleep so callers should not hold any locks 722 * where this would cause a problem. 723 */ 724 static int auditd_send_unicast_skb(struct sk_buff *skb) 725 { 726 int rc; 727 u32 portid; 728 struct net *net; 729 struct sock *sk; 730 struct auditd_connection *ac; 731 732 /* NOTE: we can't call netlink_unicast while in the RCU section so 733 * take a reference to the network namespace and grab local 734 * copies of the namespace, the sock, and the portid; the 735 * namespace and sock aren't going to go away while we hold a 736 * reference and if the portid does become invalid after the RCU 737 * section netlink_unicast() should safely return an error */ 738 739 rcu_read_lock(); 740 ac = rcu_dereference(auditd_conn); 741 if (!ac) { 742 rcu_read_unlock(); 743 kfree_skb(skb); 744 rc = -ECONNREFUSED; 745 goto err; 746 } 747 net = get_net(ac->net); 748 sk = audit_get_sk(net); 749 portid = ac->portid; 750 rcu_read_unlock(); 751 752 rc = netlink_unicast(sk, skb, portid, 0); 753 put_net(net); 754 if (rc < 0) 755 goto err; 756 757 return rc; 758 759 err: 760 if (ac && rc == -ECONNREFUSED) 761 auditd_reset(ac); 762 return rc; 763 } 764 765 /** 766 * kauditd_send_queue - Helper for kauditd_thread to flush skb queues 767 * @sk: the sending sock 768 * @portid: the netlink destination 769 * @queue: the skb queue to process 770 * @retry_limit: limit on number of netlink unicast failures 771 * @skb_hook: per-skb hook for additional processing 772 * @err_hook: hook called if the skb fails the netlink unicast send 773 * 774 * Description: 775 * Run through the given queue and attempt to send the audit records to auditd, 776 * returns zero on success, negative values on failure. It is up to the caller 777 * to ensure that the @sk is valid for the duration of this function. 778 * 779 */ 780 static int kauditd_send_queue(struct sock *sk, u32 portid, 781 struct sk_buff_head *queue, 782 unsigned int retry_limit, 783 void (*skb_hook)(struct sk_buff *skb), 784 void (*err_hook)(struct sk_buff *skb, int error)) 785 { 786 int rc = 0; 787 struct sk_buff *skb = NULL; 788 struct sk_buff *skb_tail; 789 unsigned int failed = 0; 790 791 /* NOTE: kauditd_thread takes care of all our locking, we just use 792 * the netlink info passed to us (e.g. sk and portid) */ 793 794 skb_tail = skb_peek_tail(queue); 795 while ((skb != skb_tail) && (skb = skb_dequeue(queue))) { 796 /* call the skb_hook for each skb we touch */ 797 if (skb_hook) 798 (*skb_hook)(skb); 799 800 /* can we send to anyone via unicast? */ 801 if (!sk) { 802 if (err_hook) 803 (*err_hook)(skb, -ECONNREFUSED); 804 continue; 805 } 806 807 retry: 808 /* grab an extra skb reference in case of error */ 809 skb_get(skb); 810 rc = netlink_unicast(sk, skb, portid, 0); 811 if (rc < 0) { 812 /* send failed - try a few times unless fatal error */ 813 if (++failed >= retry_limit || 814 rc == -ECONNREFUSED || rc == -EPERM) { 815 sk = NULL; 816 if (err_hook) 817 (*err_hook)(skb, rc); 818 if (rc == -EAGAIN) 819 rc = 0; 820 /* continue to drain the queue */ 821 continue; 822 } else 823 goto retry; 824 } else { 825 /* skb sent - drop the extra reference and continue */ 826 consume_skb(skb); 827 failed = 0; 828 } 829 } 830 831 return (rc >= 0 ? 0 : rc); 832 } 833 834 /* 835 * kauditd_send_multicast_skb - Send a record to any multicast listeners 836 * @skb: audit record 837 * 838 * Description: 839 * Write a multicast message to anyone listening in the initial network 840 * namespace. This function doesn't consume an skb as might be expected since 841 * it has to copy it anyways. 842 */ 843 static void kauditd_send_multicast_skb(struct sk_buff *skb) 844 { 845 struct sk_buff *copy; 846 struct sock *sock = audit_get_sk(&init_net); 847 struct nlmsghdr *nlh; 848 849 /* NOTE: we are not taking an additional reference for init_net since 850 * we don't have to worry about it going away */ 851 852 if (!netlink_has_listeners(sock, AUDIT_NLGRP_READLOG)) 853 return; 854 855 /* 856 * The seemingly wasteful skb_copy() rather than bumping the refcount 857 * using skb_get() is necessary because non-standard mods are made to 858 * the skb by the original kaudit unicast socket send routine. The 859 * existing auditd daemon assumes this breakage. Fixing this would 860 * require co-ordinating a change in the established protocol between 861 * the kaudit kernel subsystem and the auditd userspace code. There is 862 * no reason for new multicast clients to continue with this 863 * non-compliance. 864 */ 865 copy = skb_copy(skb, GFP_KERNEL); 866 if (!copy) 867 return; 868 nlh = nlmsg_hdr(copy); 869 nlh->nlmsg_len = skb->len; 870 871 nlmsg_multicast(sock, copy, 0, AUDIT_NLGRP_READLOG, GFP_KERNEL); 872 } 873 874 /** 875 * kauditd_thread - Worker thread to send audit records to userspace 876 * @dummy: unused 877 */ 878 static int kauditd_thread(void *dummy) 879 { 880 int rc; 881 u32 portid = 0; 882 struct net *net = NULL; 883 struct sock *sk = NULL; 884 struct auditd_connection *ac; 885 886 #define UNICAST_RETRIES 5 887 888 set_freezable(); 889 while (!kthread_should_stop()) { 890 /* NOTE: see the lock comments in auditd_send_unicast_skb() */ 891 rcu_read_lock(); 892 ac = rcu_dereference(auditd_conn); 893 if (!ac) { 894 rcu_read_unlock(); 895 goto main_queue; 896 } 897 net = get_net(ac->net); 898 sk = audit_get_sk(net); 899 portid = ac->portid; 900 rcu_read_unlock(); 901 902 /* attempt to flush the hold queue */ 903 rc = kauditd_send_queue(sk, portid, 904 &audit_hold_queue, UNICAST_RETRIES, 905 NULL, kauditd_rehold_skb); 906 if (rc < 0) { 907 sk = NULL; 908 auditd_reset(ac); 909 goto main_queue; 910 } 911 912 /* attempt to flush the retry queue */ 913 rc = kauditd_send_queue(sk, portid, 914 &audit_retry_queue, UNICAST_RETRIES, 915 NULL, kauditd_hold_skb); 916 if (rc < 0) { 917 sk = NULL; 918 auditd_reset(ac); 919 goto main_queue; 920 } 921 922 main_queue: 923 /* process the main queue - do the multicast send and attempt 924 * unicast, dump failed record sends to the retry queue; if 925 * sk == NULL due to previous failures we will just do the 926 * multicast send and move the record to the hold queue */ 927 rc = kauditd_send_queue(sk, portid, &audit_queue, 1, 928 kauditd_send_multicast_skb, 929 (sk ? 930 kauditd_retry_skb : kauditd_hold_skb)); 931 if (ac && rc < 0) 932 auditd_reset(ac); 933 sk = NULL; 934 935 /* drop our netns reference, no auditd sends past this line */ 936 if (net) { 937 put_net(net); 938 net = NULL; 939 } 940 941 /* we have processed all the queues so wake everyone */ 942 wake_up(&audit_backlog_wait); 943 944 /* NOTE: we want to wake up if there is anything on the queue, 945 * regardless of if an auditd is connected, as we need to 946 * do the multicast send and rotate records from the 947 * main queue to the retry/hold queues */ 948 wait_event_freezable(kauditd_wait, 949 (skb_queue_len(&audit_queue) ? 1 : 0)); 950 } 951 952 return 0; 953 } 954 955 int audit_send_list_thread(void *_dest) 956 { 957 struct audit_netlink_list *dest = _dest; 958 struct sk_buff *skb; 959 struct sock *sk = audit_get_sk(dest->net); 960 961 /* wait for parent to finish and send an ACK */ 962 audit_ctl_lock(); 963 audit_ctl_unlock(); 964 965 while ((skb = __skb_dequeue(&dest->q)) != NULL) 966 netlink_unicast(sk, skb, dest->portid, 0); 967 968 put_net(dest->net); 969 kfree(dest); 970 971 return 0; 972 } 973 974 struct sk_buff *audit_make_reply(int seq, int type, int done, 975 int multi, const void *payload, int size) 976 { 977 struct sk_buff *skb; 978 struct nlmsghdr *nlh; 979 void *data; 980 int flags = multi ? NLM_F_MULTI : 0; 981 int t = done ? NLMSG_DONE : type; 982 983 skb = nlmsg_new(size, GFP_KERNEL); 984 if (!skb) 985 return NULL; 986 987 nlh = nlmsg_put(skb, 0, seq, t, size, flags); 988 if (!nlh) 989 goto out_kfree_skb; 990 data = nlmsg_data(nlh); 991 memcpy(data, payload, size); 992 return skb; 993 994 out_kfree_skb: 995 kfree_skb(skb); 996 return NULL; 997 } 998 999 static void audit_free_reply(struct audit_reply *reply) 1000 { 1001 if (!reply) 1002 return; 1003 1004 kfree_skb(reply->skb); 1005 if (reply->net) 1006 put_net(reply->net); 1007 kfree(reply); 1008 } 1009 1010 static int audit_send_reply_thread(void *arg) 1011 { 1012 struct audit_reply *reply = (struct audit_reply *)arg; 1013 1014 audit_ctl_lock(); 1015 audit_ctl_unlock(); 1016 1017 /* Ignore failure. It'll only happen if the sender goes away, 1018 because our timeout is set to infinite. */ 1019 netlink_unicast(audit_get_sk(reply->net), reply->skb, reply->portid, 0); 1020 reply->skb = NULL; 1021 audit_free_reply(reply); 1022 return 0; 1023 } 1024 1025 /** 1026 * audit_send_reply - send an audit reply message via netlink 1027 * @request_skb: skb of request we are replying to (used to target the reply) 1028 * @seq: sequence number 1029 * @type: audit message type 1030 * @done: done (last) flag 1031 * @multi: multi-part message flag 1032 * @payload: payload data 1033 * @size: payload size 1034 * 1035 * Allocates a skb, builds the netlink message, and sends it to the port id. 1036 */ 1037 static void audit_send_reply(struct sk_buff *request_skb, int seq, int type, int done, 1038 int multi, const void *payload, int size) 1039 { 1040 struct task_struct *tsk; 1041 struct audit_reply *reply; 1042 1043 reply = kzalloc(sizeof(*reply), GFP_KERNEL); 1044 if (!reply) 1045 return; 1046 1047 reply->skb = audit_make_reply(seq, type, done, multi, payload, size); 1048 if (!reply->skb) 1049 goto err; 1050 reply->net = get_net(sock_net(NETLINK_CB(request_skb).sk)); 1051 reply->portid = NETLINK_CB(request_skb).portid; 1052 1053 tsk = kthread_run(audit_send_reply_thread, reply, "audit_send_reply"); 1054 if (IS_ERR(tsk)) 1055 goto err; 1056 1057 return; 1058 1059 err: 1060 audit_free_reply(reply); 1061 } 1062 1063 /* 1064 * Check for appropriate CAP_AUDIT_ capabilities on incoming audit 1065 * control messages. 1066 */ 1067 static int audit_netlink_ok(struct sk_buff *skb, u16 msg_type) 1068 { 1069 int err = 0; 1070 1071 /* Only support initial user namespace for now. */ 1072 /* 1073 * We return ECONNREFUSED because it tricks userspace into thinking 1074 * that audit was not configured into the kernel. Lots of users 1075 * configure their PAM stack (because that's what the distro does) 1076 * to reject login if unable to send messages to audit. If we return 1077 * ECONNREFUSED the PAM stack thinks the kernel does not have audit 1078 * configured in and will let login proceed. If we return EPERM 1079 * userspace will reject all logins. This should be removed when we 1080 * support non init namespaces!! 1081 */ 1082 if (current_user_ns() != &init_user_ns) 1083 return -ECONNREFUSED; 1084 1085 switch (msg_type) { 1086 case AUDIT_LIST: 1087 case AUDIT_ADD: 1088 case AUDIT_DEL: 1089 return -EOPNOTSUPP; 1090 case AUDIT_GET: 1091 case AUDIT_SET: 1092 case AUDIT_GET_FEATURE: 1093 case AUDIT_SET_FEATURE: 1094 case AUDIT_LIST_RULES: 1095 case AUDIT_ADD_RULE: 1096 case AUDIT_DEL_RULE: 1097 case AUDIT_SIGNAL_INFO: 1098 case AUDIT_TTY_GET: 1099 case AUDIT_TTY_SET: 1100 case AUDIT_TRIM: 1101 case AUDIT_MAKE_EQUIV: 1102 /* Only support auditd and auditctl in initial pid namespace 1103 * for now. */ 1104 if (task_active_pid_ns(current) != &init_pid_ns) 1105 return -EPERM; 1106 1107 if (!netlink_capable(skb, CAP_AUDIT_CONTROL)) 1108 err = -EPERM; 1109 break; 1110 case AUDIT_USER: 1111 case AUDIT_FIRST_USER_MSG ... AUDIT_LAST_USER_MSG: 1112 case AUDIT_FIRST_USER_MSG2 ... AUDIT_LAST_USER_MSG2: 1113 if (!netlink_capable(skb, CAP_AUDIT_WRITE)) 1114 err = -EPERM; 1115 break; 1116 default: /* bad msg */ 1117 err = -EINVAL; 1118 } 1119 1120 return err; 1121 } 1122 1123 static void audit_log_common_recv_msg(struct audit_context *context, 1124 struct audit_buffer **ab, u16 msg_type) 1125 { 1126 uid_t uid = from_kuid(&init_user_ns, current_uid()); 1127 pid_t pid = task_tgid_nr(current); 1128 1129 if (!audit_enabled && msg_type != AUDIT_USER_AVC) { 1130 *ab = NULL; 1131 return; 1132 } 1133 1134 *ab = audit_log_start(context, GFP_KERNEL, msg_type); 1135 if (unlikely(!*ab)) 1136 return; 1137 audit_log_format(*ab, "pid=%d uid=%u ", pid, uid); 1138 audit_log_session_info(*ab); 1139 audit_log_task_context(*ab); 1140 } 1141 1142 static inline void audit_log_user_recv_msg(struct audit_buffer **ab, 1143 u16 msg_type) 1144 { 1145 audit_log_common_recv_msg(NULL, ab, msg_type); 1146 } 1147 1148 static int is_audit_feature_set(int i) 1149 { 1150 return af.features & AUDIT_FEATURE_TO_MASK(i); 1151 } 1152 1153 static int audit_get_feature(struct sk_buff *skb) 1154 { 1155 u32 seq; 1156 1157 seq = nlmsg_hdr(skb)->nlmsg_seq; 1158 1159 audit_send_reply(skb, seq, AUDIT_GET_FEATURE, 0, 0, &af, sizeof(af)); 1160 1161 return 0; 1162 } 1163 1164 static void audit_log_feature_change(int which, u32 old_feature, u32 new_feature, 1165 u32 old_lock, u32 new_lock, int res) 1166 { 1167 struct audit_buffer *ab; 1168 1169 if (audit_enabled == AUDIT_OFF) 1170 return; 1171 1172 ab = audit_log_start(audit_context(), GFP_KERNEL, AUDIT_FEATURE_CHANGE); 1173 if (!ab) 1174 return; 1175 audit_log_task_info(ab); 1176 audit_log_format(ab, " feature=%s old=%u new=%u old_lock=%u new_lock=%u res=%d", 1177 audit_feature_names[which], !!old_feature, !!new_feature, 1178 !!old_lock, !!new_lock, res); 1179 audit_log_end(ab); 1180 } 1181 1182 static int audit_set_feature(struct audit_features *uaf) 1183 { 1184 int i; 1185 1186 BUILD_BUG_ON(AUDIT_LAST_FEATURE + 1 > ARRAY_SIZE(audit_feature_names)); 1187 1188 /* if there is ever a version 2 we should handle that here */ 1189 1190 for (i = 0; i <= AUDIT_LAST_FEATURE; i++) { 1191 u32 feature = AUDIT_FEATURE_TO_MASK(i); 1192 u32 old_feature, new_feature, old_lock, new_lock; 1193 1194 /* if we are not changing this feature, move along */ 1195 if (!(feature & uaf->mask)) 1196 continue; 1197 1198 old_feature = af.features & feature; 1199 new_feature = uaf->features & feature; 1200 new_lock = (uaf->lock | af.lock) & feature; 1201 old_lock = af.lock & feature; 1202 1203 /* are we changing a locked feature? */ 1204 if (old_lock && (new_feature != old_feature)) { 1205 audit_log_feature_change(i, old_feature, new_feature, 1206 old_lock, new_lock, 0); 1207 return -EPERM; 1208 } 1209 } 1210 /* nothing invalid, do the changes */ 1211 for (i = 0; i <= AUDIT_LAST_FEATURE; i++) { 1212 u32 feature = AUDIT_FEATURE_TO_MASK(i); 1213 u32 old_feature, new_feature, old_lock, new_lock; 1214 1215 /* if we are not changing this feature, move along */ 1216 if (!(feature & uaf->mask)) 1217 continue; 1218 1219 old_feature = af.features & feature; 1220 new_feature = uaf->features & feature; 1221 old_lock = af.lock & feature; 1222 new_lock = (uaf->lock | af.lock) & feature; 1223 1224 if (new_feature != old_feature) 1225 audit_log_feature_change(i, old_feature, new_feature, 1226 old_lock, new_lock, 1); 1227 1228 if (new_feature) 1229 af.features |= feature; 1230 else 1231 af.features &= ~feature; 1232 af.lock |= new_lock; 1233 } 1234 1235 return 0; 1236 } 1237 1238 static int audit_replace(struct pid *pid) 1239 { 1240 pid_t pvnr; 1241 struct sk_buff *skb; 1242 1243 pvnr = pid_vnr(pid); 1244 skb = audit_make_reply(0, AUDIT_REPLACE, 0, 0, &pvnr, sizeof(pvnr)); 1245 if (!skb) 1246 return -ENOMEM; 1247 return auditd_send_unicast_skb(skb); 1248 } 1249 1250 static int audit_receive_msg(struct sk_buff *skb, struct nlmsghdr *nlh, 1251 bool *ack) 1252 { 1253 u32 seq; 1254 void *data; 1255 int data_len; 1256 int err; 1257 struct audit_buffer *ab; 1258 u16 msg_type = nlh->nlmsg_type; 1259 struct audit_sig_info *sig_data; 1260 struct lsm_context lsmctx = { NULL, 0, 0 }; 1261 1262 err = audit_netlink_ok(skb, msg_type); 1263 if (err) 1264 return err; 1265 1266 seq = nlh->nlmsg_seq; 1267 data = nlmsg_data(nlh); 1268 data_len = nlmsg_len(nlh); 1269 1270 switch (msg_type) { 1271 case AUDIT_GET: { 1272 struct audit_status s; 1273 memset(&s, 0, sizeof(s)); 1274 s.enabled = audit_enabled; 1275 s.failure = audit_failure; 1276 /* NOTE: use pid_vnr() so the PID is relative to the current 1277 * namespace */ 1278 s.pid = auditd_pid_vnr(); 1279 s.rate_limit = audit_rate_limit; 1280 s.backlog_limit = audit_backlog_limit; 1281 s.lost = atomic_read(&audit_lost); 1282 s.backlog = skb_queue_len(&audit_queue); 1283 s.feature_bitmap = AUDIT_FEATURE_BITMAP_ALL; 1284 s.backlog_wait_time = audit_backlog_wait_time; 1285 s.backlog_wait_time_actual = atomic_read(&audit_backlog_wait_time_actual); 1286 audit_send_reply(skb, seq, AUDIT_GET, 0, 0, &s, sizeof(s)); 1287 break; 1288 } 1289 case AUDIT_SET: { 1290 struct audit_status s; 1291 memset(&s, 0, sizeof(s)); 1292 /* guard against past and future API changes */ 1293 memcpy(&s, data, min_t(size_t, sizeof(s), data_len)); 1294 if (s.mask & AUDIT_STATUS_ENABLED) { 1295 err = audit_set_enabled(s.enabled); 1296 if (err < 0) 1297 return err; 1298 } 1299 if (s.mask & AUDIT_STATUS_FAILURE) { 1300 err = audit_set_failure(s.failure); 1301 if (err < 0) 1302 return err; 1303 } 1304 if (s.mask & AUDIT_STATUS_PID) { 1305 /* NOTE: we are using the vnr PID functions below 1306 * because the s.pid value is relative to the 1307 * namespace of the caller; at present this 1308 * doesn't matter much since you can really only 1309 * run auditd from the initial pid namespace, but 1310 * something to keep in mind if this changes */ 1311 pid_t new_pid = s.pid; 1312 pid_t auditd_pid; 1313 struct pid *req_pid = task_tgid(current); 1314 1315 /* Sanity check - PID values must match. Setting 1316 * pid to 0 is how auditd ends auditing. */ 1317 if (new_pid && (new_pid != pid_vnr(req_pid))) 1318 return -EINVAL; 1319 1320 /* test the auditd connection */ 1321 audit_replace(req_pid); 1322 1323 auditd_pid = auditd_pid_vnr(); 1324 if (auditd_pid) { 1325 /* replacing a healthy auditd is not allowed */ 1326 if (new_pid) { 1327 audit_log_config_change("audit_pid", 1328 new_pid, auditd_pid, 0); 1329 return -EEXIST; 1330 } 1331 /* only current auditd can unregister itself */ 1332 if (pid_vnr(req_pid) != auditd_pid) { 1333 audit_log_config_change("audit_pid", 1334 new_pid, auditd_pid, 0); 1335 return -EACCES; 1336 } 1337 } 1338 1339 if (new_pid) { 1340 /* register a new auditd connection */ 1341 err = auditd_set(req_pid, 1342 NETLINK_CB(skb).portid, 1343 sock_net(NETLINK_CB(skb).sk), 1344 skb, ack); 1345 if (audit_enabled != AUDIT_OFF) 1346 audit_log_config_change("audit_pid", 1347 new_pid, 1348 auditd_pid, 1349 err ? 0 : 1); 1350 if (err) 1351 return err; 1352 1353 /* try to process any backlog */ 1354 wake_up_interruptible(&kauditd_wait); 1355 } else { 1356 if (audit_enabled != AUDIT_OFF) 1357 audit_log_config_change("audit_pid", 1358 new_pid, 1359 auditd_pid, 1); 1360 1361 /* unregister the auditd connection */ 1362 auditd_reset(NULL); 1363 } 1364 } 1365 if (s.mask & AUDIT_STATUS_RATE_LIMIT) { 1366 err = audit_set_rate_limit(s.rate_limit); 1367 if (err < 0) 1368 return err; 1369 } 1370 if (s.mask & AUDIT_STATUS_BACKLOG_LIMIT) { 1371 err = audit_set_backlog_limit(s.backlog_limit); 1372 if (err < 0) 1373 return err; 1374 } 1375 if (s.mask & AUDIT_STATUS_BACKLOG_WAIT_TIME) { 1376 if (sizeof(s) > (size_t)nlh->nlmsg_len) 1377 return -EINVAL; 1378 if (s.backlog_wait_time > 10*AUDIT_BACKLOG_WAIT_TIME) 1379 return -EINVAL; 1380 err = audit_set_backlog_wait_time(s.backlog_wait_time); 1381 if (err < 0) 1382 return err; 1383 } 1384 if (s.mask == AUDIT_STATUS_LOST) { 1385 u32 lost = atomic_xchg(&audit_lost, 0); 1386 1387 audit_log_config_change("lost", 0, lost, 1); 1388 return lost; 1389 } 1390 if (s.mask == AUDIT_STATUS_BACKLOG_WAIT_TIME_ACTUAL) { 1391 u32 actual = atomic_xchg(&audit_backlog_wait_time_actual, 0); 1392 1393 audit_log_config_change("backlog_wait_time_actual", 0, actual, 1); 1394 return actual; 1395 } 1396 break; 1397 } 1398 case AUDIT_GET_FEATURE: 1399 err = audit_get_feature(skb); 1400 if (err) 1401 return err; 1402 break; 1403 case AUDIT_SET_FEATURE: 1404 if (data_len < sizeof(struct audit_features)) 1405 return -EINVAL; 1406 err = audit_set_feature(data); 1407 if (err) 1408 return err; 1409 break; 1410 case AUDIT_USER: 1411 case AUDIT_FIRST_USER_MSG ... AUDIT_LAST_USER_MSG: 1412 case AUDIT_FIRST_USER_MSG2 ... AUDIT_LAST_USER_MSG2: 1413 if (!audit_enabled && msg_type != AUDIT_USER_AVC) 1414 return 0; 1415 /* exit early if there isn't at least one character to print */ 1416 if (data_len < 2) 1417 return -EINVAL; 1418 1419 err = audit_filter(msg_type, AUDIT_FILTER_USER); 1420 if (err == 1) { /* match or error */ 1421 char *str = data; 1422 1423 err = 0; 1424 if (msg_type == AUDIT_USER_TTY) { 1425 err = tty_audit_push(); 1426 if (err) 1427 break; 1428 } 1429 audit_log_user_recv_msg(&ab, msg_type); 1430 if (msg_type != AUDIT_USER_TTY) { 1431 /* ensure NULL termination */ 1432 str[data_len - 1] = '\0'; 1433 audit_log_format(ab, " msg='%.*s'", 1434 AUDIT_MESSAGE_TEXT_MAX, 1435 str); 1436 } else { 1437 audit_log_format(ab, " data="); 1438 if (str[data_len - 1] == '\0') 1439 data_len--; 1440 audit_log_n_untrustedstring(ab, str, data_len); 1441 } 1442 audit_log_end(ab); 1443 } 1444 break; 1445 case AUDIT_ADD_RULE: 1446 case AUDIT_DEL_RULE: 1447 if (data_len < sizeof(struct audit_rule_data)) 1448 return -EINVAL; 1449 if (audit_enabled == AUDIT_LOCKED) { 1450 audit_log_common_recv_msg(audit_context(), &ab, 1451 AUDIT_CONFIG_CHANGE); 1452 audit_log_format(ab, " op=%s audit_enabled=%d res=0", 1453 msg_type == AUDIT_ADD_RULE ? 1454 "add_rule" : "remove_rule", 1455 audit_enabled); 1456 audit_log_end(ab); 1457 return -EPERM; 1458 } 1459 err = audit_rule_change(msg_type, seq, data, data_len); 1460 break; 1461 case AUDIT_LIST_RULES: 1462 err = audit_list_rules_send(skb, seq); 1463 break; 1464 case AUDIT_TRIM: 1465 audit_trim_trees(); 1466 audit_log_common_recv_msg(audit_context(), &ab, 1467 AUDIT_CONFIG_CHANGE); 1468 audit_log_format(ab, " op=trim res=1"); 1469 audit_log_end(ab); 1470 break; 1471 case AUDIT_MAKE_EQUIV: { 1472 void *bufp = data; 1473 u32 sizes[2]; 1474 size_t msglen = data_len; 1475 char *old, *new; 1476 1477 err = -EINVAL; 1478 if (msglen < 2 * sizeof(u32)) 1479 break; 1480 memcpy(sizes, bufp, 2 * sizeof(u32)); 1481 bufp += 2 * sizeof(u32); 1482 msglen -= 2 * sizeof(u32); 1483 old = audit_unpack_string(&bufp, &msglen, sizes[0]); 1484 if (IS_ERR(old)) { 1485 err = PTR_ERR(old); 1486 break; 1487 } 1488 new = audit_unpack_string(&bufp, &msglen, sizes[1]); 1489 if (IS_ERR(new)) { 1490 err = PTR_ERR(new); 1491 kfree(old); 1492 break; 1493 } 1494 /* OK, here comes... */ 1495 err = audit_tag_tree(old, new); 1496 1497 audit_log_common_recv_msg(audit_context(), &ab, 1498 AUDIT_CONFIG_CHANGE); 1499 audit_log_format(ab, " op=make_equiv old="); 1500 audit_log_untrustedstring(ab, old); 1501 audit_log_format(ab, " new="); 1502 audit_log_untrustedstring(ab, new); 1503 audit_log_format(ab, " res=%d", !err); 1504 audit_log_end(ab); 1505 kfree(old); 1506 kfree(new); 1507 break; 1508 } 1509 case AUDIT_SIGNAL_INFO: 1510 if (lsmprop_is_set(&audit_sig_lsm)) { 1511 err = security_lsmprop_to_secctx(&audit_sig_lsm, 1512 &lsmctx, LSM_ID_UNDEF); 1513 if (err < 0) 1514 return err; 1515 } 1516 sig_data = kmalloc(struct_size(sig_data, ctx, lsmctx.len), 1517 GFP_KERNEL); 1518 if (!sig_data) { 1519 if (lsmprop_is_set(&audit_sig_lsm)) 1520 security_release_secctx(&lsmctx); 1521 return -ENOMEM; 1522 } 1523 sig_data->uid = from_kuid(&init_user_ns, audit_sig_uid); 1524 sig_data->pid = audit_sig_pid; 1525 if (lsmprop_is_set(&audit_sig_lsm)) { 1526 memcpy(sig_data->ctx, lsmctx.context, lsmctx.len); 1527 security_release_secctx(&lsmctx); 1528 } 1529 audit_send_reply(skb, seq, AUDIT_SIGNAL_INFO, 0, 0, 1530 sig_data, struct_size(sig_data, ctx, 1531 lsmctx.len)); 1532 kfree(sig_data); 1533 break; 1534 case AUDIT_TTY_GET: { 1535 struct audit_tty_status s; 1536 unsigned int t; 1537 1538 t = READ_ONCE(current->signal->audit_tty); 1539 s.enabled = t & AUDIT_TTY_ENABLE; 1540 s.log_passwd = !!(t & AUDIT_TTY_LOG_PASSWD); 1541 1542 audit_send_reply(skb, seq, AUDIT_TTY_GET, 0, 0, &s, sizeof(s)); 1543 break; 1544 } 1545 case AUDIT_TTY_SET: { 1546 struct audit_tty_status s, old; 1547 struct audit_buffer *ab; 1548 unsigned int t; 1549 1550 memset(&s, 0, sizeof(s)); 1551 /* guard against past and future API changes */ 1552 memcpy(&s, data, min_t(size_t, sizeof(s), data_len)); 1553 /* check if new data is valid */ 1554 if ((s.enabled != 0 && s.enabled != 1) || 1555 (s.log_passwd != 0 && s.log_passwd != 1)) 1556 err = -EINVAL; 1557 1558 if (err) 1559 t = READ_ONCE(current->signal->audit_tty); 1560 else { 1561 t = s.enabled | (-s.log_passwd & AUDIT_TTY_LOG_PASSWD); 1562 t = xchg(¤t->signal->audit_tty, t); 1563 } 1564 old.enabled = t & AUDIT_TTY_ENABLE; 1565 old.log_passwd = !!(t & AUDIT_TTY_LOG_PASSWD); 1566 1567 audit_log_common_recv_msg(audit_context(), &ab, 1568 AUDIT_CONFIG_CHANGE); 1569 audit_log_format(ab, " op=tty_set old-enabled=%d new-enabled=%d" 1570 " old-log_passwd=%d new-log_passwd=%d res=%d", 1571 old.enabled, s.enabled, old.log_passwd, 1572 s.log_passwd, !err); 1573 audit_log_end(ab); 1574 break; 1575 } 1576 default: 1577 err = -EINVAL; 1578 break; 1579 } 1580 1581 return err < 0 ? err : 0; 1582 } 1583 1584 /** 1585 * audit_receive - receive messages from a netlink control socket 1586 * @skb: the message buffer 1587 * 1588 * Parse the provided skb and deal with any messages that may be present, 1589 * malformed skbs are discarded. 1590 */ 1591 static void audit_receive(struct sk_buff *skb) 1592 { 1593 struct nlmsghdr *nlh; 1594 bool ack; 1595 /* 1596 * len MUST be signed for nlmsg_next to be able to dec it below 0 1597 * if the nlmsg_len was not aligned 1598 */ 1599 int len; 1600 int err; 1601 1602 nlh = nlmsg_hdr(skb); 1603 len = skb->len; 1604 1605 audit_ctl_lock(); 1606 while (nlmsg_ok(nlh, len)) { 1607 ack = nlh->nlmsg_flags & NLM_F_ACK; 1608 err = audit_receive_msg(skb, nlh, &ack); 1609 1610 /* send an ack if the user asked for one and audit_receive_msg 1611 * didn't already do it, or if there was an error. */ 1612 if (ack || err) 1613 netlink_ack(skb, nlh, err, NULL); 1614 1615 nlh = nlmsg_next(nlh, &len); 1616 } 1617 audit_ctl_unlock(); 1618 1619 /* can't block with the ctrl lock, so penalize the sender now */ 1620 if (audit_backlog_limit && 1621 (skb_queue_len(&audit_queue) > audit_backlog_limit)) { 1622 DECLARE_WAITQUEUE(wait, current); 1623 1624 /* wake kauditd to try and flush the queue */ 1625 wake_up_interruptible(&kauditd_wait); 1626 1627 add_wait_queue_exclusive(&audit_backlog_wait, &wait); 1628 set_current_state(TASK_UNINTERRUPTIBLE); 1629 schedule_timeout(audit_backlog_wait_time); 1630 remove_wait_queue(&audit_backlog_wait, &wait); 1631 } 1632 } 1633 1634 /* Log information about who is connecting to the audit multicast socket */ 1635 static void audit_log_multicast(int group, const char *op, int err) 1636 { 1637 const struct cred *cred; 1638 struct tty_struct *tty; 1639 char comm[sizeof(current->comm)]; 1640 struct audit_buffer *ab; 1641 1642 if (!audit_enabled) 1643 return; 1644 1645 ab = audit_log_start(audit_context(), GFP_KERNEL, AUDIT_EVENT_LISTENER); 1646 if (!ab) 1647 return; 1648 1649 cred = current_cred(); 1650 tty = audit_get_tty(); 1651 audit_log_format(ab, "pid=%u uid=%u auid=%u tty=%s ses=%u", 1652 task_tgid_nr(current), 1653 from_kuid(&init_user_ns, cred->uid), 1654 from_kuid(&init_user_ns, audit_get_loginuid(current)), 1655 tty ? tty_name(tty) : "(none)", 1656 audit_get_sessionid(current)); 1657 audit_put_tty(tty); 1658 audit_log_task_context(ab); /* subj= */ 1659 audit_log_format(ab, " comm="); 1660 audit_log_untrustedstring(ab, get_task_comm(comm, current)); 1661 audit_log_d_path_exe(ab, current->mm); /* exe= */ 1662 audit_log_format(ab, " nl-mcgrp=%d op=%s res=%d", group, op, !err); 1663 audit_log_end(ab); 1664 } 1665 1666 /* Run custom bind function on netlink socket group connect or bind requests. */ 1667 static int audit_multicast_bind(struct net *net, int group) 1668 { 1669 int err = 0; 1670 1671 if (!capable(CAP_AUDIT_READ)) 1672 err = -EPERM; 1673 audit_log_multicast(group, "connect", err); 1674 return err; 1675 } 1676 1677 static void audit_multicast_unbind(struct net *net, int group) 1678 { 1679 audit_log_multicast(group, "disconnect", 0); 1680 } 1681 1682 static int __net_init audit_net_init(struct net *net) 1683 { 1684 struct netlink_kernel_cfg cfg = { 1685 .input = audit_receive, 1686 .bind = audit_multicast_bind, 1687 .unbind = audit_multicast_unbind, 1688 .flags = NL_CFG_F_NONROOT_RECV, 1689 .groups = AUDIT_NLGRP_MAX, 1690 }; 1691 1692 struct audit_net *aunet = net_generic(net, audit_net_id); 1693 1694 aunet->sk = netlink_kernel_create(net, NETLINK_AUDIT, &cfg); 1695 if (aunet->sk == NULL) { 1696 audit_panic("cannot initialize netlink socket in namespace"); 1697 return -ENOMEM; 1698 } 1699 /* limit the timeout in case auditd is blocked/stopped */ 1700 aunet->sk->sk_sndtimeo = HZ / 10; 1701 1702 return 0; 1703 } 1704 1705 static void __net_exit audit_net_exit(struct net *net) 1706 { 1707 struct audit_net *aunet = net_generic(net, audit_net_id); 1708 1709 /* NOTE: you would think that we would want to check the auditd 1710 * connection and potentially reset it here if it lives in this 1711 * namespace, but since the auditd connection tracking struct holds a 1712 * reference to this namespace (see auditd_set()) we are only ever 1713 * going to get here after that connection has been released */ 1714 1715 netlink_kernel_release(aunet->sk); 1716 } 1717 1718 static struct pernet_operations audit_net_ops __net_initdata = { 1719 .init = audit_net_init, 1720 .exit = audit_net_exit, 1721 .id = &audit_net_id, 1722 .size = sizeof(struct audit_net), 1723 }; 1724 1725 /* Initialize audit support at boot time. */ 1726 static int __init audit_init(void) 1727 { 1728 int i; 1729 1730 if (audit_initialized == AUDIT_DISABLED) 1731 return 0; 1732 1733 audit_buffer_cache = KMEM_CACHE(audit_buffer, SLAB_PANIC); 1734 1735 skb_queue_head_init(&audit_queue); 1736 skb_queue_head_init(&audit_retry_queue); 1737 skb_queue_head_init(&audit_hold_queue); 1738 1739 for (i = 0; i < AUDIT_INODE_BUCKETS; i++) 1740 INIT_LIST_HEAD(&audit_inode_hash[i]); 1741 1742 mutex_init(&audit_cmd_mutex.lock); 1743 audit_cmd_mutex.owner = NULL; 1744 1745 pr_info("initializing netlink subsys (%s)\n", 1746 str_enabled_disabled(audit_default)); 1747 register_pernet_subsys(&audit_net_ops); 1748 1749 audit_initialized = AUDIT_INITIALIZED; 1750 1751 kauditd_task = kthread_run(kauditd_thread, NULL, "kauditd"); 1752 if (IS_ERR(kauditd_task)) { 1753 int err = PTR_ERR(kauditd_task); 1754 panic("audit: failed to start the kauditd thread (%d)\n", err); 1755 } 1756 1757 audit_log(NULL, GFP_KERNEL, AUDIT_KERNEL, 1758 "state=initialized audit_enabled=%u res=1", 1759 audit_enabled); 1760 1761 return 0; 1762 } 1763 postcore_initcall(audit_init); 1764 1765 /* 1766 * Process kernel command-line parameter at boot time. 1767 * audit={0|off} or audit={1|on}. 1768 */ 1769 static int __init audit_enable(char *str) 1770 { 1771 if (!strcasecmp(str, "off") || !strcmp(str, "0")) 1772 audit_default = AUDIT_OFF; 1773 else if (!strcasecmp(str, "on") || !strcmp(str, "1")) 1774 audit_default = AUDIT_ON; 1775 else { 1776 pr_err("audit: invalid 'audit' parameter value (%s)\n", str); 1777 audit_default = AUDIT_ON; 1778 } 1779 1780 if (audit_default == AUDIT_OFF) 1781 audit_initialized = AUDIT_DISABLED; 1782 if (audit_set_enabled(audit_default)) 1783 pr_err("audit: error setting audit state (%d)\n", 1784 audit_default); 1785 1786 pr_info("%s\n", audit_default ? 1787 "enabled (after initialization)" : "disabled (until reboot)"); 1788 1789 return 1; 1790 } 1791 __setup("audit=", audit_enable); 1792 1793 /* Process kernel command-line parameter at boot time. 1794 * audit_backlog_limit=<n> */ 1795 static int __init audit_backlog_limit_set(char *str) 1796 { 1797 u32 audit_backlog_limit_arg; 1798 1799 pr_info("audit_backlog_limit: "); 1800 if (kstrtouint(str, 0, &audit_backlog_limit_arg)) { 1801 pr_cont("using default of %u, unable to parse %s\n", 1802 audit_backlog_limit, str); 1803 return 1; 1804 } 1805 1806 audit_backlog_limit = audit_backlog_limit_arg; 1807 pr_cont("%d\n", audit_backlog_limit); 1808 1809 return 1; 1810 } 1811 __setup("audit_backlog_limit=", audit_backlog_limit_set); 1812 1813 static void audit_buffer_free(struct audit_buffer *ab) 1814 { 1815 struct sk_buff *skb; 1816 1817 if (!ab) 1818 return; 1819 1820 while ((skb = skb_dequeue(&ab->skb_list))) 1821 kfree_skb(skb); 1822 kmem_cache_free(audit_buffer_cache, ab); 1823 } 1824 1825 static struct audit_buffer *audit_buffer_alloc(struct audit_context *ctx, 1826 gfp_t gfp_mask, int type) 1827 { 1828 struct audit_buffer *ab; 1829 1830 ab = kmem_cache_alloc(audit_buffer_cache, gfp_mask); 1831 if (!ab) 1832 return NULL; 1833 1834 skb_queue_head_init(&ab->skb_list); 1835 1836 ab->skb = nlmsg_new(AUDIT_BUFSIZ, gfp_mask); 1837 if (!ab->skb) 1838 goto err; 1839 1840 skb_queue_tail(&ab->skb_list, ab->skb); 1841 1842 if (!nlmsg_put(ab->skb, 0, 0, type, 0, 0)) 1843 goto err; 1844 1845 ab->ctx = ctx; 1846 ab->gfp_mask = gfp_mask; 1847 1848 return ab; 1849 1850 err: 1851 audit_buffer_free(ab); 1852 return NULL; 1853 } 1854 1855 /** 1856 * audit_serial - compute a serial number for the audit record 1857 * 1858 * Compute a serial number for the audit record. Audit records are 1859 * written to user-space as soon as they are generated, so a complete 1860 * audit record may be written in several pieces. The timestamp of the 1861 * record and this serial number are used by the user-space tools to 1862 * determine which pieces belong to the same audit record. The 1863 * (timestamp,serial) tuple is unique for each syscall and is live from 1864 * syscall entry to syscall exit. 1865 * 1866 * NOTE: Another possibility is to store the formatted records off the 1867 * audit context (for those records that have a context), and emit them 1868 * all at syscall exit. However, this could delay the reporting of 1869 * significant errors until syscall exit (or never, if the system 1870 * halts). 1871 */ 1872 unsigned int audit_serial(void) 1873 { 1874 static atomic_t serial = ATOMIC_INIT(0); 1875 1876 return atomic_inc_return(&serial); 1877 } 1878 1879 static inline void audit_get_stamp(struct audit_context *ctx, 1880 struct audit_stamp *stamp) 1881 { 1882 if (!ctx || !auditsc_get_stamp(ctx, stamp)) { 1883 ktime_get_coarse_real_ts64(&stamp->ctime); 1884 stamp->serial = audit_serial(); 1885 } 1886 } 1887 1888 /** 1889 * audit_log_start - obtain an audit buffer 1890 * @ctx: audit_context (may be NULL) 1891 * @gfp_mask: type of allocation 1892 * @type: audit message type 1893 * 1894 * Returns audit_buffer pointer on success or NULL on error. 1895 * 1896 * Obtain an audit buffer. This routine does locking to obtain the 1897 * audit buffer, but then no locking is required for calls to 1898 * audit_log_*format. If the task (ctx) is a task that is currently in a 1899 * syscall, then the syscall is marked as auditable and an audit record 1900 * will be written at syscall exit. If there is no associated task, then 1901 * task context (ctx) should be NULL. 1902 */ 1903 struct audit_buffer *audit_log_start(struct audit_context *ctx, gfp_t gfp_mask, 1904 int type) 1905 { 1906 struct audit_buffer *ab; 1907 1908 if (audit_initialized != AUDIT_INITIALIZED) 1909 return NULL; 1910 1911 if (unlikely(!audit_filter(type, AUDIT_FILTER_EXCLUDE))) 1912 return NULL; 1913 1914 /* NOTE: don't ever fail/sleep on these two conditions: 1915 * 1. auditd generated record - since we need auditd to drain the 1916 * queue; also, when we are checking for auditd, compare PIDs using 1917 * task_tgid_vnr() since auditd_pid is set in audit_receive_msg() 1918 * using a PID anchored in the caller's namespace 1919 * 2. generator holding the audit_cmd_mutex - we don't want to block 1920 * while holding the mutex, although we do penalize the sender 1921 * later in audit_receive() when it is safe to block 1922 */ 1923 if (!(auditd_test_task(current) || audit_ctl_owner_current())) { 1924 long stime = audit_backlog_wait_time; 1925 1926 while (audit_backlog_limit && 1927 (skb_queue_len(&audit_queue) > audit_backlog_limit)) { 1928 /* wake kauditd to try and flush the queue */ 1929 wake_up_interruptible(&kauditd_wait); 1930 1931 /* sleep if we are allowed and we haven't exhausted our 1932 * backlog wait limit */ 1933 if (gfpflags_allow_blocking(gfp_mask) && (stime > 0)) { 1934 long rtime = stime; 1935 1936 DECLARE_WAITQUEUE(wait, current); 1937 1938 add_wait_queue_exclusive(&audit_backlog_wait, 1939 &wait); 1940 set_current_state(TASK_UNINTERRUPTIBLE); 1941 stime = schedule_timeout(rtime); 1942 atomic_add(rtime - stime, &audit_backlog_wait_time_actual); 1943 remove_wait_queue(&audit_backlog_wait, &wait); 1944 } else { 1945 if (audit_rate_check() && printk_ratelimit()) 1946 pr_warn("audit_backlog=%d > audit_backlog_limit=%d\n", 1947 skb_queue_len(&audit_queue), 1948 audit_backlog_limit); 1949 audit_log_lost("backlog limit exceeded"); 1950 return NULL; 1951 } 1952 } 1953 } 1954 1955 ab = audit_buffer_alloc(ctx, gfp_mask, type); 1956 if (!ab) { 1957 audit_log_lost("out of memory in audit_log_start"); 1958 return NULL; 1959 } 1960 1961 audit_get_stamp(ab->ctx, &ab->stamp); 1962 /* cancel dummy context to enable supporting records */ 1963 if (ctx) 1964 ctx->dummy = 0; 1965 audit_log_format(ab, "audit(%llu.%03lu:%u): ", 1966 (unsigned long long)ab->stamp.ctime.tv_sec, 1967 ab->stamp.ctime.tv_nsec/1000000, 1968 ab->stamp.serial); 1969 1970 return ab; 1971 } 1972 1973 /** 1974 * audit_expand - expand skb in the audit buffer 1975 * @ab: audit_buffer 1976 * @extra: space to add at tail of the skb 1977 * 1978 * Returns 0 (no space) on failed expansion, or available space if 1979 * successful. 1980 */ 1981 static inline int audit_expand(struct audit_buffer *ab, int extra) 1982 { 1983 struct sk_buff *skb = ab->skb; 1984 int oldtail = skb_tailroom(skb); 1985 int ret = pskb_expand_head(skb, 0, extra, ab->gfp_mask); 1986 int newtail = skb_tailroom(skb); 1987 1988 if (ret < 0) { 1989 audit_log_lost("out of memory in audit_expand"); 1990 return 0; 1991 } 1992 1993 skb->truesize += newtail - oldtail; 1994 return newtail; 1995 } 1996 1997 /* 1998 * Format an audit message into the audit buffer. If there isn't enough 1999 * room in the audit buffer, more room will be allocated and vsnprint 2000 * will be called a second time. Currently, we assume that a printk 2001 * can't format message larger than 1024 bytes, so we don't either. 2002 */ 2003 static __printf(2, 0) 2004 void audit_log_vformat(struct audit_buffer *ab, const char *fmt, va_list args) 2005 { 2006 int len, avail; 2007 struct sk_buff *skb; 2008 va_list args2; 2009 2010 if (!ab) 2011 return; 2012 2013 BUG_ON(!ab->skb); 2014 skb = ab->skb; 2015 avail = skb_tailroom(skb); 2016 if (avail == 0) { 2017 avail = audit_expand(ab, AUDIT_BUFSIZ); 2018 if (!avail) 2019 goto out; 2020 } 2021 va_copy(args2, args); 2022 len = vsnprintf(skb_tail_pointer(skb), avail, fmt, args); 2023 if (len >= avail) { 2024 /* The printk buffer is 1024 bytes long, so if we get 2025 * here and AUDIT_BUFSIZ is at least 1024, then we can 2026 * log everything that printk could have logged. */ 2027 avail = audit_expand(ab, 2028 max_t(unsigned, AUDIT_BUFSIZ, 1+len-avail)); 2029 if (!avail) 2030 goto out_va_end; 2031 len = vsnprintf(skb_tail_pointer(skb), avail, fmt, args2); 2032 } 2033 if (len > 0) 2034 skb_put(skb, len); 2035 out_va_end: 2036 va_end(args2); 2037 out: 2038 return; 2039 } 2040 2041 /** 2042 * audit_log_format - format a message into the audit buffer. 2043 * @ab: audit_buffer 2044 * @fmt: format string 2045 * @...: optional parameters matching @fmt string 2046 * 2047 * All the work is done in audit_log_vformat. 2048 */ 2049 void audit_log_format(struct audit_buffer *ab, const char *fmt, ...) 2050 { 2051 va_list args; 2052 2053 if (!ab) 2054 return; 2055 va_start(args, fmt); 2056 audit_log_vformat(ab, fmt, args); 2057 va_end(args); 2058 } 2059 2060 /** 2061 * audit_log_n_hex - convert a buffer to hex and append it to the audit skb 2062 * @ab: the audit_buffer 2063 * @buf: buffer to convert to hex 2064 * @len: length of @buf to be converted 2065 * 2066 * No return value; failure to expand is silently ignored. 2067 * 2068 * This function will take the passed buf and convert it into a string of 2069 * ascii hex digits. The new string is placed onto the skb. 2070 */ 2071 void audit_log_n_hex(struct audit_buffer *ab, const unsigned char *buf, 2072 size_t len) 2073 { 2074 int i, avail, new_len; 2075 unsigned char *ptr; 2076 struct sk_buff *skb; 2077 2078 if (!ab) 2079 return; 2080 2081 BUG_ON(!ab->skb); 2082 skb = ab->skb; 2083 avail = skb_tailroom(skb); 2084 new_len = len<<1; 2085 if (new_len >= avail) { 2086 /* Round the buffer request up to the next multiple */ 2087 new_len = AUDIT_BUFSIZ*(((new_len-avail)/AUDIT_BUFSIZ) + 1); 2088 avail = audit_expand(ab, new_len); 2089 if (!avail) 2090 return; 2091 } 2092 2093 ptr = skb_tail_pointer(skb); 2094 for (i = 0; i < len; i++) 2095 ptr = hex_byte_pack_upper(ptr, buf[i]); 2096 *ptr = 0; 2097 skb_put(skb, len << 1); /* new string is twice the old string */ 2098 } 2099 2100 /* 2101 * Format a string of no more than slen characters into the audit buffer, 2102 * enclosed in quote marks. 2103 */ 2104 void audit_log_n_string(struct audit_buffer *ab, const char *string, 2105 size_t slen) 2106 { 2107 int avail, new_len; 2108 unsigned char *ptr; 2109 struct sk_buff *skb; 2110 2111 if (!ab) 2112 return; 2113 2114 BUG_ON(!ab->skb); 2115 skb = ab->skb; 2116 avail = skb_tailroom(skb); 2117 new_len = slen + 3; /* enclosing quotes + null terminator */ 2118 if (new_len > avail) { 2119 avail = audit_expand(ab, new_len); 2120 if (!avail) 2121 return; 2122 } 2123 ptr = skb_tail_pointer(skb); 2124 *ptr++ = '"'; 2125 memcpy(ptr, string, slen); 2126 ptr += slen; 2127 *ptr++ = '"'; 2128 *ptr = 0; 2129 skb_put(skb, slen + 2); /* don't include null terminator */ 2130 } 2131 2132 /** 2133 * audit_string_contains_control - does a string need to be logged in hex 2134 * @string: string to be checked 2135 * @len: max length of the string to check 2136 */ 2137 bool audit_string_contains_control(const char *string, size_t len) 2138 { 2139 const unsigned char *p; 2140 for (p = string; p < (const unsigned char *)string + len; p++) { 2141 if (*p == '"' || *p < 0x21 || *p > 0x7e) 2142 return true; 2143 } 2144 return false; 2145 } 2146 2147 /** 2148 * audit_log_n_untrustedstring - log a string that may contain random characters 2149 * @ab: audit_buffer 2150 * @string: string to be logged 2151 * @len: length of string (not including trailing null) 2152 * 2153 * This code will escape a string that is passed to it if the string 2154 * contains a control character, unprintable character, double quote mark, 2155 * or a space. Unescaped strings will start and end with a double quote mark. 2156 * Strings that are escaped are printed in hex (2 digits per char). 2157 * 2158 * The caller specifies the number of characters in the string to log, which may 2159 * or may not be the entire string. 2160 */ 2161 void audit_log_n_untrustedstring(struct audit_buffer *ab, const char *string, 2162 size_t len) 2163 { 2164 if (audit_string_contains_control(string, len)) 2165 audit_log_n_hex(ab, string, len); 2166 else 2167 audit_log_n_string(ab, string, len); 2168 } 2169 2170 /** 2171 * audit_log_untrustedstring - log a string that may contain random characters 2172 * @ab: audit_buffer 2173 * @string: string to be logged 2174 * 2175 * Same as audit_log_n_untrustedstring(), except that strlen is used to 2176 * determine string length. 2177 */ 2178 void audit_log_untrustedstring(struct audit_buffer *ab, const char *string) 2179 { 2180 audit_log_n_untrustedstring(ab, string, strlen(string)); 2181 } 2182 2183 /* This is a helper-function to print the escaped d_path */ 2184 void audit_log_d_path(struct audit_buffer *ab, const char *prefix, 2185 const struct path *path) 2186 { 2187 char *p, *pathname; 2188 2189 if (prefix) 2190 audit_log_format(ab, "%s", prefix); 2191 2192 /* We will allow 11 spaces for ' (deleted)' to be appended */ 2193 pathname = kmalloc(PATH_MAX+11, ab->gfp_mask); 2194 if (!pathname) { 2195 audit_log_format(ab, "\"<no_memory>\""); 2196 return; 2197 } 2198 p = d_path(path, pathname, PATH_MAX+11); 2199 if (IS_ERR(p)) { /* Should never happen since we send PATH_MAX */ 2200 /* FIXME: can we save some information here? */ 2201 audit_log_format(ab, "\"<too_long>\""); 2202 } else 2203 audit_log_untrustedstring(ab, p); 2204 kfree(pathname); 2205 } 2206 2207 void audit_log_session_info(struct audit_buffer *ab) 2208 { 2209 unsigned int sessionid = audit_get_sessionid(current); 2210 uid_t auid = from_kuid(&init_user_ns, audit_get_loginuid(current)); 2211 2212 audit_log_format(ab, "auid=%u ses=%u", auid, sessionid); 2213 } 2214 2215 void audit_log_key(struct audit_buffer *ab, char *key) 2216 { 2217 audit_log_format(ab, " key="); 2218 if (key) 2219 audit_log_untrustedstring(ab, key); 2220 else 2221 audit_log_format(ab, "(null)"); 2222 } 2223 2224 /** 2225 * audit_buffer_aux_new - Add an aux record buffer to the skb list 2226 * @ab: audit_buffer 2227 * @type: message type 2228 * 2229 * Aux records are allocated and added to the skb list of 2230 * the "main" record. The ab->skb is reset to point to the 2231 * aux record on its creation. When the aux record in complete 2232 * ab->skb has to be reset to point to the "main" record. 2233 * This allows the audit_log_ functions to be ignorant of 2234 * which kind of record it is logging to. It also avoids adding 2235 * special data for aux records. 2236 * 2237 * On success ab->skb will point to the new aux record. 2238 * Returns 0 on success, -ENOMEM should allocation fail. 2239 */ 2240 static int audit_buffer_aux_new(struct audit_buffer *ab, int type) 2241 { 2242 WARN_ON(ab->skb != skb_peek(&ab->skb_list)); 2243 2244 ab->skb = nlmsg_new(AUDIT_BUFSIZ, ab->gfp_mask); 2245 if (!ab->skb) 2246 goto err; 2247 if (!nlmsg_put(ab->skb, 0, 0, type, 0, 0)) 2248 goto err; 2249 skb_queue_tail(&ab->skb_list, ab->skb); 2250 2251 audit_log_format(ab, "audit(%llu.%03lu:%u): ", 2252 (unsigned long long)ab->stamp.ctime.tv_sec, 2253 ab->stamp.ctime.tv_nsec/1000000, 2254 ab->stamp.serial); 2255 2256 return 0; 2257 2258 err: 2259 kfree_skb(ab->skb); 2260 ab->skb = skb_peek(&ab->skb_list); 2261 return -ENOMEM; 2262 } 2263 2264 /** 2265 * audit_buffer_aux_end - Switch back to the "main" record from an aux record 2266 * @ab: audit_buffer 2267 * 2268 * Restores the "main" audit record to ab->skb. 2269 */ 2270 static void audit_buffer_aux_end(struct audit_buffer *ab) 2271 { 2272 ab->skb = skb_peek(&ab->skb_list); 2273 } 2274 2275 /** 2276 * audit_log_subj_ctx - Add LSM subject information 2277 * @ab: audit_buffer 2278 * @prop: LSM subject properties. 2279 * 2280 * Add a subj= field and, if necessary, a AUDIT_MAC_TASK_CONTEXTS record. 2281 */ 2282 int audit_log_subj_ctx(struct audit_buffer *ab, struct lsm_prop *prop) 2283 { 2284 struct lsm_context ctx; 2285 char *space = ""; 2286 int error; 2287 int i; 2288 2289 security_current_getlsmprop_subj(prop); 2290 if (!lsmprop_is_set(prop)) 2291 return 0; 2292 2293 if (audit_subj_secctx_cnt < 2) { 2294 error = security_lsmprop_to_secctx(prop, &ctx, LSM_ID_UNDEF); 2295 if (error < 0) { 2296 if (error != -EINVAL) 2297 goto error_path; 2298 return 0; 2299 } 2300 audit_log_format(ab, " subj=%s", ctx.context); 2301 security_release_secctx(&ctx); 2302 return 0; 2303 } 2304 /* Multiple LSMs provide contexts. Include an aux record. */ 2305 audit_log_format(ab, " subj=?"); 2306 error = audit_buffer_aux_new(ab, AUDIT_MAC_TASK_CONTEXTS); 2307 if (error) 2308 goto error_path; 2309 2310 for (i = 0; i < audit_subj_secctx_cnt; i++) { 2311 error = security_lsmprop_to_secctx(prop, &ctx, 2312 audit_subj_lsms[i]->id); 2313 if (error < 0) { 2314 /* 2315 * Don't print anything. An LSM like BPF could 2316 * claim to support contexts, but only do so under 2317 * certain conditions. 2318 */ 2319 if (error == -EOPNOTSUPP) 2320 continue; 2321 if (error != -EINVAL) 2322 audit_panic("error in audit_log_subj_ctx"); 2323 } else { 2324 audit_log_format(ab, "%ssubj_%s=%s", space, 2325 audit_subj_lsms[i]->name, ctx.context); 2326 space = " "; 2327 security_release_secctx(&ctx); 2328 } 2329 } 2330 audit_buffer_aux_end(ab); 2331 return 0; 2332 2333 error_path: 2334 audit_panic("error in audit_log_subj_ctx"); 2335 return error; 2336 } 2337 EXPORT_SYMBOL(audit_log_subj_ctx); 2338 2339 int audit_log_task_context(struct audit_buffer *ab) 2340 { 2341 struct lsm_prop prop; 2342 2343 security_current_getlsmprop_subj(&prop); 2344 return audit_log_subj_ctx(ab, &prop); 2345 } 2346 EXPORT_SYMBOL(audit_log_task_context); 2347 2348 int audit_log_obj_ctx(struct audit_buffer *ab, struct lsm_prop *prop) 2349 { 2350 int i; 2351 int rc; 2352 int error = 0; 2353 char *space = ""; 2354 struct lsm_context ctx; 2355 2356 if (audit_obj_secctx_cnt < 2) { 2357 error = security_lsmprop_to_secctx(prop, &ctx, LSM_ID_UNDEF); 2358 if (error < 0) { 2359 if (error != -EINVAL) 2360 goto error_path; 2361 return error; 2362 } 2363 audit_log_format(ab, " obj=%s", ctx.context); 2364 security_release_secctx(&ctx); 2365 return 0; 2366 } 2367 audit_log_format(ab, " obj=?"); 2368 error = audit_buffer_aux_new(ab, AUDIT_MAC_OBJ_CONTEXTS); 2369 if (error) 2370 goto error_path; 2371 2372 for (i = 0; i < audit_obj_secctx_cnt; i++) { 2373 rc = security_lsmprop_to_secctx(prop, &ctx, 2374 audit_obj_lsms[i]->id); 2375 if (rc < 0) { 2376 audit_log_format(ab, "%sobj_%s=?", space, 2377 audit_obj_lsms[i]->name); 2378 if (rc != -EINVAL) 2379 audit_panic("error in audit_log_obj_ctx"); 2380 error = rc; 2381 } else { 2382 audit_log_format(ab, "%sobj_%s=%s", space, 2383 audit_obj_lsms[i]->name, ctx.context); 2384 security_release_secctx(&ctx); 2385 } 2386 space = " "; 2387 } 2388 2389 audit_buffer_aux_end(ab); 2390 return error; 2391 2392 error_path: 2393 audit_panic("error in audit_log_obj_ctx"); 2394 return error; 2395 } 2396 2397 void audit_log_d_path_exe(struct audit_buffer *ab, 2398 struct mm_struct *mm) 2399 { 2400 struct file *exe_file; 2401 2402 if (!mm) 2403 goto out_null; 2404 2405 exe_file = get_mm_exe_file(mm); 2406 if (!exe_file) 2407 goto out_null; 2408 2409 audit_log_d_path(ab, " exe=", &exe_file->f_path); 2410 fput(exe_file); 2411 return; 2412 out_null: 2413 audit_log_format(ab, " exe=(null)"); 2414 } 2415 2416 struct tty_struct *audit_get_tty(void) 2417 { 2418 struct tty_struct *tty = NULL; 2419 unsigned long flags; 2420 2421 spin_lock_irqsave(¤t->sighand->siglock, flags); 2422 if (current->signal) 2423 tty = tty_kref_get(current->signal->tty); 2424 spin_unlock_irqrestore(¤t->sighand->siglock, flags); 2425 return tty; 2426 } 2427 2428 void audit_put_tty(struct tty_struct *tty) 2429 { 2430 tty_kref_put(tty); 2431 } 2432 2433 void audit_log_task_info(struct audit_buffer *ab) 2434 { 2435 const struct cred *cred; 2436 char comm[sizeof(current->comm)]; 2437 struct tty_struct *tty; 2438 2439 if (!ab) 2440 return; 2441 2442 cred = current_cred(); 2443 tty = audit_get_tty(); 2444 audit_log_format(ab, 2445 " ppid=%d pid=%d auid=%u uid=%u gid=%u" 2446 " euid=%u suid=%u fsuid=%u" 2447 " egid=%u sgid=%u fsgid=%u tty=%s ses=%u", 2448 task_ppid_nr(current), 2449 task_tgid_nr(current), 2450 from_kuid(&init_user_ns, audit_get_loginuid(current)), 2451 from_kuid(&init_user_ns, cred->uid), 2452 from_kgid(&init_user_ns, cred->gid), 2453 from_kuid(&init_user_ns, cred->euid), 2454 from_kuid(&init_user_ns, cred->suid), 2455 from_kuid(&init_user_ns, cred->fsuid), 2456 from_kgid(&init_user_ns, cred->egid), 2457 from_kgid(&init_user_ns, cred->sgid), 2458 from_kgid(&init_user_ns, cred->fsgid), 2459 tty ? tty_name(tty) : "(none)", 2460 audit_get_sessionid(current)); 2461 audit_put_tty(tty); 2462 audit_log_format(ab, " comm="); 2463 audit_log_untrustedstring(ab, get_task_comm(comm, current)); 2464 audit_log_d_path_exe(ab, current->mm); 2465 audit_log_task_context(ab); 2466 } 2467 EXPORT_SYMBOL(audit_log_task_info); 2468 2469 /** 2470 * audit_log_path_denied - report a path restriction denial 2471 * @type: audit message type (AUDIT_ANOM_LINK, AUDIT_ANOM_CREAT, etc) 2472 * @operation: specific operation name 2473 */ 2474 void audit_log_path_denied(int type, const char *operation) 2475 { 2476 struct audit_buffer *ab; 2477 2478 if (!audit_enabled) 2479 return; 2480 2481 /* Generate log with subject, operation, outcome. */ 2482 ab = audit_log_start(audit_context(), GFP_KERNEL, type); 2483 if (!ab) 2484 return; 2485 audit_log_format(ab, "op=%s", operation); 2486 audit_log_task_info(ab); 2487 audit_log_format(ab, " res=0"); 2488 audit_log_end(ab); 2489 } 2490 2491 /* global counter which is incremented every time something logs in */ 2492 static atomic_t session_id = ATOMIC_INIT(0); 2493 2494 static int audit_set_loginuid_perm(kuid_t loginuid) 2495 { 2496 /* if we are unset, we don't need privs */ 2497 if (!audit_loginuid_set(current)) 2498 return 0; 2499 /* if AUDIT_FEATURE_LOGINUID_IMMUTABLE means never ever allow a change*/ 2500 if (is_audit_feature_set(AUDIT_FEATURE_LOGINUID_IMMUTABLE)) 2501 return -EPERM; 2502 /* it is set, you need permission */ 2503 if (!capable(CAP_AUDIT_CONTROL)) 2504 return -EPERM; 2505 /* reject if this is not an unset and we don't allow that */ 2506 if (is_audit_feature_set(AUDIT_FEATURE_ONLY_UNSET_LOGINUID) 2507 && uid_valid(loginuid)) 2508 return -EPERM; 2509 return 0; 2510 } 2511 2512 static void audit_log_set_loginuid(kuid_t koldloginuid, kuid_t kloginuid, 2513 unsigned int oldsessionid, 2514 unsigned int sessionid, int rc) 2515 { 2516 struct audit_buffer *ab; 2517 uid_t uid, oldloginuid, loginuid; 2518 struct tty_struct *tty; 2519 2520 if (!audit_enabled) 2521 return; 2522 2523 ab = audit_log_start(audit_context(), GFP_KERNEL, AUDIT_LOGIN); 2524 if (!ab) 2525 return; 2526 2527 uid = from_kuid(&init_user_ns, task_uid(current)); 2528 oldloginuid = from_kuid(&init_user_ns, koldloginuid); 2529 loginuid = from_kuid(&init_user_ns, kloginuid); 2530 tty = audit_get_tty(); 2531 2532 audit_log_format(ab, "pid=%d uid=%u", task_tgid_nr(current), uid); 2533 audit_log_task_context(ab); 2534 audit_log_format(ab, " old-auid=%u auid=%u tty=%s old-ses=%u ses=%u res=%d", 2535 oldloginuid, loginuid, tty ? tty_name(tty) : "(none)", 2536 oldsessionid, sessionid, !rc); 2537 audit_put_tty(tty); 2538 audit_log_end(ab); 2539 } 2540 2541 /** 2542 * audit_set_loginuid - set current task's loginuid 2543 * @loginuid: loginuid value 2544 * 2545 * Returns 0. 2546 * 2547 * Called (set) from fs/proc/base.c::proc_loginuid_write(). 2548 */ 2549 int audit_set_loginuid(kuid_t loginuid) 2550 { 2551 unsigned int oldsessionid, sessionid = AUDIT_SID_UNSET; 2552 kuid_t oldloginuid; 2553 int rc; 2554 2555 oldloginuid = audit_get_loginuid(current); 2556 oldsessionid = audit_get_sessionid(current); 2557 2558 rc = audit_set_loginuid_perm(loginuid); 2559 if (rc) 2560 goto out; 2561 2562 /* are we setting or clearing? */ 2563 if (uid_valid(loginuid)) { 2564 sessionid = (unsigned int)atomic_inc_return(&session_id); 2565 if (unlikely(sessionid == AUDIT_SID_UNSET)) 2566 sessionid = (unsigned int)atomic_inc_return(&session_id); 2567 } 2568 2569 current->sessionid = sessionid; 2570 current->loginuid = loginuid; 2571 out: 2572 audit_log_set_loginuid(oldloginuid, loginuid, oldsessionid, sessionid, rc); 2573 return rc; 2574 } 2575 2576 /** 2577 * audit_signal_info - record signal info for shutting down audit subsystem 2578 * @sig: signal value 2579 * @t: task being signaled 2580 * 2581 * If the audit subsystem is being terminated, record the task (pid) 2582 * and uid that is doing that. 2583 */ 2584 int audit_signal_info(int sig, struct task_struct *t) 2585 { 2586 kuid_t uid = current_uid(), auid; 2587 2588 if (auditd_test_task(t) && 2589 (sig == SIGTERM || sig == SIGHUP || 2590 sig == SIGUSR1 || sig == SIGUSR2)) { 2591 audit_sig_pid = task_tgid_nr(current); 2592 auid = audit_get_loginuid(current); 2593 if (uid_valid(auid)) 2594 audit_sig_uid = auid; 2595 else 2596 audit_sig_uid = uid; 2597 security_current_getlsmprop_subj(&audit_sig_lsm); 2598 } 2599 2600 return audit_signal_info_syscall(t); 2601 } 2602 2603 /** 2604 * __audit_log_end - enqueue one audit record 2605 * @skb: the buffer to send 2606 */ 2607 static void __audit_log_end(struct sk_buff *skb) 2608 { 2609 struct nlmsghdr *nlh; 2610 2611 if (audit_rate_check()) { 2612 /* setup the netlink header, see the comments in 2613 * kauditd_send_multicast_skb() for length quirks */ 2614 nlh = nlmsg_hdr(skb); 2615 nlh->nlmsg_len = skb->len - NLMSG_HDRLEN; 2616 2617 /* queue the netlink packet */ 2618 skb_queue_tail(&audit_queue, skb); 2619 } else { 2620 audit_log_lost("rate limit exceeded"); 2621 kfree_skb(skb); 2622 } 2623 } 2624 2625 /** 2626 * audit_log_end - end one audit record 2627 * @ab: the audit_buffer 2628 * 2629 * We can not do a netlink send inside an irq context because it blocks (last 2630 * arg, flags, is not set to MSG_DONTWAIT), so the audit buffer is placed on a 2631 * queue and a kthread is scheduled to remove them from the queue outside the 2632 * irq context. May be called in any context. 2633 */ 2634 void audit_log_end(struct audit_buffer *ab) 2635 { 2636 struct sk_buff *skb; 2637 2638 if (!ab) 2639 return; 2640 2641 while ((skb = skb_dequeue(&ab->skb_list))) 2642 __audit_log_end(skb); 2643 2644 /* poke the kauditd thread */ 2645 wake_up_interruptible(&kauditd_wait); 2646 2647 audit_buffer_free(ab); 2648 } 2649 2650 /** 2651 * audit_log - Log an audit record 2652 * @ctx: audit context 2653 * @gfp_mask: type of allocation 2654 * @type: audit message type 2655 * @fmt: format string to use 2656 * @...: variable parameters matching the format string 2657 * 2658 * This is a convenience function that calls audit_log_start, 2659 * audit_log_vformat, and audit_log_end. It may be called 2660 * in any context. 2661 */ 2662 void audit_log(struct audit_context *ctx, gfp_t gfp_mask, int type, 2663 const char *fmt, ...) 2664 { 2665 struct audit_buffer *ab; 2666 va_list args; 2667 2668 ab = audit_log_start(ctx, gfp_mask, type); 2669 if (ab) { 2670 va_start(args, fmt); 2671 audit_log_vformat(ab, fmt, args); 2672 va_end(args); 2673 audit_log_end(ab); 2674 } 2675 } 2676 2677 EXPORT_SYMBOL(audit_log_start); 2678 EXPORT_SYMBOL(audit_log_end); 2679 EXPORT_SYMBOL(audit_log_format); 2680 EXPORT_SYMBOL(audit_log); 2681