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