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
30 return open_method(file, *args, **kwargs)
31 except FileNotFoundError:
32 sys.exit(f'[!] ERROR: unable to open {file}, are you sure it exists?')
36 def detect_arch(fname, archs):
37 with _open(fname, 'rt', encoding='utf-8') as f:
38 arch_pattern = re.compile(r"CONFIG_[a-zA-Z0-9_]+=y$")
40 for line in f.readlines():
41 if arch_pattern.match(line):
42 option, _ = line[7:].split('=', 1)
47 return None, 'detected more than one microarchitecture'
49 return None, 'failed to detect microarchitecture'
53 def detect_kernel_version(fname):
54 with _open(fname, 'rt', encoding='utf-8') as f:
55 ver_pattern = re.compile(r"^# Linux/.+ Kernel Configuration$|^Linux version .+")
56 for line in f.readlines():
57 if ver_pattern.match(line):
60 ver_str = parts[2].split('-', 1)[0]
61 ver_numbers = ver_str.split('.')
62 if len(ver_numbers) >= 3:
63 if all(map(lambda x: x.isdigit(), ver_numbers)):
64 return tuple(map(int, ver_numbers)), None
65 msg = f'failed to parse the version "{parts[2]}"'
67 return None, 'no kernel version detected'
70 def detect_compiler(fname):
73 with _open(fname, 'rt', encoding='utf-8') as f:
74 for line in f.readlines():
75 if line.startswith('CONFIG_GCC_VERSION='):
76 gcc_version = line[19:-1]
77 if line.startswith('CONFIG_CLANG_VERSION='):
78 clang_version = line[21:-1]
79 if gcc_version is None or clang_version is None:
80 return None, 'no CONFIG_GCC_VERSION or CONFIG_CLANG_VERSION'
81 if gcc_version == '0' and clang_version != '0':
82 return f'CLANG {clang_version}', 'OK'
83 if gcc_version != '0' and clang_version == '0':
84 return f'GCC {gcc_version}', 'OK'
85 sys.exit(f'[!] ERROR: invalid GCC_VERSION and CLANG_VERSION: {gcc_version} {clang_version}')
88 def print_unknown_options(checklist, parsed_options, opt_type):
92 if o1.opt_type != 'complex':
93 known_options.append(o1.name)
96 if o2.opt_type != 'complex':
97 if hasattr(o2, 'name'):
98 known_options.append(o2.name)
101 assert(o3.opt_type != 'complex'), \
102 f'unexpected ComplexOptCheck inside {o2.name}'
103 if hasattr(o3, 'name'):
104 known_options.append(o3.name)
106 for option, value in parsed_options.items():
107 if option not in known_options:
108 print(f'[?] No check for {opt_type} option {option} ({value})')
111 def print_checklist(mode, checklist, with_results):
114 for opt in checklist:
115 output.append(opt.json_dump(with_results))
116 print(json.dumps(output))
123 print('=' * sep_line_len)
124 print(f'{"option_name":^40}|{"type":^7}|{"desired_val":^12}|{"decision":^10}|{"reason":^18}', end='')
126 print('| check_result', end='')
128 print('=' * sep_line_len)
131 for opt in checklist:
133 if mode == 'show_ok':
134 if not opt.result.startswith('OK'):
136 if mode == 'show_fail':
137 if not opt.result.startswith('FAIL'):
139 opt.table_print(mode, with_results)
141 if mode == 'verbose':
142 print('-' * sep_line_len)
147 fail_count = len(list(filter(lambda opt: opt.result.startswith('FAIL'), checklist)))
149 ok_count = len(list(filter(lambda opt: opt.result.startswith('OK'), checklist)))
151 if mode == 'show_ok':
152 fail_suppressed = ' (suppressed in output)'
153 if mode == 'show_fail':
154 ok_suppressed = ' (suppressed in output)'
155 print(f'[+] Config check is finished: \'OK\' - {ok_count}{ok_suppressed} / \'FAIL\' - {fail_count}{fail_suppressed}')
158 def parse_kconfig_file(_mode, parsed_options, fname):
159 with _open(fname, 'rt', encoding='utf-8') as f:
160 opt_is_on = re.compile(r"CONFIG_[a-zA-Z0-9_]+=.+$")
161 opt_is_off = re.compile(r"# CONFIG_[a-zA-Z0-9_]+ is not set$")
163 for line in f.readlines():
168 if opt_is_on.match(line):
169 option, value = line.split('=', 1)
170 if value == 'is not set':
171 sys.exit(f'[!] ERROR: bad enabled Kconfig option "{line}"')
172 elif opt_is_off.match(line):
173 option, value = line[2:].split(' ', 1)
174 assert(value == 'is not set'), \
175 f'unexpected value of disabled Kconfig option "{line}"'
176 elif line != '' and not line.startswith('#'):
177 sys.exit(f'[!] ERROR: unexpected line in Kconfig file: "{line}"')
179 if option in parsed_options:
180 sys.exit(f'[!] ERROR: Kconfig option "{line}" is found multiple times')
183 parsed_options[option] = value
186 def parse_cmdline_file(mode, parsed_options, fname):
187 with open(fname, 'r', encoding='utf-8') as f:
193 sys.exit(f'[!] ERROR: more than one line in "{fname}"')
197 name, value = opt.split('=', 1)
200 value = '' # '' is not None
201 if name in parsed_options and mode != 'json':
202 print(f'[!] WARNING: cmdline option "{name}" is found multiple times')
203 value = normalize_cmdline_options(name, value)
204 parsed_options[name] = value
207 def parse_sysctl_file(mode, parsed_options, fname):
208 with open(fname, 'r', encoding='utf-8') as f:
209 sysctl_pattern = re.compile(r"[a-zA-Z0-9/\._-]+ =.*$")
210 for line in f.readlines():
212 if not sysctl_pattern.match(line):
213 sys.exit(f'[!] ERROR: unexpected line in sysctl file: "{line}"')
214 option, value = line.split('=', 1)
215 option = option.strip()
216 value = value.strip()
217 # sysctl options may be found multiple times, let's save the last value:
218 parsed_options[option] = value
220 # let's check the presence of some ancient sysctl option
221 # to ensure that we are parsing the output of `sudo sysctl -a > file`
222 if 'kernel.printk' not in parsed_options:
223 sys.exit(f'[!] ERROR: {fname} doesn\'t look like a sysctl output file, please try `sudo sysctl -a > {fname}`')
225 # let's check the presence of a sysctl option available for root
226 if 'kernel.cad_pid' not in parsed_options and mode != 'json':
227 print(f'[!] WARNING: sysctl option "kernel.cad_pid" available for root is not found in {fname}, please try `sudo sysctl -a > {fname}`')
233 # - reporting about unknown kernel options in the Kconfig
234 # - verbose printing of ComplexOptCheck items
235 # * json mode for printing the results in JSON format
236 report_modes = ['verbose', 'json', 'show_ok', 'show_fail']
237 supported_archs = ['X86_64', 'X86_32', 'ARM64', 'ARM']
238 parser = ArgumentParser(prog='kernel-hardening-checker',
239 description='A tool for checking the security hardening options of the Linux kernel')
240 parser.add_argument('--version', action='version', version=f'%(prog)s {__version__}')
241 parser.add_argument('-m', '--mode', choices=report_modes,
242 help='choose the report mode')
243 parser.add_argument('-c', '--config',
244 help='check the security hardening options in the kernel Kconfig file (also supports *.gz files)')
245 parser.add_argument('-l', '--cmdline',
246 help='check the security hardening options in the kernel cmdline file (contents of /proc/cmdline)')
247 parser.add_argument('-s', '--sysctl',
248 help='check the security hardening options in the sysctl output file (`sudo sysctl -a > file`)')
249 parser.add_argument('-v', '--kernel-version',
250 help='extract the version from the kernel version file (contents of /proc/version)')
251 parser.add_argument('-p', '--print', choices=supported_archs,
252 help='print the security hardening recommendations for the selected microarchitecture')
253 parser.add_argument('-g', '--generate', choices=supported_archs,
254 help='generate a Kconfig fragment with the security hardening options for the selected microarchitecture')
255 args = parser.parse_args()
261 print(f'[+] Special report mode: {mode}')
263 config_checklist = []
267 sys.exit('[!] ERROR: --config and --print can\'t be used together')
269 sys.exit('[!] ERROR: --config and --generate can\'t be used together')
272 print(f'[+] Kconfig file to check: {args.config}')
274 print(f'[+] Kernel cmdline file to check: {args.cmdline}')
276 print(f'[+] Sysctl output file to check: {args.sysctl}')
278 arch, msg = detect_arch(args.config, supported_archs)
280 sys.exit(f'[!] ERROR: {msg}')
282 print(f'[+] Detected microarchitecture: {arch}')
284 if args.kernel_version:
285 kernel_version, msg = detect_kernel_version(args.kernel_version)
287 kernel_version, msg = detect_kernel_version(args.config)
288 if kernel_version is None:
289 if args.kernel_version is None:
290 print('[!] Hint: provide the kernel version file through --kernel-version option')
291 sys.exit(f'[!] ERROR: {msg}')
293 print(f'[+] Detected kernel version: {kernel_version}')
295 compiler, msg = detect_compiler(args.config)
298 print(f'[+] Detected compiler: {compiler}')
300 print(f'[-] Can\'t detect the compiler: {msg}')
302 # add relevant Kconfig checks to the checklist
303 add_kconfig_checks(config_checklist, arch)
306 # add relevant cmdline checks to the checklist
307 add_cmdline_checks(config_checklist, arch)
310 # add relevant sysctl checks to the checklist
311 add_sysctl_checks(config_checklist, arch)
313 # populate the checklist with the parsed Kconfig data
314 parsed_kconfig_options = OrderedDict()
315 parse_kconfig_file(mode, parsed_kconfig_options, args.config)
316 populate_with_data(config_checklist, parsed_kconfig_options, 'kconfig')
318 # populate the checklist with the kernel version data
319 populate_with_data(config_checklist, kernel_version, 'version')
322 # populate the checklist with the parsed cmdline data
323 parsed_cmdline_options = OrderedDict()
324 parse_cmdline_file(mode, parsed_cmdline_options, args.cmdline)
325 populate_with_data(config_checklist, parsed_cmdline_options, 'cmdline')
328 # populate the checklist with the parsed sysctl data
329 parsed_sysctl_options = OrderedDict()
330 parse_sysctl_file(mode, parsed_sysctl_options, args.sysctl)
331 populate_with_data(config_checklist, parsed_sysctl_options, 'sysctl')
333 # hackish refinement of the CONFIG_ARCH_MMAP_RND_BITS check
334 mmap_rnd_bits_max = parsed_kconfig_options.get('CONFIG_ARCH_MMAP_RND_BITS_MAX', None)
335 if mmap_rnd_bits_max:
336 override_expected_value(config_checklist, 'CONFIG_ARCH_MMAP_RND_BITS', mmap_rnd_bits_max)
338 # remove the CONFIG_ARCH_MMAP_RND_BITS check to avoid false results
340 print('[-] Can\'t check CONFIG_ARCH_MMAP_RND_BITS without CONFIG_ARCH_MMAP_RND_BITS_MAX')
341 config_checklist[:] = [o for o in config_checklist if o.name != 'CONFIG_ARCH_MMAP_RND_BITS']
343 # now everything is ready, perform the checks
344 perform_checks(config_checklist)
346 if mode == 'verbose':
347 # print the parsed options without the checks (for debugging)
348 print_unknown_options(config_checklist, parsed_kconfig_options, 'kconfig')
350 print_unknown_options(config_checklist, parsed_cmdline_options, 'cmdline')
352 print_unknown_options(config_checklist, parsed_sysctl_options, 'sysctl')
354 # finally print the results
355 print_checklist(mode, config_checklist, True)
358 sys.exit('[!] ERROR: checking cmdline depends on checking Kconfig')
360 # separate sysctl checking (without kconfig)
361 assert(args.config is None and args.cmdline is None), 'unexpected args'
363 sys.exit('[!] ERROR: --sysctl and --print can\'t be used together')
365 sys.exit('[!] ERROR: --sysctl and --generate can\'t be used together')
368 print(f'[+] Sysctl output file to check: {args.sysctl}')
370 # add relevant sysctl checks to the checklist
371 add_sysctl_checks(config_checklist, None)
373 # populate the checklist with the parsed sysctl data
374 parsed_sysctl_options = OrderedDict()
375 parse_sysctl_file(mode, parsed_sysctl_options, args.sysctl)
376 populate_with_data(config_checklist, parsed_sysctl_options, 'sysctl')
378 # now everything is ready, perform the checks
379 perform_checks(config_checklist)
381 if mode == 'verbose':
382 # print the parsed options without the checks (for debugging)
383 print_unknown_options(config_checklist, parsed_sysctl_options, 'sysctl')
385 # finally print the results
386 print_checklist(mode, config_checklist, True)
390 assert(args.config is None and args.cmdline is None and args.sysctl is None), 'unexpected args'
392 sys.exit('[!] ERROR: --print and --generate can\'t be used together')
393 if mode and mode not in ('verbose', 'json'):
394 sys.exit(f'[!] ERROR: wrong mode "{mode}" for --print')
396 add_kconfig_checks(config_checklist, arch)
397 add_cmdline_checks(config_checklist, arch)
398 add_sysctl_checks(config_checklist, arch)
400 print(f'[+] Printing kernel security hardening options for {arch}...')
401 print_checklist(mode, config_checklist, False)
405 assert(args.config is None and args.cmdline is None and args.sysctl is None and args.print is None), 'unexpected args'
407 sys.exit(f'[!] ERROR: wrong mode "{mode}" for --generate')
409 add_kconfig_checks(config_checklist, arch)
410 print(f'CONFIG_{arch}=y') # the Kconfig fragment should describe the microarchitecture
411 for opt in config_checklist:
412 if opt.name == 'CONFIG_ARCH_MMAP_RND_BITS':
413 continue # don't add CONFIG_ARCH_MMAP_RND_BITS because its value needs refinement
414 if opt.expected == 'is not off':
415 continue # don't add Kconfig options without explicitly recommended values
416 if opt.expected == 'is not set':
417 print(f'# {opt.name} is not set')
419 print(f'{opt.name}={opt.expected}')