audit.c 65 KB

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