1 /* SPDX-License-Identifier: LGPL-2.1-or-later */
2
3 #include <errno.h>
4 #include <linux/netlink.h>
5 #include <stdio.h>
6 #include <sys/socket.h>
7
8 #include "alloc-util.h"
9 #include "audit-util.h"
10 #include "fd-util.h"
11 #include "fileio.h"
12 #include "macro.h"
13 #include "parse-util.h"
14 #include "process-util.h"
15 #include "user-util.h"
16
audit_session_from_pid(pid_t pid,uint32_t * id)17 int audit_session_from_pid(pid_t pid, uint32_t *id) {
18 _cleanup_free_ char *s = NULL;
19 const char *p;
20 uint32_t u;
21 int r;
22
23 assert(id);
24
25 /* We don't convert ENOENT to ESRCH here, since we can't
26 * really distinguish between "audit is not available in the
27 * kernel" and "the process does not exist", both which will
28 * result in ENOENT. */
29
30 p = procfs_file_alloca(pid, "sessionid");
31
32 r = read_one_line_file(p, &s);
33 if (r < 0)
34 return r;
35
36 r = safe_atou32(s, &u);
37 if (r < 0)
38 return r;
39
40 if (!audit_session_is_valid(u))
41 return -ENODATA;
42
43 *id = u;
44 return 0;
45 }
46
audit_loginuid_from_pid(pid_t pid,uid_t * uid)47 int audit_loginuid_from_pid(pid_t pid, uid_t *uid) {
48 _cleanup_free_ char *s = NULL;
49 const char *p;
50 uid_t u;
51 int r;
52
53 assert(uid);
54
55 p = procfs_file_alloca(pid, "loginuid");
56
57 r = read_one_line_file(p, &s);
58 if (r < 0)
59 return r;
60
61 r = parse_uid(s, &u);
62 if (r == -ENXIO) /* the UID was -1 */
63 return -ENODATA;
64 if (r < 0)
65 return r;
66
67 *uid = u;
68 return 0;
69 }
70
use_audit(void)71 bool 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);
78 if (fd < 0) {
79 cached_use = !IN_SET(errno, EAFNOSUPPORT, EPROTONOSUPPORT, EPERM);
80 if (!cached_use)
81 log_debug_errno(errno, "Won't talk to audit: %m");
82 } else {
83 cached_use = true;
84 safe_close(fd);
85 }
86 }
87
88 return cached_use;
89 }
90