Use similar f-strings for more cases
[kconfig-hardened-check.git] / kconfig_hardened_check / __init__.py
1 #!/usr/bin/python3
2
3 """
4 This tool helps me to check Linux kernel options against
5 my security hardening preferences for X86_64, ARM64, X86_32, and ARM.
6 Let the computers do their job!
7
8 Author: Alexander Popov <alex.popov@linux.com>
9
10 This module performs input/output.
11 """
12
13 # pylint: disable=missing-function-docstring,line-too-long,invalid-name,too-many-branches,too-many-statements
14
15 import sys
16 from argparse import ArgumentParser
17 from collections import OrderedDict
18 import re
19 import json
20 from .__about__ import __version__
21 from .checks import add_kconfig_checks, add_cmdline_checks, normalize_cmdline_options
22 from .engine import populate_with_data, perform_checks
23
24
25 def detect_arch(fname, archs):
26     with open(fname, 'r', encoding='utf-8') as f:
27         arch_pattern = re.compile("CONFIG_[a-zA-Z0-9_]*=y")
28         arch = None
29         for line in f.readlines():
30             if arch_pattern.match(line):
31                 option, _ = line[7:].split('=', 1)
32                 if option in archs:
33                     if arch is None:
34                         arch = option
35                     else:
36                         return None, 'more than one supported architecture is detected'
37         if arch is None:
38             return None, 'failed to detect architecture'
39         return arch, 'OK'
40
41
42 def detect_kernel_version(fname):
43     with open(fname, 'r', encoding='utf-8') as f:
44         ver_pattern = re.compile("# Linux/.* Kernel Configuration")
45         for line in f.readlines():
46             if ver_pattern.match(line):
47                 line = line.strip()
48                 parts = line.split()
49                 ver_str = parts[2]
50                 ver_numbers = ver_str.split('.')
51                 if len(ver_numbers) < 3 or not ver_numbers[0].isdigit() or not ver_numbers[1].isdigit():
52                     msg = f'failed to parse the version "{ver_str}"'
53                     return None, msg
54                 return (int(ver_numbers[0]), int(ver_numbers[1])), None
55         return None, 'no kernel version detected'
56
57
58 def detect_compiler(fname):
59     gcc_version = None
60     clang_version = None
61     with open(fname, 'r', encoding='utf-8') as f:
62         gcc_version_pattern = re.compile("CONFIG_GCC_VERSION=[0-9]*")
63         clang_version_pattern = re.compile("CONFIG_CLANG_VERSION=[0-9]*")
64         for line in f.readlines():
65             if gcc_version_pattern.match(line):
66                 gcc_version = line[19:-1]
67             if clang_version_pattern.match(line):
68                 clang_version = line[21:-1]
69     if gcc_version is None or clang_version is None:
70         return None, 'no CONFIG_GCC_VERSION or CONFIG_CLANG_VERSION'
71     if gcc_version == '0' and clang_version != '0':
72         return 'CLANG ' + clang_version, 'OK'
73     if gcc_version != '0' and clang_version == '0':
74         return 'GCC ' + gcc_version, 'OK'
75     sys.exit(f'[!] ERROR: invalid GCC_VERSION and CLANG_VERSION: {gcc_version} {clang_version}')
76
77
78 def print_unknown_options(checklist, parsed_options):
79     known_options = []
80
81     for o1 in checklist:
82         if o1.type != 'complex':
83             known_options.append(o1.name)
84             continue
85         for o2 in o1.opts:
86             if o2.type != 'complex':
87                 if hasattr(o2, 'name'):
88                     known_options.append(o2.name)
89                 continue
90             for o3 in o2.opts:
91                 assert(o3.type != 'complex'), \
92                        f'unexpected ComplexOptCheck inside {o2.name}'
93                 if hasattr(o3, 'name'):
94                     known_options.append(o3.name)
95
96     for option, value in parsed_options.items():
97         if option not in known_options:
98             print(f'[?] No check for option {option} ({value})')
99
100
101 def print_checklist(mode, checklist, with_results):
102     if mode == 'json':
103         output = []
104         for o in checklist:
105             output.append(o.json_dump(with_results))
106         print(json.dumps(output))
107         return
108
109     # table header
110     sep_line_len = 91
111     if with_results:
112         sep_line_len += 30
113     print('=' * sep_line_len)
114     print(f'{"option name":^40}|{"type":^7}|{"desired val":^12}|{"decision":^10}|{"reason":^18}', end='')
115     if with_results:
116         print('| check result', end='')
117     print()
118     print('=' * sep_line_len)
119
120     # table contents
121     for opt in checklist:
122         if with_results:
123             if mode == 'show_ok':
124                 if not opt.result.startswith('OK'):
125                     continue
126             if mode == 'show_fail':
127                 if not opt.result.startswith('FAIL'):
128                     continue
129         opt.table_print(mode, with_results)
130         print()
131         if mode == 'verbose':
132             print('-' * sep_line_len)
133     print()
134
135     # final score
136     if with_results:
137         fail_count = len(list(filter(lambda opt: opt.result.startswith('FAIL'), checklist)))
138         fail_suppressed = ''
139         ok_count = len(list(filter(lambda opt: opt.result.startswith('OK'), checklist)))
140         ok_suppressed = ''
141         if mode == 'show_ok':
142             fail_suppressed = ' (suppressed in output)'
143         if mode == 'show_fail':
144             ok_suppressed = ' (suppressed in output)'
145         if mode != 'json':
146             print(f'[+] Config check is finished: \'OK\' - {ok_count}{ok_suppressed} / \'FAIL\' - {fail_count}{fail_suppressed}')
147
148
149 def parse_kconfig_file(parsed_options, fname):
150     with open(fname, 'r', encoding='utf-8') as f:
151         opt_is_on = re.compile("CONFIG_[a-zA-Z0-9_]*=[a-zA-Z0-9_\"]*")
152         opt_is_off = re.compile("# CONFIG_[a-zA-Z0-9_]* is not set")
153
154         for line in f.readlines():
155             line = line.strip()
156             option = None
157             value = None
158
159             if opt_is_on.match(line):
160                 option, value = line.split('=', 1)
161                 if value == 'is not set':
162                     sys.exit(f'[!] ERROR: bad enabled kconfig option "{line}"')
163             elif opt_is_off.match(line):
164                 option, value = line[2:].split(' ', 1)
165                 if value != 'is not set':
166                     sys.exit(f'[!] ERROR: bad disabled kconfig option "{line}"')
167
168             if option in parsed_options:
169                 sys.exit(f'[!] ERROR: kconfig option "{line}" exists multiple times')
170
171             if option:
172                 parsed_options[option] = value
173
174
175 def parse_cmdline_file(parsed_options, fname):
176     with open(fname, 'r', encoding='utf-8') as f:
177         line = f.readline()
178         opts = line.split()
179
180         line = f.readline()
181         if line:
182             sys.exit(f'[!] ERROR: more than one line in "{fname}"')
183
184         for opt in opts:
185             if '=' in opt:
186                 name, value = opt.split('=', 1)
187             else:
188                 name = opt
189                 value = '' # '' is not None
190             value = normalize_cmdline_options(name, value)
191             parsed_options[name] = value
192
193
194 def main():
195     # Report modes:
196     #   * verbose mode for
197     #     - reporting about unknown kernel options in the kconfig
198     #     - verbose printing of ComplexOptCheck items
199     #   * json mode for printing the results in JSON format
200     report_modes = ['verbose', 'json', 'show_ok', 'show_fail']
201     supported_archs = ['X86_64', 'X86_32', 'ARM64', 'ARM']
202     parser = ArgumentParser(prog='kconfig-hardened-check',
203                             description='A tool for checking the security hardening options of the Linux kernel')
204     parser.add_argument('--version', action='version', version='%(prog)s ' + __version__)
205     parser.add_argument('-p', '--print', choices=supported_archs,
206                         help='print security hardening preferences for the selected architecture')
207     parser.add_argument('-c', '--config',
208                         help='check the kernel kconfig file against these preferences')
209     parser.add_argument('-l', '--cmdline',
210                         help='check the kernel cmdline file against these preferences')
211     parser.add_argument('-m', '--mode', choices=report_modes,
212                         help='choose the report mode')
213     args = parser.parse_args()
214
215     mode = None
216     if args.mode:
217         mode = args.mode
218         if mode != 'json':
219             print(f'[+] Special report mode: {mode}')
220
221     config_checklist = []
222
223     if args.config:
224         if args.print:
225             sys.exit('[!] ERROR: --config and --print can\'t be used together')
226
227         if mode != 'json':
228             print(f'[+] Kconfig file to check: {args.config}')
229             if args.cmdline:
230                 print(f'[+] Kernel cmdline file to check: {args.cmdline}')
231
232         arch, msg = detect_arch(args.config, supported_archs)
233         if arch is None:
234             sys.exit(f'[!] ERROR: {msg}')
235         if mode != 'json':
236             print(f'[+] Detected architecture: {arch}')
237
238         kernel_version, msg = detect_kernel_version(args.config)
239         if kernel_version is None:
240             sys.exit(f'[!] ERROR: {msg}')
241         if mode != 'json':
242             print(f'[+] Detected kernel version: {kernel_version[0]}.{kernel_version[1]}')
243
244         compiler, msg = detect_compiler(args.config)
245         if mode != 'json':
246             if compiler:
247                 print(f'[+] Detected compiler: {compiler}')
248             else:
249                 print(f'[-] Can\'t detect the compiler: {msg}')
250
251         # add relevant kconfig checks to the checklist
252         add_kconfig_checks(config_checklist, arch)
253
254         if args.cmdline:
255             # add relevant cmdline checks to the checklist
256             add_cmdline_checks(config_checklist, arch)
257
258         # populate the checklist with the parsed kconfig data
259         parsed_kconfig_options = OrderedDict()
260         parse_kconfig_file(parsed_kconfig_options, args.config)
261         populate_with_data(config_checklist, parsed_kconfig_options, 'kconfig')
262         populate_with_data(config_checklist, kernel_version, 'version')
263
264         if args.cmdline:
265             # populate the checklist with the parsed kconfig data
266             parsed_cmdline_options = OrderedDict()
267             parse_cmdline_file(parsed_cmdline_options, args.cmdline)
268             populate_with_data(config_checklist, parsed_cmdline_options, 'cmdline')
269
270         # now everything is ready, perform the checks
271         perform_checks(config_checklist)
272
273         if mode == 'verbose':
274             # print the parsed options without the checks (for debugging)
275             all_parsed_options = parsed_kconfig_options # assignment does not copy
276             if args.cmdline:
277                 all_parsed_options.update(parsed_cmdline_options)
278             print_unknown_options(config_checklist, all_parsed_options)
279
280         # finally print the results
281         print_checklist(mode, config_checklist, True)
282
283         sys.exit(0)
284     elif args.cmdline:
285         sys.exit('[!] ERROR: checking cmdline doesn\'t work without checking kconfig')
286
287     if args.print:
288         if mode in ('show_ok', 'show_fail'):
289             sys.exit(f'[!] ERROR: wrong mode "{mode}" for --print')
290         arch = args.print
291         add_kconfig_checks(config_checklist, arch)
292         add_cmdline_checks(config_checklist, arch)
293         if mode != 'json':
294             print(f'[+] Printing kernel security hardening preferences for {arch}...')
295         print_checklist(mode, config_checklist, False)
296         sys.exit(0)
297
298     parser.print_help()
299     sys.exit(0)