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