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!
8 Author: Alexander Popov <alex.popov@linux.com>
10 This module performs input/output.
13 # pylint: disable=missing-function-docstring,line-too-long,invalid-name,too-many-branches,too-many-statements
17 from argparse import ArgumentParser
18 from collections import OrderedDict
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, override_expected_value
26 def _open(file: str, *args, **kwargs):
28 if file.endswith(".gz"):
29 open_method = gzip.open
31 return open_method(file, *args, **kwargs)
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")
38 for line in f.readlines():
39 if arch_pattern.match(line):
40 option, _ = line[7:].split('=', 1)
45 return None, 'more than one supported architecture is detected'
47 return None, 'failed to detect architecture'
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):
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}"'
63 return (int(ver_numbers[0]), int(ver_numbers[1])), None
64 return None, 'no kernel version detected'
67 def detect_compiler(fname):
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}')
87 def print_unknown_options(checklist, parsed_options):
91 if o1.type != 'complex':
92 known_options.append(o1.name)
95 if o2.type != 'complex':
96 if hasattr(o2, 'name'):
97 known_options.append(o2.name)
100 assert(o3.type != 'complex'), \
101 f'unexpected ComplexOptCheck inside {o2.name}'
102 if hasattr(o3, 'name'):
103 known_options.append(o3.name)
105 for option, value in parsed_options.items():
106 if option not in known_options:
107 print(f'[?] No check for option {option} ({value})')
110 def print_checklist(mode, checklist, with_results):
113 for opt in checklist:
114 output.append(opt.json_dump(with_results))
115 print(json.dumps(output))
122 print('=' * sep_line_len)
123 print(f'{"option name":^40}|{"type":^7}|{"desired val":^12}|{"decision":^10}|{"reason":^18}', end='')
125 print('| check result', end='')
127 print('=' * sep_line_len)
130 for opt in checklist:
132 if mode == 'show_ok':
133 if not opt.result.startswith('OK'):
135 if mode == 'show_fail':
136 if not opt.result.startswith('FAIL'):
138 opt.table_print(mode, with_results)
140 if mode == 'verbose':
141 print('-' * sep_line_len)
146 fail_count = len(list(filter(lambda opt: opt.result.startswith('FAIL'), checklist)))
148 ok_count = len(list(filter(lambda opt: opt.result.startswith('OK'), checklist)))
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}')
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")
162 for line in f.readlines():
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}"')
176 if option in parsed_options:
177 sys.exit(f'[!] ERROR: kconfig option "{line}" exists multiple times')
180 parsed_options[option] = value
183 def parse_cmdline_file(parsed_options, fname):
184 with open(fname, 'r', encoding='utf-8') as f:
190 sys.exit(f'[!] ERROR: more than one line in "{fname}"')
194 name, value = opt.split('=', 1)
197 value = '' # '' is not None
198 value = normalize_cmdline_options(name, value)
199 parsed_options[name] = value
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()
227 print(f'[+] Special report mode: {mode}')
229 config_checklist = []
233 sys.exit('[!] ERROR: --config and --print can\'t be used together')
236 print(f'[+] Kconfig file to check: {args.config}')
238 print(f'[+] Kernel cmdline file to check: {args.cmdline}')
240 arch, msg = detect_arch(args.config, supported_archs)
242 sys.exit(f'[!] ERROR: {msg}')
244 print(f'[+] Detected architecture: {arch}')
246 kernel_version, msg = detect_kernel_version(args.config)
247 if kernel_version is None:
248 sys.exit(f'[!] ERROR: {msg}')
250 print(f'[+] Detected kernel version: {kernel_version[0]}.{kernel_version[1]}')
252 compiler, msg = detect_compiler(args.config)
255 print(f'[+] Detected compiler: {compiler}')
257 print(f'[-] Can\'t detect the compiler: {msg}')
259 # add relevant kconfig checks to the checklist
260 add_kconfig_checks(config_checklist, arch)
263 # add relevant cmdline checks to the checklist
264 add_cmdline_checks(config_checklist, arch)
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')
271 # populate the checklist with the kernel version data
272 populate_with_data(config_checklist, kernel_version, 'version')
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')
280 # hackish refinement of the CONFIG_ARCH_MMAP_RND_BITS check
281 mmap_rnd_bits_max = parsed_kconfig_options.get('CONFIG_ARCH_MMAP_RND_BITS_MAX', None)
282 if mmap_rnd_bits_max:
283 override_expected_value(config_checklist, 'CONFIG_ARCH_MMAP_RND_BITS', mmap_rnd_bits_max)
285 # now everything is ready, perform the checks
286 perform_checks(config_checklist)
288 if mode == 'verbose':
289 # print the parsed options without the checks (for debugging)
290 all_parsed_options = parsed_kconfig_options # assignment does not copy
292 all_parsed_options.update(parsed_cmdline_options)
293 print_unknown_options(config_checklist, all_parsed_options)
295 # finally print the results
296 print_checklist(mode, config_checklist, True)
300 sys.exit('[!] ERROR: checking cmdline doesn\'t work without checking kconfig')
303 if mode in ('show_ok', 'show_fail'):
304 sys.exit(f'[!] ERROR: wrong mode "{mode}" for --print')
306 add_kconfig_checks(config_checklist, arch)
307 add_cmdline_checks(config_checklist, arch)
309 print(f'[+] Printing kernel security hardening preferences for {arch}...')
310 print_checklist(mode, config_checklist, False)