4 This tool is for checking the security hardening options of the Linux kernel.
6 Author: Alexander Popov <alex.popov@linux.com>
8 This module performs input/output.
11 # pylint: disable=missing-function-docstring,line-too-long,invalid-name,too-many-branches,too-many-statements
15 from argparse import ArgumentParser
16 from collections import OrderedDict
19 from .__about__ import __version__
20 from .checks import add_kconfig_checks, add_cmdline_checks, normalize_cmdline_options, add_sysctl_checks
21 from .engine import populate_with_data, perform_checks, override_expected_value
24 def _open(file: str, *args, **kwargs):
26 if file.endswith('.gz'):
27 open_method = gzip.open
29 return open_method(file, *args, **kwargs)
32 def detect_arch(fname, archs):
33 with _open(fname, 'rt', encoding='utf-8') as f:
34 arch_pattern = re.compile(r"CONFIG_[a-zA-Z0-9_]+=y$")
36 for line in f.readlines():
37 if arch_pattern.match(line):
38 option, _ = line[7:].split('=', 1)
43 return None, 'detected more than one microarchitecture'
45 return None, 'failed to detect microarchitecture'
49 def detect_kernel_version(fname):
50 with _open(fname, 'rt', encoding='utf-8') as f:
51 ver_pattern = re.compile(r"^# Linux/.+ Kernel Configuration$|^Linux version .+")
52 for line in f.readlines():
53 if ver_pattern.match(line):
56 ver_str = parts[2].split('-', 1)[0]
57 ver_numbers = ver_str.split('.')
58 if len(ver_numbers) >= 3:
59 if all(map(lambda x: x.isdigit(), ver_numbers)):
60 return tuple(map(int, ver_numbers)), None
61 msg = f'failed to parse the version "{parts[2]}"'
63 return None, 'no kernel version detected'
66 def detect_compiler(fname):
69 with _open(fname, 'rt', encoding='utf-8') as f:
70 for line in f.readlines():
71 if line.startswith('CONFIG_GCC_VERSION='):
72 gcc_version = line[19:-1]
73 if line.startswith('CONFIG_CLANG_VERSION='):
74 clang_version = line[21:-1]
75 if gcc_version is None or clang_version is None:
76 return None, 'no CONFIG_GCC_VERSION or CONFIG_CLANG_VERSION'
77 if gcc_version == '0' and clang_version != '0':
78 return f'CLANG {clang_version}', 'OK'
79 if gcc_version != '0' and clang_version == '0':
80 return f'GCC {gcc_version}', 'OK'
81 sys.exit(f'[!] ERROR: invalid GCC_VERSION and CLANG_VERSION: {gcc_version} {clang_version}')
84 def print_unknown_options(checklist, parsed_options, opt_type):
88 if o1.type != 'complex':
89 known_options.append(o1.name)
92 if o2.type != 'complex':
93 if hasattr(o2, 'name'):
94 known_options.append(o2.name)
97 assert(o3.type != 'complex'), \
98 f'unexpected ComplexOptCheck inside {o2.name}'
99 if hasattr(o3, 'name'):
100 known_options.append(o3.name)
102 for option, value in parsed_options.items():
103 if option not in known_options:
104 print(f'[?] No check for {opt_type} option {option} ({value})')
107 def print_checklist(mode, checklist, with_results):
110 for opt in checklist:
111 output.append(opt.json_dump(with_results))
112 print(json.dumps(output))
119 print('=' * sep_line_len)
120 print(f'{"option name":^40}|{"type":^7}|{"desired val":^12}|{"decision":^10}|{"reason":^18}', end='')
122 print('| check result', end='')
124 print('=' * sep_line_len)
127 for opt in checklist:
129 if mode == 'show_ok':
130 if not opt.result.startswith('OK'):
132 if mode == 'show_fail':
133 if not opt.result.startswith('FAIL'):
135 opt.table_print(mode, with_results)
137 if mode == 'verbose':
138 print('-' * sep_line_len)
143 fail_count = len(list(filter(lambda opt: opt.result.startswith('FAIL'), checklist)))
145 ok_count = len(list(filter(lambda opt: opt.result.startswith('OK'), checklist)))
147 if mode == 'show_ok':
148 fail_suppressed = ' (suppressed in output)'
149 if mode == 'show_fail':
150 ok_suppressed = ' (suppressed in output)'
151 print(f'[+] Config check is finished: \'OK\' - {ok_count}{ok_suppressed} / \'FAIL\' - {fail_count}{fail_suppressed}')
154 def parse_kconfig_file(_mode, parsed_options, fname):
155 with _open(fname, 'rt', encoding='utf-8') as f:
156 opt_is_on = re.compile(r"CONFIG_[a-zA-Z0-9_]+=.+$")
157 opt_is_off = re.compile(r"# CONFIG_[a-zA-Z0-9_]+ is not set$")
159 for line in f.readlines():
164 if opt_is_on.match(line):
165 option, value = line.split('=', 1)
166 if value == 'is not set':
167 sys.exit(f'[!] ERROR: bad enabled Kconfig option "{line}"')
168 elif opt_is_off.match(line):
169 option, value = line[2:].split(' ', 1)
170 assert(value == 'is not set'), \
171 f'unexpected value of disabled Kconfig option "{line}"'
172 elif line != '' and not line.startswith('#'):
173 sys.exit(f'[!] ERROR: unexpected line in Kconfig file: "{line}"')
175 if option in parsed_options:
176 sys.exit(f'[!] ERROR: Kconfig option "{line}" is found multiple times')
179 parsed_options[option] = value
182 def parse_cmdline_file(mode, parsed_options, fname):
183 with open(fname, 'r', encoding='utf-8') as f:
189 sys.exit(f'[!] ERROR: more than one line in "{fname}"')
193 name, value = opt.split('=', 1)
196 value = '' # '' is not None
197 if name in parsed_options and mode != 'json':
198 print(f'[!] WARNING: cmdline option "{name}" is found multiple times')
199 value = normalize_cmdline_options(name, value)
200 parsed_options[name] = value
203 def parse_sysctl_file(mode, parsed_options, fname):
204 with open(fname, 'r', encoding='utf-8') as f:
205 sysctl_pattern = re.compile(r"[a-zA-Z0-9/\._-]+ =.*$")
206 for line in f.readlines():
208 if not sysctl_pattern.match(line):
209 sys.exit(f'[!] ERROR: unexpected line in sysctl file: "{line}"')
210 option, value = line.split('=', 1)
211 option = option.strip()
212 value = value.strip()
213 # sysctl options may be found multiple times, let's save the last value:
214 parsed_options[option] = value
216 # let's check the presence of some ancient sysctl option
217 # to ensure that we are parsing the output of `sudo sysctl -a > file`
218 if 'kernel.printk' not in parsed_options:
219 sys.exit(f'[!] ERROR: {fname} doesn\'t look like a sysctl output file, please try `sudo sysctl -a > {fname}`')
221 # let's check the presence of a sysctl option available for root
222 if 'net.core.bpf_jit_harden' not in parsed_options and mode != 'json':
223 print(f'[!] WARNING: sysctl option "net.core.bpf_jit_harden" available for root is not found in {fname}, please try `sudo sysctl -a > {fname}`')
229 # - reporting about unknown kernel options in the Kconfig
230 # - verbose printing of ComplexOptCheck items
231 # * json mode for printing the results in JSON format
232 report_modes = ['verbose', 'json', 'show_ok', 'show_fail']
233 supported_archs = ['X86_64', 'X86_32', 'ARM64', 'ARM']
234 parser = ArgumentParser(prog='kernel-hardening-checker',
235 description='A tool for checking the security hardening options of the Linux kernel')
236 parser.add_argument('--version', action='version', version=f'%(prog)s {__version__}')
237 parser.add_argument('-m', '--mode', choices=report_modes,
238 help='choose the report mode')
239 parser.add_argument('-c', '--config',
240 help='check the security hardening options in the kernel Kconfig file (also supports *.gz files)')
241 parser.add_argument('-l', '--cmdline',
242 help='check the security hardening options in the kernel cmdline file (contents of /proc/cmdline)')
243 parser.add_argument('-s', '--sysctl',
244 help='check the security hardening options in the sysctl output file (`sudo sysctl -a > file`)')
245 parser.add_argument('-v', '--kernel-version',
246 help='extract the version from the kernel version file (contents of /proc/version)')
247 parser.add_argument('-p', '--print', choices=supported_archs,
248 help='print the security hardening recommendations for the selected microarchitecture')
249 parser.add_argument('-g', '--generate', choices=supported_archs,
250 help='generate a Kconfig fragment with the security hardening options for the selected microarchitecture')
251 args = parser.parse_args()
257 print(f'[+] Special report mode: {mode}')
259 config_checklist = []
263 sys.exit('[!] ERROR: --config and --print can\'t be used together')
265 sys.exit('[!] ERROR: --config and --generate can\'t be used together')
268 print(f'[+] Kconfig file to check: {args.config}')
270 print(f'[+] Kernel cmdline file to check: {args.cmdline}')
272 print(f'[+] Sysctl output file to check: {args.sysctl}')
274 arch, msg = detect_arch(args.config, supported_archs)
276 sys.exit(f'[!] ERROR: {msg}')
278 print(f'[+] Detected microarchitecture: {arch}')
280 if args.kernel_version:
281 kernel_version, msg = detect_kernel_version(args.kernel_version)
283 kernel_version, msg = detect_kernel_version(args.config)
284 if kernel_version is None:
285 if args.kernel_version is None:
286 print('[!] Hint: provide the kernel version file through --kernel-version option')
287 sys.exit(f'[!] ERROR: {msg}')
289 print(f'[+] Detected kernel version: {kernel_version}')
291 compiler, msg = detect_compiler(args.config)
294 print(f'[+] Detected compiler: {compiler}')
296 print(f'[-] Can\'t detect the compiler: {msg}')
298 # add relevant Kconfig checks to the checklist
299 add_kconfig_checks(config_checklist, arch)
302 # add relevant cmdline checks to the checklist
303 add_cmdline_checks(config_checklist, arch)
306 # add relevant sysctl checks to the checklist
307 add_sysctl_checks(config_checklist, arch)
309 # populate the checklist with the parsed Kconfig data
310 parsed_kconfig_options = OrderedDict()
311 parse_kconfig_file(mode, parsed_kconfig_options, args.config)
312 populate_with_data(config_checklist, parsed_kconfig_options, 'kconfig')
314 # populate the checklist with the kernel version data
315 populate_with_data(config_checklist, kernel_version, 'version')
318 # populate the checklist with the parsed cmdline data
319 parsed_cmdline_options = OrderedDict()
320 parse_cmdline_file(mode, parsed_cmdline_options, args.cmdline)
321 populate_with_data(config_checklist, parsed_cmdline_options, 'cmdline')
324 # populate the checklist with the parsed sysctl data
325 parsed_sysctl_options = OrderedDict()
326 parse_sysctl_file(mode, parsed_sysctl_options, args.sysctl)
327 populate_with_data(config_checklist, parsed_sysctl_options, 'sysctl')
329 # hackish refinement of the CONFIG_ARCH_MMAP_RND_BITS check
330 mmap_rnd_bits_max = parsed_kconfig_options.get('CONFIG_ARCH_MMAP_RND_BITS_MAX', None)
331 if mmap_rnd_bits_max:
332 override_expected_value(config_checklist, 'CONFIG_ARCH_MMAP_RND_BITS', mmap_rnd_bits_max)
334 # remove the CONFIG_ARCH_MMAP_RND_BITS check to avoid false results
336 print('[-] Can\'t check CONFIG_ARCH_MMAP_RND_BITS without CONFIG_ARCH_MMAP_RND_BITS_MAX')
337 config_checklist[:] = [o for o in config_checklist if o.name != 'CONFIG_ARCH_MMAP_RND_BITS']
339 # now everything is ready, perform the checks
340 perform_checks(config_checklist)
342 if mode == 'verbose':
343 # print the parsed options without the checks (for debugging)
344 print_unknown_options(config_checklist, parsed_kconfig_options, 'kconfig')
346 print_unknown_options(config_checklist, parsed_cmdline_options, 'cmdline')
348 print_unknown_options(config_checklist, parsed_sysctl_options, 'sysctl')
350 # finally print the results
351 print_checklist(mode, config_checklist, True)
354 sys.exit('[!] ERROR: checking cmdline depends on checking Kconfig')
356 # separate sysctl checking (without kconfig)
357 assert(args.config is None and args.cmdline is None), 'unexpected args'
359 sys.exit('[!] ERROR: --sysctl and --print can\'t be used together')
361 sys.exit('[!] ERROR: --sysctl and --generate can\'t be used together')
364 print(f'[+] Sysctl output file to check: {args.sysctl}')
366 # add relevant sysctl checks to the checklist
367 add_sysctl_checks(config_checklist, None)
369 # populate the checklist with the parsed sysctl data
370 parsed_sysctl_options = OrderedDict()
371 parse_sysctl_file(mode, parsed_sysctl_options, args.sysctl)
372 populate_with_data(config_checklist, parsed_sysctl_options, 'sysctl')
374 # now everything is ready, perform the checks
375 perform_checks(config_checklist)
377 if mode == 'verbose':
378 # print the parsed options without the checks (for debugging)
379 print_unknown_options(config_checklist, parsed_sysctl_options, 'sysctl')
381 # finally print the results
382 print_checklist(mode, config_checklist, True)
386 assert(args.config is None and args.cmdline is None and args.sysctl is None), 'unexpected args'
388 sys.exit('[!] ERROR: --print and --generate can\'t be used together')
389 if mode and mode not in ('verbose', 'json'):
390 sys.exit(f'[!] ERROR: wrong mode "{mode}" for --print')
392 add_kconfig_checks(config_checklist, arch)
393 add_cmdline_checks(config_checklist, arch)
394 add_sysctl_checks(config_checklist, arch)
396 print(f'[+] Printing kernel security hardening options for {arch}...')
397 print_checklist(mode, config_checklist, False)
401 assert(args.config is None and args.cmdline is None and args.sysctl is None and args.print is None), 'unexpected args'
403 sys.exit(f'[!] ERROR: wrong mode "{mode}" for --generate')
405 add_kconfig_checks(config_checklist, arch)
406 print(f'CONFIG_{arch}=y') # the Kconfig fragment should describe the microarchitecture
407 for opt in config_checklist:
408 if opt.name == 'CONFIG_ARCH_MMAP_RND_BITS':
409 continue # don't add CONFIG_ARCH_MMAP_RND_BITS because its value needs refinement
410 if opt.expected == 'is not off':
411 continue # don't add Kconfig options without explicitly recommended values
412 if opt.expected == 'is not set':
413 print(f'# {opt.name} is not set')
415 print(f'{opt.name}={opt.expected}')