Save the list of disabled mitigations of CPU vulnerabilities (for history)
[kconfig-hardened-check.git] / kconfig_hardened_check / __init__.py
1 #!/usr/bin/python3
2
3 #
4 # This tool helps me to check Linux kernel options against
5 # my security 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 #    iommu=force (does it help against DMA attacks?)
15 #
16 # The list of disabled mitigations of CPU vulnerabilities:
17 #   mitigations=off
18 #   pti=off
19 #   spectre_v2=off
20 #   spectre_v2_user=off
21 #   spec_store_bypass_disable=off
22 #   l1tf=off
23 #   mds=off
24 #   tsx_async_abort=off
25 #   srbds=off
26 #   mmio_stale_data=off
27 #   retbleed=off
28 #     nopti
29 #     nokaslr
30 #     nospectre_v1
31 #     nospectre_v2
32 #     nospectre_bhb
33 #     nospec_store_bypass_disable
34 #       kpti=0
35 #       ssbd=force-off
36 #       nosmt (enabled)
37 #
38 #    Hardware tag-based KASAN with arm64 Memory Tagging Extension (MTE):
39 #           kasan=on
40 #           kasan.stacktrace=off
41 #           kasan.fault=panic
42 #
43 # N.B. Hardening sysctls:
44 #    kernel.kptr_restrict=2 (or 1?)
45 #    kernel.dmesg_restrict=1 (also see the kconfig option)
46 #    kernel.perf_event_paranoid=3
47 #    kernel.kexec_load_disabled=1
48 #    kernel.yama.ptrace_scope=3
49 #    user.max_user_namespaces=0
50 #    what about bpf_jit_enable?
51 #    kernel.unprivileged_bpf_disabled=1
52 #    net.core.bpf_jit_harden=2
53 #    vm.unprivileged_userfaultfd=0
54 #        (at first, it disabled unprivileged userfaultfd,
55 #         and since v5.11 it enables unprivileged userfaultfd for user-mode only)
56 #    vm.mmap_min_addr has a good value
57 #    dev.tty.ldisc_autoload=0
58 #    fs.protected_symlinks=1
59 #    fs.protected_hardlinks=1
60 #    fs.protected_fifos=2
61 #    fs.protected_regular=2
62 #    fs.suid_dumpable=0
63 #    kernel.modules_disabled=1
64 #    kernel.randomize_va_space = 2
65
66
67 # pylint: disable=missing-module-docstring,missing-class-docstring,missing-function-docstring
68 # pylint: disable=line-too-long,invalid-name,too-many-branches,too-many-statements
69
70
71 import sys
72 from argparse import ArgumentParser
73 from collections import OrderedDict
74 import re
75 import json
76 from .__about__ import __version__
77
78 SIMPLE_OPTION_TYPES = ('kconfig', 'version', 'cmdline')
79
80 class OptCheck:
81     def __init__(self, reason, decision, name, expected):
82         assert(name and name == name.strip() and len(name.split()) == 1), \
83                'invalid name "{}" for {}'.format(name, self.__class__.__name__)
84         self.name = name
85
86         assert(decision and decision == decision.strip() and len(decision.split()) == 1), \
87                'invalid decision "{}" for "{}" check'.format(decision, name)
88         self.decision = decision
89
90         assert(reason and reason == reason.strip() and len(reason.split()) == 1), \
91                'invalid reason "{}" for "{}" check'.format(reason, name)
92         self.reason = reason
93
94         assert(expected and expected == expected.strip()), \
95                'invalid expected value "{}" for "{}" check (1)'.format(expected, name)
96         val_len = len(expected.split())
97         if val_len == 3:
98             assert(expected == 'is not set' or expected == 'is not off'), \
99                    'invalid expected value "{}" for "{}" check (2)'.format(expected, name)
100         elif val_len == 2:
101             assert(expected == 'is present'), \
102                    'invalid expected value "{}" for "{}" check (3)'.format(expected, name)
103         else:
104             assert(val_len == 1), \
105                    'invalid expected value "{}" for "{}" check (4)'.format(expected, name)
106         self.expected = expected
107
108         self.state = None
109         self.result = None
110
111     @property
112     def type(self):
113         return None
114
115     def check(self):
116         # handle the 'is present' check
117         if self.expected == 'is present':
118             if self.state is None:
119                 self.result = 'FAIL: is not present'
120             else:
121                 self.result = 'OK: is present'
122             return
123
124         # handle the 'is not off' option check
125         if self.expected == 'is not off':
126             if self.state == 'off':
127                 self.result = 'FAIL: is off'
128             if self.state == '0':
129                 self.result = 'FAIL: is off, "0"'
130             elif self.state is None:
131                 self.result = 'FAIL: is off, not found'
132             else:
133                 self.result = 'OK: is not off, "' + self.state + '"'
134             return
135
136         # handle the option value check
137         if self.expected == self.state:
138             self.result = 'OK'
139         elif self.state is None:
140             if self.expected == 'is not set':
141                 self.result = 'OK: is not found'
142             else:
143                 self.result = 'FAIL: is not found'
144         else:
145             self.result = 'FAIL: "' + self.state + '"'
146
147     def table_print(self, _mode, with_results):
148         print('{:<40}|{:^7}|{:^12}|{:^10}|{:^18}'.format(self.name, self.type, self.expected, self.decision, self.reason), end='')
149         if with_results:
150             print('| {}'.format(self.result), end='')
151
152     def json_dump(self, with_results):
153         dump = [self.name, self.type, self.expected, self.decision, self.reason]
154         if with_results:
155             dump.append(self.result)
156         return dump
157
158
159 class KconfigCheck(OptCheck):
160     def __init__(self, *args, **kwargs):
161         super().__init__(*args, **kwargs)
162         self.name = 'CONFIG_' + self.name
163
164     @property
165     def type(self):
166         return 'kconfig'
167
168
169 class CmdlineCheck(OptCheck):
170     @property
171     def type(self):
172         return 'cmdline'
173
174
175 class VersionCheck:
176     def __init__(self, ver_expected):
177         assert(ver_expected and isinstance(ver_expected, tuple) and len(ver_expected) == 2), \
178                'invalid version "{}" for VersionCheck'.format(ver_expected)
179         self.ver_expected = ver_expected
180         self.ver = ()
181         self.result = None
182
183     @property
184     def type(self):
185         return 'version'
186
187     def check(self):
188         if self.ver[0] > self.ver_expected[0]:
189             self.result = 'OK: version >= ' + str(self.ver_expected[0]) + '.' + str(self.ver_expected[1])
190             return
191         if self.ver[0] < self.ver_expected[0]:
192             self.result = 'FAIL: version < ' + str(self.ver_expected[0]) + '.' + str(self.ver_expected[1])
193             return
194         if self.ver[1] >= self.ver_expected[1]:
195             self.result = 'OK: version >= ' + str(self.ver_expected[0]) + '.' + str(self.ver_expected[1])
196             return
197         self.result = 'FAIL: version < ' + str(self.ver_expected[0]) + '.' + str(self.ver_expected[1])
198
199     def table_print(self, _mode, with_results):
200         ver_req = 'kernel version >= ' + str(self.ver_expected[0]) + '.' + str(self.ver_expected[1])
201         print('{:<91}'.format(ver_req), end='')
202         if with_results:
203             print('| {}'.format(self.result), end='')
204
205
206 class ComplexOptCheck:
207     def __init__(self, *opts):
208         self.opts = opts
209         assert(self.opts), \
210                'empty {} check'.format(self.__class__.__name__)
211         assert(len(self.opts) != 1), \
212                 'useless {} check: {}'.format(self.__class__.__name__, opts)
213         assert(isinstance(opts[0], (KconfigCheck, CmdlineCheck))), \
214                'invalid {} check: {}'.format(self.__class__.__name__, opts)
215         self.result = None
216
217     @property
218     def type(self):
219         return 'complex'
220
221     @property
222     def name(self):
223         return self.opts[0].name
224
225     @property
226     def expected(self):
227         return self.opts[0].expected
228
229     def table_print(self, mode, with_results):
230         if mode == 'verbose':
231             print('    {:87}'.format('<<< ' + self.__class__.__name__ + ' >>>'), end='')
232             if with_results:
233                 print('| {}'.format(self.result), end='')
234             for o in self.opts:
235                 print()
236                 o.table_print(mode, with_results)
237         else:
238             o = self.opts[0]
239             o.table_print(mode, False)
240             if with_results:
241                 print('| {}'.format(self.result), end='')
242
243     def json_dump(self, with_results):
244         dump = self.opts[0].json_dump(False)
245         if with_results:
246             dump.append(self.result)
247         return dump
248
249
250 class OR(ComplexOptCheck):
251     # self.opts[0] is the option that this OR-check is about.
252     # Use cases:
253     #     OR(<X_is_hardened>, <X_is_disabled>)
254     #     OR(<X_is_hardened>, <old_X_is_hardened>)
255     def check(self):
256         for i, opt in enumerate(self.opts):
257             opt.check()
258             if opt.result.startswith('OK'):
259                 self.result = opt.result
260                 # Add more info for additional checks:
261                 if i != 0:
262                     if opt.result == 'OK':
263                         self.result = 'OK: {} is "{}"'.format(opt.name, opt.expected)
264                     elif opt.result == 'OK: is not found':
265                         self.result = 'OK: {} is not found'.format(opt.name)
266                     elif opt.result == 'OK: is present':
267                         self.result = 'OK: {} is present'.format(opt.name)
268                     elif opt.result.startswith('OK: is not off'):
269                         self.result = 'OK: {} is not off'.format(opt.name)
270                     else:
271                         # VersionCheck provides enough info
272                         assert(opt.result.startswith('OK: version')), \
273                                'unexpected OK description "{}"'.format(opt.result)
274                 return
275         self.result = self.opts[0].result
276
277
278 class AND(ComplexOptCheck):
279     # self.opts[0] is the option that this AND-check is about.
280     # Use cases:
281     #     AND(<suboption>, <main_option>)
282     #       Suboption is not checked if checking of the main_option is failed.
283     #     AND(<X_is_disabled>, <old_X_is_disabled>)
284     def check(self):
285         for i, opt in reversed(list(enumerate(self.opts))):
286             opt.check()
287             if i == 0:
288                 self.result = opt.result
289                 return
290             if not opt.result.startswith('OK'):
291                 # This FAIL is caused by additional checks,
292                 # and not by the main option that this AND-check is about.
293                 # Describe the reason of the FAIL.
294                 if opt.result.startswith('FAIL: \"') or opt.result == 'FAIL: is not found':
295                     self.result = 'FAIL: {} is not "{}"'.format(opt.name, opt.expected)
296                 elif opt.result == 'FAIL: is not present':
297                     self.result = 'FAIL: {} is not present'.format(opt.name)
298                 elif opt.result == 'FAIL: is off' or opt.result == 'FAIL: is off, "0"':
299                     self.result = 'FAIL: {} is off'.format(opt.name)
300                 elif opt.result == 'FAIL: is off, not found':
301                     self.result = 'FAIL: {} is off, not found'.format(opt.name)
302                 else:
303                     # VersionCheck provides enough info
304                     self.result = opt.result
305                     assert(opt.result.startswith('FAIL: version')), \
306                            'unexpected FAIL description "{}"'.format(opt.result)
307                 return
308
309
310 def detect_arch(fname, archs):
311     with open(fname, 'r') as f:
312         arch_pattern = re.compile("CONFIG_[a-zA-Z0-9_]*=y")
313         arch = None
314         for line in f.readlines():
315             if arch_pattern.match(line):
316                 option, _ = line[7:].split('=', 1)
317                 if option in archs:
318                     if not arch:
319                         arch = option
320                     else:
321                         return None, 'more than one supported architecture is detected'
322         if not arch:
323             return None, 'failed to detect architecture'
324         return arch, 'OK'
325
326
327 def detect_kernel_version(fname):
328     with open(fname, 'r') as f:
329         ver_pattern = re.compile("# Linux/.* Kernel Configuration")
330         for line in f.readlines():
331             if ver_pattern.match(line):
332                 line = line.strip()
333                 parts = line.split()
334                 ver_str = parts[2]
335                 ver_numbers = ver_str.split('.')
336                 if len(ver_numbers) < 3 or not ver_numbers[0].isdigit() or not ver_numbers[1].isdigit():
337                     msg = 'failed to parse the version "' + ver_str + '"'
338                     return None, msg
339                 return (int(ver_numbers[0]), int(ver_numbers[1])), None
340         return None, 'no kernel version detected'
341
342
343 def detect_compiler(fname):
344     gcc_version = None
345     clang_version = None
346     with open(fname, 'r') as f:
347         gcc_version_pattern = re.compile("CONFIG_GCC_VERSION=[0-9]*")
348         clang_version_pattern = re.compile("CONFIG_CLANG_VERSION=[0-9]*")
349         for line in f.readlines():
350             if gcc_version_pattern.match(line):
351                 gcc_version = line[19:-1]
352             if clang_version_pattern.match(line):
353                 clang_version = line[21:-1]
354     if not gcc_version or not clang_version:
355         return None, 'no CONFIG_GCC_VERSION or CONFIG_CLANG_VERSION'
356     if gcc_version == '0' and clang_version != '0':
357         return 'CLANG ' + clang_version, 'OK'
358     if gcc_version != '0' and clang_version == '0':
359         return 'GCC ' + gcc_version, 'OK'
360     sys.exit('[!] ERROR: invalid GCC_VERSION and CLANG_VERSION: {} {}'.format(gcc_version, clang_version))
361
362
363 def add_kconfig_checks(l, arch):
364     # Calling the KconfigCheck class constructor:
365     #     KconfigCheck(reason, decision, name, expected)
366     #
367     # [!] Don't add CmdlineChecks in add_kconfig_checks() to avoid wrong results
368     #     when the tool doesn't check the cmdline.
369
370     efi_not_set = KconfigCheck('-', '-', 'EFI', 'is not set')
371     cc_is_gcc = KconfigCheck('-', '-', 'CC_IS_GCC', 'y') # exists since v4.18
372     cc_is_clang = KconfigCheck('-', '-', 'CC_IS_CLANG', 'y') # exists since v4.18
373
374     modules_not_set = KconfigCheck('cut_attack_surface', 'kspp', 'MODULES', 'is not set')
375     devmem_not_set = KconfigCheck('cut_attack_surface', 'kspp', 'DEVMEM', 'is not set') # refers to LOCKDOWN
376     bpf_syscall_not_set = KconfigCheck('cut_attack_surface', 'lockdown', 'BPF_SYSCALL', 'is not set') # refers to LOCKDOWN
377
378     # 'self_protection', 'defconfig'
379     l += [KconfigCheck('self_protection', 'defconfig', 'BUG', 'y')]
380     l += [KconfigCheck('self_protection', 'defconfig', 'SLUB_DEBUG', 'y')]
381     l += [KconfigCheck('self_protection', 'defconfig', 'THREAD_INFO_IN_TASK', 'y')]
382     gcc_plugins_support_is_set = KconfigCheck('self_protection', 'defconfig', 'GCC_PLUGINS', 'y')
383     l += [gcc_plugins_support_is_set]
384     iommu_support_is_set = KconfigCheck('self_protection', 'defconfig', 'IOMMU_SUPPORT', 'y')
385     l += [iommu_support_is_set] # is needed for mitigating DMA attacks
386     l += [OR(KconfigCheck('self_protection', 'defconfig', 'STACKPROTECTOR', 'y'),
387              KconfigCheck('self_protection', 'defconfig', 'CC_STACKPROTECTOR', 'y'),
388              KconfigCheck('self_protection', 'defconfig', 'CC_STACKPROTECTOR_REGULAR', 'y'),
389              KconfigCheck('self_protection', 'defconfig', 'CC_STACKPROTECTOR_AUTO', 'y'),
390              KconfigCheck('self_protection', 'defconfig', 'CC_STACKPROTECTOR_STRONG', 'y'))]
391     l += [OR(KconfigCheck('self_protection', 'defconfig', 'STACKPROTECTOR_STRONG', 'y'),
392              KconfigCheck('self_protection', 'defconfig', 'CC_STACKPROTECTOR_STRONG', 'y'))]
393     l += [OR(KconfigCheck('self_protection', 'defconfig', 'STRICT_KERNEL_RWX', 'y'),
394              KconfigCheck('self_protection', 'defconfig', 'DEBUG_RODATA', 'y'))] # before v4.11
395     l += [OR(KconfigCheck('self_protection', 'defconfig', 'STRICT_MODULE_RWX', 'y'),
396              KconfigCheck('self_protection', 'defconfig', 'DEBUG_SET_MODULE_RONX', 'y'),
397              modules_not_set)] # DEBUG_SET_MODULE_RONX was before v4.11
398     l += [OR(KconfigCheck('self_protection', 'defconfig', 'REFCOUNT_FULL', 'y'),
399              VersionCheck((5, 5)))] # REFCOUNT_FULL is enabled by default since v5.5
400     if arch in ('X86_64', 'ARM64', 'X86_32'):
401         l += [KconfigCheck('self_protection', 'defconfig', 'RANDOMIZE_BASE', 'y')]
402     if arch in ('X86_64', 'ARM64'):
403         l += [KconfigCheck('self_protection', 'defconfig', 'VMAP_STACK', 'y')]
404     if arch in ('X86_64', 'X86_32'):
405         l += [KconfigCheck('self_protection', 'defconfig', 'X86_MCE', 'y')]
406         l += [KconfigCheck('self_protection', 'defconfig', 'X86_MCE_INTEL', 'y')]
407         l += [KconfigCheck('self_protection', 'defconfig', 'X86_MCE_AMD', 'y')]
408         l += [KconfigCheck('self_protection', 'defconfig', 'MICROCODE', 'y')] # is needed for mitigating CPU bugs
409         l += [KconfigCheck('self_protection', 'defconfig', 'RETPOLINE', 'y')]
410         l += [KconfigCheck('self_protection', 'defconfig', 'SYN_COOKIES', 'y')] # another reason?
411         l += [OR(KconfigCheck('self_protection', 'defconfig', 'X86_SMAP', 'y'),
412                  VersionCheck((5, 19)))] # X86_SMAP is enabled by default since v5.19
413         l += [OR(KconfigCheck('self_protection', 'defconfig', 'X86_UMIP', 'y'),
414                  KconfigCheck('self_protection', 'defconfig', 'X86_INTEL_UMIP', 'y'))]
415     if arch in ('ARM64', 'ARM'):
416         l += [KconfigCheck('self_protection', 'defconfig', 'STACKPROTECTOR_PER_TASK', 'y')]
417     if arch == 'X86_64':
418         l += [KconfigCheck('self_protection', 'defconfig', 'PAGE_TABLE_ISOLATION', 'y')]
419         l += [KconfigCheck('self_protection', 'defconfig', 'RANDOMIZE_MEMORY', 'y')]
420         l += [AND(KconfigCheck('self_protection', 'defconfig', 'INTEL_IOMMU', 'y'),
421                   iommu_support_is_set)]
422         l += [AND(KconfigCheck('self_protection', 'defconfig', 'AMD_IOMMU', 'y'),
423                   iommu_support_is_set)]
424     if arch == 'ARM64':
425         l += [KconfigCheck('self_protection', 'defconfig', 'ARM64_PAN', 'y')]
426         l += [KconfigCheck('self_protection', 'defconfig', 'ARM64_EPAN', 'y')]
427         l += [KconfigCheck('self_protection', 'defconfig', 'UNMAP_KERNEL_AT_EL0', 'y')]
428         l += [KconfigCheck('self_protection', 'defconfig', 'ARM64_E0PD', 'y')]
429         l += [KconfigCheck('self_protection', 'defconfig', 'RODATA_FULL_DEFAULT_ENABLED', 'y')]
430         l += [KconfigCheck('self_protection', 'defconfig', 'ARM64_PTR_AUTH_KERNEL', 'y')]
431         l += [KconfigCheck('self_protection', 'defconfig', 'ARM64_BTI_KERNEL', 'y')]
432         l += [KconfigCheck('self_protection', 'defconfig', 'MITIGATE_SPECTRE_BRANCH_HISTORY', 'y')]
433         l += [KconfigCheck('self_protection', 'defconfig', 'ARM64_MTE', 'y')]
434         l += [KconfigCheck('self_protection', 'defconfig', 'RANDOMIZE_MODULE_REGION_FULL', 'y')]
435         l += [OR(KconfigCheck('self_protection', 'defconfig', 'HARDEN_EL2_VECTORS', 'y'),
436                  AND(KconfigCheck('self_protection', 'defconfig', 'RANDOMIZE_BASE', 'y'),
437                      VersionCheck((5, 9))))] # HARDEN_EL2_VECTORS was included in RANDOMIZE_BASE in v5.9
438         l += [OR(KconfigCheck('self_protection', 'defconfig', 'HARDEN_BRANCH_PREDICTOR', 'y'),
439                  VersionCheck((5, 10)))] # HARDEN_BRANCH_PREDICTOR is enabled by default since v5.10
440     if arch == 'ARM':
441         l += [KconfigCheck('self_protection', 'defconfig', 'CPU_SW_DOMAIN_PAN', 'y')]
442         l += [KconfigCheck('self_protection', 'defconfig', 'HARDEN_BRANCH_PREDICTOR', 'y')]
443         l += [KconfigCheck('self_protection', 'defconfig', 'HARDEN_BRANCH_HISTORY', 'y')]
444
445     # 'self_protection', 'kspp'
446     l += [KconfigCheck('self_protection', 'kspp', 'BUG_ON_DATA_CORRUPTION', 'y')]
447     l += [KconfigCheck('self_protection', 'kspp', 'DEBUG_WX', 'y')]
448     l += [KconfigCheck('self_protection', 'kspp', 'SCHED_STACK_END_CHECK', 'y')]
449     l += [KconfigCheck('self_protection', 'kspp', 'SLAB_FREELIST_HARDENED', 'y')]
450     l += [KconfigCheck('self_protection', 'kspp', 'SLAB_FREELIST_RANDOM', 'y')]
451     l += [KconfigCheck('self_protection', 'kspp', 'SHUFFLE_PAGE_ALLOCATOR', 'y')]
452     l += [KconfigCheck('self_protection', 'kspp', 'FORTIFY_SOURCE', 'y')]
453     l += [KconfigCheck('self_protection', 'kspp', 'DEBUG_LIST', 'y')]
454     l += [KconfigCheck('self_protection', 'kspp', 'DEBUG_VIRTUAL', 'y')]
455     l += [KconfigCheck('self_protection', 'kspp', 'DEBUG_SG', 'y')]
456     l += [KconfigCheck('self_protection', 'kspp', 'DEBUG_CREDENTIALS', 'y')]
457     l += [KconfigCheck('self_protection', 'kspp', 'DEBUG_NOTIFIERS', 'y')]
458     l += [KconfigCheck('self_protection', 'kspp', 'INIT_ON_ALLOC_DEFAULT_ON', 'y')]
459     l += [KconfigCheck('self_protection', 'kspp', 'KFENCE', 'y')]
460     l += [KconfigCheck('self_protection', 'kspp', 'WERROR', 'y')]
461     l += [KconfigCheck('self_protection', 'kspp', 'IOMMU_DEFAULT_DMA_STRICT', 'y')]
462     l += [KconfigCheck('self_protection', 'kspp', 'IOMMU_DEFAULT_PASSTHROUGH', 'is not set')] # true if IOMMU_DEFAULT_DMA_STRICT is set
463     l += [KconfigCheck('self_protection', 'kspp', 'ZERO_CALL_USED_REGS', 'y')]
464     l += [KconfigCheck('self_protection', 'kspp', 'HW_RANDOM_TPM', 'y')]
465     l += [KconfigCheck('self_protection', 'kspp', 'STATIC_USERMODEHELPER', 'y')] # needs userspace support
466     l += [KconfigCheck('self_protection', 'kspp', 'SCHED_CORE', 'y')]
467     randstruct_is_set = OR(KconfigCheck('self_protection', 'kspp', 'RANDSTRUCT_FULL', 'y'),
468                            KconfigCheck('self_protection', 'kspp', 'GCC_PLUGIN_RANDSTRUCT', 'y'))
469     l += [randstruct_is_set]
470     l += [AND(KconfigCheck('self_protection', 'kspp', 'RANDSTRUCT_PERFORMANCE', 'is not set'),
471               KconfigCheck('self_protection', 'kspp', 'GCC_PLUGIN_RANDSTRUCT_PERFORMANCE', 'is not set'),
472               randstruct_is_set)]
473     hardened_usercopy_is_set = KconfigCheck('self_protection', 'kspp', 'HARDENED_USERCOPY', 'y')
474     l += [hardened_usercopy_is_set]
475     l += [AND(KconfigCheck('self_protection', 'kspp', 'HARDENED_USERCOPY_FALLBACK', 'is not set'),
476               hardened_usercopy_is_set)]
477     l += [AND(KconfigCheck('self_protection', 'kspp', 'HARDENED_USERCOPY_PAGESPAN', 'is not set'),
478               hardened_usercopy_is_set)]
479     l += [AND(KconfigCheck('self_protection', 'kspp', 'GCC_PLUGIN_LATENT_ENTROPY', 'y'),
480               gcc_plugins_support_is_set)]
481     l += [OR(KconfigCheck('self_protection', 'kspp', 'MODULE_SIG', 'y'),
482              modules_not_set)]
483     l += [OR(KconfigCheck('self_protection', 'kspp', 'MODULE_SIG_ALL', 'y'),
484              modules_not_set)]
485     l += [OR(KconfigCheck('self_protection', 'kspp', 'MODULE_SIG_SHA512', 'y'),
486              modules_not_set)]
487     l += [OR(KconfigCheck('self_protection', 'kspp', 'MODULE_SIG_FORCE', 'y'),
488              modules_not_set)] # refers to LOCKDOWN
489     l += [OR(KconfigCheck('self_protection', 'kspp', 'INIT_STACK_ALL_ZERO', 'y'),
490              KconfigCheck('self_protection', 'kspp', 'GCC_PLUGIN_STRUCTLEAK_BYREF_ALL', 'y'))]
491     l += [OR(KconfigCheck('self_protection', 'kspp', 'INIT_ON_FREE_DEFAULT_ON', 'y'),
492              KconfigCheck('self_protection', 'kspp', 'PAGE_POISONING_ZERO', 'y'))]
493              # CONFIG_INIT_ON_FREE_DEFAULT_ON was added in v5.3.
494              # CONFIG_PAGE_POISONING_ZERO was removed in v5.11.
495              # Starting from v5.11 CONFIG_PAGE_POISONING unconditionally checks
496              # the 0xAA poison pattern on allocation.
497              # That brings higher performance penalty.
498     l += [OR(KconfigCheck('self_protection', 'kspp', 'EFI_DISABLE_PCI_DMA', 'y'),
499              efi_not_set)]
500     l += [OR(KconfigCheck('self_protection', 'kspp', 'RESET_ATTACK_MITIGATION', 'y'),
501              efi_not_set)] # needs userspace support (systemd)
502     ubsan_bounds_is_set = KconfigCheck('self_protection', 'kspp', 'UBSAN_BOUNDS', 'y')
503     l += [ubsan_bounds_is_set]
504     l += [OR(KconfigCheck('self_protection', 'kspp', 'UBSAN_LOCAL_BOUNDS', 'y'),
505              AND(ubsan_bounds_is_set,
506                  cc_is_gcc))]
507     l += [AND(KconfigCheck('self_protection', 'kspp', 'UBSAN_TRAP', 'y'),
508               ubsan_bounds_is_set,
509               KconfigCheck('self_protection', 'kspp', 'UBSAN_SHIFT', 'is not set'),
510               KconfigCheck('self_protection', 'kspp', 'UBSAN_DIV_ZERO', 'is not set'),
511               KconfigCheck('self_protection', 'kspp', 'UBSAN_UNREACHABLE', 'is not set'),
512               KconfigCheck('self_protection', 'kspp', 'UBSAN_BOOL', 'is not set'),
513               KconfigCheck('self_protection', 'kspp', 'UBSAN_ENUM', 'is not set'),
514               KconfigCheck('self_protection', 'kspp', 'UBSAN_ALIGNMENT', 'is not set'))] # only array index bounds checking with traps
515     if arch in ('X86_64', 'ARM64', 'X86_32'):
516         l += [AND(KconfigCheck('self_protection', 'kspp', 'UBSAN_SANITIZE_ALL', 'y'),
517                   ubsan_bounds_is_set)] # ARCH_HAS_UBSAN_SANITIZE_ALL is not enabled for ARM
518         stackleak_is_set = KconfigCheck('self_protection', 'kspp', 'GCC_PLUGIN_STACKLEAK', 'y')
519         l += [AND(stackleak_is_set, gcc_plugins_support_is_set)]
520         l += [AND(KconfigCheck('self_protection', 'kspp', 'STACKLEAK_METRICS', 'is not set'),
521                   stackleak_is_set,
522                   gcc_plugins_support_is_set)]
523         l += [AND(KconfigCheck('self_protection', 'kspp', 'STACKLEAK_RUNTIME_DISABLE', 'is not set'),
524                   stackleak_is_set,
525                   gcc_plugins_support_is_set)]
526         l += [KconfigCheck('self_protection', 'kspp', 'RANDOMIZE_KSTACK_OFFSET_DEFAULT', 'y')]
527     if arch in ('X86_64', 'ARM64'):
528         cfi_clang_is_set = KconfigCheck('self_protection', 'kspp', 'CFI_CLANG', 'y')
529         l += [cfi_clang_is_set]
530         l += [AND(KconfigCheck('self_protection', 'kspp', 'CFI_PERMISSIVE', 'is not set'),
531                   cfi_clang_is_set)]
532     if arch in ('X86_64', 'X86_32'):
533         l += [KconfigCheck('self_protection', 'kspp', 'DEFAULT_MMAP_MIN_ADDR', '65536')]
534         l += [AND(KconfigCheck('self_protection', 'kspp', 'INTEL_IOMMU_DEFAULT_ON', 'y'),
535                   iommu_support_is_set)]
536     if arch in ('ARM64', 'ARM'):
537         l += [KconfigCheck('self_protection', 'kspp', 'DEFAULT_MMAP_MIN_ADDR', '32768')]
538         l += [KconfigCheck('self_protection', 'kspp', 'SYN_COOKIES', 'y')] # another reason?
539     if arch == 'X86_64':
540         l += [KconfigCheck('self_protection', 'kspp', 'SLS', 'y')] # vs CVE-2021-26341 in Straight-Line-Speculation
541         l += [AND(KconfigCheck('self_protection', 'kspp', 'INTEL_IOMMU_SVM', 'y'),
542                   iommu_support_is_set)]
543         l += [AND(KconfigCheck('self_protection', 'kspp', 'AMD_IOMMU_V2', 'y'),
544                   iommu_support_is_set)]
545     if arch == 'ARM64':
546         l += [KconfigCheck('self_protection', 'kspp', 'ARM64_SW_TTBR0_PAN', 'y')]
547         l += [KconfigCheck('self_protection', 'kspp', 'SHADOW_CALL_STACK', 'y')]
548         l += [KconfigCheck('self_protection', 'kspp', 'KASAN_HW_TAGS', 'y')]
549     if arch == 'X86_32':
550         l += [KconfigCheck('self_protection', 'kspp', 'PAGE_TABLE_ISOLATION', 'y')]
551         l += [KconfigCheck('self_protection', 'kspp', 'HIGHMEM64G', 'y')]
552         l += [KconfigCheck('self_protection', 'kspp', 'X86_PAE', 'y')]
553         l += [AND(KconfigCheck('self_protection', 'kspp', 'INTEL_IOMMU', 'y'),
554                   iommu_support_is_set)]
555
556     # 'self_protection', 'clipos'
557     l += [KconfigCheck('self_protection', 'clipos', 'SLAB_MERGE_DEFAULT', 'is not set')]
558
559     # 'security_policy'
560     if arch in ('X86_64', 'ARM64', 'X86_32'):
561         l += [KconfigCheck('security_policy', 'defconfig', 'SECURITY', 'y')] # and choose your favourite LSM
562     if arch == 'ARM':
563         l += [KconfigCheck('security_policy', 'kspp', 'SECURITY', 'y')] # and choose your favourite LSM
564     l += [KconfigCheck('security_policy', 'kspp', 'SECURITY_YAMA', 'y')]
565     l += [KconfigCheck('security_policy', 'kspp', 'SECURITY_LANDLOCK', 'y')]
566     l += [KconfigCheck('security_policy', 'kspp', 'SECURITY_SELINUX_DISABLE', 'is not set')]
567     l += [KconfigCheck('security_policy', 'kspp', 'SECURITY_SELINUX_BOOTPARAM', 'is not set')]
568     l += [KconfigCheck('security_policy', 'kspp', 'SECURITY_SELINUX_DEVELOP', 'is not set')]
569     l += [KconfigCheck('security_policy', 'kspp', 'SECURITY_LOCKDOWN_LSM', 'y')]
570     l += [KconfigCheck('security_policy', 'kspp', 'SECURITY_LOCKDOWN_LSM_EARLY', 'y')]
571     l += [KconfigCheck('security_policy', 'kspp', 'LOCK_DOWN_KERNEL_FORCE_CONFIDENTIALITY', 'y')]
572     l += [KconfigCheck('security_policy', 'kspp', 'SECURITY_WRITABLE_HOOKS', 'is not set')] # refers to SECURITY_SELINUX_DISABLE
573
574     # 'cut_attack_surface', 'defconfig'
575     l += [KconfigCheck('cut_attack_surface', 'defconfig', 'SECCOMP', 'y')]
576     l += [KconfigCheck('cut_attack_surface', 'defconfig', 'SECCOMP_FILTER', 'y')]
577     l += [OR(KconfigCheck('cut_attack_surface', 'defconfig', 'BPF_UNPRIV_DEFAULT_OFF', 'y'),
578              bpf_syscall_not_set)] # see unprivileged_bpf_disabled
579     if arch in ('X86_64', 'ARM64', 'X86_32'):
580         l += [OR(KconfigCheck('cut_attack_surface', 'defconfig', 'STRICT_DEVMEM', 'y'),
581                  devmem_not_set)] # refers to LOCKDOWN
582     if arch in ('X86_64', 'X86_32'):
583         l += [KconfigCheck('cut_attack_surface', 'defconfig', 'X86_INTEL_TSX_MODE_OFF', 'y')] # tsx=off
584
585     # 'cut_attack_surface', 'kspp'
586     l += [KconfigCheck('cut_attack_surface', 'kspp', 'SECURITY_DMESG_RESTRICT', 'y')]
587     l += [KconfigCheck('cut_attack_surface', 'kspp', 'ACPI_CUSTOM_METHOD', 'is not set')] # refers to LOCKDOWN
588     l += [KconfigCheck('cut_attack_surface', 'kspp', 'COMPAT_BRK', 'is not set')]
589     l += [KconfigCheck('cut_attack_surface', 'kspp', 'DEVKMEM', 'is not set')] # refers to LOCKDOWN
590     l += [KconfigCheck('cut_attack_surface', 'kspp', 'COMPAT_VDSO', 'is not set')]
591     l += [KconfigCheck('cut_attack_surface', 'kspp', 'BINFMT_MISC', 'is not set')]
592     l += [KconfigCheck('cut_attack_surface', 'kspp', 'INET_DIAG', 'is not set')]
593     l += [KconfigCheck('cut_attack_surface', 'kspp', 'KEXEC', 'is not set')] # refers to LOCKDOWN
594     l += [KconfigCheck('cut_attack_surface', 'kspp', 'PROC_KCORE', 'is not set')] # refers to LOCKDOWN
595     l += [KconfigCheck('cut_attack_surface', 'kspp', 'LEGACY_PTYS', 'is not set')]
596     l += [KconfigCheck('cut_attack_surface', 'kspp', 'HIBERNATION', 'is not set')] # refers to LOCKDOWN
597     l += [KconfigCheck('cut_attack_surface', 'kspp', 'IA32_EMULATION', 'is not set')]
598     l += [KconfigCheck('cut_attack_surface', 'kspp', 'X86_X32', 'is not set')]
599     l += [KconfigCheck('cut_attack_surface', 'kspp', 'MODIFY_LDT_SYSCALL', 'is not set')]
600     l += [KconfigCheck('cut_attack_surface', 'kspp', 'OABI_COMPAT', 'is not set')]
601     l += [KconfigCheck('cut_attack_surface', 'kspp', 'X86_MSR', 'is not set')] # refers to LOCKDOWN
602     l += [modules_not_set]
603     l += [devmem_not_set]
604     l += [OR(KconfigCheck('cut_attack_surface', 'kspp', 'IO_STRICT_DEVMEM', 'y'),
605              devmem_not_set)] # refers to LOCKDOWN
606     l += [AND(KconfigCheck('cut_attack_surface', 'kspp', 'LDISC_AUTOLOAD', 'is not set'),
607               KconfigCheck('cut_attack_surface', 'kspp', 'LDISC_AUTOLOAD', 'is present'))]
608     if arch == 'X86_64':
609         l += [KconfigCheck('cut_attack_surface', 'kspp', 'LEGACY_VSYSCALL_NONE', 'y')] # 'vsyscall=none'
610     if arch == 'ARM':
611         l += [OR(KconfigCheck('cut_attack_surface', 'kspp', 'STRICT_DEVMEM', 'y'),
612                  devmem_not_set)] # refers to LOCKDOWN
613
614     # 'cut_attack_surface', 'grsec'
615     l += [KconfigCheck('cut_attack_surface', 'grsec', 'ZSMALLOC_STAT', 'is not set')]
616     l += [KconfigCheck('cut_attack_surface', 'grsec', 'PAGE_OWNER', 'is not set')]
617     l += [KconfigCheck('cut_attack_surface', 'grsec', 'DEBUG_KMEMLEAK', 'is not set')]
618     l += [KconfigCheck('cut_attack_surface', 'grsec', 'BINFMT_AOUT', 'is not set')]
619     l += [KconfigCheck('cut_attack_surface', 'grsec', 'KPROBE_EVENTS', 'is not set')]
620     l += [KconfigCheck('cut_attack_surface', 'grsec', 'UPROBE_EVENTS', 'is not set')]
621     l += [KconfigCheck('cut_attack_surface', 'grsec', 'GENERIC_TRACER', 'is not set')] # refers to LOCKDOWN
622     l += [KconfigCheck('cut_attack_surface', 'grsec', 'FUNCTION_TRACER', 'is not set')]
623     l += [KconfigCheck('cut_attack_surface', 'grsec', 'STACK_TRACER', 'is not set')]
624     l += [KconfigCheck('cut_attack_surface', 'grsec', 'HIST_TRIGGERS', 'is not set')]
625     l += [KconfigCheck('cut_attack_surface', 'grsec', 'BLK_DEV_IO_TRACE', 'is not set')]
626     l += [KconfigCheck('cut_attack_surface', 'grsec', 'PROC_VMCORE', 'is not set')]
627     l += [KconfigCheck('cut_attack_surface', 'grsec', 'PROC_PAGE_MONITOR', 'is not set')]
628     l += [KconfigCheck('cut_attack_surface', 'grsec', 'USELIB', 'is not set')]
629     l += [KconfigCheck('cut_attack_surface', 'grsec', 'CHECKPOINT_RESTORE', 'is not set')]
630     l += [KconfigCheck('cut_attack_surface', 'grsec', 'USERFAULTFD', 'is not set')]
631     l += [KconfigCheck('cut_attack_surface', 'grsec', 'HWPOISON_INJECT', 'is not set')]
632     l += [KconfigCheck('cut_attack_surface', 'grsec', 'MEM_SOFT_DIRTY', 'is not set')]
633     l += [KconfigCheck('cut_attack_surface', 'grsec', 'DEVPORT', 'is not set')] # refers to LOCKDOWN
634     l += [KconfigCheck('cut_attack_surface', 'grsec', 'DEBUG_FS', 'is not set')] # refers to LOCKDOWN
635     l += [KconfigCheck('cut_attack_surface', 'grsec', 'NOTIFIER_ERROR_INJECTION', 'is not set')]
636     l += [KconfigCheck('cut_attack_surface', 'grsec', 'FAIL_FUTEX', 'is not set')]
637     l += [KconfigCheck('cut_attack_surface', 'grsec', 'PUNIT_ATOM_DEBUG', 'is not set')]
638     l += [KconfigCheck('cut_attack_surface', 'grsec', 'ACPI_CONFIGFS', 'is not set')]
639     l += [KconfigCheck('cut_attack_surface', 'grsec', 'EDAC_DEBUG', 'is not set')]
640     l += [KconfigCheck('cut_attack_surface', 'grsec', 'DRM_I915_DEBUG', 'is not set')]
641     l += [KconfigCheck('cut_attack_surface', 'grsec', 'BCACHE_CLOSURES_DEBUG', 'is not set')]
642     l += [KconfigCheck('cut_attack_surface', 'grsec', 'DVB_C8SECTPFE', 'is not set')]
643     l += [KconfigCheck('cut_attack_surface', 'grsec', 'MTD_SLRAM', 'is not set')]
644     l += [KconfigCheck('cut_attack_surface', 'grsec', 'MTD_PHRAM', 'is not set')]
645     l += [KconfigCheck('cut_attack_surface', 'grsec', 'IO_URING', 'is not set')]
646     l += [KconfigCheck('cut_attack_surface', 'grsec', 'KCMP', 'is not set')]
647     l += [KconfigCheck('cut_attack_surface', 'grsec', 'RSEQ', 'is not set')]
648     l += [KconfigCheck('cut_attack_surface', 'grsec', 'LATENCYTOP', 'is not set')]
649     l += [KconfigCheck('cut_attack_surface', 'grsec', 'KCOV', 'is not set')]
650     l += [KconfigCheck('cut_attack_surface', 'grsec', 'PROVIDE_OHCI1394_DMA_INIT', 'is not set')]
651     l += [KconfigCheck('cut_attack_surface', 'grsec', 'SUNRPC_DEBUG', 'is not set')]
652     l += [AND(KconfigCheck('cut_attack_surface', 'grsec', 'PTDUMP_DEBUGFS', 'is not set'),
653               KconfigCheck('cut_attack_surface', 'grsec', 'X86_PTDUMP', 'is not set'))]
654
655     # 'cut_attack_surface', 'maintainer'
656     l += [KconfigCheck('cut_attack_surface', 'maintainer', 'DRM_LEGACY', 'is not set')] # recommended by Daniel Vetter in /issues/38
657     l += [KconfigCheck('cut_attack_surface', 'maintainer', 'FB', 'is not set')] # recommended by Daniel Vetter in /issues/38
658     l += [KconfigCheck('cut_attack_surface', 'maintainer', 'VT', 'is not set')] # recommended by Daniel Vetter in /issues/38
659     l += [KconfigCheck('cut_attack_surface', 'maintainer', 'BLK_DEV_FD', 'is not set')] # recommended by Denis Efremov in /pull/54
660     l += [KconfigCheck('cut_attack_surface', 'maintainer', 'BLK_DEV_FD_RAWCMD', 'is not set')] # recommended by Denis Efremov in /pull/62
661
662     # 'cut_attack_surface', 'grapheneos'
663     l += [KconfigCheck('cut_attack_surface', 'grapheneos', 'AIO', 'is not set')]
664
665     # 'cut_attack_surface', 'clipos'
666     l += [KconfigCheck('cut_attack_surface', 'clipos', 'STAGING', 'is not set')]
667     l += [KconfigCheck('cut_attack_surface', 'clipos', 'KSM', 'is not set')] # to prevent FLUSH+RELOAD attack
668     l += [KconfigCheck('cut_attack_surface', 'clipos', 'KALLSYMS', 'is not set')]
669     l += [KconfigCheck('cut_attack_surface', 'clipos', 'X86_VSYSCALL_EMULATION', 'is not set')]
670     l += [KconfigCheck('cut_attack_surface', 'clipos', 'MAGIC_SYSRQ', 'is not set')]
671     l += [KconfigCheck('cut_attack_surface', 'clipos', 'KEXEC_FILE', 'is not set')] # refers to LOCKDOWN (permissive)
672     l += [KconfigCheck('cut_attack_surface', 'clipos', 'USER_NS', 'is not set')] # user.max_user_namespaces=0
673     l += [KconfigCheck('cut_attack_surface', 'clipos', 'X86_CPUID', 'is not set')]
674     l += [KconfigCheck('cut_attack_surface', 'clipos', 'X86_IOPL_IOPERM', 'is not set')] # refers to LOCKDOWN
675     l += [KconfigCheck('cut_attack_surface', 'clipos', 'ACPI_TABLE_UPGRADE', 'is not set')] # refers to LOCKDOWN
676     l += [KconfigCheck('cut_attack_surface', 'clipos', 'EFI_CUSTOM_SSDT_OVERLAYS', 'is not set')]
677     l += [KconfigCheck('cut_attack_surface', 'clipos', 'COREDUMP', 'is not set')] # cut userspace attack surface
678 #   l += [KconfigCheck('cut_attack_surface', 'clipos', 'IKCONFIG', 'is not set')] # no, IKCONFIG is needed for this check :)
679
680     # 'cut_attack_surface', 'lockdown'
681     l += [KconfigCheck('cut_attack_surface', 'lockdown', 'EFI_TEST', 'is not set')] # refers to LOCKDOWN
682     l += [KconfigCheck('cut_attack_surface', 'lockdown', 'MMIOTRACE_TEST', 'is not set')] # refers to LOCKDOWN
683     l += [KconfigCheck('cut_attack_surface', 'lockdown', 'KPROBES', 'is not set')] # refers to LOCKDOWN
684     l += [bpf_syscall_not_set] # refers to LOCKDOWN
685
686     # 'cut_attack_surface', 'my'
687     l += [KconfigCheck('cut_attack_surface', 'my', 'MMIOTRACE', 'is not set')] # refers to LOCKDOWN (permissive)
688     l += [KconfigCheck('cut_attack_surface', 'my', 'LIVEPATCH', 'is not set')]
689     l += [KconfigCheck('cut_attack_surface', 'my', 'IP_DCCP', 'is not set')]
690     l += [KconfigCheck('cut_attack_surface', 'my', 'IP_SCTP', 'is not set')]
691     l += [KconfigCheck('cut_attack_surface', 'my', 'FTRACE', 'is not set')] # refers to LOCKDOWN
692     l += [KconfigCheck('cut_attack_surface', 'my', 'VIDEO_VIVID', 'is not set')]
693     l += [KconfigCheck('cut_attack_surface', 'my', 'INPUT_EVBUG', 'is not set')] # Can be used as a keylogger
694     l += [KconfigCheck('cut_attack_surface', 'my', 'KGDB', 'is not set')]
695     l += [OR(KconfigCheck('cut_attack_surface', 'my', 'TRIM_UNUSED_KSYMS', 'y'),
696              modules_not_set)]
697
698     # 'harden_userspace'
699     if arch in ('X86_64', 'ARM64', 'X86_32'):
700         l += [KconfigCheck('harden_userspace', 'defconfig', 'INTEGRITY', 'y')]
701     if arch == 'ARM':
702         l += [KconfigCheck('harden_userspace', 'my', 'INTEGRITY', 'y')]
703     if arch == 'ARM64':
704         l += [KconfigCheck('harden_userspace', 'defconfig', 'ARM64_PTR_AUTH', 'y')]
705         l += [KconfigCheck('harden_userspace', 'defconfig', 'ARM64_BTI', 'y')]
706     if arch in ('ARM', 'X86_32'):
707         l += [KconfigCheck('harden_userspace', 'defconfig', 'VMSPLIT_3G', 'y')]
708     if arch in ('X86_64', 'ARM64'):
709         l += [KconfigCheck('harden_userspace', 'clipos', 'ARCH_MMAP_RND_BITS', '32')]
710     if arch in ('X86_32', 'ARM'):
711         l += [KconfigCheck('harden_userspace', 'my', 'ARCH_MMAP_RND_BITS', '16')]
712
713
714 def add_cmdline_checks(l, arch):
715     # Calling the CmdlineCheck class constructor:
716     #     CmdlineCheck(reason, decision, name, expected)
717     #
718     # [!] Don't add CmdlineChecks in add_kconfig_checks() to avoid wrong results
719     #     when the tool doesn't check the cmdline.
720     #
721     # [!] Make sure that values of the options in CmdlineChecks need normalization.
722     #     For more info see normalize_cmdline_options().
723     #
724     # A common pattern for checking the 'param_x' cmdline parameter
725     # that __overrides__ the 'PARAM_X_DEFAULT' kconfig option:
726     #   l += [OR(CmdlineCheck(reason, decision, 'param_x', '1'),
727     #            AND(KconfigCheck(reason, decision, 'PARAM_X_DEFAULT_ON', 'y'),
728     #                CmdlineCheck(reason, decision, 'param_x, 'is not set')))]
729     #
730     # Here we don't check the kconfig options or minimal kernel version
731     # required for the cmdline parameters. That would make the checks
732     # very complex and not give a 100% guarantee anyway.
733
734     # 'self_protection', 'defconfig'
735     l += [CmdlineCheck('self_protection', 'defconfig', 'nosmep', 'is not set')]
736     l += [CmdlineCheck('self_protection', 'defconfig', 'nosmap', 'is not set')]
737     l += [CmdlineCheck('self_protection', 'defconfig', 'nokaslr', 'is not set')]
738     l += [CmdlineCheck('self_protection', 'defconfig', 'nopti', 'is not set')]
739     l += [CmdlineCheck('self_protection', 'defconfig', 'nospectre_v1', 'is not set')]
740     l += [CmdlineCheck('self_protection', 'defconfig', 'nospectre_v2', 'is not set')]
741     l += [CmdlineCheck('self_protection', 'defconfig', 'nospectre_bhb', 'is not set')]
742     l += [CmdlineCheck('self_protection', 'defconfig', 'nospec_store_bypass_disable', 'is not set')]
743     l += [CmdlineCheck('self_protection', 'defconfig', 'arm64.nobti', 'is not set')]
744     l += [CmdlineCheck('self_protection', 'defconfig', 'arm64.nopauth', 'is not set')]
745     l += [CmdlineCheck('self_protection', 'defconfig', 'arm64.nomte', 'is not set')]
746     l += [OR(CmdlineCheck('self_protection', 'defconfig', 'mitigations', 'is not off'),
747              CmdlineCheck('self_protection', 'defconfig', 'mitigations', 'is not set'))]
748     l += [OR(CmdlineCheck('self_protection', 'defconfig', 'spectre_v2', 'is not off'),
749              CmdlineCheck('self_protection', 'defconfig', 'spectre_v2', 'is not set'))]
750     l += [OR(CmdlineCheck('self_protection', 'defconfig', 'spectre_v2_user', 'is not off'),
751              CmdlineCheck('self_protection', 'defconfig', 'spectre_v2_user', 'is not set'))]
752     l += [OR(CmdlineCheck('self_protection', 'defconfig', 'spec_store_bypass_disable', 'is not off'),
753              CmdlineCheck('self_protection', 'defconfig', 'spec_store_bypass_disable', 'is not set'))]
754     l += [OR(CmdlineCheck('self_protection', 'defconfig', 'l1tf', 'is not off'),
755              CmdlineCheck('self_protection', 'defconfig', 'l1tf', 'is not set'))]
756     l += [OR(CmdlineCheck('self_protection', 'defconfig', 'mds', 'is not off'),
757              CmdlineCheck('self_protection', 'defconfig', 'mds', 'is not set'))]
758     l += [OR(CmdlineCheck('self_protection', 'defconfig', 'tsx_async_abort', 'is not off'),
759              CmdlineCheck('self_protection', 'defconfig', 'tsx_async_abort', 'is not set'))]
760     l += [OR(CmdlineCheck('self_protection', 'defconfig', 'srbds', 'is not off'),
761              CmdlineCheck('self_protection', 'defconfig', 'srbds', 'is not set'))]
762     l += [OR(CmdlineCheck('self_protection', 'defconfig', 'mmio_stale_data', 'is not off'),
763              CmdlineCheck('self_protection', 'defconfig', 'mmio_stale_data', 'is not set'))]
764     l += [OR(CmdlineCheck('self_protection', 'defconfig', 'retbleed', 'is not off'),
765              CmdlineCheck('self_protection', 'defconfig', 'retbleed', 'is not set'))]
766     l += [OR(CmdlineCheck('self_protection', 'defconfig', 'kpti', 'is not off'),
767              CmdlineCheck('self_protection', 'defconfig', 'kpti', 'is not set'))]
768     if arch == 'ARM64':
769         l += [OR(CmdlineCheck('self_protection', 'defconfig', 'ssbd', 'kernel'),
770                  CmdlineCheck('self_protection', 'my', 'ssbd', 'force-on'),
771                  CmdlineCheck('self_protection', 'defconfig', 'ssbd', 'is not set'))]
772         l += [OR(CmdlineCheck('self_protection', 'defconfig', 'rodata', 'full'),
773                  AND(KconfigCheck('self_protection', 'defconfig', 'RODATA_FULL_DEFAULT_ENABLED', 'y'),
774                      CmdlineCheck('self_protection', 'defconfig', 'rodata', 'is not set')))]
775     else:
776         l += [OR(CmdlineCheck('self_protection', 'defconfig', 'rodata', '1'),
777                  CmdlineCheck('self_protection', 'defconfig', 'rodata', 'is not set'))]
778
779     # 'self_protection', 'kspp'
780     l += [CmdlineCheck('self_protection', 'kspp', 'nosmt', 'is present')]
781     l += [OR(CmdlineCheck('self_protection', 'kspp', 'init_on_alloc', '1'),
782              AND(KconfigCheck('self_protection', 'kspp', 'INIT_ON_ALLOC_DEFAULT_ON', 'y'),
783                  CmdlineCheck('self_protection', 'kspp', 'init_on_alloc', 'is not set')))]
784     l += [OR(CmdlineCheck('self_protection', 'kspp', 'init_on_free', '1'),
785              AND(KconfigCheck('self_protection', 'kspp', 'INIT_ON_FREE_DEFAULT_ON', 'y'),
786                  CmdlineCheck('self_protection', 'kspp', 'init_on_free', 'is not set')),
787              AND(CmdlineCheck('self_protection', 'kspp', 'page_poison', '1'),
788                  KconfigCheck('self_protection', 'kspp', 'PAGE_POISONING_ZERO', 'y'),
789                  CmdlineCheck('self_protection', 'kspp', 'slub_debug', 'P')))]
790     l += [OR(CmdlineCheck('self_protection', 'kspp', 'slab_nomerge', 'is present'),
791              AND(KconfigCheck('self_protection', 'clipos', 'SLAB_MERGE_DEFAULT', 'is not set'),
792                  CmdlineCheck('self_protection', 'kspp', 'slab_merge', 'is not set')))]
793     l += [OR(CmdlineCheck('self_protection', 'kspp', 'iommu.strict', '1'),
794              AND(KconfigCheck('self_protection', 'kspp', 'IOMMU_DEFAULT_DMA_STRICT', 'y'),
795                  CmdlineCheck('self_protection', 'kspp', 'iommu.strict', 'is not set')))]
796     l += [OR(CmdlineCheck('self_protection', 'kspp', 'iommu.passthrough', '0'),
797              AND(KconfigCheck('self_protection', 'kspp', 'IOMMU_DEFAULT_PASSTHROUGH', 'is not set'),
798                  CmdlineCheck('self_protection', 'kspp', 'iommu.passthrough', 'is not set')))]
799     # The cmdline checks compatible with the kconfig recommendations of the KSPP project...
800     l += [OR(CmdlineCheck('self_protection', 'kspp', 'hardened_usercopy', '1'),
801              AND(KconfigCheck('self_protection', 'kspp', 'HARDENED_USERCOPY', 'y'),
802                  CmdlineCheck('self_protection', 'kspp', 'hardened_usercopy', 'is not set')))]
803     l += [OR(CmdlineCheck('self_protection', 'kspp', 'slab_common.usercopy_fallback', '0'),
804              AND(KconfigCheck('self_protection', 'kspp', 'HARDENED_USERCOPY_FALLBACK', 'is not set'),
805                  CmdlineCheck('self_protection', 'kspp', 'slab_common.usercopy_fallback', 'is not set')))]
806     # ... the end
807     if arch in ('X86_64', 'ARM64', 'X86_32'):
808         l += [OR(CmdlineCheck('self_protection', 'kspp', 'randomize_kstack_offset', '1'),
809                  AND(KconfigCheck('self_protection', 'kspp', 'RANDOMIZE_KSTACK_OFFSET_DEFAULT', 'y'),
810                      CmdlineCheck('self_protection', 'kspp', 'randomize_kstack_offset', 'is not set')))]
811     if arch in ('X86_64', 'X86_32'):
812         l += [AND(CmdlineCheck('self_protection', 'kspp', 'pti', 'on'),
813                   CmdlineCheck('self_protection', 'defconfig', 'nopti', 'is not set'))]
814
815     # 'self_protection', 'clipos'
816     l += [CmdlineCheck('self_protection', 'clipos', 'page_alloc.shuffle', '1')]
817
818     # 'cut_attack_surface', 'defconfig'
819     if arch in ('X86_64', 'X86_32'):
820         l += [OR(CmdlineCheck('cut_attack_surface', 'defconfig', 'tsx', 'off'),
821                  AND(KconfigCheck('cut_attack_surface', 'defconfig', 'X86_INTEL_TSX_MODE_OFF', 'y'),
822                      CmdlineCheck('cut_attack_surface', 'defconfig', 'tsx', 'is not set')))]
823
824     # 'cut_attack_surface', 'kspp'
825     if arch == 'X86_64':
826         l += [OR(CmdlineCheck('cut_attack_surface', 'kspp', 'vsyscall', 'none'),
827                  AND(KconfigCheck('cut_attack_surface', 'kspp', 'LEGACY_VSYSCALL_NONE', 'y'),
828                      CmdlineCheck('cut_attack_surface', 'kspp', 'vsyscall', 'is not set')))]
829
830     # 'cut_attack_surface', 'grsec'
831     # The cmdline checks compatible with the kconfig options disabled by grsecurity...
832     l += [OR(CmdlineCheck('cut_attack_surface', 'grsec', 'debugfs', 'off'),
833              KconfigCheck('cut_attack_surface', 'grsec', 'DEBUG_FS', 'is not set'))] # ... the end
834
835     # 'cut_attack_surface', 'my'
836     l += [CmdlineCheck('cut_attack_surface', 'my', 'sysrq_always_enabled', 'is not set')]
837
838 def print_unknown_options(checklist, parsed_options):
839     known_options = []
840
841     for o1 in checklist:
842         if o1.type != 'complex':
843             known_options.append(o1.name)
844             continue
845         for o2 in o1.opts:
846             if o2.type != 'complex':
847                 if hasattr(o2, 'name'):
848                     known_options.append(o2.name)
849                 continue
850             for o3 in o2.opts:
851                 assert(o3.type != 'complex'), \
852                        'unexpected ComplexOptCheck inside {}'.format(o2.name)
853                 if hasattr(o3, 'name'):
854                     known_options.append(o3.name)
855
856     for option, value in parsed_options.items():
857         if option not in known_options:
858             print('[?] No check for option {} ({})'.format(option, value))
859
860
861 def print_checklist(mode, checklist, with_results):
862     if mode == 'json':
863         output = []
864         for o in checklist:
865             output.append(o.json_dump(with_results))
866         print(json.dumps(output))
867         return
868
869     # table header
870     sep_line_len = 91
871     if with_results:
872         sep_line_len += 30
873     print('=' * sep_line_len)
874     print('{:^40}|{:^7}|{:^12}|{:^10}|{:^18}'.format('option name', 'type', 'desired val', 'decision', 'reason'), end='')
875     if with_results:
876         print('| {}'.format('check result'), end='')
877     print()
878     print('=' * sep_line_len)
879
880     # table contents
881     for opt in checklist:
882         if with_results:
883             if mode == 'show_ok':
884                 if not opt.result.startswith('OK'):
885                     continue
886             if mode == 'show_fail':
887                 if not opt.result.startswith('FAIL'):
888                     continue
889         opt.table_print(mode, with_results)
890         print()
891         if mode == 'verbose':
892             print('-' * sep_line_len)
893     print()
894
895     # final score
896     if with_results:
897         fail_count = len(list(filter(lambda opt: opt.result.startswith('FAIL'), checklist)))
898         fail_suppressed = ''
899         ok_count = len(list(filter(lambda opt: opt.result.startswith('OK'), checklist)))
900         ok_suppressed = ''
901         if mode == 'show_ok':
902             fail_suppressed = ' (suppressed in output)'
903         if mode == 'show_fail':
904             ok_suppressed = ' (suppressed in output)'
905         if mode != 'json':
906             print('[+] Config check is finished: \'OK\' - {}{} / \'FAIL\' - {}{}'.format(ok_count, ok_suppressed, fail_count, fail_suppressed))
907
908
909 def populate_simple_opt_with_data(opt, data, data_type):
910     assert(opt.type != 'complex'), \
911            'unexpected ComplexOptCheck "{}"'.format(opt.name)
912     assert(opt.type in SIMPLE_OPTION_TYPES), \
913            'invalid opt type "{}"'.format(opt.type)
914     assert(data_type in SIMPLE_OPTION_TYPES), \
915            'invalid data type "{}"'.format(data_type)
916
917     if data_type != opt.type:
918         return
919
920     if data_type in ('kconfig', 'cmdline'):
921         opt.state = data.get(opt.name, None)
922     else:
923         assert(data_type == 'version'), \
924                'unexpected data type "{}"'.format(data_type)
925         opt.ver = data
926
927
928 def populate_opt_with_data(opt, data, data_type):
929     if opt.type == 'complex':
930         for o in opt.opts:
931             if o.type == 'complex':
932                 # Recursion for nested ComplexOptCheck objects
933                 populate_opt_with_data(o, data, data_type)
934             else:
935                 populate_simple_opt_with_data(o, data, data_type)
936     else:
937         assert(opt.type in ('kconfig', 'cmdline')), \
938                'bad type "{}" for a simple check'.format(opt.type)
939         populate_simple_opt_with_data(opt, data, data_type)
940
941
942 def populate_with_data(checklist, data, data_type):
943     for opt in checklist:
944         populate_opt_with_data(opt, data, data_type)
945
946
947 def perform_checks(checklist):
948     for opt in checklist:
949         opt.check()
950
951
952 def parse_kconfig_file(parsed_options, fname):
953     with open(fname, 'r') as f:
954         opt_is_on = re.compile("CONFIG_[a-zA-Z0-9_]*=[a-zA-Z0-9_\"]*")
955         opt_is_off = re.compile("# CONFIG_[a-zA-Z0-9_]* is not set")
956
957         for line in f.readlines():
958             line = line.strip()
959             option = None
960             value = None
961
962             if opt_is_on.match(line):
963                 option, value = line.split('=', 1)
964                 if value == 'is not set':
965                     sys.exit('[!] ERROR: bad enabled kconfig option "{}"'.format(line))
966             elif opt_is_off.match(line):
967                 option, value = line[2:].split(' ', 1)
968                 if value != 'is not set':
969                     sys.exit('[!] ERROR: bad disabled kconfig option "{}"'.format(line))
970
971             if option in parsed_options:
972                 sys.exit('[!] ERROR: kconfig option "{}" exists multiple times'.format(line))
973
974             if option:
975                 parsed_options[option] = value
976
977
978 def normalize_cmdline_options(option, value):
979     # Don't normalize the cmdline option values if
980     # the Linux kernel doesn't use kstrtobool() for them
981     if option == 'debugfs':
982         # See debugfs_kernel() in fs/debugfs/inode.c
983         return value
984     if option == 'mitigations':
985         # See mitigations_parse_cmdline() in kernel/cpu.c
986         return value
987     if option == 'pti':
988         # See pti_check_boottime_disable() in arch/x86/mm/pti.c
989         return value
990     if option == 'spectre_v2':
991         # See spectre_v2_parse_cmdline() in arch/x86/kernel/cpu/bugs.c
992         return value
993     if option == 'spectre_v2_user':
994         # See spectre_v2_parse_user_cmdline() in arch/x86/kernel/cpu/bugs.c
995         return value
996     if option == 'spec_store_bypass_disable':
997         # See ssb_parse_cmdline() in arch/x86/kernel/cpu/bugs.c
998         return value
999     if option == 'l1tf':
1000         # See l1tf_cmdline() in arch/x86/kernel/cpu/bugs.c
1001         return value
1002     if option == 'mds':
1003         # See mds_cmdline() in arch/x86/kernel/cpu/bugs.c
1004         return value
1005     if option == 'tsx_async_abort':
1006         # See tsx_async_abort_parse_cmdline() in arch/x86/kernel/cpu/bugs.c
1007         return value
1008     if option == 'srbds':
1009         # See srbds_parse_cmdline() in arch/x86/kernel/cpu/bugs.c
1010         return value
1011     if option == 'mmio_stale_data':
1012         # See mmio_stale_data_parse_cmdline() in arch/x86/kernel/cpu/bugs.c
1013         return value
1014     if option == 'retbleed':
1015         # See retbleed_parse_cmdline() in arch/x86/kernel/cpu/bugs.c
1016         return value
1017     if option == 'tsx':
1018         # See tsx_init() in arch/x86/kernel/cpu/tsx.c
1019         return value
1020
1021     # Implement a limited part of the kstrtobool() logic
1022     if value in ('1', 'on', 'On', 'ON', 'y', 'Y', 'yes', 'Yes', 'YES'):
1023         return '1'
1024     if value in ('0', 'off', 'Off', 'OFF', 'n', 'N', 'no', 'No', 'NO'):
1025         return '0'
1026
1027     # Preserve unique values
1028     return value
1029
1030
1031 def parse_cmdline_file(parsed_options, fname):
1032     with open(fname, 'r') as f:
1033         line = f.readline()
1034         opts = line.split()
1035
1036         line = f.readline()
1037         if line:
1038             sys.exit('[!] ERROR: more than one line in "{}"'.format(fname))
1039
1040         for opt in opts:
1041             if '=' in opt:
1042                 name, value = opt.split('=', 1)
1043             else:
1044                 name = opt
1045                 value = '' # '' is not None
1046             value = normalize_cmdline_options(name, value)
1047             parsed_options[name] = value
1048
1049
1050 def main():
1051     # Report modes:
1052     #   * verbose mode for
1053     #     - reporting about unknown kernel options in the kconfig
1054     #     - verbose printing of ComplexOptCheck items
1055     #   * json mode for printing the results in JSON format
1056     report_modes = ['verbose', 'json', 'show_ok', 'show_fail']
1057     supported_archs = ['X86_64', 'X86_32', 'ARM64', 'ARM']
1058     parser = ArgumentParser(prog='kconfig-hardened-check',
1059                             description='A tool for checking the security hardening options of the Linux kernel')
1060     parser.add_argument('--version', action='version', version='%(prog)s ' + __version__)
1061     parser.add_argument('-p', '--print', choices=supported_archs,
1062                         help='print security hardening preferences for the selected architecture')
1063     parser.add_argument('-c', '--config',
1064                         help='check the kernel kconfig file against these preferences')
1065     parser.add_argument('-l', '--cmdline',
1066                         help='check the kernel cmdline file against these preferences')
1067     parser.add_argument('-m', '--mode', choices=report_modes,
1068                         help='choose the report mode')
1069     args = parser.parse_args()
1070
1071     mode = None
1072     if args.mode:
1073         mode = args.mode
1074         if mode != 'json':
1075             print('[+] Special report mode: {}'.format(mode))
1076
1077     config_checklist = []
1078
1079     if args.config:
1080         if args.print:
1081             sys.exit('[!] ERROR: --config and --print can\'t be used together')
1082
1083         if mode != 'json':
1084             print('[+] Kconfig file to check: {}'.format(args.config))
1085             if args.cmdline:
1086                 print('[+] Kernel cmdline file to check: {}'.format(args.cmdline))
1087
1088         arch, msg = detect_arch(args.config, supported_archs)
1089         if not arch:
1090             sys.exit('[!] ERROR: {}'.format(msg))
1091         if mode != 'json':
1092             print('[+] Detected architecture: {}'.format(arch))
1093
1094         kernel_version, msg = detect_kernel_version(args.config)
1095         if not kernel_version:
1096             sys.exit('[!] ERROR: {}'.format(msg))
1097         if mode != 'json':
1098             print('[+] Detected kernel version: {}.{}'.format(kernel_version[0], kernel_version[1]))
1099
1100         compiler, msg = detect_compiler(args.config)
1101         if mode != 'json':
1102             if compiler:
1103                 print('[+] Detected compiler: {}'.format(compiler))
1104             else:
1105                 print('[-] Can\'t detect the compiler: {}'.format(msg))
1106
1107         # add relevant kconfig checks to the checklist
1108         add_kconfig_checks(config_checklist, arch)
1109
1110         if args.cmdline:
1111             # add relevant cmdline checks to the checklist
1112             add_cmdline_checks(config_checklist, arch)
1113
1114         # populate the checklist with the parsed kconfig data
1115         parsed_kconfig_options = OrderedDict()
1116         parse_kconfig_file(parsed_kconfig_options, args.config)
1117         populate_with_data(config_checklist, parsed_kconfig_options, 'kconfig')
1118         populate_with_data(config_checklist, kernel_version, 'version')
1119
1120         if args.cmdline:
1121             # populate the checklist with the parsed kconfig data
1122             parsed_cmdline_options = OrderedDict()
1123             parse_cmdline_file(parsed_cmdline_options, args.cmdline)
1124             populate_with_data(config_checklist, parsed_cmdline_options, 'cmdline')
1125
1126         # now everything is ready for performing the checks
1127         perform_checks(config_checklist)
1128
1129         # finally print the results
1130         if mode == 'verbose':
1131             print_unknown_options(config_checklist, parsed_kconfig_options)
1132         print_checklist(mode, config_checklist, True)
1133
1134         sys.exit(0)
1135     elif args.cmdline:
1136         sys.exit('[!] ERROR: checking cmdline doesn\'t work without checking kconfig')
1137
1138     if args.print:
1139         if mode in ('show_ok', 'show_fail'):
1140             sys.exit('[!] ERROR: wrong mode "{}" for --print'.format(mode))
1141         arch = args.print
1142         add_kconfig_checks(config_checklist, arch)
1143         add_cmdline_checks(config_checklist, arch)
1144         if mode != 'json':
1145             print('[+] Printing kernel security hardening preferences for {}...'.format(arch))
1146         print_checklist(mode, config_checklist, False)
1147         sys.exit(0)
1148
1149     parser.print_help()
1150     sys.exit(0)