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