1 /* Copyright 2012 The ChromiumOS Authors
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 (streq(op_str, "==")) {
38 return EQ;
39 } else if (streq(op_str, "!=")) {
40 return NE;
41 } else if (streq(op_str, "<")) {
42 return LT;
43 } else if (streq(op_str, "<=")) {
44 return LE;
45 } else if (streq(op_str, ">")) {
46 return GT;
47 } else if (streq(op_str, ">=")) {
48 return GE;
49 } else if (streq(op_str, "&")) {
50 return SET;
51 } else if (streq(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
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)571 int compile_file(const char *filename, FILE *policy_file,
572 struct filter_block *head, struct filter_block **arg_blocks,
573 struct bpf_labels *labels,
574 const struct filter_options *filteropts,
575 struct parser_state **previous_syscalls,
576 unsigned int include_level)
577 {
578 /* clang-format off */
579 struct parser_state state = {
580 .filename = filename,
581 .line_number = 0,
582 };
583 /* clang-format on */
584 /*
585 * Loop through all the lines in the policy file.
586 * Build a jump table for the syscall number.
587 * If the policy line has an arg filter, build the arg filter
588 * as well.
589 * Chain the filter sections together and dump them into
590 * the final buffer at the end.
591 */
592 attribute_cleanup_str char *line = NULL;
593 size_t len = 0;
594 int ret = 0;
595
596 while (getmultiline(&line, &len, policy_file) != -1) {
597 char *policy_line = line;
598 policy_line = strip(policy_line);
599
600 state.line_number++;
601
602 /* Allow comments and empty lines. */
603 if (*policy_line == '#' || *policy_line == '\0') {
604 /* Reuse |line| in the next getline() call. */
605 continue;
606 }
607
608 /* Allow @include and @frequency statements. */
609 if (*policy_line == '@') {
610 const char *filename = NULL;
611
612 /* Ignore @frequency statements. */
613 if (strncmp("@frequency", policy_line,
614 strlen("@frequency")) == 0) {
615 compiler_warn(&state,
616 "ignored @frequency statement");
617 continue;
618 }
619
620 if (parse_include_statement(&state, policy_line,
621 include_level,
622 &filename) != 0) {
623 compiler_warn(
624 &state,
625 "failed to parse include statement");
626 ret = -1;
627 goto out;
628 }
629
630 attribute_cleanup_fp FILE *included_file =
631 fopen(filename, "re");
632 if (included_file == NULL) {
633 compiler_pwarn(&state, "fopen('%s') failed",
634 filename);
635 ret = -1;
636 goto out;
637 }
638 if (compile_file(filename, included_file, head,
639 arg_blocks, labels, filteropts,
640 previous_syscalls,
641 include_level + 1) == -1) {
642 compiler_warn(&state, "'@include %s' failed",
643 filename);
644 ret = -1;
645 goto out;
646 }
647 continue;
648 }
649
650 /*
651 * If it's not a comment, or an empty line, or an @include
652 * statement, treat |policy_line| as a regular policy line.
653 */
654 char *syscall_name = strsep(&policy_line, ":");
655 if (policy_line == NULL) {
656 warn("compile_file: malformed policy line, missing "
657 "':'");
658 ret = -1;
659 goto out;
660 }
661
662 policy_line = strip(policy_line);
663 if (*policy_line == '\0') {
664 compiler_warn(&state, "empty policy line");
665 ret = -1;
666 goto out;
667 }
668
669 syscall_name = strip(syscall_name);
670 size_t ind = 0;
671 int nr = lookup_syscall(syscall_name, &ind);
672 if (nr < 0) {
673 compiler_warn(&state, "nonexistent syscall '%s'",
674 syscall_name);
675 if (filteropts->allow_logging) {
676 /*
677 * If we're logging failures, assume we're in a
678 * debugging case and continue.
679 * This is not super risky because an invalid
680 * syscall name is likely caused by a typo or by
681 * leftover lines from a different architecture.
682 * In either case, not including a policy line
683 * is equivalent to killing the process if the
684 * syscall is made, so there's no added attack
685 * surface.
686 */
687 /* Reuse |line| in the next getline() call. */
688 continue;
689 }
690 ret = -1;
691 goto out;
692 }
693
694 if (!insert_and_check_duplicate_syscall(previous_syscalls,
695 &state, ind)) {
696 if (!filteropts->allow_duplicate_syscalls)
697 ret = -1;
698 compiler_warn(&state, "syscall %s redefined here",
699 lookup_syscall_name(nr));
700 compiler_warn(previous_syscalls[ind],
701 "previous definition here");
702 }
703
704 /*
705 * For each syscall, add either a simple ALLOW,
706 * or an arg filter block.
707 */
708 if (streq(policy_line, "1")) {
709 /* Add simple ALLOW. */
710 append_allow_syscall(head, nr);
711 } else {
712 /*
713 * Create and jump to the label that will hold
714 * the arg filter block.
715 */
716 unsigned int id = bpf_label_id(labels, syscall_name);
717 struct sock_filter *nr_comp =
718 new_instr_buf(ALLOW_SYSCALL_LEN);
719 bpf_allow_syscall_args(nr_comp, nr, id);
720 append_filter_block(head, nr_comp, ALLOW_SYSCALL_LEN);
721
722 /* Build the arg filter block. */
723 struct filter_block *block =
724 compile_policy_line(&state, nr, policy_line, id,
725 labels, filteropts->action);
726
727 if (!block) {
728 if (*arg_blocks) {
729 free_block_list(*arg_blocks);
730 *arg_blocks = NULL;
731 }
732 warn("could not allocate filter block");
733 ret = -1;
734 goto out;
735 }
736
737 if (*arg_blocks) {
738 extend_filter_block_list(*arg_blocks, block);
739 } else {
740 *arg_blocks = block;
741 }
742 }
743 /* Reuse |line| in the next getline() call. */
744 }
745 /* getline(3) returned -1. This can mean EOF or an error. */
746 if (!feof(policy_file)) {
747 if (*arg_blocks) {
748 free_block_list(*arg_blocks);
749 *arg_blocks = NULL;
750 }
751 warn("getmultiline() failed");
752 ret = -1;
753 }
754
755 out:
756 return ret;
757 }
758
compile_filter(const char * filename,FILE * initial_file,struct sock_fprog * prog,const struct filter_options * filteropts)759 int compile_filter(const char *filename, FILE *initial_file,
760 struct sock_fprog *prog,
761 const struct filter_options *filteropts)
762 {
763 int ret = 0;
764 struct bpf_labels labels;
765 labels.count = 0;
766
767 if (!initial_file) {
768 warn("compile_filter: |initial_file| is NULL");
769 return -1;
770 }
771
772 struct filter_block *head = new_filter_block();
773 struct filter_block *arg_blocks = NULL;
774
775 /*
776 * Create the data structure that will keep track of what system
777 * calls we have already defined if the option is true.
778 */
779 size_t num_syscalls = get_num_syscalls();
780 struct parser_state **previous_syscalls =
781 calloc(num_syscalls, sizeof(*previous_syscalls));
782
783 /* Start filter by validating arch. */
784 struct sock_filter *valid_arch = new_instr_buf(ARCH_VALIDATION_LEN);
785 size_t len = bpf_validate_arch(valid_arch);
786 append_filter_block(head, valid_arch, len);
787
788 /* Load syscall number. */
789 struct sock_filter *load_nr = new_instr_buf(ONE_INSTR);
790 len = bpf_load_syscall_nr(load_nr);
791 append_filter_block(head, load_nr, len);
792
793 /*
794 * On kernels without SECCOMP_RET_LOG, Minijail can attempt to write the
795 * first failing syscall to syslog(3). In order for syslog(3) to work,
796 * some syscalls need to be unconditionally allowed.
797 */
798 if (filteropts->allow_syscalls_for_logging)
799 allow_logging_syscalls(head);
800
801 if (compile_file(filename, initial_file, head, &arg_blocks, &labels,
802 filteropts, previous_syscalls,
803 0 /* include_level */) != 0) {
804 warn("compile_filter: compile_file() failed");
805 ret = -1;
806 goto free_filter;
807 }
808
809 /*
810 * If none of the syscalls match, either fall through to LOG, TRAP, or
811 * KILL.
812 */
813 switch (filteropts->action) {
814 case ACTION_RET_KILL:
815 append_ret_kill(head);
816 break;
817 case ACTION_RET_KILL_PROCESS:
818 append_ret_kill_process(head);
819 break;
820 case ACTION_RET_TRAP:
821 append_ret_trap(head);
822 break;
823 case ACTION_RET_LOG:
824 if (filteropts->allow_logging) {
825 append_ret_log(head);
826 } else {
827 warn("compile_filter: cannot use RET_LOG without "
828 "allowing logging");
829 ret = -1;
830 goto free_filter;
831 }
832 break;
833 default:
834 warn("compile_filter: invalid log action %d",
835 filteropts->action);
836 ret = -1;
837 goto free_filter;
838 }
839
840 /* Allocate the final buffer, now that we know its size. */
841 size_t final_filter_len =
842 head->total_len + (arg_blocks ? arg_blocks->total_len : 0);
843 if (final_filter_len > BPF_MAXINSNS) {
844 ret = -1;
845 goto free_filter;
846 }
847
848 struct sock_filter *final_filter =
849 calloc(final_filter_len, sizeof(struct sock_filter));
850 if (!final_filter)
851 die("could not allocate final BPF filter");
852
853 if (flatten_block_list(head, final_filter, 0, final_filter_len) < 0) {
854 free(final_filter);
855 ret = -1;
856 goto free_filter;
857 }
858
859 if (flatten_block_list(arg_blocks, final_filter, head->total_len,
860 final_filter_len) < 0) {
861 free(final_filter);
862 ret = -1;
863 goto free_filter;
864 }
865
866 if (bpf_resolve_jumps(&labels, final_filter, final_filter_len) < 0) {
867 free(final_filter);
868 ret = -1;
869 goto free_filter;
870 }
871
872 prog->filter = final_filter;
873 prog->len = final_filter_len;
874
875 free_filter:
876 free_block_list(head);
877 free_block_list(arg_blocks);
878 free_label_strings(&labels);
879 free_previous_syscalls(previous_syscalls);
880 return ret;
881 }
882
flatten_block_list(struct filter_block * head,struct sock_filter * filter,size_t index,size_t cap)883 int flatten_block_list(struct filter_block *head, struct sock_filter *filter,
884 size_t index, size_t cap)
885 {
886 size_t _index = index;
887
888 struct filter_block *curr;
889 size_t i;
890
891 for (curr = head; curr; curr = curr->next) {
892 for (i = 0; i < curr->len; i++) {
893 if (_index >= cap)
894 return -1;
895 filter[_index++] = curr->instrs[i];
896 }
897 }
898 return 0;
899 }
900
free_block_list(struct filter_block * head)901 void free_block_list(struct filter_block *head)
902 {
903 struct filter_block *current, *prev;
904
905 current = head;
906 while (current) {
907 free(current->instrs);
908 prev = current;
909 current = current->next;
910 free(prev);
911 }
912 }
913
free_previous_syscalls(struct parser_state ** previous_syscalls)914 void free_previous_syscalls(struct parser_state **previous_syscalls)
915 {
916 size_t num_syscalls = get_num_syscalls();
917 for (size_t i = 0; i < num_syscalls; i++) {
918 struct parser_state *state = previous_syscalls[i];
919 if (state) {
920 free((char *)state->filename);
921 free(state);
922 }
923 }
924 free(previous_syscalls);
925 }
926