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