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):
57 ver_numbers = ver_str.split('.')
58 if len(ver_numbers) < 3 or not ver_numbers[0].isdigit() or not ver_numbers[1].isdigit():
59 msg = f'failed to parse the version "{ver_str}"'
61 return (int(ver_numbers[0]), int(ver_numbers[1])), None
62 return None, 'no kernel version detected'
65 def detect_compiler(fname):
68 with _open(fname, 'rt', encoding='utf-8') as f:
69 for line in f.readlines():
70 if line.startswith('CONFIG_GCC_VERSION='):
71 gcc_version = line[19:-1]
72 if line.startswith('CONFIG_CLANG_VERSION='):
73 clang_version = line[21:-1]
74 if gcc_version is None or clang_version is None:
75 return None, 'no CONFIG_GCC_VERSION or CONFIG_CLANG_VERSION'
76 if gcc_version == '0' and clang_version != '0':
77 return 'CLANG ' + clang_version, 'OK'
78 if gcc_version != '0' and clang_version == '0':
79 return 'GCC ' + gcc_version, 'OK'
80 sys.exit(f'[!] ERROR: invalid GCC_VERSION and CLANG_VERSION: {gcc_version} {clang_version}')
83 def print_unknown_options(checklist, parsed_options, opt_type):
87 if o1.type != 'complex':
88 known_options.append(o1.name)
91 if o2.type != 'complex':
92 if hasattr(o2, 'name'):
93 known_options.append(o2.name)
96 assert(o3.type != 'complex'), \
97 f'unexpected ComplexOptCheck inside {o2.name}'
98 if hasattr(o3, 'name'):
99 known_options.append(o3.name)
101 for option, value in parsed_options.items():
102 if option not in known_options:
103 print(f'[?] No check for {opt_type} option {option} ({value})')
106 def print_checklist(mode, checklist, with_results):
109 for opt in checklist:
110 output.append(opt.json_dump(with_results))
111 print(json.dumps(output))
118 print('=' * sep_line_len)
119 print(f'{"option name":^40}|{"type":^7}|{"desired val":^12}|{"decision":^10}|{"reason":^18}', end='')
121 print('| check result', end='')
123 print('=' * sep_line_len)
126 for opt in checklist:
128 if mode == 'show_ok':
129 if not opt.result.startswith('OK'):
131 if mode == 'show_fail':
132 if not opt.result.startswith('FAIL'):
134 opt.table_print(mode, with_results)
136 if mode == 'verbose':
137 print('-' * sep_line_len)
142 fail_count = len(list(filter(lambda opt: opt.result.startswith('FAIL'), checklist)))
144 ok_count = len(list(filter(lambda opt: opt.result.startswith('OK'), checklist)))
146 if mode == 'show_ok':
147 fail_suppressed = ' (suppressed in output)'
148 if mode == 'show_fail':
149 ok_suppressed = ' (suppressed in output)'
150 print(f'[+] Config check is finished: \'OK\' - {ok_count}{ok_suppressed} / \'FAIL\' - {fail_count}{fail_suppressed}')
153 def parse_kconfig_file(mode, parsed_options, fname):
154 with _open(fname, 'rt', encoding='utf-8') as f:
155 opt_is_on = re.compile(r"CONFIG_[a-zA-Z0-9_]+=.+$")
156 opt_is_off = re.compile(r"# CONFIG_[a-zA-Z0-9_]+ is not set$")
158 for line in f.readlines():
163 if opt_is_on.match(line):
164 option, value = line.split('=', 1)
165 if value == 'is not set':
166 sys.exit(f'[!] ERROR: bad enabled Kconfig option "{line}"')
167 elif opt_is_off.match(line):
168 option, value = line[2:].split(' ', 1)
169 assert(value == 'is not set'), \
170 f'unexpected value of disabled Kconfig option "{line}"'
171 elif line != '' and not line.startswith('#'):
172 sys.exit(f'[!] ERROR: unexpected line in Kconfig file: "{line}"')
174 if option in parsed_options:
175 sys.exit(f'[!] ERROR: Kconfig option "{line}" is found multiple times')
178 parsed_options[option] = value
181 def parse_cmdline_file(mode, parsed_options, fname):
182 with open(fname, 'r', encoding='utf-8') as f:
188 sys.exit(f'[!] ERROR: more than one line in "{fname}"')
192 name, value = opt.split('=', 1)
195 value = '' # '' is not None
196 if name in parsed_options and mode != 'json':
197 print(f'[!] WARNING: cmdline option "{name}" is found multiple times')
198 value = normalize_cmdline_options(name, value)
199 parsed_options[name] = value
202 def parse_sysctl_file(mode, parsed_options, fname):
203 with open(fname, 'r', encoding='utf-8') as f:
204 sysctl_pattern = re.compile(r"[a-zA-Z0-9/\._-]+ =.*$")
205 for line in f.readlines():
207 if not sysctl_pattern.match(line):
208 sys.exit(f'[!] ERROR: unexpected line in sysctl file: "{line}"')
209 option, value = line.split('=', 1)
210 option = option.strip()
211 value = value.strip()
212 # sysctl options may be found multiple times, let's save the last value:
213 parsed_options[option] = value
215 # let's check the presence of some ancient sysctl option
216 # to ensure that we are parsing the output of `sudo sysctl -a > file`
217 if 'kernel.printk' not in parsed_options:
218 sys.exit(f'[!] ERROR: {fname} doesn\'t look like a sysctl output file, please try `sudo sysctl -a > {fname}`')
220 # let's check the presence of a sysctl option available for root
221 if 'net.core.bpf_jit_harden' not in parsed_options and mode != 'json':
222 print(f'[!] WARNING: sysctl option "net.core.bpf_jit_harden" available for root is not found in {fname}, please try `sudo sysctl -a > {fname}`')
228 # - reporting about unknown kernel options in the Kconfig
229 # - verbose printing of ComplexOptCheck items
230 # * json mode for printing the results in JSON format
231 report_modes = ['verbose', 'json', 'show_ok', 'show_fail']
232 supported_archs = ['X86_64', 'X86_32', 'ARM64', 'ARM']
233 parser = ArgumentParser(prog='kernel-hardening-checker',
234 description='A tool for checking the security hardening options of the Linux kernel')
235 parser.add_argument('--version', action='version', version='%(prog)s ' + __version__)
236 parser.add_argument('-m', '--mode', choices=report_modes,
237 help='choose the report mode')
238 parser.add_argument('-c', '--config',
239 help='check the security hardening options in the kernel Kconfig file (also supports *.gz files)')
240 parser.add_argument('-l', '--cmdline',
241 help='check the security hardening options in the kernel cmdline file (contents of /proc/cmdline)')
242 parser.add_argument('-s', '--sysctl',
243 help='check the security hardening options in the sysctl output file (`sudo sysctl -a > file`)')
244 parser.add_argument('-v', '--kernel-version',
245 help='extract the version from the kernel version file (contents of /proc/version)')
246 parser.add_argument('-p', '--print', choices=supported_archs,
247 help='print the security hardening recommendations for the selected microarchitecture')
248 parser.add_argument('-g', '--generate', choices=supported_archs,
249 help='generate a Kconfig fragment with the security hardening options for the selected microarchitecture')
250 args = parser.parse_args()
256 print(f'[+] Special report mode: {mode}')
258 config_checklist = []
262 sys.exit('[!] ERROR: --config and --print can\'t be used together')
264 sys.exit('[!] ERROR: --config and --generate can\'t be used together')
267 print(f'[+] Kconfig file to check: {args.config}')
269 print(f'[+] Kernel cmdline file to check: {args.cmdline}')
271 print(f'[+] Sysctl output file to check: {args.sysctl}')
273 arch, msg = detect_arch(args.config, supported_archs)
275 sys.exit(f'[!] ERROR: {msg}')
277 print(f'[+] Detected microarchitecture: {arch}')
279 if args.kernel_version:
280 kernel_version, msg = detect_kernel_version(args.kernel_version)
282 kernel_version, msg = detect_kernel_version(args.config)
283 if kernel_version is None:
284 if not args.kernel_version:
285 print('[!] Hint: provide the kernel version file through --kernel-version option')
286 sys.exit(f'[!] ERROR: {msg}')
288 print(f'[+] Detected kernel version: {kernel_version[0]}.{kernel_version[1]}')
290 compiler, msg = detect_compiler(args.config)
293 print(f'[+] Detected compiler: {compiler}')
295 print(f'[-] Can\'t detect the compiler: {msg}')
297 # add relevant Kconfig checks to the checklist
298 add_kconfig_checks(config_checklist, arch)
301 # add relevant cmdline checks to the checklist
302 add_cmdline_checks(config_checklist, arch)
305 # add relevant sysctl checks to the checklist
306 add_sysctl_checks(config_checklist, arch)
308 # populate the checklist with the parsed Kconfig data
309 parsed_kconfig_options = OrderedDict()
310 parse_kconfig_file(mode, parsed_kconfig_options, args.config)
311 populate_with_data(config_checklist, parsed_kconfig_options, 'kconfig')
313 # populate the checklist with the kernel version data
314 populate_with_data(config_checklist, kernel_version, 'version')
317 # populate the checklist with the parsed cmdline data
318 parsed_cmdline_options = OrderedDict()
319 parse_cmdline_file(mode, parsed_cmdline_options, args.cmdline)
320 populate_with_data(config_checklist, parsed_cmdline_options, 'cmdline')
323 # populate the checklist with the parsed sysctl data
324 parsed_sysctl_options = OrderedDict()
325 parse_sysctl_file(mode, parsed_sysctl_options, args.sysctl)
326 populate_with_data(config_checklist, parsed_sysctl_options, 'sysctl')
328 # hackish refinement of the CONFIG_ARCH_MMAP_RND_BITS check
329 mmap_rnd_bits_max = parsed_kconfig_options.get('CONFIG_ARCH_MMAP_RND_BITS_MAX', None)
330 if mmap_rnd_bits_max:
331 override_expected_value(config_checklist, 'CONFIG_ARCH_MMAP_RND_BITS', mmap_rnd_bits_max)
333 # remove the CONFIG_ARCH_MMAP_RND_BITS check to avoid false results
334 print('[-] Can\'t check CONFIG_ARCH_MMAP_RND_BITS without CONFIG_ARCH_MMAP_RND_BITS_MAX')
335 config_checklist[:] = [o for o in config_checklist if o.name != 'CONFIG_ARCH_MMAP_RND_BITS']
337 # now everything is ready, perform the checks
338 perform_checks(config_checklist)
340 if mode == 'verbose':
341 # print the parsed options without the checks (for debugging)
342 print_unknown_options(config_checklist, parsed_kconfig_options, 'kconfig')
344 print_unknown_options(config_checklist, parsed_cmdline_options, 'cmdline')
346 print_unknown_options(config_checklist, parsed_sysctl_options, 'sysctl')
348 # finally print the results
349 print_checklist(mode, config_checklist, True)
352 sys.exit('[!] ERROR: checking cmdline depends on checking Kconfig')
354 # separate sysctl checking (without kconfig)
355 assert(args.config is None and args.cmdline is None), 'unexpected args'
357 sys.exit('[!] ERROR: --sysctl and --print can\'t be used together')
359 sys.exit('[!] ERROR: --sysctl and --generate can\'t be used together')
362 print(f'[+] Sysctl output file to check: {args.sysctl}')
364 # add relevant sysctl checks to the checklist
365 add_sysctl_checks(config_checklist, None)
367 # populate the checklist with the parsed sysctl data
368 parsed_sysctl_options = OrderedDict()
369 parse_sysctl_file(mode, parsed_sysctl_options, args.sysctl)
370 populate_with_data(config_checklist, parsed_sysctl_options, 'sysctl')
372 # now everything is ready, perform the checks
373 perform_checks(config_checklist)
375 if mode == 'verbose':
376 # print the parsed options without the checks (for debugging)
377 print_unknown_options(config_checklist, parsed_sysctl_options, 'sysctl')
379 # finally print the results
380 print_checklist(mode, config_checklist, True)
384 assert(args.config is None and args.cmdline is None and args.sysctl is None), 'unexpected args'
386 sys.exit('[!] ERROR: --print and --generate can\'t be used together')
387 if mode and mode not in ('verbose', 'json'):
388 sys.exit(f'[!] ERROR: wrong mode "{mode}" for --print')
390 add_kconfig_checks(config_checklist, arch)
391 add_cmdline_checks(config_checklist, arch)
392 add_sysctl_checks(config_checklist, arch)
394 print(f'[+] Printing kernel security hardening options for {arch}...')
395 print_checklist(mode, config_checklist, False)
399 assert(args.config is None and args.cmdline is None and args.sysctl is None and args.print is None), 'unexpected args'
401 sys.exit(f'[!] ERROR: wrong mode "{mode}" for --generate')
403 add_kconfig_checks(config_checklist, arch)
404 print(f'CONFIG_{arch}=y') # the Kconfig fragment should describe the microarchitecture
405 for opt in config_checklist:
406 if opt.name == 'CONFIG_ARCH_MMAP_RND_BITS':
407 continue # don't add CONFIG_ARCH_MMAP_RND_BITS because its value needs refinement
408 if opt.expected == 'is not set':
409 print(f'# {opt.name} is not set')
411 print(f'{opt.name}={opt.expected}')