audit.c 62 KB

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