Get rid of useless regular expressions in detect_compiler()
[kconfig-hardened-check.git] / kconfig_hardened_check / __init__.py
1 #!/usr/bin/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("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("# Linux/.+ Kernel Configuration$")
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]
57                 ver_numbers = ver_str.split('.')
58                 if len(ver_numbers) < 3 or not ver_numbers[0].isdigit() or not ver_numbers[1].isdigit():
59                     msg = f'failed to parse the version "{ver_str}"'
60                     return None, msg
61                 return (int(ver_numbers[0]), int(ver_numbers[1])), None
62         return None, 'no kernel version detected'
63
64
65 def detect_compiler(fname):
66     gcc_version = None
67     clang_version = None
68     with _open(fname, 'rt', encoding='utf-8') as f:
69         for line in f.readlines():
70             if line.startswith('CONFIG_GCC_VERSION='):
71                 gcc_version = line[19:-1]
72             if line.startswith('CONFIG_CLANG_VERSION='):
73                 clang_version = line[21:-1]
74     if gcc_version is None or clang_version is None:
75         return None, 'no CONFIG_GCC_VERSION or CONFIG_CLANG_VERSION'
76     if gcc_version == '0' and clang_version != '0':
77         return 'CLANG ' + clang_version, 'OK'
78     if gcc_version != '0' and clang_version == '0':
79         return 'GCC ' + gcc_version, 'OK'
80     sys.exit(f'[!] ERROR: invalid GCC_VERSION and CLANG_VERSION: {gcc_version} {clang_version}')
81
82
83 def print_unknown_options(checklist, parsed_options):
84     known_options = []
85
86     for o1 in checklist:
87         if o1.type != 'complex':
88             known_options.append(o1.name)
89             continue
90         for o2 in o1.opts:
91             if o2.type != 'complex':
92                 if hasattr(o2, 'name'):
93                     known_options.append(o2.name)
94                 continue
95             for o3 in o2.opts:
96                 assert(o3.type != 'complex'), \
97                        f'unexpected ComplexOptCheck inside {o2.name}'
98                 if hasattr(o3, 'name'):
99                     known_options.append(o3.name)
100
101     for option, value in parsed_options.items():
102         if option not in known_options:
103             print(f'[?] No check for option {option} ({value})')
104
105
106 def print_checklist(mode, checklist, with_results):
107     if mode == 'json':
108         output = []
109         for opt in checklist:
110             output.append(opt.json_dump(with_results))
111         print(json.dumps(output))
112         return
113
114     # table header
115     sep_line_len = 91
116     if with_results:
117         sep_line_len += 30
118     print('=' * sep_line_len)
119     print(f'{"option name":^40}|{"type":^7}|{"desired val":^12}|{"decision":^10}|{"reason":^18}', end='')
120     if with_results:
121         print('| check result', end='')
122     print()
123     print('=' * sep_line_len)
124
125     # table contents
126     for opt in checklist:
127         if with_results:
128             if mode == 'show_ok':
129                 if not opt.result.startswith('OK'):
130                     continue
131             if mode == 'show_fail':
132                 if not opt.result.startswith('FAIL'):
133                     continue
134         opt.table_print(mode, with_results)
135         print()
136         if mode == 'verbose':
137             print('-' * sep_line_len)
138     print()
139
140     # final score
141     if with_results:
142         fail_count = len(list(filter(lambda opt: opt.result.startswith('FAIL'), checklist)))
143         fail_suppressed = ''
144         ok_count = len(list(filter(lambda opt: opt.result.startswith('OK'), checklist)))
145         ok_suppressed = ''
146         if mode == 'show_ok':
147             fail_suppressed = ' (suppressed in output)'
148         if mode == 'show_fail':
149             ok_suppressed = ' (suppressed in output)'
150         print(f'[+] Config check is finished: \'OK\' - {ok_count}{ok_suppressed} / \'FAIL\' - {fail_count}{fail_suppressed}')
151
152
153 def parse_kconfig_file(parsed_options, fname):
154     with _open(fname, 'rt', encoding='utf-8') as f:
155         opt_is_on = re.compile("CONFIG_[a-zA-Z0-9_]*=[a-zA-Z0-9_\"]*")
156         opt_is_off = re.compile("# CONFIG_[a-zA-Z0-9_]* is not set")
157
158         for line in f.readlines():
159             line = line.strip()
160             option = None
161             value = None
162
163             if opt_is_on.match(line):
164                 option, value = line.split('=', 1)
165                 if value == 'is not set':
166                     sys.exit(f'[!] ERROR: bad enabled Kconfig option "{line}"')
167             elif opt_is_off.match(line):
168                 option, value = line[2:].split(' ', 1)
169                 if value != 'is not set':
170                     sys.exit(f'[!] ERROR: bad disabled Kconfig option "{line}"')
171
172             if option in parsed_options:
173                 sys.exit(f'[!] ERROR: Kconfig option "{line}" exists multiple times')
174
175             if option:
176                 parsed_options[option] = value
177
178
179 def parse_cmdline_file(parsed_options, fname):
180     with open(fname, 'r', encoding='utf-8') as f:
181         line = f.readline()
182         opts = line.split()
183
184         line = f.readline()
185         if line:
186             sys.exit(f'[!] ERROR: more than one line in "{fname}"')
187
188         for opt in opts:
189             if '=' in opt:
190                 name, value = opt.split('=', 1)
191             else:
192                 name = opt
193                 value = '' # '' is not None
194             if name in parsed_options:
195                 sys.exit(f'[!] ERROR: cmdline option "{name}" exists multiple times')
196             value = normalize_cmdline_options(name, value)
197             parsed_options[name] = value
198
199
200 def parse_sysctl_file(parsed_options, fname):
201     print('parse_sysctl_file: TODO')
202
203
204 def main():
205     # Report modes:
206     #   * verbose mode for
207     #     - reporting about unknown kernel options in the Kconfig
208     #     - verbose printing of ComplexOptCheck items
209     #   * json mode for printing the results in JSON format
210     report_modes = ['verbose', 'json', 'show_ok', 'show_fail']
211     supported_archs = ['X86_64', 'X86_32', 'ARM64', 'ARM']
212     parser = ArgumentParser(prog='kconfig-hardened-check',
213                             description='A tool for checking the security hardening options of the Linux kernel')
214     parser.add_argument('--version', action='version', version='%(prog)s ' + __version__)
215     parser.add_argument('-m', '--mode', choices=report_modes,
216                         help='choose the report mode')
217     parser.add_argument('-c', '--config',
218                         help='check the security hardening options in the kernel Kconfig file (also supports *.gz files)')
219     parser.add_argument('-l', '--cmdline',
220                         help='check the security hardening options in the kernel cmdline file (contents of /proc/cmdline)')
221 #   parser.add_argument('-s', '--sysctl',
222 #                       help='check the security hardening options in the sysctl output file (`sudo sysctl -a > file`)')
223     parser.add_argument('-p', '--print', choices=supported_archs,
224                         help='print the security hardening recommendations for the selected microarchitecture')
225     parser.add_argument('-g', '--generate', choices=supported_archs,
226                         help='generate a Kconfig fragment with the security hardening options for the selected microarchitecture')
227     args = parser.parse_args()
228     args.sysctl = None # FIXME
229
230     mode = None
231     if args.mode:
232         mode = args.mode
233         if mode != 'json':
234             print(f'[+] Special report mode: {mode}')
235
236     config_checklist = []
237
238     if args.config:
239         if args.print:
240             sys.exit('[!] ERROR: --config and --print can\'t be used together')
241
242         if args.generate:
243             sys.exit('[!] ERROR: --config and --generate can\'t be used together')
244
245         if mode != 'json':
246             print(f'[+] Kconfig file to check: {args.config}')
247             if args.cmdline:
248                 print(f'[+] Kernel cmdline file to check: {args.cmdline}')
249             if args.sysctl:
250                 print(f'[+] Kernel sysctl output file to check: {args.sysctl}')
251
252         arch, msg = detect_arch(args.config, supported_archs)
253         if arch is None:
254             sys.exit(f'[!] ERROR: {msg}')
255         if mode != 'json':
256             print(f'[+] Detected microarchitecture: {arch}')
257
258         kernel_version, msg = detect_kernel_version(args.config)
259         if kernel_version is None:
260             sys.exit(f'[!] ERROR: {msg}')
261         if mode != 'json':
262             print(f'[+] Detected kernel version: {kernel_version[0]}.{kernel_version[1]}')
263
264         compiler, msg = detect_compiler(args.config)
265         if mode != 'json':
266             if compiler:
267                 print(f'[+] Detected compiler: {compiler}')
268             else:
269                 print(f'[-] Can\'t detect the compiler: {msg}')
270
271         # add relevant Kconfig checks to the checklist
272         add_kconfig_checks(config_checklist, arch)
273
274         if args.cmdline:
275             # add relevant cmdline checks to the checklist
276             add_cmdline_checks(config_checklist, arch)
277
278         if args.sysctl:
279             # add relevant sysctl checks to the checklist
280             add_sysctl_checks(config_checklist, arch)
281
282         # populate the checklist with the parsed Kconfig data
283         parsed_kconfig_options = OrderedDict()
284         parse_kconfig_file(parsed_kconfig_options, args.config)
285         populate_with_data(config_checklist, parsed_kconfig_options, 'kconfig')
286
287         # populate the checklist with the kernel version data
288         populate_with_data(config_checklist, kernel_version, 'version')
289
290         if args.cmdline:
291             # populate the checklist with the parsed cmdline data
292             parsed_cmdline_options = OrderedDict()
293             parse_cmdline_file(parsed_cmdline_options, args.cmdline)
294             populate_with_data(config_checklist, parsed_cmdline_options, 'cmdline')
295
296         if args.sysctl:
297             # populate the checklist with the parsed sysctl data
298             parsed_sysctl_options = OrderedDict()
299             parse_sysctl_file(parsed_sysctl_options, args.sysctl)
300             populate_with_data(config_checklist, parsed_sysctl_options, 'sysctl')
301
302         # hackish refinement of the CONFIG_ARCH_MMAP_RND_BITS check
303         mmap_rnd_bits_max = parsed_kconfig_options.get('CONFIG_ARCH_MMAP_RND_BITS_MAX', None)
304         if mmap_rnd_bits_max:
305             override_expected_value(config_checklist, 'CONFIG_ARCH_MMAP_RND_BITS', mmap_rnd_bits_max)
306
307         # now everything is ready, perform the checks
308         perform_checks(config_checklist)
309
310         if mode == 'verbose':
311             # print the parsed options without the checks (for debugging)
312             all_parsed_options = parsed_kconfig_options # assignment does not copy
313             if args.cmdline:
314                 all_parsed_options.update(parsed_cmdline_options)
315             if args.sysctl:
316                 all_parsed_options.update(parsed_sysctl_options)
317             print_unknown_options(config_checklist, all_parsed_options)
318
319         # finally print the results
320         print_checklist(mode, config_checklist, True)
321
322         sys.exit(0)
323     elif args.cmdline:
324         sys.exit('[!] ERROR: checking cmdline depends on checking Kconfig')
325     elif args.sysctl:
326         # TODO: sysctl check should also work separately
327         sys.exit('[!] ERROR: checking sysctl depends on checking Kconfig')
328
329     if args.print:
330         assert(args.config is None and args.cmdline is None and args.sysctl is None), 'unexpected args'
331         if mode and mode not in ('verbose', 'json'):
332             sys.exit(f'[!] ERROR: wrong mode "{mode}" for --print')
333         arch = args.print
334         add_kconfig_checks(config_checklist, arch)
335         add_cmdline_checks(config_checklist, arch)
336         add_sysctl_checks(config_checklist, arch)
337         if mode != 'json':
338             print(f'[+] Printing kernel security hardening options for {arch}...')
339         print_checklist(mode, config_checklist, False)
340         sys.exit(0)
341
342     if args.generate:
343         assert(args.config is None and args.cmdline is None and args.sysctl is None), 'unexpected args'
344         if mode:
345             sys.exit(f'[!] ERROR: wrong mode "{mode}" for --generate')
346         arch = args.generate
347         add_kconfig_checks(config_checklist, arch)
348         print(f'CONFIG_{arch}=y') # the Kconfig fragment should describe the microarchitecture
349         for opt in config_checklist:
350             if opt.name == 'CONFIG_ARCH_MMAP_RND_BITS':
351                 continue # don't add CONFIG_ARCH_MMAP_RND_BITS because its value needs refinement
352             if opt.expected == 'is not set':
353                 print(f'# {opt.name} is not set')
354             else:
355                 print(f'{opt.name}={opt.expected}')
356         sys.exit(0)
357
358     parser.print_help()
359     sys.exit(0)