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