]> git.ipfire.org Git - thirdparty/systemd.git/blame - src/basic/audit.c
util-lib: split out fd-related operations into fd-util.[ch]
[thirdparty/systemd.git] / src / basic / audit.c
CommitLineData
d7832d2c
KS
1/*-*- Mode: C; c-basic-offset: 8; indent-tabs-mode: nil -*-*/
2
3/***
4 This file is part of systemd.
5
6 Copyright 2010 Lennart Poettering
7
8 systemd is free software; you can redistribute it and/or modify it
5430f7f2
LP
9 under the terms of the GNU Lesser General Public License as published by
10 the Free Software Foundation; either version 2.1 of the License, or
d7832d2c
KS
11 (at your option) any later version.
12
13 systemd is distributed in the hope that it will be useful, but
14 WITHOUT ANY WARRANTY; without even the implied warranty of
15 MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU
5430f7f2 16 Lesser General Public License for more details.
d7832d2c 17
5430f7f2 18 You should have received a copy of the GNU Lesser General Public License
d7832d2c
KS
19 along with systemd; If not, see <http://www.gnu.org/licenses/>.
20***/
21
d7832d2c 22#include <errno.h>
d7832d2c 23#include <stdio.h>
d7832d2c 24
d7832d2c 25#include "audit.h"
3ffd4af2 26#include "fd-util.h"
a5c32cff 27#include "fileio.h"
3ffd4af2
LP
28#include "macro.h"
29#include "process-util.h"
30#include "util.h"
d7832d2c
KS
31
32int audit_session_from_pid(pid_t pid, uint32_t *id) {
5b12334d
LP
33 _cleanup_free_ char *s = NULL;
34 const char *p;
d7832d2c
KS
35 uint32_t u;
36 int r;
37
38 assert(id);
39
d7e46e01
LP
40 /* We don't convert ENOENT to ESRCH here, since we can't
41 * really distuingish between "audit is not available in the
42 * kernel" and "the process does not exist", both which will
43 * result in ENOENT. */
44
b68fa010 45 p = procfs_file_alloca(pid, "sessionid");
d7832d2c 46
5b12334d 47 r = read_one_line_file(p, &s);
d7832d2c
KS
48 if (r < 0)
49 return r;
50
51 r = safe_atou32(s, &u);
d7832d2c
KS
52 if (r < 0)
53 return r;
54
cfeaa44a 55 if (u == AUDIT_SESSION_INVALID || u <= 0)
d7e46e01 56 return -ENODATA;
d7832d2c
KS
57
58 *id = u;
59 return 0;
60}
61
62int audit_loginuid_from_pid(pid_t pid, uid_t *uid) {
5b12334d
LP
63 _cleanup_free_ char *s = NULL;
64 const char *p;
d7832d2c
KS
65 uid_t u;
66 int r;
67
68 assert(uid);
69
b68fa010 70 p = procfs_file_alloca(pid, "loginuid");
d7832d2c 71
5b12334d 72 r = read_one_line_file(p, &s);
d7832d2c
KS
73 if (r < 0)
74 return r;
75
76 r = parse_uid(s, &u);
d7e46e01
LP
77 if (r == -ENXIO) /* the UID was -1 */
78 return -ENODATA;
d7832d2c
KS
79 if (r < 0)
80 return r;
81
d7832d2c
KS
82 *uid = (uid_t) u;
83 return 0;
84}
cfb1f5df
LP
85
86bool use_audit(void) {
87 static int cached_use = -1;
88
89 if (cached_use < 0) {
90 int fd;
91
92 fd = socket(AF_NETLINK, SOCK_RAW|SOCK_CLOEXEC|SOCK_NONBLOCK, NETLINK_AUDIT);
93 if (fd < 0)
94 cached_use = errno != EAFNOSUPPORT && errno != EPROTONOSUPPORT;
95 else {
96 cached_use = true;
97 safe_close(fd);
98 }
99 }
100
101 return cached_use;
102}