audit.c 65 KB

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