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 # N.B. Hardening sysctls:
43 # kernel.kptr_restrict=2 (or 1?)
44 # kernel.dmesg_restrict=1 (also see the kconfig option)
45 # kernel.perf_event_paranoid=3
46 # kernel.kexec_load_disabled=1
47 # kernel.yama.ptrace_scope=3
48 # user.max_user_namespaces=0
49 # what about bpf_jit_enable?
50 # kernel.unprivileged_bpf_disabled=1
51 # net.core.bpf_jit_harden=2
53 # vm.unprivileged_userfaultfd=0
54 # (at first, it disabled unprivileged userfaultfd,
55 # and since v5.11 it enables unprivileged userfaultfd for user-mode only)
57 # dev.tty.ldisc_autoload=0
58 # fs.protected_symlinks=1
59 # fs.protected_hardlinks=1
60 # fs.protected_fifos=2
61 # fs.protected_regular=2
63 # kernel.modules_disabled=1
66 # pylint: disable=missing-module-docstring,missing-class-docstring,missing-function-docstring
67 # pylint: disable=line-too-long,invalid-name,too-many-branches,too-many-statements
71 from argparse import ArgumentParser
72 from collections import OrderedDict
75 from .__about__ import __version__
79 def __init__(self, reason, decision, name, expected):
81 self.expected = expected
82 self.decision = decision
88 if self.expected == self.state:
90 elif self.state is None:
91 if self.expected == 'is not set':
92 self.result = 'OK: not found'
94 self.result = 'FAIL: not found'
96 self.result = 'FAIL: "' + self.state + '"'
98 if self.result.startswith('OK'):
102 def table_print(self, _mode, with_results):
103 print('CONFIG_{:<38}|{:^13}|{:^10}|{:^20}'.format(self.name, self.expected, self.decision, self.reason), end='')
105 print('| {}'.format(self.result), end='')
109 def __init__(self, ver_expected):
110 self.ver_expected = ver_expected
115 if self.ver[0] > self.ver_expected[0]:
116 self.result = 'OK: version >= ' + str(self.ver_expected[0]) + '.' + str(self.ver_expected[1])
118 if self.ver[0] < self.ver_expected[0]:
119 self.result = 'FAIL: version < ' + str(self.ver_expected[0]) + '.' + str(self.ver_expected[1])
121 if self.ver[1] >= self.ver_expected[1]:
122 self.result = 'OK: version >= ' + str(self.ver_expected[0]) + '.' + str(self.ver_expected[1])
124 self.result = 'FAIL: version < ' + str(self.ver_expected[0]) + '.' + str(self.ver_expected[1])
127 def table_print(self, _mode, with_results):
128 ver_req = 'kernel version >= ' + str(self.ver_expected[0]) + '.' + str(self.ver_expected[1])
129 print('{:<91}'.format(ver_req), end='')
131 print('| {}'.format(self.result), end='')
135 def __init__(self, name):
141 if self.state is None:
142 self.result = 'FAIL: not present'
144 self.result = 'OK: is present'
147 def table_print(self, _mode, with_results):
148 print('CONFIG_{:<84}'.format(self.name + ' is present'), end='')
150 print('| {}'.format(self.result), end='')
153 class ComplexOptCheck:
154 def __init__(self, *opts):
157 sys.exit('[!] ERROR: empty {} check'.format(self.__class__.__name__))
158 if not isinstance(opts[0], OptCheck):
159 sys.exit('[!] ERROR: invalid {} check: {}'.format(self.__class__.__name__, opts))
164 return self.opts[0].name
168 return self.opts[0].expected
172 return self.opts[0].decision
176 return self.opts[0].reason
178 def table_print(self, mode, with_results):
179 if mode == 'verbose':
180 print(' {:87}'.format('<<< ' + self.__class__.__name__ + ' >>>'), end='')
182 print('| {}'.format(self.result), end='')
185 o.table_print(mode, with_results)
188 o.table_print(mode, False)
190 print('| {}'.format(self.result), end='')
193 class OR(ComplexOptCheck):
194 # self.opts[0] is the option that this OR-check is about.
196 # OR(<X_is_hardened>, <X_is_disabled>)
197 # OR(<X_is_hardened>, <old_X_is_hardened>)
201 sys.exit('[!] ERROR: invalid OR check')
203 for i, opt in enumerate(self.opts):
206 if opt.result != 'OK' or i == 0:
207 # Preserve additional explanation of this OK result.
208 # Simple OK is enough only for the main option that
209 # this OR-check is about.
210 self.result = opt.result
212 # Simple OK is not enough for additional checks.
213 self.result = 'OK: CONFIG_{} "{}"'.format(opt.name, opt.expected)
215 self.result = self.opts[0].result
219 class AND(ComplexOptCheck):
220 # self.opts[0] is the option that this AND-check is about.
222 # AND(<suboption>, <main_option>)
223 # Suboption is not checked if checking of the main_option is failed.
224 # AND(<X_is_disabled>, <old_X_is_disabled>)
227 for i, opt in reversed(list(enumerate(self.opts))):
230 self.result = opt.result
233 # This FAIL is caused by additional checks,
234 # and not by the main option that this AND-check is about.
235 # Describe the reason of the FAIL.
236 if opt.result.startswith('FAIL: \"') or opt.result == 'FAIL: not found':
237 self.result = 'FAIL: CONFIG_{} not "{}"'.format(opt.name, opt.expected)
238 elif opt.result == 'FAIL: not present':
239 self.result = 'FAIL: CONFIG_{} not present'.format(opt.name)
241 # This FAIL message is self-explaining.
242 self.result = opt.result
245 sys.exit('[!] ERROR: invalid AND check')
248 def detect_arch(fname, archs):
249 with open(fname, 'r') as f:
250 arch_pattern = re.compile("CONFIG_[a-zA-Z0-9_]*=y")
252 for line in f.readlines():
253 if arch_pattern.match(line):
254 option, _ = line[7:].split('=', 1)
259 return None, 'more than one supported architecture is detected'
261 return None, 'failed to detect architecture'
265 def detect_version(fname):
266 with open(fname, 'r') as f:
267 ver_pattern = re.compile("# Linux/.* Kernel Configuration")
268 for line in f.readlines():
269 if ver_pattern.match(line):
273 ver_numbers = ver_str.split('.')
274 if len(ver_numbers) < 3 or not ver_numbers[0].isdigit() or not ver_numbers[1].isdigit():
275 msg = 'failed to parse the version "' + ver_str + '"'
277 return (int(ver_numbers[0]), int(ver_numbers[1])), None
278 return None, 'no kernel version detected'
281 def construct_checklist(l, arch):
282 modules_not_set = OptCheck('cut_attack_surface', 'kspp', 'MODULES', 'is not set')
283 devmem_not_set = OptCheck('cut_attack_surface', 'kspp', 'DEVMEM', 'is not set') # refers to LOCKDOWN
285 # 'self_protection', 'defconfig'
286 l += [OptCheck('self_protection', 'defconfig', 'BUG', 'y')]
287 l += [OptCheck('self_protection', 'defconfig', 'SLUB_DEBUG', 'y')]
288 l += [OptCheck('self_protection', 'defconfig', 'GCC_PLUGINS', 'y')]
289 l += [OR(OptCheck('self_protection', 'defconfig', 'STACKPROTECTOR_STRONG', 'y'),
290 OptCheck('self_protection', 'defconfig', 'CC_STACKPROTECTOR_STRONG', 'y'))]
291 l += [OR(OptCheck('self_protection', 'defconfig', 'STRICT_KERNEL_RWX', 'y'),
292 OptCheck('self_protection', 'defconfig', 'DEBUG_RODATA', 'y'))] # before v4.11
293 l += [OR(OptCheck('self_protection', 'defconfig', 'STRICT_MODULE_RWX', 'y'),
294 OptCheck('self_protection', 'defconfig', 'DEBUG_SET_MODULE_RONX', 'y'),
295 modules_not_set)] # DEBUG_SET_MODULE_RONX was before v4.11
296 l += [OR(OptCheck('self_protection', 'defconfig', 'REFCOUNT_FULL', 'y'),
297 VerCheck((5, 5)))] # REFCOUNT_FULL is enabled by default since v5.5
298 iommu_support_is_set = OptCheck('self_protection', 'defconfig', 'IOMMU_SUPPORT', 'y')
299 l += [iommu_support_is_set] # is needed for mitigating DMA attacks
300 if arch in ('X86_64', 'ARM64', 'X86_32'):
301 l += [OptCheck('self_protection', 'defconfig', 'RANDOMIZE_BASE', 'y')]
302 l += [OptCheck('self_protection', 'defconfig', 'THREAD_INFO_IN_TASK', 'y')]
303 if arch in ('X86_64', 'ARM64'):
304 l += [OptCheck('self_protection', 'defconfig', 'VMAP_STACK', 'y')]
305 if arch in ('X86_64', 'X86_32'):
306 l += [OptCheck('self_protection', 'defconfig', 'MICROCODE', 'y')] # is needed for mitigating CPU bugs
307 l += [OptCheck('self_protection', 'defconfig', 'RETPOLINE', 'y')]
308 l += [OptCheck('self_protection', 'defconfig', 'X86_SMAP', 'y')]
309 l += [OptCheck('self_protection', 'defconfig', 'SYN_COOKIES', 'y')] # another reason?
310 l += [OR(OptCheck('self_protection', 'defconfig', 'X86_UMIP', 'y'),
311 OptCheck('self_protection', 'defconfig', 'X86_INTEL_UMIP', 'y'))]
312 if arch in ('ARM64', 'ARM'):
313 l += [OptCheck('self_protection', 'defconfig', 'STACKPROTECTOR_PER_TASK', 'y')]
315 l += [OptCheck('self_protection', 'defconfig', 'PAGE_TABLE_ISOLATION', 'y')]
316 l += [OptCheck('self_protection', 'defconfig', 'RANDOMIZE_MEMORY', 'y')]
317 l += [AND(OptCheck('self_protection', 'defconfig', 'INTEL_IOMMU', 'y'),
318 iommu_support_is_set)]
319 l += [AND(OptCheck('self_protection', 'defconfig', 'AMD_IOMMU', 'y'),
320 iommu_support_is_set)]
322 l += [OptCheck('self_protection', 'defconfig', 'ARM64_PAN', 'y')]
323 l += [OptCheck('self_protection', 'defconfig', 'UNMAP_KERNEL_AT_EL0', 'y')]
324 l += [OR(OptCheck('self_protection', 'defconfig', 'HARDEN_EL2_VECTORS', 'y'),
325 AND(OptCheck('self_protection', 'defconfig', 'RANDOMIZE_BASE', 'y'),
326 VerCheck((5, 9))))] # HARDEN_EL2_VECTORS was included in RANDOMIZE_BASE in v5.9
327 l += [OptCheck('self_protection', 'defconfig', 'RODATA_FULL_DEFAULT_ENABLED', 'y')]
328 l += [OptCheck('self_protection', 'defconfig', 'ARM64_PTR_AUTH', 'y')]
329 l += [OptCheck('self_protection', 'defconfig', 'ARM64_BTI_KERNEL', 'y')]
330 l += [OR(OptCheck('self_protection', 'defconfig', 'HARDEN_BRANCH_PREDICTOR', 'y'),
331 VerCheck((5, 10)))] # HARDEN_BRANCH_PREDICTOR is enabled by default since v5.10
333 l += [OptCheck('self_protection', 'defconfig', 'CPU_SW_DOMAIN_PAN', 'y')]
334 l += [OptCheck('self_protection', 'defconfig', 'HARDEN_BRANCH_PREDICTOR', 'y')]
336 # 'self_protection', 'kspp'
337 l += [OptCheck('self_protection', 'kspp', 'SECURITY_DMESG_RESTRICT', 'y')]
338 l += [OptCheck('self_protection', 'kspp', 'BUG_ON_DATA_CORRUPTION', 'y')]
339 l += [OptCheck('self_protection', 'kspp', 'DEBUG_WX', 'y')]
340 l += [OptCheck('self_protection', 'kspp', 'SCHED_STACK_END_CHECK', 'y')]
341 l += [OptCheck('self_protection', 'kspp', 'SLAB_FREELIST_HARDENED', 'y')]
342 l += [OptCheck('self_protection', 'kspp', 'SLAB_FREELIST_RANDOM', 'y')]
343 l += [OptCheck('self_protection', 'kspp', 'SHUFFLE_PAGE_ALLOCATOR', 'y')]
344 l += [OptCheck('self_protection', 'kspp', 'FORTIFY_SOURCE', 'y')]
345 l += [OptCheck('self_protection', 'kspp', 'DEBUG_LIST', 'y')]
346 l += [OptCheck('self_protection', 'kspp', 'DEBUG_SG', 'y')]
347 l += [OptCheck('self_protection', 'kspp', 'DEBUG_CREDENTIALS', 'y')]
348 l += [OptCheck('self_protection', 'kspp', 'DEBUG_NOTIFIERS', 'y')]
349 l += [OptCheck('self_protection', 'kspp', 'INIT_ON_ALLOC_DEFAULT_ON', 'y')]
350 l += [OptCheck('self_protection', 'kspp', 'GCC_PLUGIN_LATENT_ENTROPY', 'y')]
351 randstruct_is_set = OptCheck('self_protection', 'kspp', 'GCC_PLUGIN_RANDSTRUCT', 'y')
352 l += [randstruct_is_set]
353 hardened_usercopy_is_set = OptCheck('self_protection', 'kspp', 'HARDENED_USERCOPY', 'y')
354 l += [hardened_usercopy_is_set]
355 l += [AND(OptCheck('self_protection', 'kspp', 'HARDENED_USERCOPY_FALLBACK', 'is not set'),
356 hardened_usercopy_is_set)]
357 l += [OR(OptCheck('self_protection', 'kspp', 'MODULE_SIG', 'y'),
359 l += [OR(OptCheck('self_protection', 'kspp', 'MODULE_SIG_ALL', 'y'),
361 l += [OR(OptCheck('self_protection', 'kspp', 'MODULE_SIG_SHA512', 'y'),
363 l += [OR(OptCheck('self_protection', 'kspp', 'MODULE_SIG_FORCE', 'y'),
364 modules_not_set)] # refers to LOCKDOWN
365 l += [OR(OptCheck('self_protection', 'kspp', 'INIT_STACK_ALL_ZERO', 'y'),
366 OptCheck('self_protection', 'kspp', 'GCC_PLUGIN_STRUCTLEAK_BYREF_ALL', 'y'))]
367 l += [OR(OptCheck('self_protection', 'kspp', 'INIT_ON_FREE_DEFAULT_ON', 'y'),
368 OptCheck('self_protection', 'kspp', 'PAGE_POISONING_ZERO', 'y'))]
369 # CONFIG_INIT_ON_FREE_DEFAULT_ON was added in v5.3.
370 # CONFIG_PAGE_POISONING_ZERO was removed in v5.11.
371 # Starting from v5.11 CONFIG_PAGE_POISONING unconditionally checks
372 # the 0xAA poison pattern on allocation.
373 # That brings higher performance penalty.
374 if arch in ('X86_64', 'ARM64', 'X86_32'):
375 stackleak_is_set = OptCheck('self_protection', 'kspp', 'GCC_PLUGIN_STACKLEAK', 'y')
376 l += [stackleak_is_set]
377 if arch in ('X86_64', 'X86_32'):
378 l += [OptCheck('self_protection', 'kspp', 'DEFAULT_MMAP_MIN_ADDR', '65536')]
379 if arch in ('ARM64', 'ARM'):
380 l += [OptCheck('self_protection', 'kspp', 'DEFAULT_MMAP_MIN_ADDR', '32768')]
381 l += [OptCheck('self_protection', 'kspp', 'SYN_COOKIES', 'y')] # another reason?
383 l += [OptCheck('self_protection', 'kspp', 'ARM64_SW_TTBR0_PAN', 'y')]
385 l += [OptCheck('self_protection', 'kspp', 'PAGE_TABLE_ISOLATION', 'y')]
386 l += [OptCheck('self_protection', 'kspp', 'HIGHMEM64G', 'y')]
387 l += [OptCheck('self_protection', 'kspp', 'X86_PAE', 'y')]
389 # 'self_protection', 'clipos'
390 l += [OptCheck('self_protection', 'clipos', 'DEBUG_VIRTUAL', 'y')]
391 l += [OptCheck('self_protection', 'clipos', 'STATIC_USERMODEHELPER', 'y')] # needs userspace support
392 l += [OptCheck('self_protection', 'clipos', 'EFI_DISABLE_PCI_DMA', 'y')]
393 l += [OptCheck('self_protection', 'clipos', 'SLAB_MERGE_DEFAULT', 'is not set')] # slab_nomerge
394 l += [OptCheck('self_protection', 'clipos', 'RANDOM_TRUST_BOOTLOADER', 'is not set')]
395 l += [OptCheck('self_protection', 'clipos', 'RANDOM_TRUST_CPU', 'is not set')]
396 l += [AND(OptCheck('self_protection', 'clipos', 'GCC_PLUGIN_RANDSTRUCT_PERFORMANCE', 'is not set'),
398 if arch in ('X86_64', 'ARM64', 'X86_32'):
399 l += [AND(OptCheck('self_protection', 'clipos', 'STACKLEAK_METRICS', 'is not set'),
401 l += [AND(OptCheck('self_protection', 'clipos', 'STACKLEAK_RUNTIME_DISABLE', 'is not set'),
403 if arch in ('X86_64', 'X86_32'):
404 l += [AND(OptCheck('self_protection', 'clipos', 'INTEL_IOMMU_DEFAULT_ON', 'y'),
405 iommu_support_is_set)]
407 l += [AND(OptCheck('self_protection', 'clipos', 'INTEL_IOMMU_SVM', 'y'),
408 iommu_support_is_set)]
410 l += [AND(OptCheck('self_protection', 'clipos', 'INTEL_IOMMU', 'y'),
411 iommu_support_is_set)]
413 # 'self_protection', 'my'
414 l += [AND(OptCheck('self_protection', 'my', 'UBSAN_BOUNDS', 'y'),
415 OptCheck('self_protection', 'my', 'UBSAN_MISC', 'is not set'),
416 OptCheck('self_protection', 'my', 'UBSAN_TRAP', 'y'))]
417 l += [OptCheck('self_protection', 'my', 'RESET_ATTACK_MITIGATION', 'y')] # needs userspace support (systemd)
419 l += [AND(OptCheck('self_protection', 'my', 'AMD_IOMMU_V2', 'y'),
420 iommu_support_is_set)]
422 l += [OptCheck('self_protection', 'my', 'SHADOW_CALL_STACK', 'y')] # depends on clang, maybe it's alternative to STACKPROTECTOR_STRONG
425 if arch in ('X86_64', 'ARM64', 'X86_32'):
426 l += [OptCheck('security_policy', 'defconfig', 'SECURITY', 'y')] # and choose your favourite LSM
428 l += [OptCheck('security_policy', 'kspp', 'SECURITY', 'y')] # and choose your favourite LSM
429 l += [OptCheck('security_policy', 'kspp', 'SECURITY_YAMA', 'y')]
430 l += [OR(OptCheck('security_policy', 'my', 'SECURITY_WRITABLE_HOOKS', 'is not set'),
431 OptCheck('security_policy', 'kspp', 'SECURITY_SELINUX_DISABLE', 'is not set'))]
432 l += [OptCheck('security_policy', 'clipos', 'SECURITY_LOCKDOWN_LSM', 'y')]
433 l += [OptCheck('security_policy', 'clipos', 'SECURITY_LOCKDOWN_LSM_EARLY', 'y')]
434 l += [OptCheck('security_policy', 'clipos', 'LOCK_DOWN_KERNEL_FORCE_CONFIDENTIALITY', 'y')]
435 l += [OptCheck('security_policy', 'my', 'SECURITY_SAFESETID', 'y')]
436 loadpin_is_set = OptCheck('security_policy', 'my', 'SECURITY_LOADPIN', 'y')
437 l += [loadpin_is_set] # needs userspace support
438 l += [AND(OptCheck('security_policy', 'my', 'SECURITY_LOADPIN_ENFORCE', 'y'),
441 # 'cut_attack_surface', 'defconfig'
442 l += [OptCheck('cut_attack_surface', 'defconfig', 'SECCOMP', 'y')]
443 l += [OptCheck('cut_attack_surface', 'defconfig', 'SECCOMP_FILTER', 'y')]
444 if arch in ('X86_64', 'ARM64', 'X86_32'):
445 l += [OR(OptCheck('cut_attack_surface', 'defconfig', 'STRICT_DEVMEM', 'y'),
446 devmem_not_set)] # refers to LOCKDOWN
448 # 'cut_attack_surface', 'kspp'
449 l += [OptCheck('cut_attack_surface', 'kspp', 'ACPI_CUSTOM_METHOD', 'is not set')] # refers to LOCKDOWN
450 l += [OptCheck('cut_attack_surface', 'kspp', 'COMPAT_BRK', 'is not set')]
451 l += [OptCheck('cut_attack_surface', 'kspp', 'DEVKMEM', 'is not set')] # refers to LOCKDOWN
452 l += [OptCheck('cut_attack_surface', 'kspp', 'COMPAT_VDSO', 'is not set')]
453 l += [OptCheck('cut_attack_surface', 'kspp', 'BINFMT_MISC', 'is not set')]
454 l += [OptCheck('cut_attack_surface', 'kspp', 'INET_DIAG', 'is not set')]
455 l += [OptCheck('cut_attack_surface', 'kspp', 'KEXEC', 'is not set')] # refers to LOCKDOWN
456 l += [OptCheck('cut_attack_surface', 'kspp', 'PROC_KCORE', 'is not set')] # refers to LOCKDOWN
457 l += [OptCheck('cut_attack_surface', 'kspp', 'LEGACY_PTYS', 'is not set')]
458 l += [OptCheck('cut_attack_surface', 'kspp', 'HIBERNATION', 'is not set')] # refers to LOCKDOWN
459 l += [OptCheck('cut_attack_surface', 'kspp', 'IA32_EMULATION', 'is not set')]
460 l += [OptCheck('cut_attack_surface', 'kspp', 'X86_X32', 'is not set')]
461 l += [OptCheck('cut_attack_surface', 'kspp', 'MODIFY_LDT_SYSCALL', 'is not set')]
462 l += [OptCheck('cut_attack_surface', 'kspp', 'OABI_COMPAT', 'is not set')]
463 l += [modules_not_set]
464 l += [devmem_not_set]
465 l += [OR(OptCheck('cut_attack_surface', 'kspp', 'IO_STRICT_DEVMEM', 'y'),
466 devmem_not_set)] # refers to LOCKDOWN
468 l += [OR(OptCheck('cut_attack_surface', 'kspp', 'STRICT_DEVMEM', 'y'),
469 devmem_not_set)] # refers to LOCKDOWN
471 l += [OptCheck('cut_attack_surface', 'kspp', 'LEGACY_VSYSCALL_NONE', 'y')] # 'vsyscall=none'
473 # 'cut_attack_surface', 'grsecurity'
474 l += [OptCheck('cut_attack_surface', 'grsecurity', 'ZSMALLOC_STAT', 'is not set')]
475 l += [OptCheck('cut_attack_surface', 'grsecurity', 'PAGE_OWNER', 'is not set')]
476 l += [OptCheck('cut_attack_surface', 'grsecurity', 'DEBUG_KMEMLEAK', 'is not set')]
477 l += [OptCheck('cut_attack_surface', 'grsecurity', 'BINFMT_AOUT', 'is not set')]
478 l += [OptCheck('cut_attack_surface', 'grsecurity', 'KPROBES', 'is not set')] # refers to LOCKDOWN
479 l += [OptCheck('cut_attack_surface', 'grsecurity', 'UPROBES', 'is not set')]
480 l += [OptCheck('cut_attack_surface', 'grsecurity', 'GENERIC_TRACER', 'is not set')] # refers to LOCKDOWN
481 l += [OptCheck('cut_attack_surface', 'grsecurity', 'PROC_VMCORE', 'is not set')]
482 l += [OptCheck('cut_attack_surface', 'grsecurity', 'PROC_PAGE_MONITOR', 'is not set')]
483 l += [OptCheck('cut_attack_surface', 'grsecurity', 'USELIB', 'is not set')]
484 l += [OptCheck('cut_attack_surface', 'grsecurity', 'CHECKPOINT_RESTORE', 'is not set')]
485 l += [OptCheck('cut_attack_surface', 'grsecurity', 'USERFAULTFD', 'is not set')]
486 l += [OptCheck('cut_attack_surface', 'grsecurity', 'HWPOISON_INJECT', 'is not set')]
487 l += [OptCheck('cut_attack_surface', 'grsecurity', 'MEM_SOFT_DIRTY', 'is not set')]
488 l += [OptCheck('cut_attack_surface', 'grsecurity', 'DEVPORT', 'is not set')] # refers to LOCKDOWN
489 l += [OptCheck('cut_attack_surface', 'grsecurity', 'DEBUG_FS', 'is not set')] # refers to LOCKDOWN
490 l += [OptCheck('cut_attack_surface', 'grsecurity', 'NOTIFIER_ERROR_INJECTION', 'is not set')]
491 l += [AND(OptCheck('cut_attack_surface', 'grsecurity', 'X86_PTDUMP', 'is not set'),
492 OptCheck('cut_attack_surface', 'my', 'PTDUMP_DEBUGFS', 'is not set'))]
494 # 'cut_attack_surface', 'maintainer'
495 l += [OptCheck('cut_attack_surface', 'maintainer', 'DRM_LEGACY', 'is not set')]
496 l += [OptCheck('cut_attack_surface', 'maintainer', 'FB', 'is not set')]
497 l += [OptCheck('cut_attack_surface', 'maintainer', 'VT', 'is not set')]
499 # 'cut_attack_surface', 'grapheneos'
500 l += [OptCheck('cut_attack_surface', 'grapheneos', 'AIO', 'is not set')]
502 # 'cut_attack_surface', 'clipos'
503 l += [OptCheck('cut_attack_surface', 'clipos', 'STAGING', 'is not set')]
504 l += [OptCheck('cut_attack_surface', 'clipos', 'KSM', 'is not set')] # to prevent FLUSH+RELOAD attack
505 # l += [OptCheck('cut_attack_surface', 'clipos', 'IKCONFIG', 'is not set')] # no, IKCONFIG is needed for this check :)
506 l += [OptCheck('cut_attack_surface', 'clipos', 'KALLSYMS', 'is not set')]
507 l += [OptCheck('cut_attack_surface', 'clipos', 'X86_VSYSCALL_EMULATION', 'is not set')]
508 l += [OptCheck('cut_attack_surface', 'clipos', 'MAGIC_SYSRQ', 'is not set')]
509 l += [OptCheck('cut_attack_surface', 'clipos', 'KEXEC_FILE', 'is not set')] # refers to LOCKDOWN (permissive)
510 l += [OptCheck('cut_attack_surface', 'clipos', 'USER_NS', 'is not set')] # user.max_user_namespaces=0
511 l += [OptCheck('cut_attack_surface', 'clipos', 'X86_MSR', 'is not set')] # refers to LOCKDOWN
512 l += [OptCheck('cut_attack_surface', 'clipos', 'X86_CPUID', 'is not set')]
513 l += [OptCheck('cut_attack_surface', 'clipos', 'IO_URING', 'is not set')]
514 l += [OptCheck('cut_attack_surface', 'clipos', 'X86_IOPL_IOPERM', 'is not set')] # refers to LOCKDOWN
515 l += [OptCheck('cut_attack_surface', 'clipos', 'ACPI_TABLE_UPGRADE', 'is not set')] # refers to LOCKDOWN
516 l += [OptCheck('cut_attack_surface', 'clipos', 'EFI_CUSTOM_SSDT_OVERLAYS', 'is not set')]
517 l += [AND(OptCheck('cut_attack_surface', 'clipos', 'LDISC_AUTOLOAD', 'is not set'),
518 PresenceCheck('LDISC_AUTOLOAD'))]
519 if arch in ('X86_64', 'X86_32'):
520 l += [OptCheck('cut_attack_surface', 'clipos', 'X86_INTEL_TSX_MODE_OFF', 'y')] # tsx=off
522 # 'cut_attack_surface', 'lockdown'
523 l += [OptCheck('cut_attack_surface', 'lockdown', 'EFI_TEST', 'is not set')] # refers to LOCKDOWN
524 l += [OptCheck('cut_attack_surface', 'lockdown', 'BPF_SYSCALL', 'is not set')] # refers to LOCKDOWN
525 l += [OptCheck('cut_attack_surface', 'lockdown', 'MMIOTRACE_TEST', 'is not set')] # refers to LOCKDOWN
527 # 'cut_attack_surface', 'my'
528 l += [OptCheck('cut_attack_surface', 'my', 'TRIM_UNUSED_KSYMS', 'y')]
529 l += [OptCheck('cut_attack_surface', 'my', 'MMIOTRACE', 'is not set')] # refers to LOCKDOWN (permissive)
530 l += [OptCheck('cut_attack_surface', 'my', 'LIVEPATCH', 'is not set')]
531 l += [OptCheck('cut_attack_surface', 'my', 'IP_DCCP', 'is not set')]
532 l += [OptCheck('cut_attack_surface', 'my', 'IP_SCTP', 'is not set')]
533 l += [OptCheck('cut_attack_surface', 'my', 'FTRACE', 'is not set')] # refers to LOCKDOWN
534 l += [OptCheck('cut_attack_surface', 'my', 'VIDEO_VIVID', 'is not set')]
535 l += [OptCheck('cut_attack_surface', 'my', 'INPUT_EVBUG', 'is not set')] # Can be used as a keylogger
537 # 'userspace_hardening'
538 if arch in ('X86_64', 'ARM64', 'X86_32'):
539 l += [OptCheck('userspace_hardening', 'defconfig', 'INTEGRITY', 'y')]
541 l += [OptCheck('userspace_hardening', 'my', 'INTEGRITY', 'y')]
543 l += [OptCheck('userspace_hardening', 'defconfig', 'ARM64_MTE', 'y')]
544 if arch in ('ARM', 'X86_32'):
545 l += [OptCheck('userspace_hardening', 'defconfig', 'VMSPLIT_3G', 'y')]
546 if arch in ('X86_64', 'ARM64'):
547 l += [OptCheck('userspace_hardening', 'clipos', 'ARCH_MMAP_RND_BITS', '32')]
548 if arch in ('X86_32', 'ARM'):
549 l += [OptCheck('userspace_hardening', 'my', 'ARCH_MMAP_RND_BITS', '16')]
551 # l += [OptCheck('feature_test', 'my', 'LKDTM', 'm')] # only for debugging!
554 def print_unknown_options(checklist, parsed_options):
556 for opt in checklist:
557 if hasattr(opt, 'opts'):
559 if hasattr(o, 'name'):
560 known_options.append(o.name)
562 known_options.append(opt.name)
563 for option, value in parsed_options.items():
564 if option not in known_options:
565 print('[?] No rule for option {} ({})'.format(option, value))
568 def print_checklist(mode, checklist, with_results):
572 opt = ['CONFIG_'+o.name, o.expected, o.decision, o.reason]
576 print(json.dumps(opts))
583 print('=' * sep_line_len)
584 print('{:^45}|{:^13}|{:^10}|{:^20}'.format('option name', 'desired val', 'decision', 'reason'), end='')
586 print('| {}'.format('check result'), end='')
588 print('=' * sep_line_len)
591 for opt in checklist:
593 if mode == 'show_ok':
594 if not opt.result.startswith('OK'):
596 if mode == 'show_fail':
597 if not opt.result.startswith('FAIL'):
599 opt.table_print(mode, with_results)
601 if mode == 'verbose':
602 print('-' * sep_line_len)
607 fail_count = len(list(filter(lambda opt: opt.result.startswith('FAIL'), checklist)))
609 ok_count = len(list(filter(lambda opt: opt.result.startswith('OK'), checklist)))
611 if mode == 'show_ok':
612 fail_suppressed = ' (suppressed in output)'
613 if mode == 'show_fail':
614 ok_suppressed = ' (suppressed in output)'
616 print('[+] Config check is finished: \'OK\' - {}{} / \'FAIL\' - {}{}'.format(ok_count, ok_suppressed, fail_count, fail_suppressed))
619 def perform_check(opt, parsed_options, kernel_version):
620 if hasattr(opt, 'opts'):
621 # prepare ComplexOptCheck
623 if hasattr(o, 'opts'):
624 # Recursion for nested ComplexOptChecks
625 perform_check(o, parsed_options, kernel_version)
626 if hasattr(o, 'state'):
627 o.state = parsed_options.get(o.name, None)
628 if hasattr(o, 'ver'):
629 o.ver = kernel_version
631 # prepare simple check, opt.state is mandatory
632 if not hasattr(opt, 'state'):
633 sys.exit('[!] ERROR: bad simple check {}'.format(vars(opt)))
634 opt.state = parsed_options.get(opt.name, None)
638 def perform_checks(checklist, parsed_options, kernel_version):
639 for opt in checklist:
640 perform_check(opt, parsed_options, kernel_version)
643 def parse_config_file(parsed_options, fname):
644 with open(fname, 'r') as f:
645 opt_is_on = re.compile("CONFIG_[a-zA-Z0-9_]*=[a-zA-Z0-9_\"]*")
646 opt_is_off = re.compile("# CONFIG_[a-zA-Z0-9_]* is not set")
648 for line in f.readlines():
653 if opt_is_on.match(line):
654 option, value = line[7:].split('=', 1)
655 elif opt_is_off.match(line):
656 option, value = line[9:].split(' ', 1)
657 if value != 'is not set':
658 sys.exit('[!] ERROR: bad disabled config option "{}"'.format(line))
660 if option in parsed_options:
661 sys.exit('[!] ERROR: config option "{}" exists multiple times'.format(line))
664 parsed_options[option] = value
666 return parsed_options
672 # - reporting about unknown kernel options in the config
673 # - verbose printing of ComplexOptCheck items
674 # * json mode for printing the results in JSON format
675 report_modes = ['verbose', 'json', 'show_ok', 'show_fail']
676 supported_archs = ['X86_64', 'X86_32', 'ARM64', 'ARM']
677 parser = ArgumentParser(prog='kconfig-hardened-check',
678 description='A tool for checking the security hardening options of the Linux kernel')
679 parser.add_argument('--version', action='version', version='%(prog)s ' + __version__)
680 parser.add_argument('-p', '--print', choices=supported_archs,
681 help='print security hardening preferences for the selected architecture')
682 parser.add_argument('-c', '--config',
683 help='check the kernel config file against these preferences')
684 parser.add_argument('-m', '--mode', choices=report_modes,
685 help='choose the report mode')
686 args = parser.parse_args()
692 print("[+] Special report mode: {}".format(mode))
694 config_checklist = []
698 print('[+] Config file to check: {}'.format(args.config))
700 arch, msg = detect_arch(args.config, supported_archs)
702 sys.exit('[!] ERROR: {}'.format(msg))
704 print('[+] Detected architecture: {}'.format(arch))
706 kernel_version, msg = detect_version(args.config)
707 if not kernel_version:
708 sys.exit('[!] ERROR: {}'.format(msg))
710 print('[+] Detected kernel version: {}.{}'.format(kernel_version[0], kernel_version[1]))
712 construct_checklist(config_checklist, arch)
713 parsed_options = OrderedDict()
714 parse_config_file(parsed_options, args.config)
715 perform_checks(config_checklist, parsed_options, kernel_version)
717 if mode == 'verbose':
718 print_unknown_options(config_checklist, parsed_options)
719 print_checklist(mode, config_checklist, True)
724 if mode in ('show_ok', 'show_fail'):
725 sys.exit('[!] ERROR: please use "{}" mode for checking the kernel config'.format(mode))
727 construct_checklist(config_checklist, arch)
729 print('[+] Printing kernel security hardening preferences for {}...'.format(arch))
730 print_checklist(mode, config_checklist, False)
736 if __name__ == '__main__':