]>
git.ipfire.org Git - thirdparty/systemd.git/blob - src/basic/audit-util.c
7f86f84fa353fb86e70126ea3704ff91724878d6
1 /* SPDX-License-Identifier: LGPL-2.1-or-later */
4 #include <linux/audit.h>
5 #include <linux/netlink.h>
7 #include <sys/socket.h>
9 #include "alloc-util.h"
10 #include "audit-util.h"
13 #include "iovec-util.h"
15 #include "parse-util.h"
16 #include "process-util.h"
17 #include "socket-util.h"
18 #include "user-util.h"
20 int audit_session_from_pid(pid_t pid
, uint32_t *id
) {
21 _cleanup_free_
char *s
= NULL
;
28 /* We don't convert ENOENT to ESRCH here, since we can't
29 * really distinguish between "audit is not available in the
30 * kernel" and "the process does not exist", both which will
31 * result in ENOENT. */
33 p
= procfs_file_alloca(pid
, "sessionid");
35 r
= read_one_line_file(p
, &s
);
39 r
= safe_atou32(s
, &u
);
43 if (!audit_session_is_valid(u
))
50 int audit_loginuid_from_pid(pid_t pid
, uid_t
*uid
) {
51 _cleanup_free_
char *s
= NULL
;
58 p
= procfs_file_alloca(pid
, "loginuid");
60 r
= read_one_line_file(p
, &s
);
65 if (r
== -ENXIO
) /* the UID was -1 */
74 static int try_audit_request(int fd
) {
85 .hdr
.nlmsg_len
= NLMSG_LENGTH(0),
86 .hdr
.nlmsg_type
= AUDIT_GET_FEATURE
,
87 .hdr
.nlmsg_flags
= NLM_F_REQUEST
| NLM_F_ACK
,
89 iov
= IOVEC_MAKE(&msg
, msg
.hdr
.nlmsg_len
);
90 mh
= (struct msghdr
) {
95 if (sendmsg(fd
, &mh
, MSG_NOSIGNAL
) < 0)
98 iov
.iov_len
= sizeof(msg
);
100 n
= recvmsg_safe(fd
, &mh
, 0);
103 if (n
!= NLMSG_LENGTH(sizeof(struct nlmsgerr
)))
106 if (msg
.hdr
.nlmsg_type
!= NLMSG_ERROR
)
109 return msg
.err
.error
;
112 bool use_audit(void) {
113 static int cached_use
= -1;
116 if (cached_use
< 0) {
119 fd
= socket(AF_NETLINK
, SOCK_RAW
|SOCK_CLOEXEC
|SOCK_NONBLOCK
, NETLINK_AUDIT
);
121 cached_use
= !IN_SET(errno
, EAFNOSUPPORT
, EPROTONOSUPPORT
, EPERM
);
123 log_debug_errno(errno
, "Won't talk to audit: %m");
125 /* If we try and use the audit fd but get -ECONNREFUSED, it is because
126 * we are not in the initial user namespace, and the kernel does not
127 * have support for audit outside of the initial user namespace
128 * (see https://elixir.bootlin.com/linux/latest/C/ident/audit_netlink_ok).
130 * If we receive any other error, do not disable audit because we are not
131 * sure that the error indicates that audit will not work in general. */
132 r
= try_audit_request(fd
);
134 cached_use
= r
!= -ECONNREFUSED
;
135 log_debug_errno(r
, cached_use
?
136 "Failed to make request on audit fd, ignoring: %m" :
137 "Won't talk to audit: %m");