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