c69380c19cd35ef91f4d4f43571a6640dc0aa719
[kconfig-hardened-check.git] / kconfig_hardened_check / __init__.py
1 #!/usr/bin/python3
2
3 #
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!
7 #
8 # Author: Alexander Popov <alex.popov@linux.com>
9 #
10 # Please don't cry if my Python code looks like C.
11 #
12 #
13 # N.B Hardening command line parameters:
14 #    slab_nomerge
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)
20 #    loadpin.enforce=1
21 #    debugfs=no-mount (or off if possible)
22 #
23 #    Mitigations of CPU vulnerabilities:
24 #       Аrch-independent:
25 #           mitigations=auto,nosmt (nosmt is slow)
26 #       X86:
27 #           spectre_v2=on
28 #           pti=on
29 #           spec_store_bypass_disable=on
30 #           l1tf=full,force
31 #           mds=full,nosmt
32 #           tsx=off
33 #       ARM64:
34 #           kpti=on
35 #           ssbd=force-on
36 #
37 #    Should NOT be set:
38 #           nokaslr
39 #           arm64.nobti
40 #           arm64.nopauth
41 #
42 #    Hardware tag-based KASAN with arm64 Memory Tagging Extension (MTE):
43 #           kasan=on
44 #           kasan.stacktrace=off
45 #           kasan.fault=panic
46 #
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
57 #
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)
61 #
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
67 #    fs.suid_dumpable=0
68 #    kernel.modules_disabled=1
69
70
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
73
74
75 import sys
76 from argparse import ArgumentParser
77 from collections import OrderedDict
78 import re
79 import json
80 from .__about__ import __version__
81
82
83 class OptCheck:
84     def __init__(self, reason, decision, name, expected):
85         self.name = name
86         self.expected = expected
87         self.decision = decision
88         self.reason = reason
89         self.state = None
90         self.result = None
91
92     def check(self):
93         if self.expected == self.state:
94             self.result = 'OK'
95         elif self.state is None:
96             if self.expected == 'is not set':
97                 self.result = 'OK: not found'
98             else:
99                 self.result = 'FAIL: not found'
100         else:
101             self.result = 'FAIL: "' + self.state + '"'
102
103         if self.result.startswith('OK'):
104             return True
105         return False
106
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='')
109         if with_results:
110             print('|   {}'.format(self.result), end='')
111
112
113 class VerCheck:
114     def __init__(self, ver_expected):
115         self.ver_expected = ver_expected
116         self.ver = ()
117         self.result = None
118
119     def check(self):
120         if self.ver[0] > self.ver_expected[0]:
121             self.result = 'OK: version >= ' + str(self.ver_expected[0]) + '.' + str(self.ver_expected[1])
122             return True
123         if self.ver[0] < self.ver_expected[0]:
124             self.result = 'FAIL: version < ' + str(self.ver_expected[0]) + '.' + str(self.ver_expected[1])
125             return False
126         if self.ver[1] >= self.ver_expected[1]:
127             self.result = 'OK: version >= ' + str(self.ver_expected[0]) + '.' + str(self.ver_expected[1])
128             return True
129         self.result = 'FAIL: version < ' + str(self.ver_expected[0]) + '.' + str(self.ver_expected[1])
130         return False
131
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='')
135         if with_results:
136             print('|   {}'.format(self.result), end='')
137
138
139 class PresenceCheck:
140     def __init__(self, name):
141         self.name = name
142         self.state = None
143         self.result = None
144
145     def check(self):
146         if self.state is None:
147             self.result = 'FAIL: not present'
148             return False
149         self.result = 'OK: is present'
150         return True
151
152     def table_print(self, _mode, with_results):
153         print('CONFIG_{:<84}'.format(self.name + ' is present'), end='')
154         if with_results:
155             print('|   {}'.format(self.result), end='')
156
157
158 class ComplexOptCheck:
159     def __init__(self, *opts):
160         self.opts = opts
161         if not 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))
165         self.result = None
166
167     @property
168     def name(self):
169         return self.opts[0].name
170
171     @property
172     def expected(self):
173         return self.opts[0].expected
174
175     @property
176     def decision(self):
177         return self.opts[0].decision
178
179     @property
180     def reason(self):
181         return self.opts[0].reason
182
183     def table_print(self, mode, with_results):
184         if mode == 'verbose':
185             print('    {:87}'.format('<<< ' + self.__class__.__name__ + ' >>>'), end='')
186             if with_results:
187                 print('|   {}'.format(self.result), end='')
188             for o in self.opts:
189                 print()
190                 o.table_print(mode, with_results)
191         else:
192             o = self.opts[0]
193             o.table_print(mode, False)
194             if with_results:
195                 print('|   {}'.format(self.result), end='')
196
197
198 class OR(ComplexOptCheck):
199     # self.opts[0] is the option that this OR-check is about.
200     # Use cases:
201     #     OR(<X_is_hardened>, <X_is_disabled>)
202     #     OR(<X_is_hardened>, <old_X_is_hardened>)
203
204     def check(self):
205         if not self.opts:
206             sys.exit('[!] ERROR: invalid OR check')
207
208         for i, opt in enumerate(self.opts):
209             ret = opt.check()
210             if ret:
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
216                 else:
217                     # Simple OK is not enough for additional checks.
218                     self.result = 'OK: CONFIG_{} "{}"'.format(opt.name, opt.expected)
219                 return True
220         self.result = self.opts[0].result
221         return False
222
223
224 class AND(ComplexOptCheck):
225     # self.opts[0] is the option that this AND-check is about.
226     # Use cases:
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>)
230
231     def check(self):
232         for i, opt in reversed(list(enumerate(self.opts))):
233             ret = opt.check()
234             if i == 0:
235                 self.result = opt.result
236                 return ret
237             if not ret:
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)
245                 else:
246                     # This FAIL message is self-explaining.
247                     self.result = opt.result
248                 return False
249
250         sys.exit('[!] ERROR: invalid AND check')
251
252
253 def detect_arch(fname, archs):
254     with open(fname, 'r') as f:
255         arch_pattern = re.compile("CONFIG_[a-zA-Z0-9_]*=y")
256         arch = None
257         for line in f.readlines():
258             if arch_pattern.match(line):
259                 option, _ = line[7:].split('=', 1)
260                 if option in archs:
261                     if not arch:
262                         arch = option
263                     else:
264                         return None, 'more than one supported architecture is detected'
265         if not arch:
266             return None, 'failed to detect architecture'
267         return arch, 'OK'
268
269
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):
275                 line = line.strip()
276                 parts = line.split()
277                 ver_str = parts[2]
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 + '"'
281                     return None, msg
282                 return (int(ver_numbers[0]), int(ver_numbers[1])), None
283         return None, 'no kernel version detected'
284
285
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
289
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')]
319     if arch == 'X86_64':
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)]
326     if arch == 'ARM64':
327         l += [OptCheck('self_protection', 'defconfig', 'ARM64_PAN', 'y')]
328         l += [OptCheck('self_protection', 'defconfig', 'ARM64_EPAN', 'y')]
329         l += [OptCheck('self_protection', 'defconfig', 'UNMAP_KERNEL_AT_EL0', 'y')]
330         l += [OR(OptCheck('self_protection', 'defconfig', 'HARDEN_EL2_VECTORS', 'y'),
331                  AND(OptCheck('self_protection', 'defconfig', 'RANDOMIZE_BASE', 'y'),
332                      VerCheck((5, 9))))] # HARDEN_EL2_VECTORS was included in RANDOMIZE_BASE in v5.9
333         l += [OptCheck('self_protection', 'defconfig', 'RODATA_FULL_DEFAULT_ENABLED', 'y')]
334         l += [OptCheck('self_protection', 'defconfig', 'ARM64_PTR_AUTH', 'y')]
335         l += [OptCheck('self_protection', 'defconfig', 'ARM64_BTI_KERNEL', 'y')]
336         l += [OR(OptCheck('self_protection', 'defconfig', 'HARDEN_BRANCH_PREDICTOR', 'y'),
337                  VerCheck((5, 10)))] # HARDEN_BRANCH_PREDICTOR is enabled by default since v5.10
338         l += [OptCheck('self_protection', 'defconfig', 'ARM64_MTE', 'y')]
339     if arch == 'ARM':
340         l += [OptCheck('self_protection', 'defconfig', 'CPU_SW_DOMAIN_PAN', 'y')]
341         l += [OptCheck('self_protection', 'defconfig', 'HARDEN_BRANCH_PREDICTOR', 'y')]
342
343     # 'self_protection', 'kspp'
344     l += [OptCheck('self_protection', 'kspp', 'SECURITY_DMESG_RESTRICT', 'y')]
345     l += [OptCheck('self_protection', 'kspp', 'BUG_ON_DATA_CORRUPTION', 'y')]
346     l += [OptCheck('self_protection', 'kspp', 'DEBUG_WX', 'y')]
347     l += [OptCheck('self_protection', 'kspp', 'SCHED_STACK_END_CHECK', 'y')]
348     l += [OptCheck('self_protection', 'kspp', 'SLAB_FREELIST_HARDENED', 'y')]
349     l += [OptCheck('self_protection', 'kspp', 'SLAB_FREELIST_RANDOM', 'y')]
350     l += [OptCheck('self_protection', 'kspp', 'SHUFFLE_PAGE_ALLOCATOR', 'y')]
351     l += [OptCheck('self_protection', 'kspp', 'FORTIFY_SOURCE', 'y')]
352     l += [OptCheck('self_protection', 'kspp', 'DEBUG_LIST', 'y')]
353     l += [OptCheck('self_protection', 'kspp', 'DEBUG_SG', 'y')]
354     l += [OptCheck('self_protection', 'kspp', 'DEBUG_CREDENTIALS', 'y')]
355     l += [OptCheck('self_protection', 'kspp', 'DEBUG_NOTIFIERS', 'y')]
356     l += [OptCheck('self_protection', 'kspp', 'INIT_ON_ALLOC_DEFAULT_ON', 'y')]
357     l += [OptCheck('self_protection', 'kspp', 'GCC_PLUGIN_LATENT_ENTROPY', 'y')]
358     randstruct_is_set = OptCheck('self_protection', 'kspp', 'GCC_PLUGIN_RANDSTRUCT', 'y')
359     l += [randstruct_is_set]
360     hardened_usercopy_is_set = OptCheck('self_protection', 'kspp', 'HARDENED_USERCOPY', 'y')
361     l += [hardened_usercopy_is_set]
362     l += [AND(OptCheck('self_protection', 'kspp', 'HARDENED_USERCOPY_FALLBACK', 'is not set'),
363               hardened_usercopy_is_set)]
364     l += [OR(OptCheck('self_protection', 'kspp', 'MODULE_SIG', 'y'),
365              modules_not_set)]
366     l += [OR(OptCheck('self_protection', 'kspp', 'MODULE_SIG_ALL', 'y'),
367              modules_not_set)]
368     l += [OR(OptCheck('self_protection', 'kspp', 'MODULE_SIG_SHA512', 'y'),
369              modules_not_set)]
370     l += [OR(OptCheck('self_protection', 'kspp', 'MODULE_SIG_FORCE', 'y'),
371              modules_not_set)] # refers to LOCKDOWN
372     l += [OR(OptCheck('self_protection', 'kspp', 'INIT_STACK_ALL_ZERO', 'y'),
373              OptCheck('self_protection', 'kspp', 'GCC_PLUGIN_STRUCTLEAK_BYREF_ALL', 'y'))]
374     l += [OR(OptCheck('self_protection', 'kspp', 'INIT_ON_FREE_DEFAULT_ON', 'y'),
375              OptCheck('self_protection', 'kspp', 'PAGE_POISONING_ZERO', 'y'))]
376              # CONFIG_INIT_ON_FREE_DEFAULT_ON was added in v5.3.
377              # CONFIG_PAGE_POISONING_ZERO was removed in v5.11.
378              # Starting from v5.11 CONFIG_PAGE_POISONING unconditionally checks
379              # the 0xAA poison pattern on allocation.
380              # That brings higher performance penalty.
381     if arch in ('X86_64', 'ARM64', 'X86_32'):
382         stackleak_is_set = OptCheck('self_protection', 'kspp', 'GCC_PLUGIN_STACKLEAK', 'y')
383         l += [stackleak_is_set]
384     if arch in ('X86_64', 'X86_32'):
385         l += [OptCheck('self_protection', 'kspp', 'DEFAULT_MMAP_MIN_ADDR', '65536')]
386     if arch in ('ARM64', 'ARM'):
387         l += [OptCheck('self_protection', 'kspp', 'DEFAULT_MMAP_MIN_ADDR', '32768')]
388         l += [OptCheck('self_protection', 'kspp', 'SYN_COOKIES', 'y')] # another reason?
389     if arch == 'ARM64':
390         l += [OptCheck('self_protection', 'kspp', 'ARM64_SW_TTBR0_PAN', 'y')]
391     if arch == 'X86_32':
392         l += [OptCheck('self_protection', 'kspp', 'PAGE_TABLE_ISOLATION', 'y')]
393         l += [OptCheck('self_protection', 'kspp', 'HIGHMEM64G', 'y')]
394         l += [OptCheck('self_protection', 'kspp', 'X86_PAE', 'y')]
395
396     # 'self_protection', 'clipos'
397     l += [OptCheck('self_protection', 'clipos', 'DEBUG_VIRTUAL', 'y')]
398     l += [OptCheck('self_protection', 'clipos', 'STATIC_USERMODEHELPER', 'y')] # needs userspace support
399     l += [OptCheck('self_protection', 'clipos', 'EFI_DISABLE_PCI_DMA', 'y')]
400     l += [OptCheck('self_protection', 'clipos', 'SLAB_MERGE_DEFAULT', 'is not set')] # slab_nomerge
401     l += [OptCheck('self_protection', 'clipos', 'RANDOM_TRUST_BOOTLOADER', 'is not set')]
402     l += [OptCheck('self_protection', 'clipos', 'RANDOM_TRUST_CPU', 'is not set')]
403     l += [AND(OptCheck('self_protection', 'clipos', 'GCC_PLUGIN_RANDSTRUCT_PERFORMANCE', 'is not set'),
404               randstruct_is_set)]
405     if arch in ('X86_64', 'ARM64', 'X86_32'):
406         l += [AND(OptCheck('self_protection', 'clipos', 'STACKLEAK_METRICS', 'is not set'),
407                   stackleak_is_set)]
408         l += [AND(OptCheck('self_protection', 'clipos', 'STACKLEAK_RUNTIME_DISABLE', 'is not set'),
409                   stackleak_is_set)]
410     if arch in ('X86_64', 'X86_32'):
411         l += [AND(OptCheck('self_protection', 'clipos', 'INTEL_IOMMU_DEFAULT_ON', 'y'),
412                   iommu_support_is_set)]
413     if arch == 'X86_64':
414         l += [AND(OptCheck('self_protection', 'clipos', 'INTEL_IOMMU_SVM', 'y'),
415                   iommu_support_is_set)]
416     if arch == 'X86_32':
417         l += [AND(OptCheck('self_protection', 'clipos', 'INTEL_IOMMU', 'y'),
418                   iommu_support_is_set)]
419
420     # 'self_protection', 'my'
421     l += [AND(OptCheck('self_protection', 'my', 'UBSAN_BOUNDS', 'y'),
422               OptCheck('self_protection', 'my', 'UBSAN_MISC', 'is not set'),
423               OptCheck('self_protection', 'my', 'UBSAN_TRAP', 'y'))]
424     l += [OptCheck('self_protection', 'my', 'RESET_ATTACK_MITIGATION', 'y')] # needs userspace support (systemd)
425     if arch == 'X86_64':
426         l += [AND(OptCheck('self_protection', 'my', 'AMD_IOMMU_V2', 'y'),
427                   iommu_support_is_set)]
428     if arch == 'ARM64':
429         l += [OptCheck('self_protection', 'my', 'SHADOW_CALL_STACK', 'y')] # depends on clang, maybe it's alternative to STACKPROTECTOR_STRONG
430         l += [OptCheck('self_protection', 'my', 'KASAN_HW_TAGS', 'y')]
431         cfi_clang_is_set = OptCheck('self_protection', 'my', 'CFI_CLANG', 'y')
432         l += [cfi_clang_is_set]
433         l += [AND(OptCheck('self_protection', 'my', 'CFI_PERMISSIVE', 'is not set'),
434                   cfi_clang_is_set)]
435
436     # 'security_policy'
437     if arch in ('X86_64', 'ARM64', 'X86_32'):
438         l += [OptCheck('security_policy', 'defconfig', 'SECURITY', 'y')] # and choose your favourite LSM
439     if arch == 'ARM':
440         l += [OptCheck('security_policy', 'kspp', 'SECURITY', 'y')] # and choose your favourite LSM
441     l += [OptCheck('security_policy', 'kspp', 'SECURITY_YAMA', 'y')]
442     l += [OR(OptCheck('security_policy', 'my', 'SECURITY_WRITABLE_HOOKS', 'is not set'),
443              OptCheck('security_policy', 'kspp', 'SECURITY_SELINUX_DISABLE', 'is not set'))]
444     l += [OptCheck('security_policy', 'clipos', 'SECURITY_LOCKDOWN_LSM', 'y')]
445     l += [OptCheck('security_policy', 'clipos', 'SECURITY_LOCKDOWN_LSM_EARLY', 'y')]
446     l += [OptCheck('security_policy', 'clipos', 'LOCK_DOWN_KERNEL_FORCE_CONFIDENTIALITY', 'y')]
447     l += [OptCheck('security_policy', 'my', 'SECURITY_SAFESETID', 'y')]
448     loadpin_is_set = OptCheck('security_policy', 'my', 'SECURITY_LOADPIN', 'y')
449     l += [loadpin_is_set] # needs userspace support
450     l += [AND(OptCheck('security_policy', 'my', 'SECURITY_LOADPIN_ENFORCE', 'y'),
451               loadpin_is_set)]
452
453     # 'cut_attack_surface', 'defconfig'
454     l += [OptCheck('cut_attack_surface', 'defconfig', 'SECCOMP', 'y')]
455     l += [OptCheck('cut_attack_surface', 'defconfig', 'SECCOMP_FILTER', 'y')]
456     if arch in ('X86_64', 'ARM64', 'X86_32'):
457         l += [OR(OptCheck('cut_attack_surface', 'defconfig', 'STRICT_DEVMEM', 'y'),
458                  devmem_not_set)] # refers to LOCKDOWN
459
460     # 'cut_attack_surface', 'kspp'
461     l += [OptCheck('cut_attack_surface', 'kspp', 'ACPI_CUSTOM_METHOD', 'is not set')] # refers to LOCKDOWN
462     l += [OptCheck('cut_attack_surface', 'kspp', 'COMPAT_BRK', 'is not set')]
463     l += [OptCheck('cut_attack_surface', 'kspp', 'DEVKMEM', 'is not set')] # refers to LOCKDOWN
464     l += [OptCheck('cut_attack_surface', 'kspp', 'COMPAT_VDSO', 'is not set')]
465     l += [OptCheck('cut_attack_surface', 'kspp', 'BINFMT_MISC', 'is not set')]
466     l += [OptCheck('cut_attack_surface', 'kspp', 'INET_DIAG', 'is not set')]
467     l += [OptCheck('cut_attack_surface', 'kspp', 'KEXEC', 'is not set')] # refers to LOCKDOWN
468     l += [OptCheck('cut_attack_surface', 'kspp', 'PROC_KCORE', 'is not set')] # refers to LOCKDOWN
469     l += [OptCheck('cut_attack_surface', 'kspp', 'LEGACY_PTYS', 'is not set')]
470     l += [OptCheck('cut_attack_surface', 'kspp', 'HIBERNATION', 'is not set')] # refers to LOCKDOWN
471     l += [OptCheck('cut_attack_surface', 'kspp', 'IA32_EMULATION', 'is not set')]
472     l += [OptCheck('cut_attack_surface', 'kspp', 'X86_X32', 'is not set')]
473     l += [OptCheck('cut_attack_surface', 'kspp', 'MODIFY_LDT_SYSCALL', 'is not set')]
474     l += [OptCheck('cut_attack_surface', 'kspp', 'OABI_COMPAT', 'is not set')]
475     l += [modules_not_set]
476     l += [devmem_not_set]
477     l += [OR(OptCheck('cut_attack_surface', 'kspp', 'IO_STRICT_DEVMEM', 'y'),
478              devmem_not_set)] # refers to LOCKDOWN
479     if arch == 'ARM':
480         l += [OR(OptCheck('cut_attack_surface', 'kspp', 'STRICT_DEVMEM', 'y'),
481                  devmem_not_set)] # refers to LOCKDOWN
482     if arch == 'X86_64':
483         l += [OptCheck('cut_attack_surface', 'kspp', 'LEGACY_VSYSCALL_NONE', 'y')] # 'vsyscall=none'
484
485     # 'cut_attack_surface', 'grsecurity'
486     l += [OptCheck('cut_attack_surface', 'grsecurity', 'ZSMALLOC_STAT', 'is not set')]
487     l += [OptCheck('cut_attack_surface', 'grsecurity', 'PAGE_OWNER', 'is not set')]
488     l += [OptCheck('cut_attack_surface', 'grsecurity', 'DEBUG_KMEMLEAK', 'is not set')]
489     l += [OptCheck('cut_attack_surface', 'grsecurity', 'BINFMT_AOUT', 'is not set')]
490     l += [OptCheck('cut_attack_surface', 'grsecurity', 'KPROBES', 'is not set')] # refers to LOCKDOWN
491     l += [OptCheck('cut_attack_surface', 'grsecurity', 'UPROBES', 'is not set')]
492     l += [OptCheck('cut_attack_surface', 'grsecurity', 'GENERIC_TRACER', 'is not set')] # refers to LOCKDOWN
493     l += [OptCheck('cut_attack_surface', 'grsecurity', 'PROC_VMCORE', 'is not set')]
494     l += [OptCheck('cut_attack_surface', 'grsecurity', 'PROC_PAGE_MONITOR', 'is not set')]
495     l += [OptCheck('cut_attack_surface', 'grsecurity', 'USELIB', 'is not set')]
496     l += [OptCheck('cut_attack_surface', 'grsecurity', 'CHECKPOINT_RESTORE', 'is not set')]
497     l += [OptCheck('cut_attack_surface', 'grsecurity', 'USERFAULTFD', 'is not set')]
498     l += [OptCheck('cut_attack_surface', 'grsecurity', 'HWPOISON_INJECT', 'is not set')]
499     l += [OptCheck('cut_attack_surface', 'grsecurity', 'MEM_SOFT_DIRTY', 'is not set')]
500     l += [OptCheck('cut_attack_surface', 'grsecurity', 'DEVPORT', 'is not set')] # refers to LOCKDOWN
501     l += [OptCheck('cut_attack_surface', 'grsecurity', 'DEBUG_FS', 'is not set')] # refers to LOCKDOWN
502     l += [OptCheck('cut_attack_surface', 'grsecurity', 'NOTIFIER_ERROR_INJECTION', 'is not set')]
503     l += [AND(OptCheck('cut_attack_surface', 'grsecurity', 'X86_PTDUMP', 'is not set'),
504               OptCheck('cut_attack_surface', 'my', 'PTDUMP_DEBUGFS', 'is not set'))]
505
506     # 'cut_attack_surface', 'maintainer'
507     l += [OptCheck('cut_attack_surface', 'maintainer', 'DRM_LEGACY', 'is not set')]
508     l += [OptCheck('cut_attack_surface', 'maintainer', 'FB', 'is not set')]
509     l += [OptCheck('cut_attack_surface', 'maintainer', 'VT', 'is not set')]
510
511     # 'cut_attack_surface', 'grapheneos'
512     l += [OptCheck('cut_attack_surface', 'grapheneos', 'AIO', 'is not set')]
513
514     # 'cut_attack_surface', 'clipos'
515     l += [OptCheck('cut_attack_surface', 'clipos', 'STAGING', 'is not set')]
516     l += [OptCheck('cut_attack_surface', 'clipos', 'KSM', 'is not set')] # to prevent FLUSH+RELOAD attack
517 #   l += [OptCheck('cut_attack_surface', 'clipos', 'IKCONFIG', 'is not set')] # no, IKCONFIG is needed for this check :)
518     l += [OptCheck('cut_attack_surface', 'clipos', 'KALLSYMS', 'is not set')]
519     l += [OptCheck('cut_attack_surface', 'clipos', 'X86_VSYSCALL_EMULATION', 'is not set')]
520     l += [OptCheck('cut_attack_surface', 'clipos', 'MAGIC_SYSRQ', 'is not set')]
521     l += [OptCheck('cut_attack_surface', 'clipos', 'KEXEC_FILE', 'is not set')] # refers to LOCKDOWN (permissive)
522     l += [OptCheck('cut_attack_surface', 'clipos', 'USER_NS', 'is not set')] # user.max_user_namespaces=0
523     l += [OptCheck('cut_attack_surface', 'clipos', 'X86_MSR', 'is not set')] # refers to LOCKDOWN
524     l += [OptCheck('cut_attack_surface', 'clipos', 'X86_CPUID', 'is not set')]
525     l += [OptCheck('cut_attack_surface', 'clipos', 'IO_URING', 'is not set')]
526     l += [OptCheck('cut_attack_surface', 'clipos', 'X86_IOPL_IOPERM', 'is not set')] # refers to LOCKDOWN
527     l += [OptCheck('cut_attack_surface', 'clipos', 'ACPI_TABLE_UPGRADE', 'is not set')] # refers to LOCKDOWN
528     l += [OptCheck('cut_attack_surface', 'clipos', 'EFI_CUSTOM_SSDT_OVERLAYS', 'is not set')]
529     l += [AND(OptCheck('cut_attack_surface', 'clipos', 'LDISC_AUTOLOAD', 'is not set'),
530               PresenceCheck('LDISC_AUTOLOAD'))]
531     if arch in ('X86_64', 'X86_32'):
532         l += [OptCheck('cut_attack_surface', 'clipos', 'X86_INTEL_TSX_MODE_OFF', 'y')] # tsx=off
533
534     # 'cut_attack_surface', 'lockdown'
535     l += [OptCheck('cut_attack_surface', 'lockdown', 'EFI_TEST', 'is not set')] # refers to LOCKDOWN
536     l += [OptCheck('cut_attack_surface', 'lockdown', 'BPF_SYSCALL', 'is not set')] # refers to LOCKDOWN
537     l += [OptCheck('cut_attack_surface', 'lockdown', 'MMIOTRACE_TEST', 'is not set')] # refers to LOCKDOWN
538
539     # 'cut_attack_surface', 'my'
540     l += [OptCheck('cut_attack_surface', 'my', 'TRIM_UNUSED_KSYMS', 'y')]
541     l += [OptCheck('cut_attack_surface', 'my', 'MMIOTRACE', 'is not set')] # refers to LOCKDOWN (permissive)
542     l += [OptCheck('cut_attack_surface', 'my', 'LIVEPATCH', 'is not set')]
543     l += [OptCheck('cut_attack_surface', 'my', 'IP_DCCP', 'is not set')]
544     l += [OptCheck('cut_attack_surface', 'my', 'IP_SCTP', 'is not set')]
545     l += [OptCheck('cut_attack_surface', 'my', 'FTRACE', 'is not set')] # refers to LOCKDOWN
546     l += [OptCheck('cut_attack_surface', 'my', 'VIDEO_VIVID', 'is not set')]
547     l += [OptCheck('cut_attack_surface', 'my', 'INPUT_EVBUG', 'is not set')] # Can be used as a keylogger
548
549     # 'userspace_hardening'
550     if arch in ('X86_64', 'ARM64', 'X86_32'):
551         l += [OptCheck('userspace_hardening', 'defconfig', 'INTEGRITY', 'y')]
552     if arch == 'ARM':
553         l += [OptCheck('userspace_hardening', 'my', 'INTEGRITY', 'y')]
554     if arch == 'ARM64':
555         l += [OptCheck('userspace_hardening', 'defconfig', 'ARM64_MTE', 'y')]
556     if arch in ('ARM', 'X86_32'):
557         l += [OptCheck('userspace_hardening', 'defconfig', 'VMSPLIT_3G', 'y')]
558     if arch in ('X86_64', 'ARM64'):
559         l += [OptCheck('userspace_hardening', 'clipos', 'ARCH_MMAP_RND_BITS', '32')]
560     if arch in ('X86_32', 'ARM'):
561         l += [OptCheck('userspace_hardening', 'my', 'ARCH_MMAP_RND_BITS', '16')]
562
563 #   l += [OptCheck('feature_test', 'my', 'LKDTM', 'm')] # only for debugging!
564
565
566 def print_unknown_options(checklist, parsed_options):
567     known_options = []
568     for opt in checklist:
569         if hasattr(opt, 'opts'):
570             for o in opt.opts:
571                 if hasattr(o, 'name'):
572                     known_options.append(o.name)
573         else:
574             known_options.append(opt.name)
575     for option, value in parsed_options.items():
576         if option not in known_options:
577             print('[?] No rule for option {} ({})'.format(option, value))
578
579
580 def print_checklist(mode, checklist, with_results):
581     if mode == 'json':
582         opts = []
583         for o in checklist:
584             opt = ['CONFIG_'+o.name, o.expected, o.decision, o.reason]
585             if with_results:
586                 opt.append(o.result)
587             opts.append(opt)
588         print(json.dumps(opts))
589         return
590
591     # table header
592     sep_line_len = 91
593     if with_results:
594         sep_line_len += 30
595     print('=' * sep_line_len)
596     print('{:^45}|{:^13}|{:^10}|{:^20}'.format('option name', 'desired val', 'decision', 'reason'), end='')
597     if with_results:
598         print('|   {}'.format('check result'), end='')
599     print()
600     print('=' * sep_line_len)
601
602     # table contents
603     for opt in checklist:
604         if with_results:
605             if mode == 'show_ok':
606                 if not opt.result.startswith('OK'):
607                     continue
608             if mode == 'show_fail':
609                 if not opt.result.startswith('FAIL'):
610                     continue
611         opt.table_print(mode, with_results)
612         print()
613         if mode == 'verbose':
614             print('-' * sep_line_len)
615     print()
616
617     # final score
618     if with_results:
619         fail_count = len(list(filter(lambda opt: opt.result.startswith('FAIL'), checklist)))
620         fail_suppressed = ''
621         ok_count = len(list(filter(lambda opt: opt.result.startswith('OK'), checklist)))
622         ok_suppressed = ''
623         if mode == 'show_ok':
624             fail_suppressed = ' (suppressed in output)'
625         if mode == 'show_fail':
626             ok_suppressed = ' (suppressed in output)'
627         if mode != 'json':
628             print('[+] Config check is finished: \'OK\' - {}{} / \'FAIL\' - {}{}'.format(ok_count, ok_suppressed, fail_count, fail_suppressed))
629
630
631 def perform_check(opt, parsed_options, kernel_version):
632     if hasattr(opt, 'opts'):
633         # prepare ComplexOptCheck
634         for o in opt.opts:
635             if hasattr(o, 'opts'):
636                 # Recursion for nested ComplexOptChecks
637                 perform_check(o, parsed_options, kernel_version)
638             if hasattr(o, 'state'):
639                 o.state = parsed_options.get(o.name, None)
640             if hasattr(o, 'ver'):
641                 o.ver = kernel_version
642     else:
643         # prepare simple check, opt.state is mandatory
644         if not hasattr(opt, 'state'):
645             sys.exit('[!] ERROR: bad simple check {}'.format(vars(opt)))
646         opt.state = parsed_options.get(opt.name, None)
647     opt.check()
648
649
650 def perform_checks(checklist, parsed_options, kernel_version):
651     for opt in checklist:
652         perform_check(opt, parsed_options, kernel_version)
653
654
655 def parse_config_file(parsed_options, fname):
656     with open(fname, 'r') as f:
657         opt_is_on = re.compile("CONFIG_[a-zA-Z0-9_]*=[a-zA-Z0-9_\"]*")
658         opt_is_off = re.compile("# CONFIG_[a-zA-Z0-9_]* is not set")
659
660         for line in f.readlines():
661             line = line.strip()
662             option = None
663             value = None
664
665             if opt_is_on.match(line):
666                 option, value = line[7:].split('=', 1)
667             elif opt_is_off.match(line):
668                 option, value = line[9:].split(' ', 1)
669                 if value != 'is not set':
670                     sys.exit('[!] ERROR: bad disabled config option "{}"'.format(line))
671
672             if option in parsed_options:
673                 sys.exit('[!] ERROR: config option "{}" exists multiple times'.format(line))
674
675             if option:
676                 parsed_options[option] = value
677
678         return parsed_options
679
680
681 def main():
682     # Report modes:
683     #   * verbose mode for
684     #     - reporting about unknown kernel options in the config
685     #     - verbose printing of ComplexOptCheck items
686     #   * json mode for printing the results in JSON format
687     report_modes = ['verbose', 'json', 'show_ok', 'show_fail']
688     supported_archs = ['X86_64', 'X86_32', 'ARM64', 'ARM']
689     parser = ArgumentParser(prog='kconfig-hardened-check',
690                             description='A tool for checking the security hardening options of the Linux kernel')
691     parser.add_argument('--version', action='version', version='%(prog)s ' + __version__)
692     parser.add_argument('-p', '--print', choices=supported_archs,
693                         help='print security hardening preferences for the selected architecture')
694     parser.add_argument('-c', '--config',
695                         help='check the kernel config file against these preferences')
696     parser.add_argument('-m', '--mode', choices=report_modes,
697                         help='choose the report mode')
698     args = parser.parse_args()
699
700     mode = None
701     if args.mode:
702         mode = args.mode
703         if mode != 'json':
704             print("[+] Special report mode: {}".format(mode))
705
706     config_checklist = []
707
708     if args.config:
709         if mode != 'json':
710             print('[+] Config file to check: {}'.format(args.config))
711
712         arch, msg = detect_arch(args.config, supported_archs)
713         if not arch:
714             sys.exit('[!] ERROR: {}'.format(msg))
715         if mode != 'json':
716             print('[+] Detected architecture: {}'.format(arch))
717
718         kernel_version, msg = detect_version(args.config)
719         if not kernel_version:
720             sys.exit('[!] ERROR: {}'.format(msg))
721         if mode != 'json':
722             print('[+] Detected kernel version: {}.{}'.format(kernel_version[0], kernel_version[1]))
723
724         construct_checklist(config_checklist, arch)
725         parsed_options = OrderedDict()
726         parse_config_file(parsed_options, args.config)
727         perform_checks(config_checklist, parsed_options, kernel_version)
728
729         if mode == 'verbose':
730             print_unknown_options(config_checklist, parsed_options)
731         print_checklist(mode, config_checklist, True)
732
733         sys.exit(0)
734
735     if args.print:
736         if mode in ('show_ok', 'show_fail'):
737             sys.exit('[!] ERROR: please use "{}" mode for checking the kernel config'.format(mode))
738         arch = args.print
739         construct_checklist(config_checklist, arch)
740         if mode != 'json':
741             print('[+] Printing kernel security hardening preferences for {}...'.format(arch))
742         print_checklist(mode, config_checklist, False)
743         sys.exit(0)
744
745     parser.print_help()
746     sys.exit(0)
747
748 if __name__ == '__main__':
749     main()