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