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