Book a Demo!
CoCalc Logo Icon
StoreFeaturesDocsShareSupportNewsAboutPoliciesSign UpSign In
freebsd
GitHub Repository: freebsd/freebsd-src
Path: blob/main/tests/sys/audit/utils.c
39492 views
1
/*-
2
* Copyright 2018 Aniket Pandey
3
*
4
* Redistribution and use in source and binary forms, with or without
5
* modification, are permitted provided that the following conditions
6
* are met:
7
* 1. Redistributions of source code must retain the above copyright
8
* notice, this list of conditions and the following disclaimer.
9
* 2. Redistributions in binary form must reproduce the above copyright
10
* notice, this list of conditions and the following disclaimer in the
11
* documentation and/or other materials provided with the distribution.
12
*
13
* THIS SOFTWARE IS PROVIDED BY THE AUTHOR AND CONTRIBUTORS ``AS IS'' AND
14
* ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE
15
* IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE
16
* ARE DISCLAIMED. IN NO EVENT SHALL THE AUTHOR OR CONTRIBUTORS BE LIABLE
17
* FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL
18
* DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS
19
* OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF
20
* OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION)
21
* HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT
22
* LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY
23
* SUCH DAMAGE.
24
*/
25
26
#include <sys/types.h>
27
#include <sys/extattr.h>
28
#include <sys/ioctl.h>
29
30
#include <bsm/libbsm.h>
31
#include <bsm/auditd_lib.h>
32
#include <security/audit/audit_ioctl.h>
33
34
#include <atf-c.h>
35
#include <errno.h>
36
#include <fcntl.h>
37
#include <stdlib.h>
38
#include <string.h>
39
#include <time.h>
40
#include <unistd.h>
41
42
#include "utils.h"
43
44
/*
45
* Checks the presence of "auditregex" in auditpipe(4) after the
46
* corresponding system call has been triggered.
47
*/
48
static bool
49
get_records(const char *auditregex, FILE *pipestream)
50
{
51
uint8_t *buff;
52
tokenstr_t token;
53
ssize_t size = 1024;
54
char membuff[size];
55
char del[] = ",";
56
int reclen, bytes = 0;
57
FILE *memstream;
58
59
/*
60
* Open a stream on 'membuff' (address to memory buffer) for storing
61
* the audit records in the default mode.'reclen' is the length of the
62
* available records from auditpipe which is passed to the functions
63
* au_fetch_tok(3) and au_print_flags_tok(3) for further use.
64
*/
65
ATF_REQUIRE((memstream = fmemopen(membuff, size, "w")) != NULL);
66
ATF_REQUIRE((reclen = au_read_rec(pipestream, &buff)) != -1);
67
68
/*
69
* Iterate through each BSM token, extracting the bits that are
70
* required to start processing the token sequences.
71
*/
72
while (bytes < reclen) {
73
if (au_fetch_tok(&token, buff + bytes, reclen - bytes) == -1) {
74
perror("au_read_rec");
75
atf_tc_fail("Incomplete Audit Record");
76
}
77
78
/* Print the tokens as they are obtained, in the default form */
79
au_print_flags_tok(memstream, &token, del, AU_OFLAG_NONE);
80
fputc(',', memstream);
81
bytes += token.len;
82
}
83
84
free(buff);
85
ATF_REQUIRE_EQ(0, fclose(memstream));
86
return (atf_utils_grep_string("%s", membuff, auditregex));
87
}
88
89
/*
90
* Override the system-wide audit mask settings in /etc/security/audit_control
91
* and set the auditpipe's maximum allowed queue length limit
92
*/
93
static void
94
set_preselect_mode(int filedesc, au_mask_t *fmask)
95
{
96
int qlimit_max;
97
int fmode = AUDITPIPE_PRESELECT_MODE_LOCAL;
98
99
/* Set local preselection mode for auditing */
100
if (ioctl(filedesc, AUDITPIPE_SET_PRESELECT_MODE, &fmode) < 0)
101
atf_tc_fail("Preselection mode: %s", strerror(errno));
102
103
/* Set local preselection flag corresponding to the audit_event */
104
if (ioctl(filedesc, AUDITPIPE_SET_PRESELECT_FLAGS, fmask) < 0)
105
atf_tc_fail("Preselection flag: %s", strerror(errno));
106
107
/* Set local preselection flag for non-attributable audit_events */
108
if (ioctl(filedesc, AUDITPIPE_SET_PRESELECT_NAFLAGS, fmask) < 0)
109
atf_tc_fail("Preselection naflag: %s", strerror(errno));
110
111
/* Query the maximum possible queue length limit for auditpipe */
112
if (ioctl(filedesc, AUDITPIPE_GET_QLIMIT_MAX, &qlimit_max) < 0)
113
atf_tc_fail("Query max-limit: %s", strerror(errno));
114
115
/* Set the queue length limit as obtained from previous step */
116
if (ioctl(filedesc, AUDITPIPE_SET_QLIMIT, &qlimit_max) < 0)
117
atf_tc_fail("Set max-qlimit: %s", strerror(errno));
118
119
/* This removes any outstanding record on the auditpipe */
120
if (ioctl(filedesc, AUDITPIPE_FLUSH) < 0)
121
atf_tc_fail("Auditpipe flush: %s", strerror(errno));
122
}
123
124
/*
125
* Get the corresponding audit_mask for class-name "name" then set the
126
* success and failure bits for fmask to be used as the ioctl argument
127
*/
128
static au_mask_t
129
get_audit_mask(const char *name)
130
{
131
au_mask_t fmask;
132
au_class_ent_t *class;
133
134
ATF_REQUIRE((class = getauclassnam(name)) != NULL);
135
fmask.am_success = class->ac_class;
136
fmask.am_failure = class->ac_class;
137
return (fmask);
138
}
139
140
/*
141
* Loop until the auditpipe returns something, check if it is what
142
* we want, else repeat the procedure until ppoll(2) times out.
143
*/
144
static void
145
check_auditpipe(struct pollfd fd[], const char *auditregex, FILE *pipestream)
146
{
147
struct timespec currtime, endtime, timeout;
148
149
/* Set the expire time for poll(2) while waiting for syscall audit */
150
ATF_REQUIRE_EQ(0, clock_gettime(CLOCK_MONOTONIC, &endtime));
151
/* Set limit to 30 seconds total and ~10s without an event. */
152
endtime.tv_sec += 30;
153
154
for (;;) {
155
/* Update the time left for auditpipe to return any event */
156
ATF_REQUIRE_EQ(0, clock_gettime(CLOCK_MONOTONIC, &currtime));
157
timespecsub(&endtime, &currtime, &timeout);
158
timeout.tv_sec = MIN(timeout.tv_sec, 9);
159
if (timeout.tv_sec < 0) {
160
atf_tc_fail("%s not found in auditpipe within the "
161
"time limit", auditregex);
162
}
163
164
switch (ppoll(fd, 1, &timeout, NULL)) {
165
/* ppoll(2) returns, check if it's what we want */
166
case 1:
167
if (fd[0].revents & POLLIN) {
168
if (get_records(auditregex, pipestream))
169
return;
170
} else {
171
atf_tc_fail("Auditpipe returned an "
172
"unknown event %#x", fd[0].revents);
173
}
174
break;
175
176
/* poll(2) timed out */
177
case 0:
178
atf_tc_fail("%s not found in auditpipe within the "
179
"time limit", auditregex);
180
break;
181
182
/* poll(2) standard error */
183
case -1:
184
atf_tc_fail("Poll: %s", strerror(errno));
185
break;
186
187
default:
188
atf_tc_fail("Poll returned too many file descriptors");
189
}
190
}
191
}
192
193
/*
194
* Wrapper functions around static "check_auditpipe"
195
*/
196
static void
197
check_audit_startup(struct pollfd fd[], const char *auditrgx, FILE *pipestream){
198
check_auditpipe(fd, auditrgx, pipestream);
199
}
200
201
void
202
check_audit(struct pollfd fd[], const char *auditrgx, FILE *pipestream) {
203
check_auditpipe(fd, auditrgx, pipestream);
204
205
/* Teardown: /dev/auditpipe's instance opened for this test-suite */
206
ATF_REQUIRE_EQ(0, fclose(pipestream));
207
}
208
209
void
210
skip_if_extattr_not_supported(const char *path)
211
{
212
ssize_t result;
213
214
/*
215
* Some file systems (e.g. tmpfs) do not support extattr, so we need
216
* skip tests that use extattrs. To detect this we can check whether
217
* the extattr_list_file returns EOPNOTSUPP.
218
*/
219
result = extattr_list_file(path, EXTATTR_NAMESPACE_USER, NULL, 0);
220
if (result == -1 && errno == EOPNOTSUPP) {
221
atf_tc_skip("File system does not support extattrs.");
222
}
223
}
224
225
static bool
226
is_auditd_running(void)
227
{
228
int trigger;
229
int err;
230
231
/*
232
* AUDIT_TRIGGER_INITIALIZE is a no-op message on FreeBSD and can
233
* therefore be used to check whether auditd has already been started.
234
* This is significantly cheaper than running `service auditd onestatus`
235
* for each test case. It is also slightly less racy since it will only
236
* return true once auditd() has opened the trigger file rather than
237
* just when the pidfile has been created.
238
*/
239
trigger = AUDIT_TRIGGER_INITIALIZE;
240
err = auditon(A_SENDTRIGGER, &trigger, sizeof(trigger));
241
if (err == 0) {
242
fprintf(stderr, "auditd(8) is running.\n");
243
return (true);
244
} else {
245
/*
246
* A_SENDTRIGGER returns ENODEV if auditd isn't listening,
247
* all other error codes indicate a fatal error.
248
*/
249
ATF_REQUIRE_MSG(errno == ENODEV,
250
"Unexpected error from auditon(2): %s", strerror(errno));
251
return (false);
252
}
253
254
}
255
256
FILE *
257
setup(struct pollfd fd[], const char *name)
258
{
259
au_mask_t fmask, nomask;
260
FILE *pipestream;
261
fmask = get_audit_mask(name);
262
nomask = get_audit_mask("no");
263
264
ATF_REQUIRE((fd[0].fd = open("/dev/auditpipe", O_RDONLY)) != -1);
265
ATF_REQUIRE((pipestream = fdopen(fd[0].fd, "r")) != NULL);
266
fd[0].events = POLLIN;
267
268
/*
269
* Disable stream buffering for read operations from /dev/auditpipe.
270
* Otherwise it is possible that fread(3), called via au_read_rec(3),
271
* can store buffered data in user-space unbeknown to ppoll(2), which
272
* as a result, reports that /dev/auditpipe is empty.
273
*/
274
ATF_REQUIRE_EQ(0, setvbuf(pipestream, NULL, _IONBF, 0));
275
276
/* Set local preselection audit_class as "no" for audit startup */
277
set_preselect_mode(fd[0].fd, &nomask);
278
if (!is_auditd_running()) {
279
fprintf(stderr, "Running audit_quick_start() for testing... ");
280
/*
281
* Previously, this test started auditd using
282
* `service auditd onestart`. However, there is a race condition
283
* there since service can return before auditd(8) has
284
* fully started (once the daemon parent process has forked)
285
* and this can cause check_audit_startup() to fail sometimes.
286
*
287
* In the CheriBSD CI this caused the first test executed by
288
* kyua (administrative:acct_failure) to fail every time, but
289
* subsequent ones would almost always succeed.
290
*
291
* To avoid this problem (and as a nice side-effect this speeds
292
* up the test quite a bit), we register this process as a
293
* "fake" auditd(8) using the audit_quick_start() function from
294
* libauditd.
295
*/
296
atf_utils_create_file("started_fake_auditd", "yes\n");
297
ATF_REQUIRE(atf_utils_file_exists("started_fake_auditd"));
298
ATF_REQUIRE_EQ_MSG(0, audit_quick_start(),
299
"Failed to start fake auditd: %m");
300
fprintf(stderr, "done.\n");
301
/* audit_quick_start() should log an audit start event. */
302
check_audit_startup(fd, "audit startup", pipestream);
303
/*
304
* If we exit cleanly shutdown audit_quick_start(), if not
305
* cleanup() will take care of it.
306
* This is not required, but makes it easier to run individual
307
* tests outside of kyua.
308
*/
309
atexit(cleanup);
310
}
311
312
/* Set local preselection parameters specific to "name" audit_class */
313
set_preselect_mode(fd[0].fd, &fmask);
314
return (pipestream);
315
}
316
317
void
318
cleanup(void)
319
{
320
if (atf_utils_file_exists("started_fake_auditd")) {
321
fprintf(stderr, "Running audit_quick_stop()... ");
322
if (audit_quick_stop() != 0) {
323
fprintf(stderr, "Failed to stop fake auditd: %m\n");
324
abort();
325
}
326
fprintf(stderr, "done.\n");
327
unlink("started_fake_auditd");
328
}
329
}
330
331