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 typing import List, Tuple, Dict, TextIO
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 StrOrNone, TupleOrNone, ChecklistObjType, print_unknown_options, populate_with_data, perform_checks, override_expected_value
24 def _open(file: str, *args, **kwargs) -> TextIO:
25 if file.endswith('.gz'):
26 return gzip.open(file, *args, **kwargs)
27 return open(file, *args, **kwargs)
30 def detect_arch(fname: str, archs: List[str]) -> Tuple[StrOrNone, str]:
31 with _open(fname, 'rt', encoding='utf-8') as f:
32 arch_pattern = re.compile(r"CONFIG_[a-zA-Z0-9_]+=y$")
34 for line in f.readlines():
35 if arch_pattern.match(line):
36 option, _ = line[7:].split('=', 1)
41 return None, 'detected more than one microarchitecture'
43 return None, 'failed to detect microarchitecture'
47 def detect_kernel_version(fname: str) -> Tuple[TupleOrNone, str]:
48 with _open(fname, 'rt', encoding='utf-8') as f:
49 ver_pattern = re.compile(r"^# Linux/.+ Kernel Configuration$|^Linux version .+")
50 for line in f.readlines():
51 if ver_pattern.match(line):
54 ver_str = parts[2].split('-', 1)[0]
55 ver_numbers = ver_str.split('.')
56 if len(ver_numbers) >= 3:
57 if all(map(lambda x: x.isdigit(), ver_numbers)):
58 return tuple(map(int, ver_numbers)), 'OK'
59 msg = f'failed to parse the version "{parts[2]}"'
61 return None, 'no kernel version detected'
64 def detect_compiler(fname: str) -> Tuple[StrOrNone, str]:
67 with _open(fname, 'rt', encoding='utf-8') as f:
68 for line in f.readlines():
69 if line.startswith('CONFIG_GCC_VERSION='):
70 gcc_version = line[19:-1]
71 if line.startswith('CONFIG_CLANG_VERSION='):
72 clang_version = line[21:-1]
73 if gcc_version is None or clang_version is None:
74 return None, 'no CONFIG_GCC_VERSION or CONFIG_CLANG_VERSION'
75 if gcc_version == '0' and clang_version != '0':
76 return f'CLANG {clang_version}', 'OK'
77 if gcc_version != '0' and clang_version == '0':
78 return f'GCC {gcc_version}', 'OK'
79 sys.exit(f'[!] ERROR: invalid GCC_VERSION and CLANG_VERSION: {gcc_version} {clang_version}')
82 def print_checklist(mode: StrOrNone, checklist: List[ChecklistObjType], with_results: bool) -> None:
86 output.append(opt.json_dump(with_results))
87 print(json.dumps(output))
94 print('=' * sep_line_len)
95 print(f'{"option_name":^40}|{"type":^7}|{"desired_val":^12}|{"decision":^10}|{"reason":^18}', end='')
97 print('| check_result', end='')
99 print('=' * sep_line_len)
104 for opt in checklist:
106 assert(opt.result), f'unexpected empty result of {opt.name} check'
107 if opt.result.startswith('OK'):
109 if mode == 'show_fail':
111 elif opt.result.startswith('FAIL'):
113 if mode == 'show_ok':
116 assert(False), f'unexpected result "{opt.result}" of {opt.name} check'
117 opt.table_print(mode, with_results)
119 if mode == 'verbose':
120 print('-' * sep_line_len)
127 if mode == 'show_ok':
128 fail_suppressed = ' (suppressed in output)'
129 if mode == 'show_fail':
130 ok_suppressed = ' (suppressed in output)'
131 print(f'[+] Config check is finished: \'OK\' - {ok_count}{ok_suppressed} / \'FAIL\' - {fail_count}{fail_suppressed}')
134 def parse_kconfig_file(_mode: StrOrNone, parsed_options: Dict[str, str], fname: str) -> None:
135 with _open(fname, 'rt', encoding='utf-8') as f:
136 opt_is_on = re.compile(r"CONFIG_[a-zA-Z0-9_]+=.+$")
137 opt_is_off = re.compile(r"# CONFIG_[a-zA-Z0-9_]+ is not set$")
139 for line in f.readlines():
144 if opt_is_on.match(line):
145 option, value = line.split('=', 1)
146 if value == 'is not set':
147 sys.exit(f'[!] ERROR: bad enabled Kconfig option "{line}"')
148 elif opt_is_off.match(line):
149 option, value = line[2:].split(' ', 1)
150 assert(value == 'is not set'), \
151 f'unexpected value of disabled Kconfig option "{line}"'
152 elif line != '' and not line.startswith('#'):
153 sys.exit(f'[!] ERROR: unexpected line in Kconfig file: "{line}"')
155 if option in parsed_options:
156 sys.exit(f'[!] ERROR: Kconfig option "{line}" is found multiple times')
159 assert(value), f'unexpected empty value for {option}'
160 parsed_options[option] = value
163 def parse_cmdline_file(mode: StrOrNone, parsed_options: Dict[str, str], fname: str) -> None:
164 with open(fname, 'r', encoding='utf-8') as f:
170 sys.exit(f'[!] ERROR: more than one line in "{fname}"')
174 name, value = opt.split('=', 1)
177 value = '' # '' is not None
178 if name in parsed_options and mode != 'json':
179 print(f'[!] WARNING: cmdline option "{name}" is found multiple times')
180 value = normalize_cmdline_options(name, value)
181 assert(value is not None), f'unexpected None value for {name}'
182 parsed_options[name] = value
185 def parse_sysctl_file(mode: StrOrNone, parsed_options: Dict[str, str], fname: str) -> None:
186 with open(fname, 'r', encoding='utf-8') as f:
187 sysctl_pattern = re.compile(r"[a-zA-Z0-9/\._-]+ =.*$")
188 for line in f.readlines():
190 if not sysctl_pattern.match(line):
191 sys.exit(f'[!] ERROR: unexpected line in sysctl file: "{line}"')
192 option, value = line.split('=', 1)
193 option = option.strip()
194 value = value.strip()
195 # sysctl options may be found multiple times, let's save the last value:
196 parsed_options[option] = value
198 # let's check the presence of some ancient sysctl option
199 # to ensure that we are parsing the output of `sudo sysctl -a > file`
200 if 'kernel.printk' not in parsed_options:
201 sys.exit(f'[!] ERROR: {fname} doesn\'t look like a sysctl output file, please try `sudo sysctl -a > {fname}`')
203 # let's check the presence of a sysctl option available for root
204 if 'kernel.cad_pid' not in parsed_options and mode != 'json':
205 print(f'[!] WARNING: sysctl option "kernel.cad_pid" available for root is not found in {fname}, please try `sudo sysctl -a > {fname}`')
211 # - reporting about unknown kernel options in the Kconfig
212 # - verbose printing of ComplexOptCheck items
213 # * json mode for printing the results in JSON format
214 report_modes = ['verbose', 'json', 'show_ok', 'show_fail']
215 supported_archs = ['X86_64', 'X86_32', 'ARM64', 'ARM']
216 parser = ArgumentParser(prog='kernel-hardening-checker',
217 description='A tool for checking the security hardening options of the Linux kernel')
218 parser.add_argument('--version', action='version', version=f'%(prog)s {__version__}')
219 parser.add_argument('-m', '--mode', choices=report_modes,
220 help='choose the report mode')
221 parser.add_argument('-c', '--config',
222 help='check the security hardening options in the kernel Kconfig file (also supports *.gz files)')
223 parser.add_argument('-l', '--cmdline',
224 help='check the security hardening options in the kernel cmdline file (contents of /proc/cmdline)')
225 parser.add_argument('-s', '--sysctl',
226 help='check the security hardening options in the sysctl output file (`sudo sysctl -a > file`)')
227 parser.add_argument('-v', '--kernel-version',
228 help='extract the version from the kernel version file (contents of /proc/version)')
229 parser.add_argument('-p', '--print', choices=supported_archs,
230 help='print the security hardening recommendations for the selected microarchitecture')
231 parser.add_argument('-g', '--generate', choices=supported_archs,
232 help='generate a Kconfig fragment with the security hardening options for the selected microarchitecture')
233 args = parser.parse_args()
239 print(f'[+] Special report mode: {mode}')
241 config_checklist = [] # type: List[ChecklistObjType]
245 sys.exit('[!] ERROR: --config and --print can\'t be used together')
247 sys.exit('[!] ERROR: --config and --generate can\'t be used together')
250 print(f'[+] Kconfig file to check: {args.config}')
252 print(f'[+] Kernel cmdline file to check: {args.cmdline}')
254 print(f'[+] Sysctl output file to check: {args.sysctl}')
256 arch, msg = detect_arch(args.config, supported_archs)
258 sys.exit(f'[!] ERROR: {msg}')
260 print(f'[+] Detected microarchitecture: {arch}')
262 if args.kernel_version:
263 kernel_version, msg = detect_kernel_version(args.kernel_version)
265 kernel_version, msg = detect_kernel_version(args.config)
266 if kernel_version is None:
267 if args.kernel_version is None:
268 print('[!] Hint: provide the kernel version file through --kernel-version option')
269 sys.exit(f'[!] ERROR: {msg}')
271 print(f'[+] Detected kernel version: {kernel_version}')
273 compiler, msg = detect_compiler(args.config)
276 print(f'[+] Detected compiler: {compiler}')
278 print(f'[-] Can\'t detect the compiler: {msg}')
280 # add relevant Kconfig checks to the checklist
281 add_kconfig_checks(config_checklist, arch)
284 # add relevant cmdline checks to the checklist
285 add_cmdline_checks(config_checklist, arch)
288 # add relevant sysctl checks to the checklist
289 add_sysctl_checks(config_checklist, arch)
291 # populate the checklist with the parsed Kconfig data
292 parsed_kconfig_options = {} # type: Dict[str, str]
293 parse_kconfig_file(mode, parsed_kconfig_options, args.config)
294 populate_with_data(config_checklist, parsed_kconfig_options, 'kconfig')
296 # populate the checklist with the kernel version data
297 populate_with_data(config_checklist, kernel_version, 'version')
300 # populate the checklist with the parsed cmdline data
301 parsed_cmdline_options = {} # type: Dict[str, str]
302 parse_cmdline_file(mode, parsed_cmdline_options, args.cmdline)
303 populate_with_data(config_checklist, parsed_cmdline_options, 'cmdline')
306 # populate the checklist with the parsed sysctl data
307 parsed_sysctl_options = {} # type: Dict[str, str]
308 parse_sysctl_file(mode, parsed_sysctl_options, args.sysctl)
309 populate_with_data(config_checklist, parsed_sysctl_options, 'sysctl')
311 # hackish refinement of the CONFIG_ARCH_MMAP_RND_BITS check
312 mmap_rnd_bits_max = parsed_kconfig_options.get('CONFIG_ARCH_MMAP_RND_BITS_MAX', None)
313 if mmap_rnd_bits_max:
314 override_expected_value(config_checklist, 'CONFIG_ARCH_MMAP_RND_BITS', mmap_rnd_bits_max)
316 # remove the CONFIG_ARCH_MMAP_RND_BITS check to avoid false results
318 print('[-] Can\'t check CONFIG_ARCH_MMAP_RND_BITS without CONFIG_ARCH_MMAP_RND_BITS_MAX')
319 config_checklist[:] = [o for o in config_checklist if o.name != 'CONFIG_ARCH_MMAP_RND_BITS']
321 # now everything is ready, perform the checks
322 perform_checks(config_checklist)
324 if mode == 'verbose':
325 # print the parsed options without the checks (for debugging)
326 print_unknown_options(config_checklist, parsed_kconfig_options, 'kconfig')
328 print_unknown_options(config_checklist, parsed_cmdline_options, 'cmdline')
330 print_unknown_options(config_checklist, parsed_sysctl_options, 'sysctl')
332 # finally print the results
333 print_checklist(mode, config_checklist, True)
336 sys.exit('[!] ERROR: checking cmdline depends on checking Kconfig')
338 # separate sysctl checking (without kconfig)
339 assert(args.config is None and args.cmdline is None), 'unexpected args'
341 sys.exit('[!] ERROR: --sysctl and --print can\'t be used together')
343 sys.exit('[!] ERROR: --sysctl and --generate can\'t be used together')
346 print(f'[+] Sysctl output file to check: {args.sysctl}')
348 # add relevant sysctl checks to the checklist
349 add_sysctl_checks(config_checklist, None)
351 # populate the checklist with the parsed sysctl data
352 parsed_sysctl_options = {}
353 parse_sysctl_file(mode, parsed_sysctl_options, args.sysctl)
354 populate_with_data(config_checklist, parsed_sysctl_options, 'sysctl')
356 # now everything is ready, perform the checks
357 perform_checks(config_checklist)
359 if mode == 'verbose':
360 # print the parsed options without the checks (for debugging)
361 print_unknown_options(config_checklist, parsed_sysctl_options, 'sysctl')
363 # finally print the results
364 print_checklist(mode, config_checklist, True)
368 assert(args.config is None and args.cmdline is None and args.sysctl is None), 'unexpected args'
370 sys.exit('[!] ERROR: --print and --generate can\'t be used together')
371 if mode and mode not in ('verbose', 'json'):
372 sys.exit(f'[!] ERROR: wrong mode "{mode}" for --print')
374 assert(arch), 'unexpected empty arch from ArgumentParser'
375 add_kconfig_checks(config_checklist, arch)
376 add_cmdline_checks(config_checklist, arch)
377 add_sysctl_checks(config_checklist, arch)
379 print(f'[+] Printing kernel security hardening options for {arch}...')
380 print_checklist(mode, config_checklist, False)
384 assert(args.config is None and
385 args.cmdline is None and
386 args.sysctl is None and
387 args.print is None), \
390 sys.exit(f'[!] ERROR: wrong mode "{mode}" for --generate')
392 assert(arch), 'unexpected empty arch from ArgumentParser'
393 add_kconfig_checks(config_checklist, arch)
394 print(f'CONFIG_{arch}=y') # the Kconfig fragment should describe the microarchitecture
395 for opt in config_checklist:
396 if opt.name == 'CONFIG_ARCH_MMAP_RND_BITS':
397 continue # don't add CONFIG_ARCH_MMAP_RND_BITS because its value needs refinement
398 if opt.expected == 'is not off':
399 continue # don't add Kconfig options without explicitly recommended values
400 if opt.expected == 'is not set':
401 print(f'# {opt.name} is not set')
403 print(f'{opt.name}={opt.expected}')