• Home
  • Line#
  • Scopes#
  • Navigate#
  • Raw
  • Download
1 /* Copyright (c) 2012 The Chromium OS Authors. All rights reserved.
2  * Use of this source code is governed by a BSD-style license that can be
3  * found in the LICENSE file.
4  */
5 
6 #include <errno.h>
7 #include <stdio.h>
8 #include <stdlib.h>
9 #include <string.h>
10 
11 #include "syscall_filter.h"
12 
13 #include "util.h"
14 
15 /* clang-format off */
16 #define ONE_INSTR	1
17 #define TWO_INSTRS	2
18 
19 #define compiler_warn(_state, _msg, ...)                                       \
20 	warn("%s: %s(%zd): " _msg, __func__, (_state)->filename,               \
21 	     (_state)->line_number, ## __VA_ARGS__)
22 
23 #define compiler_pwarn(_state, _msg, ...)                                      \
24 	compiler_warn(_state, _msg ": %m", ## __VA_ARGS__)
25 /* clang-format on */
26 
seccomp_can_softfail(void)27 int seccomp_can_softfail(void)
28 {
29 #if defined(USE_SECCOMP_SOFTFAIL)
30 	return 1;
31 #endif
32 	return 0;
33 }
34 
str_to_op(const char * op_str)35 int str_to_op(const char *op_str)
36 {
37 	if (!strcmp(op_str, "==")) {
38 		return EQ;
39 	} else if (!strcmp(op_str, "!=")) {
40 		return NE;
41 	} else if (!strcmp(op_str, "<")) {
42 		return LT;
43 	} else if (!strcmp(op_str, "<=")) {
44 		return LE;
45 	} else if (!strcmp(op_str, ">")) {
46 		return GT;
47 	} else if (!strcmp(op_str, ">=")) {
48 		return GE;
49 	} else if (!strcmp(op_str, "&")) {
50 		return SET;
51 	} else if (!strcmp(op_str, "in")) {
52 		return IN;
53 	} else {
54 		return 0;
55 	}
56 }
57 
new_instr_buf(size_t count)58 struct sock_filter *new_instr_buf(size_t count)
59 {
60 	struct sock_filter *buf = calloc(count, sizeof(struct sock_filter));
61 	if (!buf)
62 		die("could not allocate BPF instruction buffer");
63 
64 	return buf;
65 }
66 
new_filter_block(void)67 struct filter_block *new_filter_block(void)
68 {
69 	struct filter_block *block = calloc(1, sizeof(struct filter_block));
70 	if (!block)
71 		die("could not allocate BPF filter block");
72 
73 	block->instrs = NULL;
74 	block->last = block->next = NULL;
75 
76 	return block;
77 }
78 
append_filter_block(struct filter_block * head,struct sock_filter * instrs,size_t len)79 void append_filter_block(struct filter_block *head, struct sock_filter *instrs,
80 			 size_t len)
81 {
82 	struct filter_block *new_last;
83 
84 	/*
85 	 * If |head| has no filter assigned yet,
86 	 * we don't create a new node.
87 	 */
88 	if (head->instrs == NULL) {
89 		new_last = head;
90 	} else {
91 		new_last = new_filter_block();
92 		if (head->next != NULL) {
93 			head->last->next = new_last;
94 			head->last = new_last;
95 		} else {
96 			head->last = head->next = new_last;
97 		}
98 		head->total_len += len;
99 	}
100 
101 	new_last->instrs = instrs;
102 	new_last->total_len = new_last->len = len;
103 	new_last->last = new_last->next = NULL;
104 }
105 
extend_filter_block_list(struct filter_block * list,struct filter_block * another)106 void extend_filter_block_list(struct filter_block *list,
107 			      struct filter_block *another)
108 {
109 	if (list->last != NULL) {
110 		list->last->next = another;
111 		list->last = another->last;
112 	} else {
113 		list->next = another;
114 		list->last = another->last;
115 	}
116 	list->total_len += another->total_len;
117 }
118 
append_ret_kill(struct filter_block * head)119 void append_ret_kill(struct filter_block *head)
120 {
121 	struct sock_filter *filter = new_instr_buf(ONE_INSTR);
122 	set_bpf_ret_kill(filter);
123 	append_filter_block(head, filter, ONE_INSTR);
124 }
125 
append_ret_kill_process(struct filter_block * head)126 void append_ret_kill_process(struct filter_block *head)
127 {
128 	struct sock_filter *filter = new_instr_buf(ONE_INSTR);
129 	set_bpf_ret_kill_process(filter);
130 	append_filter_block(head, filter, ONE_INSTR);
131 }
132 
append_ret_trap(struct filter_block * head)133 void append_ret_trap(struct filter_block *head)
134 {
135 	struct sock_filter *filter = new_instr_buf(ONE_INSTR);
136 	set_bpf_ret_trap(filter);
137 	append_filter_block(head, filter, ONE_INSTR);
138 }
139 
append_ret_errno(struct filter_block * head,int errno_val)140 void append_ret_errno(struct filter_block *head, int errno_val)
141 {
142 	struct sock_filter *filter = new_instr_buf(ONE_INSTR);
143 	set_bpf_ret_errno(filter, errno_val);
144 	append_filter_block(head, filter, ONE_INSTR);
145 }
146 
append_ret_log(struct filter_block * head)147 void append_ret_log(struct filter_block *head)
148 {
149 	struct sock_filter *filter = new_instr_buf(ONE_INSTR);
150 	set_bpf_ret_log(filter);
151 	append_filter_block(head, filter, ONE_INSTR);
152 }
153 
append_allow_syscall(struct filter_block * head,int nr)154 void append_allow_syscall(struct filter_block *head, int nr)
155 {
156 	struct sock_filter *filter = new_instr_buf(ALLOW_SYSCALL_LEN);
157 	size_t len = bpf_allow_syscall(filter, nr);
158 	if (len != ALLOW_SYSCALL_LEN)
159 		die("error building syscall number comparison");
160 
161 	append_filter_block(head, filter, len);
162 }
163 
copy_parser_state(struct parser_state * src,struct parser_state * dest)164 void copy_parser_state(struct parser_state *src, struct parser_state *dest)
165 {
166 	const char *filename = strdup(src->filename);
167 	if (!filename)
168 		pdie("strdup(src->filename) failed");
169 
170 	dest->line_number = src->line_number;
171 	dest->filename = filename;
172 }
173 
174 /*
175  * Inserts the current state into the array of previous syscall states at the
176  * index |ind| if it is a newly encountered syscall. Returns true if it is a
177  * newly encountered syscall and false if it is a duplicate.
178  */
insert_and_check_duplicate_syscall(struct parser_state ** previous_syscalls,struct parser_state * state,size_t ind)179 bool insert_and_check_duplicate_syscall(struct parser_state **previous_syscalls,
180 					struct parser_state *state, size_t ind)
181 {
182 	if (ind >= get_num_syscalls()) {
183 		die("syscall index %zu out of range: %zu total syscalls", ind,
184 		    get_num_syscalls());
185 	}
186 	struct parser_state *prev_state_ptr = previous_syscalls[ind];
187 	if (prev_state_ptr == NULL) {
188 		previous_syscalls[ind] = calloc(1, sizeof(struct parser_state));
189 		if (!previous_syscalls[ind])
190 			die("could not allocate parser_state buffer");
191 		copy_parser_state(state, previous_syscalls[ind]);
192 		return true;
193 	}
194 	return false;
195 }
196 
allow_logging_syscalls(struct filter_block * head)197 void allow_logging_syscalls(struct filter_block *head)
198 {
199 	unsigned int i;
200 
201 	for (i = 0; i < log_syscalls_len; i++) {
202 		warn("allowing syscall: %s", log_syscalls[i]);
203 		append_allow_syscall(head,
204 				     lookup_syscall(log_syscalls[i], NULL));
205 	}
206 }
207 
get_label_id(struct bpf_labels * labels,const char * label_str)208 unsigned int get_label_id(struct bpf_labels *labels, const char *label_str)
209 {
210 	int label_id = bpf_label_id(labels, label_str);
211 	if (label_id < 0)
212 		die("could not allocate BPF label string");
213 	return label_id;
214 }
215 
group_end_lbl(struct bpf_labels * labels,int nr,int idx)216 unsigned int group_end_lbl(struct bpf_labels *labels, int nr, int idx)
217 {
218 	char lbl_str[MAX_BPF_LABEL_LEN];
219 	snprintf(lbl_str, MAX_BPF_LABEL_LEN, "%d_%d_end", nr, idx);
220 	return get_label_id(labels, lbl_str);
221 }
222 
success_lbl(struct bpf_labels * labels,int nr)223 unsigned int success_lbl(struct bpf_labels *labels, int nr)
224 {
225 	char lbl_str[MAX_BPF_LABEL_LEN];
226 	snprintf(lbl_str, MAX_BPF_LABEL_LEN, "%d_success", nr);
227 	return get_label_id(labels, lbl_str);
228 }
229 
is_implicit_relative_path(const char * filename)230 int is_implicit_relative_path(const char *filename)
231 {
232 	return filename[0] != '/' && (filename[0] != '.' || filename[1] != '/');
233 }
234 
compile_atom(struct parser_state * state,struct filter_block * head,char * atom,struct bpf_labels * labels,int nr,int grp_idx)235 int compile_atom(struct parser_state *state, struct filter_block *head,
236 		 char *atom, struct bpf_labels *labels, int nr, int grp_idx)
237 {
238 	/* Splits the atom. */
239 	char *atom_ptr = NULL;
240 	char *argidx_str = strtok_r(atom, " ", &atom_ptr);
241 	if (argidx_str == NULL) {
242 		compiler_warn(state, "empty atom");
243 		return -1;
244 	}
245 
246 	char *operator_str = strtok_r(NULL, " ", &atom_ptr);
247 	if (operator_str == NULL) {
248 		compiler_warn(state, "invalid atom '%s'", argidx_str);
249 		return -1;
250 	}
251 
252 	char *constant_str = strtok_r(NULL, " ", &atom_ptr);
253 	if (constant_str == NULL) {
254 		compiler_warn(state, "invalid atom '%s %s'", argidx_str,
255 			      operator_str);
256 		return -1;
257 	}
258 
259 	/* Checks that there are no extra tokens. */
260 	const char *extra = strtok_r(NULL, " ", &atom_ptr);
261 	if (extra != NULL) {
262 		compiler_warn(state, "extra token '%s'", extra);
263 		return -1;
264 	}
265 
266 	if (strncmp(argidx_str, "arg", 3)) {
267 		compiler_warn(state, "invalid argument token '%s'", argidx_str);
268 		return -1;
269 	}
270 
271 	char *argidx_ptr;
272 	long int argidx = strtol(argidx_str + 3, &argidx_ptr, 10);
273 	/*
274 	 * Checks that an actual argument index was parsed,
275 	 * and that there was nothing left after the index.
276 	 */
277 	if (argidx_ptr == argidx_str + 3 || *argidx_ptr != '\0') {
278 		compiler_warn(state, "invalid argument index '%s'",
279 			      argidx_str + 3);
280 		return -1;
281 	}
282 
283 	int op = str_to_op(operator_str);
284 	if (op < MIN_OPERATOR) {
285 		compiler_warn(state, "invalid operator '%s'", operator_str);
286 		return -1;
287 	}
288 
289 	char *constant_str_ptr;
290 	long int c = parse_constant(constant_str, &constant_str_ptr);
291 	if (constant_str_ptr == constant_str) {
292 		compiler_warn(state, "invalid constant '%s'", constant_str);
293 		return -1;
294 	}
295 
296 	/*
297 	 * Looks up the label for the end of the AND statement
298 	 * this atom belongs to.
299 	 */
300 	unsigned int id = group_end_lbl(labels, nr, grp_idx);
301 
302 	/*
303 	 * Builds a BPF comparison between a syscall argument
304 	 * and a constant.
305 	 * The comparison lives inside an AND statement.
306 	 * If the comparison succeeds, we continue
307 	 * to the next comparison.
308 	 * If this comparison fails, the whole AND statement
309 	 * will fail, so we jump to the end of this AND statement.
310 	 */
311 	struct sock_filter *comp_block;
312 	size_t len = bpf_arg_comp(&comp_block, op, argidx, c, id);
313 	if (len == 0)
314 		return -1;
315 
316 	append_filter_block(head, comp_block, len);
317 	return 0;
318 }
319 
compile_errno(struct parser_state * state,struct filter_block * head,char * ret_errno,enum block_action action)320 int compile_errno(struct parser_state *state, struct filter_block *head,
321 		  char *ret_errno, enum block_action action)
322 {
323 	char *errno_ptr = NULL;
324 
325 	/* Splits the 'return' keyword and the actual errno value. */
326 	char *ret_str = strtok_r(ret_errno, " ", &errno_ptr);
327 	if (!ret_str || strncmp(ret_str, "return", strlen("return")))
328 		return -1;
329 
330 	char *errno_val_str = strtok_r(NULL, " ", &errno_ptr);
331 
332 	if (errno_val_str) {
333 		char *errno_val_ptr;
334 		int errno_val = parse_constant(errno_val_str, &errno_val_ptr);
335 		/* Checks to see if we parsed an actual errno. */
336 		if (errno_val_ptr == errno_val_str || errno_val == -1) {
337 			compiler_warn(state, "invalid errno value '%s'",
338 				      errno_val_ptr);
339 			return -1;
340 		}
341 
342 		append_ret_errno(head, errno_val);
343 	} else {
344 		switch (action) {
345 		case ACTION_RET_KILL:
346 			append_ret_kill(head);
347 			break;
348 		case ACTION_RET_KILL_PROCESS:
349 			append_ret_kill_process(head);
350 			break;
351 		case ACTION_RET_TRAP:
352 			append_ret_trap(head);
353 			break;
354 		case ACTION_RET_LOG:
355 			compiler_warn(state, "invalid action: ACTION_RET_LOG");
356 			return -1;
357 		}
358 	}
359 	return 0;
360 }
361 
compile_policy_line(struct parser_state * state,int nr,const char * policy_line,unsigned int entry_lbl_id,struct bpf_labels * labels,enum block_action action)362 struct filter_block *compile_policy_line(struct parser_state *state, int nr,
363 					 const char *policy_line,
364 					 unsigned int entry_lbl_id,
365 					 struct bpf_labels *labels,
366 					 enum block_action action)
367 {
368 	/*
369 	 * |policy_line| should be an expression of the form:
370 	 * "arg0 == 3 && arg1 == 5 || arg0 == 0x8"
371 	 *
372 	 * This is, an expression in DNF (disjunctive normal form);
373 	 * a disjunction ('||') of one or more conjunctions ('&&')
374 	 * of one or more atoms.
375 	 *
376 	 * Atoms are of the form "arg{DNUM} {OP} {NUM}"
377 	 * where:
378 	 *   - DNUM is a decimal number.
379 	 *   - OP is an operator: ==, !=, & (flags set), or 'in' (inclusion).
380 	 *   - NUM is an octal, decimal, or hexadecimal number.
381 	 *
382 	 * When the syscall arguments make the expression true,
383 	 * the syscall is allowed. If not, the process is killed.
384 	 *
385 	 * To block a syscall without killing the process,
386 	 * |policy_line| can be of the form:
387 	 * "return <errno>"
388 	 *
389 	 * This "return {NUM}" policy line will block the syscall,
390 	 * make it return -1 and set |errno| to NUM.
391 	 *
392 	 * A regular policy line can also include a "return <errno>" clause,
393 	 * separated by a semicolon (';'):
394 	 * "arg0 == 3 && arg1 == 5 || arg0 == 0x8; return {NUM}"
395 	 *
396 	 * If the syscall arguments don't make the expression true,
397 	 * the syscall will be blocked as above instead of killing the process.
398 	 */
399 
400 	size_t len = 0;
401 	int grp_idx = 0;
402 
403 	/* Checks for empty policy lines. */
404 	if (strlen(policy_line) == 0) {
405 		compiler_warn(state, "empty policy line");
406 		return NULL;
407 	}
408 
409 	/* We will modify |policy_line|, so let's make a copy. */
410 	char *line = strdup(policy_line);
411 	if (!line)
412 		return NULL;
413 
414 	/*
415 	 * We build the filter section as a collection of smaller
416 	 * "filter blocks" linked together in a singly-linked list.
417 	 */
418 	struct filter_block *head = new_filter_block();
419 
420 	/*
421 	 * Filter sections begin with a label where the main filter
422 	 * will jump after checking the syscall number.
423 	 */
424 	struct sock_filter *entry_label = new_instr_buf(ONE_INSTR);
425 	set_bpf_lbl(entry_label, entry_lbl_id);
426 	append_filter_block(head, entry_label, ONE_INSTR);
427 
428 	/* Checks whether we're unconditionally blocking this syscall. */
429 	if (strncmp(line, "return", strlen("return")) == 0) {
430 		if (compile_errno(state, head, line, action) < 0) {
431 			free_block_list(head);
432 			free(line);
433 			return NULL;
434 		}
435 		free(line);
436 		return head;
437 	}
438 
439 	/* Splits the optional "return <errno>" part. */
440 	char *line_ptr;
441 	char *arg_filter = strtok_r(line, ";", &line_ptr);
442 	char *ret_errno = strtok_r(NULL, ";", &line_ptr);
443 
444 	/*
445 	 * Splits the policy line by '||' into conjunctions and each conjunction
446 	 * by '&&' into atoms.
447 	 */
448 	char *arg_filter_str = arg_filter;
449 	char *group;
450 	while ((group = tokenize(&arg_filter_str, "||")) != NULL) {
451 		char *group_str = group;
452 		char *comp;
453 		while ((comp = tokenize(&group_str, "&&")) != NULL) {
454 			/* Compiles each atom into a BPF block. */
455 			if (compile_atom(state, head, comp, labels, nr,
456 					 grp_idx) < 0) {
457 				free_block_list(head);
458 				free(line);
459 				return NULL;
460 			}
461 		}
462 		/*
463 		 * If the AND statement succeeds, we're done,
464 		 * so jump to SUCCESS line.
465 		 */
466 		unsigned int id = success_lbl(labels, nr);
467 		struct sock_filter *group_end_block = new_instr_buf(TWO_INSTRS);
468 		len = set_bpf_jump_lbl(group_end_block, id);
469 		/*
470 		 * The end of each AND statement falls after the
471 		 * jump to SUCCESS.
472 		 */
473 		id = group_end_lbl(labels, nr, grp_idx++);
474 		len += set_bpf_lbl(group_end_block + len, id);
475 		append_filter_block(head, group_end_block, len);
476 	}
477 
478 	/*
479 	 * If no AND statements succeed, we end up here,
480 	 * because we never jumped to SUCCESS.
481 	 * If we have to return an errno, do it,
482 	 * otherwise just kill the task.
483 	 */
484 	if (ret_errno) {
485 		if (compile_errno(state, head, ret_errno, action) < 0) {
486 			free_block_list(head);
487 			free(line);
488 			return NULL;
489 		}
490 	} else {
491 		switch (action) {
492 		case ACTION_RET_KILL:
493 			append_ret_kill(head);
494 			break;
495 		case ACTION_RET_KILL_PROCESS:
496 			append_ret_kill_process(head);
497 			break;
498 		case ACTION_RET_TRAP:
499 			append_ret_trap(head);
500 			break;
501 		case ACTION_RET_LOG:
502 			append_ret_log(head);
503 			break;
504 		}
505 	}
506 
507 	/*
508 	 * Every time the filter succeeds we jump to a predefined SUCCESS
509 	 * label. Add that label and BPF RET_ALLOW code now.
510 	 */
511 	unsigned int id = success_lbl(labels, nr);
512 	struct sock_filter *success_block = new_instr_buf(TWO_INSTRS);
513 	len = set_bpf_lbl(success_block, id);
514 	len += set_bpf_ret_allow(success_block + len);
515 	append_filter_block(head, success_block, len);
516 
517 	free(line);
518 	return head;
519 }
520 
parse_include_statement(struct parser_state * state,char * policy_line,unsigned int include_level,const char ** ret_filename)521 int parse_include_statement(struct parser_state *state, char *policy_line,
522 			    unsigned int include_level,
523 			    const char **ret_filename)
524 {
525 	if (strncmp("@include", policy_line, strlen("@include")) != 0) {
526 		compiler_warn(state, "invalid statement '%s'", policy_line);
527 		return -1;
528 	}
529 
530 	if (policy_line[strlen("@include")] != ' ') {
531 		compiler_warn(state, "invalid include statement '%s'",
532 			      policy_line);
533 		return -1;
534 	}
535 
536 	/*
537 	 * Disallow nested includes: only the initial policy file can have
538 	 * @include statements.
539 	 * Nested includes are not currently necessary and make the policy
540 	 * harder to understand.
541 	 */
542 	if (include_level > 0) {
543 		compiler_warn(state, "@include statement nested too deep");
544 		return -1;
545 	}
546 
547 	char *statement = policy_line;
548 	/* Discard "@include" token. */
549 	(void)strsep(&statement, " ");
550 
551 	/*
552 	 * compile_filter() below receives a FILE*, so it's not trivial to open
553 	 * included files relative to the initial policy filename.
554 	 * To avoid mistakes, force the included file path to be absolute
555 	 * (start with '/'), or to explicitly load the file relative to CWD by
556 	 * using './'.
557 	 */
558 	const char *filename = statement;
559 	if (is_implicit_relative_path(filename)) {
560 		compiler_warn(
561 		    state,
562 		    "implicit relative path '%s' not supported, use './%s'",
563 		    filename, filename);
564 		return -1;
565 	}
566 
567 	*ret_filename = filename;
568 	return 0;
569 }
570 
571 /*
572  * This is like getline() but supports line wrapping with \.
573  */
getmultiline(char ** lineptr,size_t * n,FILE * stream)574 static ssize_t getmultiline(char **lineptr, size_t *n, FILE *stream)
575 {
576 	ssize_t ret = getline(lineptr, n, stream);
577 	if (ret < 0)
578 		return ret;
579 
580 	char *line = *lineptr;
581 	/* Eat the newline to make processing below easier. */
582 	if (ret > 0 && line[ret - 1] == '\n')
583 		line[--ret] = '\0';
584 
585 	/* If the line doesn't end in a backslash, we're done. */
586 	if (ret <= 0 || line[ret - 1] != '\\')
587 		return ret;
588 
589 	/* This line ends in a backslash. Get the nextline. */
590 	line[--ret] = '\0';
591 	size_t next_n = 0;
592 	char *next_line = NULL;
593 	ssize_t next_ret = getmultiline(&next_line, &next_n, stream);
594 	if (next_ret == -1) {
595 		free(next_line);
596 		/* We couldn't fully read the line, so return an error. */
597 		return -1;
598 	}
599 
600 	/* Merge the lines. */
601 	*n = ret + next_ret + 2;
602 	line = realloc(line, *n);
603 	if (!line) {
604 		free(next_line);
605 		return -1;
606 	}
607 	line[ret] = ' ';
608 	memcpy(&line[ret + 1], next_line, next_ret + 1);
609 	free(next_line);
610 	*lineptr = line;
611 	return *n - 1;
612 }
613 
compile_file(const char * filename,FILE * policy_file,struct filter_block * head,struct filter_block ** arg_blocks,struct bpf_labels * labels,const struct filter_options * filteropts,struct parser_state ** previous_syscalls,unsigned int include_level)614 int compile_file(const char *filename, FILE *policy_file,
615 		 struct filter_block *head, struct filter_block **arg_blocks,
616 		 struct bpf_labels *labels,
617 		 const struct filter_options *filteropts,
618 		 struct parser_state **previous_syscalls,
619 		 unsigned int include_level)
620 {
621 	/* clang-format off */
622 	struct parser_state state = {
623 		.filename = filename,
624 		.line_number = 0,
625 	};
626 	/* clang-format on */
627 	/*
628 	 * Loop through all the lines in the policy file.
629 	 * Build a jump table for the syscall number.
630 	 * If the policy line has an arg filter, build the arg filter
631 	 * as well.
632 	 * Chain the filter sections together and dump them into
633 	 * the final buffer at the end.
634 	 */
635 	char *line = NULL;
636 	size_t len = 0;
637 	int ret = 0;
638 
639 	while (getmultiline(&line, &len, policy_file) != -1) {
640 		char *policy_line = line;
641 		policy_line = strip(policy_line);
642 
643 		state.line_number++;
644 
645 		/* Allow comments and empty lines. */
646 		if (*policy_line == '#' || *policy_line == '\0') {
647 			/* Reuse |line| in the next getline() call. */
648 			continue;
649 		}
650 
651 		/* Allow @include and @frequency statements. */
652 		if (*policy_line == '@') {
653 			const char *filename = NULL;
654 
655 			/* Ignore @frequency statements. */
656 			if (strncmp("@frequency", policy_line,
657 				    strlen("@frequency")) == 0) {
658 				compiler_warn(&state,
659 					      "ignored @frequency statement");
660 				continue;
661 			}
662 
663 			if (parse_include_statement(&state, policy_line,
664 						    include_level,
665 						    &filename) != 0) {
666 				compiler_warn(
667 				    &state,
668 				    "failed to parse include statement");
669 				ret = -1;
670 				goto free_line;
671 			}
672 
673 			FILE *included_file = fopen(filename, "re");
674 			if (included_file == NULL) {
675 				compiler_pwarn(&state, "fopen('%s') failed",
676 					       filename);
677 				ret = -1;
678 				goto free_line;
679 			}
680 			if (compile_file(filename, included_file, head,
681 					 arg_blocks, labels, filteropts,
682 					 previous_syscalls,
683 					 include_level + 1) == -1) {
684 				compiler_warn(&state, "'@include %s' failed",
685 					      filename);
686 				fclose(included_file);
687 				ret = -1;
688 				goto free_line;
689 			}
690 			fclose(included_file);
691 			continue;
692 		}
693 
694 		/*
695 		 * If it's not a comment, or an empty line, or an @include
696 		 * statement, treat |policy_line| as a regular policy line.
697 		 */
698 		char *syscall_name = strsep(&policy_line, ":");
699 		if (policy_line == NULL) {
700 			warn("compile_file: malformed policy line, missing "
701 			     "':'");
702 			ret = -1;
703 			goto free_line;
704 		}
705 
706 		policy_line = strip(policy_line);
707 		if (*policy_line == '\0') {
708 			compiler_warn(&state, "empty policy line");
709 			ret = -1;
710 			goto free_line;
711 		}
712 
713 		syscall_name = strip(syscall_name);
714 		size_t ind = 0;
715 		int nr = lookup_syscall(syscall_name, &ind);
716 		if (nr < 0) {
717 			compiler_warn(&state, "nonexistent syscall '%s'",
718 				      syscall_name);
719 			if (filteropts->allow_logging) {
720 				/*
721 				 * If we're logging failures, assume we're in a
722 				 * debugging case and continue.
723 				 * This is not super risky because an invalid
724 				 * syscall name is likely caused by a typo or by
725 				 * leftover lines from a different architecture.
726 				 * In either case, not including a policy line
727 				 * is equivalent to killing the process if the
728 				 * syscall is made, so there's no added attack
729 				 * surface.
730 				 */
731 				/* Reuse |line| in the next getline() call. */
732 				continue;
733 			}
734 			ret = -1;
735 			goto free_line;
736 		}
737 
738 		if (!insert_and_check_duplicate_syscall(previous_syscalls,
739 							&state, ind)) {
740 			if (!filteropts->allow_duplicate_syscalls)
741 				ret = -1;
742 			compiler_warn(&state, "syscall %s redefined here",
743 				      lookup_syscall_name(nr));
744 			compiler_warn(previous_syscalls[ind],
745 				      "previous definition here");
746 		}
747 
748 		/*
749 		 * For each syscall, add either a simple ALLOW,
750 		 * or an arg filter block.
751 		 */
752 		if (strcmp(policy_line, "1") == 0) {
753 			/* Add simple ALLOW. */
754 			append_allow_syscall(head, nr);
755 		} else {
756 			/*
757 			 * Create and jump to the label that will hold
758 			 * the arg filter block.
759 			 */
760 			unsigned int id = bpf_label_id(labels, syscall_name);
761 			struct sock_filter *nr_comp =
762 			    new_instr_buf(ALLOW_SYSCALL_LEN);
763 			bpf_allow_syscall_args(nr_comp, nr, id);
764 			append_filter_block(head, nr_comp, ALLOW_SYSCALL_LEN);
765 
766 			/* Build the arg filter block. */
767 			struct filter_block *block =
768 			    compile_policy_line(&state, nr, policy_line, id,
769 						labels, filteropts->action);
770 
771 			if (!block) {
772 				if (*arg_blocks) {
773 					free_block_list(*arg_blocks);
774 					*arg_blocks = NULL;
775 				}
776 				warn("could not allocate filter block");
777 				ret = -1;
778 				goto free_line;
779 			}
780 
781 			if (*arg_blocks) {
782 				extend_filter_block_list(*arg_blocks, block);
783 			} else {
784 				*arg_blocks = block;
785 			}
786 		}
787 		/* Reuse |line| in the next getline() call. */
788 	}
789 	/* getline(3) returned -1. This can mean EOF or the below errors. */
790 	if (errno == EINVAL || errno == ENOMEM) {
791 		if (*arg_blocks) {
792 			free_block_list(*arg_blocks);
793 			*arg_blocks = NULL;
794 		}
795 		warn("getmultiline() failed");
796 		ret = -1;
797 	}
798 
799 free_line:
800 	free(line);
801 	return ret;
802 }
803 
compile_filter(const char * filename,FILE * initial_file,struct sock_fprog * prog,const struct filter_options * filteropts)804 int compile_filter(const char *filename, FILE *initial_file,
805 		   struct sock_fprog *prog,
806 		   const struct filter_options *filteropts)
807 {
808 	int ret = 0;
809 	struct bpf_labels labels;
810 	labels.count = 0;
811 
812 	if (!initial_file) {
813 		warn("compile_filter: |initial_file| is NULL");
814 		return -1;
815 	}
816 
817 	struct filter_block *head = new_filter_block();
818 	struct filter_block *arg_blocks = NULL;
819 
820 	/*
821 	 * Create the data structure that will keep track of what system
822 	 * calls we have already defined if the option is true.
823 	 */
824 	size_t num_syscalls = get_num_syscalls();
825 	struct parser_state **previous_syscalls =
826 	    calloc(num_syscalls, sizeof(*previous_syscalls));
827 
828 	/* Start filter by validating arch. */
829 	struct sock_filter *valid_arch = new_instr_buf(ARCH_VALIDATION_LEN);
830 	size_t len = bpf_validate_arch(valid_arch);
831 	append_filter_block(head, valid_arch, len);
832 
833 	/* Load syscall number. */
834 	struct sock_filter *load_nr = new_instr_buf(ONE_INSTR);
835 	len = bpf_load_syscall_nr(load_nr);
836 	append_filter_block(head, load_nr, len);
837 
838 	/*
839 	 * On kernels without SECCOMP_RET_LOG, Minijail can attempt to write the
840 	 * first failing syscall to syslog(3). In order for syslog(3) to work,
841 	 * some syscalls need to be unconditionally allowed.
842 	 */
843 	if (filteropts->allow_syscalls_for_logging)
844 		allow_logging_syscalls(head);
845 
846 	if (compile_file(filename, initial_file, head, &arg_blocks, &labels,
847 			 filteropts, previous_syscalls,
848 			 0 /* include_level */) != 0) {
849 		warn("compile_filter: compile_file() failed");
850 		ret = -1;
851 		goto free_filter;
852 	}
853 
854 	/*
855 	 * If none of the syscalls match, either fall through to LOG, TRAP, or
856 	 * KILL.
857 	 */
858 	switch (filteropts->action) {
859 	case ACTION_RET_KILL:
860 		append_ret_kill(head);
861 		break;
862 	case ACTION_RET_KILL_PROCESS:
863 		append_ret_kill_process(head);
864 		break;
865 	case ACTION_RET_TRAP:
866 		append_ret_trap(head);
867 		break;
868 	case ACTION_RET_LOG:
869 		if (filteropts->allow_logging) {
870 			append_ret_log(head);
871 		} else {
872 			warn("compile_filter: cannot use RET_LOG without "
873 			     "allowing logging");
874 			ret = -1;
875 			goto free_filter;
876 		}
877 		break;
878 	default:
879 		warn("compile_filter: invalid log action %d",
880 		     filteropts->action);
881 		ret = -1;
882 		goto free_filter;
883 	}
884 
885 	/* Allocate the final buffer, now that we know its size. */
886 	size_t final_filter_len =
887 	    head->total_len + (arg_blocks ? arg_blocks->total_len : 0);
888 	if (final_filter_len > BPF_MAXINSNS) {
889 		ret = -1;
890 		goto free_filter;
891 	}
892 
893 	struct sock_filter *final_filter =
894 	    calloc(final_filter_len, sizeof(struct sock_filter));
895 	if (!final_filter)
896 		die("could not allocate final BPF filter");
897 
898 	if (flatten_block_list(head, final_filter, 0, final_filter_len) < 0) {
899 		free(final_filter);
900 		ret = -1;
901 		goto free_filter;
902 	}
903 
904 	if (flatten_block_list(arg_blocks, final_filter, head->total_len,
905 			       final_filter_len) < 0) {
906 		free(final_filter);
907 		ret = -1;
908 		goto free_filter;
909 	}
910 
911 	if (bpf_resolve_jumps(&labels, final_filter, final_filter_len) < 0) {
912 		free(final_filter);
913 		ret = -1;
914 		goto free_filter;
915 	}
916 
917 	prog->filter = final_filter;
918 	prog->len = final_filter_len;
919 
920 free_filter:
921 	free_block_list(head);
922 	free_block_list(arg_blocks);
923 	free_label_strings(&labels);
924 	free_previous_syscalls(previous_syscalls);
925 	return ret;
926 }
927 
flatten_block_list(struct filter_block * head,struct sock_filter * filter,size_t index,size_t cap)928 int flatten_block_list(struct filter_block *head, struct sock_filter *filter,
929 		       size_t index, size_t cap)
930 {
931 	size_t _index = index;
932 
933 	struct filter_block *curr;
934 	size_t i;
935 
936 	for (curr = head; curr; curr = curr->next) {
937 		for (i = 0; i < curr->len; i++) {
938 			if (_index >= cap)
939 				return -1;
940 			filter[_index++] = curr->instrs[i];
941 		}
942 	}
943 	return 0;
944 }
945 
free_block_list(struct filter_block * head)946 void free_block_list(struct filter_block *head)
947 {
948 	struct filter_block *current, *prev;
949 
950 	current = head;
951 	while (current) {
952 		free(current->instrs);
953 		prev = current;
954 		current = current->next;
955 		free(prev);
956 	}
957 }
958 
free_previous_syscalls(struct parser_state ** previous_syscalls)959 void free_previous_syscalls(struct parser_state **previous_syscalls)
960 {
961 	size_t num_syscalls = get_num_syscalls();
962 	for (size_t i = 0; i < num_syscalls; i++) {
963 		struct parser_state *state = previous_syscalls[i];
964 		if (state) {
965 			free((char *)state->filename);
966 			free(state);
967 		}
968 	}
969 	free(previous_syscalls);
970 }
971