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