Add hardware tag-based KASAN with arm64 Memory Tagging Extension
[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', 'UNMAP_KERNEL_AT_EL0', 'y')]
329         l += [OR(OptCheck('self_protection', 'defconfig', 'HARDEN_EL2_VECTORS', 'y'),
330                  AND(OptCheck('self_protection', 'defconfig', 'RANDOMIZE_BASE', 'y'),
331                      VerCheck((5, 9))))] # HARDEN_EL2_VECTORS was included in RANDOMIZE_BASE in v5.9
332         l += [OptCheck('self_protection', 'defconfig', 'RODATA_FULL_DEFAULT_ENABLED', 'y')]
333         l += [OptCheck('self_protection', 'defconfig', 'ARM64_PTR_AUTH', 'y')]
334         l += [OptCheck('self_protection', 'defconfig', 'ARM64_BTI_KERNEL', 'y')]
335         l += [OR(OptCheck('self_protection', 'defconfig', 'HARDEN_BRANCH_PREDICTOR', 'y'),
336                  VerCheck((5, 10)))] # HARDEN_BRANCH_PREDICTOR is enabled by default since v5.10
337         l += [OptCheck('self_protection', 'defconfig', 'ARM64_MTE', 'y')]
338     if arch == 'ARM':
339         l += [OptCheck('self_protection', 'defconfig', 'CPU_SW_DOMAIN_PAN', 'y')]
340         l += [OptCheck('self_protection', 'defconfig', 'HARDEN_BRANCH_PREDICTOR', 'y')]
341
342     # 'self_protection', 'kspp'
343     l += [OptCheck('self_protection', 'kspp', 'SECURITY_DMESG_RESTRICT', 'y')]
344     l += [OptCheck('self_protection', 'kspp', 'BUG_ON_DATA_CORRUPTION', 'y')]
345     l += [OptCheck('self_protection', 'kspp', 'DEBUG_WX', 'y')]
346     l += [OptCheck('self_protection', 'kspp', 'SCHED_STACK_END_CHECK', 'y')]
347     l += [OptCheck('self_protection', 'kspp', 'SLAB_FREELIST_HARDENED', 'y')]
348     l += [OptCheck('self_protection', 'kspp', 'SLAB_FREELIST_RANDOM', 'y')]
349     l += [OptCheck('self_protection', 'kspp', 'SHUFFLE_PAGE_ALLOCATOR', 'y')]
350     l += [OptCheck('self_protection', 'kspp', 'FORTIFY_SOURCE', 'y')]
351     l += [OptCheck('self_protection', 'kspp', 'DEBUG_LIST', 'y')]
352     l += [OptCheck('self_protection', 'kspp', 'DEBUG_SG', 'y')]
353     l += [OptCheck('self_protection', 'kspp', 'DEBUG_CREDENTIALS', 'y')]
354     l += [OptCheck('self_protection', 'kspp', 'DEBUG_NOTIFIERS', 'y')]
355     l += [OptCheck('self_protection', 'kspp', 'INIT_ON_ALLOC_DEFAULT_ON', 'y')]
356     l += [OptCheck('self_protection', 'kspp', 'GCC_PLUGIN_LATENT_ENTROPY', 'y')]
357     randstruct_is_set = OptCheck('self_protection', 'kspp', 'GCC_PLUGIN_RANDSTRUCT', 'y')
358     l += [randstruct_is_set]
359     hardened_usercopy_is_set = OptCheck('self_protection', 'kspp', 'HARDENED_USERCOPY', 'y')
360     l += [hardened_usercopy_is_set]
361     l += [AND(OptCheck('self_protection', 'kspp', 'HARDENED_USERCOPY_FALLBACK', 'is not set'),
362               hardened_usercopy_is_set)]
363     l += [OR(OptCheck('self_protection', 'kspp', 'MODULE_SIG', 'y'),
364              modules_not_set)]
365     l += [OR(OptCheck('self_protection', 'kspp', 'MODULE_SIG_ALL', 'y'),
366              modules_not_set)]
367     l += [OR(OptCheck('self_protection', 'kspp', 'MODULE_SIG_SHA512', 'y'),
368              modules_not_set)]
369     l += [OR(OptCheck('self_protection', 'kspp', 'MODULE_SIG_FORCE', 'y'),
370              modules_not_set)] # refers to LOCKDOWN
371     l += [OR(OptCheck('self_protection', 'kspp', 'INIT_STACK_ALL_ZERO', 'y'),
372              OptCheck('self_protection', 'kspp', 'GCC_PLUGIN_STRUCTLEAK_BYREF_ALL', 'y'))]
373     l += [OR(OptCheck('self_protection', 'kspp', 'INIT_ON_FREE_DEFAULT_ON', 'y'),
374              OptCheck('self_protection', 'kspp', 'PAGE_POISONING_ZERO', 'y'))]
375              # CONFIG_INIT_ON_FREE_DEFAULT_ON was added in v5.3.
376              # CONFIG_PAGE_POISONING_ZERO was removed in v5.11.
377              # Starting from v5.11 CONFIG_PAGE_POISONING unconditionally checks
378              # the 0xAA poison pattern on allocation.
379              # That brings higher performance penalty.
380     if arch in ('X86_64', 'ARM64', 'X86_32'):
381         stackleak_is_set = OptCheck('self_protection', 'kspp', 'GCC_PLUGIN_STACKLEAK', 'y')
382         l += [stackleak_is_set]
383     if arch in ('X86_64', 'X86_32'):
384         l += [OptCheck('self_protection', 'kspp', 'DEFAULT_MMAP_MIN_ADDR', '65536')]
385     if arch in ('ARM64', 'ARM'):
386         l += [OptCheck('self_protection', 'kspp', 'DEFAULT_MMAP_MIN_ADDR', '32768')]
387         l += [OptCheck('self_protection', 'kspp', 'SYN_COOKIES', 'y')] # another reason?
388     if arch == 'ARM64':
389         l += [OptCheck('self_protection', 'kspp', 'ARM64_SW_TTBR0_PAN', 'y')]
390     if arch == 'X86_32':
391         l += [OptCheck('self_protection', 'kspp', 'PAGE_TABLE_ISOLATION', 'y')]
392         l += [OptCheck('self_protection', 'kspp', 'HIGHMEM64G', 'y')]
393         l += [OptCheck('self_protection', 'kspp', 'X86_PAE', 'y')]
394
395     # 'self_protection', 'clipos'
396     l += [OptCheck('self_protection', 'clipos', 'DEBUG_VIRTUAL', 'y')]
397     l += [OptCheck('self_protection', 'clipos', 'STATIC_USERMODEHELPER', 'y')] # needs userspace support
398     l += [OptCheck('self_protection', 'clipos', 'EFI_DISABLE_PCI_DMA', 'y')]
399     l += [OptCheck('self_protection', 'clipos', 'SLAB_MERGE_DEFAULT', 'is not set')] # slab_nomerge
400     l += [OptCheck('self_protection', 'clipos', 'RANDOM_TRUST_BOOTLOADER', 'is not set')]
401     l += [OptCheck('self_protection', 'clipos', 'RANDOM_TRUST_CPU', 'is not set')]
402     l += [AND(OptCheck('self_protection', 'clipos', 'GCC_PLUGIN_RANDSTRUCT_PERFORMANCE', 'is not set'),
403               randstruct_is_set)]
404     if arch in ('X86_64', 'ARM64', 'X86_32'):
405         l += [AND(OptCheck('self_protection', 'clipos', 'STACKLEAK_METRICS', 'is not set'),
406                   stackleak_is_set)]
407         l += [AND(OptCheck('self_protection', 'clipos', 'STACKLEAK_RUNTIME_DISABLE', 'is not set'),
408                   stackleak_is_set)]
409     if arch in ('X86_64', 'X86_32'):
410         l += [AND(OptCheck('self_protection', 'clipos', 'INTEL_IOMMU_DEFAULT_ON', 'y'),
411                   iommu_support_is_set)]
412     if arch == 'X86_64':
413         l += [AND(OptCheck('self_protection', 'clipos', 'INTEL_IOMMU_SVM', 'y'),
414                   iommu_support_is_set)]
415     if arch == 'X86_32':
416         l += [AND(OptCheck('self_protection', 'clipos', 'INTEL_IOMMU', 'y'),
417                   iommu_support_is_set)]
418
419     # 'self_protection', 'my'
420     l += [AND(OptCheck('self_protection', 'my', 'UBSAN_BOUNDS', 'y'),
421               OptCheck('self_protection', 'my', 'UBSAN_MISC', 'is not set'),
422               OptCheck('self_protection', 'my', 'UBSAN_TRAP', 'y'))]
423     l += [OptCheck('self_protection', 'my', 'RESET_ATTACK_MITIGATION', 'y')] # needs userspace support (systemd)
424     if arch == 'X86_64':
425         l += [AND(OptCheck('self_protection', 'my', 'AMD_IOMMU_V2', 'y'),
426                   iommu_support_is_set)]
427     if arch == 'ARM64':
428         l += [OptCheck('self_protection', 'my', 'SHADOW_CALL_STACK', 'y')] # depends on clang, maybe it's alternative to STACKPROTECTOR_STRONG
429         l += [OptCheck('self_protection', 'my', 'KASAN_HW_TAGS', 'y')]
430
431     # 'security_policy'
432     if arch in ('X86_64', 'ARM64', 'X86_32'):
433         l += [OptCheck('security_policy', 'defconfig', 'SECURITY', 'y')] # and choose your favourite LSM
434     if arch == 'ARM':
435         l += [OptCheck('security_policy', 'kspp', 'SECURITY', 'y')] # and choose your favourite LSM
436     l += [OptCheck('security_policy', 'kspp', 'SECURITY_YAMA', 'y')]
437     l += [OR(OptCheck('security_policy', 'my', 'SECURITY_WRITABLE_HOOKS', 'is not set'),
438              OptCheck('security_policy', 'kspp', 'SECURITY_SELINUX_DISABLE', 'is not set'))]
439     l += [OptCheck('security_policy', 'clipos', 'SECURITY_LOCKDOWN_LSM', 'y')]
440     l += [OptCheck('security_policy', 'clipos', 'SECURITY_LOCKDOWN_LSM_EARLY', 'y')]
441     l += [OptCheck('security_policy', 'clipos', 'LOCK_DOWN_KERNEL_FORCE_CONFIDENTIALITY', 'y')]
442     l += [OptCheck('security_policy', 'my', 'SECURITY_SAFESETID', 'y')]
443     loadpin_is_set = OptCheck('security_policy', 'my', 'SECURITY_LOADPIN', 'y')
444     l += [loadpin_is_set] # needs userspace support
445     l += [AND(OptCheck('security_policy', 'my', 'SECURITY_LOADPIN_ENFORCE', 'y'),
446               loadpin_is_set)]
447
448     # 'cut_attack_surface', 'defconfig'
449     l += [OptCheck('cut_attack_surface', 'defconfig', 'SECCOMP', 'y')]
450     l += [OptCheck('cut_attack_surface', 'defconfig', 'SECCOMP_FILTER', 'y')]
451     if arch in ('X86_64', 'ARM64', 'X86_32'):
452         l += [OR(OptCheck('cut_attack_surface', 'defconfig', 'STRICT_DEVMEM', 'y'),
453                  devmem_not_set)] # refers to LOCKDOWN
454
455     # 'cut_attack_surface', 'kspp'
456     l += [OptCheck('cut_attack_surface', 'kspp', 'ACPI_CUSTOM_METHOD', 'is not set')] # refers to LOCKDOWN
457     l += [OptCheck('cut_attack_surface', 'kspp', 'COMPAT_BRK', 'is not set')]
458     l += [OptCheck('cut_attack_surface', 'kspp', 'DEVKMEM', 'is not set')] # refers to LOCKDOWN
459     l += [OptCheck('cut_attack_surface', 'kspp', 'COMPAT_VDSO', 'is not set')]
460     l += [OptCheck('cut_attack_surface', 'kspp', 'BINFMT_MISC', 'is not set')]
461     l += [OptCheck('cut_attack_surface', 'kspp', 'INET_DIAG', 'is not set')]
462     l += [OptCheck('cut_attack_surface', 'kspp', 'KEXEC', 'is not set')] # refers to LOCKDOWN
463     l += [OptCheck('cut_attack_surface', 'kspp', 'PROC_KCORE', 'is not set')] # refers to LOCKDOWN
464     l += [OptCheck('cut_attack_surface', 'kspp', 'LEGACY_PTYS', 'is not set')]
465     l += [OptCheck('cut_attack_surface', 'kspp', 'HIBERNATION', 'is not set')] # refers to LOCKDOWN
466     l += [OptCheck('cut_attack_surface', 'kspp', 'IA32_EMULATION', 'is not set')]
467     l += [OptCheck('cut_attack_surface', 'kspp', 'X86_X32', 'is not set')]
468     l += [OptCheck('cut_attack_surface', 'kspp', 'MODIFY_LDT_SYSCALL', 'is not set')]
469     l += [OptCheck('cut_attack_surface', 'kspp', 'OABI_COMPAT', 'is not set')]
470     l += [modules_not_set]
471     l += [devmem_not_set]
472     l += [OR(OptCheck('cut_attack_surface', 'kspp', 'IO_STRICT_DEVMEM', 'y'),
473              devmem_not_set)] # refers to LOCKDOWN
474     if arch == 'ARM':
475         l += [OR(OptCheck('cut_attack_surface', 'kspp', 'STRICT_DEVMEM', 'y'),
476                  devmem_not_set)] # refers to LOCKDOWN
477     if arch == 'X86_64':
478         l += [OptCheck('cut_attack_surface', 'kspp', 'LEGACY_VSYSCALL_NONE', 'y')] # 'vsyscall=none'
479
480     # 'cut_attack_surface', 'grsecurity'
481     l += [OptCheck('cut_attack_surface', 'grsecurity', 'ZSMALLOC_STAT', 'is not set')]
482     l += [OptCheck('cut_attack_surface', 'grsecurity', 'PAGE_OWNER', 'is not set')]
483     l += [OptCheck('cut_attack_surface', 'grsecurity', 'DEBUG_KMEMLEAK', 'is not set')]
484     l += [OptCheck('cut_attack_surface', 'grsecurity', 'BINFMT_AOUT', 'is not set')]
485     l += [OptCheck('cut_attack_surface', 'grsecurity', 'KPROBES', 'is not set')] # refers to LOCKDOWN
486     l += [OptCheck('cut_attack_surface', 'grsecurity', 'UPROBES', 'is not set')]
487     l += [OptCheck('cut_attack_surface', 'grsecurity', 'GENERIC_TRACER', 'is not set')] # refers to LOCKDOWN
488     l += [OptCheck('cut_attack_surface', 'grsecurity', 'PROC_VMCORE', 'is not set')]
489     l += [OptCheck('cut_attack_surface', 'grsecurity', 'PROC_PAGE_MONITOR', 'is not set')]
490     l += [OptCheck('cut_attack_surface', 'grsecurity', 'USELIB', 'is not set')]
491     l += [OptCheck('cut_attack_surface', 'grsecurity', 'CHECKPOINT_RESTORE', 'is not set')]
492     l += [OptCheck('cut_attack_surface', 'grsecurity', 'USERFAULTFD', 'is not set')]
493     l += [OptCheck('cut_attack_surface', 'grsecurity', 'HWPOISON_INJECT', 'is not set')]
494     l += [OptCheck('cut_attack_surface', 'grsecurity', 'MEM_SOFT_DIRTY', 'is not set')]
495     l += [OptCheck('cut_attack_surface', 'grsecurity', 'DEVPORT', 'is not set')] # refers to LOCKDOWN
496     l += [OptCheck('cut_attack_surface', 'grsecurity', 'DEBUG_FS', 'is not set')] # refers to LOCKDOWN
497     l += [OptCheck('cut_attack_surface', 'grsecurity', 'NOTIFIER_ERROR_INJECTION', 'is not set')]
498     l += [AND(OptCheck('cut_attack_surface', 'grsecurity', 'X86_PTDUMP', 'is not set'),
499               OptCheck('cut_attack_surface', 'my', 'PTDUMP_DEBUGFS', 'is not set'))]
500
501     # 'cut_attack_surface', 'maintainer'
502     l += [OptCheck('cut_attack_surface', 'maintainer', 'DRM_LEGACY', 'is not set')]
503     l += [OptCheck('cut_attack_surface', 'maintainer', 'FB', 'is not set')]
504     l += [OptCheck('cut_attack_surface', 'maintainer', 'VT', 'is not set')]
505
506     # 'cut_attack_surface', 'grapheneos'
507     l += [OptCheck('cut_attack_surface', 'grapheneos', 'AIO', 'is not set')]
508
509     # 'cut_attack_surface', 'clipos'
510     l += [OptCheck('cut_attack_surface', 'clipos', 'STAGING', 'is not set')]
511     l += [OptCheck('cut_attack_surface', 'clipos', 'KSM', 'is not set')] # to prevent FLUSH+RELOAD attack
512 #   l += [OptCheck('cut_attack_surface', 'clipos', 'IKCONFIG', 'is not set')] # no, IKCONFIG is needed for this check :)
513     l += [OptCheck('cut_attack_surface', 'clipos', 'KALLSYMS', 'is not set')]
514     l += [OptCheck('cut_attack_surface', 'clipos', 'X86_VSYSCALL_EMULATION', 'is not set')]
515     l += [OptCheck('cut_attack_surface', 'clipos', 'MAGIC_SYSRQ', 'is not set')]
516     l += [OptCheck('cut_attack_surface', 'clipos', 'KEXEC_FILE', 'is not set')] # refers to LOCKDOWN (permissive)
517     l += [OptCheck('cut_attack_surface', 'clipos', 'USER_NS', 'is not set')] # user.max_user_namespaces=0
518     l += [OptCheck('cut_attack_surface', 'clipos', 'X86_MSR', 'is not set')] # refers to LOCKDOWN
519     l += [OptCheck('cut_attack_surface', 'clipos', 'X86_CPUID', 'is not set')]
520     l += [OptCheck('cut_attack_surface', 'clipos', 'IO_URING', 'is not set')]
521     l += [OptCheck('cut_attack_surface', 'clipos', 'X86_IOPL_IOPERM', 'is not set')] # refers to LOCKDOWN
522     l += [OptCheck('cut_attack_surface', 'clipos', 'ACPI_TABLE_UPGRADE', 'is not set')] # refers to LOCKDOWN
523     l += [OptCheck('cut_attack_surface', 'clipos', 'EFI_CUSTOM_SSDT_OVERLAYS', 'is not set')]
524     l += [AND(OptCheck('cut_attack_surface', 'clipos', 'LDISC_AUTOLOAD', 'is not set'),
525               PresenceCheck('LDISC_AUTOLOAD'))]
526     if arch in ('X86_64', 'X86_32'):
527         l += [OptCheck('cut_attack_surface', 'clipos', 'X86_INTEL_TSX_MODE_OFF', 'y')] # tsx=off
528
529     # 'cut_attack_surface', 'lockdown'
530     l += [OptCheck('cut_attack_surface', 'lockdown', 'EFI_TEST', 'is not set')] # refers to LOCKDOWN
531     l += [OptCheck('cut_attack_surface', 'lockdown', 'BPF_SYSCALL', 'is not set')] # refers to LOCKDOWN
532     l += [OptCheck('cut_attack_surface', 'lockdown', 'MMIOTRACE_TEST', 'is not set')] # refers to LOCKDOWN
533
534     # 'cut_attack_surface', 'my'
535     l += [OptCheck('cut_attack_surface', 'my', 'TRIM_UNUSED_KSYMS', 'y')]
536     l += [OptCheck('cut_attack_surface', 'my', 'MMIOTRACE', 'is not set')] # refers to LOCKDOWN (permissive)
537     l += [OptCheck('cut_attack_surface', 'my', 'LIVEPATCH', 'is not set')]
538     l += [OptCheck('cut_attack_surface', 'my', 'IP_DCCP', 'is not set')]
539     l += [OptCheck('cut_attack_surface', 'my', 'IP_SCTP', 'is not set')]
540     l += [OptCheck('cut_attack_surface', 'my', 'FTRACE', 'is not set')] # refers to LOCKDOWN
541     l += [OptCheck('cut_attack_surface', 'my', 'VIDEO_VIVID', 'is not set')]
542     l += [OptCheck('cut_attack_surface', 'my', 'INPUT_EVBUG', 'is not set')] # Can be used as a keylogger
543
544     # 'userspace_hardening'
545     if arch in ('X86_64', 'ARM64', 'X86_32'):
546         l += [OptCheck('userspace_hardening', 'defconfig', 'INTEGRITY', 'y')]
547     if arch == 'ARM':
548         l += [OptCheck('userspace_hardening', 'my', 'INTEGRITY', 'y')]
549     if arch == 'ARM64':
550         l += [OptCheck('userspace_hardening', 'defconfig', 'ARM64_MTE', 'y')]
551     if arch in ('ARM', 'X86_32'):
552         l += [OptCheck('userspace_hardening', 'defconfig', 'VMSPLIT_3G', 'y')]
553     if arch in ('X86_64', 'ARM64'):
554         l += [OptCheck('userspace_hardening', 'clipos', 'ARCH_MMAP_RND_BITS', '32')]
555     if arch in ('X86_32', 'ARM'):
556         l += [OptCheck('userspace_hardening', 'my', 'ARCH_MMAP_RND_BITS', '16')]
557
558 #   l += [OptCheck('feature_test', 'my', 'LKDTM', 'm')] # only for debugging!
559
560
561 def print_unknown_options(checklist, parsed_options):
562     known_options = []
563     for opt in checklist:
564         if hasattr(opt, 'opts'):
565             for o in opt.opts:
566                 if hasattr(o, 'name'):
567                     known_options.append(o.name)
568         else:
569             known_options.append(opt.name)
570     for option, value in parsed_options.items():
571         if option not in known_options:
572             print('[?] No rule for option {} ({})'.format(option, value))
573
574
575 def print_checklist(mode, checklist, with_results):
576     if mode == 'json':
577         opts = []
578         for o in checklist:
579             opt = ['CONFIG_'+o.name, o.expected, o.decision, o.reason]
580             if with_results:
581                 opt.append(o.result)
582             opts.append(opt)
583         print(json.dumps(opts))
584         return
585
586     # table header
587     sep_line_len = 91
588     if with_results:
589         sep_line_len += 30
590     print('=' * sep_line_len)
591     print('{:^45}|{:^13}|{:^10}|{:^20}'.format('option name', 'desired val', 'decision', 'reason'), end='')
592     if with_results:
593         print('|   {}'.format('check result'), end='')
594     print()
595     print('=' * sep_line_len)
596
597     # table contents
598     for opt in checklist:
599         if with_results:
600             if mode == 'show_ok':
601                 if not opt.result.startswith('OK'):
602                     continue
603             if mode == 'show_fail':
604                 if not opt.result.startswith('FAIL'):
605                     continue
606         opt.table_print(mode, with_results)
607         print()
608         if mode == 'verbose':
609             print('-' * sep_line_len)
610     print()
611
612     # final score
613     if with_results:
614         fail_count = len(list(filter(lambda opt: opt.result.startswith('FAIL'), checklist)))
615         fail_suppressed = ''
616         ok_count = len(list(filter(lambda opt: opt.result.startswith('OK'), checklist)))
617         ok_suppressed = ''
618         if mode == 'show_ok':
619             fail_suppressed = ' (suppressed in output)'
620         if mode == 'show_fail':
621             ok_suppressed = ' (suppressed in output)'
622         if mode != 'json':
623             print('[+] Config check is finished: \'OK\' - {}{} / \'FAIL\' - {}{}'.format(ok_count, ok_suppressed, fail_count, fail_suppressed))
624
625
626 def perform_check(opt, parsed_options, kernel_version):
627     if hasattr(opt, 'opts'):
628         # prepare ComplexOptCheck
629         for o in opt.opts:
630             if hasattr(o, 'opts'):
631                 # Recursion for nested ComplexOptChecks
632                 perform_check(o, parsed_options, kernel_version)
633             if hasattr(o, 'state'):
634                 o.state = parsed_options.get(o.name, None)
635             if hasattr(o, 'ver'):
636                 o.ver = kernel_version
637     else:
638         # prepare simple check, opt.state is mandatory
639         if not hasattr(opt, 'state'):
640             sys.exit('[!] ERROR: bad simple check {}'.format(vars(opt)))
641         opt.state = parsed_options.get(opt.name, None)
642     opt.check()
643
644
645 def perform_checks(checklist, parsed_options, kernel_version):
646     for opt in checklist:
647         perform_check(opt, parsed_options, kernel_version)
648
649
650 def parse_config_file(parsed_options, fname):
651     with open(fname, 'r') as f:
652         opt_is_on = re.compile("CONFIG_[a-zA-Z0-9_]*=[a-zA-Z0-9_\"]*")
653         opt_is_off = re.compile("# CONFIG_[a-zA-Z0-9_]* is not set")
654
655         for line in f.readlines():
656             line = line.strip()
657             option = None
658             value = None
659
660             if opt_is_on.match(line):
661                 option, value = line[7:].split('=', 1)
662             elif opt_is_off.match(line):
663                 option, value = line[9:].split(' ', 1)
664                 if value != 'is not set':
665                     sys.exit('[!] ERROR: bad disabled config option "{}"'.format(line))
666
667             if option in parsed_options:
668                 sys.exit('[!] ERROR: config option "{}" exists multiple times'.format(line))
669
670             if option:
671                 parsed_options[option] = value
672
673         return parsed_options
674
675
676 def main():
677     # Report modes:
678     #   * verbose mode for
679     #     - reporting about unknown kernel options in the config
680     #     - verbose printing of ComplexOptCheck items
681     #   * json mode for printing the results in JSON format
682     report_modes = ['verbose', 'json', 'show_ok', 'show_fail']
683     supported_archs = ['X86_64', 'X86_32', 'ARM64', 'ARM']
684     parser = ArgumentParser(prog='kconfig-hardened-check',
685                             description='A tool for checking the security hardening options of the Linux kernel')
686     parser.add_argument('--version', action='version', version='%(prog)s ' + __version__)
687     parser.add_argument('-p', '--print', choices=supported_archs,
688                         help='print security hardening preferences for the selected architecture')
689     parser.add_argument('-c', '--config',
690                         help='check the kernel config file against these preferences')
691     parser.add_argument('-m', '--mode', choices=report_modes,
692                         help='choose the report mode')
693     args = parser.parse_args()
694
695     mode = None
696     if args.mode:
697         mode = args.mode
698         if mode != 'json':
699             print("[+] Special report mode: {}".format(mode))
700
701     config_checklist = []
702
703     if args.config:
704         if mode != 'json':
705             print('[+] Config file to check: {}'.format(args.config))
706
707         arch, msg = detect_arch(args.config, supported_archs)
708         if not arch:
709             sys.exit('[!] ERROR: {}'.format(msg))
710         if mode != 'json':
711             print('[+] Detected architecture: {}'.format(arch))
712
713         kernel_version, msg = detect_version(args.config)
714         if not kernel_version:
715             sys.exit('[!] ERROR: {}'.format(msg))
716         if mode != 'json':
717             print('[+] Detected kernel version: {}.{}'.format(kernel_version[0], kernel_version[1]))
718
719         construct_checklist(config_checklist, arch)
720         parsed_options = OrderedDict()
721         parse_config_file(parsed_options, args.config)
722         perform_checks(config_checklist, parsed_options, kernel_version)
723
724         if mode == 'verbose':
725             print_unknown_options(config_checklist, parsed_options)
726         print_checklist(mode, config_checklist, True)
727
728         sys.exit(0)
729
730     if args.print:
731         if mode in ('show_ok', 'show_fail'):
732             sys.exit('[!] ERROR: please use "{}" mode for checking the kernel config'.format(mode))
733         arch = args.print
734         construct_checklist(config_checklist, arch)
735         if mode != 'json':
736             print('[+] Printing kernel security hardening preferences for {}...'.format(arch))
737         print_checklist(mode, config_checklist, False)
738         sys.exit(0)
739
740     parser.print_help()
741     sys.exit(0)
742
743 if __name__ == '__main__':
744     main()