4 # This tool helps me to check the Linux kernel Kconfig option list
5 # against my security 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:
15 # page_alloc.shuffle=1
16 # iommu=force (does it help against DMA attacks?)
17 # slub_debug=FZ (slow)
18 # init_on_alloc=1 (since v5.3)
19 # init_on_free=1 (since v5.3, otherwise slub_debug=P and page_poison=1)
21 # debugfs=no-mount (or off if possible)
23 # Mitigations of CPU vulnerabilities:
25 # mitigations=auto,nosmt (nosmt is slow)
29 # spec_store_bypass_disable=on
42 # Hardware tag-based KASAN with arm64 Memory Tagging Extension (MTE):
44 # kasan.stacktrace=off
47 # N.B. Hardening sysctls:
48 # kernel.kptr_restrict=2 (or 1?)
49 # kernel.dmesg_restrict=1 (also see the kconfig option)
50 # kernel.perf_event_paranoid=3
51 # kernel.kexec_load_disabled=1
52 # kernel.yama.ptrace_scope=3
53 # user.max_user_namespaces=0
54 # what about bpf_jit_enable?
55 # kernel.unprivileged_bpf_disabled=1
56 # net.core.bpf_jit_harden=2
58 # vm.unprivileged_userfaultfd=0
59 # (at first, it disabled unprivileged userfaultfd,
60 # and since v5.11 it enables unprivileged userfaultfd for user-mode only)
62 # dev.tty.ldisc_autoload=0
63 # fs.protected_symlinks=1
64 # fs.protected_hardlinks=1
65 # fs.protected_fifos=2
66 # fs.protected_regular=2
68 # kernel.modules_disabled=1
71 # pylint: disable=missing-module-docstring,missing-class-docstring,missing-function-docstring
72 # pylint: disable=line-too-long,invalid-name,too-many-branches,too-many-statements
76 from argparse import ArgumentParser
77 from collections import OrderedDict
80 from .__about__ import __version__
84 def __init__(self, reason, decision, name, expected):
86 self.expected = expected
87 self.decision = decision
93 if self.expected == self.state:
95 elif self.state is None:
96 if self.expected == 'is not set':
97 self.result = 'OK: not found'
99 self.result = 'FAIL: not found'
101 self.result = 'FAIL: "' + self.state + '"'
103 if self.result.startswith('OK'):
107 def table_print(self, _mode, with_results):
108 print('CONFIG_{:<38}|{:^13}|{:^10}|{:^20}'.format(self.name, self.expected, self.decision, self.reason), end='')
110 print('| {}'.format(self.result), end='')
114 def __init__(self, ver_expected):
115 self.ver_expected = ver_expected
120 if self.ver[0] > self.ver_expected[0]:
121 self.result = 'OK: version >= ' + str(self.ver_expected[0]) + '.' + str(self.ver_expected[1])
123 if self.ver[0] < self.ver_expected[0]:
124 self.result = 'FAIL: version < ' + str(self.ver_expected[0]) + '.' + str(self.ver_expected[1])
126 if self.ver[1] >= self.ver_expected[1]:
127 self.result = 'OK: version >= ' + str(self.ver_expected[0]) + '.' + str(self.ver_expected[1])
129 self.result = 'FAIL: version < ' + str(self.ver_expected[0]) + '.' + str(self.ver_expected[1])
132 def table_print(self, _mode, with_results):
133 ver_req = 'kernel version >= ' + str(self.ver_expected[0]) + '.' + str(self.ver_expected[1])
134 print('{:<91}'.format(ver_req), end='')
136 print('| {}'.format(self.result), end='')
140 def __init__(self, name):
146 if self.state is None:
147 self.result = 'FAIL: not present'
149 self.result = 'OK: is present'
152 def table_print(self, _mode, with_results):
153 print('CONFIG_{:<84}'.format(self.name + ' is present'), end='')
155 print('| {}'.format(self.result), end='')
158 class ComplexOptCheck:
159 def __init__(self, *opts):
162 sys.exit('[!] ERROR: empty {} check'.format(self.__class__.__name__))
163 if not isinstance(opts[0], OptCheck):
164 sys.exit('[!] ERROR: invalid {} check: {}'.format(self.__class__.__name__, opts))
169 return self.opts[0].name
173 return self.opts[0].expected
177 return self.opts[0].decision
181 return self.opts[0].reason
183 def table_print(self, mode, with_results):
184 if mode == 'verbose':
185 print(' {:87}'.format('<<< ' + self.__class__.__name__ + ' >>>'), end='')
187 print('| {}'.format(self.result), end='')
190 o.table_print(mode, with_results)
193 o.table_print(mode, False)
195 print('| {}'.format(self.result), end='')
198 class OR(ComplexOptCheck):
199 # self.opts[0] is the option that this OR-check is about.
201 # OR(<X_is_hardened>, <X_is_disabled>)
202 # OR(<X_is_hardened>, <old_X_is_hardened>)
206 sys.exit('[!] ERROR: invalid OR check')
208 for i, opt in enumerate(self.opts):
211 if opt.result != 'OK' or i == 0:
212 # Preserve additional explanation of this OK result.
213 # Simple OK is enough only for the main option that
214 # this OR-check is about.
215 self.result = opt.result
217 # Simple OK is not enough for additional checks.
218 self.result = 'OK: CONFIG_{} "{}"'.format(opt.name, opt.expected)
220 self.result = self.opts[0].result
224 class AND(ComplexOptCheck):
225 # self.opts[0] is the option that this AND-check is about.
227 # AND(<suboption>, <main_option>)
228 # Suboption is not checked if checking of the main_option is failed.
229 # AND(<X_is_disabled>, <old_X_is_disabled>)
232 for i, opt in reversed(list(enumerate(self.opts))):
235 self.result = opt.result
238 # This FAIL is caused by additional checks,
239 # and not by the main option that this AND-check is about.
240 # Describe the reason of the FAIL.
241 if opt.result.startswith('FAIL: \"') or opt.result == 'FAIL: not found':
242 self.result = 'FAIL: CONFIG_{} not "{}"'.format(opt.name, opt.expected)
243 elif opt.result == 'FAIL: not present':
244 self.result = 'FAIL: CONFIG_{} not present'.format(opt.name)
246 # This FAIL message is self-explaining.
247 self.result = opt.result
250 sys.exit('[!] ERROR: invalid AND check')
253 def detect_arch(fname, archs):
254 with open(fname, 'r') as f:
255 arch_pattern = re.compile("CONFIG_[a-zA-Z0-9_]*=y")
257 for line in f.readlines():
258 if arch_pattern.match(line):
259 option, _ = line[7:].split('=', 1)
264 return None, 'more than one supported architecture is detected'
266 return None, 'failed to detect architecture'
270 def detect_version(fname):
271 with open(fname, 'r') as f:
272 ver_pattern = re.compile("# Linux/.* Kernel Configuration")
273 for line in f.readlines():
274 if ver_pattern.match(line):
278 ver_numbers = ver_str.split('.')
279 if len(ver_numbers) < 3 or not ver_numbers[0].isdigit() or not ver_numbers[1].isdigit():
280 msg = 'failed to parse the version "' + ver_str + '"'
282 return (int(ver_numbers[0]), int(ver_numbers[1])), None
283 return None, 'no kernel version detected'
286 def construct_checklist(l, arch):
287 modules_not_set = OptCheck('cut_attack_surface', 'kspp', 'MODULES', 'is not set')
288 devmem_not_set = OptCheck('cut_attack_surface', 'kspp', 'DEVMEM', 'is not set') # refers to LOCKDOWN
290 # 'self_protection', 'defconfig'
291 l += [OptCheck('self_protection', 'defconfig', 'BUG', 'y')]
292 l += [OptCheck('self_protection', 'defconfig', 'SLUB_DEBUG', 'y')]
293 l += [OptCheck('self_protection', 'defconfig', 'GCC_PLUGINS', 'y')]
294 l += [OR(OptCheck('self_protection', 'defconfig', 'STACKPROTECTOR_STRONG', 'y'),
295 OptCheck('self_protection', 'defconfig', 'CC_STACKPROTECTOR_STRONG', 'y'))]
296 l += [OR(OptCheck('self_protection', 'defconfig', 'STRICT_KERNEL_RWX', 'y'),
297 OptCheck('self_protection', 'defconfig', 'DEBUG_RODATA', 'y'))] # before v4.11
298 l += [OR(OptCheck('self_protection', 'defconfig', 'STRICT_MODULE_RWX', 'y'),
299 OptCheck('self_protection', 'defconfig', 'DEBUG_SET_MODULE_RONX', 'y'),
300 modules_not_set)] # DEBUG_SET_MODULE_RONX was before v4.11
301 l += [OR(OptCheck('self_protection', 'defconfig', 'REFCOUNT_FULL', 'y'),
302 VerCheck((5, 5)))] # REFCOUNT_FULL is enabled by default since v5.5
303 iommu_support_is_set = OptCheck('self_protection', 'defconfig', 'IOMMU_SUPPORT', 'y')
304 l += [iommu_support_is_set] # is needed for mitigating DMA attacks
305 if arch in ('X86_64', 'ARM64', 'X86_32'):
306 l += [OptCheck('self_protection', 'defconfig', 'RANDOMIZE_BASE', 'y')]
307 l += [OptCheck('self_protection', 'defconfig', 'THREAD_INFO_IN_TASK', 'y')]
308 if arch in ('X86_64', 'ARM64'):
309 l += [OptCheck('self_protection', 'defconfig', 'VMAP_STACK', 'y')]
310 if arch in ('X86_64', 'X86_32'):
311 l += [OptCheck('self_protection', 'defconfig', 'MICROCODE', 'y')] # is needed for mitigating CPU bugs
312 l += [OptCheck('self_protection', 'defconfig', 'RETPOLINE', 'y')]
313 l += [OptCheck('self_protection', 'defconfig', 'X86_SMAP', 'y')]
314 l += [OptCheck('self_protection', 'defconfig', 'SYN_COOKIES', 'y')] # another reason?
315 l += [OR(OptCheck('self_protection', 'defconfig', 'X86_UMIP', 'y'),
316 OptCheck('self_protection', 'defconfig', 'X86_INTEL_UMIP', 'y'))]
317 if arch in ('ARM64', 'ARM'):
318 l += [OptCheck('self_protection', 'defconfig', 'STACKPROTECTOR_PER_TASK', 'y')]
320 l += [OptCheck('self_protection', 'defconfig', 'PAGE_TABLE_ISOLATION', 'y')]
321 l += [OptCheck('self_protection', 'defconfig', 'RANDOMIZE_MEMORY', 'y')]
322 l += [AND(OptCheck('self_protection', 'defconfig', 'INTEL_IOMMU', 'y'),
323 iommu_support_is_set)]
324 l += [AND(OptCheck('self_protection', 'defconfig', 'AMD_IOMMU', 'y'),
325 iommu_support_is_set)]
327 l += [OptCheck('self_protection', 'defconfig', 'ARM64_PAN', 'y')]
328 l += [OptCheck('self_protection', 'defconfig', 'UNMAP_KERNEL_AT_EL0', 'y')]
329 l += [OR(OptCheck('self_protection', 'defconfig', 'HARDEN_EL2_VECTORS', 'y'),
330 AND(OptCheck('self_protection', 'defconfig', 'RANDOMIZE_BASE', 'y'),
331 VerCheck((5, 9))))] # HARDEN_EL2_VECTORS was included in RANDOMIZE_BASE in v5.9
332 l += [OptCheck('self_protection', 'defconfig', 'RODATA_FULL_DEFAULT_ENABLED', 'y')]
333 l += [OptCheck('self_protection', 'defconfig', 'ARM64_PTR_AUTH', 'y')]
334 l += [OptCheck('self_protection', 'defconfig', 'ARM64_BTI_KERNEL', 'y')]
335 l += [OR(OptCheck('self_protection', 'defconfig', 'HARDEN_BRANCH_PREDICTOR', 'y'),
336 VerCheck((5, 10)))] # HARDEN_BRANCH_PREDICTOR is enabled by default since v5.10
337 l += [OptCheck('self_protection', 'defconfig', 'ARM64_MTE', 'y')]
339 l += [OptCheck('self_protection', 'defconfig', 'CPU_SW_DOMAIN_PAN', 'y')]
340 l += [OptCheck('self_protection', 'defconfig', 'HARDEN_BRANCH_PREDICTOR', 'y')]
342 # 'self_protection', 'kspp'
343 l += [OptCheck('self_protection', 'kspp', 'SECURITY_DMESG_RESTRICT', 'y')]
344 l += [OptCheck('self_protection', 'kspp', 'BUG_ON_DATA_CORRUPTION', 'y')]
345 l += [OptCheck('self_protection', 'kspp', 'DEBUG_WX', 'y')]
346 l += [OptCheck('self_protection', 'kspp', 'SCHED_STACK_END_CHECK', 'y')]
347 l += [OptCheck('self_protection', 'kspp', 'SLAB_FREELIST_HARDENED', 'y')]
348 l += [OptCheck('self_protection', 'kspp', 'SLAB_FREELIST_RANDOM', 'y')]
349 l += [OptCheck('self_protection', 'kspp', 'SHUFFLE_PAGE_ALLOCATOR', 'y')]
350 l += [OptCheck('self_protection', 'kspp', 'FORTIFY_SOURCE', 'y')]
351 l += [OptCheck('self_protection', 'kspp', 'DEBUG_LIST', 'y')]
352 l += [OptCheck('self_protection', 'kspp', 'DEBUG_SG', 'y')]
353 l += [OptCheck('self_protection', 'kspp', 'DEBUG_CREDENTIALS', 'y')]
354 l += [OptCheck('self_protection', 'kspp', 'DEBUG_NOTIFIERS', 'y')]
355 l += [OptCheck('self_protection', 'kspp', 'INIT_ON_ALLOC_DEFAULT_ON', 'y')]
356 l += [OptCheck('self_protection', 'kspp', 'GCC_PLUGIN_LATENT_ENTROPY', 'y')]
357 randstruct_is_set = OptCheck('self_protection', 'kspp', 'GCC_PLUGIN_RANDSTRUCT', 'y')
358 l += [randstruct_is_set]
359 hardened_usercopy_is_set = OptCheck('self_protection', 'kspp', 'HARDENED_USERCOPY', 'y')
360 l += [hardened_usercopy_is_set]
361 l += [AND(OptCheck('self_protection', 'kspp', 'HARDENED_USERCOPY_FALLBACK', 'is not set'),
362 hardened_usercopy_is_set)]
363 l += [OR(OptCheck('self_protection', 'kspp', 'MODULE_SIG', 'y'),
365 l += [OR(OptCheck('self_protection', 'kspp', 'MODULE_SIG_ALL', 'y'),
367 l += [OR(OptCheck('self_protection', 'kspp', 'MODULE_SIG_SHA512', 'y'),
369 l += [OR(OptCheck('self_protection', 'kspp', 'MODULE_SIG_FORCE', 'y'),
370 modules_not_set)] # refers to LOCKDOWN
371 l += [OR(OptCheck('self_protection', 'kspp', 'INIT_STACK_ALL_ZERO', 'y'),
372 OptCheck('self_protection', 'kspp', 'GCC_PLUGIN_STRUCTLEAK_BYREF_ALL', 'y'))]
373 l += [OR(OptCheck('self_protection', 'kspp', 'INIT_ON_FREE_DEFAULT_ON', 'y'),
374 OptCheck('self_protection', 'kspp', 'PAGE_POISONING_ZERO', 'y'))]
375 # CONFIG_INIT_ON_FREE_DEFAULT_ON was added in v5.3.
376 # CONFIG_PAGE_POISONING_ZERO was removed in v5.11.
377 # Starting from v5.11 CONFIG_PAGE_POISONING unconditionally checks
378 # the 0xAA poison pattern on allocation.
379 # That brings higher performance penalty.
380 if arch in ('X86_64', 'ARM64', 'X86_32'):
381 stackleak_is_set = OptCheck('self_protection', 'kspp', 'GCC_PLUGIN_STACKLEAK', 'y')
382 l += [stackleak_is_set]
383 if arch in ('X86_64', 'X86_32'):
384 l += [OptCheck('self_protection', 'kspp', 'DEFAULT_MMAP_MIN_ADDR', '65536')]
385 if arch in ('ARM64', 'ARM'):
386 l += [OptCheck('self_protection', 'kspp', 'DEFAULT_MMAP_MIN_ADDR', '32768')]
387 l += [OptCheck('self_protection', 'kspp', 'SYN_COOKIES', 'y')] # another reason?
389 l += [OptCheck('self_protection', 'kspp', 'ARM64_SW_TTBR0_PAN', 'y')]
391 l += [OptCheck('self_protection', 'kspp', 'PAGE_TABLE_ISOLATION', 'y')]
392 l += [OptCheck('self_protection', 'kspp', 'HIGHMEM64G', 'y')]
393 l += [OptCheck('self_protection', 'kspp', 'X86_PAE', 'y')]
395 # 'self_protection', 'clipos'
396 l += [OptCheck('self_protection', 'clipos', 'DEBUG_VIRTUAL', 'y')]
397 l += [OptCheck('self_protection', 'clipos', 'STATIC_USERMODEHELPER', 'y')] # needs userspace support
398 l += [OptCheck('self_protection', 'clipos', 'EFI_DISABLE_PCI_DMA', 'y')]
399 l += [OptCheck('self_protection', 'clipos', 'SLAB_MERGE_DEFAULT', 'is not set')] # slab_nomerge
400 l += [OptCheck('self_protection', 'clipos', 'RANDOM_TRUST_BOOTLOADER', 'is not set')]
401 l += [OptCheck('self_protection', 'clipos', 'RANDOM_TRUST_CPU', 'is not set')]
402 l += [AND(OptCheck('self_protection', 'clipos', 'GCC_PLUGIN_RANDSTRUCT_PERFORMANCE', 'is not set'),
404 if arch in ('X86_64', 'ARM64', 'X86_32'):
405 l += [AND(OptCheck('self_protection', 'clipos', 'STACKLEAK_METRICS', 'is not set'),
407 l += [AND(OptCheck('self_protection', 'clipos', 'STACKLEAK_RUNTIME_DISABLE', 'is not set'),
409 if arch in ('X86_64', 'X86_32'):
410 l += [AND(OptCheck('self_protection', 'clipos', 'INTEL_IOMMU_DEFAULT_ON', 'y'),
411 iommu_support_is_set)]
413 l += [AND(OptCheck('self_protection', 'clipos', 'INTEL_IOMMU_SVM', 'y'),
414 iommu_support_is_set)]
416 l += [AND(OptCheck('self_protection', 'clipos', 'INTEL_IOMMU', 'y'),
417 iommu_support_is_set)]
419 # 'self_protection', 'my'
420 l += [AND(OptCheck('self_protection', 'my', 'UBSAN_BOUNDS', 'y'),
421 OptCheck('self_protection', 'my', 'UBSAN_MISC', 'is not set'),
422 OptCheck('self_protection', 'my', 'UBSAN_TRAP', 'y'))]
423 l += [OptCheck('self_protection', 'my', 'RESET_ATTACK_MITIGATION', 'y')] # needs userspace support (systemd)
425 l += [AND(OptCheck('self_protection', 'my', 'AMD_IOMMU_V2', 'y'),
426 iommu_support_is_set)]
428 l += [OptCheck('self_protection', 'my', 'SHADOW_CALL_STACK', 'y')] # depends on clang, maybe it's alternative to STACKPROTECTOR_STRONG
429 l += [OptCheck('self_protection', 'my', 'KASAN_HW_TAGS', 'y')]
432 if arch in ('X86_64', 'ARM64', 'X86_32'):
433 l += [OptCheck('security_policy', 'defconfig', 'SECURITY', 'y')] # and choose your favourite LSM
435 l += [OptCheck('security_policy', 'kspp', 'SECURITY', 'y')] # and choose your favourite LSM
436 l += [OptCheck('security_policy', 'kspp', 'SECURITY_YAMA', 'y')]
437 l += [OR(OptCheck('security_policy', 'my', 'SECURITY_WRITABLE_HOOKS', 'is not set'),
438 OptCheck('security_policy', 'kspp', 'SECURITY_SELINUX_DISABLE', 'is not set'))]
439 l += [OptCheck('security_policy', 'clipos', 'SECURITY_LOCKDOWN_LSM', 'y')]
440 l += [OptCheck('security_policy', 'clipos', 'SECURITY_LOCKDOWN_LSM_EARLY', 'y')]
441 l += [OptCheck('security_policy', 'clipos', 'LOCK_DOWN_KERNEL_FORCE_CONFIDENTIALITY', 'y')]
442 l += [OptCheck('security_policy', 'my', 'SECURITY_SAFESETID', 'y')]
443 loadpin_is_set = OptCheck('security_policy', 'my', 'SECURITY_LOADPIN', 'y')
444 l += [loadpin_is_set] # needs userspace support
445 l += [AND(OptCheck('security_policy', 'my', 'SECURITY_LOADPIN_ENFORCE', 'y'),
448 # 'cut_attack_surface', 'defconfig'
449 l += [OptCheck('cut_attack_surface', 'defconfig', 'SECCOMP', 'y')]
450 l += [OptCheck('cut_attack_surface', 'defconfig', 'SECCOMP_FILTER', 'y')]
451 if arch in ('X86_64', 'ARM64', 'X86_32'):
452 l += [OR(OptCheck('cut_attack_surface', 'defconfig', 'STRICT_DEVMEM', 'y'),
453 devmem_not_set)] # refers to LOCKDOWN
455 # 'cut_attack_surface', 'kspp'
456 l += [OptCheck('cut_attack_surface', 'kspp', 'ACPI_CUSTOM_METHOD', 'is not set')] # refers to LOCKDOWN
457 l += [OptCheck('cut_attack_surface', 'kspp', 'COMPAT_BRK', 'is not set')]
458 l += [OptCheck('cut_attack_surface', 'kspp', 'DEVKMEM', 'is not set')] # refers to LOCKDOWN
459 l += [OptCheck('cut_attack_surface', 'kspp', 'COMPAT_VDSO', 'is not set')]
460 l += [OptCheck('cut_attack_surface', 'kspp', 'BINFMT_MISC', 'is not set')]
461 l += [OptCheck('cut_attack_surface', 'kspp', 'INET_DIAG', 'is not set')]
462 l += [OptCheck('cut_attack_surface', 'kspp', 'KEXEC', 'is not set')] # refers to LOCKDOWN
463 l += [OptCheck('cut_attack_surface', 'kspp', 'PROC_KCORE', 'is not set')] # refers to LOCKDOWN
464 l += [OptCheck('cut_attack_surface', 'kspp', 'LEGACY_PTYS', 'is not set')]
465 l += [OptCheck('cut_attack_surface', 'kspp', 'HIBERNATION', 'is not set')] # refers to LOCKDOWN
466 l += [OptCheck('cut_attack_surface', 'kspp', 'IA32_EMULATION', 'is not set')]
467 l += [OptCheck('cut_attack_surface', 'kspp', 'X86_X32', 'is not set')]
468 l += [OptCheck('cut_attack_surface', 'kspp', 'MODIFY_LDT_SYSCALL', 'is not set')]
469 l += [OptCheck('cut_attack_surface', 'kspp', 'OABI_COMPAT', 'is not set')]
470 l += [modules_not_set]
471 l += [devmem_not_set]
472 l += [OR(OptCheck('cut_attack_surface', 'kspp', 'IO_STRICT_DEVMEM', 'y'),
473 devmem_not_set)] # refers to LOCKDOWN
475 l += [OR(OptCheck('cut_attack_surface', 'kspp', 'STRICT_DEVMEM', 'y'),
476 devmem_not_set)] # refers to LOCKDOWN
478 l += [OptCheck('cut_attack_surface', 'kspp', 'LEGACY_VSYSCALL_NONE', 'y')] # 'vsyscall=none'
480 # 'cut_attack_surface', 'grsecurity'
481 l += [OptCheck('cut_attack_surface', 'grsecurity', 'ZSMALLOC_STAT', 'is not set')]
482 l += [OptCheck('cut_attack_surface', 'grsecurity', 'PAGE_OWNER', 'is not set')]
483 l += [OptCheck('cut_attack_surface', 'grsecurity', 'DEBUG_KMEMLEAK', 'is not set')]
484 l += [OptCheck('cut_attack_surface', 'grsecurity', 'BINFMT_AOUT', 'is not set')]
485 l += [OptCheck('cut_attack_surface', 'grsecurity', 'KPROBES', 'is not set')] # refers to LOCKDOWN
486 l += [OptCheck('cut_attack_surface', 'grsecurity', 'UPROBES', 'is not set')]
487 l += [OptCheck('cut_attack_surface', 'grsecurity', 'GENERIC_TRACER', 'is not set')] # refers to LOCKDOWN
488 l += [OptCheck('cut_attack_surface', 'grsecurity', 'PROC_VMCORE', 'is not set')]
489 l += [OptCheck('cut_attack_surface', 'grsecurity', 'PROC_PAGE_MONITOR', 'is not set')]
490 l += [OptCheck('cut_attack_surface', 'grsecurity', 'USELIB', 'is not set')]
491 l += [OptCheck('cut_attack_surface', 'grsecurity', 'CHECKPOINT_RESTORE', 'is not set')]
492 l += [OptCheck('cut_attack_surface', 'grsecurity', 'USERFAULTFD', 'is not set')]
493 l += [OptCheck('cut_attack_surface', 'grsecurity', 'HWPOISON_INJECT', 'is not set')]
494 l += [OptCheck('cut_attack_surface', 'grsecurity', 'MEM_SOFT_DIRTY', 'is not set')]
495 l += [OptCheck('cut_attack_surface', 'grsecurity', 'DEVPORT', 'is not set')] # refers to LOCKDOWN
496 l += [OptCheck('cut_attack_surface', 'grsecurity', 'DEBUG_FS', 'is not set')] # refers to LOCKDOWN
497 l += [OptCheck('cut_attack_surface', 'grsecurity', 'NOTIFIER_ERROR_INJECTION', 'is not set')]
498 l += [AND(OptCheck('cut_attack_surface', 'grsecurity', 'X86_PTDUMP', 'is not set'),
499 OptCheck('cut_attack_surface', 'my', 'PTDUMP_DEBUGFS', 'is not set'))]
501 # 'cut_attack_surface', 'maintainer'
502 l += [OptCheck('cut_attack_surface', 'maintainer', 'DRM_LEGACY', 'is not set')]
503 l += [OptCheck('cut_attack_surface', 'maintainer', 'FB', 'is not set')]
504 l += [OptCheck('cut_attack_surface', 'maintainer', 'VT', 'is not set')]
506 # 'cut_attack_surface', 'grapheneos'
507 l += [OptCheck('cut_attack_surface', 'grapheneos', 'AIO', 'is not set')]
509 # 'cut_attack_surface', 'clipos'
510 l += [OptCheck('cut_attack_surface', 'clipos', 'STAGING', 'is not set')]
511 l += [OptCheck('cut_attack_surface', 'clipos', 'KSM', 'is not set')] # to prevent FLUSH+RELOAD attack
512 # l += [OptCheck('cut_attack_surface', 'clipos', 'IKCONFIG', 'is not set')] # no, IKCONFIG is needed for this check :)
513 l += [OptCheck('cut_attack_surface', 'clipos', 'KALLSYMS', 'is not set')]
514 l += [OptCheck('cut_attack_surface', 'clipos', 'X86_VSYSCALL_EMULATION', 'is not set')]
515 l += [OptCheck('cut_attack_surface', 'clipos', 'MAGIC_SYSRQ', 'is not set')]
516 l += [OptCheck('cut_attack_surface', 'clipos', 'KEXEC_FILE', 'is not set')] # refers to LOCKDOWN (permissive)
517 l += [OptCheck('cut_attack_surface', 'clipos', 'USER_NS', 'is not set')] # user.max_user_namespaces=0
518 l += [OptCheck('cut_attack_surface', 'clipos', 'X86_MSR', 'is not set')] # refers to LOCKDOWN
519 l += [OptCheck('cut_attack_surface', 'clipos', 'X86_CPUID', 'is not set')]
520 l += [OptCheck('cut_attack_surface', 'clipos', 'IO_URING', 'is not set')]
521 l += [OptCheck('cut_attack_surface', 'clipos', 'X86_IOPL_IOPERM', 'is not set')] # refers to LOCKDOWN
522 l += [OptCheck('cut_attack_surface', 'clipos', 'ACPI_TABLE_UPGRADE', 'is not set')] # refers to LOCKDOWN
523 l += [OptCheck('cut_attack_surface', 'clipos', 'EFI_CUSTOM_SSDT_OVERLAYS', 'is not set')]
524 l += [AND(OptCheck('cut_attack_surface', 'clipos', 'LDISC_AUTOLOAD', 'is not set'),
525 PresenceCheck('LDISC_AUTOLOAD'))]
526 if arch in ('X86_64', 'X86_32'):
527 l += [OptCheck('cut_attack_surface', 'clipos', 'X86_INTEL_TSX_MODE_OFF', 'y')] # tsx=off
529 # 'cut_attack_surface', 'lockdown'
530 l += [OptCheck('cut_attack_surface', 'lockdown', 'EFI_TEST', 'is not set')] # refers to LOCKDOWN
531 l += [OptCheck('cut_attack_surface', 'lockdown', 'BPF_SYSCALL', 'is not set')] # refers to LOCKDOWN
532 l += [OptCheck('cut_attack_surface', 'lockdown', 'MMIOTRACE_TEST', 'is not set')] # refers to LOCKDOWN
534 # 'cut_attack_surface', 'my'
535 l += [OptCheck('cut_attack_surface', 'my', 'TRIM_UNUSED_KSYMS', 'y')]
536 l += [OptCheck('cut_attack_surface', 'my', 'MMIOTRACE', 'is not set')] # refers to LOCKDOWN (permissive)
537 l += [OptCheck('cut_attack_surface', 'my', 'LIVEPATCH', 'is not set')]
538 l += [OptCheck('cut_attack_surface', 'my', 'IP_DCCP', 'is not set')]
539 l += [OptCheck('cut_attack_surface', 'my', 'IP_SCTP', 'is not set')]
540 l += [OptCheck('cut_attack_surface', 'my', 'FTRACE', 'is not set')] # refers to LOCKDOWN
541 l += [OptCheck('cut_attack_surface', 'my', 'VIDEO_VIVID', 'is not set')]
542 l += [OptCheck('cut_attack_surface', 'my', 'INPUT_EVBUG', 'is not set')] # Can be used as a keylogger
544 # 'userspace_hardening'
545 if arch in ('X86_64', 'ARM64', 'X86_32'):
546 l += [OptCheck('userspace_hardening', 'defconfig', 'INTEGRITY', 'y')]
548 l += [OptCheck('userspace_hardening', 'my', 'INTEGRITY', 'y')]
550 l += [OptCheck('userspace_hardening', 'defconfig', 'ARM64_MTE', 'y')]
551 if arch in ('ARM', 'X86_32'):
552 l += [OptCheck('userspace_hardening', 'defconfig', 'VMSPLIT_3G', 'y')]
553 if arch in ('X86_64', 'ARM64'):
554 l += [OptCheck('userspace_hardening', 'clipos', 'ARCH_MMAP_RND_BITS', '32')]
555 if arch in ('X86_32', 'ARM'):
556 l += [OptCheck('userspace_hardening', 'my', 'ARCH_MMAP_RND_BITS', '16')]
558 # l += [OptCheck('feature_test', 'my', 'LKDTM', 'm')] # only for debugging!
561 def print_unknown_options(checklist, parsed_options):
563 for opt in checklist:
564 if hasattr(opt, 'opts'):
566 if hasattr(o, 'name'):
567 known_options.append(o.name)
569 known_options.append(opt.name)
570 for option, value in parsed_options.items():
571 if option not in known_options:
572 print('[?] No rule for option {} ({})'.format(option, value))
575 def print_checklist(mode, checklist, with_results):
579 opt = ['CONFIG_'+o.name, o.expected, o.decision, o.reason]
583 print(json.dumps(opts))
590 print('=' * sep_line_len)
591 print('{:^45}|{:^13}|{:^10}|{:^20}'.format('option name', 'desired val', 'decision', 'reason'), end='')
593 print('| {}'.format('check result'), end='')
595 print('=' * sep_line_len)
598 for opt in checklist:
600 if mode == 'show_ok':
601 if not opt.result.startswith('OK'):
603 if mode == 'show_fail':
604 if not opt.result.startswith('FAIL'):
606 opt.table_print(mode, with_results)
608 if mode == 'verbose':
609 print('-' * sep_line_len)
614 fail_count = len(list(filter(lambda opt: opt.result.startswith('FAIL'), checklist)))
616 ok_count = len(list(filter(lambda opt: opt.result.startswith('OK'), checklist)))
618 if mode == 'show_ok':
619 fail_suppressed = ' (suppressed in output)'
620 if mode == 'show_fail':
621 ok_suppressed = ' (suppressed in output)'
623 print('[+] Config check is finished: \'OK\' - {}{} / \'FAIL\' - {}{}'.format(ok_count, ok_suppressed, fail_count, fail_suppressed))
626 def perform_check(opt, parsed_options, kernel_version):
627 if hasattr(opt, 'opts'):
628 # prepare ComplexOptCheck
630 if hasattr(o, 'opts'):
631 # Recursion for nested ComplexOptChecks
632 perform_check(o, parsed_options, kernel_version)
633 if hasattr(o, 'state'):
634 o.state = parsed_options.get(o.name, None)
635 if hasattr(o, 'ver'):
636 o.ver = kernel_version
638 # prepare simple check, opt.state is mandatory
639 if not hasattr(opt, 'state'):
640 sys.exit('[!] ERROR: bad simple check {}'.format(vars(opt)))
641 opt.state = parsed_options.get(opt.name, None)
645 def perform_checks(checklist, parsed_options, kernel_version):
646 for opt in checklist:
647 perform_check(opt, parsed_options, kernel_version)
650 def parse_config_file(parsed_options, fname):
651 with open(fname, 'r') as f:
652 opt_is_on = re.compile("CONFIG_[a-zA-Z0-9_]*=[a-zA-Z0-9_\"]*")
653 opt_is_off = re.compile("# CONFIG_[a-zA-Z0-9_]* is not set")
655 for line in f.readlines():
660 if opt_is_on.match(line):
661 option, value = line[7:].split('=', 1)
662 elif opt_is_off.match(line):
663 option, value = line[9:].split(' ', 1)
664 if value != 'is not set':
665 sys.exit('[!] ERROR: bad disabled config option "{}"'.format(line))
667 if option in parsed_options:
668 sys.exit('[!] ERROR: config option "{}" exists multiple times'.format(line))
671 parsed_options[option] = value
673 return parsed_options
679 # - reporting about unknown kernel options in the config
680 # - verbose printing of ComplexOptCheck items
681 # * json mode for printing the results in JSON format
682 report_modes = ['verbose', 'json', 'show_ok', 'show_fail']
683 supported_archs = ['X86_64', 'X86_32', 'ARM64', 'ARM']
684 parser = ArgumentParser(prog='kconfig-hardened-check',
685 description='A tool for checking the security hardening options of the Linux kernel')
686 parser.add_argument('--version', action='version', version='%(prog)s ' + __version__)
687 parser.add_argument('-p', '--print', choices=supported_archs,
688 help='print security hardening preferences for the selected architecture')
689 parser.add_argument('-c', '--config',
690 help='check the kernel config file against these preferences')
691 parser.add_argument('-m', '--mode', choices=report_modes,
692 help='choose the report mode')
693 args = parser.parse_args()
699 print("[+] Special report mode: {}".format(mode))
701 config_checklist = []
705 print('[+] Config file to check: {}'.format(args.config))
707 arch, msg = detect_arch(args.config, supported_archs)
709 sys.exit('[!] ERROR: {}'.format(msg))
711 print('[+] Detected architecture: {}'.format(arch))
713 kernel_version, msg = detect_version(args.config)
714 if not kernel_version:
715 sys.exit('[!] ERROR: {}'.format(msg))
717 print('[+] Detected kernel version: {}.{}'.format(kernel_version[0], kernel_version[1]))
719 construct_checklist(config_checklist, arch)
720 parsed_options = OrderedDict()
721 parse_config_file(parsed_options, args.config)
722 perform_checks(config_checklist, parsed_options, kernel_version)
724 if mode == 'verbose':
725 print_unknown_options(config_checklist, parsed_options)
726 print_checklist(mode, config_checklist, True)
731 if mode in ('show_ok', 'show_fail'):
732 sys.exit('[!] ERROR: please use "{}" mode for checking the kernel config'.format(mode))
734 construct_checklist(config_checklist, arch)
736 print('[+] Printing kernel security hardening preferences for {}...'.format(arch))
737 print_checklist(mode, config_checklist, False)
743 if __name__ == '__main__':