audit.c 44 KB

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