Don't use the `type` name for the class methods
[kconfig-hardened-check.git] / kernel_hardening_checker / __init__.py
1 #!/usr/bin/env python3
2
3 """
4 This tool is for checking the security hardening options of the Linux kernel.
5
6 Author: Alexander Popov <alex.popov@linux.com>
7
8 This module performs input/output.
9 """
10
11 # pylint: disable=missing-function-docstring,line-too-long,invalid-name,too-many-branches,too-many-statements
12
13 import gzip
14 import sys
15 from argparse import ArgumentParser
16 from collections import OrderedDict
17 import re
18 import json
19 from .__about__ import __version__
20 from .checks import add_kconfig_checks, add_cmdline_checks, normalize_cmdline_options, add_sysctl_checks
21 from .engine import populate_with_data, perform_checks, override_expected_value
22
23
24 def _open(file: str, *args, **kwargs):
25     open_method = open
26     if file.endswith('.gz'):
27         open_method = gzip.open
28
29     return open_method(file, *args, **kwargs)
30
31
32 def detect_arch(fname, archs):
33     with _open(fname, 'rt', encoding='utf-8') as f:
34         arch_pattern = re.compile(r"CONFIG_[a-zA-Z0-9_]+=y$")
35         arch = None
36         for line in f.readlines():
37             if arch_pattern.match(line):
38                 option, _ = line[7:].split('=', 1)
39                 if option in archs:
40                     if arch is None:
41                         arch = option
42                     else:
43                         return None, 'detected more than one microarchitecture'
44         if arch is None:
45             return None, 'failed to detect microarchitecture'
46         return arch, 'OK'
47
48
49 def detect_kernel_version(fname):
50     with _open(fname, 'rt', encoding='utf-8') as f:
51         ver_pattern = re.compile(r"^# Linux/.+ Kernel Configuration$|^Linux version .+")
52         for line in f.readlines():
53             if ver_pattern.match(line):
54                 line = line.strip()
55                 parts = line.split()
56                 ver_str = parts[2].split('-', 1)[0]
57                 ver_numbers = ver_str.split('.')
58                 if len(ver_numbers) >= 3:
59                     if all(map(lambda x: x.isdigit(), ver_numbers)):
60                         return tuple(map(int, ver_numbers)), None
61                 msg = f'failed to parse the version "{parts[2]}"'
62                 return None, msg
63         return None, 'no kernel version detected'
64
65
66 def detect_compiler(fname):
67     gcc_version = None
68     clang_version = None
69     with _open(fname, 'rt', encoding='utf-8') as f:
70         for line in f.readlines():
71             if line.startswith('CONFIG_GCC_VERSION='):
72                 gcc_version = line[19:-1]
73             if line.startswith('CONFIG_CLANG_VERSION='):
74                 clang_version = line[21:-1]
75     if gcc_version is None or clang_version is None:
76         return None, 'no CONFIG_GCC_VERSION or CONFIG_CLANG_VERSION'
77     if gcc_version == '0' and clang_version != '0':
78         return f'CLANG {clang_version}', 'OK'
79     if gcc_version != '0' and clang_version == '0':
80         return f'GCC {gcc_version}', 'OK'
81     sys.exit(f'[!] ERROR: invalid GCC_VERSION and CLANG_VERSION: {gcc_version} {clang_version}')
82
83
84 def print_unknown_options(checklist, parsed_options, opt_type):
85     known_options = []
86
87     for o1 in checklist:
88         if o1.opt_type != 'complex':
89             known_options.append(o1.name)
90             continue
91         for o2 in o1.opts:
92             if o2.opt_type != 'complex':
93                 if hasattr(o2, 'name'):
94                     known_options.append(o2.name)
95                 continue
96             for o3 in o2.opts:
97                 assert(o3.opt_type != 'complex'), \
98                        f'unexpected ComplexOptCheck inside {o2.name}'
99                 if hasattr(o3, 'name'):
100                     known_options.append(o3.name)
101
102     for option, value in parsed_options.items():
103         if option not in known_options:
104             print(f'[?] No check for {opt_type} option {option} ({value})')
105
106
107 def print_checklist(mode, checklist, with_results):
108     if mode == 'json':
109         output = []
110         for opt in checklist:
111             output.append(opt.json_dump(with_results))
112         print(json.dumps(output))
113         return
114
115     # table header
116     sep_line_len = 91
117     if with_results:
118         sep_line_len += 30
119     print('=' * sep_line_len)
120     print(f'{"option_name":^40}|{"type":^7}|{"desired_val":^12}|{"decision":^10}|{"reason":^18}', end='')
121     if with_results:
122         print('| check_result', end='')
123     print()
124     print('=' * sep_line_len)
125
126     # table contents
127     for opt in checklist:
128         if with_results:
129             if mode == 'show_ok':
130                 if not opt.result.startswith('OK'):
131                     continue
132             if mode == 'show_fail':
133                 if not opt.result.startswith('FAIL'):
134                     continue
135         opt.table_print(mode, with_results)
136         print()
137         if mode == 'verbose':
138             print('-' * sep_line_len)
139     print()
140
141     # final score
142     if with_results:
143         fail_count = len(list(filter(lambda opt: opt.result.startswith('FAIL'), checklist)))
144         fail_suppressed = ''
145         ok_count = len(list(filter(lambda opt: opt.result.startswith('OK'), checklist)))
146         ok_suppressed = ''
147         if mode == 'show_ok':
148             fail_suppressed = ' (suppressed in output)'
149         if mode == 'show_fail':
150             ok_suppressed = ' (suppressed in output)'
151         print(f'[+] Config check is finished: \'OK\' - {ok_count}{ok_suppressed} / \'FAIL\' - {fail_count}{fail_suppressed}')
152
153
154 def parse_kconfig_file(_mode, parsed_options, fname):
155     with _open(fname, 'rt', encoding='utf-8') as f:
156         opt_is_on = re.compile(r"CONFIG_[a-zA-Z0-9_]+=.+$")
157         opt_is_off = re.compile(r"# CONFIG_[a-zA-Z0-9_]+ is not set$")
158
159         for line in f.readlines():
160             line = line.strip()
161             option = None
162             value = None
163
164             if opt_is_on.match(line):
165                 option, value = line.split('=', 1)
166                 if value == 'is not set':
167                     sys.exit(f'[!] ERROR: bad enabled Kconfig option "{line}"')
168             elif opt_is_off.match(line):
169                 option, value = line[2:].split(' ', 1)
170                 assert(value == 'is not set'), \
171                        f'unexpected value of disabled Kconfig option "{line}"'
172             elif line != '' and not line.startswith('#'):
173                 sys.exit(f'[!] ERROR: unexpected line in Kconfig file: "{line}"')
174
175             if option in parsed_options:
176                 sys.exit(f'[!] ERROR: Kconfig option "{line}" is found multiple times')
177
178             if option:
179                 parsed_options[option] = value
180
181
182 def parse_cmdline_file(mode, parsed_options, fname):
183     with open(fname, 'r', encoding='utf-8') as f:
184         line = f.readline()
185         opts = line.split()
186
187         line = f.readline()
188         if line:
189             sys.exit(f'[!] ERROR: more than one line in "{fname}"')
190
191         for opt in opts:
192             if '=' in opt:
193                 name, value = opt.split('=', 1)
194             else:
195                 name = opt
196                 value = '' # '' is not None
197             if name in parsed_options and mode != 'json':
198                 print(f'[!] WARNING: cmdline option "{name}" is found multiple times')
199             value = normalize_cmdline_options(name, value)
200             parsed_options[name] = value
201
202
203 def parse_sysctl_file(mode, parsed_options, fname):
204     with open(fname, 'r', encoding='utf-8') as f:
205         sysctl_pattern = re.compile(r"[a-zA-Z0-9/\._-]+ =.*$")
206         for line in f.readlines():
207             line = line.strip()
208             if not sysctl_pattern.match(line):
209                 sys.exit(f'[!] ERROR: unexpected line in sysctl file: "{line}"')
210             option, value = line.split('=', 1)
211             option = option.strip()
212             value = value.strip()
213             # sysctl options may be found multiple times, let's save the last value:
214             parsed_options[option] = value
215
216     # let's check the presence of some ancient sysctl option
217     # to ensure that we are parsing the output of `sudo sysctl -a > file`
218     if 'kernel.printk' not in parsed_options:
219         sys.exit(f'[!] ERROR: {fname} doesn\'t look like a sysctl output file, please try `sudo sysctl -a > {fname}`')
220
221     # let's check the presence of a sysctl option available for root
222     if 'net.core.bpf_jit_harden' not in parsed_options and mode != 'json':
223         print(f'[!] WARNING: sysctl option "net.core.bpf_jit_harden" available for root is not found in {fname}, please try `sudo sysctl -a > {fname}`')
224
225
226 def main():
227     # Report modes:
228     #   * verbose mode for
229     #     - reporting about unknown kernel options in the Kconfig
230     #     - verbose printing of ComplexOptCheck items
231     #   * json mode for printing the results in JSON format
232     report_modes = ['verbose', 'json', 'show_ok', 'show_fail']
233     supported_archs = ['X86_64', 'X86_32', 'ARM64', 'ARM']
234     parser = ArgumentParser(prog='kernel-hardening-checker',
235                             description='A tool for checking the security hardening options of the Linux kernel')
236     parser.add_argument('--version', action='version', version=f'%(prog)s {__version__}')
237     parser.add_argument('-m', '--mode', choices=report_modes,
238                         help='choose the report mode')
239     parser.add_argument('-c', '--config',
240                         help='check the security hardening options in the kernel Kconfig file (also supports *.gz files)')
241     parser.add_argument('-l', '--cmdline',
242                         help='check the security hardening options in the kernel cmdline file (contents of /proc/cmdline)')
243     parser.add_argument('-s', '--sysctl',
244                         help='check the security hardening options in the sysctl output file (`sudo sysctl -a > file`)')
245     parser.add_argument('-v', '--kernel-version',
246                         help='extract the version from the kernel version file (contents of /proc/version)')
247     parser.add_argument('-p', '--print', choices=supported_archs,
248                         help='print the security hardening recommendations for the selected microarchitecture')
249     parser.add_argument('-g', '--generate', choices=supported_archs,
250                         help='generate a Kconfig fragment with the security hardening options for the selected microarchitecture')
251     args = parser.parse_args()
252
253     mode = None
254     if args.mode:
255         mode = args.mode
256         if mode != 'json':
257             print(f'[+] Special report mode: {mode}')
258
259     config_checklist = []
260
261     if args.config:
262         if args.print:
263             sys.exit('[!] ERROR: --config and --print can\'t be used together')
264         if args.generate:
265             sys.exit('[!] ERROR: --config and --generate can\'t be used together')
266
267         if mode != 'json':
268             print(f'[+] Kconfig file to check: {args.config}')
269             if args.cmdline:
270                 print(f'[+] Kernel cmdline file to check: {args.cmdline}')
271             if args.sysctl:
272                 print(f'[+] Sysctl output file to check: {args.sysctl}')
273
274         arch, msg = detect_arch(args.config, supported_archs)
275         if arch is None:
276             sys.exit(f'[!] ERROR: {msg}')
277         if mode != 'json':
278             print(f'[+] Detected microarchitecture: {arch}')
279
280         if args.kernel_version:
281             kernel_version, msg = detect_kernel_version(args.kernel_version)
282         else:
283             kernel_version, msg = detect_kernel_version(args.config)
284         if kernel_version is None:
285             if args.kernel_version is None:
286                 print('[!] Hint: provide the kernel version file through --kernel-version option')
287             sys.exit(f'[!] ERROR: {msg}')
288         if mode != 'json':
289             print(f'[+] Detected kernel version: {kernel_version}')
290
291         compiler, msg = detect_compiler(args.config)
292         if mode != 'json':
293             if compiler:
294                 print(f'[+] Detected compiler: {compiler}')
295             else:
296                 print(f'[-] Can\'t detect the compiler: {msg}')
297
298         # add relevant Kconfig checks to the checklist
299         add_kconfig_checks(config_checklist, arch)
300
301         if args.cmdline:
302             # add relevant cmdline checks to the checklist
303             add_cmdline_checks(config_checklist, arch)
304
305         if args.sysctl:
306             # add relevant sysctl checks to the checklist
307             add_sysctl_checks(config_checklist, arch)
308
309         # populate the checklist with the parsed Kconfig data
310         parsed_kconfig_options = OrderedDict()
311         parse_kconfig_file(mode, parsed_kconfig_options, args.config)
312         populate_with_data(config_checklist, parsed_kconfig_options, 'kconfig')
313
314         # populate the checklist with the kernel version data
315         populate_with_data(config_checklist, kernel_version, 'version')
316
317         if args.cmdline:
318             # populate the checklist with the parsed cmdline data
319             parsed_cmdline_options = OrderedDict()
320             parse_cmdline_file(mode, parsed_cmdline_options, args.cmdline)
321             populate_with_data(config_checklist, parsed_cmdline_options, 'cmdline')
322
323         if args.sysctl:
324             # populate the checklist with the parsed sysctl data
325             parsed_sysctl_options = OrderedDict()
326             parse_sysctl_file(mode, parsed_sysctl_options, args.sysctl)
327             populate_with_data(config_checklist, parsed_sysctl_options, 'sysctl')
328
329         # hackish refinement of the CONFIG_ARCH_MMAP_RND_BITS check
330         mmap_rnd_bits_max = parsed_kconfig_options.get('CONFIG_ARCH_MMAP_RND_BITS_MAX', None)
331         if mmap_rnd_bits_max:
332             override_expected_value(config_checklist, 'CONFIG_ARCH_MMAP_RND_BITS', mmap_rnd_bits_max)
333         else:
334             # remove the CONFIG_ARCH_MMAP_RND_BITS check to avoid false results
335             if mode != 'json':
336                 print('[-] Can\'t check CONFIG_ARCH_MMAP_RND_BITS without CONFIG_ARCH_MMAP_RND_BITS_MAX')
337             config_checklist[:] = [o for o in config_checklist if o.name != 'CONFIG_ARCH_MMAP_RND_BITS']
338
339         # now everything is ready, perform the checks
340         perform_checks(config_checklist)
341
342         if mode == 'verbose':
343             # print the parsed options without the checks (for debugging)
344             print_unknown_options(config_checklist, parsed_kconfig_options, 'kconfig')
345             if args.cmdline:
346                 print_unknown_options(config_checklist, parsed_cmdline_options, 'cmdline')
347             if args.sysctl:
348                 print_unknown_options(config_checklist, parsed_sysctl_options, 'sysctl')
349
350         # finally print the results
351         print_checklist(mode, config_checklist, True)
352         sys.exit(0)
353     elif args.cmdline:
354         sys.exit('[!] ERROR: checking cmdline depends on checking Kconfig')
355     elif args.sysctl:
356         # separate sysctl checking (without kconfig)
357         assert(args.config is None and args.cmdline is None), 'unexpected args'
358         if args.print:
359             sys.exit('[!] ERROR: --sysctl and --print can\'t be used together')
360         if args.generate:
361             sys.exit('[!] ERROR: --sysctl and --generate can\'t be used together')
362
363         if mode != 'json':
364             print(f'[+] Sysctl output file to check: {args.sysctl}')
365
366         # add relevant sysctl checks to the checklist
367         add_sysctl_checks(config_checklist, None)
368
369         # populate the checklist with the parsed sysctl data
370         parsed_sysctl_options = OrderedDict()
371         parse_sysctl_file(mode, parsed_sysctl_options, args.sysctl)
372         populate_with_data(config_checklist, parsed_sysctl_options, 'sysctl')
373
374         # now everything is ready, perform the checks
375         perform_checks(config_checklist)
376
377         if mode == 'verbose':
378             # print the parsed options without the checks (for debugging)
379             print_unknown_options(config_checklist, parsed_sysctl_options, 'sysctl')
380
381         # finally print the results
382         print_checklist(mode, config_checklist, True)
383         sys.exit(0)
384
385     if args.print:
386         assert(args.config is None and args.cmdline is None and args.sysctl is None), 'unexpected args'
387         if args.generate:
388             sys.exit('[!] ERROR: --print and --generate can\'t be used together')
389         if mode and mode not in ('verbose', 'json'):
390             sys.exit(f'[!] ERROR: wrong mode "{mode}" for --print')
391         arch = args.print
392         add_kconfig_checks(config_checklist, arch)
393         add_cmdline_checks(config_checklist, arch)
394         add_sysctl_checks(config_checklist, arch)
395         if mode != 'json':
396             print(f'[+] Printing kernel security hardening options for {arch}...')
397         print_checklist(mode, config_checklist, False)
398         sys.exit(0)
399
400     if args.generate:
401         assert(args.config is None and args.cmdline is None and args.sysctl is None and args.print is None), 'unexpected args'
402         if mode:
403             sys.exit(f'[!] ERROR: wrong mode "{mode}" for --generate')
404         arch = args.generate
405         add_kconfig_checks(config_checklist, arch)
406         print(f'CONFIG_{arch}=y') # the Kconfig fragment should describe the microarchitecture
407         for opt in config_checklist:
408             if opt.name == 'CONFIG_ARCH_MMAP_RND_BITS':
409                 continue # don't add CONFIG_ARCH_MMAP_RND_BITS because its value needs refinement
410             if opt.expected == 'is not off':
411                 continue # don't add Kconfig options without explicitly recommended values
412             if opt.expected == 'is not set':
413                 print(f'# {opt.name} is not set')
414             else:
415                 print(f'{opt.name}={opt.expected}')
416         sys.exit(0)
417
418     parser.print_help()
419     sys.exit(0)