]> git.ipfire.org Git - thirdparty/systemd.git/blame - src/basic/audit-util.c
util: introduce memcmp_safe()
[thirdparty/systemd.git] / src / basic / audit-util.c
CommitLineData
53e1b683 1/* SPDX-License-Identifier: LGPL-2.1+ */
d7832d2c 2
d7832d2c 3#include <errno.h>
11c3a366 4#include <linux/netlink.h>
d7832d2c 5#include <stdio.h>
11c3a366 6#include <sys/socket.h>
d7832d2c 7
b5efdb8a 8#include "alloc-util.h"
430f0182 9#include "audit-util.h"
3ffd4af2 10#include "fd-util.h"
a5c32cff 11#include "fileio.h"
3ffd4af2 12#include "macro.h"
6bedfcbb 13#include "parse-util.h"
3ffd4af2 14#include "process-util.h"
b1d4f8e1 15#include "user-util.h"
d7832d2c
KS
16
17int audit_session_from_pid(pid_t pid, uint32_t *id) {
5b12334d
LP
18 _cleanup_free_ char *s = NULL;
19 const char *p;
d7832d2c
KS
20 uint32_t u;
21 int r;
22
23 assert(id);
24
d7e46e01
LP
25 /* We don't convert ENOENT to ESRCH here, since we can't
26 * really distuingish between "audit is not available in the
27 * kernel" and "the process does not exist", both which will
28 * result in ENOENT. */
29
b68fa010 30 p = procfs_file_alloca(pid, "sessionid");
d7832d2c 31
5b12334d 32 r = read_one_line_file(p, &s);
d7832d2c
KS
33 if (r < 0)
34 return r;
35
36 r = safe_atou32(s, &u);
d7832d2c
KS
37 if (r < 0)
38 return r;
39
3a87a86e 40 if (!audit_session_is_valid(u))
d7e46e01 41 return -ENODATA;
d7832d2c
KS
42
43 *id = u;
44 return 0;
45}
46
47int audit_loginuid_from_pid(pid_t pid, uid_t *uid) {
5b12334d
LP
48 _cleanup_free_ char *s = NULL;
49 const char *p;
d7832d2c
KS
50 uid_t u;
51 int r;
52
53 assert(uid);
54
b68fa010 55 p = procfs_file_alloca(pid, "loginuid");
d7832d2c 56
5b12334d 57 r = read_one_line_file(p, &s);
d7832d2c
KS
58 if (r < 0)
59 return r;
60
61 r = parse_uid(s, &u);
d7e46e01
LP
62 if (r == -ENXIO) /* the UID was -1 */
63 return -ENODATA;
d7832d2c
KS
64 if (r < 0)
65 return r;
66
3a87a86e 67 *uid = u;
d7832d2c
KS
68 return 0;
69}
cfb1f5df
LP
70
71bool use_audit(void) {
72 static int cached_use = -1;
73
74 if (cached_use < 0) {
75 int fd;
76
77 fd = socket(AF_NETLINK, SOCK_RAW|SOCK_CLOEXEC|SOCK_NONBLOCK, NETLINK_AUDIT);
f006b30b
GS
78 if (fd < 0) {
79 cached_use = !IN_SET(errno, EAFNOSUPPORT, EPROTONOSUPPORT, EPERM);
13bb68bb
ZJS
80 if (!cached_use)
81 log_debug_errno(errno, "Won't talk to audit: %m");
82 } else {
cfb1f5df
LP
83 cached_use = true;
84 safe_close(fd);
85 }
86 }
87
88 return cached_use;
89}