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