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