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 MAX_POLICY_LINE_LENGTH	1024
17 
18 #define ONE_INSTR	1
19 #define TWO_INSTRS	2
20 
21 #define compiler_warn(_state, _msg, ...)                                       \
22 	warn("%s: %s(%zd): " _msg, __func__, (_state)->filename,               \
23 	     (_state)->line_number, ## __VA_ARGS__)
24 
25 #define compiler_pwarn(_state, _msg, ...)                                      \
26 	compiler_warn(_state, _msg ": %m", ## __VA_ARGS__)
27 /* clang-format on */
28 
seccomp_can_softfail(void)29 int seccomp_can_softfail(void)
30 {
31 #if defined(USE_SECCOMP_SOFTFAIL)
32 	return 1;
33 #endif
34 	return 0;
35 }
36 
str_to_op(const char * op_str)37 int str_to_op(const char *op_str)
38 {
39 	if (!strcmp(op_str, "==")) {
40 		return EQ;
41 	} else if (!strcmp(op_str, "!=")) {
42 		return NE;
43 	} else if (!strcmp(op_str, "&")) {
44 		return SET;
45 	} else if (!strcmp(op_str, "in")) {
46 		return IN;
47 	} else {
48 		return 0;
49 	}
50 }
51 
new_instr_buf(size_t count)52 struct sock_filter *new_instr_buf(size_t count)
53 {
54 	struct sock_filter *buf = calloc(count, sizeof(struct sock_filter));
55 	if (!buf)
56 		die("could not allocate BPF instruction buffer");
57 
58 	return buf;
59 }
60 
new_filter_block(void)61 struct filter_block *new_filter_block(void)
62 {
63 	struct filter_block *block = calloc(1, sizeof(struct filter_block));
64 	if (!block)
65 		die("could not allocate BPF filter block");
66 
67 	block->instrs = NULL;
68 	block->last = block->next = NULL;
69 
70 	return block;
71 }
72 
append_filter_block(struct filter_block * head,struct sock_filter * instrs,size_t len)73 void append_filter_block(struct filter_block *head, struct sock_filter *instrs,
74 			 size_t len)
75 {
76 	struct filter_block *new_last;
77 
78 	/*
79 	 * If |head| has no filter assigned yet,
80 	 * we don't create a new node.
81 	 */
82 	if (head->instrs == NULL) {
83 		new_last = head;
84 	} else {
85 		new_last = new_filter_block();
86 		if (head->next != NULL) {
87 			head->last->next = new_last;
88 			head->last = new_last;
89 		} else {
90 			head->last = head->next = new_last;
91 		}
92 		head->total_len += len;
93 	}
94 
95 	new_last->instrs = instrs;
96 	new_last->total_len = new_last->len = len;
97 	new_last->last = new_last->next = NULL;
98 }
99 
extend_filter_block_list(struct filter_block * list,struct filter_block * another)100 void extend_filter_block_list(struct filter_block *list,
101 			      struct filter_block *another)
102 {
103 	if (list->last != NULL) {
104 		list->last->next = another;
105 		list->last = another->last;
106 	} else {
107 		list->next = another;
108 		list->last = another->last;
109 	}
110 	list->total_len += another->total_len;
111 }
112 
append_ret_kill(struct filter_block * head)113 void append_ret_kill(struct filter_block *head)
114 {
115 	struct sock_filter *filter = new_instr_buf(ONE_INSTR);
116 	set_bpf_ret_kill(filter);
117 	append_filter_block(head, filter, ONE_INSTR);
118 }
119 
append_ret_trap(struct filter_block * head)120 void append_ret_trap(struct filter_block *head)
121 {
122 	struct sock_filter *filter = new_instr_buf(ONE_INSTR);
123 	set_bpf_ret_trap(filter);
124 	append_filter_block(head, filter, ONE_INSTR);
125 }
126 
append_ret_errno(struct filter_block * head,int errno_val)127 void append_ret_errno(struct filter_block *head, int errno_val)
128 {
129 	struct sock_filter *filter = new_instr_buf(ONE_INSTR);
130 	set_bpf_ret_errno(filter, errno_val);
131 	append_filter_block(head, filter, ONE_INSTR);
132 }
133 
append_allow_syscall(struct filter_block * head,int nr)134 void append_allow_syscall(struct filter_block *head, int nr)
135 {
136 	struct sock_filter *filter = new_instr_buf(ALLOW_SYSCALL_LEN);
137 	size_t len = bpf_allow_syscall(filter, nr);
138 	if (len != ALLOW_SYSCALL_LEN)
139 		die("error building syscall number comparison");
140 
141 	append_filter_block(head, filter, len);
142 }
143 
allow_logging_syscalls(struct filter_block * head)144 void allow_logging_syscalls(struct filter_block *head)
145 {
146 	unsigned int i;
147 	for (i = 0; i < log_syscalls_len; i++) {
148 		warn("allowing syscall: %s", log_syscalls[i]);
149 		append_allow_syscall(head, lookup_syscall(log_syscalls[i]));
150 	}
151 }
152 
get_label_id(struct bpf_labels * labels,const char * label_str)153 unsigned int get_label_id(struct bpf_labels *labels, const char *label_str)
154 {
155 	int label_id = bpf_label_id(labels, label_str);
156 	if (label_id < 0)
157 		die("could not allocate BPF label string");
158 	return label_id;
159 }
160 
group_end_lbl(struct bpf_labels * labels,int nr,int idx)161 unsigned int group_end_lbl(struct bpf_labels *labels, int nr, int idx)
162 {
163 	char lbl_str[MAX_BPF_LABEL_LEN];
164 	snprintf(lbl_str, MAX_BPF_LABEL_LEN, "%d_%d_end", nr, idx);
165 	return get_label_id(labels, lbl_str);
166 }
167 
success_lbl(struct bpf_labels * labels,int nr)168 unsigned int success_lbl(struct bpf_labels *labels, int nr)
169 {
170 	char lbl_str[MAX_BPF_LABEL_LEN];
171 	snprintf(lbl_str, MAX_BPF_LABEL_LEN, "%d_success", nr);
172 	return get_label_id(labels, lbl_str);
173 }
174 
is_implicit_relative_path(const char * filename)175 int is_implicit_relative_path(const char *filename)
176 {
177 	return filename[0] != '/' && (filename[0] != '.' || filename[1] != '/');
178 }
179 
compile_atom(struct parser_state * state,struct filter_block * head,char * atom,struct bpf_labels * labels,int nr,int grp_idx)180 int compile_atom(struct parser_state *state, struct filter_block *head,
181 		 char *atom, struct bpf_labels *labels, int nr, int grp_idx)
182 {
183 	/* Splits the atom. */
184 	char *atom_ptr = NULL;
185 	char *argidx_str = strtok_r(atom, " ", &atom_ptr);
186 	if (argidx_str == NULL) {
187 		compiler_warn(state, "empty atom");
188 		return -1;
189 	}
190 
191 	char *operator_str = strtok_r(NULL, " ", &atom_ptr);
192 	if (operator_str == NULL) {
193 		compiler_warn(state, "invalid atom '%s'", argidx_str);
194 		return -1;
195 	}
196 
197 	char *constant_str = strtok_r(NULL, " ", &atom_ptr);
198 	if (constant_str == NULL) {
199 		compiler_warn(state, "invalid atom '%s %s'", argidx_str,
200 			      operator_str);
201 		return -1;
202 	}
203 
204 	/* Checks that there are no extra tokens. */
205 	const char *extra = strtok_r(NULL, " ", &atom_ptr);
206 	if (extra != NULL) {
207 		compiler_warn(state, "extra token '%s'", extra);
208 		return -1;
209 	}
210 
211 	if (strncmp(argidx_str, "arg", 3)) {
212 		compiler_warn(state, "invalid argument token '%s'", argidx_str);
213 		return -1;
214 	}
215 
216 	char *argidx_ptr;
217 	long int argidx = strtol(argidx_str + 3, &argidx_ptr, 10);
218 	/*
219 	 * Checks that an actual argument index was parsed,
220 	 * and that there was nothing left after the index.
221 	 */
222 	if (argidx_ptr == argidx_str + 3 || *argidx_ptr != '\0') {
223 		compiler_warn(state, "invalid argument index '%s'",
224 			      argidx_str + 3);
225 		return -1;
226 	}
227 
228 	int op = str_to_op(operator_str);
229 	if (op < MIN_OPERATOR) {
230 		compiler_warn(state, "invalid operator '%s'", operator_str);
231 		return -1;
232 	}
233 
234 	char *constant_str_ptr;
235 	long int c = parse_constant(constant_str, &constant_str_ptr);
236 	if (constant_str_ptr == constant_str) {
237 		compiler_warn(state, "invalid constant '%s'", constant_str);
238 		return -1;
239 	}
240 
241 	/*
242 	 * Looks up the label for the end of the AND statement
243 	 * this atom belongs to.
244 	 */
245 	unsigned int id = group_end_lbl(labels, nr, grp_idx);
246 
247 	/*
248 	 * Builds a BPF comparison between a syscall argument
249 	 * and a constant.
250 	 * The comparison lives inside an AND statement.
251 	 * If the comparison succeeds, we continue
252 	 * to the next comparison.
253 	 * If this comparison fails, the whole AND statement
254 	 * will fail, so we jump to the end of this AND statement.
255 	 */
256 	struct sock_filter *comp_block;
257 	size_t len = bpf_arg_comp(&comp_block, op, argidx, c, id);
258 	if (len == 0)
259 		return -1;
260 
261 	append_filter_block(head, comp_block, len);
262 	return 0;
263 }
264 
compile_errno(struct parser_state * state,struct filter_block * head,char * ret_errno,int use_ret_trap)265 int compile_errno(struct parser_state *state, struct filter_block *head,
266 		  char *ret_errno, int use_ret_trap)
267 {
268 	char *errno_ptr = NULL;
269 
270 	/* Splits the 'return' keyword and the actual errno value. */
271 	char *ret_str = strtok_r(ret_errno, " ", &errno_ptr);
272 	if (!ret_str || strncmp(ret_str, "return", strlen("return")))
273 		return -1;
274 
275 	char *errno_val_str = strtok_r(NULL, " ", &errno_ptr);
276 
277 	if (errno_val_str) {
278 		char *errno_val_ptr;
279 		int errno_val = parse_constant(errno_val_str, &errno_val_ptr);
280 		/* Checks to see if we parsed an actual errno. */
281 		if (errno_val_ptr == errno_val_str || errno_val == -1) {
282 			compiler_warn(state, "invalid errno value '%s'",
283 				      errno_val_ptr);
284 			return -1;
285 		}
286 
287 		append_ret_errno(head, errno_val);
288 	} else {
289 		if (!use_ret_trap)
290 			append_ret_kill(head);
291 		else
292 			append_ret_trap(head);
293 	}
294 	return 0;
295 }
296 
compile_policy_line(struct parser_state * state,int nr,const char * policy_line,unsigned int entry_lbl_id,struct bpf_labels * labels,int use_ret_trap)297 struct filter_block *compile_policy_line(struct parser_state *state, int nr,
298 					 const char *policy_line,
299 					 unsigned int entry_lbl_id,
300 					 struct bpf_labels *labels,
301 					 int use_ret_trap)
302 {
303 	/*
304 	 * |policy_line| should be an expression of the form:
305 	 * "arg0 == 3 && arg1 == 5 || arg0 == 0x8"
306 	 *
307 	 * This is, an expression in DNF (disjunctive normal form);
308 	 * a disjunction ('||') of one or more conjunctions ('&&')
309 	 * of one or more atoms.
310 	 *
311 	 * Atoms are of the form "arg{DNUM} {OP} {NUM}"
312 	 * where:
313 	 *   - DNUM is a decimal number.
314 	 *   - OP is an operator: ==, !=, & (flags set), or 'in' (inclusion).
315 	 *   - NUM is an octal, decimal, or hexadecimal number.
316 	 *
317 	 * When the syscall arguments make the expression true,
318 	 * the syscall is allowed. If not, the process is killed.
319 	 *
320 	 * To block a syscall without killing the process,
321 	 * |policy_line| can be of the form:
322 	 * "return <errno>"
323 	 *
324 	 * This "return {NUM}" policy line will block the syscall,
325 	 * make it return -1 and set |errno| to NUM.
326 	 *
327 	 * A regular policy line can also include a "return <errno>" clause,
328 	 * separated by a semicolon (';'):
329 	 * "arg0 == 3 && arg1 == 5 || arg0 == 0x8; return {NUM}"
330 	 *
331 	 * If the syscall arguments don't make the expression true,
332 	 * the syscall will be blocked as above instead of killing the process.
333 	 */
334 
335 	size_t len = 0;
336 	int grp_idx = 0;
337 
338 	/* Checks for empty policy lines. */
339 	if (strlen(policy_line) == 0) {
340 		compiler_warn(state, "empty policy line");
341 		return NULL;
342 	}
343 
344 	/* Checks for overly long policy lines. */
345 	if (strlen(policy_line) >= MAX_POLICY_LINE_LENGTH)
346 		return NULL;
347 
348 	/* We will modify |policy_line|, so let's make a copy. */
349 	char *line = strndup(policy_line, MAX_POLICY_LINE_LENGTH);
350 	if (!line)
351 		return NULL;
352 
353 	/*
354 	 * We build the filter section as a collection of smaller
355 	 * "filter blocks" linked together in a singly-linked list.
356 	 */
357 	struct filter_block *head = new_filter_block();
358 
359 	/*
360 	 * Filter sections begin with a label where the main filter
361 	 * will jump after checking the syscall number.
362 	 */
363 	struct sock_filter *entry_label = new_instr_buf(ONE_INSTR);
364 	set_bpf_lbl(entry_label, entry_lbl_id);
365 	append_filter_block(head, entry_label, ONE_INSTR);
366 
367 	/* Checks whether we're unconditionally blocking this syscall. */
368 	if (strncmp(line, "return", strlen("return")) == 0) {
369 		if (compile_errno(state, head, line, use_ret_trap) < 0) {
370 			free_block_list(head);
371 			free(line);
372 			return NULL;
373 		}
374 		free(line);
375 		return head;
376 	}
377 
378 	/* Splits the optional "return <errno>" part. */
379 	char *line_ptr;
380 	char *arg_filter = strtok_r(line, ";", &line_ptr);
381 	char *ret_errno = strtok_r(NULL, ";", &line_ptr);
382 
383 	/*
384 	 * Splits the policy line by '||' into conjunctions and each conjunction
385 	 * by '&&' into atoms.
386 	 */
387 	char *arg_filter_str = arg_filter;
388 	char *group;
389 	while ((group = tokenize(&arg_filter_str, "||")) != NULL) {
390 		char *group_str = group;
391 		char *comp;
392 		while ((comp = tokenize(&group_str, "&&")) != NULL) {
393 			/* Compiles each atom into a BPF block. */
394 			if (compile_atom(state, head, comp, labels, nr,
395 					 grp_idx) < 0) {
396 				free_block_list(head);
397 				free(line);
398 				return NULL;
399 			}
400 		}
401 		/*
402 		 * If the AND statement succeeds, we're done,
403 		 * so jump to SUCCESS line.
404 		 */
405 		unsigned int id = success_lbl(labels, nr);
406 		struct sock_filter *group_end_block = new_instr_buf(TWO_INSTRS);
407 		len = set_bpf_jump_lbl(group_end_block, id);
408 		/*
409 		 * The end of each AND statement falls after the
410 		 * jump to SUCCESS.
411 		 */
412 		id = group_end_lbl(labels, nr, grp_idx++);
413 		len += set_bpf_lbl(group_end_block + len, id);
414 		append_filter_block(head, group_end_block, len);
415 	}
416 
417 	/*
418 	 * If no AND statements succeed, we end up here,
419 	 * because we never jumped to SUCCESS.
420 	 * If we have to return an errno, do it,
421 	 * otherwise just kill the task.
422 	 */
423 	if (ret_errno) {
424 		if (compile_errno(state, head, ret_errno, use_ret_trap) < 0) {
425 			free_block_list(head);
426 			free(line);
427 			return NULL;
428 		}
429 	} else {
430 		if (!use_ret_trap)
431 			append_ret_kill(head);
432 		else
433 			append_ret_trap(head);
434 	}
435 
436 	/*
437 	 * Every time the filter succeeds we jump to a predefined SUCCESS
438 	 * label. Add that label and BPF RET_ALLOW code now.
439 	 */
440 	unsigned int id = success_lbl(labels, nr);
441 	struct sock_filter *success_block = new_instr_buf(TWO_INSTRS);
442 	len = set_bpf_lbl(success_block, id);
443 	len += set_bpf_ret_allow(success_block + len);
444 	append_filter_block(head, success_block, len);
445 
446 	free(line);
447 	return head;
448 }
449 
parse_include_statement(struct parser_state * state,char * policy_line,unsigned int include_level,const char ** ret_filename)450 int parse_include_statement(struct parser_state *state, char *policy_line,
451 			    unsigned int include_level,
452 			    const char **ret_filename)
453 {
454 	if (strncmp("@include", policy_line, strlen("@include")) != 0) {
455 		compiler_warn(state, "invalid statement '%s'", policy_line);
456 		return -1;
457 	}
458 
459 	if (policy_line[strlen("@include")] != ' ') {
460 		compiler_warn(state, "invalid include statement '%s'",
461 			      policy_line);
462 		return -1;
463 	}
464 
465 	/*
466 	 * Disallow nested includes: only the initial policy file can have
467 	 * @include statements.
468 	 * Nested includes are not currently necessary and make the policy
469 	 * harder to understand.
470 	 */
471 	if (include_level > 0) {
472 		compiler_warn(state, "@include statement nested too deep");
473 		return -1;
474 	}
475 
476 	char *statement = policy_line;
477 	/* Discard "@include" token. */
478 	(void)strsep(&statement, " ");
479 
480 	/*
481 	 * compile_filter() below receives a FILE*, so it's not trivial to open
482 	 * included files relative to the initial policy filename.
483 	 * To avoid mistakes, force the included file path to be absolute
484 	 * (start with '/'), or to explicitly load the file relative to CWD by
485 	 * using './'.
486 	 */
487 	const char *filename = statement;
488 	if (is_implicit_relative_path(filename)) {
489 		compiler_warn(
490 		    state,
491 		    "implicit relative path '%s' not supported, use './%s'",
492 		    filename, filename);
493 		return -1;
494 	}
495 
496 	*ret_filename = filename;
497 	return 0;
498 }
499 
compile_file(const char * filename,FILE * policy_file,struct filter_block * head,struct filter_block ** arg_blocks,struct bpf_labels * labels,int use_ret_trap,int allow_logging,unsigned int include_level)500 int compile_file(const char *filename, FILE *policy_file,
501 		 struct filter_block *head, struct filter_block **arg_blocks,
502 		 struct bpf_labels *labels, int use_ret_trap, int allow_logging,
503 		 unsigned int include_level)
504 {
505 	/* clang-format off */
506 	struct parser_state state = {
507 		.filename = filename,
508 		.line_number = 0,
509 	};
510 	/* clang-format on */
511 	/*
512 	 * Loop through all the lines in the policy file.
513 	 * Build a jump table for the syscall number.
514 	 * If the policy line has an arg filter, build the arg filter
515 	 * as well.
516 	 * Chain the filter sections together and dump them into
517 	 * the final buffer at the end.
518 	 */
519 	char *line = NULL;
520 	size_t len = 0;
521 	int ret = 0;
522 
523 	while (getline(&line, &len, policy_file) != -1) {
524 		char *policy_line = line;
525 		policy_line = strip(policy_line);
526 
527 		state.line_number++;
528 
529 		/* Allow comments and empty lines. */
530 		if (*policy_line == '#' || *policy_line == '\0') {
531 			/* Reuse |line| in the next getline() call. */
532 			continue;
533 		}
534 
535 		/* Allow @include statements. */
536 		if (*policy_line == '@') {
537 			const char *filename = NULL;
538 			if (parse_include_statement(&state, policy_line,
539 						    include_level,
540 						    &filename) != 0) {
541 				compiler_warn(
542 				    &state,
543 				    "failed to parse include statement");
544 				ret = -1;
545 				goto free_line;
546 			}
547 
548 			FILE *included_file = fopen(filename, "re");
549 			if (included_file == NULL) {
550 				compiler_pwarn(&state, "fopen('%s') failed",
551 					       filename);
552 				ret = -1;
553 				goto free_line;
554 			}
555 			if (compile_file(filename, included_file, head,
556 					 arg_blocks, labels, use_ret_trap,
557 					 allow_logging,
558 					 ++include_level) == -1) {
559 				compiler_warn(&state, "'@include %s' failed",
560 					      filename);
561 				fclose(included_file);
562 				ret = -1;
563 				goto free_line;
564 			}
565 			fclose(included_file);
566 			continue;
567 		}
568 
569 		/*
570 		 * If it's not a comment, or an empty line, or an @include
571 		 * statement, treat |policy_line| as a regular policy line.
572 		 */
573 		char *syscall_name = strsep(&policy_line, ":");
574 		if (policy_line == NULL) {
575 			warn("compile_file: malformed policy line, missing "
576 			     "':'");
577 			ret = -1;
578 			goto free_line;
579 		}
580 
581 		policy_line = strip(policy_line);
582 		if (*policy_line == '\0') {
583 			compiler_warn(&state, "empty policy line");
584 			ret = -1;
585 			goto free_line;
586 		}
587 
588 		syscall_name = strip(syscall_name);
589 		int nr = lookup_syscall(syscall_name);
590 		if (nr < 0) {
591 			compiler_warn(&state, "nonexistent syscall '%s'",
592 				      syscall_name);
593 			if (allow_logging) {
594 				/*
595 				 * If we're logging failures, assume we're in a
596 				 * debugging case and continue.
597 				 * This is not super risky because an invalid
598 				 * syscall name is likely caused by a typo or by
599 				 * leftover lines from a different architecture.
600 				 * In either case, not including a policy line
601 				 * is equivalent to killing the process if the
602 				 * syscall is made, so there's no added attack
603 				 * surface.
604 				 */
605 				/* Reuse |line| in the next getline() call. */
606 				continue;
607 			}
608 			ret = -1;
609 			goto free_line;
610 		}
611 
612 		/*
613 		 * For each syscall, add either a simple ALLOW,
614 		 * or an arg filter block.
615 		 */
616 		if (strcmp(policy_line, "1") == 0) {
617 			/* Add simple ALLOW. */
618 			append_allow_syscall(head, nr);
619 		} else {
620 			/*
621 			 * Create and jump to the label that will hold
622 			 * the arg filter block.
623 			 */
624 			unsigned int id = bpf_label_id(labels, syscall_name);
625 			struct sock_filter *nr_comp =
626 			    new_instr_buf(ALLOW_SYSCALL_LEN);
627 			bpf_allow_syscall_args(nr_comp, nr, id);
628 			append_filter_block(head, nr_comp, ALLOW_SYSCALL_LEN);
629 
630 			/* Build the arg filter block. */
631 			struct filter_block *block = compile_policy_line(
632 			    &state, nr, policy_line, id, labels, use_ret_trap);
633 
634 			if (!block) {
635 				if (*arg_blocks) {
636 					free_block_list(*arg_blocks);
637 					*arg_blocks = NULL;
638 				}
639 				ret = -1;
640 				goto free_line;
641 			}
642 
643 			if (*arg_blocks) {
644 				extend_filter_block_list(*arg_blocks, block);
645 			} else {
646 				*arg_blocks = block;
647 			}
648 		}
649 		/* Reuse |line| in the next getline() call. */
650 	}
651 	/* getline(3) returned -1. This can mean EOF or the below errors. */
652 	if (errno == EINVAL || errno == ENOMEM) {
653 		if (*arg_blocks) {
654 			free_block_list(*arg_blocks);
655 			*arg_blocks = NULL;
656 		}
657 		ret = -1;
658 	}
659 
660 free_line:
661 	free(line);
662 	return ret;
663 }
664 
compile_filter(const char * filename,FILE * initial_file,struct sock_fprog * prog,int use_ret_trap,int allow_logging)665 int compile_filter(const char *filename, FILE *initial_file,
666 		   struct sock_fprog *prog, int use_ret_trap, int allow_logging)
667 {
668 	int ret = 0;
669 	struct bpf_labels labels;
670 	labels.count = 0;
671 
672 	if (!initial_file) {
673 		warn("compile_filter: |initial_file| is NULL");
674 		return -1;
675 	}
676 
677 	struct filter_block *head = new_filter_block();
678 	struct filter_block *arg_blocks = NULL;
679 
680 	/* Start filter by validating arch. */
681 	struct sock_filter *valid_arch = new_instr_buf(ARCH_VALIDATION_LEN);
682 	size_t len = bpf_validate_arch(valid_arch);
683 	append_filter_block(head, valid_arch, len);
684 
685 	/* Load syscall number. */
686 	struct sock_filter *load_nr = new_instr_buf(ONE_INSTR);
687 	len = bpf_load_syscall_nr(load_nr);
688 	append_filter_block(head, load_nr, len);
689 
690 	/* If logging failures, allow the necessary syscalls first. */
691 	if (allow_logging)
692 		allow_logging_syscalls(head);
693 
694 	if (compile_file(filename, initial_file, head, &arg_blocks, &labels,
695 			 use_ret_trap, allow_logging,
696 			 0 /* include_level */) != 0) {
697 		warn("compile_filter: compile_file() failed");
698 		ret = -1;
699 		goto free_filter;
700 	}
701 
702 	/*
703 	 * If none of the syscalls match, either fall through to KILL,
704 	 * or return TRAP.
705 	 */
706 	if (!use_ret_trap)
707 		append_ret_kill(head);
708 	else
709 		append_ret_trap(head);
710 
711 	/* Allocate the final buffer, now that we know its size. */
712 	size_t final_filter_len =
713 	    head->total_len + (arg_blocks ? arg_blocks->total_len : 0);
714 	if (final_filter_len > BPF_MAXINSNS) {
715 		ret = -1;
716 		goto free_filter;
717 	}
718 
719 	struct sock_filter *final_filter =
720 	    calloc(final_filter_len, sizeof(struct sock_filter));
721 
722 	if (flatten_block_list(head, final_filter, 0, final_filter_len) < 0) {
723 		free(final_filter);
724 		ret = -1;
725 		goto free_filter;
726 	}
727 
728 	if (flatten_block_list(arg_blocks, final_filter, head->total_len,
729 			       final_filter_len) < 0) {
730 		free(final_filter);
731 		ret = -1;
732 		goto free_filter;
733 	}
734 
735 	if (bpf_resolve_jumps(&labels, final_filter, final_filter_len) < 0) {
736 		free(final_filter);
737 		ret = -1;
738 		goto free_filter;
739 	}
740 
741 	prog->filter = final_filter;
742 	prog->len = final_filter_len;
743 
744 free_filter:
745 	free_block_list(head);
746 	free_block_list(arg_blocks);
747 	free_label_strings(&labels);
748 	return ret;
749 }
750 
flatten_block_list(struct filter_block * head,struct sock_filter * filter,size_t index,size_t cap)751 int flatten_block_list(struct filter_block *head, struct sock_filter *filter,
752 		       size_t index, size_t cap)
753 {
754 	size_t _index = index;
755 
756 	struct filter_block *curr;
757 	size_t i;
758 
759 	for (curr = head; curr; curr = curr->next) {
760 		for (i = 0; i < curr->len; i++) {
761 			if (_index >= cap)
762 				return -1;
763 			filter[_index++] = curr->instrs[i];
764 		}
765 	}
766 	return 0;
767 }
768 
free_block_list(struct filter_block * head)769 void free_block_list(struct filter_block *head)
770 {
771 	struct filter_block *current, *prev;
772 
773 	current = head;
774 	while (current) {
775 		free(current->instrs);
776 		prev = current;
777 		current = current->next;
778 		free(prev);
779 	}
780 }
781