audit.c 65 KB

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