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_selected_syscalls(struct filter_block * head,const char * const * allowlist,size_t allowlist_len,bool log_additions)197 static void allow_selected_syscalls(struct filter_block *head,
198 const char *const *allowlist,
199 size_t allowlist_len, bool log_additions)
200 {
201 unsigned int i;
202
203 for (i = 0; i < allowlist_len; i++) {
204 if (log_additions)
205 warn("allowing syscall: %s", allowlist[i]);
206 append_allow_syscall(head, lookup_syscall(allowlist[i], NULL));
207 }
208 }
209
get_label_id(struct bpf_labels * labels,const char * label_str)210 unsigned int get_label_id(struct bpf_labels *labels, const char *label_str)
211 {
212 int label_id = bpf_label_id(labels, label_str);
213 if (label_id < 0)
214 die("could not allocate BPF label string");
215 return label_id;
216 }
217
group_end_lbl(struct bpf_labels * labels,int nr,int idx)218 unsigned int group_end_lbl(struct bpf_labels *labels, int nr, int idx)
219 {
220 char lbl_str[MAX_BPF_LABEL_LEN];
221 snprintf(lbl_str, MAX_BPF_LABEL_LEN, "%d_%d_end", nr, idx);
222 return get_label_id(labels, lbl_str);
223 }
224
success_lbl(struct bpf_labels * labels,int nr)225 unsigned int success_lbl(struct bpf_labels *labels, int nr)
226 {
227 char lbl_str[MAX_BPF_LABEL_LEN];
228 snprintf(lbl_str, MAX_BPF_LABEL_LEN, "%d_success", nr);
229 return get_label_id(labels, lbl_str);
230 }
231
is_implicit_relative_path(const char * filename)232 int is_implicit_relative_path(const char *filename)
233 {
234 return filename[0] != '/' && (filename[0] != '.' || filename[1] != '/');
235 }
236
compile_atom(struct parser_state * state,struct filter_block * head,char * atom,struct bpf_labels * labels,int nr,int grp_idx)237 int compile_atom(struct parser_state *state, struct filter_block *head,
238 char *atom, struct bpf_labels *labels, int nr, int grp_idx)
239 {
240 /* Splits the atom. */
241 char *atom_ptr = NULL;
242 char *argidx_str = strtok_r(atom, " ", &atom_ptr);
243 if (argidx_str == NULL) {
244 compiler_warn(state, "empty atom");
245 return -1;
246 }
247
248 char *operator_str = strtok_r(NULL, " ", &atom_ptr);
249 if (operator_str == NULL) {
250 compiler_warn(state, "invalid atom '%s'", argidx_str);
251 return -1;
252 }
253
254 char *constant_str = strtok_r(NULL, " ", &atom_ptr);
255 if (constant_str == NULL) {
256 compiler_warn(state, "invalid atom '%s %s'", argidx_str,
257 operator_str);
258 return -1;
259 }
260
261 /* Checks that there are no extra tokens. */
262 const char *extra = strtok_r(NULL, " ", &atom_ptr);
263 if (extra != NULL) {
264 compiler_warn(state, "extra token '%s'", extra);
265 return -1;
266 }
267
268 if (strncmp(argidx_str, "arg", 3)) {
269 compiler_warn(state, "invalid argument token '%s'", argidx_str);
270 return -1;
271 }
272
273 char *argidx_ptr;
274 long int argidx = strtol(argidx_str + 3, &argidx_ptr, 10);
275 /*
276 * Checks that an actual argument index was parsed,
277 * and that there was nothing left after the index.
278 */
279 if (argidx_ptr == argidx_str + 3 || *argidx_ptr != '\0') {
280 compiler_warn(state, "invalid argument index '%s'",
281 argidx_str + 3);
282 return -1;
283 }
284
285 int op = str_to_op(operator_str);
286 if (op < MIN_OPERATOR) {
287 compiler_warn(state, "invalid operator '%s'", operator_str);
288 return -1;
289 }
290
291 char *constant_str_ptr;
292 long int c = parse_constant(constant_str, &constant_str_ptr);
293 if (constant_str_ptr == constant_str) {
294 compiler_warn(state, "invalid constant '%s'", constant_str);
295 return -1;
296 }
297
298 /*
299 * Looks up the label for the end of the AND statement
300 * this atom belongs to.
301 */
302 unsigned int id = group_end_lbl(labels, nr, grp_idx);
303
304 /*
305 * Builds a BPF comparison between a syscall argument
306 * and a constant.
307 * The comparison lives inside an AND statement.
308 * If the comparison succeeds, we continue
309 * to the next comparison.
310 * If this comparison fails, the whole AND statement
311 * will fail, so we jump to the end of this AND statement.
312 */
313 struct sock_filter *comp_block;
314 size_t len = bpf_arg_comp(&comp_block, op, argidx, c, id);
315 if (len == 0)
316 return -1;
317
318 append_filter_block(head, comp_block, len);
319 return 0;
320 }
321
compile_errno(struct parser_state * state,struct filter_block * head,char * ret_errno,enum block_action action)322 int compile_errno(struct parser_state *state, struct filter_block *head,
323 char *ret_errno, enum block_action action)
324 {
325 char *errno_ptr = NULL;
326
327 /* Splits the 'return' keyword and the actual errno value. */
328 char *ret_str = strtok_r(ret_errno, " ", &errno_ptr);
329 if (!ret_str || strncmp(ret_str, "return", strlen("return")))
330 return -1;
331
332 char *errno_val_str = strtok_r(NULL, " ", &errno_ptr);
333
334 if (errno_val_str) {
335 char *errno_val_ptr;
336 int errno_val = parse_constant(errno_val_str, &errno_val_ptr);
337 /* Checks to see if we parsed an actual errno. */
338 if (errno_val_ptr == errno_val_str || errno_val == -1) {
339 compiler_warn(state, "invalid errno value '%s'",
340 errno_val_ptr);
341 return -1;
342 }
343
344 append_ret_errno(head, errno_val);
345 } else {
346 switch (action) {
347 case ACTION_RET_KILL:
348 append_ret_kill(head);
349 break;
350 case ACTION_RET_KILL_PROCESS:
351 append_ret_kill_process(head);
352 break;
353 case ACTION_RET_TRAP:
354 append_ret_trap(head);
355 break;
356 case ACTION_RET_LOG:
357 compiler_warn(state, "invalid action: ACTION_RET_LOG");
358 return -1;
359 }
360 }
361 return 0;
362 }
363
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)364 struct filter_block *compile_policy_line(struct parser_state *state, int nr,
365 const char *policy_line,
366 unsigned int entry_lbl_id,
367 struct bpf_labels *labels,
368 enum block_action action)
369 {
370 /*
371 * |policy_line| should be an expression of the form:
372 * "arg0 == 3 && arg1 == 5 || arg0 == 0x8"
373 *
374 * This is, an expression in DNF (disjunctive normal form);
375 * a disjunction ('||') of one or more conjunctions ('&&')
376 * of one or more atoms.
377 *
378 * Atoms are of the form "arg{DNUM} {OP} {NUM}"
379 * where:
380 * - DNUM is a decimal number.
381 * - OP is an operator: ==, !=, & (flags set), or 'in' (inclusion).
382 * - NUM is an octal, decimal, or hexadecimal number.
383 *
384 * When the syscall arguments make the expression true,
385 * the syscall is allowed. If not, the process is killed.
386 *
387 * To block a syscall without killing the process,
388 * |policy_line| can be of the form:
389 * "return <errno>"
390 *
391 * This "return {NUM}" policy line will block the syscall,
392 * make it return -1 and set |errno| to NUM.
393 *
394 * A regular policy line can also include a "return <errno>" clause,
395 * separated by a semicolon (';'):
396 * "arg0 == 3 && arg1 == 5 || arg0 == 0x8; return {NUM}"
397 *
398 * If the syscall arguments don't make the expression true,
399 * the syscall will be blocked as above instead of killing the process.
400 */
401
402 size_t len = 0;
403 int grp_idx = 0;
404
405 /* Checks for empty policy lines. */
406 if (strlen(policy_line) == 0) {
407 compiler_warn(state, "empty policy line");
408 return NULL;
409 }
410
411 /* We will modify |policy_line|, so let's make a copy. */
412 char *line = strdup(policy_line);
413 if (!line)
414 return NULL;
415
416 /*
417 * We build the filter section as a collection of smaller
418 * "filter blocks" linked together in a singly-linked list.
419 */
420 struct filter_block *head = new_filter_block();
421
422 /*
423 * Filter sections begin with a label where the main filter
424 * will jump after checking the syscall number.
425 */
426 struct sock_filter *entry_label = new_instr_buf(ONE_INSTR);
427 set_bpf_lbl(entry_label, entry_lbl_id);
428 append_filter_block(head, entry_label, ONE_INSTR);
429
430 /* Checks whether we're unconditionally blocking this syscall. */
431 if (strncmp(line, "return", strlen("return")) == 0) {
432 if (compile_errno(state, head, line, action) < 0) {
433 free_block_list(head);
434 free(line);
435 return NULL;
436 }
437 free(line);
438 return head;
439 }
440
441 /* Splits the optional "return <errno>" part. */
442 char *line_ptr;
443 char *arg_filter = strtok_r(line, ";", &line_ptr);
444 char *ret_errno = strtok_r(NULL, ";", &line_ptr);
445
446 /*
447 * Splits the policy line by '||' into conjunctions and each conjunction
448 * by '&&' into atoms.
449 */
450 char *arg_filter_str = arg_filter;
451 char *group;
452 while ((group = tokenize(&arg_filter_str, "||")) != NULL) {
453 char *group_str = group;
454 char *comp;
455 while ((comp = tokenize(&group_str, "&&")) != NULL) {
456 /* Compiles each atom into a BPF block. */
457 if (compile_atom(state, head, comp, labels, nr,
458 grp_idx) < 0) {
459 free_block_list(head);
460 free(line);
461 return NULL;
462 }
463 }
464 /*
465 * If the AND statement succeeds, we're done,
466 * so jump to SUCCESS line.
467 */
468 unsigned int id = success_lbl(labels, nr);
469 struct sock_filter *group_end_block = new_instr_buf(TWO_INSTRS);
470 len = set_bpf_jump_lbl(group_end_block, id);
471 /*
472 * The end of each AND statement falls after the
473 * jump to SUCCESS.
474 */
475 id = group_end_lbl(labels, nr, grp_idx++);
476 len += set_bpf_lbl(group_end_block + len, id);
477 append_filter_block(head, group_end_block, len);
478 }
479
480 /*
481 * If no AND statements succeed, we end up here,
482 * because we never jumped to SUCCESS.
483 * If we have to return an errno, do it,
484 * otherwise just kill the task.
485 */
486 if (ret_errno) {
487 if (compile_errno(state, head, ret_errno, action) < 0) {
488 free_block_list(head);
489 free(line);
490 return NULL;
491 }
492 } else {
493 switch (action) {
494 case ACTION_RET_KILL:
495 append_ret_kill(head);
496 break;
497 case ACTION_RET_KILL_PROCESS:
498 append_ret_kill_process(head);
499 break;
500 case ACTION_RET_TRAP:
501 append_ret_trap(head);
502 break;
503 case ACTION_RET_LOG:
504 append_ret_log(head);
505 break;
506 }
507 }
508
509 /*
510 * Every time the filter succeeds we jump to a predefined SUCCESS
511 * label. Add that label and BPF RET_ALLOW code now.
512 */
513 unsigned int id = success_lbl(labels, nr);
514 struct sock_filter *success_block = new_instr_buf(TWO_INSTRS);
515 len = set_bpf_lbl(success_block, id);
516 len += set_bpf_ret_allow(success_block + len);
517 append_filter_block(head, success_block, len);
518
519 free(line);
520 return head;
521 }
522
parse_include_statement(struct parser_state * state,char * policy_line,unsigned int include_level,const char ** ret_filename)523 int parse_include_statement(struct parser_state *state, char *policy_line,
524 unsigned int include_level,
525 const char **ret_filename)
526 {
527 if (strncmp("@include", policy_line, strlen("@include")) != 0) {
528 compiler_warn(state, "invalid statement '%s'", policy_line);
529 return -1;
530 }
531
532 if (policy_line[strlen("@include")] != ' ') {
533 compiler_warn(state, "invalid include statement '%s'",
534 policy_line);
535 return -1;
536 }
537
538 /*
539 * Disallow nested includes: only the initial policy file can have
540 * @include statements.
541 * Nested includes are not currently necessary and make the policy
542 * harder to understand.
543 */
544 if (include_level > 0) {
545 compiler_warn(state, "@include statement nested too deep");
546 return -1;
547 }
548
549 char *statement = policy_line;
550 /* Discard "@include" token. */
551 (void)strsep(&statement, " ");
552
553 /*
554 * compile_filter() below receives a FILE*, so it's not trivial to open
555 * included files relative to the initial policy filename.
556 * To avoid mistakes, force the included file path to be absolute
557 * (start with '/'), or to explicitly load the file relative to CWD by
558 * using './'.
559 */
560 const char *filename = statement;
561 if (is_implicit_relative_path(filename)) {
562 compiler_warn(
563 state,
564 "implicit relative path '%s' not supported, use './%s'",
565 filename, filename);
566 return -1;
567 }
568
569 *ret_filename = filename;
570 return 0;
571 }
572
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)573 int compile_file(const char *filename, FILE *policy_file,
574 struct filter_block *head, struct filter_block **arg_blocks,
575 struct bpf_labels *labels,
576 const struct filter_options *filteropts,
577 struct parser_state **previous_syscalls,
578 unsigned int include_level)
579 {
580 /* clang-format off */
581 struct parser_state state = {
582 .filename = filename,
583 .line_number = 0,
584 };
585 /* clang-format on */
586 /*
587 * Loop through all the lines in the policy file.
588 * Build a jump table for the syscall number.
589 * If the policy line has an arg filter, build the arg filter
590 * as well.
591 * Chain the filter sections together and dump them into
592 * the final buffer at the end.
593 */
594 attribute_cleanup_str char *line = NULL;
595 size_t len = 0;
596 int ret = 0;
597
598 while (getmultiline(&line, &len, policy_file) != -1) {
599 char *policy_line = line;
600 policy_line = strip(policy_line);
601
602 state.line_number++;
603
604 /* Allow comments and empty lines. */
605 if (*policy_line == '#' || *policy_line == '\0') {
606 /* Reuse |line| in the next getline() call. */
607 continue;
608 }
609
610 /* Allow @include and @frequency statements. */
611 if (*policy_line == '@') {
612 const char *filename = NULL;
613
614 /* Ignore @frequency statements. */
615 if (strncmp("@frequency", policy_line,
616 strlen("@frequency")) == 0) {
617 compiler_warn(&state,
618 "ignored @frequency statement");
619 continue;
620 }
621
622 if (parse_include_statement(&state, policy_line,
623 include_level,
624 &filename) != 0) {
625 compiler_warn(
626 &state,
627 "failed to parse include statement");
628 ret = -1;
629 goto out;
630 }
631
632 attribute_cleanup_fp FILE *included_file =
633 fopen(filename, "re");
634 if (included_file == NULL) {
635 compiler_pwarn(&state, "fopen('%s') failed",
636 filename);
637 ret = -1;
638 goto out;
639 }
640 if (compile_file(filename, included_file, head,
641 arg_blocks, labels, filteropts,
642 previous_syscalls,
643 include_level + 1) == -1) {
644 compiler_warn(&state, "'@include %s' failed",
645 filename);
646 ret = -1;
647 goto out;
648 }
649 continue;
650 }
651
652 /*
653 * If it's not a comment, or an empty line, or an @include
654 * statement, treat |policy_line| as a regular policy line.
655 */
656 char *syscall_name = strsep(&policy_line, ":");
657 if (policy_line == NULL) {
658 warn("compile_file: malformed policy line, missing "
659 "':'");
660 ret = -1;
661 goto out;
662 }
663
664 policy_line = strip(policy_line);
665 if (*policy_line == '\0') {
666 compiler_warn(&state, "empty policy line");
667 ret = -1;
668 goto out;
669 }
670
671 syscall_name = strip(syscall_name);
672 size_t ind = 0;
673 int nr = lookup_syscall(syscall_name, &ind);
674 if (nr < 0) {
675 compiler_warn(&state, "nonexistent syscall '%s'",
676 syscall_name);
677 if (filteropts->allow_logging) {
678 /*
679 * If we're logging failures, assume we're in a
680 * debugging case and continue.
681 * This is not super risky because an invalid
682 * syscall name is likely caused by a typo or by
683 * leftover lines from a different architecture.
684 * In either case, not including a policy line
685 * is equivalent to killing the process if the
686 * syscall is made, so there's no added attack
687 * surface.
688 */
689 /* Reuse |line| in the next getline() call. */
690 continue;
691 }
692 ret = -1;
693 goto out;
694 }
695
696 if (!insert_and_check_duplicate_syscall(previous_syscalls,
697 &state, ind)) {
698 if (!filteropts->allow_duplicate_syscalls)
699 ret = -1;
700 compiler_warn(&state, "syscall %s redefined here",
701 lookup_syscall_name(nr));
702 compiler_warn(previous_syscalls[ind],
703 "previous definition here");
704 }
705
706 /*
707 * For each syscall, add either a simple ALLOW,
708 * or an arg filter block.
709 */
710 if (streq(policy_line, "1")) {
711 /* Add simple ALLOW. */
712 append_allow_syscall(head, nr);
713 } else {
714 /*
715 * Create and jump to the label that will hold
716 * the arg filter block.
717 */
718 unsigned int id = bpf_label_id(labels, syscall_name);
719 struct sock_filter *nr_comp =
720 new_instr_buf(ALLOW_SYSCALL_LEN);
721 bpf_allow_syscall_args(nr_comp, nr, id);
722 append_filter_block(head, nr_comp, ALLOW_SYSCALL_LEN);
723
724 /* Build the arg filter block. */
725 struct filter_block *block =
726 compile_policy_line(&state, nr, policy_line, id,
727 labels, filteropts->action);
728
729 if (!block) {
730 if (*arg_blocks) {
731 free_block_list(*arg_blocks);
732 *arg_blocks = NULL;
733 }
734 warn("could not allocate filter block");
735 ret = -1;
736 goto out;
737 }
738
739 if (*arg_blocks) {
740 extend_filter_block_list(*arg_blocks, block);
741 } else {
742 *arg_blocks = block;
743 }
744 }
745 /* Reuse |line| in the next getline() call. */
746 }
747 /* getline(3) returned -1. This can mean EOF or an error. */
748 if (!feof(policy_file)) {
749 if (*arg_blocks) {
750 free_block_list(*arg_blocks);
751 *arg_blocks = NULL;
752 }
753 warn("getmultiline() failed");
754 ret = -1;
755 }
756
757 out:
758 return ret;
759 }
760
compile_filter(const char * filename,FILE * initial_file,struct sock_fprog * prog,const struct filter_options * filteropts)761 int compile_filter(const char *filename, FILE *initial_file,
762 struct sock_fprog *prog,
763 const struct filter_options *filteropts)
764 {
765 int ret = 0;
766 struct bpf_labels labels;
767 labels.count = 0;
768
769 if (!initial_file) {
770 warn("compile_filter: |initial_file| is NULL");
771 return -1;
772 }
773
774 struct filter_block *head = new_filter_block();
775 struct filter_block *arg_blocks = NULL;
776
777 /*
778 * Create the data structure that will keep track of what system
779 * calls we have already defined if the option is true.
780 */
781 size_t num_syscalls = get_num_syscalls();
782 struct parser_state **previous_syscalls =
783 calloc(num_syscalls, sizeof(*previous_syscalls));
784
785 /* Start filter by validating arch. */
786 struct sock_filter *valid_arch = new_instr_buf(ARCH_VALIDATION_LEN);
787 size_t len = bpf_validate_arch(valid_arch);
788 append_filter_block(head, valid_arch, len);
789
790 /* Load syscall number. */
791 struct sock_filter *load_nr = new_instr_buf(ONE_INSTR);
792 len = bpf_load_syscall_nr(load_nr);
793 append_filter_block(head, load_nr, len);
794
795 /*
796 * On kernels without SECCOMP_RET_LOG, Minijail can attempt to write the
797 * first failing syscall to syslog(3). In order for syslog(3) to work,
798 * some syscalls need to be unconditionally allowed.
799 */
800 if (filteropts->allow_syscalls_for_logging)
801 allow_selected_syscalls(head, log_syscalls, log_syscalls_len,
802 true /* log_additions */);
803
804 if (filteropts->include_libc_compatibility_allowlist)
805 allow_selected_syscalls(head, libc_compatibility_syscalls,
806 libc_compatibility_syscalls_len,
807 false /* log_additions */);
808
809 if (compile_file(filename, initial_file, head, &arg_blocks, &labels,
810 filteropts, previous_syscalls,
811 0 /* include_level */) != 0) {
812 warn("compile_filter: compile_file() failed");
813 ret = -1;
814 goto free_filter;
815 }
816
817 /*
818 * If none of the syscalls match, either fall through to LOG, TRAP, or
819 * KILL.
820 */
821 switch (filteropts->action) {
822 case ACTION_RET_KILL:
823 append_ret_kill(head);
824 break;
825 case ACTION_RET_KILL_PROCESS:
826 append_ret_kill_process(head);
827 break;
828 case ACTION_RET_TRAP:
829 append_ret_trap(head);
830 break;
831 case ACTION_RET_LOG:
832 if (filteropts->allow_logging) {
833 append_ret_log(head);
834 } else {
835 warn("compile_filter: cannot use RET_LOG without "
836 "allowing logging");
837 ret = -1;
838 goto free_filter;
839 }
840 break;
841 default:
842 warn("compile_filter: invalid log action %d",
843 filteropts->action);
844 ret = -1;
845 goto free_filter;
846 }
847
848 /* Allocate the final buffer, now that we know its size. */
849 size_t final_filter_len =
850 head->total_len + (arg_blocks ? arg_blocks->total_len : 0);
851 if (final_filter_len > BPF_MAXINSNS) {
852 ret = -1;
853 goto free_filter;
854 }
855
856 struct sock_filter *final_filter =
857 calloc(final_filter_len, sizeof(struct sock_filter));
858 if (!final_filter)
859 die("could not allocate final BPF filter");
860
861 if (flatten_block_list(head, final_filter, 0, final_filter_len) < 0) {
862 free(final_filter);
863 ret = -1;
864 goto free_filter;
865 }
866
867 if (flatten_block_list(arg_blocks, final_filter, head->total_len,
868 final_filter_len) < 0) {
869 free(final_filter);
870 ret = -1;
871 goto free_filter;
872 }
873
874 if (bpf_resolve_jumps(&labels, final_filter, final_filter_len) < 0) {
875 free(final_filter);
876 ret = -1;
877 goto free_filter;
878 }
879
880 prog->filter = final_filter;
881 prog->len = final_filter_len;
882
883 free_filter:
884 free_block_list(head);
885 free_block_list(arg_blocks);
886 free_label_strings(&labels);
887 free_previous_syscalls(previous_syscalls);
888 return ret;
889 }
890
flatten_block_list(struct filter_block * head,struct sock_filter * filter,size_t index,size_t cap)891 int flatten_block_list(struct filter_block *head, struct sock_filter *filter,
892 size_t index, size_t cap)
893 {
894 size_t _index = index;
895
896 struct filter_block *curr;
897 size_t i;
898
899 for (curr = head; curr; curr = curr->next) {
900 for (i = 0; i < curr->len; i++) {
901 if (_index >= cap)
902 return -1;
903 filter[_index++] = curr->instrs[i];
904 }
905 }
906 return 0;
907 }
908
free_block_list(struct filter_block * head)909 void free_block_list(struct filter_block *head)
910 {
911 struct filter_block *current, *prev;
912
913 current = head;
914 while (current) {
915 free(current->instrs);
916 prev = current;
917 current = current->next;
918 free(prev);
919 }
920 }
921
free_previous_syscalls(struct parser_state ** previous_syscalls)922 void free_previous_syscalls(struct parser_state **previous_syscalls)
923 {
924 size_t num_syscalls = get_num_syscalls();
925 for (size_t i = 0; i < num_syscalls; i++) {
926 struct parser_state *state = previous_syscalls[i];
927 if (state) {
928 free((char *)state->filename);
929 free(state);
930 }
931 }
932 free(previous_syscalls);
933 }
934