audit.c 62 KB

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