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