4 # This tool helps me to check the Linux kernel Kconfig option list
5 # against my 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 # Please don't cry if my Python code looks like C.
13 # N.B Hardening command line parameters:
16 # page_alloc.shuffle=1
17 # iommu=force (does it help against DMA attacks?)
18 # page_poison=1 (if enabled)
22 # debugfs=no-mount (or off if possible)
24 # Mitigations of CPU vulnerabilities:
26 # mitigations=auto,nosmt
30 # spec_store_bypass_disable=on
38 # N.B. Hardening sysctls:
39 # kernel.kptr_restrict=2
40 # kernel.dmesg_restrict=1
41 # kernel.perf_event_paranoid=3
42 # kernel.kexec_load_disabled=1
43 # kernel.yama.ptrace_scope=3
44 # user.max_user_namespaces=0
45 # what about bpf_jit_enable?
46 # kernel.unprivileged_bpf_disabled=1
47 # net.core.bpf_jit_harden=2
49 # vm.unprivileged_userfaultfd=0
51 # dev.tty.ldisc_autoload=0
52 # fs.protected_symlinks=1
53 # fs.protected_hardlinks=1
54 # fs.protected_fifos=2
55 # fs.protected_regular=2
57 # kernel.modules_disabled=1
60 # pylint: disable=missing-module-docstring,missing-class-docstring,missing-function-docstring
61 # pylint: disable=line-too-long,invalid-name,too-many-branches,too-many-statements
65 from argparse import ArgumentParser
66 from collections import OrderedDict
69 from .__about__ import __version__
73 def __init__(self, reason, decision, name, expected):
75 self.expected = expected
76 self.decision = decision
82 if self.expected == self.state:
84 elif self.state is None:
85 if self.expected == 'is not set':
86 self.result = 'OK: not found'
88 self.result = 'FAIL: not found'
90 self.result = 'FAIL: "' + self.state + '"'
92 if self.result.startswith('OK'):
96 def table_print(self, _mode, with_results):
97 print('CONFIG_{:<38}|{:^13}|{:^10}|{:^20}'.format(self.name, self.expected, self.decision, self.reason), end='')
99 print('| {}'.format(self.result), end='')
103 def __init__(self, ver_expected):
104 self.ver_expected = ver_expected
109 if self.ver[0] > self.ver_expected[0]:
110 self.result = 'OK: version >= ' + str(self.ver_expected[0]) + '.' + str(self.ver_expected[1])
112 if self.ver[0] < self.ver_expected[0]:
113 self.result = 'FAIL: version < ' + str(self.ver_expected[0]) + '.' + str(self.ver_expected[1])
115 if self.ver[1] >= self.ver_expected[1]:
116 self.result = 'OK: version >= ' + str(self.ver_expected[0]) + '.' + str(self.ver_expected[1])
118 self.result = 'FAIL: version < ' + str(self.ver_expected[0]) + '.' + str(self.ver_expected[1])
121 def table_print(self, _mode, with_results):
122 ver_req = 'kernel version >= ' + str(self.ver_expected[0]) + '.' + str(self.ver_expected[1])
123 print('{:<91}'.format(ver_req), end='')
125 print('| {}'.format(self.result), end='')
129 def __init__(self, name):
135 if self.state is None:
136 self.result = 'FAIL: not present'
138 self.result = 'OK: is present'
141 def table_print(self, _mode, with_results):
142 print('CONFIG_{:<84}'.format(self.name + ' is present'), end='')
144 print('| {}'.format(self.result), end='')
147 class ComplexOptCheck:
148 def __init__(self, *opts):
151 sys.exit('[!] ERROR: empty {} check'.format(self.__class__.__name__))
152 if not isinstance(opts[0], OptCheck):
153 sys.exit('[!] ERROR: invalid {} check: {}'.format(self.__class__.__name__, opts))
158 return self.opts[0].name
162 return self.opts[0].expected
166 return self.opts[0].decision
170 return self.opts[0].reason
172 def table_print(self, mode, with_results):
173 if mode == 'verbose':
174 print(' {:87}'.format('<<< ' + self.__class__.__name__ + ' >>>'), end='')
176 print('| {}'.format(self.result), end='')
179 o.table_print(mode, with_results)
182 o.table_print(mode, False)
184 print('| {}'.format(self.result), end='')
187 class OR(ComplexOptCheck):
188 # self.opts[0] is the option that this OR-check is about.
190 # OR(<X_is_hardened>, <X_is_disabled>)
191 # OR(<X_is_hardened>, <old_X_is_hardened>)
195 sys.exit('[!] ERROR: invalid OR check')
197 for i, opt in enumerate(self.opts):
200 if opt.result != 'OK' or i == 0:
201 # Preserve additional explanation of this OK result.
202 # Simple OK is enough only for the main option that
203 # this OR-check is about.
204 self.result = opt.result
206 # Simple OK is not enough for additional checks.
207 self.result = 'OK: CONFIG_{} "{}"'.format(opt.name, opt.expected)
209 self.result = self.opts[0].result
213 class AND(ComplexOptCheck):
214 # self.opts[0] is the option that this AND-check is about.
216 # AND(<suboption>, <main_option>)
217 # Suboption is not checked if checking of the main_option is failed.
218 # AND(<X_is_disabled>, <old_X_is_disabled>)
221 for i, opt in reversed(list(enumerate(self.opts))):
224 self.result = opt.result
227 # This FAIL is caused by additional checks,
228 # and not by the main option that this AND-check is about.
229 # Describe the reason of the FAIL.
230 if opt.result.startswith('FAIL: \"') or opt.result == 'FAIL: not found':
231 self.result = 'FAIL: CONFIG_{} not "{}"'.format(opt.name, opt.expected)
232 elif opt.result == 'FAIL: not present':
233 self.result = 'FAIL: CONFIG_{} not present'.format(opt.name)
235 # This FAIL message is self-explaining.
236 self.result = opt.result
239 sys.exit('[!] ERROR: invalid AND check')
242 def detect_arch(fname, archs):
243 with open(fname, 'r') as f:
244 arch_pattern = re.compile("CONFIG_[a-zA-Z0-9_]*=y")
246 for line in f.readlines():
247 if arch_pattern.match(line):
248 option, _ = line[7:].split('=', 1)
253 return None, 'more than one supported architecture is detected'
255 return None, 'failed to detect architecture'
259 def detect_version(fname):
260 with open(fname, 'r') as f:
261 ver_pattern = re.compile("# Linux/.* Kernel Configuration")
262 for line in f.readlines():
263 if ver_pattern.match(line):
267 ver_numbers = ver_str.split('.')
268 if len(ver_numbers) < 3 or not ver_numbers[0].isdigit() or not ver_numbers[1].isdigit():
269 msg = 'failed to parse the version "' + ver_str + '"'
271 return (int(ver_numbers[0]), int(ver_numbers[1])), None
272 return None, 'no kernel version detected'
275 def construct_checklist(l, arch):
276 modules_not_set = OptCheck('cut_attack_surface', 'kspp', 'MODULES', 'is not set')
277 devmem_not_set = OptCheck('cut_attack_surface', 'kspp', 'DEVMEM', 'is not set') # refers to LOCKDOWN
279 # 'self_protection', 'defconfig'
280 l += [OptCheck('self_protection', 'defconfig', 'BUG', 'y')]
281 l += [OptCheck('self_protection', 'defconfig', 'SLUB_DEBUG', 'y')]
282 l += [OptCheck('self_protection', 'defconfig', 'GCC_PLUGINS', 'y')]
283 l += [OR(OptCheck('self_protection', 'defconfig', 'STACKPROTECTOR_STRONG', 'y'),
284 OptCheck('self_protection', 'defconfig', 'CC_STACKPROTECTOR_STRONG', 'y'))]
285 l += [OR(OptCheck('self_protection', 'defconfig', 'STRICT_KERNEL_RWX', 'y'),
286 OptCheck('self_protection', 'defconfig', 'DEBUG_RODATA', 'y'))] # before v4.11
287 l += [OR(OptCheck('self_protection', 'defconfig', 'STRICT_MODULE_RWX', 'y'),
288 OptCheck('self_protection', 'defconfig', 'DEBUG_SET_MODULE_RONX', 'y'),
289 modules_not_set)] # DEBUG_SET_MODULE_RONX was before v4.11
290 l += [OR(OptCheck('self_protection', 'defconfig', 'REFCOUNT_FULL', 'y'),
291 VerCheck((5, 5)))] # REFCOUNT_FULL is enabled by default since v5.5
292 iommu_support_is_set = OptCheck('self_protection', 'defconfig', 'IOMMU_SUPPORT', 'y')
293 l += [iommu_support_is_set] # is needed for mitigating DMA attacks
294 if arch in ('X86_64', 'X86_32'):
295 l += [OptCheck('self_protection', 'defconfig', 'MICROCODE', 'y')] # is needed for mitigating CPU bugs
296 l += [OptCheck('self_protection', 'defconfig', 'RETPOLINE', 'y')]
297 l += [OptCheck('self_protection', 'defconfig', 'X86_SMAP', 'y')]
298 l += [OptCheck('self_protection', 'defconfig', 'SYN_COOKIES', 'y')] # another reason?
299 l += [OR(OptCheck('self_protection', 'defconfig', 'X86_UMIP', 'y'),
300 OptCheck('self_protection', 'defconfig', 'X86_INTEL_UMIP', 'y'))]
302 l += [OptCheck('self_protection', 'defconfig', 'PAGE_TABLE_ISOLATION', 'y')]
303 l += [OptCheck('self_protection', 'defconfig', 'RANDOMIZE_MEMORY', 'y')]
304 l += [AND(OptCheck('self_protection', 'defconfig', 'INTEL_IOMMU', 'y'),
305 iommu_support_is_set)]
306 l += [AND(OptCheck('self_protection', 'defconfig', 'AMD_IOMMU', 'y'),
307 iommu_support_is_set)]
309 l += [OptCheck('self_protection', 'defconfig', 'ARM64_PAN', 'y')]
310 l += [OptCheck('self_protection', 'defconfig', 'UNMAP_KERNEL_AT_EL0', 'y')]
311 l += [OR(OptCheck('self_protection', 'defconfig', 'HARDEN_EL2_VECTORS', 'y'),
312 AND(OptCheck('self_protection', 'defconfig', 'RANDOMIZE_BASE', 'y'),
313 VerCheck((5, 9))))] # HARDEN_EL2_VECTORS was included in RANDOMIZE_BASE in v5.9
314 l += [OptCheck('self_protection', 'defconfig', 'RODATA_FULL_DEFAULT_ENABLED', 'y')]
315 l += [OptCheck('self_protection', 'defconfig', 'ARM64_PTR_AUTH', 'y')]
316 l += [OptCheck('self_protection', 'defconfig', 'ARM64_BTI_KERNEL', 'y')]
317 if arch in ('X86_64', 'ARM64'):
318 l += [OptCheck('self_protection', 'defconfig', 'VMAP_STACK', 'y')]
319 if arch in ('X86_64', 'ARM64', 'X86_32'):
320 l += [OptCheck('self_protection', 'defconfig', 'RANDOMIZE_BASE', 'y')]
321 l += [OptCheck('self_protection', 'defconfig', 'THREAD_INFO_IN_TASK', 'y')]
323 l += [OptCheck('self_protection', 'defconfig', 'CPU_SW_DOMAIN_PAN', 'y')]
324 l += [OptCheck('self_protection', 'defconfig', 'STACKPROTECTOR_PER_TASK', 'y')]
325 if arch in ('ARM64', 'ARM'):
326 l += [OptCheck('self_protection', 'defconfig', 'HARDEN_BRANCH_PREDICTOR', 'y')]
328 # 'self_protection', 'kspp'
329 l += [OptCheck('self_protection', 'kspp', 'BUG_ON_DATA_CORRUPTION', 'y')]
330 l += [OptCheck('self_protection', 'kspp', 'DEBUG_WX', 'y')]
331 l += [OptCheck('self_protection', 'kspp', 'SCHED_STACK_END_CHECK', 'y')]
332 l += [OptCheck('self_protection', 'kspp', 'SLAB_FREELIST_HARDENED', 'y')]
333 l += [OptCheck('self_protection', 'kspp', 'SLAB_FREELIST_RANDOM', 'y')]
334 l += [OptCheck('self_protection', 'kspp', 'SHUFFLE_PAGE_ALLOCATOR', 'y')]
335 l += [OptCheck('self_protection', 'kspp', 'FORTIFY_SOURCE', 'y')]
336 l += [OptCheck('self_protection', 'kspp', 'DEBUG_LIST', 'y')]
337 l += [OptCheck('self_protection', 'kspp', 'DEBUG_SG', 'y')]
338 l += [OptCheck('self_protection', 'kspp', 'DEBUG_CREDENTIALS', 'y')]
339 l += [OptCheck('self_protection', 'kspp', 'DEBUG_NOTIFIERS', 'y')]
340 l += [OptCheck('self_protection', 'kspp', 'INIT_ON_ALLOC_DEFAULT_ON', 'y')]
341 l += [OptCheck('self_protection', 'kspp', 'GCC_PLUGIN_LATENT_ENTROPY', 'y')]
342 randstruct_is_set = OptCheck('self_protection', 'kspp', 'GCC_PLUGIN_RANDSTRUCT', 'y')
343 l += [randstruct_is_set]
344 hardened_usercopy_is_set = OptCheck('self_protection', 'kspp', 'HARDENED_USERCOPY', 'y')
345 l += [hardened_usercopy_is_set]
346 l += [AND(OptCheck('self_protection', 'kspp', 'HARDENED_USERCOPY_FALLBACK', 'is not set'),
347 hardened_usercopy_is_set)]
348 l += [OR(OptCheck('self_protection', 'kspp', 'MODULE_SIG', 'y'),
350 l += [OR(OptCheck('self_protection', 'kspp', 'MODULE_SIG_ALL', 'y'),
352 l += [OR(OptCheck('self_protection', 'kspp', 'MODULE_SIG_SHA512', 'y'),
354 l += [OR(OptCheck('self_protection', 'kspp', 'MODULE_SIG_FORCE', 'y'),
355 modules_not_set)] # refers to LOCKDOWN
356 l += [OR(OptCheck('self_protection', 'kspp', 'INIT_STACK_ALL_ZERO', 'y'),
357 OptCheck('self_protection', 'kspp', 'GCC_PLUGIN_STRUCTLEAK_BYREF_ALL', 'y'))]
358 l += [OR(OptCheck('self_protection', 'kspp', 'INIT_ON_FREE_DEFAULT_ON', 'y'),
359 OptCheck('self_protection', 'kspp', 'PAGE_POISONING_ZERO', 'y'))] # before v5.3
360 if arch in ('X86_64', 'ARM64', 'X86_32'):
361 stackleak_is_set = OptCheck('self_protection', 'kspp', 'GCC_PLUGIN_STACKLEAK', 'y')
362 l += [stackleak_is_set]
363 if arch in ('X86_64', 'X86_32'):
364 l += [OptCheck('self_protection', 'kspp', 'DEFAULT_MMAP_MIN_ADDR', '65536')]
366 l += [OptCheck('self_protection', 'kspp', 'PAGE_TABLE_ISOLATION', 'y')]
367 l += [OptCheck('self_protection', 'kspp', 'HIGHMEM64G', 'y')]
368 l += [OptCheck('self_protection', 'kspp', 'X86_PAE', 'y')]
370 l += [OptCheck('self_protection', 'kspp', 'ARM64_SW_TTBR0_PAN', 'y')]
371 if arch in ('ARM64', 'ARM'):
372 l += [OptCheck('self_protection', 'kspp', 'SYN_COOKIES', 'y')] # another reason?
373 l += [OptCheck('self_protection', 'kspp', 'DEFAULT_MMAP_MIN_ADDR', '32768')]
375 # 'self_protection', 'clipos'
376 l += [OptCheck('self_protection', 'clipos', 'SECURITY_DMESG_RESTRICT', 'y')]
377 l += [OptCheck('self_protection', 'clipos', 'DEBUG_VIRTUAL', 'y')]
378 l += [OptCheck('self_protection', 'clipos', 'STATIC_USERMODEHELPER', 'y')] # needs userspace support
379 l += [OptCheck('self_protection', 'clipos', 'EFI_DISABLE_PCI_DMA', 'y')]
380 l += [OptCheck('self_protection', 'clipos', 'SLAB_MERGE_DEFAULT', 'is not set')] # slab_nomerge
381 l += [OptCheck('self_protection', 'clipos', 'RANDOM_TRUST_BOOTLOADER', 'is not set')]
382 l += [OptCheck('self_protection', 'clipos', 'RANDOM_TRUST_CPU', 'is not set')]
383 l += [AND(OptCheck('self_protection', 'clipos', 'GCC_PLUGIN_RANDSTRUCT_PERFORMANCE', 'is not set'),
385 if arch in ('X86_64', 'ARM64', 'X86_32'):
386 l += [AND(OptCheck('self_protection', 'clipos', 'STACKLEAK_METRICS', 'is not set'),
388 l += [AND(OptCheck('self_protection', 'clipos', 'STACKLEAK_RUNTIME_DISABLE', 'is not set'),
390 if arch in ('X86_64', 'X86_32'):
391 l += [AND(OptCheck('self_protection', 'clipos', 'INTEL_IOMMU_SVM', 'y'),
392 iommu_support_is_set)]
393 l += [AND(OptCheck('self_protection', 'clipos', 'INTEL_IOMMU_DEFAULT_ON', 'y'),
394 iommu_support_is_set)]
396 l += [AND(OptCheck('self_protection', 'clipos', 'INTEL_IOMMU', 'y'),
397 iommu_support_is_set)]
399 # 'self_protection', 'my'
400 l += [AND(OptCheck('self_protection', 'my', 'UBSAN_BOUNDS', 'y'),
401 OptCheck('self_protection', 'my', 'UBSAN_MISC', 'is not set'),
402 OptCheck('self_protection', 'my', 'UBSAN_TRAP', 'y'))]
403 l += [OptCheck('self_protection', 'my', 'SLUB_DEBUG_ON', 'y')] # TODO: is it better to set that via kernel cmd?
404 l += [OptCheck('self_protection', 'my', 'RESET_ATTACK_MITIGATION', 'y')] # needs userspace support (systemd)
406 l += [AND(OptCheck('self_protection', 'my', 'AMD_IOMMU_V2', 'y'),
407 iommu_support_is_set)]
409 l += [OptCheck('self_protection', 'my', 'SHADOW_CALL_STACK', 'y')]
412 if arch in ('X86_64', 'ARM64', 'X86_32'):
413 l += [OptCheck('security_policy', 'defconfig', 'SECURITY', 'y')] # and choose your favourite LSM
415 l += [OptCheck('security_policy', 'kspp', 'SECURITY', 'y')] # and choose your favourite LSM
416 l += [OptCheck('security_policy', 'kspp', 'SECURITY_YAMA', 'y')]
417 l += [OR(OptCheck('security_policy', 'my', 'SECURITY_WRITABLE_HOOKS', 'is not set'),
418 OptCheck('security_policy', 'kspp', 'SECURITY_SELINUX_DISABLE', 'is not set'))]
419 l += [OptCheck('security_policy', 'clipos', 'SECURITY_LOCKDOWN_LSM', 'y')]
420 l += [OptCheck('security_policy', 'clipos', 'SECURITY_LOCKDOWN_LSM_EARLY', 'y')]
421 l += [OptCheck('security_policy', 'clipos', 'LOCK_DOWN_KERNEL_FORCE_CONFIDENTIALITY', 'y')]
422 l += [OptCheck('security_policy', 'my', 'SECURITY_SAFESETID', 'y')]
423 loadpin_is_set = OptCheck('security_policy', 'my', 'SECURITY_LOADPIN', 'y')
424 l += [loadpin_is_set] # needs userspace support
425 l += [AND(OptCheck('security_policy', 'my', 'SECURITY_LOADPIN_ENFORCE', 'y'),
428 # 'cut_attack_surface', 'defconfig'
429 l += [OptCheck('cut_attack_surface', 'defconfig', 'SECCOMP', 'y')]
430 l += [OptCheck('cut_attack_surface', 'defconfig', 'SECCOMP_FILTER', 'y')]
431 if arch in ('X86_64', 'ARM64', 'X86_32'):
432 l += [OR(OptCheck('cut_attack_surface', 'defconfig', 'STRICT_DEVMEM', 'y'),
433 devmem_not_set)] # refers to LOCKDOWN
435 # 'cut_attack_surface', 'kspp'
436 l += [OptCheck('cut_attack_surface', 'kspp', 'ACPI_CUSTOM_METHOD', 'is not set')] # refers to LOCKDOWN
437 l += [OptCheck('cut_attack_surface', 'kspp', 'COMPAT_BRK', 'is not set')]
438 l += [OptCheck('cut_attack_surface', 'kspp', 'DEVKMEM', 'is not set')] # refers to LOCKDOWN
439 l += [OptCheck('cut_attack_surface', 'kspp', 'COMPAT_VDSO', 'is not set')]
440 l += [OptCheck('cut_attack_surface', 'kspp', 'BINFMT_MISC', 'is not set')]
441 l += [OptCheck('cut_attack_surface', 'kspp', 'INET_DIAG', 'is not set')]
442 l += [OptCheck('cut_attack_surface', 'kspp', 'KEXEC', 'is not set')] # refers to LOCKDOWN
443 l += [OptCheck('cut_attack_surface', 'kspp', 'PROC_KCORE', 'is not set')] # refers to LOCKDOWN
444 l += [OptCheck('cut_attack_surface', 'kspp', 'LEGACY_PTYS', 'is not set')]
445 l += [OptCheck('cut_attack_surface', 'kspp', 'HIBERNATION', 'is not set')] # refers to LOCKDOWN
446 l += [OptCheck('cut_attack_surface', 'kspp', 'IA32_EMULATION', 'is not set')]
447 l += [OptCheck('cut_attack_surface', 'kspp', 'X86_X32', 'is not set')]
448 l += [OptCheck('cut_attack_surface', 'kspp', 'MODIFY_LDT_SYSCALL', 'is not set')]
449 l += [OptCheck('cut_attack_surface', 'kspp', 'OABI_COMPAT', 'is not set')]
450 l += [modules_not_set]
451 l += [devmem_not_set]
452 l += [OR(OptCheck('cut_attack_surface', 'kspp', 'IO_STRICT_DEVMEM', 'y'),
453 devmem_not_set)] # refers to LOCKDOWN
455 l += [OR(OptCheck('cut_attack_surface', 'kspp', 'STRICT_DEVMEM', 'y'),
456 devmem_not_set)] # refers to LOCKDOWN
458 l += [OptCheck('cut_attack_surface', 'kspp', 'LEGACY_VSYSCALL_NONE', 'y')] # 'vsyscall=none'
460 # 'cut_attack_surface', 'grsecurity'
461 l += [OptCheck('cut_attack_surface', 'grsecurity', 'ZSMALLOC_STAT', 'is not set')]
462 l += [OptCheck('cut_attack_surface', 'grsecurity', 'PAGE_OWNER', 'is not set')]
463 l += [OptCheck('cut_attack_surface', 'grsecurity', 'DEBUG_KMEMLEAK', 'is not set')]
464 l += [OptCheck('cut_attack_surface', 'grsecurity', 'BINFMT_AOUT', 'is not set')]
465 l += [OptCheck('cut_attack_surface', 'grsecurity', 'KPROBES', 'is not set')] # refers to LOCKDOWN
466 l += [OptCheck('cut_attack_surface', 'grsecurity', 'UPROBES', 'is not set')]
467 l += [OptCheck('cut_attack_surface', 'grsecurity', 'GENERIC_TRACER', 'is not set')] # refers to LOCKDOWN
468 l += [OptCheck('cut_attack_surface', 'grsecurity', 'PROC_VMCORE', 'is not set')]
469 l += [OptCheck('cut_attack_surface', 'grsecurity', 'PROC_PAGE_MONITOR', 'is not set')]
470 l += [OptCheck('cut_attack_surface', 'grsecurity', 'USELIB', 'is not set')]
471 l += [OptCheck('cut_attack_surface', 'grsecurity', 'CHECKPOINT_RESTORE', 'is not set')]
472 l += [OptCheck('cut_attack_surface', 'grsecurity', 'USERFAULTFD', 'is not set')]
473 l += [OptCheck('cut_attack_surface', 'grsecurity', 'HWPOISON_INJECT', 'is not set')]
474 l += [OptCheck('cut_attack_surface', 'grsecurity', 'MEM_SOFT_DIRTY', 'is not set')]
475 l += [OptCheck('cut_attack_surface', 'grsecurity', 'DEVPORT', 'is not set')] # refers to LOCKDOWN
476 l += [OptCheck('cut_attack_surface', 'grsecurity', 'DEBUG_FS', 'is not set')] # refers to LOCKDOWN
477 l += [OptCheck('cut_attack_surface', 'grsecurity', 'NOTIFIER_ERROR_INJECTION', 'is not set')]
478 l += [AND(OptCheck('cut_attack_surface', 'grsecurity', 'X86_PTDUMP', 'is not set'),
479 OptCheck('cut_attack_surface', 'my', 'PTDUMP_DEBUGFS', 'is not set'))]
481 # 'cut_attack_surface', 'maintainer'
482 l += [OptCheck('cut_attack_surface', 'maintainer', 'DRM_LEGACY', 'is not set')]
483 l += [OptCheck('cut_attack_surface', 'maintainer', 'FB', 'is not set')]
484 l += [OptCheck('cut_attack_surface', 'maintainer', 'VT', 'is not set')]
486 # 'cut_attack_surface', 'grapheneos'
487 l += [OptCheck('cut_attack_surface', 'grapheneos', 'AIO', 'is not set')]
489 # 'cut_attack_surface', 'clipos'
490 l += [OptCheck('cut_attack_surface', 'clipos', 'STAGING', 'is not set')]
491 l += [OptCheck('cut_attack_surface', 'clipos', 'KSM', 'is not set')] # to prevent FLUSH+RELOAD attack
492 # l += [OptCheck('cut_attack_surface', 'clipos', 'IKCONFIG', 'is not set')] # no, IKCONFIG is needed for this check :)
493 l += [OptCheck('cut_attack_surface', 'clipos', 'KALLSYMS', 'is not set')]
494 l += [OptCheck('cut_attack_surface', 'clipos', 'X86_VSYSCALL_EMULATION', 'is not set')]
495 l += [OptCheck('cut_attack_surface', 'clipos', 'MAGIC_SYSRQ', 'is not set')]
496 l += [OptCheck('cut_attack_surface', 'clipos', 'KEXEC_FILE', 'is not set')] # refers to LOCKDOWN (permissive)
497 l += [OptCheck('cut_attack_surface', 'clipos', 'USER_NS', 'is not set')] # user.max_user_namespaces=0
498 l += [OptCheck('cut_attack_surface', 'clipos', 'X86_MSR', 'is not set')] # refers to LOCKDOWN
499 l += [OptCheck('cut_attack_surface', 'clipos', 'X86_CPUID', 'is not set')]
500 l += [OptCheck('cut_attack_surface', 'clipos', 'IO_URING', 'is not set')]
501 l += [OptCheck('cut_attack_surface', 'clipos', 'X86_IOPL_IOPERM', 'is not set')] # refers to LOCKDOWN
502 l += [OptCheck('cut_attack_surface', 'clipos', 'ACPI_TABLE_UPGRADE', 'is not set')] # refers to LOCKDOWN
503 l += [OptCheck('cut_attack_surface', 'clipos', 'EFI_CUSTOM_SSDT_OVERLAYS', 'is not set')]
504 l += [AND(OptCheck('cut_attack_surface', 'clipos', 'LDISC_AUTOLOAD', 'is not set'),
505 PresenceCheck('LDISC_AUTOLOAD'))]
506 if arch in ('X86_64', 'X86_32'):
507 l += [OptCheck('cut_attack_surface', 'clipos', 'X86_INTEL_TSX_MODE_OFF', 'y')] # tsx=off
509 # 'cut_attack_surface', 'lockdown'
510 l += [OptCheck('cut_attack_surface', 'lockdown', 'EFI_TEST', 'is not set')] # refers to LOCKDOWN
511 l += [OptCheck('cut_attack_surface', 'lockdown', 'BPF_SYSCALL', 'is not set')] # refers to LOCKDOWN
512 l += [OptCheck('cut_attack_surface', 'lockdown', 'MMIOTRACE_TEST', 'is not set')] # refers to LOCKDOWN
514 # 'cut_attack_surface', 'my'
515 l += [OptCheck('cut_attack_surface', 'my', 'TRIM_UNUSED_KSYMS', 'y')]
516 l += [OptCheck('cut_attack_surface', 'my', 'MMIOTRACE', 'is not set')] # refers to LOCKDOWN (permissive)
517 l += [OptCheck('cut_attack_surface', 'my', 'LIVEPATCH', 'is not set')]
518 l += [OptCheck('cut_attack_surface', 'my', 'IP_DCCP', 'is not set')]
519 l += [OptCheck('cut_attack_surface', 'my', 'IP_SCTP', 'is not set')]
520 l += [OptCheck('cut_attack_surface', 'my', 'FTRACE', 'is not set')] # refers to LOCKDOWN
521 l += [OptCheck('cut_attack_surface', 'my', 'VIDEO_VIVID', 'is not set')]
522 l += [OptCheck('cut_attack_surface', 'my', 'INPUT_EVBUG', 'is not set')] # Can be used as a keylogger
524 # 'userspace_hardening'
525 if arch in ('X86_64', 'ARM64', 'X86_32'):
526 l += [OptCheck('userspace_hardening', 'defconfig', 'INTEGRITY', 'y')]
528 l += [OptCheck('userspace_hardening', 'my', 'INTEGRITY', 'y')]
529 if arch in ('ARM', 'X86_32'):
530 l += [OptCheck('userspace_hardening', 'defconfig', 'VMSPLIT_3G', 'y')]
531 if arch in ('X86_64', 'ARM64'):
532 l += [OptCheck('userspace_hardening', 'clipos', 'ARCH_MMAP_RND_BITS', '32')]
533 if arch in ('X86_32', 'ARM'):
534 l += [OptCheck('userspace_hardening', 'my', 'ARCH_MMAP_RND_BITS', '16')]
536 # l += [OptCheck('feature_test', 'my', 'LKDTM', 'm')] # only for debugging!
539 def print_unknown_options(checklist, parsed_options):
541 for opt in checklist:
542 if hasattr(opt, 'opts'):
544 if hasattr(o, 'name'):
545 known_options.append(o.name)
547 known_options.append(opt.name)
548 for option, value in parsed_options.items():
549 if option not in known_options:
550 print('[?] No rule for option {} ({})'.format(option, value))
553 def print_checklist(mode, checklist, with_results):
557 opt = ['CONFIG_'+o.name, o.expected, o.decision, o.reason]
561 print(json.dumps(opts))
568 print('=' * sep_line_len)
569 print('{:^45}|{:^13}|{:^10}|{:^20}'.format('option name', 'desired val', 'decision', 'reason'), end='')
571 print('| {}'.format('check result'), end='')
573 print('=' * sep_line_len)
576 for opt in checklist:
578 if mode == 'show_ok':
579 if not opt.result.startswith('OK'):
581 if mode == 'show_fail':
582 if not opt.result.startswith('FAIL'):
584 opt.table_print(mode, with_results)
586 if mode == 'verbose':
587 print('-' * sep_line_len)
592 fail_count = len(list(filter(lambda opt: opt.result.startswith('FAIL'), checklist)))
594 ok_count = len(list(filter(lambda opt: opt.result.startswith('OK'), checklist)))
596 if mode == 'show_ok':
597 fail_suppressed = ' (suppressed in output)'
598 if mode == 'show_fail':
599 ok_suppressed = ' (suppressed in output)'
601 print('[+] Config check is finished: \'OK\' - {}{} / \'FAIL\' - {}{}'.format(ok_count, ok_suppressed, fail_count, fail_suppressed))
604 def perform_check(opt, parsed_options, kernel_version):
605 if hasattr(opt, 'opts'):
606 # prepare ComplexOptCheck
608 if hasattr(o, 'opts'):
609 # Recursion for nested ComplexOptChecks
610 perform_check(o, parsed_options, kernel_version)
611 if hasattr(o, 'state'):
612 o.state = parsed_options.get(o.name, None)
613 if hasattr(o, 'ver'):
614 o.ver = kernel_version
616 # prepare simple check, opt.state is mandatory
617 if not hasattr(opt, 'state'):
618 sys.exit('[!] ERROR: bad simple check {}'.format(vars(opt)))
619 opt.state = parsed_options.get(opt.name, None)
623 def perform_checks(checklist, parsed_options, kernel_version):
624 for opt in checklist:
625 perform_check(opt, parsed_options, kernel_version)
628 def parse_config_file(parsed_options, fname):
629 with open(fname, 'r') as f:
630 opt_is_on = re.compile("CONFIG_[a-zA-Z0-9_]*=[a-zA-Z0-9_\"]*")
631 opt_is_off = re.compile("# CONFIG_[a-zA-Z0-9_]* is not set")
633 for line in f.readlines():
638 if opt_is_on.match(line):
639 option, value = line[7:].split('=', 1)
640 elif opt_is_off.match(line):
641 option, value = line[9:].split(' ', 1)
642 if value != 'is not set':
643 sys.exit('[!] ERROR: bad disabled config option "{}"'.format(line))
645 if option in parsed_options:
646 sys.exit('[!] ERROR: config option "{}" exists multiple times'.format(line))
649 parsed_options[option] = value
651 return parsed_options
657 # - reporting about unknown kernel options in the config
658 # - verbose printing of ComplexOptCheck items
659 # * json mode for printing the results in JSON format
660 report_modes = ['verbose', 'json', 'show_ok', 'show_fail']
661 supported_archs = ['X86_64', 'X86_32', 'ARM64', 'ARM']
662 parser = ArgumentParser(prog='kconfig-hardened-check',
663 description='Checks the hardening options in the Linux kernel config')
664 parser.add_argument('--version', action='version', version='%(prog)s ' + __version__)
665 parser.add_argument('-p', '--print', choices=supported_archs,
666 help='print hardening preferences for selected architecture')
667 parser.add_argument('-c', '--config',
668 help='check the kernel config file against these preferences')
669 parser.add_argument('-m', '--mode', choices=report_modes,
670 help='choose the report mode')
671 args = parser.parse_args()
677 print("[+] Special report mode: {}".format(mode))
679 config_checklist = []
683 print('[+] Config file to check: {}'.format(args.config))
685 arch, msg = detect_arch(args.config, supported_archs)
687 sys.exit('[!] ERROR: {}'.format(msg))
689 print('[+] Detected architecture: {}'.format(arch))
691 kernel_version, msg = detect_version(args.config)
692 if not kernel_version:
693 sys.exit('[!] ERROR: {}'.format(msg))
695 print('[+] Detected kernel version: {}.{}'.format(kernel_version[0], kernel_version[1]))
697 construct_checklist(config_checklist, arch)
698 parsed_options = OrderedDict()
699 parse_config_file(parsed_options, args.config)
700 perform_checks(config_checklist, parsed_options, kernel_version)
702 if mode == 'verbose':
703 print_unknown_options(config_checklist, parsed_options)
704 print_checklist(mode, config_checklist, True)
709 if mode in ('show_ok', 'show_fail'):
710 sys.exit('[!] ERROR: please use "{}" mode for checking the kernel config'.format(mode))
712 construct_checklist(config_checklist, arch)
714 print('[+] Printing kernel hardening preferences for {}...'.format(arch))
715 print_checklist(mode, config_checklist, False)
721 if __name__ == '__main__':