caedb97320c52e40b5f3a73ca9500788812a4924
[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
432     # 'security_policy'
433     if arch in ('X86_64', 'ARM64', 'X86_32'):
434         l += [OptCheck('security_policy', 'defconfig', 'SECURITY', 'y')] # and choose your favourite LSM
435     if arch == 'ARM':
436         l += [OptCheck('security_policy', 'kspp', 'SECURITY', 'y')] # and choose your favourite LSM
437     l += [OptCheck('security_policy', 'kspp', 'SECURITY_YAMA', 'y')]
438     l += [OR(OptCheck('security_policy', 'my', 'SECURITY_WRITABLE_HOOKS', 'is not set'),
439              OptCheck('security_policy', 'kspp', 'SECURITY_SELINUX_DISABLE', 'is not set'))]
440     l += [OptCheck('security_policy', 'clipos', 'SECURITY_LOCKDOWN_LSM', 'y')]
441     l += [OptCheck('security_policy', 'clipos', 'SECURITY_LOCKDOWN_LSM_EARLY', 'y')]
442     l += [OptCheck('security_policy', 'clipos', 'LOCK_DOWN_KERNEL_FORCE_CONFIDENTIALITY', 'y')]
443     l += [OptCheck('security_policy', 'my', 'SECURITY_SAFESETID', 'y')]
444     loadpin_is_set = OptCheck('security_policy', 'my', 'SECURITY_LOADPIN', 'y')
445     l += [loadpin_is_set] # needs userspace support
446     l += [AND(OptCheck('security_policy', 'my', 'SECURITY_LOADPIN_ENFORCE', 'y'),
447               loadpin_is_set)]
448
449     # 'cut_attack_surface', 'defconfig'
450     l += [OptCheck('cut_attack_surface', 'defconfig', 'SECCOMP', 'y')]
451     l += [OptCheck('cut_attack_surface', 'defconfig', 'SECCOMP_FILTER', 'y')]
452     if arch in ('X86_64', 'ARM64', 'X86_32'):
453         l += [OR(OptCheck('cut_attack_surface', 'defconfig', 'STRICT_DEVMEM', 'y'),
454                  devmem_not_set)] # refers to LOCKDOWN
455
456     # 'cut_attack_surface', 'kspp'
457     l += [OptCheck('cut_attack_surface', 'kspp', 'ACPI_CUSTOM_METHOD', 'is not set')] # refers to LOCKDOWN
458     l += [OptCheck('cut_attack_surface', 'kspp', 'COMPAT_BRK', 'is not set')]
459     l += [OptCheck('cut_attack_surface', 'kspp', 'DEVKMEM', 'is not set')] # refers to LOCKDOWN
460     l += [OptCheck('cut_attack_surface', 'kspp', 'COMPAT_VDSO', 'is not set')]
461     l += [OptCheck('cut_attack_surface', 'kspp', 'BINFMT_MISC', 'is not set')]
462     l += [OptCheck('cut_attack_surface', 'kspp', 'INET_DIAG', 'is not set')]
463     l += [OptCheck('cut_attack_surface', 'kspp', 'KEXEC', 'is not set')] # refers to LOCKDOWN
464     l += [OptCheck('cut_attack_surface', 'kspp', 'PROC_KCORE', 'is not set')] # refers to LOCKDOWN
465     l += [OptCheck('cut_attack_surface', 'kspp', 'LEGACY_PTYS', 'is not set')]
466     l += [OptCheck('cut_attack_surface', 'kspp', 'HIBERNATION', 'is not set')] # refers to LOCKDOWN
467     l += [OptCheck('cut_attack_surface', 'kspp', 'IA32_EMULATION', 'is not set')]
468     l += [OptCheck('cut_attack_surface', 'kspp', 'X86_X32', 'is not set')]
469     l += [OptCheck('cut_attack_surface', 'kspp', 'MODIFY_LDT_SYSCALL', 'is not set')]
470     l += [OptCheck('cut_attack_surface', 'kspp', 'OABI_COMPAT', 'is not set')]
471     l += [modules_not_set]
472     l += [devmem_not_set]
473     l += [OR(OptCheck('cut_attack_surface', 'kspp', 'IO_STRICT_DEVMEM', 'y'),
474              devmem_not_set)] # refers to LOCKDOWN
475     if arch == 'ARM':
476         l += [OR(OptCheck('cut_attack_surface', 'kspp', 'STRICT_DEVMEM', 'y'),
477                  devmem_not_set)] # refers to LOCKDOWN
478     if arch == 'X86_64':
479         l += [OptCheck('cut_attack_surface', 'kspp', 'LEGACY_VSYSCALL_NONE', 'y')] # 'vsyscall=none'
480
481     # 'cut_attack_surface', 'grsecurity'
482     l += [OptCheck('cut_attack_surface', 'grsecurity', 'ZSMALLOC_STAT', 'is not set')]
483     l += [OptCheck('cut_attack_surface', 'grsecurity', 'PAGE_OWNER', 'is not set')]
484     l += [OptCheck('cut_attack_surface', 'grsecurity', 'DEBUG_KMEMLEAK', 'is not set')]
485     l += [OptCheck('cut_attack_surface', 'grsecurity', 'BINFMT_AOUT', 'is not set')]
486     l += [OptCheck('cut_attack_surface', 'grsecurity', 'KPROBES', 'is not set')] # refers to LOCKDOWN
487     l += [OptCheck('cut_attack_surface', 'grsecurity', 'UPROBES', 'is not set')]
488     l += [OptCheck('cut_attack_surface', 'grsecurity', 'GENERIC_TRACER', 'is not set')] # refers to LOCKDOWN
489     l += [OptCheck('cut_attack_surface', 'grsecurity', 'PROC_VMCORE', 'is not set')]
490     l += [OptCheck('cut_attack_surface', 'grsecurity', 'PROC_PAGE_MONITOR', 'is not set')]
491     l += [OptCheck('cut_attack_surface', 'grsecurity', 'USELIB', 'is not set')]
492     l += [OptCheck('cut_attack_surface', 'grsecurity', 'CHECKPOINT_RESTORE', 'is not set')]
493     l += [OptCheck('cut_attack_surface', 'grsecurity', 'USERFAULTFD', 'is not set')]
494     l += [OptCheck('cut_attack_surface', 'grsecurity', 'HWPOISON_INJECT', 'is not set')]
495     l += [OptCheck('cut_attack_surface', 'grsecurity', 'MEM_SOFT_DIRTY', 'is not set')]
496     l += [OptCheck('cut_attack_surface', 'grsecurity', 'DEVPORT', 'is not set')] # refers to LOCKDOWN
497     l += [OptCheck('cut_attack_surface', 'grsecurity', 'DEBUG_FS', 'is not set')] # refers to LOCKDOWN
498     l += [OptCheck('cut_attack_surface', 'grsecurity', 'NOTIFIER_ERROR_INJECTION', 'is not set')]
499     l += [AND(OptCheck('cut_attack_surface', 'grsecurity', 'X86_PTDUMP', 'is not set'),
500               OptCheck('cut_attack_surface', 'my', 'PTDUMP_DEBUGFS', 'is not set'))]
501
502     # 'cut_attack_surface', 'maintainer'
503     l += [OptCheck('cut_attack_surface', 'maintainer', 'DRM_LEGACY', 'is not set')]
504     l += [OptCheck('cut_attack_surface', 'maintainer', 'FB', 'is not set')]
505     l += [OptCheck('cut_attack_surface', 'maintainer', 'VT', 'is not set')]
506
507     # 'cut_attack_surface', 'grapheneos'
508     l += [OptCheck('cut_attack_surface', 'grapheneos', 'AIO', 'is not set')]
509
510     # 'cut_attack_surface', 'clipos'
511     l += [OptCheck('cut_attack_surface', 'clipos', 'STAGING', 'is not set')]
512     l += [OptCheck('cut_attack_surface', 'clipos', 'KSM', 'is not set')] # to prevent FLUSH+RELOAD attack
513 #   l += [OptCheck('cut_attack_surface', 'clipos', 'IKCONFIG', 'is not set')] # no, IKCONFIG is needed for this check :)
514     l += [OptCheck('cut_attack_surface', 'clipos', 'KALLSYMS', 'is not set')]
515     l += [OptCheck('cut_attack_surface', 'clipos', 'X86_VSYSCALL_EMULATION', 'is not set')]
516     l += [OptCheck('cut_attack_surface', 'clipos', 'MAGIC_SYSRQ', 'is not set')]
517     l += [OptCheck('cut_attack_surface', 'clipos', 'KEXEC_FILE', 'is not set')] # refers to LOCKDOWN (permissive)
518     l += [OptCheck('cut_attack_surface', 'clipos', 'USER_NS', 'is not set')] # user.max_user_namespaces=0
519     l += [OptCheck('cut_attack_surface', 'clipos', 'X86_MSR', 'is not set')] # refers to LOCKDOWN
520     l += [OptCheck('cut_attack_surface', 'clipos', 'X86_CPUID', 'is not set')]
521     l += [OptCheck('cut_attack_surface', 'clipos', 'IO_URING', 'is not set')]
522     l += [OptCheck('cut_attack_surface', 'clipos', 'X86_IOPL_IOPERM', 'is not set')] # refers to LOCKDOWN
523     l += [OptCheck('cut_attack_surface', 'clipos', 'ACPI_TABLE_UPGRADE', 'is not set')] # refers to LOCKDOWN
524     l += [OptCheck('cut_attack_surface', 'clipos', 'EFI_CUSTOM_SSDT_OVERLAYS', 'is not set')]
525     l += [AND(OptCheck('cut_attack_surface', 'clipos', 'LDISC_AUTOLOAD', 'is not set'),
526               PresenceCheck('LDISC_AUTOLOAD'))]
527     if arch in ('X86_64', 'X86_32'):
528         l += [OptCheck('cut_attack_surface', 'clipos', 'X86_INTEL_TSX_MODE_OFF', 'y')] # tsx=off
529
530     # 'cut_attack_surface', 'lockdown'
531     l += [OptCheck('cut_attack_surface', 'lockdown', 'EFI_TEST', 'is not set')] # refers to LOCKDOWN
532     l += [OptCheck('cut_attack_surface', 'lockdown', 'BPF_SYSCALL', 'is not set')] # refers to LOCKDOWN
533     l += [OptCheck('cut_attack_surface', 'lockdown', 'MMIOTRACE_TEST', 'is not set')] # refers to LOCKDOWN
534
535     # 'cut_attack_surface', 'my'
536     l += [OptCheck('cut_attack_surface', 'my', 'TRIM_UNUSED_KSYMS', 'y')]
537     l += [OptCheck('cut_attack_surface', 'my', 'MMIOTRACE', 'is not set')] # refers to LOCKDOWN (permissive)
538     l += [OptCheck('cut_attack_surface', 'my', 'LIVEPATCH', 'is not set')]
539     l += [OptCheck('cut_attack_surface', 'my', 'IP_DCCP', 'is not set')]
540     l += [OptCheck('cut_attack_surface', 'my', 'IP_SCTP', 'is not set')]
541     l += [OptCheck('cut_attack_surface', 'my', 'FTRACE', 'is not set')] # refers to LOCKDOWN
542     l += [OptCheck('cut_attack_surface', 'my', 'VIDEO_VIVID', 'is not set')]
543     l += [OptCheck('cut_attack_surface', 'my', 'INPUT_EVBUG', 'is not set')] # Can be used as a keylogger
544
545     # 'userspace_hardening'
546     if arch in ('X86_64', 'ARM64', 'X86_32'):
547         l += [OptCheck('userspace_hardening', 'defconfig', 'INTEGRITY', 'y')]
548     if arch == 'ARM':
549         l += [OptCheck('userspace_hardening', 'my', 'INTEGRITY', 'y')]
550     if arch == 'ARM64':
551         l += [OptCheck('userspace_hardening', 'defconfig', 'ARM64_MTE', 'y')]
552     if arch in ('ARM', 'X86_32'):
553         l += [OptCheck('userspace_hardening', 'defconfig', 'VMSPLIT_3G', 'y')]
554     if arch in ('X86_64', 'ARM64'):
555         l += [OptCheck('userspace_hardening', 'clipos', 'ARCH_MMAP_RND_BITS', '32')]
556     if arch in ('X86_32', 'ARM'):
557         l += [OptCheck('userspace_hardening', 'my', 'ARCH_MMAP_RND_BITS', '16')]
558
559 #   l += [OptCheck('feature_test', 'my', 'LKDTM', 'm')] # only for debugging!
560
561
562 def print_unknown_options(checklist, parsed_options):
563     known_options = []
564     for opt in checklist:
565         if hasattr(opt, 'opts'):
566             for o in opt.opts:
567                 if hasattr(o, 'name'):
568                     known_options.append(o.name)
569         else:
570             known_options.append(opt.name)
571     for option, value in parsed_options.items():
572         if option not in known_options:
573             print('[?] No rule for option {} ({})'.format(option, value))
574
575
576 def print_checklist(mode, checklist, with_results):
577     if mode == 'json':
578         opts = []
579         for o in checklist:
580             opt = ['CONFIG_'+o.name, o.expected, o.decision, o.reason]
581             if with_results:
582                 opt.append(o.result)
583             opts.append(opt)
584         print(json.dumps(opts))
585         return
586
587     # table header
588     sep_line_len = 91
589     if with_results:
590         sep_line_len += 30
591     print('=' * sep_line_len)
592     print('{:^45}|{:^13}|{:^10}|{:^20}'.format('option name', 'desired val', 'decision', 'reason'), end='')
593     if with_results:
594         print('|   {}'.format('check result'), end='')
595     print()
596     print('=' * sep_line_len)
597
598     # table contents
599     for opt in checklist:
600         if with_results:
601             if mode == 'show_ok':
602                 if not opt.result.startswith('OK'):
603                     continue
604             if mode == 'show_fail':
605                 if not opt.result.startswith('FAIL'):
606                     continue
607         opt.table_print(mode, with_results)
608         print()
609         if mode == 'verbose':
610             print('-' * sep_line_len)
611     print()
612
613     # final score
614     if with_results:
615         fail_count = len(list(filter(lambda opt: opt.result.startswith('FAIL'), checklist)))
616         fail_suppressed = ''
617         ok_count = len(list(filter(lambda opt: opt.result.startswith('OK'), checklist)))
618         ok_suppressed = ''
619         if mode == 'show_ok':
620             fail_suppressed = ' (suppressed in output)'
621         if mode == 'show_fail':
622             ok_suppressed = ' (suppressed in output)'
623         if mode != 'json':
624             print('[+] Config check is finished: \'OK\' - {}{} / \'FAIL\' - {}{}'.format(ok_count, ok_suppressed, fail_count, fail_suppressed))
625
626
627 def perform_check(opt, parsed_options, kernel_version):
628     if hasattr(opt, 'opts'):
629         # prepare ComplexOptCheck
630         for o in opt.opts:
631             if hasattr(o, 'opts'):
632                 # Recursion for nested ComplexOptChecks
633                 perform_check(o, parsed_options, kernel_version)
634             if hasattr(o, 'state'):
635                 o.state = parsed_options.get(o.name, None)
636             if hasattr(o, 'ver'):
637                 o.ver = kernel_version
638     else:
639         # prepare simple check, opt.state is mandatory
640         if not hasattr(opt, 'state'):
641             sys.exit('[!] ERROR: bad simple check {}'.format(vars(opt)))
642         opt.state = parsed_options.get(opt.name, None)
643     opt.check()
644
645
646 def perform_checks(checklist, parsed_options, kernel_version):
647     for opt in checklist:
648         perform_check(opt, parsed_options, kernel_version)
649
650
651 def parse_config_file(parsed_options, fname):
652     with open(fname, 'r') as f:
653         opt_is_on = re.compile("CONFIG_[a-zA-Z0-9_]*=[a-zA-Z0-9_\"]*")
654         opt_is_off = re.compile("# CONFIG_[a-zA-Z0-9_]* is not set")
655
656         for line in f.readlines():
657             line = line.strip()
658             option = None
659             value = None
660
661             if opt_is_on.match(line):
662                 option, value = line[7:].split('=', 1)
663             elif opt_is_off.match(line):
664                 option, value = line[9:].split(' ', 1)
665                 if value != 'is not set':
666                     sys.exit('[!] ERROR: bad disabled config option "{}"'.format(line))
667
668             if option in parsed_options:
669                 sys.exit('[!] ERROR: config option "{}" exists multiple times'.format(line))
670
671             if option:
672                 parsed_options[option] = value
673
674         return parsed_options
675
676
677 def main():
678     # Report modes:
679     #   * verbose mode for
680     #     - reporting about unknown kernel options in the config
681     #     - verbose printing of ComplexOptCheck items
682     #   * json mode for printing the results in JSON format
683     report_modes = ['verbose', 'json', 'show_ok', 'show_fail']
684     supported_archs = ['X86_64', 'X86_32', 'ARM64', 'ARM']
685     parser = ArgumentParser(prog='kconfig-hardened-check',
686                             description='A tool for checking the security hardening options of the Linux kernel')
687     parser.add_argument('--version', action='version', version='%(prog)s ' + __version__)
688     parser.add_argument('-p', '--print', choices=supported_archs,
689                         help='print security hardening preferences for the selected architecture')
690     parser.add_argument('-c', '--config',
691                         help='check the kernel config file against these preferences')
692     parser.add_argument('-m', '--mode', choices=report_modes,
693                         help='choose the report mode')
694     args = parser.parse_args()
695
696     mode = None
697     if args.mode:
698         mode = args.mode
699         if mode != 'json':
700             print("[+] Special report mode: {}".format(mode))
701
702     config_checklist = []
703
704     if args.config:
705         if mode != 'json':
706             print('[+] Config file to check: {}'.format(args.config))
707
708         arch, msg = detect_arch(args.config, supported_archs)
709         if not arch:
710             sys.exit('[!] ERROR: {}'.format(msg))
711         if mode != 'json':
712             print('[+] Detected architecture: {}'.format(arch))
713
714         kernel_version, msg = detect_version(args.config)
715         if not kernel_version:
716             sys.exit('[!] ERROR: {}'.format(msg))
717         if mode != 'json':
718             print('[+] Detected kernel version: {}.{}'.format(kernel_version[0], kernel_version[1]))
719
720         construct_checklist(config_checklist, arch)
721         parsed_options = OrderedDict()
722         parse_config_file(parsed_options, args.config)
723         perform_checks(config_checklist, parsed_options, kernel_version)
724
725         if mode == 'verbose':
726             print_unknown_options(config_checklist, parsed_options)
727         print_checklist(mode, config_checklist, True)
728
729         sys.exit(0)
730
731     if args.print:
732         if mode in ('show_ok', 'show_fail'):
733             sys.exit('[!] ERROR: please use "{}" mode for checking the kernel config'.format(mode))
734         arch = args.print
735         construct_checklist(config_checklist, arch)
736         if mode != 'json':
737             print('[+] Printing kernel security hardening preferences for {}...'.format(arch))
738         print_checklist(mode, config_checklist, False)
739         sys.exit(0)
740
741     parser.print_help()
742     sys.exit(0)
743
744 if __name__ == '__main__':
745     main()