Paul Lawrence | eabc352 | 2016-11-11 11:33:42 -0800 | [diff] [blame] | 1 | #!/usr/bin/env python |
| 2 | import os |
| 3 | from subprocess import Popen, PIPE |
| 4 | import textwrap |
| 5 | from gensyscalls import SysCallsTxtParser |
| 6 | |
| 7 | |
| 8 | syscall_file = "SYSCALLS.TXT" |
| 9 | |
| 10 | |
| 11 | class SyscallRange(object): |
| 12 | def __init__(self, name, value): |
| 13 | self.names = [name] |
| 14 | self.begin = value |
| 15 | self.end = self.begin + 1 |
| 16 | |
| 17 | def add(self, name, value): |
| 18 | if value != self.end: |
| 19 | raise ValueError |
| 20 | self.end += 1 |
| 21 | self.names.append(name) |
| 22 | |
| 23 | |
| 24 | def generate_bpf_jge(value, ge_target, less_target): |
| 25 | return "BPF_JUMP(BPF_JMP|BPF_JGE|BPF_K, {0}, {1}, {2})".format(value, ge_target, less_target) |
| 26 | |
| 27 | |
| 28 | # Converts the sorted ranges of allowed syscalls to a binary tree bpf |
| 29 | # For a single range, output a simple jump to {fail} or {allow}. We can't set |
| 30 | # the jump ranges yet, since we don't know the size of the filter, so use a |
| 31 | # placeholder |
| 32 | # For multiple ranges, split into two, convert the two halves and output a jump |
| 33 | # to the correct half |
| 34 | def convert_to_bpf(ranges): |
| 35 | if len(ranges) == 1: |
| 36 | # We will replace {fail} and {allow} with appropriate range jumps later |
| 37 | return [generate_bpf_jge(ranges[0].end, "{fail}", "{allow}") + |
| 38 | ", //" + "|".join(ranges[0].names)] |
| 39 | else: |
| 40 | half = (len(ranges) + 1) / 2 |
| 41 | first = convert_to_bpf(ranges[:half]) |
| 42 | second = convert_to_bpf(ranges[half:]) |
| 43 | return [generate_bpf_jge(ranges[half].begin, len(first), 0) + ","] + first + second |
| 44 | |
| 45 | |
| 46 | def construct_bpf(architecture, header_dir, output_path): |
| 47 | parser = SysCallsTxtParser() |
| 48 | parser.parse_file(syscall_file) |
| 49 | syscalls = parser.syscalls |
| 50 | |
| 51 | # Select only elements matching required architecture |
| 52 | syscalls = [x for x in syscalls if architecture in x and x[architecture]] |
| 53 | |
| 54 | # We only want the name |
| 55 | names = [x["name"] for x in syscalls] |
| 56 | |
| 57 | # Run preprocessor over the __NR_syscall symbols, including unistd.h, |
| 58 | # to get the actual numbers |
| 59 | prefix = "__SECCOMP_" # prefix to ensure no name collisions |
| 60 | cpp = Popen(["../../prebuilts/clang/host/linux-x86/clang-stable/bin/clang", |
| 61 | "-E", "-nostdinc", "-I" + header_dir, "-Ikernel/uapi/", "-"], |
| 62 | stdin=PIPE, stdout=PIPE) |
| 63 | cpp.stdin.write("#include <asm/unistd.h>\n") |
| 64 | for name in names: |
| 65 | # In SYSCALLS.TXT, there are two arm-specific syscalls whose names start |
| 66 | # with __ARM__NR_. These we must simply write out as is. |
| 67 | if not name.startswith("__ARM_NR_"): |
| 68 | cpp.stdin.write(prefix + name + ", __NR_" + name + "\n") |
| 69 | else: |
| 70 | cpp.stdin.write(prefix + name + ", " + name + "\n") |
| 71 | content = cpp.communicate()[0].split("\n") |
| 72 | |
| 73 | # The input is now the preprocessed source file. This will contain a lot |
| 74 | # of junk from the preprocessor, but our lines will be in the format: |
| 75 | # |
| 76 | # __SECCOMP_${NAME}, (0 + value) |
| 77 | |
| 78 | syscalls = [] |
| 79 | for line in content: |
| 80 | if not line.startswith(prefix): |
| 81 | continue |
| 82 | |
| 83 | # We might pick up extra whitespace during preprocessing, so best to strip. |
| 84 | name, value = [w.strip() for w in line.split(",")] |
| 85 | name = name[len(prefix):] |
| 86 | |
| 87 | # Note that some of the numbers were expressed as base + offset, so we |
| 88 | # need to eval, not just int |
| 89 | value = eval(value) |
| 90 | syscalls.append((name, value)) |
| 91 | |
| 92 | # Sort the values so we convert to ranges and binary chop |
| 93 | syscalls = sorted(syscalls, lambda x, y: cmp(x[1], y[1])) |
| 94 | |
| 95 | # Turn into a list of ranges. Keep the names for the comments |
| 96 | ranges = [] |
| 97 | for name, value in syscalls: |
| 98 | if not ranges: |
| 99 | ranges.append(SyscallRange(name, value)) |
| 100 | continue |
| 101 | |
| 102 | last_range = ranges[-1] |
| 103 | if last_range.end == value: |
| 104 | last_range.add(name, value) |
| 105 | else: |
| 106 | ranges.append(SyscallRange(name, value)) |
| 107 | |
| 108 | bpf = convert_to_bpf(ranges) |
| 109 | |
| 110 | # Now we know the size of the tree, we can substitute the {fail} and {allow} |
| 111 | # placeholders |
| 112 | for i, statement in enumerate(bpf): |
| 113 | # Replace placeholder with |
| 114 | # "distance to jump to fail, distance to jump to allow" |
| 115 | # We will add a kill statement and an allow statement after the tree |
| 116 | # With bpfs jmp 0 means the next statement, so the distance to the end is |
| 117 | # len(bpf) - i - 1, which is where we will put the kill statement, and |
| 118 | # then the statement after that is the allow statement |
| 119 | if "{fail}" in statement and "{allow}" in statement: |
Paul Lawrence | be8a2af | 2017-01-25 15:20:52 -0800 | [diff] [blame^] | 120 | bpf[i] = statement.format(fail=str(len(bpf) - i), |
| 121 | allow=str(len(bpf) - i - 1)) |
Paul Lawrence | eabc352 | 2016-11-11 11:33:42 -0800 | [diff] [blame] | 122 | |
| 123 | # Add check that we aren't off the bottom of the syscalls |
| 124 | bpf.insert(0, |
| 125 | "BPF_JUMP(BPF_JMP|BPF_JGE|BPF_K, " + str(ranges[0].begin) + |
| 126 | ", 0, " + str(len(bpf)) + "),") |
| 127 | |
Paul Lawrence | be8a2af | 2017-01-25 15:20:52 -0800 | [diff] [blame^] | 128 | # Add the allow calls at the end. If the syscall is not matched, we will |
| 129 | # continue. This allows the user to choose to match further syscalls, and |
| 130 | # also to choose the action when we want to block |
Paul Lawrence | eabc352 | 2016-11-11 11:33:42 -0800 | [diff] [blame] | 131 | bpf.append("BPF_STMT(BPF_RET|BPF_K, SECCOMP_RET_ALLOW),") |
| 132 | |
| 133 | # And output policy |
| 134 | header = textwrap.dedent("""\ |
| 135 | // Autogenerated file - edit at your peril!! |
| 136 | |
| 137 | #include <linux/filter.h> |
| 138 | #include <errno.h> |
| 139 | |
| 140 | #include "seccomp_policy.h" |
| 141 | const struct sock_filter {architecture}_filter[] = {{ |
| 142 | """).format(architecture=architecture) |
| 143 | |
| 144 | footer = textwrap.dedent("""\ |
| 145 | |
| 146 | }}; |
| 147 | |
| 148 | const size_t {architecture}_filter_size = sizeof({architecture}_filter) / sizeof(struct sock_filter); |
| 149 | """).format(architecture=architecture) |
| 150 | output = header + "\n".join(bpf) + footer |
| 151 | |
| 152 | existing = "" |
| 153 | if os.path.isfile(output_path): |
| 154 | existing = open(output_path).read() |
| 155 | if output == existing: |
| 156 | print "File " + output_path + " not changed." |
| 157 | else: |
| 158 | with open(output_path, "w") as output_file: |
| 159 | output_file.write(output) |
| 160 | |
| 161 | print "Generated file " + output_path |
| 162 | |
| 163 | |
| 164 | def main(): |
| 165 | # Set working directory for predictable results |
| 166 | os.chdir(os.path.join(os.environ["ANDROID_BUILD_TOP"], "bionic/libc")) |
| 167 | construct_bpf("arm", "kernel/uapi/asm-arm", "seccomp/arm_policy.c") |
| 168 | construct_bpf("arm64", "kernel/uapi/asm-arm64", "seccomp/arm64_policy.c") |
| 169 | |
| 170 | |
| 171 | if __name__ == "__main__": |
| 172 | main() |