audit.c 62 KB

12345678910111213141516171819202122232425262728293031323334353637383940414243444546474849505152535455565758596061626364656667686970717273747576777879808182838485868788899091929394959697989910010110210310410510610710810911011111211311411511611711811912012112212312412512612712812913013113213313413513613713813914014114214314414514614714814915015115215315415515615715815916016116216316416516616716816917017117217317417517617717817918018118218318418518618718818919019119219319419519619719819920020120220320420520620720820921021121221321421521621721821922022122222322422522622722822923023123223323423523623723823924024124224324424524624724824925025125225325425525625725825926026126226326426526626726826927027127227327427527627727827928028128228328428528628728828929029129229329429529629729829930030130230330430530630730830931031131231331431531631731831932032132232332432532632732832933033133233333433533633733833934034134234334434534634734834935035135235335435535635735835936036136236336436536636736836937037137237337437537637737837938038138238338438538638738838939039139239339439539639739839940040140240340440540640740840941041141241341441541641741841942042142242342442542642742842943043143243343443543643743843944044144244344444544644744844945045145245345445545645745845946046146246346446546646746846947047147247347447547647747847948048148248348448548648748848949049149249349449549649749849950050150250350450550650750850951051151251351451551651751851952052152252352452552652752852953053153253353453553653753853954054154254354454554654754854955055155255355455555655755855956056156256356456556656756856957057157257357457557657757857958058158258358458558658758858959059159259359459559659759859960060160260360460560660760860961061161261361461561661761861962062162262362462562662762862963063163263363463563663763863964064164264364464564664764864965065165265365465565665765865966066166266366466566666766866967067167267367467567667767867968068168268368468568668768868969069169269369469569669769869970070170270370470570670770870971071171271371471571671771871972072172272372472572672772872973073173273373473573673773873974074174274374474574674774874975075175275375475575675775875976076176276376476576676776876977077177277377477577677777877978078178278378478578678778878979079179279379479579679779879980080180280380480580680780880981081181281381481581681781881982082182282382482582682782882983083183283383483583683783883984084184284384484584684784884985085185285385485585685785885986086186286386486586686786886987087187287387487587687787887988088188288388488588688788888989089189289389489589689789889990090190290390490590690790890991091191291391491591691791891992092192292392492592692792892993093193293393493593693793893994094194294394494594694794894995095195295395495595695795895996096196296396496596696796896997097197297397497597697797897998098198298398498598698798898999099199299399499599699799899910001001100210031004100510061007100810091010101110121013101410151016101710181019102010211022102310241025102610271028102910301031103210331034103510361037103810391040104110421043104410451046104710481049105010511052105310541055105610571058105910601061106210631064106510661067106810691070107110721073107410751076107710781079108010811082108310841085108610871088108910901091109210931094109510961097109810991100110111021103110411051106110711081109111011111112111311141115111611171118111911201121112211231124112511261127112811291130113111321133113411351136113711381139114011411142114311441145114611471148114911501151115211531154115511561157115811591160116111621163116411651166116711681169117011711172117311741175117611771178117911801181118211831184118511861187118811891190119111921193119411951196119711981199120012011202120312041205120612071208120912101211121212131214121512161217121812191220122112221223122412251226122712281229123012311232123312341235123612371238123912401241124212431244124512461247124812491250125112521253125412551256125712581259126012611262126312641265126612671268126912701271127212731274127512761277127812791280128112821283128412851286128712881289129012911292129312941295129612971298129913001301130213031304130513061307130813091310131113121313131413151316131713181319132013211322132313241325132613271328132913301331133213331334133513361337133813391340134113421343134413451346134713481349135013511352135313541355135613571358135913601361136213631364136513661367136813691370137113721373137413751376137713781379138013811382138313841385138613871388138913901391139213931394139513961397139813991400140114021403140414051406140714081409141014111412141314141415141614171418141914201421142214231424142514261427142814291430143114321433143414351436143714381439144014411442144314441445144614471448144914501451145214531454145514561457145814591460146114621463146414651466146714681469147014711472147314741475147614771478147914801481148214831484148514861487148814891490149114921493149414951496149714981499150015011502150315041505150615071508150915101511151215131514151515161517151815191520152115221523152415251526152715281529153015311532153315341535153615371538153915401541154215431544154515461547154815491550155115521553155415551556155715581559156015611562156315641565156615671568156915701571157215731574157515761577157815791580158115821583158415851586158715881589159015911592159315941595159615971598159916001601160216031604160516061607160816091610161116121613161416151616161716181619162016211622162316241625162616271628162916301631163216331634163516361637163816391640164116421643164416451646164716481649165016511652165316541655165616571658165916601661166216631664166516661667166816691670167116721673167416751676167716781679168016811682168316841685168616871688168916901691169216931694169516961697169816991700170117021703170417051706170717081709171017111712171317141715171617171718171917201721172217231724172517261727172817291730173117321733173417351736173717381739174017411742174317441745174617471748174917501751175217531754175517561757175817591760176117621763176417651766176717681769177017711772177317741775177617771778177917801781178217831784178517861787178817891790179117921793179417951796179717981799180018011802180318041805180618071808180918101811181218131814181518161817181818191820182118221823182418251826182718281829183018311832183318341835183618371838183918401841184218431844184518461847184818491850185118521853185418551856185718581859186018611862186318641865186618671868186918701871187218731874187518761877187818791880188118821883188418851886188718881889189018911892189318941895189618971898189919001901190219031904190519061907190819091910191119121913191419151916191719181919192019211922192319241925192619271928192919301931193219331934193519361937193819391940194119421943194419451946194719481949195019511952195319541955195619571958195919601961196219631964196519661967196819691970197119721973197419751976197719781979198019811982198319841985198619871988198919901991199219931994199519961997199819992000200120022003200420052006200720082009201020112012201320142015201620172018201920202021202220232024202520262027202820292030203120322033203420352036203720382039204020412042204320442045204620472048204920502051205220532054205520562057205820592060206120622063206420652066206720682069207020712072207320742075207620772078207920802081208220832084208520862087208820892090209120922093209420952096209720982099210021012102210321042105210621072108210921102111211221132114211521162117211821192120212121222123212421252126212721282129213021312132213321342135213621372138213921402141214221432144214521462147214821492150215121522153215421552156215721582159216021612162216321642165216621672168216921702171217221732174217521762177217821792180218121822183218421852186218721882189219021912192219321942195219621972198219922002201220222032204220522062207220822092210221122122213221422152216221722182219222022212222222322242225222622272228222922302231223222332234223522362237223822392240224122422243224422452246224722482249225022512252225322542255225622572258225922602261226222632264226522662267226822692270227122722273227422752276227722782279228022812282228322842285228622872288228922902291229222932294229522962297229822992300230123022303230423052306230723082309231023112312231323142315231623172318231923202321232223232324232523262327232823292330233123322333233423352336233723382339234023412342234323442345234623472348234923502351235223532354235523562357235823592360236123622363236423652366236723682369
  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. kfree_skb(skb);
  560. rc = -ECONNREFUSED;
  561. goto err;
  562. }
  563. net = get_net(ac->net);
  564. sk = audit_get_sk(net);
  565. portid = ac->portid;
  566. rcu_read_unlock();
  567. rc = netlink_unicast(sk, skb, portid, 0);
  568. put_net(net);
  569. if (rc < 0)
  570. goto err;
  571. return rc;
  572. err:
  573. if (ac && rc == -ECONNREFUSED)
  574. auditd_reset(ac);
  575. return rc;
  576. }
  577. /**
  578. * kauditd_send_queue - Helper for kauditd_thread to flush skb queues
  579. * @sk: the sending sock
  580. * @portid: the netlink destination
  581. * @queue: the skb queue to process
  582. * @retry_limit: limit on number of netlink unicast failures
  583. * @skb_hook: per-skb hook for additional processing
  584. * @err_hook: hook called if the skb fails the netlink unicast send
  585. *
  586. * Description:
  587. * Run through the given queue and attempt to send the audit records to auditd,
  588. * returns zero on success, negative values on failure. It is up to the caller
  589. * to ensure that the @sk is valid for the duration of this function.
  590. *
  591. */
  592. static int kauditd_send_queue(struct sock *sk, u32 portid,
  593. struct sk_buff_head *queue,
  594. unsigned int retry_limit,
  595. void (*skb_hook)(struct sk_buff *skb),
  596. void (*err_hook)(struct sk_buff *skb))
  597. {
  598. int rc = 0;
  599. struct sk_buff *skb;
  600. static unsigned int failed = 0;
  601. /* NOTE: kauditd_thread takes care of all our locking, we just use
  602. * the netlink info passed to us (e.g. sk and portid) */
  603. while ((skb = skb_dequeue(queue))) {
  604. /* call the skb_hook for each skb we touch */
  605. if (skb_hook)
  606. (*skb_hook)(skb);
  607. /* can we send to anyone via unicast? */
  608. if (!sk) {
  609. if (err_hook)
  610. (*err_hook)(skb);
  611. continue;
  612. }
  613. /* grab an extra skb reference in case of error */
  614. skb_get(skb);
  615. rc = netlink_unicast(sk, skb, portid, 0);
  616. if (rc < 0) {
  617. /* fatal failure for our queue flush attempt? */
  618. if (++failed >= retry_limit ||
  619. rc == -ECONNREFUSED || rc == -EPERM) {
  620. /* yes - error processing for the queue */
  621. sk = NULL;
  622. if (err_hook)
  623. (*err_hook)(skb);
  624. if (!skb_hook)
  625. goto out;
  626. /* keep processing with the skb_hook */
  627. continue;
  628. } else
  629. /* no - requeue to preserve ordering */
  630. skb_queue_head(queue, skb);
  631. } else {
  632. /* it worked - drop the extra reference and continue */
  633. consume_skb(skb);
  634. failed = 0;
  635. }
  636. }
  637. out:
  638. return (rc >= 0 ? 0 : rc);
  639. }
  640. /*
  641. * kauditd_send_multicast_skb - Send a record to any multicast listeners
  642. * @skb: audit record
  643. *
  644. * Description:
  645. * Write a multicast message to anyone listening in the initial network
  646. * namespace. This function doesn't consume an skb as might be expected since
  647. * it has to copy it anyways.
  648. */
  649. static void kauditd_send_multicast_skb(struct sk_buff *skb)
  650. {
  651. struct sk_buff *copy;
  652. struct sock *sock = audit_get_sk(&init_net);
  653. struct nlmsghdr *nlh;
  654. /* NOTE: we are not taking an additional reference for init_net since
  655. * we don't have to worry about it going away */
  656. if (!netlink_has_listeners(sock, AUDIT_NLGRP_READLOG))
  657. return;
  658. /*
  659. * The seemingly wasteful skb_copy() rather than bumping the refcount
  660. * using skb_get() is necessary because non-standard mods are made to
  661. * the skb by the original kaudit unicast socket send routine. The
  662. * existing auditd daemon assumes this breakage. Fixing this would
  663. * require co-ordinating a change in the established protocol between
  664. * the kaudit kernel subsystem and the auditd userspace code. There is
  665. * no reason for new multicast clients to continue with this
  666. * non-compliance.
  667. */
  668. copy = skb_copy(skb, GFP_KERNEL);
  669. if (!copy)
  670. return;
  671. nlh = nlmsg_hdr(copy);
  672. nlh->nlmsg_len = skb->len;
  673. nlmsg_multicast(sock, copy, 0, AUDIT_NLGRP_READLOG, GFP_KERNEL);
  674. }
  675. /**
  676. * kauditd_thread - Worker thread to send audit records to userspace
  677. * @dummy: unused
  678. */
  679. static int kauditd_thread(void *dummy)
  680. {
  681. int rc;
  682. u32 portid = 0;
  683. struct net *net = NULL;
  684. struct sock *sk = NULL;
  685. struct auditd_connection *ac;
  686. #define UNICAST_RETRIES 5
  687. set_freezable();
  688. while (!kthread_should_stop()) {
  689. /* NOTE: see the lock comments in auditd_send_unicast_skb() */
  690. rcu_read_lock();
  691. ac = rcu_dereference(auditd_conn);
  692. if (!ac) {
  693. rcu_read_unlock();
  694. goto main_queue;
  695. }
  696. net = get_net(ac->net);
  697. sk = audit_get_sk(net);
  698. portid = ac->portid;
  699. rcu_read_unlock();
  700. /* attempt to flush the hold queue */
  701. rc = kauditd_send_queue(sk, portid,
  702. &audit_hold_queue, UNICAST_RETRIES,
  703. NULL, kauditd_rehold_skb);
  704. if (ac && rc < 0) {
  705. sk = NULL;
  706. auditd_reset(ac);
  707. goto main_queue;
  708. }
  709. /* attempt to flush the retry queue */
  710. rc = kauditd_send_queue(sk, portid,
  711. &audit_retry_queue, UNICAST_RETRIES,
  712. NULL, kauditd_hold_skb);
  713. if (ac && rc < 0) {
  714. sk = NULL;
  715. auditd_reset(ac);
  716. goto main_queue;
  717. }
  718. main_queue:
  719. /* process the main queue - do the multicast send and attempt
  720. * unicast, dump failed record sends to the retry queue; if
  721. * sk == NULL due to previous failures we will just do the
  722. * multicast send and move the record to the hold queue */
  723. rc = kauditd_send_queue(sk, portid, &audit_queue, 1,
  724. kauditd_send_multicast_skb,
  725. (sk ?
  726. kauditd_retry_skb : kauditd_hold_skb));
  727. if (ac && rc < 0)
  728. auditd_reset(ac);
  729. sk = NULL;
  730. /* drop our netns reference, no auditd sends past this line */
  731. if (net) {
  732. put_net(net);
  733. net = NULL;
  734. }
  735. /* we have processed all the queues so wake everyone */
  736. wake_up(&audit_backlog_wait);
  737. /* NOTE: we want to wake up if there is anything on the queue,
  738. * regardless of if an auditd is connected, as we need to
  739. * do the multicast send and rotate records from the
  740. * main queue to the retry/hold queues */
  741. wait_event_freezable(kauditd_wait,
  742. (skb_queue_len(&audit_queue) ? 1 : 0));
  743. }
  744. return 0;
  745. }
  746. int audit_send_list(void *_dest)
  747. {
  748. struct audit_netlink_list *dest = _dest;
  749. struct sk_buff *skb;
  750. struct sock *sk = audit_get_sk(dest->net);
  751. /* wait for parent to finish and send an ACK */
  752. mutex_lock(&audit_cmd_mutex);
  753. mutex_unlock(&audit_cmd_mutex);
  754. while ((skb = __skb_dequeue(&dest->q)) != NULL)
  755. netlink_unicast(sk, skb, dest->portid, 0);
  756. put_net(dest->net);
  757. kfree(dest);
  758. return 0;
  759. }
  760. struct sk_buff *audit_make_reply(int seq, int type, int done,
  761. int multi, const void *payload, int size)
  762. {
  763. struct sk_buff *skb;
  764. struct nlmsghdr *nlh;
  765. void *data;
  766. int flags = multi ? NLM_F_MULTI : 0;
  767. int t = done ? NLMSG_DONE : type;
  768. skb = nlmsg_new(size, GFP_KERNEL);
  769. if (!skb)
  770. return NULL;
  771. nlh = nlmsg_put(skb, 0, seq, t, size, flags);
  772. if (!nlh)
  773. goto out_kfree_skb;
  774. data = nlmsg_data(nlh);
  775. memcpy(data, payload, size);
  776. return skb;
  777. out_kfree_skb:
  778. kfree_skb(skb);
  779. return NULL;
  780. }
  781. static int audit_send_reply_thread(void *arg)
  782. {
  783. struct audit_reply *reply = (struct audit_reply *)arg;
  784. struct sock *sk = audit_get_sk(reply->net);
  785. mutex_lock(&audit_cmd_mutex);
  786. mutex_unlock(&audit_cmd_mutex);
  787. /* Ignore failure. It'll only happen if the sender goes away,
  788. because our timeout is set to infinite. */
  789. netlink_unicast(sk, reply->skb, reply->portid, 0);
  790. put_net(reply->net);
  791. kfree(reply);
  792. return 0;
  793. }
  794. /**
  795. * audit_send_reply - send an audit reply message via netlink
  796. * @request_skb: skb of request we are replying to (used to target the reply)
  797. * @seq: sequence number
  798. * @type: audit message type
  799. * @done: done (last) flag
  800. * @multi: multi-part message flag
  801. * @payload: payload data
  802. * @size: payload size
  803. *
  804. * Allocates an skb, builds the netlink message, and sends it to the port id.
  805. * No failure notifications.
  806. */
  807. static void audit_send_reply(struct sk_buff *request_skb, int seq, int type, int done,
  808. int multi, const void *payload, int size)
  809. {
  810. struct net *net = sock_net(NETLINK_CB(request_skb).sk);
  811. struct sk_buff *skb;
  812. struct task_struct *tsk;
  813. struct audit_reply *reply = kmalloc(sizeof(struct audit_reply),
  814. GFP_KERNEL);
  815. if (!reply)
  816. return;
  817. skb = audit_make_reply(seq, type, done, multi, payload, size);
  818. if (!skb)
  819. goto out;
  820. reply->net = get_net(net);
  821. reply->portid = NETLINK_CB(request_skb).portid;
  822. reply->skb = skb;
  823. tsk = kthread_run(audit_send_reply_thread, reply, "audit_send_reply");
  824. if (!IS_ERR(tsk))
  825. return;
  826. kfree_skb(skb);
  827. out:
  828. kfree(reply);
  829. }
  830. /*
  831. * Check for appropriate CAP_AUDIT_ capabilities on incoming audit
  832. * control messages.
  833. */
  834. static int audit_netlink_ok(struct sk_buff *skb, u16 msg_type)
  835. {
  836. int err = 0;
  837. /* Only support initial user namespace for now. */
  838. /*
  839. * We return ECONNREFUSED because it tricks userspace into thinking
  840. * that audit was not configured into the kernel. Lots of users
  841. * configure their PAM stack (because that's what the distro does)
  842. * to reject login if unable to send messages to audit. If we return
  843. * ECONNREFUSED the PAM stack thinks the kernel does not have audit
  844. * configured in and will let login proceed. If we return EPERM
  845. * userspace will reject all logins. This should be removed when we
  846. * support non init namespaces!!
  847. */
  848. if (current_user_ns() != &init_user_ns)
  849. return -ECONNREFUSED;
  850. switch (msg_type) {
  851. case AUDIT_LIST:
  852. case AUDIT_ADD:
  853. case AUDIT_DEL:
  854. return -EOPNOTSUPP;
  855. case AUDIT_GET:
  856. case AUDIT_SET:
  857. case AUDIT_GET_FEATURE:
  858. case AUDIT_SET_FEATURE:
  859. case AUDIT_LIST_RULES:
  860. case AUDIT_ADD_RULE:
  861. case AUDIT_DEL_RULE:
  862. case AUDIT_SIGNAL_INFO:
  863. case AUDIT_TTY_GET:
  864. case AUDIT_TTY_SET:
  865. case AUDIT_TRIM:
  866. case AUDIT_MAKE_EQUIV:
  867. /* Only support auditd and auditctl in initial pid namespace
  868. * for now. */
  869. if (task_active_pid_ns(current) != &init_pid_ns)
  870. return -EPERM;
  871. if (!netlink_capable(skb, CAP_AUDIT_CONTROL))
  872. err = -EPERM;
  873. break;
  874. case AUDIT_USER:
  875. case AUDIT_FIRST_USER_MSG ... AUDIT_LAST_USER_MSG:
  876. case AUDIT_FIRST_USER_MSG2 ... AUDIT_LAST_USER_MSG2:
  877. if (!netlink_capable(skb, CAP_AUDIT_WRITE))
  878. err = -EPERM;
  879. break;
  880. default: /* bad msg */
  881. err = -EINVAL;
  882. }
  883. return err;
  884. }
  885. static void audit_log_common_recv_msg(struct audit_buffer **ab, u16 msg_type)
  886. {
  887. uid_t uid = from_kuid(&init_user_ns, current_uid());
  888. pid_t pid = task_tgid_nr(current);
  889. if (!audit_enabled && msg_type != AUDIT_USER_AVC) {
  890. *ab = NULL;
  891. return;
  892. }
  893. *ab = audit_log_start(NULL, GFP_KERNEL, msg_type);
  894. if (unlikely(!*ab))
  895. return;
  896. audit_log_format(*ab, "pid=%d uid=%u", pid, uid);
  897. audit_log_session_info(*ab);
  898. audit_log_task_context(*ab);
  899. }
  900. int is_audit_feature_set(int i)
  901. {
  902. return af.features & AUDIT_FEATURE_TO_MASK(i);
  903. }
  904. static int audit_get_feature(struct sk_buff *skb)
  905. {
  906. u32 seq;
  907. seq = nlmsg_hdr(skb)->nlmsg_seq;
  908. audit_send_reply(skb, seq, AUDIT_GET_FEATURE, 0, 0, &af, sizeof(af));
  909. return 0;
  910. }
  911. static void audit_log_feature_change(int which, u32 old_feature, u32 new_feature,
  912. u32 old_lock, u32 new_lock, int res)
  913. {
  914. struct audit_buffer *ab;
  915. if (audit_enabled == AUDIT_OFF)
  916. return;
  917. ab = audit_log_start(NULL, GFP_KERNEL, AUDIT_FEATURE_CHANGE);
  918. audit_log_task_info(ab, current);
  919. audit_log_format(ab, " feature=%s old=%u new=%u old_lock=%u new_lock=%u res=%d",
  920. audit_feature_names[which], !!old_feature, !!new_feature,
  921. !!old_lock, !!new_lock, res);
  922. audit_log_end(ab);
  923. }
  924. static int audit_set_feature(struct sk_buff *skb)
  925. {
  926. struct audit_features *uaf;
  927. int i;
  928. BUILD_BUG_ON(AUDIT_LAST_FEATURE + 1 > ARRAY_SIZE(audit_feature_names));
  929. uaf = nlmsg_data(nlmsg_hdr(skb));
  930. /* if there is ever a version 2 we should handle that here */
  931. for (i = 0; i <= AUDIT_LAST_FEATURE; i++) {
  932. u32 feature = AUDIT_FEATURE_TO_MASK(i);
  933. u32 old_feature, new_feature, old_lock, new_lock;
  934. /* if we are not changing this feature, move along */
  935. if (!(feature & uaf->mask))
  936. continue;
  937. old_feature = af.features & feature;
  938. new_feature = uaf->features & feature;
  939. new_lock = (uaf->lock | af.lock) & feature;
  940. old_lock = af.lock & feature;
  941. /* are we changing a locked feature? */
  942. if (old_lock && (new_feature != old_feature)) {
  943. audit_log_feature_change(i, old_feature, new_feature,
  944. old_lock, new_lock, 0);
  945. return -EPERM;
  946. }
  947. }
  948. /* nothing invalid, do the changes */
  949. for (i = 0; i <= AUDIT_LAST_FEATURE; i++) {
  950. u32 feature = AUDIT_FEATURE_TO_MASK(i);
  951. u32 old_feature, new_feature, old_lock, new_lock;
  952. /* if we are not changing this feature, move along */
  953. if (!(feature & uaf->mask))
  954. continue;
  955. old_feature = af.features & feature;
  956. new_feature = uaf->features & feature;
  957. old_lock = af.lock & feature;
  958. new_lock = (uaf->lock | af.lock) & feature;
  959. if (new_feature != old_feature)
  960. audit_log_feature_change(i, old_feature, new_feature,
  961. old_lock, new_lock, 1);
  962. if (new_feature)
  963. af.features |= feature;
  964. else
  965. af.features &= ~feature;
  966. af.lock |= new_lock;
  967. }
  968. return 0;
  969. }
  970. static int audit_replace(struct pid *pid)
  971. {
  972. pid_t pvnr;
  973. struct sk_buff *skb;
  974. pvnr = pid_vnr(pid);
  975. skb = audit_make_reply(0, AUDIT_REPLACE, 0, 0, &pvnr, sizeof(pvnr));
  976. if (!skb)
  977. return -ENOMEM;
  978. return auditd_send_unicast_skb(skb);
  979. }
  980. static int audit_receive_msg(struct sk_buff *skb, struct nlmsghdr *nlh)
  981. {
  982. u32 seq;
  983. void *data;
  984. int err;
  985. struct audit_buffer *ab;
  986. u16 msg_type = nlh->nlmsg_type;
  987. struct audit_sig_info *sig_data;
  988. char *ctx = NULL;
  989. u32 len;
  990. err = audit_netlink_ok(skb, msg_type);
  991. if (err)
  992. return err;
  993. seq = nlh->nlmsg_seq;
  994. data = nlmsg_data(nlh);
  995. switch (msg_type) {
  996. case AUDIT_GET: {
  997. struct audit_status s;
  998. memset(&s, 0, sizeof(s));
  999. s.enabled = audit_enabled;
  1000. s.failure = audit_failure;
  1001. /* NOTE: use pid_vnr() so the PID is relative to the current
  1002. * namespace */
  1003. s.pid = auditd_pid_vnr();
  1004. s.rate_limit = audit_rate_limit;
  1005. s.backlog_limit = audit_backlog_limit;
  1006. s.lost = atomic_read(&audit_lost);
  1007. s.backlog = skb_queue_len(&audit_queue);
  1008. s.feature_bitmap = AUDIT_FEATURE_BITMAP_ALL;
  1009. s.backlog_wait_time = audit_backlog_wait_time;
  1010. audit_send_reply(skb, seq, AUDIT_GET, 0, 0, &s, sizeof(s));
  1011. break;
  1012. }
  1013. case AUDIT_SET: {
  1014. struct audit_status s;
  1015. memset(&s, 0, sizeof(s));
  1016. /* guard against past and future API changes */
  1017. memcpy(&s, data, min_t(size_t, sizeof(s), nlmsg_len(nlh)));
  1018. if (s.mask & AUDIT_STATUS_ENABLED) {
  1019. err = audit_set_enabled(s.enabled);
  1020. if (err < 0)
  1021. return err;
  1022. }
  1023. if (s.mask & AUDIT_STATUS_FAILURE) {
  1024. err = audit_set_failure(s.failure);
  1025. if (err < 0)
  1026. return err;
  1027. }
  1028. if (s.mask & AUDIT_STATUS_PID) {
  1029. /* NOTE: we are using the vnr PID functions below
  1030. * because the s.pid value is relative to the
  1031. * namespace of the caller; at present this
  1032. * doesn't matter much since you can really only
  1033. * run auditd from the initial pid namespace, but
  1034. * something to keep in mind if this changes */
  1035. pid_t new_pid = s.pid;
  1036. pid_t auditd_pid;
  1037. struct pid *req_pid = task_tgid(current);
  1038. /* sanity check - PID values must match */
  1039. if (new_pid != pid_vnr(req_pid))
  1040. return -EINVAL;
  1041. /* test the auditd connection */
  1042. audit_replace(req_pid);
  1043. auditd_pid = auditd_pid_vnr();
  1044. /* only the current auditd can unregister itself */
  1045. if ((!new_pid) && (new_pid != auditd_pid)) {
  1046. audit_log_config_change("audit_pid", new_pid,
  1047. auditd_pid, 0);
  1048. return -EACCES;
  1049. }
  1050. /* replacing a healthy auditd is not allowed */
  1051. if (auditd_pid && new_pid) {
  1052. audit_log_config_change("audit_pid", new_pid,
  1053. auditd_pid, 0);
  1054. return -EEXIST;
  1055. }
  1056. if (new_pid) {
  1057. /* register a new auditd connection */
  1058. err = auditd_set(req_pid,
  1059. NETLINK_CB(skb).portid,
  1060. sock_net(NETLINK_CB(skb).sk));
  1061. if (audit_enabled != AUDIT_OFF)
  1062. audit_log_config_change("audit_pid",
  1063. new_pid,
  1064. auditd_pid,
  1065. err ? 0 : 1);
  1066. if (err)
  1067. return err;
  1068. /* try to process any backlog */
  1069. wake_up_interruptible(&kauditd_wait);
  1070. } else {
  1071. if (audit_enabled != AUDIT_OFF)
  1072. audit_log_config_change("audit_pid",
  1073. new_pid,
  1074. auditd_pid, 1);
  1075. /* unregister the auditd connection */
  1076. auditd_reset(NULL);
  1077. }
  1078. }
  1079. if (s.mask & AUDIT_STATUS_RATE_LIMIT) {
  1080. err = audit_set_rate_limit(s.rate_limit);
  1081. if (err < 0)
  1082. return err;
  1083. }
  1084. if (s.mask & AUDIT_STATUS_BACKLOG_LIMIT) {
  1085. err = audit_set_backlog_limit(s.backlog_limit);
  1086. if (err < 0)
  1087. return err;
  1088. }
  1089. if (s.mask & AUDIT_STATUS_BACKLOG_WAIT_TIME) {
  1090. if (sizeof(s) > (size_t)nlh->nlmsg_len)
  1091. return -EINVAL;
  1092. if (s.backlog_wait_time > 10*AUDIT_BACKLOG_WAIT_TIME)
  1093. return -EINVAL;
  1094. err = audit_set_backlog_wait_time(s.backlog_wait_time);
  1095. if (err < 0)
  1096. return err;
  1097. }
  1098. if (s.mask == AUDIT_STATUS_LOST) {
  1099. u32 lost = atomic_xchg(&audit_lost, 0);
  1100. audit_log_config_change("lost", 0, lost, 1);
  1101. return lost;
  1102. }
  1103. break;
  1104. }
  1105. case AUDIT_GET_FEATURE:
  1106. err = audit_get_feature(skb);
  1107. if (err)
  1108. return err;
  1109. break;
  1110. case AUDIT_SET_FEATURE:
  1111. err = audit_set_feature(skb);
  1112. if (err)
  1113. return err;
  1114. break;
  1115. case AUDIT_USER:
  1116. case AUDIT_FIRST_USER_MSG ... AUDIT_LAST_USER_MSG:
  1117. case AUDIT_FIRST_USER_MSG2 ... AUDIT_LAST_USER_MSG2:
  1118. if (!audit_enabled && msg_type != AUDIT_USER_AVC)
  1119. return 0;
  1120. err = audit_filter(msg_type, AUDIT_FILTER_USER);
  1121. if (err == 1) { /* match or error */
  1122. err = 0;
  1123. if (msg_type == AUDIT_USER_TTY) {
  1124. err = tty_audit_push();
  1125. if (err)
  1126. break;
  1127. }
  1128. audit_log_common_recv_msg(&ab, msg_type);
  1129. if (msg_type != AUDIT_USER_TTY)
  1130. audit_log_format(ab, " msg='%.*s'",
  1131. AUDIT_MESSAGE_TEXT_MAX,
  1132. (char *)data);
  1133. else {
  1134. int size;
  1135. audit_log_format(ab, " data=");
  1136. size = nlmsg_len(nlh);
  1137. if (size > 0 &&
  1138. ((unsigned char *)data)[size - 1] == '\0')
  1139. size--;
  1140. audit_log_n_untrustedstring(ab, data, size);
  1141. }
  1142. audit_log_end(ab);
  1143. }
  1144. break;
  1145. case AUDIT_ADD_RULE:
  1146. case AUDIT_DEL_RULE:
  1147. if (nlmsg_len(nlh) < sizeof(struct audit_rule_data))
  1148. return -EINVAL;
  1149. if (audit_enabled == AUDIT_LOCKED) {
  1150. audit_log_common_recv_msg(&ab, AUDIT_CONFIG_CHANGE);
  1151. audit_log_format(ab, " audit_enabled=%d res=0", audit_enabled);
  1152. audit_log_end(ab);
  1153. return -EPERM;
  1154. }
  1155. err = audit_rule_change(msg_type, seq, data, nlmsg_len(nlh));
  1156. break;
  1157. case AUDIT_LIST_RULES:
  1158. err = audit_list_rules_send(skb, seq);
  1159. break;
  1160. case AUDIT_TRIM:
  1161. audit_trim_trees();
  1162. audit_log_common_recv_msg(&ab, AUDIT_CONFIG_CHANGE);
  1163. audit_log_format(ab, " op=trim res=1");
  1164. audit_log_end(ab);
  1165. break;
  1166. case AUDIT_MAKE_EQUIV: {
  1167. void *bufp = data;
  1168. u32 sizes[2];
  1169. size_t msglen = nlmsg_len(nlh);
  1170. char *old, *new;
  1171. err = -EINVAL;
  1172. if (msglen < 2 * sizeof(u32))
  1173. break;
  1174. memcpy(sizes, bufp, 2 * sizeof(u32));
  1175. bufp += 2 * sizeof(u32);
  1176. msglen -= 2 * sizeof(u32);
  1177. old = audit_unpack_string(&bufp, &msglen, sizes[0]);
  1178. if (IS_ERR(old)) {
  1179. err = PTR_ERR(old);
  1180. break;
  1181. }
  1182. new = audit_unpack_string(&bufp, &msglen, sizes[1]);
  1183. if (IS_ERR(new)) {
  1184. err = PTR_ERR(new);
  1185. kfree(old);
  1186. break;
  1187. }
  1188. /* OK, here comes... */
  1189. err = audit_tag_tree(old, new);
  1190. audit_log_common_recv_msg(&ab, AUDIT_CONFIG_CHANGE);
  1191. audit_log_format(ab, " op=make_equiv old=");
  1192. audit_log_untrustedstring(ab, old);
  1193. audit_log_format(ab, " new=");
  1194. audit_log_untrustedstring(ab, new);
  1195. audit_log_format(ab, " res=%d", !err);
  1196. audit_log_end(ab);
  1197. kfree(old);
  1198. kfree(new);
  1199. break;
  1200. }
  1201. case AUDIT_SIGNAL_INFO:
  1202. len = 0;
  1203. if (audit_sig_sid) {
  1204. err = security_secid_to_secctx(audit_sig_sid, &ctx, &len);
  1205. if (err)
  1206. return err;
  1207. }
  1208. sig_data = kmalloc(sizeof(*sig_data) + len, GFP_KERNEL);
  1209. if (!sig_data) {
  1210. if (audit_sig_sid)
  1211. security_release_secctx(ctx, len);
  1212. return -ENOMEM;
  1213. }
  1214. sig_data->uid = from_kuid(&init_user_ns, audit_sig_uid);
  1215. sig_data->pid = audit_sig_pid;
  1216. if (audit_sig_sid) {
  1217. memcpy(sig_data->ctx, ctx, len);
  1218. security_release_secctx(ctx, len);
  1219. }
  1220. audit_send_reply(skb, seq, AUDIT_SIGNAL_INFO, 0, 0,
  1221. sig_data, sizeof(*sig_data) + len);
  1222. kfree(sig_data);
  1223. break;
  1224. case AUDIT_TTY_GET: {
  1225. struct audit_tty_status s;
  1226. unsigned int t;
  1227. t = READ_ONCE(current->signal->audit_tty);
  1228. s.enabled = t & AUDIT_TTY_ENABLE;
  1229. s.log_passwd = !!(t & AUDIT_TTY_LOG_PASSWD);
  1230. audit_send_reply(skb, seq, AUDIT_TTY_GET, 0, 0, &s, sizeof(s));
  1231. break;
  1232. }
  1233. case AUDIT_TTY_SET: {
  1234. struct audit_tty_status s, old;
  1235. struct audit_buffer *ab;
  1236. unsigned int t;
  1237. memset(&s, 0, sizeof(s));
  1238. /* guard against past and future API changes */
  1239. memcpy(&s, data, min_t(size_t, sizeof(s), nlmsg_len(nlh)));
  1240. /* check if new data is valid */
  1241. if ((s.enabled != 0 && s.enabled != 1) ||
  1242. (s.log_passwd != 0 && s.log_passwd != 1))
  1243. err = -EINVAL;
  1244. if (err)
  1245. t = READ_ONCE(current->signal->audit_tty);
  1246. else {
  1247. t = s.enabled | (-s.log_passwd & AUDIT_TTY_LOG_PASSWD);
  1248. t = xchg(&current->signal->audit_tty, t);
  1249. }
  1250. old.enabled = t & AUDIT_TTY_ENABLE;
  1251. old.log_passwd = !!(t & AUDIT_TTY_LOG_PASSWD);
  1252. audit_log_common_recv_msg(&ab, AUDIT_CONFIG_CHANGE);
  1253. audit_log_format(ab, " op=tty_set old-enabled=%d new-enabled=%d"
  1254. " old-log_passwd=%d new-log_passwd=%d res=%d",
  1255. old.enabled, s.enabled, old.log_passwd,
  1256. s.log_passwd, !err);
  1257. audit_log_end(ab);
  1258. break;
  1259. }
  1260. default:
  1261. err = -EINVAL;
  1262. break;
  1263. }
  1264. return err < 0 ? err : 0;
  1265. }
  1266. /**
  1267. * audit_receive - receive messages from a netlink control socket
  1268. * @skb: the message buffer
  1269. *
  1270. * Parse the provided skb and deal with any messages that may be present,
  1271. * malformed skbs are discarded.
  1272. */
  1273. static void audit_receive(struct sk_buff *skb)
  1274. {
  1275. struct nlmsghdr *nlh;
  1276. /*
  1277. * len MUST be signed for nlmsg_next to be able to dec it below 0
  1278. * if the nlmsg_len was not aligned
  1279. */
  1280. int len;
  1281. int err;
  1282. nlh = nlmsg_hdr(skb);
  1283. len = skb->len;
  1284. mutex_lock(&audit_cmd_mutex);
  1285. while (nlmsg_ok(nlh, len)) {
  1286. err = audit_receive_msg(skb, nlh);
  1287. /* if err or if this message says it wants a response */
  1288. if (err || (nlh->nlmsg_flags & NLM_F_ACK))
  1289. netlink_ack(skb, nlh, err, NULL);
  1290. nlh = nlmsg_next(nlh, &len);
  1291. }
  1292. mutex_unlock(&audit_cmd_mutex);
  1293. }
  1294. /* Run custom bind function on netlink socket group connect or bind requests. */
  1295. static int audit_bind(struct net *net, int group)
  1296. {
  1297. if (!capable(CAP_AUDIT_READ))
  1298. return -EPERM;
  1299. return 0;
  1300. }
  1301. static int __net_init audit_net_init(struct net *net)
  1302. {
  1303. struct netlink_kernel_cfg cfg = {
  1304. .input = audit_receive,
  1305. .bind = audit_bind,
  1306. .flags = NL_CFG_F_NONROOT_RECV,
  1307. .groups = AUDIT_NLGRP_MAX,
  1308. };
  1309. struct audit_net *aunet = net_generic(net, audit_net_id);
  1310. aunet->sk = netlink_kernel_create(net, NETLINK_AUDIT, &cfg);
  1311. if (aunet->sk == NULL) {
  1312. audit_panic("cannot initialize netlink socket in namespace");
  1313. return -ENOMEM;
  1314. }
  1315. aunet->sk->sk_sndtimeo = MAX_SCHEDULE_TIMEOUT;
  1316. return 0;
  1317. }
  1318. static void __net_exit audit_net_exit(struct net *net)
  1319. {
  1320. struct audit_net *aunet = net_generic(net, audit_net_id);
  1321. /* NOTE: you would think that we would want to check the auditd
  1322. * connection and potentially reset it here if it lives in this
  1323. * namespace, but since the auditd connection tracking struct holds a
  1324. * reference to this namespace (see auditd_set()) we are only ever
  1325. * going to get here after that connection has been released */
  1326. netlink_kernel_release(aunet->sk);
  1327. }
  1328. static struct pernet_operations audit_net_ops __net_initdata = {
  1329. .init = audit_net_init,
  1330. .exit = audit_net_exit,
  1331. .id = &audit_net_id,
  1332. .size = sizeof(struct audit_net),
  1333. };
  1334. /* Initialize audit support at boot time. */
  1335. static int __init audit_init(void)
  1336. {
  1337. int i;
  1338. if (audit_initialized == AUDIT_DISABLED)
  1339. return 0;
  1340. audit_buffer_cache = kmem_cache_create("audit_buffer",
  1341. sizeof(struct audit_buffer),
  1342. 0, SLAB_PANIC, NULL);
  1343. skb_queue_head_init(&audit_queue);
  1344. skb_queue_head_init(&audit_retry_queue);
  1345. skb_queue_head_init(&audit_hold_queue);
  1346. for (i = 0; i < AUDIT_INODE_BUCKETS; i++)
  1347. INIT_LIST_HEAD(&audit_inode_hash[i]);
  1348. pr_info("initializing netlink subsys (%s)\n",
  1349. audit_default ? "enabled" : "disabled");
  1350. register_pernet_subsys(&audit_net_ops);
  1351. audit_initialized = AUDIT_INITIALIZED;
  1352. audit_enabled = audit_default;
  1353. audit_ever_enabled |= !!audit_default;
  1354. kauditd_task = kthread_run(kauditd_thread, NULL, "kauditd");
  1355. if (IS_ERR(kauditd_task)) {
  1356. int err = PTR_ERR(kauditd_task);
  1357. panic("audit: failed to start the kauditd thread (%d)\n", err);
  1358. }
  1359. audit_log(NULL, GFP_KERNEL, AUDIT_KERNEL,
  1360. "state=initialized audit_enabled=%u res=1",
  1361. audit_enabled);
  1362. return 0;
  1363. }
  1364. __initcall(audit_init);
  1365. /* Process kernel command-line parameter at boot time. audit=0 or audit=1. */
  1366. static int __init audit_enable(char *str)
  1367. {
  1368. audit_default = !!simple_strtol(str, NULL, 0);
  1369. if (!audit_default)
  1370. audit_initialized = AUDIT_DISABLED;
  1371. pr_info("%s\n", audit_default ?
  1372. "enabled (after initialization)" : "disabled (until reboot)");
  1373. return 1;
  1374. }
  1375. __setup("audit=", audit_enable);
  1376. /* Process kernel command-line parameter at boot time.
  1377. * audit_backlog_limit=<n> */
  1378. static int __init audit_backlog_limit_set(char *str)
  1379. {
  1380. u32 audit_backlog_limit_arg;
  1381. pr_info("audit_backlog_limit: ");
  1382. if (kstrtouint(str, 0, &audit_backlog_limit_arg)) {
  1383. pr_cont("using default of %u, unable to parse %s\n",
  1384. audit_backlog_limit, str);
  1385. return 1;
  1386. }
  1387. audit_backlog_limit = audit_backlog_limit_arg;
  1388. pr_cont("%d\n", audit_backlog_limit);
  1389. return 1;
  1390. }
  1391. __setup("audit_backlog_limit=", audit_backlog_limit_set);
  1392. static void audit_buffer_free(struct audit_buffer *ab)
  1393. {
  1394. if (!ab)
  1395. return;
  1396. kfree_skb(ab->skb);
  1397. kmem_cache_free(audit_buffer_cache, ab);
  1398. }
  1399. static struct audit_buffer *audit_buffer_alloc(struct audit_context *ctx,
  1400. gfp_t gfp_mask, int type)
  1401. {
  1402. struct audit_buffer *ab;
  1403. ab = kmem_cache_alloc(audit_buffer_cache, gfp_mask);
  1404. if (!ab)
  1405. return NULL;
  1406. ab->skb = nlmsg_new(AUDIT_BUFSIZ, gfp_mask);
  1407. if (!ab->skb)
  1408. goto err;
  1409. if (!nlmsg_put(ab->skb, 0, 0, type, 0, 0))
  1410. goto err;
  1411. ab->ctx = ctx;
  1412. ab->gfp_mask = gfp_mask;
  1413. return ab;
  1414. err:
  1415. audit_buffer_free(ab);
  1416. return NULL;
  1417. }
  1418. /**
  1419. * audit_serial - compute a serial number for the audit record
  1420. *
  1421. * Compute a serial number for the audit record. Audit records are
  1422. * written to user-space as soon as they are generated, so a complete
  1423. * audit record may be written in several pieces. The timestamp of the
  1424. * record and this serial number are used by the user-space tools to
  1425. * determine which pieces belong to the same audit record. The
  1426. * (timestamp,serial) tuple is unique for each syscall and is live from
  1427. * syscall entry to syscall exit.
  1428. *
  1429. * NOTE: Another possibility is to store the formatted records off the
  1430. * audit context (for those records that have a context), and emit them
  1431. * all at syscall exit. However, this could delay the reporting of
  1432. * significant errors until syscall exit (or never, if the system
  1433. * halts).
  1434. */
  1435. unsigned int audit_serial(void)
  1436. {
  1437. static atomic_t serial = ATOMIC_INIT(0);
  1438. return atomic_add_return(1, &serial);
  1439. }
  1440. static inline void audit_get_stamp(struct audit_context *ctx,
  1441. struct timespec64 *t, unsigned int *serial)
  1442. {
  1443. if (!ctx || !auditsc_get_stamp(ctx, t, serial)) {
  1444. ktime_get_real_ts64(t);
  1445. *serial = audit_serial();
  1446. }
  1447. }
  1448. /**
  1449. * audit_log_start - obtain an audit buffer
  1450. * @ctx: audit_context (may be NULL)
  1451. * @gfp_mask: type of allocation
  1452. * @type: audit message type
  1453. *
  1454. * Returns audit_buffer pointer on success or NULL on error.
  1455. *
  1456. * Obtain an audit buffer. This routine does locking to obtain the
  1457. * audit buffer, but then no locking is required for calls to
  1458. * audit_log_*format. If the task (ctx) is a task that is currently in a
  1459. * syscall, then the syscall is marked as auditable and an audit record
  1460. * will be written at syscall exit. If there is no associated task, then
  1461. * task context (ctx) should be NULL.
  1462. */
  1463. struct audit_buffer *audit_log_start(struct audit_context *ctx, gfp_t gfp_mask,
  1464. int type)
  1465. {
  1466. struct audit_buffer *ab;
  1467. struct timespec64 t;
  1468. unsigned int uninitialized_var(serial);
  1469. if (audit_initialized != AUDIT_INITIALIZED)
  1470. return NULL;
  1471. if (unlikely(!audit_filter(type, AUDIT_FILTER_TYPE)))
  1472. return NULL;
  1473. /* NOTE: don't ever fail/sleep on these two conditions:
  1474. * 1. auditd generated record - since we need auditd to drain the
  1475. * queue; also, when we are checking for auditd, compare PIDs using
  1476. * task_tgid_vnr() since auditd_pid is set in audit_receive_msg()
  1477. * using a PID anchored in the caller's namespace
  1478. * 2. generator holding the audit_cmd_mutex - we don't want to block
  1479. * while holding the mutex */
  1480. if (!(auditd_test_task(current) ||
  1481. (current == __mutex_owner(&audit_cmd_mutex)))) {
  1482. long stime = audit_backlog_wait_time;
  1483. while (audit_backlog_limit &&
  1484. (skb_queue_len(&audit_queue) > audit_backlog_limit)) {
  1485. /* wake kauditd to try and flush the queue */
  1486. wake_up_interruptible(&kauditd_wait);
  1487. /* sleep if we are allowed and we haven't exhausted our
  1488. * backlog wait limit */
  1489. if (gfpflags_allow_blocking(gfp_mask) && (stime > 0)) {
  1490. DECLARE_WAITQUEUE(wait, current);
  1491. add_wait_queue_exclusive(&audit_backlog_wait,
  1492. &wait);
  1493. set_current_state(TASK_UNINTERRUPTIBLE);
  1494. stime = schedule_timeout(stime);
  1495. remove_wait_queue(&audit_backlog_wait, &wait);
  1496. } else {
  1497. if (audit_rate_check() && printk_ratelimit())
  1498. pr_warn("audit_backlog=%d > audit_backlog_limit=%d\n",
  1499. skb_queue_len(&audit_queue),
  1500. audit_backlog_limit);
  1501. audit_log_lost("backlog limit exceeded");
  1502. return NULL;
  1503. }
  1504. }
  1505. }
  1506. ab = audit_buffer_alloc(ctx, gfp_mask, type);
  1507. if (!ab) {
  1508. audit_log_lost("out of memory in audit_log_start");
  1509. return NULL;
  1510. }
  1511. audit_get_stamp(ab->ctx, &t, &serial);
  1512. audit_log_format(ab, "audit(%llu.%03lu:%u): ",
  1513. (unsigned long long)t.tv_sec, t.tv_nsec/1000000, serial);
  1514. return ab;
  1515. }
  1516. /**
  1517. * audit_expand - expand skb in the audit buffer
  1518. * @ab: audit_buffer
  1519. * @extra: space to add at tail of the skb
  1520. *
  1521. * Returns 0 (no space) on failed expansion, or available space if
  1522. * successful.
  1523. */
  1524. static inline int audit_expand(struct audit_buffer *ab, int extra)
  1525. {
  1526. struct sk_buff *skb = ab->skb;
  1527. int oldtail = skb_tailroom(skb);
  1528. int ret = pskb_expand_head(skb, 0, extra, ab->gfp_mask);
  1529. int newtail = skb_tailroom(skb);
  1530. if (ret < 0) {
  1531. audit_log_lost("out of memory in audit_expand");
  1532. return 0;
  1533. }
  1534. skb->truesize += newtail - oldtail;
  1535. return newtail;
  1536. }
  1537. /*
  1538. * Format an audit message into the audit buffer. If there isn't enough
  1539. * room in the audit buffer, more room will be allocated and vsnprint
  1540. * will be called a second time. Currently, we assume that a printk
  1541. * can't format message larger than 1024 bytes, so we don't either.
  1542. */
  1543. static void audit_log_vformat(struct audit_buffer *ab, const char *fmt,
  1544. va_list args)
  1545. {
  1546. int len, avail;
  1547. struct sk_buff *skb;
  1548. va_list args2;
  1549. if (!ab)
  1550. return;
  1551. BUG_ON(!ab->skb);
  1552. skb = ab->skb;
  1553. avail = skb_tailroom(skb);
  1554. if (avail == 0) {
  1555. avail = audit_expand(ab, AUDIT_BUFSIZ);
  1556. if (!avail)
  1557. goto out;
  1558. }
  1559. va_copy(args2, args);
  1560. len = vsnprintf(skb_tail_pointer(skb), avail, fmt, args);
  1561. if (len >= avail) {
  1562. /* The printk buffer is 1024 bytes long, so if we get
  1563. * here and AUDIT_BUFSIZ is at least 1024, then we can
  1564. * log everything that printk could have logged. */
  1565. avail = audit_expand(ab,
  1566. max_t(unsigned, AUDIT_BUFSIZ, 1+len-avail));
  1567. if (!avail)
  1568. goto out_va_end;
  1569. len = vsnprintf(skb_tail_pointer(skb), avail, fmt, args2);
  1570. }
  1571. if (len > 0)
  1572. skb_put(skb, len);
  1573. out_va_end:
  1574. va_end(args2);
  1575. out:
  1576. return;
  1577. }
  1578. /**
  1579. * audit_log_format - format a message into the audit buffer.
  1580. * @ab: audit_buffer
  1581. * @fmt: format string
  1582. * @...: optional parameters matching @fmt string
  1583. *
  1584. * All the work is done in audit_log_vformat.
  1585. */
  1586. void audit_log_format(struct audit_buffer *ab, const char *fmt, ...)
  1587. {
  1588. va_list args;
  1589. if (!ab)
  1590. return;
  1591. va_start(args, fmt);
  1592. audit_log_vformat(ab, fmt, args);
  1593. va_end(args);
  1594. }
  1595. /**
  1596. * audit_log_hex - convert a buffer to hex and append it to the audit skb
  1597. * @ab: the audit_buffer
  1598. * @buf: buffer to convert to hex
  1599. * @len: length of @buf to be converted
  1600. *
  1601. * No return value; failure to expand is silently ignored.
  1602. *
  1603. * This function will take the passed buf and convert it into a string of
  1604. * ascii hex digits. The new string is placed onto the skb.
  1605. */
  1606. void audit_log_n_hex(struct audit_buffer *ab, const unsigned char *buf,
  1607. size_t len)
  1608. {
  1609. int i, avail, new_len;
  1610. unsigned char *ptr;
  1611. struct sk_buff *skb;
  1612. if (!ab)
  1613. return;
  1614. BUG_ON(!ab->skb);
  1615. skb = ab->skb;
  1616. avail = skb_tailroom(skb);
  1617. new_len = len<<1;
  1618. if (new_len >= avail) {
  1619. /* Round the buffer request up to the next multiple */
  1620. new_len = AUDIT_BUFSIZ*(((new_len-avail)/AUDIT_BUFSIZ) + 1);
  1621. avail = audit_expand(ab, new_len);
  1622. if (!avail)
  1623. return;
  1624. }
  1625. ptr = skb_tail_pointer(skb);
  1626. for (i = 0; i < len; i++)
  1627. ptr = hex_byte_pack_upper(ptr, buf[i]);
  1628. *ptr = 0;
  1629. skb_put(skb, len << 1); /* new string is twice the old string */
  1630. }
  1631. /*
  1632. * Format a string of no more than slen characters into the audit buffer,
  1633. * enclosed in quote marks.
  1634. */
  1635. void audit_log_n_string(struct audit_buffer *ab, const char *string,
  1636. size_t slen)
  1637. {
  1638. int avail, new_len;
  1639. unsigned char *ptr;
  1640. struct sk_buff *skb;
  1641. if (!ab)
  1642. return;
  1643. BUG_ON(!ab->skb);
  1644. skb = ab->skb;
  1645. avail = skb_tailroom(skb);
  1646. new_len = slen + 3; /* enclosing quotes + null terminator */
  1647. if (new_len > avail) {
  1648. avail = audit_expand(ab, new_len);
  1649. if (!avail)
  1650. return;
  1651. }
  1652. ptr = skb_tail_pointer(skb);
  1653. *ptr++ = '"';
  1654. memcpy(ptr, string, slen);
  1655. ptr += slen;
  1656. *ptr++ = '"';
  1657. *ptr = 0;
  1658. skb_put(skb, slen + 2); /* don't include null terminator */
  1659. }
  1660. /**
  1661. * audit_string_contains_control - does a string need to be logged in hex
  1662. * @string: string to be checked
  1663. * @len: max length of the string to check
  1664. */
  1665. bool audit_string_contains_control(const char *string, size_t len)
  1666. {
  1667. const unsigned char *p;
  1668. for (p = string; p < (const unsigned char *)string + len; p++) {
  1669. if (*p == '"' || *p < 0x21 || *p > 0x7e)
  1670. return true;
  1671. }
  1672. return false;
  1673. }
  1674. /**
  1675. * audit_log_n_untrustedstring - log a string that may contain random characters
  1676. * @ab: audit_buffer
  1677. * @len: length of string (not including trailing null)
  1678. * @string: string to be logged
  1679. *
  1680. * This code will escape a string that is passed to it if the string
  1681. * contains a control character, unprintable character, double quote mark,
  1682. * or a space. Unescaped strings will start and end with a double quote mark.
  1683. * Strings that are escaped are printed in hex (2 digits per char).
  1684. *
  1685. * The caller specifies the number of characters in the string to log, which may
  1686. * or may not be the entire string.
  1687. */
  1688. void audit_log_n_untrustedstring(struct audit_buffer *ab, const char *string,
  1689. size_t len)
  1690. {
  1691. if (audit_string_contains_control(string, len))
  1692. audit_log_n_hex(ab, string, len);
  1693. else
  1694. audit_log_n_string(ab, string, len);
  1695. }
  1696. /**
  1697. * audit_log_untrustedstring - log a string that may contain random characters
  1698. * @ab: audit_buffer
  1699. * @string: string to be logged
  1700. *
  1701. * Same as audit_log_n_untrustedstring(), except that strlen is used to
  1702. * determine string length.
  1703. */
  1704. void audit_log_untrustedstring(struct audit_buffer *ab, const char *string)
  1705. {
  1706. audit_log_n_untrustedstring(ab, string, strlen(string));
  1707. }
  1708. /* This is a helper-function to print the escaped d_path */
  1709. void audit_log_d_path(struct audit_buffer *ab, const char *prefix,
  1710. const struct path *path)
  1711. {
  1712. char *p, *pathname;
  1713. if (prefix)
  1714. audit_log_format(ab, "%s", prefix);
  1715. /* We will allow 11 spaces for ' (deleted)' to be appended */
  1716. pathname = kmalloc(PATH_MAX+11, ab->gfp_mask);
  1717. if (!pathname) {
  1718. audit_log_string(ab, "<no_memory>");
  1719. return;
  1720. }
  1721. p = d_path(path, pathname, PATH_MAX+11);
  1722. if (IS_ERR(p)) { /* Should never happen since we send PATH_MAX */
  1723. /* FIXME: can we save some information here? */
  1724. audit_log_string(ab, "<too_long>");
  1725. } else
  1726. audit_log_untrustedstring(ab, p);
  1727. kfree(pathname);
  1728. }
  1729. void audit_log_session_info(struct audit_buffer *ab)
  1730. {
  1731. unsigned int sessionid = audit_get_sessionid(current);
  1732. uid_t auid = from_kuid(&init_user_ns, audit_get_loginuid(current));
  1733. audit_log_format(ab, " auid=%u ses=%u", auid, sessionid);
  1734. }
  1735. void audit_log_key(struct audit_buffer *ab, char *key)
  1736. {
  1737. audit_log_format(ab, " key=");
  1738. if (key)
  1739. audit_log_untrustedstring(ab, key);
  1740. else
  1741. audit_log_format(ab, "(null)");
  1742. }
  1743. void audit_log_cap(struct audit_buffer *ab, char *prefix, kernel_cap_t *cap)
  1744. {
  1745. int i;
  1746. audit_log_format(ab, " %s=", prefix);
  1747. CAP_FOR_EACH_U32(i) {
  1748. audit_log_format(ab, "%08x",
  1749. cap->cap[CAP_LAST_U32 - i]);
  1750. }
  1751. }
  1752. static void audit_log_fcaps(struct audit_buffer *ab, struct audit_names *name)
  1753. {
  1754. audit_log_cap(ab, "cap_fp", &name->fcap.permitted);
  1755. audit_log_cap(ab, "cap_fi", &name->fcap.inheritable);
  1756. audit_log_format(ab, " cap_fe=%d cap_fver=%x",
  1757. name->fcap.fE, name->fcap_ver);
  1758. }
  1759. static inline int audit_copy_fcaps(struct audit_names *name,
  1760. const struct dentry *dentry)
  1761. {
  1762. struct cpu_vfs_cap_data caps;
  1763. int rc;
  1764. if (!dentry)
  1765. return 0;
  1766. rc = get_vfs_caps_from_disk(dentry, &caps);
  1767. if (rc)
  1768. return rc;
  1769. name->fcap.permitted = caps.permitted;
  1770. name->fcap.inheritable = caps.inheritable;
  1771. name->fcap.fE = !!(caps.magic_etc & VFS_CAP_FLAGS_EFFECTIVE);
  1772. name->fcap_ver = (caps.magic_etc & VFS_CAP_REVISION_MASK) >>
  1773. VFS_CAP_REVISION_SHIFT;
  1774. return 0;
  1775. }
  1776. /* Copy inode data into an audit_names. */
  1777. void audit_copy_inode(struct audit_names *name, const struct dentry *dentry,
  1778. struct inode *inode)
  1779. {
  1780. name->ino = inode->i_ino;
  1781. name->dev = inode->i_sb->s_dev;
  1782. name->mode = inode->i_mode;
  1783. name->uid = inode->i_uid;
  1784. name->gid = inode->i_gid;
  1785. name->rdev = inode->i_rdev;
  1786. security_inode_getsecid(inode, &name->osid);
  1787. audit_copy_fcaps(name, dentry);
  1788. }
  1789. /**
  1790. * audit_log_name - produce AUDIT_PATH record from struct audit_names
  1791. * @context: audit_context for the task
  1792. * @n: audit_names structure with reportable details
  1793. * @path: optional path to report instead of audit_names->name
  1794. * @record_num: record number to report when handling a list of names
  1795. * @call_panic: optional pointer to int that will be updated if secid fails
  1796. */
  1797. void audit_log_name(struct audit_context *context, struct audit_names *n,
  1798. const struct path *path, int record_num, int *call_panic)
  1799. {
  1800. struct audit_buffer *ab;
  1801. ab = audit_log_start(context, GFP_KERNEL, AUDIT_PATH);
  1802. if (!ab)
  1803. return;
  1804. audit_log_format(ab, "item=%d", record_num);
  1805. if (path)
  1806. audit_log_d_path(ab, " name=", path);
  1807. else if (n->name) {
  1808. switch (n->name_len) {
  1809. case AUDIT_NAME_FULL:
  1810. /* log the full path */
  1811. audit_log_format(ab, " name=");
  1812. audit_log_untrustedstring(ab, n->name->name);
  1813. break;
  1814. case 0:
  1815. /* name was specified as a relative path and the
  1816. * directory component is the cwd */
  1817. audit_log_d_path(ab, " name=", &context->pwd);
  1818. break;
  1819. default:
  1820. /* log the name's directory component */
  1821. audit_log_format(ab, " name=");
  1822. audit_log_n_untrustedstring(ab, n->name->name,
  1823. n->name_len);
  1824. }
  1825. } else
  1826. audit_log_format(ab, " name=(null)");
  1827. if (n->ino != AUDIT_INO_UNSET)
  1828. audit_log_format(ab, " inode=%lu"
  1829. " dev=%02x:%02x mode=%#ho"
  1830. " ouid=%u ogid=%u rdev=%02x:%02x",
  1831. n->ino,
  1832. MAJOR(n->dev),
  1833. MINOR(n->dev),
  1834. n->mode,
  1835. from_kuid(&init_user_ns, n->uid),
  1836. from_kgid(&init_user_ns, n->gid),
  1837. MAJOR(n->rdev),
  1838. MINOR(n->rdev));
  1839. if (n->osid != 0) {
  1840. char *ctx = NULL;
  1841. u32 len;
  1842. if (security_secid_to_secctx(
  1843. n->osid, &ctx, &len)) {
  1844. audit_log_format(ab, " osid=%u", n->osid);
  1845. if (call_panic)
  1846. *call_panic = 2;
  1847. } else {
  1848. audit_log_format(ab, " obj=%s", ctx);
  1849. security_release_secctx(ctx, len);
  1850. }
  1851. }
  1852. /* log the audit_names record type */
  1853. audit_log_format(ab, " nametype=");
  1854. switch(n->type) {
  1855. case AUDIT_TYPE_NORMAL:
  1856. audit_log_format(ab, "NORMAL");
  1857. break;
  1858. case AUDIT_TYPE_PARENT:
  1859. audit_log_format(ab, "PARENT");
  1860. break;
  1861. case AUDIT_TYPE_CHILD_DELETE:
  1862. audit_log_format(ab, "DELETE");
  1863. break;
  1864. case AUDIT_TYPE_CHILD_CREATE:
  1865. audit_log_format(ab, "CREATE");
  1866. break;
  1867. default:
  1868. audit_log_format(ab, "UNKNOWN");
  1869. break;
  1870. }
  1871. audit_log_fcaps(ab, n);
  1872. audit_log_end(ab);
  1873. }
  1874. int audit_log_task_context(struct audit_buffer *ab)
  1875. {
  1876. char *ctx = NULL;
  1877. unsigned len;
  1878. int error;
  1879. u32 sid;
  1880. security_task_getsecid(current, &sid);
  1881. if (!sid)
  1882. return 0;
  1883. error = security_secid_to_secctx(sid, &ctx, &len);
  1884. if (error) {
  1885. if (error != -EINVAL)
  1886. goto error_path;
  1887. return 0;
  1888. }
  1889. audit_log_format(ab, " subj=%s", ctx);
  1890. security_release_secctx(ctx, len);
  1891. return 0;
  1892. error_path:
  1893. audit_panic("error in audit_log_task_context");
  1894. return error;
  1895. }
  1896. EXPORT_SYMBOL(audit_log_task_context);
  1897. void audit_log_d_path_exe(struct audit_buffer *ab,
  1898. struct mm_struct *mm)
  1899. {
  1900. struct file *exe_file;
  1901. if (!mm)
  1902. goto out_null;
  1903. exe_file = get_mm_exe_file(mm);
  1904. if (!exe_file)
  1905. goto out_null;
  1906. audit_log_d_path(ab, " exe=", &exe_file->f_path);
  1907. fput(exe_file);
  1908. return;
  1909. out_null:
  1910. audit_log_format(ab, " exe=(null)");
  1911. }
  1912. struct tty_struct *audit_get_tty(struct task_struct *tsk)
  1913. {
  1914. struct tty_struct *tty = NULL;
  1915. unsigned long flags;
  1916. spin_lock_irqsave(&tsk->sighand->siglock, flags);
  1917. if (tsk->signal)
  1918. tty = tty_kref_get(tsk->signal->tty);
  1919. spin_unlock_irqrestore(&tsk->sighand->siglock, flags);
  1920. return tty;
  1921. }
  1922. void audit_put_tty(struct tty_struct *tty)
  1923. {
  1924. tty_kref_put(tty);
  1925. }
  1926. void audit_log_task_info(struct audit_buffer *ab, struct task_struct *tsk)
  1927. {
  1928. const struct cred *cred;
  1929. char comm[sizeof(tsk->comm)];
  1930. struct tty_struct *tty;
  1931. if (!ab)
  1932. return;
  1933. /* tsk == current */
  1934. cred = current_cred();
  1935. tty = audit_get_tty(tsk);
  1936. audit_log_format(ab,
  1937. " ppid=%d pid=%d auid=%u uid=%u gid=%u"
  1938. " euid=%u suid=%u fsuid=%u"
  1939. " egid=%u sgid=%u fsgid=%u tty=%s ses=%u",
  1940. task_ppid_nr(tsk),
  1941. task_tgid_nr(tsk),
  1942. from_kuid(&init_user_ns, audit_get_loginuid(tsk)),
  1943. from_kuid(&init_user_ns, cred->uid),
  1944. from_kgid(&init_user_ns, cred->gid),
  1945. from_kuid(&init_user_ns, cred->euid),
  1946. from_kuid(&init_user_ns, cred->suid),
  1947. from_kuid(&init_user_ns, cred->fsuid),
  1948. from_kgid(&init_user_ns, cred->egid),
  1949. from_kgid(&init_user_ns, cred->sgid),
  1950. from_kgid(&init_user_ns, cred->fsgid),
  1951. tty ? tty_name(tty) : "(none)",
  1952. audit_get_sessionid(tsk));
  1953. audit_put_tty(tty);
  1954. audit_log_format(ab, " comm=");
  1955. audit_log_untrustedstring(ab, get_task_comm(comm, tsk));
  1956. audit_log_d_path_exe(ab, tsk->mm);
  1957. audit_log_task_context(ab);
  1958. }
  1959. EXPORT_SYMBOL(audit_log_task_info);
  1960. /**
  1961. * audit_log_link_denied - report a link restriction denial
  1962. * @operation: specific link operation
  1963. * @link: the path that triggered the restriction
  1964. */
  1965. void audit_log_link_denied(const char *operation, const struct path *link)
  1966. {
  1967. struct audit_buffer *ab;
  1968. struct audit_names *name;
  1969. name = kzalloc(sizeof(*name), GFP_NOFS);
  1970. if (!name)
  1971. return;
  1972. /* Generate AUDIT_ANOM_LINK with subject, operation, outcome. */
  1973. ab = audit_log_start(current->audit_context, GFP_KERNEL,
  1974. AUDIT_ANOM_LINK);
  1975. if (!ab)
  1976. goto out;
  1977. audit_log_format(ab, "op=%s", operation);
  1978. audit_log_task_info(ab, current);
  1979. audit_log_format(ab, " res=0");
  1980. audit_log_end(ab);
  1981. /* Generate AUDIT_PATH record with object. */
  1982. name->type = AUDIT_TYPE_NORMAL;
  1983. audit_copy_inode(name, link->dentry, d_backing_inode(link->dentry));
  1984. audit_log_name(current->audit_context, name, link, 0, NULL);
  1985. out:
  1986. kfree(name);
  1987. }
  1988. /**
  1989. * audit_log_end - end one audit record
  1990. * @ab: the audit_buffer
  1991. *
  1992. * We can not do a netlink send inside an irq context because it blocks (last
  1993. * arg, flags, is not set to MSG_DONTWAIT), so the audit buffer is placed on a
  1994. * queue and a tasklet is scheduled to remove them from the queue outside the
  1995. * irq context. May be called in any context.
  1996. */
  1997. void audit_log_end(struct audit_buffer *ab)
  1998. {
  1999. struct sk_buff *skb;
  2000. struct nlmsghdr *nlh;
  2001. if (!ab)
  2002. return;
  2003. if (audit_rate_check()) {
  2004. skb = ab->skb;
  2005. ab->skb = NULL;
  2006. /* setup the netlink header, see the comments in
  2007. * kauditd_send_multicast_skb() for length quirks */
  2008. nlh = nlmsg_hdr(skb);
  2009. nlh->nlmsg_len = skb->len - NLMSG_HDRLEN;
  2010. /* queue the netlink packet and poke the kauditd thread */
  2011. skb_queue_tail(&audit_queue, skb);
  2012. wake_up_interruptible(&kauditd_wait);
  2013. } else
  2014. audit_log_lost("rate limit exceeded");
  2015. audit_buffer_free(ab);
  2016. }
  2017. /**
  2018. * audit_log - Log an audit record
  2019. * @ctx: audit context
  2020. * @gfp_mask: type of allocation
  2021. * @type: audit message type
  2022. * @fmt: format string to use
  2023. * @...: variable parameters matching the format string
  2024. *
  2025. * This is a convenience function that calls audit_log_start,
  2026. * audit_log_vformat, and audit_log_end. It may be called
  2027. * in any context.
  2028. */
  2029. void audit_log(struct audit_context *ctx, gfp_t gfp_mask, int type,
  2030. const char *fmt, ...)
  2031. {
  2032. struct audit_buffer *ab;
  2033. va_list args;
  2034. ab = audit_log_start(ctx, gfp_mask, type);
  2035. if (ab) {
  2036. va_start(args, fmt);
  2037. audit_log_vformat(ab, fmt, args);
  2038. va_end(args);
  2039. audit_log_end(ab);
  2040. }
  2041. }
  2042. #ifdef CONFIG_SECURITY
  2043. /**
  2044. * audit_log_secctx - Converts and logs SELinux context
  2045. * @ab: audit_buffer
  2046. * @secid: security number
  2047. *
  2048. * This is a helper function that calls security_secid_to_secctx to convert
  2049. * secid to secctx and then adds the (converted) SELinux context to the audit
  2050. * log by calling audit_log_format, thus also preventing leak of internal secid
  2051. * to userspace. If secid cannot be converted audit_panic is called.
  2052. */
  2053. void audit_log_secctx(struct audit_buffer *ab, u32 secid)
  2054. {
  2055. u32 len;
  2056. char *secctx;
  2057. if (security_secid_to_secctx(secid, &secctx, &len)) {
  2058. audit_panic("Cannot convert secid to context");
  2059. } else {
  2060. audit_log_format(ab, " obj=%s", secctx);
  2061. security_release_secctx(secctx, len);
  2062. }
  2063. }
  2064. EXPORT_SYMBOL(audit_log_secctx);
  2065. #endif
  2066. EXPORT_SYMBOL(audit_log_start);
  2067. EXPORT_SYMBOL(audit_log_end);
  2068. EXPORT_SYMBOL(audit_log_format);
  2069. EXPORT_SYMBOL(audit_log);