audit.c 61 KB

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