Back to home page

LXR

 
 

    


0001 /* audit.c -- Auditing support
0002  * Gateway between the kernel (e.g., selinux) and the user-space audit daemon.
0003  * System-call specific features have moved to auditsc.c
0004  *
0005  * Copyright 2003-2007 Red Hat Inc., Durham, North Carolina.
0006  * All Rights Reserved.
0007  *
0008  * This program is free software; you can redistribute it and/or modify
0009  * it under the terms of the GNU General Public License as published by
0010  * the Free Software Foundation; either version 2 of the License, or
0011  * (at your option) any later version.
0012  *
0013  * This program is distributed in the hope that it will be useful,
0014  * but WITHOUT ANY WARRANTY; without even the implied warranty of
0015  * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
0016  * GNU General Public License for more details.
0017  *
0018  * You should have received a copy of the GNU General Public License
0019  * along with this program; if not, write to the Free Software
0020  * Foundation, Inc., 59 Temple Place, Suite 330, Boston, MA  02111-1307  USA
0021  *
0022  * Written by Rickard E. (Rik) Faith <faith@redhat.com>
0023  *
0024  * Goals: 1) Integrate fully with Security Modules.
0025  *    2) Minimal run-time overhead:
0026  *       a) Minimal when syscall auditing is disabled (audit_enable=0).
0027  *       b) Small when syscall auditing is enabled and no audit record
0028  *      is generated (defer as much work as possible to record
0029  *      generation time):
0030  *      i) context is allocated,
0031  *      ii) names from getname are stored without a copy, and
0032  *      iii) inode information stored from path_lookup.
0033  *    3) Ability to disable syscall auditing at boot time (audit=0).
0034  *    4) Usable by other parts of the kernel (if audit_log* is called,
0035  *       then a syscall record will be generated automatically for the
0036  *       current syscall).
0037  *    5) Netlink interface to user-space.
0038  *    6) Support low-overhead kernel-based filtering to minimize the
0039  *       information that must be passed to user-space.
0040  *
0041  * Example user-space utilities: http://people.redhat.com/sgrubb/audit/
0042  */
0043 
0044 #define pr_fmt(fmt) KBUILD_MODNAME ": " fmt
0045 
0046 #include <linux/file.h>
0047 #include <linux/init.h>
0048 #include <linux/types.h>
0049 #include <linux/atomic.h>
0050 #include <linux/mm.h>
0051 #include <linux/export.h>
0052 #include <linux/slab.h>
0053 #include <linux/err.h>
0054 #include <linux/kthread.h>
0055 #include <linux/kernel.h>
0056 #include <linux/syscalls.h>
0057 
0058 #include <linux/audit.h>
0059 
0060 #include <net/sock.h>
0061 #include <net/netlink.h>
0062 #include <linux/skbuff.h>
0063 #ifdef CONFIG_SECURITY
0064 #include <linux/security.h>
0065 #endif
0066 #include <linux/freezer.h>
0067 #include <linux/pid_namespace.h>
0068 #include <net/netns/generic.h>
0069 
0070 #include "audit.h"
0071 
0072 /* No auditing will take place until audit_initialized == AUDIT_INITIALIZED.
0073  * (Initialization happens after skb_init is called.) */
0074 #define AUDIT_DISABLED      -1
0075 #define AUDIT_UNINITIALIZED 0
0076 #define AUDIT_INITIALIZED   1
0077 static int  audit_initialized;
0078 
0079 #define AUDIT_OFF   0
0080 #define AUDIT_ON    1
0081 #define AUDIT_LOCKED    2
0082 u32     audit_enabled;
0083 u32     audit_ever_enabled;
0084 
0085 EXPORT_SYMBOL_GPL(audit_enabled);
0086 
0087 /* Default state when kernel boots without any parameters. */
0088 static u32  audit_default;
0089 
0090 /* If auditing cannot proceed, audit_failure selects what happens. */
0091 static u32  audit_failure = AUDIT_FAIL_PRINTK;
0092 
0093 /*
0094  * If audit records are to be written to the netlink socket, audit_pid
0095  * contains the pid of the auditd process and audit_nlk_portid contains
0096  * the portid to use to send netlink messages to that process.
0097  */
0098 int     audit_pid;
0099 static __u32    audit_nlk_portid;
0100 
0101 /* If audit_rate_limit is non-zero, limit the rate of sending audit records
0102  * to that number per second.  This prevents DoS attacks, but results in
0103  * audit records being dropped. */
0104 static u32  audit_rate_limit;
0105 
0106 /* Number of outstanding audit_buffers allowed.
0107  * When set to zero, this means unlimited. */
0108 static u32  audit_backlog_limit = 64;
0109 #define AUDIT_BACKLOG_WAIT_TIME (60 * HZ)
0110 static u32  audit_backlog_wait_time = AUDIT_BACKLOG_WAIT_TIME;
0111 
0112 /* The identity of the user shutting down the audit system. */
0113 kuid_t      audit_sig_uid = INVALID_UID;
0114 pid_t       audit_sig_pid = -1;
0115 u32     audit_sig_sid = 0;
0116 
0117 /* Records can be lost in several ways:
0118    0) [suppressed in audit_alloc]
0119    1) out of memory in audit_log_start [kmalloc of struct audit_buffer]
0120    2) out of memory in audit_log_move [alloc_skb]
0121    3) suppressed due to audit_rate_limit
0122    4) suppressed due to audit_backlog_limit
0123 */
0124 static atomic_t    audit_lost = ATOMIC_INIT(0);
0125 
0126 /* The netlink socket. */
0127 static struct sock *audit_sock;
0128 static unsigned int audit_net_id;
0129 
0130 /* Hash for inode-based rules */
0131 struct list_head audit_inode_hash[AUDIT_INODE_BUCKETS];
0132 
0133 /* The audit_freelist is a list of pre-allocated audit buffers (if more
0134  * than AUDIT_MAXFREE are in use, the audit buffer is freed instead of
0135  * being placed on the freelist). */
0136 static DEFINE_SPINLOCK(audit_freelist_lock);
0137 static int     audit_freelist_count;
0138 static LIST_HEAD(audit_freelist);
0139 
0140 /* queue msgs to send via kauditd_task */
0141 static struct sk_buff_head audit_queue;
0142 /* queue msgs due to temporary unicast send problems */
0143 static struct sk_buff_head audit_retry_queue;
0144 /* queue msgs waiting for new auditd connection */
0145 static struct sk_buff_head audit_hold_queue;
0146 
0147 /* queue servicing thread */
0148 static struct task_struct *kauditd_task;
0149 static DECLARE_WAIT_QUEUE_HEAD(kauditd_wait);
0150 
0151 /* waitqueue for callers who are blocked on the audit backlog */
0152 static DECLARE_WAIT_QUEUE_HEAD(audit_backlog_wait);
0153 
0154 static struct audit_features af = {.vers = AUDIT_FEATURE_VERSION,
0155                    .mask = -1,
0156                    .features = 0,
0157                    .lock = 0,};
0158 
0159 static char *audit_feature_names[2] = {
0160     "only_unset_loginuid",
0161     "loginuid_immutable",
0162 };
0163 
0164 
0165 /* Serialize requests from userspace. */
0166 DEFINE_MUTEX(audit_cmd_mutex);
0167 
0168 /* AUDIT_BUFSIZ is the size of the temporary buffer used for formatting
0169  * audit records.  Since printk uses a 1024 byte buffer, this buffer
0170  * should be at least that large. */
0171 #define AUDIT_BUFSIZ 1024
0172 
0173 /* AUDIT_MAXFREE is the number of empty audit_buffers we keep on the
0174  * audit_freelist.  Doing so eliminates many kmalloc/kfree calls. */
0175 #define AUDIT_MAXFREE  (2*NR_CPUS)
0176 
0177 /* The audit_buffer is used when formatting an audit record.  The caller
0178  * locks briefly to get the record off the freelist or to allocate the
0179  * buffer, and locks briefly to send the buffer to the netlink layer or
0180  * to place it on a transmit queue.  Multiple audit_buffers can be in
0181  * use simultaneously. */
0182 struct audit_buffer {
0183     struct list_head     list;
0184     struct sk_buff       *skb;  /* formatted skb ready to send */
0185     struct audit_context *ctx;  /* NULL or associated context */
0186     gfp_t            gfp_mask;
0187 };
0188 
0189 struct audit_reply {
0190     __u32 portid;
0191     struct net *net;
0192     struct sk_buff *skb;
0193 };
0194 
0195 static void audit_set_portid(struct audit_buffer *ab, __u32 portid)
0196 {
0197     if (ab) {
0198         struct nlmsghdr *nlh = nlmsg_hdr(ab->skb);
0199         nlh->nlmsg_pid = portid;
0200     }
0201 }
0202 
0203 void audit_panic(const char *message)
0204 {
0205     switch (audit_failure) {
0206     case AUDIT_FAIL_SILENT:
0207         break;
0208     case AUDIT_FAIL_PRINTK:
0209         if (printk_ratelimit())
0210             pr_err("%s\n", message);
0211         break;
0212     case AUDIT_FAIL_PANIC:
0213         /* test audit_pid since printk is always losey, why bother? */
0214         if (audit_pid)
0215             panic("audit: %s\n", message);
0216         break;
0217     }
0218 }
0219 
0220 static inline int audit_rate_check(void)
0221 {
0222     static unsigned long    last_check = 0;
0223     static int      messages   = 0;
0224     static DEFINE_SPINLOCK(lock);
0225     unsigned long       flags;
0226     unsigned long       now;
0227     unsigned long       elapsed;
0228     int         retval     = 0;
0229 
0230     if (!audit_rate_limit) return 1;
0231 
0232     spin_lock_irqsave(&lock, flags);
0233     if (++messages < audit_rate_limit) {
0234         retval = 1;
0235     } else {
0236         now     = jiffies;
0237         elapsed = now - last_check;
0238         if (elapsed > HZ) {
0239             last_check = now;
0240             messages   = 0;
0241             retval     = 1;
0242         }
0243     }
0244     spin_unlock_irqrestore(&lock, flags);
0245 
0246     return retval;
0247 }
0248 
0249 /**
0250  * audit_log_lost - conditionally log lost audit message event
0251  * @message: the message stating reason for lost audit message
0252  *
0253  * Emit at least 1 message per second, even if audit_rate_check is
0254  * throttling.
0255  * Always increment the lost messages counter.
0256 */
0257 void audit_log_lost(const char *message)
0258 {
0259     static unsigned long    last_msg = 0;
0260     static DEFINE_SPINLOCK(lock);
0261     unsigned long       flags;
0262     unsigned long       now;
0263     int         print;
0264 
0265     atomic_inc(&audit_lost);
0266 
0267     print = (audit_failure == AUDIT_FAIL_PANIC || !audit_rate_limit);
0268 
0269     if (!print) {
0270         spin_lock_irqsave(&lock, flags);
0271         now = jiffies;
0272         if (now - last_msg > HZ) {
0273             print = 1;
0274             last_msg = now;
0275         }
0276         spin_unlock_irqrestore(&lock, flags);
0277     }
0278 
0279     if (print) {
0280         if (printk_ratelimit())
0281             pr_warn("audit_lost=%u audit_rate_limit=%u audit_backlog_limit=%u\n",
0282                 atomic_read(&audit_lost),
0283                 audit_rate_limit,
0284                 audit_backlog_limit);
0285         audit_panic(message);
0286     }
0287 }
0288 
0289 static int audit_log_config_change(char *function_name, u32 new, u32 old,
0290                    int allow_changes)
0291 {
0292     struct audit_buffer *ab;
0293     int rc = 0;
0294 
0295     ab = audit_log_start(NULL, GFP_KERNEL, AUDIT_CONFIG_CHANGE);
0296     if (unlikely(!ab))
0297         return rc;
0298     audit_log_format(ab, "%s=%u old=%u", function_name, new, old);
0299     audit_log_session_info(ab);
0300     rc = audit_log_task_context(ab);
0301     if (rc)
0302         allow_changes = 0; /* Something weird, deny request */
0303     audit_log_format(ab, " res=%d", allow_changes);
0304     audit_log_end(ab);
0305     return rc;
0306 }
0307 
0308 static int audit_do_config_change(char *function_name, u32 *to_change, u32 new)
0309 {
0310     int allow_changes, rc = 0;
0311     u32 old = *to_change;
0312 
0313     /* check if we are locked */
0314     if (audit_enabled == AUDIT_LOCKED)
0315         allow_changes = 0;
0316     else
0317         allow_changes = 1;
0318 
0319     if (audit_enabled != AUDIT_OFF) {
0320         rc = audit_log_config_change(function_name, new, old, allow_changes);
0321         if (rc)
0322             allow_changes = 0;
0323     }
0324 
0325     /* If we are allowed, make the change */
0326     if (allow_changes == 1)
0327         *to_change = new;
0328     /* Not allowed, update reason */
0329     else if (rc == 0)
0330         rc = -EPERM;
0331     return rc;
0332 }
0333 
0334 static int audit_set_rate_limit(u32 limit)
0335 {
0336     return audit_do_config_change("audit_rate_limit", &audit_rate_limit, limit);
0337 }
0338 
0339 static int audit_set_backlog_limit(u32 limit)
0340 {
0341     return audit_do_config_change("audit_backlog_limit", &audit_backlog_limit, limit);
0342 }
0343 
0344 static int audit_set_backlog_wait_time(u32 timeout)
0345 {
0346     return audit_do_config_change("audit_backlog_wait_time",
0347                       &audit_backlog_wait_time, timeout);
0348 }
0349 
0350 static int audit_set_enabled(u32 state)
0351 {
0352     int rc;
0353     if (state > AUDIT_LOCKED)
0354         return -EINVAL;
0355 
0356     rc =  audit_do_config_change("audit_enabled", &audit_enabled, state);
0357     if (!rc)
0358         audit_ever_enabled |= !!state;
0359 
0360     return rc;
0361 }
0362 
0363 static int audit_set_failure(u32 state)
0364 {
0365     if (state != AUDIT_FAIL_SILENT
0366         && state != AUDIT_FAIL_PRINTK
0367         && state != AUDIT_FAIL_PANIC)
0368         return -EINVAL;
0369 
0370     return audit_do_config_change("audit_failure", &audit_failure, state);
0371 }
0372 
0373 /*
0374  * For one reason or another this nlh isn't getting delivered to the userspace
0375  * audit daemon, just send it to printk.
0376  */
0377 static void kauditd_printk_skb(struct sk_buff *skb)
0378 {
0379     struct nlmsghdr *nlh = nlmsg_hdr(skb);
0380     char *data = nlmsg_data(nlh);
0381 
0382     if (nlh->nlmsg_type != AUDIT_EOE) {
0383         if (printk_ratelimit())
0384             pr_notice("type=%d %s\n", nlh->nlmsg_type, data);
0385         else
0386             audit_log_lost("printk limit exceeded");
0387     }
0388 }
0389 
0390 /**
0391  * kauditd_hold_skb - Queue an audit record, waiting for auditd
0392  * @skb: audit record
0393  *
0394  * Description:
0395  * Queue the audit record, waiting for an instance of auditd.  When this
0396  * function is called we haven't given up yet on sending the record, but things
0397  * are not looking good.  The first thing we want to do is try to write the
0398  * record via printk and then see if we want to try and hold on to the record
0399  * and queue it, if we have room.  If we want to hold on to the record, but we
0400  * don't have room, record a record lost message.
0401  */
0402 static void kauditd_hold_skb(struct sk_buff *skb)
0403 {
0404     /* at this point it is uncertain if we will ever send this to auditd so
0405      * try to send the message via printk before we go any further */
0406     kauditd_printk_skb(skb);
0407 
0408     /* can we just silently drop the message? */
0409     if (!audit_default) {
0410         kfree_skb(skb);
0411         return;
0412     }
0413 
0414     /* if we have room, queue the message */
0415     if (!audit_backlog_limit ||
0416         skb_queue_len(&audit_hold_queue) < audit_backlog_limit) {
0417         skb_queue_tail(&audit_hold_queue, skb);
0418         return;
0419     }
0420 
0421     /* we have no other options - drop the message */
0422     audit_log_lost("kauditd hold queue overflow");
0423     kfree_skb(skb);
0424 }
0425 
0426 /**
0427  * kauditd_retry_skb - Queue an audit record, attempt to send again to auditd
0428  * @skb: audit record
0429  *
0430  * Description:
0431  * Not as serious as kauditd_hold_skb() as we still have a connected auditd,
0432  * but for some reason we are having problems sending it audit records so
0433  * queue the given record and attempt to resend.
0434  */
0435 static void kauditd_retry_skb(struct sk_buff *skb)
0436 {
0437     /* NOTE: because records should only live in the retry queue for a
0438      * short period of time, before either being sent or moved to the hold
0439      * queue, we don't currently enforce a limit on this queue */
0440     skb_queue_tail(&audit_retry_queue, skb);
0441 }
0442 
0443 /**
0444  * auditd_reset - Disconnect the auditd connection
0445  *
0446  * Description:
0447  * Break the auditd/kauditd connection and move all the records in the retry
0448  * queue into the hold queue in case auditd reconnects.  The audit_cmd_mutex
0449  * must be held when calling this function.
0450  */
0451 static void auditd_reset(void)
0452 {
0453     struct sk_buff *skb;
0454 
0455     /* break the connection */
0456     if (audit_sock) {
0457         sock_put(audit_sock);
0458         audit_sock = NULL;
0459     }
0460     audit_pid = 0;
0461     audit_nlk_portid = 0;
0462 
0463     /* flush all of the retry queue to the hold queue */
0464     while ((skb = skb_dequeue(&audit_retry_queue)))
0465         kauditd_hold_skb(skb);
0466 }
0467 
0468 /**
0469  * kauditd_send_unicast_skb - Send a record via unicast to auditd
0470  * @skb: audit record
0471  */
0472 static int kauditd_send_unicast_skb(struct sk_buff *skb)
0473 {
0474     int rc;
0475 
0476     /* if we know nothing is connected, don't even try the netlink call */
0477     if (!audit_pid)
0478         return -ECONNREFUSED;
0479 
0480     /* get an extra skb reference in case we fail to send */
0481     skb_get(skb);
0482     rc = netlink_unicast(audit_sock, skb, audit_nlk_portid, 0);
0483     if (rc >= 0) {
0484         consume_skb(skb);
0485         rc = 0;
0486     }
0487 
0488     return rc;
0489 }
0490 
0491 /*
0492  * kauditd_send_multicast_skb - Send a record to any multicast listeners
0493  * @skb: audit record
0494  *
0495  * Description:
0496  * This function doesn't consume an skb as might be expected since it has to
0497  * copy it anyways.
0498  */
0499 static void kauditd_send_multicast_skb(struct sk_buff *skb)
0500 {
0501     struct sk_buff *copy;
0502     struct audit_net *aunet = net_generic(&init_net, audit_net_id);
0503     struct sock *sock = aunet->nlsk;
0504     struct nlmsghdr *nlh;
0505 
0506     if (!netlink_has_listeners(sock, AUDIT_NLGRP_READLOG))
0507         return;
0508 
0509     /*
0510      * The seemingly wasteful skb_copy() rather than bumping the refcount
0511      * using skb_get() is necessary because non-standard mods are made to
0512      * the skb by the original kaudit unicast socket send routine.  The
0513      * existing auditd daemon assumes this breakage.  Fixing this would
0514      * require co-ordinating a change in the established protocol between
0515      * the kaudit kernel subsystem and the auditd userspace code.  There is
0516      * no reason for new multicast clients to continue with this
0517      * non-compliance.
0518      */
0519     copy = skb_copy(skb, GFP_KERNEL);
0520     if (!copy)
0521         return;
0522     nlh = nlmsg_hdr(copy);
0523     nlh->nlmsg_len = skb->len;
0524 
0525     nlmsg_multicast(sock, copy, 0, AUDIT_NLGRP_READLOG, GFP_KERNEL);
0526 }
0527 
0528 /**
0529  * kauditd_wake_condition - Return true when it is time to wake kauditd_thread
0530  *
0531  * Description:
0532  * This function is for use by the wait_event_freezable() call in
0533  * kauditd_thread().
0534  */
0535 static int kauditd_wake_condition(void)
0536 {
0537     static int pid_last = 0;
0538     int rc;
0539     int pid = audit_pid;
0540 
0541     /* wake on new messages or a change in the connected auditd */
0542     rc = skb_queue_len(&audit_queue) || (pid && pid != pid_last);
0543     if (rc)
0544         pid_last = pid;
0545 
0546     return rc;
0547 }
0548 
0549 static int kauditd_thread(void *dummy)
0550 {
0551     int rc;
0552     int auditd = 0;
0553     int reschedule = 0;
0554     struct sk_buff *skb;
0555     struct nlmsghdr *nlh;
0556 
0557 #define UNICAST_RETRIES 5
0558 #define AUDITD_BAD(x,y) \
0559     ((x) == -ECONNREFUSED || (x) == -EPERM || ++(y) >= UNICAST_RETRIES)
0560 
0561     /* NOTE: we do invalidate the auditd connection flag on any sending
0562      * errors, but we only "restore" the connection flag at specific places
0563      * in the loop in order to help ensure proper ordering of audit
0564      * records */
0565 
0566     set_freezable();
0567     while (!kthread_should_stop()) {
0568         /* NOTE: possible area for future improvement is to look at
0569          *       the hold and retry queues, since only this thread
0570          *       has access to these queues we might be able to do
0571          *       our own queuing and skip some/all of the locking */
0572 
0573         /* NOTE: it might be a fun experiment to split the hold and
0574          *       retry queue handling to another thread, but the
0575          *       synchronization issues and other overhead might kill
0576          *       any performance gains */
0577 
0578         /* attempt to flush the hold queue */
0579         while (auditd && (skb = skb_dequeue(&audit_hold_queue))) {
0580             rc = kauditd_send_unicast_skb(skb);
0581             if (rc) {
0582                 /* requeue to the same spot */
0583                 skb_queue_head(&audit_hold_queue, skb);
0584 
0585                 auditd = 0;
0586                 if (AUDITD_BAD(rc, reschedule)) {
0587                     mutex_lock(&audit_cmd_mutex);
0588                     auditd_reset();
0589                     mutex_unlock(&audit_cmd_mutex);
0590                     reschedule = 0;
0591                 }
0592             } else
0593                 /* we were able to send successfully */
0594                 reschedule = 0;
0595         }
0596 
0597         /* attempt to flush the retry queue */
0598         while (auditd && (skb = skb_dequeue(&audit_retry_queue))) {
0599             rc = kauditd_send_unicast_skb(skb);
0600             if (rc) {
0601                 auditd = 0;
0602                 if (AUDITD_BAD(rc, reschedule)) {
0603                     kauditd_hold_skb(skb);
0604                     mutex_lock(&audit_cmd_mutex);
0605                     auditd_reset();
0606                     mutex_unlock(&audit_cmd_mutex);
0607                     reschedule = 0;
0608                 } else
0609                     /* temporary problem (we hope), queue
0610                      * to the same spot and retry */
0611                     skb_queue_head(&audit_retry_queue, skb);
0612             } else
0613                 /* we were able to send successfully */
0614                 reschedule = 0;
0615         }
0616 
0617         /* standard queue processing, try to be as quick as possible */
0618 quick_loop:
0619         skb = skb_dequeue(&audit_queue);
0620         if (skb) {
0621             /* setup the netlink header, see the comments in
0622              * kauditd_send_multicast_skb() for length quirks */
0623             nlh = nlmsg_hdr(skb);
0624             nlh->nlmsg_len = skb->len - NLMSG_HDRLEN;
0625 
0626             /* attempt to send to any multicast listeners */
0627             kauditd_send_multicast_skb(skb);
0628 
0629             /* attempt to send to auditd, queue on failure */
0630             if (auditd) {
0631                 rc = kauditd_send_unicast_skb(skb);
0632                 if (rc) {
0633                     auditd = 0;
0634                     if (AUDITD_BAD(rc, reschedule)) {
0635                         mutex_lock(&audit_cmd_mutex);
0636                         auditd_reset();
0637                         mutex_unlock(&audit_cmd_mutex);
0638                         reschedule = 0;
0639                     }
0640 
0641                     /* move to the retry queue */
0642                     kauditd_retry_skb(skb);
0643                 } else
0644                     /* everything is working so go fast! */
0645                     goto quick_loop;
0646             } else if (reschedule)
0647                 /* we are currently having problems, move to
0648                  * the retry queue */
0649                 kauditd_retry_skb(skb);
0650             else
0651                 /* dump the message via printk and hold it */
0652                 kauditd_hold_skb(skb);
0653         } else {
0654             /* we have flushed the backlog so wake everyone */
0655             wake_up(&audit_backlog_wait);
0656 
0657             /* if everything is okay with auditd (if present), go
0658              * to sleep until there is something new in the queue
0659              * or we have a change in the connected auditd;
0660              * otherwise simply reschedule to give things a chance
0661              * to recover */
0662             if (reschedule) {
0663                 set_current_state(TASK_INTERRUPTIBLE);
0664                 schedule();
0665             } else
0666                 wait_event_freezable(kauditd_wait,
0667                              kauditd_wake_condition());
0668 
0669             /* update the auditd connection status */
0670             auditd = (audit_pid ? 1 : 0);
0671         }
0672     }
0673 
0674     return 0;
0675 }
0676 
0677 int audit_send_list(void *_dest)
0678 {
0679     struct audit_netlink_list *dest = _dest;
0680     struct sk_buff *skb;
0681     struct net *net = dest->net;
0682     struct audit_net *aunet = net_generic(net, audit_net_id);
0683 
0684     /* wait for parent to finish and send an ACK */
0685     mutex_lock(&audit_cmd_mutex);
0686     mutex_unlock(&audit_cmd_mutex);
0687 
0688     while ((skb = __skb_dequeue(&dest->q)) != NULL)
0689         netlink_unicast(aunet->nlsk, skb, dest->portid, 0);
0690 
0691     put_net(net);
0692     kfree(dest);
0693 
0694     return 0;
0695 }
0696 
0697 struct sk_buff *audit_make_reply(__u32 portid, int seq, int type, int done,
0698                  int multi, const void *payload, int size)
0699 {
0700     struct sk_buff  *skb;
0701     struct nlmsghdr *nlh;
0702     void        *data;
0703     int     flags = multi ? NLM_F_MULTI : 0;
0704     int     t     = done  ? NLMSG_DONE  : type;
0705 
0706     skb = nlmsg_new(size, GFP_KERNEL);
0707     if (!skb)
0708         return NULL;
0709 
0710     nlh = nlmsg_put(skb, portid, seq, t, size, flags);
0711     if (!nlh)
0712         goto out_kfree_skb;
0713     data = nlmsg_data(nlh);
0714     memcpy(data, payload, size);
0715     return skb;
0716 
0717 out_kfree_skb:
0718     kfree_skb(skb);
0719     return NULL;
0720 }
0721 
0722 static int audit_send_reply_thread(void *arg)
0723 {
0724     struct audit_reply *reply = (struct audit_reply *)arg;
0725     struct net *net = reply->net;
0726     struct audit_net *aunet = net_generic(net, audit_net_id);
0727 
0728     mutex_lock(&audit_cmd_mutex);
0729     mutex_unlock(&audit_cmd_mutex);
0730 
0731     /* Ignore failure. It'll only happen if the sender goes away,
0732        because our timeout is set to infinite. */
0733     netlink_unicast(aunet->nlsk , reply->skb, reply->portid, 0);
0734     put_net(net);
0735     kfree(reply);
0736     return 0;
0737 }
0738 
0739 /**
0740  * audit_send_reply - send an audit reply message via netlink
0741  * @request_skb: skb of request we are replying to (used to target the reply)
0742  * @seq: sequence number
0743  * @type: audit message type
0744  * @done: done (last) flag
0745  * @multi: multi-part message flag
0746  * @payload: payload data
0747  * @size: payload size
0748  *
0749  * Allocates an skb, builds the netlink message, and sends it to the port id.
0750  * No failure notifications.
0751  */
0752 static void audit_send_reply(struct sk_buff *request_skb, int seq, int type, int done,
0753                  int multi, const void *payload, int size)
0754 {
0755     u32 portid = NETLINK_CB(request_skb).portid;
0756     struct net *net = sock_net(NETLINK_CB(request_skb).sk);
0757     struct sk_buff *skb;
0758     struct task_struct *tsk;
0759     struct audit_reply *reply = kmalloc(sizeof(struct audit_reply),
0760                         GFP_KERNEL);
0761 
0762     if (!reply)
0763         return;
0764 
0765     skb = audit_make_reply(portid, seq, type, done, multi, payload, size);
0766     if (!skb)
0767         goto out;
0768 
0769     reply->net = get_net(net);
0770     reply->portid = portid;
0771     reply->skb = skb;
0772 
0773     tsk = kthread_run(audit_send_reply_thread, reply, "audit_send_reply");
0774     if (!IS_ERR(tsk))
0775         return;
0776     kfree_skb(skb);
0777 out:
0778     kfree(reply);
0779 }
0780 
0781 /*
0782  * Check for appropriate CAP_AUDIT_ capabilities on incoming audit
0783  * control messages.
0784  */
0785 static int audit_netlink_ok(struct sk_buff *skb, u16 msg_type)
0786 {
0787     int err = 0;
0788 
0789     /* Only support initial user namespace for now. */
0790     /*
0791      * We return ECONNREFUSED because it tricks userspace into thinking
0792      * that audit was not configured into the kernel.  Lots of users
0793      * configure their PAM stack (because that's what the distro does)
0794      * to reject login if unable to send messages to audit.  If we return
0795      * ECONNREFUSED the PAM stack thinks the kernel does not have audit
0796      * configured in and will let login proceed.  If we return EPERM
0797      * userspace will reject all logins.  This should be removed when we
0798      * support non init namespaces!!
0799      */
0800     if (current_user_ns() != &init_user_ns)
0801         return -ECONNREFUSED;
0802 
0803     switch (msg_type) {
0804     case AUDIT_LIST:
0805     case AUDIT_ADD:
0806     case AUDIT_DEL:
0807         return -EOPNOTSUPP;
0808     case AUDIT_GET:
0809     case AUDIT_SET:
0810     case AUDIT_GET_FEATURE:
0811     case AUDIT_SET_FEATURE:
0812     case AUDIT_LIST_RULES:
0813     case AUDIT_ADD_RULE:
0814     case AUDIT_DEL_RULE:
0815     case AUDIT_SIGNAL_INFO:
0816     case AUDIT_TTY_GET:
0817     case AUDIT_TTY_SET:
0818     case AUDIT_TRIM:
0819     case AUDIT_MAKE_EQUIV:
0820         /* Only support auditd and auditctl in initial pid namespace
0821          * for now. */
0822         if (task_active_pid_ns(current) != &init_pid_ns)
0823             return -EPERM;
0824 
0825         if (!netlink_capable(skb, CAP_AUDIT_CONTROL))
0826             err = -EPERM;
0827         break;
0828     case AUDIT_USER:
0829     case AUDIT_FIRST_USER_MSG ... AUDIT_LAST_USER_MSG:
0830     case AUDIT_FIRST_USER_MSG2 ... AUDIT_LAST_USER_MSG2:
0831         if (!netlink_capable(skb, CAP_AUDIT_WRITE))
0832             err = -EPERM;
0833         break;
0834     default:  /* bad msg */
0835         err = -EINVAL;
0836     }
0837 
0838     return err;
0839 }
0840 
0841 static void audit_log_common_recv_msg(struct audit_buffer **ab, u16 msg_type)
0842 {
0843     uid_t uid = from_kuid(&init_user_ns, current_uid());
0844     pid_t pid = task_tgid_nr(current);
0845 
0846     if (!audit_enabled && msg_type != AUDIT_USER_AVC) {
0847         *ab = NULL;
0848         return;
0849     }
0850 
0851     *ab = audit_log_start(NULL, GFP_KERNEL, msg_type);
0852     if (unlikely(!*ab))
0853         return;
0854     audit_log_format(*ab, "pid=%d uid=%u", pid, uid);
0855     audit_log_session_info(*ab);
0856     audit_log_task_context(*ab);
0857 }
0858 
0859 int is_audit_feature_set(int i)
0860 {
0861     return af.features & AUDIT_FEATURE_TO_MASK(i);
0862 }
0863 
0864 
0865 static int audit_get_feature(struct sk_buff *skb)
0866 {
0867     u32 seq;
0868 
0869     seq = nlmsg_hdr(skb)->nlmsg_seq;
0870 
0871     audit_send_reply(skb, seq, AUDIT_GET_FEATURE, 0, 0, &af, sizeof(af));
0872 
0873     return 0;
0874 }
0875 
0876 static void audit_log_feature_change(int which, u32 old_feature, u32 new_feature,
0877                      u32 old_lock, u32 new_lock, int res)
0878 {
0879     struct audit_buffer *ab;
0880 
0881     if (audit_enabled == AUDIT_OFF)
0882         return;
0883 
0884     ab = audit_log_start(NULL, GFP_KERNEL, AUDIT_FEATURE_CHANGE);
0885     audit_log_task_info(ab, current);
0886     audit_log_format(ab, " feature=%s old=%u new=%u old_lock=%u new_lock=%u res=%d",
0887              audit_feature_names[which], !!old_feature, !!new_feature,
0888              !!old_lock, !!new_lock, res);
0889     audit_log_end(ab);
0890 }
0891 
0892 static int audit_set_feature(struct sk_buff *skb)
0893 {
0894     struct audit_features *uaf;
0895     int i;
0896 
0897     BUILD_BUG_ON(AUDIT_LAST_FEATURE + 1 > ARRAY_SIZE(audit_feature_names));
0898     uaf = nlmsg_data(nlmsg_hdr(skb));
0899 
0900     /* if there is ever a version 2 we should handle that here */
0901 
0902     for (i = 0; i <= AUDIT_LAST_FEATURE; i++) {
0903         u32 feature = AUDIT_FEATURE_TO_MASK(i);
0904         u32 old_feature, new_feature, old_lock, new_lock;
0905 
0906         /* if we are not changing this feature, move along */
0907         if (!(feature & uaf->mask))
0908             continue;
0909 
0910         old_feature = af.features & feature;
0911         new_feature = uaf->features & feature;
0912         new_lock = (uaf->lock | af.lock) & feature;
0913         old_lock = af.lock & feature;
0914 
0915         /* are we changing a locked feature? */
0916         if (old_lock && (new_feature != old_feature)) {
0917             audit_log_feature_change(i, old_feature, new_feature,
0918                          old_lock, new_lock, 0);
0919             return -EPERM;
0920         }
0921     }
0922     /* nothing invalid, do the changes */
0923     for (i = 0; i <= AUDIT_LAST_FEATURE; i++) {
0924         u32 feature = AUDIT_FEATURE_TO_MASK(i);
0925         u32 old_feature, new_feature, old_lock, new_lock;
0926 
0927         /* if we are not changing this feature, move along */
0928         if (!(feature & uaf->mask))
0929             continue;
0930 
0931         old_feature = af.features & feature;
0932         new_feature = uaf->features & feature;
0933         old_lock = af.lock & feature;
0934         new_lock = (uaf->lock | af.lock) & feature;
0935 
0936         if (new_feature != old_feature)
0937             audit_log_feature_change(i, old_feature, new_feature,
0938                          old_lock, new_lock, 1);
0939 
0940         if (new_feature)
0941             af.features |= feature;
0942         else
0943             af.features &= ~feature;
0944         af.lock |= new_lock;
0945     }
0946 
0947     return 0;
0948 }
0949 
0950 static int audit_replace(pid_t pid)
0951 {
0952     struct sk_buff *skb = audit_make_reply(0, 0, AUDIT_REPLACE, 0, 0,
0953                            &pid, sizeof(pid));
0954 
0955     if (!skb)
0956         return -ENOMEM;
0957     return netlink_unicast(audit_sock, skb, audit_nlk_portid, 0);
0958 }
0959 
0960 static int audit_receive_msg(struct sk_buff *skb, struct nlmsghdr *nlh)
0961 {
0962     u32         seq;
0963     void            *data;
0964     int         err;
0965     struct audit_buffer *ab;
0966     u16         msg_type = nlh->nlmsg_type;
0967     struct audit_sig_info   *sig_data;
0968     char            *ctx = NULL;
0969     u32         len;
0970 
0971     err = audit_netlink_ok(skb, msg_type);
0972     if (err)
0973         return err;
0974 
0975     seq  = nlh->nlmsg_seq;
0976     data = nlmsg_data(nlh);
0977 
0978     switch (msg_type) {
0979     case AUDIT_GET: {
0980         struct audit_status s;
0981         memset(&s, 0, sizeof(s));
0982         s.enabled       = audit_enabled;
0983         s.failure       = audit_failure;
0984         s.pid           = audit_pid;
0985         s.rate_limit        = audit_rate_limit;
0986         s.backlog_limit     = audit_backlog_limit;
0987         s.lost          = atomic_read(&audit_lost);
0988         s.backlog       = skb_queue_len(&audit_queue);
0989         s.feature_bitmap    = AUDIT_FEATURE_BITMAP_ALL;
0990         s.backlog_wait_time = audit_backlog_wait_time;
0991         audit_send_reply(skb, seq, AUDIT_GET, 0, 0, &s, sizeof(s));
0992         break;
0993     }
0994     case AUDIT_SET: {
0995         struct audit_status s;
0996         memset(&s, 0, sizeof(s));
0997         /* guard against past and future API changes */
0998         memcpy(&s, data, min_t(size_t, sizeof(s), nlmsg_len(nlh)));
0999         if (s.mask & AUDIT_STATUS_ENABLED) {
1000             err = audit_set_enabled(s.enabled);
1001             if (err < 0)
1002                 return err;
1003         }
1004         if (s.mask & AUDIT_STATUS_FAILURE) {
1005             err = audit_set_failure(s.failure);
1006             if (err < 0)
1007                 return err;
1008         }
1009         if (s.mask & AUDIT_STATUS_PID) {
1010             /* NOTE: we are using task_tgid_vnr() below because
1011              *       the s.pid value is relative to the namespace
1012              *       of the caller; at present this doesn't matter
1013              *       much since you can really only run auditd
1014              *       from the initial pid namespace, but something
1015              *       to keep in mind if this changes */
1016             int new_pid = s.pid;
1017             pid_t requesting_pid = task_tgid_vnr(current);
1018 
1019             if ((!new_pid) && (requesting_pid != audit_pid)) {
1020                 audit_log_config_change("audit_pid", new_pid, audit_pid, 0);
1021                 return -EACCES;
1022             }
1023             if (audit_pid && new_pid &&
1024                 audit_replace(requesting_pid) != -ECONNREFUSED) {
1025                 audit_log_config_change("audit_pid", new_pid, audit_pid, 0);
1026                 return -EEXIST;
1027             }
1028             if (audit_enabled != AUDIT_OFF)
1029                 audit_log_config_change("audit_pid", new_pid, audit_pid, 1);
1030             if (new_pid) {
1031                 if (audit_sock)
1032                     sock_put(audit_sock);
1033                 audit_pid = new_pid;
1034                 audit_nlk_portid = NETLINK_CB(skb).portid;
1035                 sock_hold(skb->sk);
1036                 audit_sock = skb->sk;
1037             } else {
1038                 auditd_reset();
1039             }
1040             wake_up_interruptible(&kauditd_wait);
1041         }
1042         if (s.mask & AUDIT_STATUS_RATE_LIMIT) {
1043             err = audit_set_rate_limit(s.rate_limit);
1044             if (err < 0)
1045                 return err;
1046         }
1047         if (s.mask & AUDIT_STATUS_BACKLOG_LIMIT) {
1048             err = audit_set_backlog_limit(s.backlog_limit);
1049             if (err < 0)
1050                 return err;
1051         }
1052         if (s.mask & AUDIT_STATUS_BACKLOG_WAIT_TIME) {
1053             if (sizeof(s) > (size_t)nlh->nlmsg_len)
1054                 return -EINVAL;
1055             if (s.backlog_wait_time > 10*AUDIT_BACKLOG_WAIT_TIME)
1056                 return -EINVAL;
1057             err = audit_set_backlog_wait_time(s.backlog_wait_time);
1058             if (err < 0)
1059                 return err;
1060         }
1061         break;
1062     }
1063     case AUDIT_GET_FEATURE:
1064         err = audit_get_feature(skb);
1065         if (err)
1066             return err;
1067         break;
1068     case AUDIT_SET_FEATURE:
1069         err = audit_set_feature(skb);
1070         if (err)
1071             return err;
1072         break;
1073     case AUDIT_USER:
1074     case AUDIT_FIRST_USER_MSG ... AUDIT_LAST_USER_MSG:
1075     case AUDIT_FIRST_USER_MSG2 ... AUDIT_LAST_USER_MSG2:
1076         if (!audit_enabled && msg_type != AUDIT_USER_AVC)
1077             return 0;
1078 
1079         err = audit_filter(msg_type, AUDIT_FILTER_USER);
1080         if (err == 1) { /* match or error */
1081             err = 0;
1082             if (msg_type == AUDIT_USER_TTY) {
1083                 err = tty_audit_push();
1084                 if (err)
1085                     break;
1086             }
1087             mutex_unlock(&audit_cmd_mutex);
1088             audit_log_common_recv_msg(&ab, msg_type);
1089             if (msg_type != AUDIT_USER_TTY)
1090                 audit_log_format(ab, " msg='%.*s'",
1091                          AUDIT_MESSAGE_TEXT_MAX,
1092                          (char *)data);
1093             else {
1094                 int size;
1095 
1096                 audit_log_format(ab, " data=");
1097                 size = nlmsg_len(nlh);
1098                 if (size > 0 &&
1099                     ((unsigned char *)data)[size - 1] == '\0')
1100                     size--;
1101                 audit_log_n_untrustedstring(ab, data, size);
1102             }
1103             audit_set_portid(ab, NETLINK_CB(skb).portid);
1104             audit_log_end(ab);
1105             mutex_lock(&audit_cmd_mutex);
1106         }
1107         break;
1108     case AUDIT_ADD_RULE:
1109     case AUDIT_DEL_RULE:
1110         if (nlmsg_len(nlh) < sizeof(struct audit_rule_data))
1111             return -EINVAL;
1112         if (audit_enabled == AUDIT_LOCKED) {
1113             audit_log_common_recv_msg(&ab, AUDIT_CONFIG_CHANGE);
1114             audit_log_format(ab, " audit_enabled=%d res=0", audit_enabled);
1115             audit_log_end(ab);
1116             return -EPERM;
1117         }
1118         err = audit_rule_change(msg_type, NETLINK_CB(skb).portid,
1119                        seq, data, nlmsg_len(nlh));
1120         break;
1121     case AUDIT_LIST_RULES:
1122         err = audit_list_rules_send(skb, seq);
1123         break;
1124     case AUDIT_TRIM:
1125         audit_trim_trees();
1126         audit_log_common_recv_msg(&ab, AUDIT_CONFIG_CHANGE);
1127         audit_log_format(ab, " op=trim res=1");
1128         audit_log_end(ab);
1129         break;
1130     case AUDIT_MAKE_EQUIV: {
1131         void *bufp = data;
1132         u32 sizes[2];
1133         size_t msglen = nlmsg_len(nlh);
1134         char *old, *new;
1135 
1136         err = -EINVAL;
1137         if (msglen < 2 * sizeof(u32))
1138             break;
1139         memcpy(sizes, bufp, 2 * sizeof(u32));
1140         bufp += 2 * sizeof(u32);
1141         msglen -= 2 * sizeof(u32);
1142         old = audit_unpack_string(&bufp, &msglen, sizes[0]);
1143         if (IS_ERR(old)) {
1144             err = PTR_ERR(old);
1145             break;
1146         }
1147         new = audit_unpack_string(&bufp, &msglen, sizes[1]);
1148         if (IS_ERR(new)) {
1149             err = PTR_ERR(new);
1150             kfree(old);
1151             break;
1152         }
1153         /* OK, here comes... */
1154         err = audit_tag_tree(old, new);
1155 
1156         audit_log_common_recv_msg(&ab, AUDIT_CONFIG_CHANGE);
1157 
1158         audit_log_format(ab, " op=make_equiv old=");
1159         audit_log_untrustedstring(ab, old);
1160         audit_log_format(ab, " new=");
1161         audit_log_untrustedstring(ab, new);
1162         audit_log_format(ab, " res=%d", !err);
1163         audit_log_end(ab);
1164         kfree(old);
1165         kfree(new);
1166         break;
1167     }
1168     case AUDIT_SIGNAL_INFO:
1169         len = 0;
1170         if (audit_sig_sid) {
1171             err = security_secid_to_secctx(audit_sig_sid, &ctx, &len);
1172             if (err)
1173                 return err;
1174         }
1175         sig_data = kmalloc(sizeof(*sig_data) + len, GFP_KERNEL);
1176         if (!sig_data) {
1177             if (audit_sig_sid)
1178                 security_release_secctx(ctx, len);
1179             return -ENOMEM;
1180         }
1181         sig_data->uid = from_kuid(&init_user_ns, audit_sig_uid);
1182         sig_data->pid = audit_sig_pid;
1183         if (audit_sig_sid) {
1184             memcpy(sig_data->ctx, ctx, len);
1185             security_release_secctx(ctx, len);
1186         }
1187         audit_send_reply(skb, seq, AUDIT_SIGNAL_INFO, 0, 0,
1188                  sig_data, sizeof(*sig_data) + len);
1189         kfree(sig_data);
1190         break;
1191     case AUDIT_TTY_GET: {
1192         struct audit_tty_status s;
1193         unsigned int t;
1194 
1195         t = READ_ONCE(current->signal->audit_tty);
1196         s.enabled = t & AUDIT_TTY_ENABLE;
1197         s.log_passwd = !!(t & AUDIT_TTY_LOG_PASSWD);
1198 
1199         audit_send_reply(skb, seq, AUDIT_TTY_GET, 0, 0, &s, sizeof(s));
1200         break;
1201     }
1202     case AUDIT_TTY_SET: {
1203         struct audit_tty_status s, old;
1204         struct audit_buffer *ab;
1205         unsigned int t;
1206 
1207         memset(&s, 0, sizeof(s));
1208         /* guard against past and future API changes */
1209         memcpy(&s, data, min_t(size_t, sizeof(s), nlmsg_len(nlh)));
1210         /* check if new data is valid */
1211         if ((s.enabled != 0 && s.enabled != 1) ||
1212             (s.log_passwd != 0 && s.log_passwd != 1))
1213             err = -EINVAL;
1214 
1215         if (err)
1216             t = READ_ONCE(current->signal->audit_tty);
1217         else {
1218             t = s.enabled | (-s.log_passwd & AUDIT_TTY_LOG_PASSWD);
1219             t = xchg(&current->signal->audit_tty, t);
1220         }
1221         old.enabled = t & AUDIT_TTY_ENABLE;
1222         old.log_passwd = !!(t & AUDIT_TTY_LOG_PASSWD);
1223 
1224         audit_log_common_recv_msg(&ab, AUDIT_CONFIG_CHANGE);
1225         audit_log_format(ab, " op=tty_set old-enabled=%d new-enabled=%d"
1226                  " old-log_passwd=%d new-log_passwd=%d res=%d",
1227                  old.enabled, s.enabled, old.log_passwd,
1228                  s.log_passwd, !err);
1229         audit_log_end(ab);
1230         break;
1231     }
1232     default:
1233         err = -EINVAL;
1234         break;
1235     }
1236 
1237     return err < 0 ? err : 0;
1238 }
1239 
1240 /*
1241  * Get message from skb.  Each message is processed by audit_receive_msg.
1242  * Malformed skbs with wrong length are discarded silently.
1243  */
1244 static void audit_receive_skb(struct sk_buff *skb)
1245 {
1246     struct nlmsghdr *nlh;
1247     /*
1248      * len MUST be signed for nlmsg_next to be able to dec it below 0
1249      * if the nlmsg_len was not aligned
1250      */
1251     int len;
1252     int err;
1253 
1254     nlh = nlmsg_hdr(skb);
1255     len = skb->len;
1256 
1257     while (nlmsg_ok(nlh, len)) {
1258         err = audit_receive_msg(skb, nlh);
1259         /* if err or if this message says it wants a response */
1260         if (err || (nlh->nlmsg_flags & NLM_F_ACK))
1261             netlink_ack(skb, nlh, err);
1262 
1263         nlh = nlmsg_next(nlh, &len);
1264     }
1265 }
1266 
1267 /* Receive messages from netlink socket. */
1268 static void audit_receive(struct sk_buff  *skb)
1269 {
1270     mutex_lock(&audit_cmd_mutex);
1271     audit_receive_skb(skb);
1272     mutex_unlock(&audit_cmd_mutex);
1273 }
1274 
1275 /* Run custom bind function on netlink socket group connect or bind requests. */
1276 static int audit_bind(struct net *net, int group)
1277 {
1278     if (!capable(CAP_AUDIT_READ))
1279         return -EPERM;
1280 
1281     return 0;
1282 }
1283 
1284 static int __net_init audit_net_init(struct net *net)
1285 {
1286     struct netlink_kernel_cfg cfg = {
1287         .input  = audit_receive,
1288         .bind   = audit_bind,
1289         .flags  = NL_CFG_F_NONROOT_RECV,
1290         .groups = AUDIT_NLGRP_MAX,
1291     };
1292 
1293     struct audit_net *aunet = net_generic(net, audit_net_id);
1294 
1295     aunet->nlsk = netlink_kernel_create(net, NETLINK_AUDIT, &cfg);
1296     if (aunet->nlsk == NULL) {
1297         audit_panic("cannot initialize netlink socket in namespace");
1298         return -ENOMEM;
1299     }
1300     aunet->nlsk->sk_sndtimeo = MAX_SCHEDULE_TIMEOUT;
1301     return 0;
1302 }
1303 
1304 static void __net_exit audit_net_exit(struct net *net)
1305 {
1306     struct audit_net *aunet = net_generic(net, audit_net_id);
1307     struct sock *sock = aunet->nlsk;
1308     mutex_lock(&audit_cmd_mutex);
1309     if (sock == audit_sock)
1310         auditd_reset();
1311     mutex_unlock(&audit_cmd_mutex);
1312 
1313     netlink_kernel_release(sock);
1314     aunet->nlsk = NULL;
1315 }
1316 
1317 static struct pernet_operations audit_net_ops __net_initdata = {
1318     .init = audit_net_init,
1319     .exit = audit_net_exit,
1320     .id = &audit_net_id,
1321     .size = sizeof(struct audit_net),
1322 };
1323 
1324 /* Initialize audit support at boot time. */
1325 static int __init audit_init(void)
1326 {
1327     int i;
1328 
1329     if (audit_initialized == AUDIT_DISABLED)
1330         return 0;
1331 
1332     pr_info("initializing netlink subsys (%s)\n",
1333         audit_default ? "enabled" : "disabled");
1334     register_pernet_subsys(&audit_net_ops);
1335 
1336     skb_queue_head_init(&audit_queue);
1337     skb_queue_head_init(&audit_retry_queue);
1338     skb_queue_head_init(&audit_hold_queue);
1339     audit_initialized = AUDIT_INITIALIZED;
1340     audit_enabled = audit_default;
1341     audit_ever_enabled |= !!audit_default;
1342 
1343     for (i = 0; i < AUDIT_INODE_BUCKETS; i++)
1344         INIT_LIST_HEAD(&audit_inode_hash[i]);
1345 
1346     kauditd_task = kthread_run(kauditd_thread, NULL, "kauditd");
1347     if (IS_ERR(kauditd_task)) {
1348         int err = PTR_ERR(kauditd_task);
1349         panic("audit: failed to start the kauditd thread (%d)\n", err);
1350     }
1351 
1352     audit_log(NULL, GFP_KERNEL, AUDIT_KERNEL, "initialized");
1353 
1354     return 0;
1355 }
1356 __initcall(audit_init);
1357 
1358 /* Process kernel command-line parameter at boot time.  audit=0 or audit=1. */
1359 static int __init audit_enable(char *str)
1360 {
1361     audit_default = !!simple_strtol(str, NULL, 0);
1362     if (!audit_default)
1363         audit_initialized = AUDIT_DISABLED;
1364 
1365     pr_info("%s\n", audit_default ?
1366         "enabled (after initialization)" : "disabled (until reboot)");
1367 
1368     return 1;
1369 }
1370 __setup("audit=", audit_enable);
1371 
1372 /* Process kernel command-line parameter at boot time.
1373  * audit_backlog_limit=<n> */
1374 static int __init audit_backlog_limit_set(char *str)
1375 {
1376     u32 audit_backlog_limit_arg;
1377 
1378     pr_info("audit_backlog_limit: ");
1379     if (kstrtouint(str, 0, &audit_backlog_limit_arg)) {
1380         pr_cont("using default of %u, unable to parse %s\n",
1381             audit_backlog_limit, str);
1382         return 1;
1383     }
1384 
1385     audit_backlog_limit = audit_backlog_limit_arg;
1386     pr_cont("%d\n", audit_backlog_limit);
1387 
1388     return 1;
1389 }
1390 __setup("audit_backlog_limit=", audit_backlog_limit_set);
1391 
1392 static void audit_buffer_free(struct audit_buffer *ab)
1393 {
1394     unsigned long flags;
1395 
1396     if (!ab)
1397         return;
1398 
1399     kfree_skb(ab->skb);
1400     spin_lock_irqsave(&audit_freelist_lock, flags);
1401     if (audit_freelist_count > AUDIT_MAXFREE)
1402         kfree(ab);
1403     else {
1404         audit_freelist_count++;
1405         list_add(&ab->list, &audit_freelist);
1406     }
1407     spin_unlock_irqrestore(&audit_freelist_lock, flags);
1408 }
1409 
1410 static struct audit_buffer * audit_buffer_alloc(struct audit_context *ctx,
1411                         gfp_t gfp_mask, int type)
1412 {
1413     unsigned long flags;
1414     struct audit_buffer *ab = NULL;
1415     struct nlmsghdr *nlh;
1416 
1417     spin_lock_irqsave(&audit_freelist_lock, flags);
1418     if (!list_empty(&audit_freelist)) {
1419         ab = list_entry(audit_freelist.next,
1420                 struct audit_buffer, list);
1421         list_del(&ab->list);
1422         --audit_freelist_count;
1423     }
1424     spin_unlock_irqrestore(&audit_freelist_lock, flags);
1425 
1426     if (!ab) {
1427         ab = kmalloc(sizeof(*ab), gfp_mask);
1428         if (!ab)
1429             goto err;
1430     }
1431 
1432     ab->ctx = ctx;
1433     ab->gfp_mask = gfp_mask;
1434 
1435     ab->skb = nlmsg_new(AUDIT_BUFSIZ, gfp_mask);
1436     if (!ab->skb)
1437         goto err;
1438 
1439     nlh = nlmsg_put(ab->skb, 0, 0, type, 0, 0);
1440     if (!nlh)
1441         goto out_kfree_skb;
1442 
1443     return ab;
1444 
1445 out_kfree_skb:
1446     kfree_skb(ab->skb);
1447     ab->skb = NULL;
1448 err:
1449     audit_buffer_free(ab);
1450     return NULL;
1451 }
1452 
1453 /**
1454  * audit_serial - compute a serial number for the audit record
1455  *
1456  * Compute a serial number for the audit record.  Audit records are
1457  * written to user-space as soon as they are generated, so a complete
1458  * audit record may be written in several pieces.  The timestamp of the
1459  * record and this serial number are used by the user-space tools to
1460  * determine which pieces belong to the same audit record.  The
1461  * (timestamp,serial) tuple is unique for each syscall and is live from
1462  * syscall entry to syscall exit.
1463  *
1464  * NOTE: Another possibility is to store the formatted records off the
1465  * audit context (for those records that have a context), and emit them
1466  * all at syscall exit.  However, this could delay the reporting of
1467  * significant errors until syscall exit (or never, if the system
1468  * halts).
1469  */
1470 unsigned int audit_serial(void)
1471 {
1472     static atomic_t serial = ATOMIC_INIT(0);
1473 
1474     return atomic_add_return(1, &serial);
1475 }
1476 
1477 static inline void audit_get_stamp(struct audit_context *ctx,
1478                    struct timespec *t, unsigned int *serial)
1479 {
1480     if (!ctx || !auditsc_get_stamp(ctx, t, serial)) {
1481         *t = CURRENT_TIME;
1482         *serial = audit_serial();
1483     }
1484 }
1485 
1486 /**
1487  * audit_log_start - obtain an audit buffer
1488  * @ctx: audit_context (may be NULL)
1489  * @gfp_mask: type of allocation
1490  * @type: audit message type
1491  *
1492  * Returns audit_buffer pointer on success or NULL on error.
1493  *
1494  * Obtain an audit buffer.  This routine does locking to obtain the
1495  * audit buffer, but then no locking is required for calls to
1496  * audit_log_*format.  If the task (ctx) is a task that is currently in a
1497  * syscall, then the syscall is marked as auditable and an audit record
1498  * will be written at syscall exit.  If there is no associated task, then
1499  * task context (ctx) should be NULL.
1500  */
1501 struct audit_buffer *audit_log_start(struct audit_context *ctx, gfp_t gfp_mask,
1502                      int type)
1503 {
1504     struct audit_buffer *ab;
1505     struct timespec t;
1506     unsigned int uninitialized_var(serial);
1507 
1508     if (audit_initialized != AUDIT_INITIALIZED)
1509         return NULL;
1510 
1511     if (unlikely(!audit_filter(type, AUDIT_FILTER_TYPE)))
1512         return NULL;
1513 
1514     /* don't ever fail/sleep on these two conditions:
1515      * 1. auditd generated record - since we need auditd to drain the
1516      *    queue; also, when we are checking for auditd, compare PIDs using
1517      *    task_tgid_vnr() since auditd_pid is set in audit_receive_msg()
1518      *    using a PID anchored in the caller's namespace
1519      * 2. audit command message - record types 1000 through 1099 inclusive
1520      *    are command messages/records used to manage the kernel subsystem
1521      *    and the audit userspace, blocking on these messages could cause
1522      *    problems under load so don't do it (note: not all of these
1523      *    command types are valid as record types, but it is quicker to
1524      *    just check two ints than a series of ints in a if/switch stmt) */
1525     if (!((audit_pid && audit_pid == task_tgid_vnr(current)) ||
1526           (type >= 1000 && type <= 1099))) {
1527         long sleep_time = audit_backlog_wait_time;
1528 
1529         while (audit_backlog_limit &&
1530                (skb_queue_len(&audit_queue) > audit_backlog_limit)) {
1531             /* wake kauditd to try and flush the queue */
1532             wake_up_interruptible(&kauditd_wait);
1533 
1534             /* sleep if we are allowed and we haven't exhausted our
1535              * backlog wait limit */
1536             if ((gfp_mask & __GFP_DIRECT_RECLAIM) &&
1537                 (sleep_time > 0)) {
1538                 DECLARE_WAITQUEUE(wait, current);
1539 
1540                 add_wait_queue_exclusive(&audit_backlog_wait,
1541                              &wait);
1542                 set_current_state(TASK_UNINTERRUPTIBLE);
1543                 sleep_time = schedule_timeout(sleep_time);
1544                 remove_wait_queue(&audit_backlog_wait, &wait);
1545             } else {
1546                 if (audit_rate_check() && printk_ratelimit())
1547                     pr_warn("audit_backlog=%d > audit_backlog_limit=%d\n",
1548                         skb_queue_len(&audit_queue),
1549                         audit_backlog_limit);
1550                 audit_log_lost("backlog limit exceeded");
1551                 return NULL;
1552             }
1553         }
1554     }
1555 
1556     ab = audit_buffer_alloc(ctx, gfp_mask, type);
1557     if (!ab) {
1558         audit_log_lost("out of memory in audit_log_start");
1559         return NULL;
1560     }
1561 
1562     audit_get_stamp(ab->ctx, &t, &serial);
1563     audit_log_format(ab, "audit(%lu.%03lu:%u): ",
1564              t.tv_sec, t.tv_nsec/1000000, serial);
1565 
1566     return ab;
1567 }
1568 
1569 /**
1570  * audit_expand - expand skb in the audit buffer
1571  * @ab: audit_buffer
1572  * @extra: space to add at tail of the skb
1573  *
1574  * Returns 0 (no space) on failed expansion, or available space if
1575  * successful.
1576  */
1577 static inline int audit_expand(struct audit_buffer *ab, int extra)
1578 {
1579     struct sk_buff *skb = ab->skb;
1580     int oldtail = skb_tailroom(skb);
1581     int ret = pskb_expand_head(skb, 0, extra, ab->gfp_mask);
1582     int newtail = skb_tailroom(skb);
1583 
1584     if (ret < 0) {
1585         audit_log_lost("out of memory in audit_expand");
1586         return 0;
1587     }
1588 
1589     skb->truesize += newtail - oldtail;
1590     return newtail;
1591 }
1592 
1593 /*
1594  * Format an audit message into the audit buffer.  If there isn't enough
1595  * room in the audit buffer, more room will be allocated and vsnprint
1596  * will be called a second time.  Currently, we assume that a printk
1597  * can't format message larger than 1024 bytes, so we don't either.
1598  */
1599 static void audit_log_vformat(struct audit_buffer *ab, const char *fmt,
1600                   va_list args)
1601 {
1602     int len, avail;
1603     struct sk_buff *skb;
1604     va_list args2;
1605 
1606     if (!ab)
1607         return;
1608 
1609     BUG_ON(!ab->skb);
1610     skb = ab->skb;
1611     avail = skb_tailroom(skb);
1612     if (avail == 0) {
1613         avail = audit_expand(ab, AUDIT_BUFSIZ);
1614         if (!avail)
1615             goto out;
1616     }
1617     va_copy(args2, args);
1618     len = vsnprintf(skb_tail_pointer(skb), avail, fmt, args);
1619     if (len >= avail) {
1620         /* The printk buffer is 1024 bytes long, so if we get
1621          * here and AUDIT_BUFSIZ is at least 1024, then we can
1622          * log everything that printk could have logged. */
1623         avail = audit_expand(ab,
1624             max_t(unsigned, AUDIT_BUFSIZ, 1+len-avail));
1625         if (!avail)
1626             goto out_va_end;
1627         len = vsnprintf(skb_tail_pointer(skb), avail, fmt, args2);
1628     }
1629     if (len > 0)
1630         skb_put(skb, len);
1631 out_va_end:
1632     va_end(args2);
1633 out:
1634     return;
1635 }
1636 
1637 /**
1638  * audit_log_format - format a message into the audit buffer.
1639  * @ab: audit_buffer
1640  * @fmt: format string
1641  * @...: optional parameters matching @fmt string
1642  *
1643  * All the work is done in audit_log_vformat.
1644  */
1645 void audit_log_format(struct audit_buffer *ab, const char *fmt, ...)
1646 {
1647     va_list args;
1648 
1649     if (!ab)
1650         return;
1651     va_start(args, fmt);
1652     audit_log_vformat(ab, fmt, args);
1653     va_end(args);
1654 }
1655 
1656 /**
1657  * audit_log_hex - convert a buffer to hex and append it to the audit skb
1658  * @ab: the audit_buffer
1659  * @buf: buffer to convert to hex
1660  * @len: length of @buf to be converted
1661  *
1662  * No return value; failure to expand is silently ignored.
1663  *
1664  * This function will take the passed buf and convert it into a string of
1665  * ascii hex digits. The new string is placed onto the skb.
1666  */
1667 void audit_log_n_hex(struct audit_buffer *ab, const unsigned char *buf,
1668         size_t len)
1669 {
1670     int i, avail, new_len;
1671     unsigned char *ptr;
1672     struct sk_buff *skb;
1673 
1674     if (!ab)
1675         return;
1676 
1677     BUG_ON(!ab->skb);
1678     skb = ab->skb;
1679     avail = skb_tailroom(skb);
1680     new_len = len<<1;
1681     if (new_len >= avail) {
1682         /* Round the buffer request up to the next multiple */
1683         new_len = AUDIT_BUFSIZ*(((new_len-avail)/AUDIT_BUFSIZ) + 1);
1684         avail = audit_expand(ab, new_len);
1685         if (!avail)
1686             return;
1687     }
1688 
1689     ptr = skb_tail_pointer(skb);
1690     for (i = 0; i < len; i++)
1691         ptr = hex_byte_pack_upper(ptr, buf[i]);
1692     *ptr = 0;
1693     skb_put(skb, len << 1); /* new string is twice the old string */
1694 }
1695 
1696 /*
1697  * Format a string of no more than slen characters into the audit buffer,
1698  * enclosed in quote marks.
1699  */
1700 void audit_log_n_string(struct audit_buffer *ab, const char *string,
1701             size_t slen)
1702 {
1703     int avail, new_len;
1704     unsigned char *ptr;
1705     struct sk_buff *skb;
1706 
1707     if (!ab)
1708         return;
1709 
1710     BUG_ON(!ab->skb);
1711     skb = ab->skb;
1712     avail = skb_tailroom(skb);
1713     new_len = slen + 3; /* enclosing quotes + null terminator */
1714     if (new_len > avail) {
1715         avail = audit_expand(ab, new_len);
1716         if (!avail)
1717             return;
1718     }
1719     ptr = skb_tail_pointer(skb);
1720     *ptr++ = '"';
1721     memcpy(ptr, string, slen);
1722     ptr += slen;
1723     *ptr++ = '"';
1724     *ptr = 0;
1725     skb_put(skb, slen + 2); /* don't include null terminator */
1726 }
1727 
1728 /**
1729  * audit_string_contains_control - does a string need to be logged in hex
1730  * @string: string to be checked
1731  * @len: max length of the string to check
1732  */
1733 bool audit_string_contains_control(const char *string, size_t len)
1734 {
1735     const unsigned char *p;
1736     for (p = string; p < (const unsigned char *)string + len; p++) {
1737         if (*p == '"' || *p < 0x21 || *p > 0x7e)
1738             return true;
1739     }
1740     return false;
1741 }
1742 
1743 /**
1744  * audit_log_n_untrustedstring - log a string that may contain random characters
1745  * @ab: audit_buffer
1746  * @len: length of string (not including trailing null)
1747  * @string: string to be logged
1748  *
1749  * This code will escape a string that is passed to it if the string
1750  * contains a control character, unprintable character, double quote mark,
1751  * or a space. Unescaped strings will start and end with a double quote mark.
1752  * Strings that are escaped are printed in hex (2 digits per char).
1753  *
1754  * The caller specifies the number of characters in the string to log, which may
1755  * or may not be the entire string.
1756  */
1757 void audit_log_n_untrustedstring(struct audit_buffer *ab, const char *string,
1758                  size_t len)
1759 {
1760     if (audit_string_contains_control(string, len))
1761         audit_log_n_hex(ab, string, len);
1762     else
1763         audit_log_n_string(ab, string, len);
1764 }
1765 
1766 /**
1767  * audit_log_untrustedstring - log a string that may contain random characters
1768  * @ab: audit_buffer
1769  * @string: string to be logged
1770  *
1771  * Same as audit_log_n_untrustedstring(), except that strlen is used to
1772  * determine string length.
1773  */
1774 void audit_log_untrustedstring(struct audit_buffer *ab, const char *string)
1775 {
1776     audit_log_n_untrustedstring(ab, string, strlen(string));
1777 }
1778 
1779 /* This is a helper-function to print the escaped d_path */
1780 void audit_log_d_path(struct audit_buffer *ab, const char *prefix,
1781               const struct path *path)
1782 {
1783     char *p, *pathname;
1784 
1785     if (prefix)
1786         audit_log_format(ab, "%s", prefix);
1787 
1788     /* We will allow 11 spaces for ' (deleted)' to be appended */
1789     pathname = kmalloc(PATH_MAX+11, ab->gfp_mask);
1790     if (!pathname) {
1791         audit_log_string(ab, "<no_memory>");
1792         return;
1793     }
1794     p = d_path(path, pathname, PATH_MAX+11);
1795     if (IS_ERR(p)) { /* Should never happen since we send PATH_MAX */
1796         /* FIXME: can we save some information here? */
1797         audit_log_string(ab, "<too_long>");
1798     } else
1799         audit_log_untrustedstring(ab, p);
1800     kfree(pathname);
1801 }
1802 
1803 void audit_log_session_info(struct audit_buffer *ab)
1804 {
1805     unsigned int sessionid = audit_get_sessionid(current);
1806     uid_t auid = from_kuid(&init_user_ns, audit_get_loginuid(current));
1807 
1808     audit_log_format(ab, " auid=%u ses=%u", auid, sessionid);
1809 }
1810 
1811 void audit_log_key(struct audit_buffer *ab, char *key)
1812 {
1813     audit_log_format(ab, " key=");
1814     if (key)
1815         audit_log_untrustedstring(ab, key);
1816     else
1817         audit_log_format(ab, "(null)");
1818 }
1819 
1820 void audit_log_cap(struct audit_buffer *ab, char *prefix, kernel_cap_t *cap)
1821 {
1822     int i;
1823 
1824     audit_log_format(ab, " %s=", prefix);
1825     CAP_FOR_EACH_U32(i) {
1826         audit_log_format(ab, "%08x",
1827                  cap->cap[CAP_LAST_U32 - i]);
1828     }
1829 }
1830 
1831 static void audit_log_fcaps(struct audit_buffer *ab, struct audit_names *name)
1832 {
1833     kernel_cap_t *perm = &name->fcap.permitted;
1834     kernel_cap_t *inh = &name->fcap.inheritable;
1835     int log = 0;
1836 
1837     if (!cap_isclear(*perm)) {
1838         audit_log_cap(ab, "cap_fp", perm);
1839         log = 1;
1840     }
1841     if (!cap_isclear(*inh)) {
1842         audit_log_cap(ab, "cap_fi", inh);
1843         log = 1;
1844     }
1845 
1846     if (log)
1847         audit_log_format(ab, " cap_fe=%d cap_fver=%x",
1848                  name->fcap.fE, name->fcap_ver);
1849 }
1850 
1851 static inline int audit_copy_fcaps(struct audit_names *name,
1852                    const struct dentry *dentry)
1853 {
1854     struct cpu_vfs_cap_data caps;
1855     int rc;
1856 
1857     if (!dentry)
1858         return 0;
1859 
1860     rc = get_vfs_caps_from_disk(dentry, &caps);
1861     if (rc)
1862         return rc;
1863 
1864     name->fcap.permitted = caps.permitted;
1865     name->fcap.inheritable = caps.inheritable;
1866     name->fcap.fE = !!(caps.magic_etc & VFS_CAP_FLAGS_EFFECTIVE);
1867     name->fcap_ver = (caps.magic_etc & VFS_CAP_REVISION_MASK) >>
1868                 VFS_CAP_REVISION_SHIFT;
1869 
1870     return 0;
1871 }
1872 
1873 /* Copy inode data into an audit_names. */
1874 void audit_copy_inode(struct audit_names *name, const struct dentry *dentry,
1875               struct inode *inode)
1876 {
1877     name->ino   = inode->i_ino;
1878     name->dev   = inode->i_sb->s_dev;
1879     name->mode  = inode->i_mode;
1880     name->uid   = inode->i_uid;
1881     name->gid   = inode->i_gid;
1882     name->rdev  = inode->i_rdev;
1883     security_inode_getsecid(inode, &name->osid);
1884     audit_copy_fcaps(name, dentry);
1885 }
1886 
1887 /**
1888  * audit_log_name - produce AUDIT_PATH record from struct audit_names
1889  * @context: audit_context for the task
1890  * @n: audit_names structure with reportable details
1891  * @path: optional path to report instead of audit_names->name
1892  * @record_num: record number to report when handling a list of names
1893  * @call_panic: optional pointer to int that will be updated if secid fails
1894  */
1895 void audit_log_name(struct audit_context *context, struct audit_names *n,
1896             const struct path *path, int record_num, int *call_panic)
1897 {
1898     struct audit_buffer *ab;
1899     ab = audit_log_start(context, GFP_KERNEL, AUDIT_PATH);
1900     if (!ab)
1901         return;
1902 
1903     audit_log_format(ab, "item=%d", record_num);
1904 
1905     if (path)
1906         audit_log_d_path(ab, " name=", path);
1907     else if (n->name) {
1908         switch (n->name_len) {
1909         case AUDIT_NAME_FULL:
1910             /* log the full path */
1911             audit_log_format(ab, " name=");
1912             audit_log_untrustedstring(ab, n->name->name);
1913             break;
1914         case 0:
1915             /* name was specified as a relative path and the
1916              * directory component is the cwd */
1917             audit_log_d_path(ab, " name=", &context->pwd);
1918             break;
1919         default:
1920             /* log the name's directory component */
1921             audit_log_format(ab, " name=");
1922             audit_log_n_untrustedstring(ab, n->name->name,
1923                             n->name_len);
1924         }
1925     } else
1926         audit_log_format(ab, " name=(null)");
1927 
1928     if (n->ino != AUDIT_INO_UNSET)
1929         audit_log_format(ab, " inode=%lu"
1930                  " dev=%02x:%02x mode=%#ho"
1931                  " ouid=%u ogid=%u rdev=%02x:%02x",
1932                  n->ino,
1933                  MAJOR(n->dev),
1934                  MINOR(n->dev),
1935                  n->mode,
1936                  from_kuid(&init_user_ns, n->uid),
1937                  from_kgid(&init_user_ns, n->gid),
1938                  MAJOR(n->rdev),
1939                  MINOR(n->rdev));
1940     if (n->osid != 0) {
1941         char *ctx = NULL;
1942         u32 len;
1943         if (security_secid_to_secctx(
1944             n->osid, &ctx, &len)) {
1945             audit_log_format(ab, " osid=%u", n->osid);
1946             if (call_panic)
1947                 *call_panic = 2;
1948         } else {
1949             audit_log_format(ab, " obj=%s", ctx);
1950             security_release_secctx(ctx, len);
1951         }
1952     }
1953 
1954     /* log the audit_names record type */
1955     audit_log_format(ab, " nametype=");
1956     switch(n->type) {
1957     case AUDIT_TYPE_NORMAL:
1958         audit_log_format(ab, "NORMAL");
1959         break;
1960     case AUDIT_TYPE_PARENT:
1961         audit_log_format(ab, "PARENT");
1962         break;
1963     case AUDIT_TYPE_CHILD_DELETE:
1964         audit_log_format(ab, "DELETE");
1965         break;
1966     case AUDIT_TYPE_CHILD_CREATE:
1967         audit_log_format(ab, "CREATE");
1968         break;
1969     default:
1970         audit_log_format(ab, "UNKNOWN");
1971         break;
1972     }
1973 
1974     audit_log_fcaps(ab, n);
1975     audit_log_end(ab);
1976 }
1977 
1978 int audit_log_task_context(struct audit_buffer *ab)
1979 {
1980     char *ctx = NULL;
1981     unsigned len;
1982     int error;
1983     u32 sid;
1984 
1985     security_task_getsecid(current, &sid);
1986     if (!sid)
1987         return 0;
1988 
1989     error = security_secid_to_secctx(sid, &ctx, &len);
1990     if (error) {
1991         if (error != -EINVAL)
1992             goto error_path;
1993         return 0;
1994     }
1995 
1996     audit_log_format(ab, " subj=%s", ctx);
1997     security_release_secctx(ctx, len);
1998     return 0;
1999 
2000 error_path:
2001     audit_panic("error in audit_log_task_context");
2002     return error;
2003 }
2004 EXPORT_SYMBOL(audit_log_task_context);
2005 
2006 void audit_log_d_path_exe(struct audit_buffer *ab,
2007               struct mm_struct *mm)
2008 {
2009     struct file *exe_file;
2010 
2011     if (!mm)
2012         goto out_null;
2013 
2014     exe_file = get_mm_exe_file(mm);
2015     if (!exe_file)
2016         goto out_null;
2017 
2018     audit_log_d_path(ab, " exe=", &exe_file->f_path);
2019     fput(exe_file);
2020     return;
2021 out_null:
2022     audit_log_format(ab, " exe=(null)");
2023 }
2024 
2025 struct tty_struct *audit_get_tty(struct task_struct *tsk)
2026 {
2027     struct tty_struct *tty = NULL;
2028     unsigned long flags;
2029 
2030     spin_lock_irqsave(&tsk->sighand->siglock, flags);
2031     if (tsk->signal)
2032         tty = tty_kref_get(tsk->signal->tty);
2033     spin_unlock_irqrestore(&tsk->sighand->siglock, flags);
2034     return tty;
2035 }
2036 
2037 void audit_put_tty(struct tty_struct *tty)
2038 {
2039     tty_kref_put(tty);
2040 }
2041 
2042 void audit_log_task_info(struct audit_buffer *ab, struct task_struct *tsk)
2043 {
2044     const struct cred *cred;
2045     char comm[sizeof(tsk->comm)];
2046     struct tty_struct *tty;
2047 
2048     if (!ab)
2049         return;
2050 
2051     /* tsk == current */
2052     cred = current_cred();
2053     tty = audit_get_tty(tsk);
2054     audit_log_format(ab,
2055              " ppid=%d pid=%d auid=%u uid=%u gid=%u"
2056              " euid=%u suid=%u fsuid=%u"
2057              " egid=%u sgid=%u fsgid=%u tty=%s ses=%u",
2058              task_ppid_nr(tsk),
2059              task_tgid_nr(tsk),
2060              from_kuid(&init_user_ns, audit_get_loginuid(tsk)),
2061              from_kuid(&init_user_ns, cred->uid),
2062              from_kgid(&init_user_ns, cred->gid),
2063              from_kuid(&init_user_ns, cred->euid),
2064              from_kuid(&init_user_ns, cred->suid),
2065              from_kuid(&init_user_ns, cred->fsuid),
2066              from_kgid(&init_user_ns, cred->egid),
2067              from_kgid(&init_user_ns, cred->sgid),
2068              from_kgid(&init_user_ns, cred->fsgid),
2069              tty ? tty_name(tty) : "(none)",
2070              audit_get_sessionid(tsk));
2071     audit_put_tty(tty);
2072     audit_log_format(ab, " comm=");
2073     audit_log_untrustedstring(ab, get_task_comm(comm, tsk));
2074     audit_log_d_path_exe(ab, tsk->mm);
2075     audit_log_task_context(ab);
2076 }
2077 EXPORT_SYMBOL(audit_log_task_info);
2078 
2079 /**
2080  * audit_log_link_denied - report a link restriction denial
2081  * @operation: specific link operation
2082  * @link: the path that triggered the restriction
2083  */
2084 void audit_log_link_denied(const char *operation, const struct path *link)
2085 {
2086     struct audit_buffer *ab;
2087     struct audit_names *name;
2088 
2089     name = kzalloc(sizeof(*name), GFP_NOFS);
2090     if (!name)
2091         return;
2092 
2093     /* Generate AUDIT_ANOM_LINK with subject, operation, outcome. */
2094     ab = audit_log_start(current->audit_context, GFP_KERNEL,
2095                  AUDIT_ANOM_LINK);
2096     if (!ab)
2097         goto out;
2098     audit_log_format(ab, "op=%s", operation);
2099     audit_log_task_info(ab, current);
2100     audit_log_format(ab, " res=0");
2101     audit_log_end(ab);
2102 
2103     /* Generate AUDIT_PATH record with object. */
2104     name->type = AUDIT_TYPE_NORMAL;
2105     audit_copy_inode(name, link->dentry, d_backing_inode(link->dentry));
2106     audit_log_name(current->audit_context, name, link, 0, NULL);
2107 out:
2108     kfree(name);
2109 }
2110 
2111 /**
2112  * audit_log_end - end one audit record
2113  * @ab: the audit_buffer
2114  *
2115  * We can not do a netlink send inside an irq context because it blocks (last
2116  * arg, flags, is not set to MSG_DONTWAIT), so the audit buffer is placed on a
2117  * queue and a tasklet is scheduled to remove them from the queue outside the
2118  * irq context.  May be called in any context.
2119  */
2120 void audit_log_end(struct audit_buffer *ab)
2121 {
2122     if (!ab)
2123         return;
2124     if (!audit_rate_check()) {
2125         audit_log_lost("rate limit exceeded");
2126     } else {
2127         skb_queue_tail(&audit_queue, ab->skb);
2128         wake_up_interruptible(&kauditd_wait);
2129         ab->skb = NULL;
2130     }
2131     audit_buffer_free(ab);
2132 }
2133 
2134 /**
2135  * audit_log - Log an audit record
2136  * @ctx: audit context
2137  * @gfp_mask: type of allocation
2138  * @type: audit message type
2139  * @fmt: format string to use
2140  * @...: variable parameters matching the format string
2141  *
2142  * This is a convenience function that calls audit_log_start,
2143  * audit_log_vformat, and audit_log_end.  It may be called
2144  * in any context.
2145  */
2146 void audit_log(struct audit_context *ctx, gfp_t gfp_mask, int type,
2147            const char *fmt, ...)
2148 {
2149     struct audit_buffer *ab;
2150     va_list args;
2151 
2152     ab = audit_log_start(ctx, gfp_mask, type);
2153     if (ab) {
2154         va_start(args, fmt);
2155         audit_log_vformat(ab, fmt, args);
2156         va_end(args);
2157         audit_log_end(ab);
2158     }
2159 }
2160 
2161 #ifdef CONFIG_SECURITY
2162 /**
2163  * audit_log_secctx - Converts and logs SELinux context
2164  * @ab: audit_buffer
2165  * @secid: security number
2166  *
2167  * This is a helper function that calls security_secid_to_secctx to convert
2168  * secid to secctx and then adds the (converted) SELinux context to the audit
2169  * log by calling audit_log_format, thus also preventing leak of internal secid
2170  * to userspace. If secid cannot be converted audit_panic is called.
2171  */
2172 void audit_log_secctx(struct audit_buffer *ab, u32 secid)
2173 {
2174     u32 len;
2175     char *secctx;
2176 
2177     if (security_secid_to_secctx(secid, &secctx, &len)) {
2178         audit_panic("Cannot convert secid to context");
2179     } else {
2180         audit_log_format(ab, " obj=%s", secctx);
2181         security_release_secctx(secctx, len);
2182     }
2183 }
2184 EXPORT_SYMBOL(audit_log_secctx);
2185 #endif
2186 
2187 EXPORT_SYMBOL(audit_log_start);
2188 EXPORT_SYMBOL(audit_log_end);
2189 EXPORT_SYMBOL(audit_log_format);
2190 EXPORT_SYMBOL(audit_log);