Debian Codegraph @

src/journal/journald-audit.c

raw
1 /* SPDX-License-Identifier: LGPL-2.1-or-later */
2
3 #include <linux/audit.h>
4
5 #include "sd-event.h"
6
7 #include "alloc-util.h"
8 #include "audit-type.h"
9 #include "errno-util.h"
10 #include "fd-util.h"
11 #include "hexdecoct.h"
12 #include "iovec-util.h"
13 #include "journal-internal.h"
14 #include "journald-audit.h"
15 #include "journald-manager.h"
16 #include "log.h"
17 #include "log-ratelimit.h"
18 #include "stdio-util.h"
19 #include "string-util.h"
20 #include "time-util.h"
21
22 typedef struct MapField {
23 const char *audit_field;
24 const char *journal_field;
25 int (*map)(const char *field, const char **p, struct iovec *iovec, size_t *n);
26 } MapField;
27
28 static int map_simple_field(
29 const char *field,
30 const char **p,
31 struct iovec *iovec,
32 size_t *n) {
33
34 _cleanup_free_ char *c = NULL;
35 size_t l = 0;
36 const char *e;
37
38 assert(field);
39 assert(p);
40 assert(iovec);
41 assert(n);
42
43 l = strlen(field);
44 c = malloc(l + 1);
45 if (!c)
46 return -ENOMEM;
47
48 memcpy(c, field, l);
49 for (e = *p; !IN_SET(*e, 0, ' '); e++) {
50 if (!GREEDY_REALLOC(c, l+2))
51 return -ENOMEM;
52
53 c[l++] = *e;
54 }
55
56 c[l] = 0;
57
58 iovec[(*n)++] = IOVEC_MAKE(c, l);
59
60 *p = e;
61 c = NULL;
62
63 return 1;
64 }
65
66 static int map_string_field_internal(
67 const char *field,
68 const char **p,
69 struct iovec *iovec,
70 size_t *n,
71 bool filter_printable) {
72
73 _cleanup_free_ char *c = NULL;
74 const char *s, *e;
75 size_t l;
76
77 assert(field);
78 assert(p);
79 assert(iovec);
80 assert(n);
81
82 /* The kernel formats string fields in one of two formats. */
83
84 if (**p == '"') {
85 /* Normal quoted syntax */
86 s = *p + 1;
87 e = strchr(s, '"');
88 if (!e)
89 return 0;
90
91 l = strlen(field) + (e - s);
92 c = malloc(l+1);
93 if (!c)
94 return -ENOMEM;
95
96 *mempcpy_typesafe(stpcpy(c, field), s, e - s) = 0;
97
98 e += 1;
99
100 } else if (unhexchar(**p) >= 0) {
101 /* Hexadecimal escaping */
102 l = strlen(field);
103 c = malloc(l + 2);
104 if (!c)
105 return -ENOMEM;
106
107 memcpy(c, field, l);
108 for (e = *p; !IN_SET(*e, 0, ' '); e += 2) {
109 int a, b;
110 uint8_t x;
111
112 a = unhexchar(e[0]);
113 if (a < 0)
114 return 0;
115
116 b = unhexchar(e[1]);
117 if (b < 0)
118 return 0;
119
120 x = ((uint8_t) a << 4 | (uint8_t) b);
121
122 if (filter_printable && x < (uint8_t) ' ')
123 x = (uint8_t) ' ';
124
125 if (!GREEDY_REALLOC(c, l+2))
126 return -ENOMEM;
127
128 c[l++] = (char) x;
129 }
130
131 c[l] = 0;
132 } else
133 return 0;
134
135 iovec[(*n)++] = IOVEC_MAKE(c, l);
136
137 *p = e;
138 c = NULL;
139
140 return 1;
141 }
142
143 static int map_string_field(const char *field, const char **p, struct iovec *iovec, size_t *n) {
144 return map_string_field_internal(field, p, iovec, n, false);
145 }
146
147 static int map_string_field_printable(const char *field, const char **p, struct iovec *iovec, size_t *n) {
148 return map_string_field_internal(field, p, iovec, n, true);
149 }
150
151 static int map_generic_field(
152 const char *prefix,
153 const char **p,
154 struct iovec *iovec,
155 size_t *n) {
156
157 const char *e, *f;
158 char *c, *t;
159 int r;
160
161 assert(p);
162
163 /* Implements fallback mappings for all fields we don't know */
164
165 for (e = *p; e < *p + 16; e++) {
166
167 if (IN_SET(*e, 0, ' '))
168 return 0;
169
170 if (*e == '=')
171 break;
172
173 if (!(ascii_isalpha(*e) ||
174 ascii_isdigit(*e) ||
175 IN_SET(*e, '_', '-')))
176 return 0;
177 }
178
179 if (e <= *p || e >= *p + 16)
180 return 0;
181
182 c = newa(char, strlen(prefix) + (e - *p) + 2);
183
184 t = stpcpy(c, prefix);
185 for (f = *p; f < e; f++) {
186 char x;
187
188 if (*f >= 'a' && *f <= 'z')
189 x = (*f - 'a') + 'A'; /* uppercase */
190 else if (*f == '-')
191 x = '_'; /* dashes → underscores */
192 else
193 x = *f;
194
195 *(t++) = x;
196 }
197 strcpy(t, "=");
198
199 e++;
200
201 r = map_simple_field(c, &e, iovec, n);
202 if (r < 0)
203 return r;
204
205 *p = e;
206 return r;
207 }
208
209 /* Kernel fields are those occurring in the audit string before
210 * msg='. All of these fields are trusted, hence carry the "_" prefix.
211 * We try to translate the fields we know into our native names. The
212 * other's are generically mapped to _AUDIT_FIELD_XYZ= */
213 static const MapField map_fields_kernel[] = {
214
215 /* First, we map certain well-known audit fields into native
216 * well-known fields */
217 { "pid=", "_PID=", map_simple_field },
218 { "ppid=", "_PPID=", map_simple_field },
219 { "uid=", "_UID=", map_simple_field },
220 { "euid=", "_EUID=", map_simple_field },
221 { "fsuid=", "_FSUID=", map_simple_field },
222 { "gid=", "_GID=", map_simple_field },
223 { "egid=", "_EGID=", map_simple_field },
224 { "fsgid=", "_FSGID=", map_simple_field },
225 { "tty=", "_TTY=", map_simple_field },
226 { "ses=", "_AUDIT_SESSION=", map_simple_field },
227 { "auid=", "_AUDIT_LOGINUID=", map_simple_field },
228 { "subj=", "_SELINUX_CONTEXT=", map_simple_field },
229 { "comm=", "_COMM=", map_string_field },
230 { "exe=", "_EXE=", map_string_field },
231 { "proctitle=", "_CMDLINE=", map_string_field_printable },
232
233 /* Some fields don't map to native well-known fields. However,
234 * we know that they are string fields, hence let's undo
235 * string field escaping for them, though we stick to the
236 * generic field names. */
237 { "path=", "_AUDIT_FIELD_PATH=", map_string_field },
238 { "dev=", "_AUDIT_FIELD_DEV=", map_string_field },
239 { "name=", "_AUDIT_FIELD_NAME=", map_string_field },
240 {}
241 };
242
243 /* Userspace fields are those occurring in the audit string after
244 * msg='. All of these fields are untrusted, hence carry no "_"
245 * prefix. We map the fields we don't know to AUDIT_FIELD_XYZ= */
246 static const MapField map_fields_userspace[] = {
247 { "cwd=", "AUDIT_FIELD_CWD=", map_string_field },
248 { "cmd=", "AUDIT_FIELD_CMD=", map_string_field },
249 { "acct=", "AUDIT_FIELD_ACCT=", map_string_field },
250 { "exe=", "AUDIT_FIELD_EXE=", map_string_field },
251 { "comm=", "AUDIT_FIELD_COMM=", map_string_field },
252 {}
253 };
254
255 static int map_all_fields(
256 const char *p,
257 const MapField map_fields[],
258 const char *prefix,
259 bool handle_msg,
260 struct iovec *iovec,
261 size_t *n,
262 size_t m) {
263
264 int r;
265
266 assert(p);
267 assert(iovec);
268 assert(n);
269
270 for (;;) {
271 bool mapped = false;
272 const MapField *mf;
273 const char *v;
274
275 if (*n >= m) {
276 log_debug(
277 "More fields in audit message than audit field limit (%i), skipping remaining fields",
278 N_IOVEC_AUDIT_FIELDS);
279 return 0;
280 }
281
282 p += strspn(p, WHITESPACE);
283
284 if (*p == 0)
285 return 0;
286
287 if (handle_msg) {
288 v = startswith(p, "msg='");
289 if (v) {
290 _cleanup_free_ char *c = NULL;
291 const char *e;
292
293 /* Userspace message. It's enclosed in
294 simple quotation marks, is not
295 escaped, but the last field in the
296 line, hence let's remove the
297 quotation mark, and apply the
298 userspace mapping instead of the
299 kernel mapping. */
300
301 e = endswith(v, "'");
302 if (!e)
303 return 0; /* don't continue splitting up if the final quotation mark is missing */
304
305 c = strndup(v, e - v);
306 if (!c)
307 return -ENOMEM;
308
309 return map_all_fields(c, map_fields_userspace, "AUDIT_FIELD_", false, iovec, n, m);
310 }
311 }
312
313 /* Try to map the kernel fields to our own names */
314 for (mf = map_fields; mf->audit_field; mf++) {
315 v = startswith(p, mf->audit_field);
316 if (!v)
317 continue;
318
319 r = mf->map(mf->journal_field, &v, iovec, n);
320 if (r < 0)
321 return log_debug_errno(r, "Failed to parse audit array: %m");
322
323 if (r > 0) {
324 mapped = true;
325 p = v;
326 break;
327 }
328 }
329
330 if (!mapped) {
331 r = map_generic_field(prefix, &p, iovec, n);
332 if (r < 0)
333 return log_debug_errno(r, "Failed to parse audit array: %m");
334
335 if (r == 0)
336 /* Couldn't process as generic field, let's just skip over it */
337 p += strcspn(p, WHITESPACE);
338 }
339 }
340 }
341
342 void process_audit_string(Manager *m, int type, const char *data, size_t size) {
343 size_t n = 0, z;
344 uint64_t seconds, msec, id;
345 const char *p, *type_name, *type_field_name, *mm;
346 char id_field[STRLEN("_AUDIT_ID=") + DECIMAL_STR_MAX(uint64_t)],
347 type_field[STRLEN("_AUDIT_TYPE=") + DECIMAL_STR_MAX(int)];
348 struct iovec iovec[N_IOVEC_META_FIELDS + 7 + N_IOVEC_AUDIT_FIELDS];
349 int k;
350
351 assert(m);
352
353 if (size <= 0)
354 return;
355
356 if (!data)
357 return;
358
359 /* Note that the input buffer is NUL terminated, but let's
360 * check whether there is a spurious NUL byte */
361 if (memchr(data, 0, size))
362 return;
363
364 p = startswith(data, "audit");
365 if (!p)
366 return;
367
368 k = 0;
369 if (sscanf(p, "(%" PRIu64 ".%" PRIu64 ":%" PRIu64 "):%n",
370 &seconds,
371 &msec,
372 &id,
373 &k) != 3 || k == 0)
374 return;
375
376 p += k;
377 p += strspn(p, WHITESPACE);
378
379 if (isempty(p))
380 return;
381
382 iovec[n++] = IOVEC_MAKE_STRING("_TRANSPORT=audit");
383
384 xsprintf(type_field, "_AUDIT_TYPE=%i", type);
385 iovec[n++] = IOVEC_MAKE_STRING(type_field);
386
387 xsprintf(id_field, "_AUDIT_ID=%" PRIu64, id);
388 iovec[n++] = IOVEC_MAKE_STRING(id_field);
389
390 assert_cc(4 == LOG_FAC(LOG_AUTH));
391 iovec[n++] = IOVEC_MAKE_STRING("SYSLOG_FACILITY=4");
392 iovec[n++] = IOVEC_MAKE_STRING("SYSLOG_IDENTIFIER=audit");
393
394 type_name = audit_type_name_alloca(type);
395
396 type_field_name = strjoina("_AUDIT_TYPE_NAME=", type_name);
397 iovec[n++] = IOVEC_MAKE_STRING(type_field_name);
398
399 _cleanup_free_ char *mm_alloc = strjoin("MESSAGE=", type_name, " ", p);
400 if (mm_alloc)
401 mm = mm_alloc;
402 else
403 mm = strjoina("MESSAGE=", type_name, " (message is truncated because of OOM)");
404 iovec[n++] = IOVEC_MAKE_STRING(mm);
405
406 z = n;
407
408 map_all_fields(p, map_fields_kernel, "_AUDIT_FIELD_", true, iovec, &n, n + N_IOVEC_AUDIT_FIELDS);
409
410 manager_dispatch_message(m, iovec, n, ELEMENTSOF(iovec), NULL,
411 TIMEVAL_STORE((usec_t) seconds * USEC_PER_SEC + (usec_t) msec * USEC_PER_MSEC),
412 LOG_NOTICE, 0);
413
414 /* free() all entries that map_all_fields() added. All others are allocated on the stack, constant,
415 * or freed by their _cleanup_ attributes. */
416 for (; z < n; z++)
417 free(iovec[z].iov_base);
418 }
419
420 void manager_process_audit_message(
421 Manager *m,
422 const void *buffer,
423 size_t buffer_size,
424 const struct ucred *ucred,
425 const union sockaddr_union *sa,
426 socklen_t salen) {
427
428 const struct nlmsghdr *nl = buffer;
429
430 assert(m);
431
432 if (buffer_size < ALIGN(sizeof(struct nlmsghdr)))
433 return;
434
435 assert(buffer);
436
437 /* Filter out fake data */
438 if (!sa ||
439 salen != sizeof(struct sockaddr_nl) ||
440 sa->nl.nl_family != AF_NETLINK ||
441 sa->nl.nl_pid != 0) {
442 log_debug("Audit netlink message from invalid sender.");
443 return;
444 }
445
446 if (!ucred || ucred->pid != 0) {
447 log_debug("Audit netlink message with invalid credentials.");
448 return;
449 }
450
451 if (!NLMSG_OK(nl, buffer_size)) {
452 log_ratelimit_error(JOURNAL_LOG_RATELIMIT, "Audit netlink message truncated.");
453 return;
454 }
455
456 /* Ignore special Netlink messages */
457 if (IN_SET(nl->nlmsg_type, NLMSG_NOOP, NLMSG_ERROR))
458 return;
459
460 /* Except AUDIT_USER, all messages below AUDIT_FIRST_USER_MSG are control messages, let's ignore those */
461 if (nl->nlmsg_type < AUDIT_FIRST_USER_MSG && nl->nlmsg_type != AUDIT_USER)
462 return;
463
464 process_audit_string(m, nl->nlmsg_type, NLMSG_DATA(nl), nl->nlmsg_len - ALIGN(sizeof(struct nlmsghdr)));
465 }
466
467 static int manager_set_kernel_audit(Manager *m) {
468 int r;
469
470 assert(m);
471 assert(m->audit_fd >= 0);
472 assert(m->config.set_audit >= 0);
473
474 if (m->config.set_audit == AUDIT_KEEP)
475 return 0;
476
477 /* In the following, we can handle 'set_audit' as a boolean. */
478 assert(IN_SET(m->config.set_audit, AUDIT_NO, AUDIT_YES));
479
480 struct {
481 union {
482 struct nlmsghdr header;
483 uint8_t header_space[NLMSG_HDRLEN];
484 };
485 struct audit_status body;
486 } _packed_ request = {
487 .header.nlmsg_len = NLMSG_LENGTH(sizeof(struct audit_status)),
488 .header.nlmsg_type = AUDIT_SET,
489 .header.nlmsg_flags = NLM_F_REQUEST,
490 .header.nlmsg_seq = 1,
491 .header.nlmsg_pid = 0,
492 .body.mask = AUDIT_STATUS_ENABLED,
493 .body.enabled = m->config.set_audit,
494 };
495 union sockaddr_union sa = {
496 .nl.nl_family = AF_NETLINK,
497 .nl.nl_pid = 0,
498 };
499 struct iovec iovec = {
500 .iov_base = &request,
501 .iov_len = NLMSG_LENGTH(sizeof(struct audit_status)),
502 };
503 struct msghdr mh = {
504 .msg_iov = &iovec,
505 .msg_iovlen = 1,
506 .msg_name = &sa.sa,
507 .msg_namelen = sizeof(sa.nl),
508 };
509
510 r = 0;
511 ssize_t n = sendmsg(m->audit_fd, &mh, MSG_NOSIGNAL);
512 if (n < 0)
513 r = -errno;
514 if (n != NLMSG_LENGTH(sizeof(struct audit_status)))
515 r = SYNTHETIC_ERRNO(EIO);
516 if (r < 0)
517 return log_warning_errno(r, "Failed to %s kernel auditing: %m", enable_disable(m->config.set_audit));
518
519 /* We don't wait for the result here, we can't do anything about it anyway. */
520
521 log_debug("Auditing in kernel is %s.", enabled_disabled(m->config.set_audit));
522 return 0;
523 }
524
525 int manager_open_audit(Manager *m) {
526 int r;
527
528 if (m->audit_fd < 0) {
529 static const union sockaddr_union sa = {
530 .nl.nl_family = AF_NETLINK,
531 .nl.nl_pid = 0,
532 .nl.nl_groups = AUDIT_NLGRP_READLOG,
533 };
534
535 m->audit_fd = socket(AF_NETLINK, SOCK_RAW|SOCK_CLOEXEC|SOCK_NONBLOCK, NETLINK_AUDIT);
536 if (m->audit_fd < 0) {
537 if (ERRNO_IS_NOT_SUPPORTED(errno))
538 log_debug("Audit not supported in the kernel.");
539 else
540 log_warning_errno(errno, "Failed to create audit socket, ignoring: %m");
541
542 return 0;
543 }
544
545 if (bind(m->audit_fd, &sa.sa, sizeof(sa.nl)) < 0) {
546 log_warning_errno(errno,
547 "Failed to join audit multicast group. "
548 "The kernel is probably too old or multicast reading is not supported. "
549 "Ignoring: %m");
550 m->audit_fd = safe_close(m->audit_fd);
551 return 0;
552 }
553 } else
554 (void) fd_nonblock(m->audit_fd, true);
555
556 r = setsockopt_int(m->audit_fd, SOL_SOCKET, SO_PASSCRED, true);
557 if (r < 0)
558 return log_error_errno(r, "Failed to set SO_PASSCRED on audit socket: %m");
559
560 r = sd_event_add_io(m->event, &m->audit_event_source, m->audit_fd, EPOLLIN, manager_process_datagram, m);
561 if (r < 0)
562 return log_error_errno(r, "Failed to add audit fd to event loop: %m");
563
564 (void) manager_set_kernel_audit(m);
565 return 0;
566 }
567
568 void manager_reset_kernel_audit(Manager *m, AuditSetMode old_set_audit) {
569 assert(m);
570
571 if (m->audit_fd < 0)
572 return;
573
574 if (m->config.set_audit == old_set_audit)
575 return;
576
577 (void) manager_set_kernel_audit(m);
578 }