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