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