2b5fe1e68d7bd5b2fa6d58b95e7c26be90a6ac1d
[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 #    slab_nomerge
15 #    page_alloc.shuffle=1
16 #    iommu=force (does it help against DMA attacks?)
17 #    slub_debug=FZ (slow)
18 #    init_on_alloc=1 (since v5.3)
19 #    init_on_free=1 (since v5.3, otherwise slub_debug=P and page_poison=1)
20 #    loadpin.enforce=1
21 #    debugfs=no-mount (or off if possible)
22 #    randomize_kstack_offset=1
23 #
24 #    Mitigations of CPU vulnerabilities:
25 #       Аrch-independent:
26 #           mitigations=auto,nosmt (nosmt is slow)
27 #       X86:
28 #           spectre_v2=on
29 #           pti=on
30 #           spec_store_bypass_disable=on
31 #           l1tf=full,force
32 #           l1d_flush=on (a part of the l1tf option)
33 #           mds=full,nosmt
34 #           tsx=off
35 #       ARM64:
36 #           kpti=on
37 #           ssbd=force-on
38 #
39 #    Should NOT be set:
40 #           nokaslr
41 #           arm64.nobti
42 #           arm64.nopauth
43 #
44 #    Hardware tag-based KASAN with arm64 Memory Tagging Extension (MTE):
45 #           kasan=on
46 #           kasan.stacktrace=off
47 #           kasan.fault=panic
48 #
49 # N.B. Hardening sysctls:
50 #    kernel.kptr_restrict=2 (or 1?)
51 #    kernel.dmesg_restrict=1 (also see the kconfig option)
52 #    kernel.perf_event_paranoid=3
53 #    kernel.kexec_load_disabled=1
54 #    kernel.yama.ptrace_scope=3
55 #    user.max_user_namespaces=0
56 #    what about bpf_jit_enable?
57 #    kernel.unprivileged_bpf_disabled=1
58 #    net.core.bpf_jit_harden=2
59 #
60 #    vm.unprivileged_userfaultfd=0
61 #        (at first, it disabled unprivileged userfaultfd,
62 #         and since v5.11 it enables unprivileged userfaultfd for user-mode only)
63 #
64 #    dev.tty.ldisc_autoload=0
65 #    fs.protected_symlinks=1
66 #    fs.protected_hardlinks=1
67 #    fs.protected_fifos=2
68 #    fs.protected_regular=2
69 #    fs.suid_dumpable=0
70 #    kernel.modules_disabled=1
71
72
73 # pylint: disable=missing-module-docstring,missing-class-docstring,missing-function-docstring
74 # pylint: disable=line-too-long,invalid-name,too-many-branches,too-many-statements
75
76
77 import sys
78 from argparse import ArgumentParser
79 from collections import OrderedDict
80 import re
81 import json
82 from .__about__ import __version__
83
84 TYPES_OF_CHECKS = ('kconfig', 'version')
85
86 class OptCheck:
87     def __init__(self, reason, decision, name, expected):
88         self.name = name
89         self.expected = expected
90         self.decision = decision
91         self.reason = reason
92         self.state = None
93         self.result = None
94
95     def check(self):
96         if self.expected == self.state:
97             self.result = 'OK'
98         elif self.state is None:
99             if self.expected == 'is not set':
100                 self.result = 'OK: not found'
101             else:
102                 self.result = 'FAIL: not found'
103         else:
104             self.result = 'FAIL: "' + self.state + '"'
105
106         if self.result.startswith('OK'):
107             return True
108         return False
109
110     def table_print(self, _mode, with_results):
111         print('{:<40}|{:^7}|{:^12}|{:^10}|{:^18}'.format(self.name, self.type, self.expected, self.decision, self.reason), end='')
112         if with_results:
113             print('| {}'.format(self.result), end='')
114
115
116 class KconfigCheck(OptCheck):
117     def __init__(self, *args, **kwargs):
118         super().__init__(*args, **kwargs)
119         self.name = 'CONFIG_' + self.name
120
121     @property
122     def type(self):
123         return 'kconfig'
124
125     def json_dump(self, with_results):
126         dump = [self.name, self.type, self.expected, self.decision, self.reason]
127         if with_results:
128             dump.append(self.result)
129         return dump
130
131
132 class VersionCheck:
133     def __init__(self, ver_expected):
134         self.ver_expected = ver_expected
135         self.ver = ()
136         self.result = None
137
138     @property
139     def type(self):
140         return 'version'
141
142     def check(self):
143         if self.ver[0] > self.ver_expected[0]:
144             self.result = 'OK: version >= ' + str(self.ver_expected[0]) + '.' + str(self.ver_expected[1])
145             return True
146         if self.ver[0] < self.ver_expected[0]:
147             self.result = 'FAIL: version < ' + str(self.ver_expected[0]) + '.' + str(self.ver_expected[1])
148             return False
149         if self.ver[1] >= self.ver_expected[1]:
150             self.result = 'OK: version >= ' + str(self.ver_expected[0]) + '.' + str(self.ver_expected[1])
151             return True
152         self.result = 'FAIL: version < ' + str(self.ver_expected[0]) + '.' + str(self.ver_expected[1])
153         return False
154
155     def table_print(self, _mode, with_results):
156         ver_req = 'kernel version >= ' + str(self.ver_expected[0]) + '.' + str(self.ver_expected[1])
157         print('{:<91}'.format(ver_req), end='')
158         if with_results:
159             print('| {}'.format(self.result), end='')
160
161
162 class PresenceCheck:
163     def __init__(self, name, type):
164         self.type = type
165         if self.type == 'kconfig':
166             self.name = 'CONFIG_' + name
167         else:
168             sys.exit('[!] ERROR: unsupported type "{}" for {}'.format(type, self.__class__.__name__))
169         self.state = None
170         self.result = None
171
172     def check(self):
173         if self.state is None:
174             self.result = 'FAIL: not present'
175             return False
176         self.result = 'OK: is present'
177         return True
178
179     def table_print(self, _mode, with_results):
180         print('{:<91}'.format(self.name + ' is present'), end='')
181         if with_results:
182             print('| {}'.format(self.result), end='')
183
184
185 class ComplexOptCheck:
186     def __init__(self, *opts):
187         self.opts = opts
188         if not self.opts:
189             sys.exit('[!] ERROR: empty {} check'.format(self.__class__.__name__))
190         if len(self.opts) == 1:
191             sys.exit('[!] ERROR: useless {} check'.format(self.__class__.__name__))
192         if not isinstance(opts[0], KconfigCheck):
193             sys.exit('[!] ERROR: invalid {} check: {}'.format(self.__class__.__name__, opts))
194         self.result = None
195
196     @property
197     def name(self):
198         return self.opts[0].name
199
200     @property
201     def type(self):
202         return 'complex'
203
204     @property
205     def expected(self):
206         return self.opts[0].expected
207
208     @property
209     def decision(self):
210         return self.opts[0].decision
211
212     @property
213     def reason(self):
214         return self.opts[0].reason
215
216     def table_print(self, mode, with_results):
217         if mode == 'verbose':
218             print('    {:87}'.format('<<< ' + self.__class__.__name__ + ' >>>'), end='')
219             if with_results:
220                 print('| {}'.format(self.result), end='')
221             for o in self.opts:
222                 print()
223                 o.table_print(mode, with_results)
224         else:
225             o = self.opts[0]
226             o.table_print(mode, False)
227             if with_results:
228                 print('| {}'.format(self.result), end='')
229
230     def json_dump(self, with_results):
231         dump = self.opts[0].json_dump(False)
232         if with_results:
233             dump.append(self.result)
234         return dump
235
236
237 class OR(ComplexOptCheck):
238     # self.opts[0] is the option that this OR-check is about.
239     # Use cases:
240     #     OR(<X_is_hardened>, <X_is_disabled>)
241     #     OR(<X_is_hardened>, <old_X_is_hardened>)
242
243     def check(self):
244         if not self.opts:
245             sys.exit('[!] ERROR: invalid OR check')
246
247         for i, opt in enumerate(self.opts):
248             ret = opt.check()
249             if ret:
250                 if opt.result == 'OK' and i != 0:
251                     # Simple OK is not enough for additional checks, add more info:
252                     self.result = 'OK: {} "{}"'.format(opt.name, opt.expected)
253                 else:
254                     self.result = opt.result
255                 return True
256         self.result = self.opts[0].result
257         return False
258
259
260 class AND(ComplexOptCheck):
261     # self.opts[0] is the option that this AND-check is about.
262     # Use cases:
263     #     AND(<suboption>, <main_option>)
264     #       Suboption is not checked if checking of the main_option is failed.
265     #     AND(<X_is_disabled>, <old_X_is_disabled>)
266
267     def check(self):
268         for i, opt in reversed(list(enumerate(self.opts))):
269             ret = opt.check()
270             if i == 0:
271                 self.result = opt.result
272                 return ret
273             if not ret:
274                 # This FAIL is caused by additional checks,
275                 # and not by the main option that this AND-check is about.
276                 # Describe the reason of the FAIL.
277                 if opt.result.startswith('FAIL: \"') or opt.result == 'FAIL: not found':
278                     self.result = 'FAIL: {} not "{}"'.format(opt.name, opt.expected)
279                 elif opt.result == 'FAIL: not present':
280                     self.result = 'FAIL: {} not present'.format(opt.name)
281                 else:
282                     # This FAIL message is self-explaining.
283                     self.result = opt.result
284                 return False
285
286         sys.exit('[!] ERROR: invalid AND check')
287
288
289 def detect_arch(fname, archs):
290     with open(fname, 'r') as f:
291         arch_pattern = re.compile("CONFIG_[a-zA-Z0-9_]*=y")
292         arch = None
293         for line in f.readlines():
294             if arch_pattern.match(line):
295                 option, _ = line[7:].split('=', 1)
296                 if option in archs:
297                     if not arch:
298                         arch = option
299                     else:
300                         return None, 'more than one supported architecture is detected'
301         if not arch:
302             return None, 'failed to detect architecture'
303         return arch, 'OK'
304
305
306 def detect_version(fname):
307     with open(fname, 'r') as f:
308         ver_pattern = re.compile("# Linux/.* Kernel Configuration")
309         for line in f.readlines():
310             if ver_pattern.match(line):
311                 line = line.strip()
312                 parts = line.split()
313                 ver_str = parts[2]
314                 ver_numbers = ver_str.split('.')
315                 if len(ver_numbers) < 3 or not ver_numbers[0].isdigit() or not ver_numbers[1].isdigit():
316                     msg = 'failed to parse the version "' + ver_str + '"'
317                     return None, msg
318                 return (int(ver_numbers[0]), int(ver_numbers[1])), None
319         return None, 'no kernel version detected'
320
321
322 def add_kconfig_checks(l, arch):
323     # Calling the KconfigCheck class constructor:
324     #     KconfigCheck(reason, decision, name, expected)
325
326     modules_not_set = KconfigCheck('cut_attack_surface', 'kspp', 'MODULES', 'is not set')
327     devmem_not_set = KconfigCheck('cut_attack_surface', 'kspp', 'DEVMEM', 'is not set') # refers to LOCKDOWN
328
329     # 'self_protection', 'defconfig'
330     l += [KconfigCheck('self_protection', 'defconfig', 'BUG', 'y')]
331     l += [KconfigCheck('self_protection', 'defconfig', 'SLUB_DEBUG', 'y')]
332     l += [KconfigCheck('self_protection', 'defconfig', 'GCC_PLUGINS', 'y')]
333     l += [OR(KconfigCheck('self_protection', 'defconfig', 'STACKPROTECTOR_STRONG', 'y'),
334              KconfigCheck('self_protection', 'defconfig', 'CC_STACKPROTECTOR_STRONG', 'y'))]
335     l += [OR(KconfigCheck('self_protection', 'defconfig', 'STRICT_KERNEL_RWX', 'y'),
336              KconfigCheck('self_protection', 'defconfig', 'DEBUG_RODATA', 'y'))] # before v4.11
337     l += [OR(KconfigCheck('self_protection', 'defconfig', 'STRICT_MODULE_RWX', 'y'),
338              KconfigCheck('self_protection', 'defconfig', 'DEBUG_SET_MODULE_RONX', 'y'),
339              modules_not_set)] # DEBUG_SET_MODULE_RONX was before v4.11
340     l += [OR(KconfigCheck('self_protection', 'defconfig', 'REFCOUNT_FULL', 'y'),
341              VersionCheck((5, 5)))] # REFCOUNT_FULL is enabled by default since v5.5
342     iommu_support_is_set = KconfigCheck('self_protection', 'defconfig', 'IOMMU_SUPPORT', 'y')
343     l += [iommu_support_is_set] # is needed for mitigating DMA attacks
344     if arch in ('X86_64', 'ARM64', 'X86_32'):
345         l += [KconfigCheck('self_protection', 'defconfig', 'RANDOMIZE_BASE', 'y')]
346         l += [KconfigCheck('self_protection', 'defconfig', 'THREAD_INFO_IN_TASK', 'y')]
347     if arch in ('X86_64', 'ARM64'):
348         l += [KconfigCheck('self_protection', 'defconfig', 'VMAP_STACK', 'y')]
349     if arch in ('X86_64', 'X86_32'):
350         l += [KconfigCheck('self_protection', 'defconfig', 'MICROCODE', 'y')] # is needed for mitigating CPU bugs
351         l += [KconfigCheck('self_protection', 'defconfig', 'RETPOLINE', 'y')]
352         l += [KconfigCheck('self_protection', 'defconfig', 'X86_SMAP', 'y')]
353         l += [KconfigCheck('self_protection', 'defconfig', 'SYN_COOKIES', 'y')] # another reason?
354         l += [OR(KconfigCheck('self_protection', 'defconfig', 'X86_UMIP', 'y'),
355                  KconfigCheck('self_protection', 'defconfig', 'X86_INTEL_UMIP', 'y'))]
356     if arch in ('ARM64', 'ARM'):
357         l += [KconfigCheck('self_protection', 'defconfig', 'STACKPROTECTOR_PER_TASK', 'y')]
358     if arch == 'X86_64':
359         l += [KconfigCheck('self_protection', 'defconfig', 'PAGE_TABLE_ISOLATION', 'y')]
360         l += [KconfigCheck('self_protection', 'defconfig', 'RANDOMIZE_MEMORY', 'y')]
361         l += [AND(KconfigCheck('self_protection', 'defconfig', 'INTEL_IOMMU', 'y'),
362                   iommu_support_is_set)]
363         l += [AND(KconfigCheck('self_protection', 'defconfig', 'AMD_IOMMU', 'y'),
364                   iommu_support_is_set)]
365     if arch == 'ARM64':
366         l += [KconfigCheck('self_protection', 'defconfig', 'ARM64_PAN', 'y')]
367         l += [KconfigCheck('self_protection', 'defconfig', 'ARM64_EPAN', 'y')]
368         l += [KconfigCheck('self_protection', 'defconfig', 'UNMAP_KERNEL_AT_EL0', 'y')]
369         l += [OR(KconfigCheck('self_protection', 'defconfig', 'HARDEN_EL2_VECTORS', 'y'),
370                  AND(KconfigCheck('self_protection', 'defconfig', 'RANDOMIZE_BASE', 'y'),
371                      VersionCheck((5, 9))))] # HARDEN_EL2_VECTORS was included in RANDOMIZE_BASE in v5.9
372         l += [KconfigCheck('self_protection', 'defconfig', 'RODATA_FULL_DEFAULT_ENABLED', 'y')]
373         l += [KconfigCheck('self_protection', 'defconfig', 'ARM64_PTR_AUTH_KERNEL', 'y')]
374         l += [KconfigCheck('self_protection', 'defconfig', 'ARM64_BTI_KERNEL', 'y')]
375         l += [OR(KconfigCheck('self_protection', 'defconfig', 'HARDEN_BRANCH_PREDICTOR', 'y'),
376                  VersionCheck((5, 10)))] # HARDEN_BRANCH_PREDICTOR is enabled by default since v5.10
377         l += [KconfigCheck('self_protection', 'defconfig', 'ARM64_MTE', 'y')]
378     if arch == 'ARM':
379         l += [KconfigCheck('self_protection', 'defconfig', 'CPU_SW_DOMAIN_PAN', 'y')]
380         l += [KconfigCheck('self_protection', 'defconfig', 'HARDEN_BRANCH_PREDICTOR', 'y')]
381
382     # 'self_protection', 'kspp'
383     l += [KconfigCheck('self_protection', 'kspp', 'SECURITY_DMESG_RESTRICT', 'y')]
384     l += [KconfigCheck('self_protection', 'kspp', 'BUG_ON_DATA_CORRUPTION', 'y')]
385     l += [KconfigCheck('self_protection', 'kspp', 'DEBUG_WX', 'y')]
386     l += [KconfigCheck('self_protection', 'kspp', 'SCHED_STACK_END_CHECK', 'y')]
387     l += [KconfigCheck('self_protection', 'kspp', 'SLAB_FREELIST_HARDENED', 'y')]
388     l += [KconfigCheck('self_protection', 'kspp', 'SLAB_FREELIST_RANDOM', 'y')]
389     l += [KconfigCheck('self_protection', 'kspp', 'SHUFFLE_PAGE_ALLOCATOR', 'y')]
390     l += [KconfigCheck('self_protection', 'kspp', 'FORTIFY_SOURCE', 'y')]
391     l += [KconfigCheck('self_protection', 'kspp', 'DEBUG_LIST', 'y')]
392     l += [KconfigCheck('self_protection', 'kspp', 'DEBUG_SG', 'y')]
393     l += [KconfigCheck('self_protection', 'kspp', 'DEBUG_CREDENTIALS', 'y')]
394     l += [KconfigCheck('self_protection', 'kspp', 'DEBUG_NOTIFIERS', 'y')]
395     l += [KconfigCheck('self_protection', 'kspp', 'INIT_ON_ALLOC_DEFAULT_ON', 'y')]
396     l += [KconfigCheck('self_protection', 'kspp', 'GCC_PLUGIN_LATENT_ENTROPY', 'y')]
397     randstruct_is_set = KconfigCheck('self_protection', 'kspp', 'GCC_PLUGIN_RANDSTRUCT', 'y')
398     l += [randstruct_is_set]
399     hardened_usercopy_is_set = KconfigCheck('self_protection', 'kspp', 'HARDENED_USERCOPY', 'y')
400     l += [hardened_usercopy_is_set]
401     l += [AND(KconfigCheck('self_protection', 'kspp', 'HARDENED_USERCOPY_FALLBACK', 'is not set'),
402               hardened_usercopy_is_set)]
403     l += [AND(KconfigCheck('self_protection', 'kspp', 'HARDENED_USERCOPY_PAGESPAN', 'is not set'),
404               hardened_usercopy_is_set)]
405     l += [OR(KconfigCheck('self_protection', 'kspp', 'MODULE_SIG', 'y'),
406              modules_not_set)]
407     l += [OR(KconfigCheck('self_protection', 'kspp', 'MODULE_SIG_ALL', 'y'),
408              modules_not_set)]
409     l += [OR(KconfigCheck('self_protection', 'kspp', 'MODULE_SIG_SHA512', 'y'),
410              modules_not_set)]
411     l += [OR(KconfigCheck('self_protection', 'kspp', 'MODULE_SIG_FORCE', 'y'),
412              modules_not_set)] # refers to LOCKDOWN
413     l += [OR(KconfigCheck('self_protection', 'kspp', 'INIT_STACK_ALL_ZERO', 'y'),
414              KconfigCheck('self_protection', 'kspp', 'GCC_PLUGIN_STRUCTLEAK_BYREF_ALL', 'y'))]
415     l += [OR(KconfigCheck('self_protection', 'kspp', 'INIT_ON_FREE_DEFAULT_ON', 'y'),
416              KconfigCheck('self_protection', 'kspp', 'PAGE_POISONING_ZERO', 'y'))]
417              # CONFIG_INIT_ON_FREE_DEFAULT_ON was added in v5.3.
418              # CONFIG_PAGE_POISONING_ZERO was removed in v5.11.
419              # Starting from v5.11 CONFIG_PAGE_POISONING unconditionally checks
420              # the 0xAA poison pattern on allocation.
421              # That brings higher performance penalty.
422     if arch in ('X86_64', 'ARM64', 'X86_32'):
423         stackleak_is_set = KconfigCheck('self_protection', 'kspp', 'GCC_PLUGIN_STACKLEAK', 'y')
424         l += [stackleak_is_set]
425         l += [KconfigCheck('self_protection', 'kspp', 'RANDOMIZE_KSTACK_OFFSET_DEFAULT', 'y')]
426     if arch in ('X86_64', 'X86_32'):
427         l += [KconfigCheck('self_protection', 'kspp', 'DEFAULT_MMAP_MIN_ADDR', '65536')]
428     if arch in ('ARM64', 'ARM'):
429         l += [KconfigCheck('self_protection', 'kspp', 'DEFAULT_MMAP_MIN_ADDR', '32768')]
430         l += [KconfigCheck('self_protection', 'kspp', 'SYN_COOKIES', 'y')] # another reason?
431     if arch == 'ARM64':
432         l += [KconfigCheck('self_protection', 'kspp', 'ARM64_SW_TTBR0_PAN', 'y')]
433     if arch == 'X86_32':
434         l += [KconfigCheck('self_protection', 'kspp', 'PAGE_TABLE_ISOLATION', 'y')]
435         l += [KconfigCheck('self_protection', 'kspp', 'HIGHMEM64G', 'y')]
436         l += [KconfigCheck('self_protection', 'kspp', 'X86_PAE', 'y')]
437
438     # 'self_protection', 'maintainer'
439     ubsan_bounds_is_set = KconfigCheck('self_protection', 'maintainer', 'UBSAN_BOUNDS', 'y') # only array index bounds checking
440     l += [ubsan_bounds_is_set] # recommended by Kees Cook in /issues/53
441     l += [AND(KconfigCheck('self_protection', 'maintainer', 'UBSAN_SANITIZE_ALL', 'y'),
442               ubsan_bounds_is_set)] # recommended by Kees Cook in /issues/53
443     l += [AND(KconfigCheck('self_protection', 'maintainer', 'UBSAN_TRAP', 'y'),
444               ubsan_bounds_is_set)] # recommended by Kees Cook in /issues/53
445
446     # 'self_protection', 'clipos'
447     l += [KconfigCheck('self_protection', 'clipos', 'DEBUG_VIRTUAL', 'y')]
448     l += [KconfigCheck('self_protection', 'clipos', 'STATIC_USERMODEHELPER', 'y')] # needs userspace support
449     l += [KconfigCheck('self_protection', 'clipos', 'EFI_DISABLE_PCI_DMA', 'y')]
450     l += [KconfigCheck('self_protection', 'clipos', 'SLAB_MERGE_DEFAULT', 'is not set')] # slab_nomerge
451     l += [KconfigCheck('self_protection', 'clipos', 'RANDOM_TRUST_BOOTLOADER', 'is not set')]
452     l += [KconfigCheck('self_protection', 'clipos', 'RANDOM_TRUST_CPU', 'is not set')]
453     l += [AND(KconfigCheck('self_protection', 'clipos', 'GCC_PLUGIN_RANDSTRUCT_PERFORMANCE', 'is not set'),
454               randstruct_is_set)]
455     if arch in ('X86_64', 'ARM64', 'X86_32'):
456         l += [AND(KconfigCheck('self_protection', 'clipos', 'STACKLEAK_METRICS', 'is not set'),
457                   stackleak_is_set)]
458         l += [AND(KconfigCheck('self_protection', 'clipos', 'STACKLEAK_RUNTIME_DISABLE', 'is not set'),
459                   stackleak_is_set)]
460     if arch in ('X86_64', 'X86_32'):
461         l += [AND(KconfigCheck('self_protection', 'clipos', 'INTEL_IOMMU_DEFAULT_ON', 'y'),
462                   iommu_support_is_set)]
463     if arch == 'X86_64':
464         l += [AND(KconfigCheck('self_protection', 'clipos', 'INTEL_IOMMU_SVM', 'y'),
465                   iommu_support_is_set)]
466     if arch == 'X86_32':
467         l += [AND(KconfigCheck('self_protection', 'clipos', 'INTEL_IOMMU', 'y'),
468                   iommu_support_is_set)]
469
470     # 'self_protection', 'my'
471     l += [KconfigCheck('self_protection', 'my', 'RESET_ATTACK_MITIGATION', 'y')] # needs userspace support (systemd)
472     if arch == 'X86_64':
473         l += [AND(KconfigCheck('self_protection', 'my', 'AMD_IOMMU_V2', 'y'),
474                   iommu_support_is_set)]
475     if arch == 'ARM64':
476         l += [KconfigCheck('self_protection', 'my', 'SHADOW_CALL_STACK', 'y')] # depends on clang, maybe it's alternative to STACKPROTECTOR_STRONG
477         l += [KconfigCheck('self_protection', 'my', 'KASAN_HW_TAGS', 'y')]
478         cfi_clang_is_set = KconfigCheck('self_protection', 'my', 'CFI_CLANG', 'y')
479         l += [cfi_clang_is_set]
480         l += [AND(KconfigCheck('self_protection', 'my', 'CFI_PERMISSIVE', 'is not set'),
481                   cfi_clang_is_set)]
482
483     # 'security_policy'
484     if arch in ('X86_64', 'ARM64', 'X86_32'):
485         l += [KconfigCheck('security_policy', 'defconfig', 'SECURITY', 'y')] # and choose your favourite LSM
486     if arch == 'ARM':
487         l += [KconfigCheck('security_policy', 'kspp', 'SECURITY', 'y')] # and choose your favourite LSM
488     l += [KconfigCheck('security_policy', 'kspp', 'SECURITY_YAMA', 'y')]
489     l += [OR(KconfigCheck('security_policy', 'my', 'SECURITY_WRITABLE_HOOKS', 'is not set'),
490              KconfigCheck('security_policy', 'kspp', 'SECURITY_SELINUX_DISABLE', 'is not set'))]
491     l += [KconfigCheck('security_policy', 'clipos', 'SECURITY_LOCKDOWN_LSM', 'y')]
492     l += [KconfigCheck('security_policy', 'clipos', 'SECURITY_LOCKDOWN_LSM_EARLY', 'y')]
493     l += [KconfigCheck('security_policy', 'clipos', 'LOCK_DOWN_KERNEL_FORCE_CONFIDENTIALITY', 'y')]
494     l += [KconfigCheck('security_policy', 'my', 'SECURITY_SAFESETID', 'y')]
495     loadpin_is_set = KconfigCheck('security_policy', 'my', 'SECURITY_LOADPIN', 'y')
496     l += [loadpin_is_set] # needs userspace support
497     l += [AND(KconfigCheck('security_policy', 'my', 'SECURITY_LOADPIN_ENFORCE', 'y'),
498               loadpin_is_set)]
499
500     # 'cut_attack_surface', 'defconfig'
501     l += [KconfigCheck('cut_attack_surface', 'defconfig', 'SECCOMP', 'y')]
502     l += [KconfigCheck('cut_attack_surface', 'defconfig', 'SECCOMP_FILTER', 'y')]
503     if arch in ('X86_64', 'ARM64', 'X86_32'):
504         l += [OR(KconfigCheck('cut_attack_surface', 'defconfig', 'STRICT_DEVMEM', 'y'),
505                  devmem_not_set)] # refers to LOCKDOWN
506
507     # 'cut_attack_surface', 'kspp'
508     l += [KconfigCheck('cut_attack_surface', 'kspp', 'ACPI_CUSTOM_METHOD', 'is not set')] # refers to LOCKDOWN
509     l += [KconfigCheck('cut_attack_surface', 'kspp', 'COMPAT_BRK', 'is not set')]
510     l += [KconfigCheck('cut_attack_surface', 'kspp', 'DEVKMEM', 'is not set')] # refers to LOCKDOWN
511     l += [KconfigCheck('cut_attack_surface', 'kspp', 'COMPAT_VDSO', 'is not set')]
512     l += [KconfigCheck('cut_attack_surface', 'kspp', 'BINFMT_MISC', 'is not set')]
513     l += [KconfigCheck('cut_attack_surface', 'kspp', 'INET_DIAG', 'is not set')]
514     l += [KconfigCheck('cut_attack_surface', 'kspp', 'KEXEC', 'is not set')] # refers to LOCKDOWN
515     l += [KconfigCheck('cut_attack_surface', 'kspp', 'PROC_KCORE', 'is not set')] # refers to LOCKDOWN
516     l += [KconfigCheck('cut_attack_surface', 'kspp', 'LEGACY_PTYS', 'is not set')]
517     l += [KconfigCheck('cut_attack_surface', 'kspp', 'HIBERNATION', 'is not set')] # refers to LOCKDOWN
518     l += [KconfigCheck('cut_attack_surface', 'kspp', 'IA32_EMULATION', 'is not set')]
519     l += [KconfigCheck('cut_attack_surface', 'kspp', 'X86_X32', 'is not set')]
520     l += [KconfigCheck('cut_attack_surface', 'kspp', 'MODIFY_LDT_SYSCALL', 'is not set')]
521     l += [KconfigCheck('cut_attack_surface', 'kspp', 'OABI_COMPAT', 'is not set')]
522     l += [modules_not_set]
523     l += [devmem_not_set]
524     l += [OR(KconfigCheck('cut_attack_surface', 'kspp', 'IO_STRICT_DEVMEM', 'y'),
525              devmem_not_set)] # refers to LOCKDOWN
526     if arch == 'ARM':
527         l += [OR(KconfigCheck('cut_attack_surface', 'kspp', 'STRICT_DEVMEM', 'y'),
528                  devmem_not_set)] # refers to LOCKDOWN
529     if arch == 'X86_64':
530         l += [KconfigCheck('cut_attack_surface', 'kspp', 'LEGACY_VSYSCALL_NONE', 'y')] # 'vsyscall=none'
531
532     # 'cut_attack_surface', 'grsec'
533     l += [KconfigCheck('cut_attack_surface', 'grsec', 'ZSMALLOC_STAT', 'is not set')]
534     l += [KconfigCheck('cut_attack_surface', 'grsec', 'PAGE_OWNER', 'is not set')]
535     l += [KconfigCheck('cut_attack_surface', 'grsec', 'DEBUG_KMEMLEAK', 'is not set')]
536     l += [KconfigCheck('cut_attack_surface', 'grsec', 'BINFMT_AOUT', 'is not set')]
537     l += [KconfigCheck('cut_attack_surface', 'grsec', 'KPROBE_EVENTS', 'is not set')]
538     l += [KconfigCheck('cut_attack_surface', 'grsec', 'UPROBE_EVENTS', 'is not set')]
539     l += [KconfigCheck('cut_attack_surface', 'grsec', 'GENERIC_TRACER', 'is not set')] # refers to LOCKDOWN
540     l += [KconfigCheck('cut_attack_surface', 'grsec', 'FUNCTION_TRACER', 'is not set')]
541     l += [KconfigCheck('cut_attack_surface', 'grsec', 'STACK_TRACER', 'is not set')]
542     l += [KconfigCheck('cut_attack_surface', 'grsec', 'HIST_TRIGGERS', 'is not set')]
543     l += [KconfigCheck('cut_attack_surface', 'grsec', 'BLK_DEV_IO_TRACE', 'is not set')]
544     l += [KconfigCheck('cut_attack_surface', 'grsec', 'PROC_VMCORE', 'is not set')]
545     l += [KconfigCheck('cut_attack_surface', 'grsec', 'PROC_PAGE_MONITOR', 'is not set')]
546     l += [KconfigCheck('cut_attack_surface', 'grsec', 'USELIB', 'is not set')]
547     l += [KconfigCheck('cut_attack_surface', 'grsec', 'CHECKPOINT_RESTORE', 'is not set')]
548     l += [KconfigCheck('cut_attack_surface', 'grsec', 'USERFAULTFD', 'is not set')]
549     l += [KconfigCheck('cut_attack_surface', 'grsec', 'HWPOISON_INJECT', 'is not set')]
550     l += [KconfigCheck('cut_attack_surface', 'grsec', 'MEM_SOFT_DIRTY', 'is not set')]
551     l += [KconfigCheck('cut_attack_surface', 'grsec', 'DEVPORT', 'is not set')] # refers to LOCKDOWN
552     l += [KconfigCheck('cut_attack_surface', 'grsec', 'DEBUG_FS', 'is not set')] # refers to LOCKDOWN
553     l += [KconfigCheck('cut_attack_surface', 'grsec', 'NOTIFIER_ERROR_INJECTION', 'is not set')]
554     l += [KconfigCheck('cut_attack_surface', 'grsec', 'FAIL_FUTEX', 'is not set')]
555     l += [KconfigCheck('cut_attack_surface', 'grsec', 'PUNIT_ATOM_DEBUG', 'is not set')]
556     l += [KconfigCheck('cut_attack_surface', 'grsec', 'ACPI_CONFIGFS', 'is not set')]
557     l += [KconfigCheck('cut_attack_surface', 'grsec', 'EDAC_DEBUG', 'is not set')]
558     l += [KconfigCheck('cut_attack_surface', 'grsec', 'DRM_I915_DEBUG', 'is not set')]
559     l += [KconfigCheck('cut_attack_surface', 'grsec', 'BCACHE_CLOSURES_DEBUG', 'is not set')]
560     l += [KconfigCheck('cut_attack_surface', 'grsec', 'DVB_C8SECTPFE', 'is not set')]
561     l += [KconfigCheck('cut_attack_surface', 'grsec', 'MTD_SLRAM', 'is not set')]
562     l += [KconfigCheck('cut_attack_surface', 'grsec', 'MTD_PHRAM', 'is not set')]
563     l += [KconfigCheck('cut_attack_surface', 'grsec', 'IO_URING', 'is not set')]
564     l += [KconfigCheck('cut_attack_surface', 'grsec', 'KCMP', 'is not set')]
565     l += [KconfigCheck('cut_attack_surface', 'grsec', 'RSEQ', 'is not set')]
566     l += [KconfigCheck('cut_attack_surface', 'grsec', 'LATENCYTOP', 'is not set')]
567     l += [KconfigCheck('cut_attack_surface', 'grsec', 'KCOV', 'is not set')]
568     l += [KconfigCheck('cut_attack_surface', 'grsec', 'PROVIDE_OHCI1394_DMA_INIT', 'is not set')]
569     l += [KconfigCheck('cut_attack_surface', 'grsec', 'SUNRPC_DEBUG', 'is not set')]
570     l += [AND(KconfigCheck('cut_attack_surface', 'grsec', 'PTDUMP_DEBUGFS', 'is not set'),
571               KconfigCheck('cut_attack_surface', 'grsec', 'X86_PTDUMP', 'is not set'))]
572
573     # 'cut_attack_surface', 'maintainer'
574     l += [KconfigCheck('cut_attack_surface', 'maintainer', 'DRM_LEGACY', 'is not set')] # recommended by Daniel Vetter in /issues/38
575     l += [KconfigCheck('cut_attack_surface', 'maintainer', 'FB', 'is not set')] # recommended by Daniel Vetter in /issues/38
576     l += [KconfigCheck('cut_attack_surface', 'maintainer', 'VT', 'is not set')] # recommended by Daniel Vetter in /issues/38
577     l += [KconfigCheck('cut_attack_surface', 'maintainer', 'BLK_DEV_FD', 'is not set')] # recommended by Denis Efremov in /pull/54
578
579     # 'cut_attack_surface', 'grapheneos'
580     l += [KconfigCheck('cut_attack_surface', 'grapheneos', 'AIO', 'is not set')]
581
582     # 'cut_attack_surface', 'clipos'
583     l += [KconfigCheck('cut_attack_surface', 'clipos', 'STAGING', 'is not set')]
584     l += [KconfigCheck('cut_attack_surface', 'clipos', 'KSM', 'is not set')] # to prevent FLUSH+RELOAD attack
585 #   l += [KconfigCheck('cut_attack_surface', 'clipos', 'IKCONFIG', 'is not set')] # no, IKCONFIG is needed for this check :)
586     l += [KconfigCheck('cut_attack_surface', 'clipos', 'KALLSYMS', 'is not set')]
587     l += [KconfigCheck('cut_attack_surface', 'clipos', 'X86_VSYSCALL_EMULATION', 'is not set')]
588     l += [KconfigCheck('cut_attack_surface', 'clipos', 'MAGIC_SYSRQ', 'is not set')]
589     l += [KconfigCheck('cut_attack_surface', 'clipos', 'KEXEC_FILE', 'is not set')] # refers to LOCKDOWN (permissive)
590     l += [KconfigCheck('cut_attack_surface', 'clipos', 'USER_NS', 'is not set')] # user.max_user_namespaces=0
591     l += [KconfigCheck('cut_attack_surface', 'clipos', 'X86_MSR', 'is not set')] # refers to LOCKDOWN
592     l += [KconfigCheck('cut_attack_surface', 'clipos', 'X86_CPUID', 'is not set')]
593     l += [KconfigCheck('cut_attack_surface', 'clipos', 'X86_IOPL_IOPERM', 'is not set')] # refers to LOCKDOWN
594     l += [KconfigCheck('cut_attack_surface', 'clipos', 'ACPI_TABLE_UPGRADE', 'is not set')] # refers to LOCKDOWN
595     l += [KconfigCheck('cut_attack_surface', 'clipos', 'EFI_CUSTOM_SSDT_OVERLAYS', 'is not set')]
596     l += [AND(KconfigCheck('cut_attack_surface', 'clipos', 'LDISC_AUTOLOAD', 'is not set'),
597               PresenceCheck('LDISC_AUTOLOAD', 'kconfig'))]
598     if arch in ('X86_64', 'X86_32'):
599         l += [KconfigCheck('cut_attack_surface', 'clipos', 'X86_INTEL_TSX_MODE_OFF', 'y')] # tsx=off
600
601     # 'cut_attack_surface', 'lockdown'
602     l += [KconfigCheck('cut_attack_surface', 'lockdown', 'EFI_TEST', 'is not set')] # refers to LOCKDOWN
603     l += [KconfigCheck('cut_attack_surface', 'lockdown', 'BPF_SYSCALL', 'is not set')] # refers to LOCKDOWN
604     l += [KconfigCheck('cut_attack_surface', 'lockdown', 'MMIOTRACE_TEST', 'is not set')] # refers to LOCKDOWN
605     l += [KconfigCheck('cut_attack_surface', 'lockdown', 'KPROBES', 'is not set')] # refers to LOCKDOWN
606
607     # 'cut_attack_surface', 'my'
608     l += [OR(KconfigCheck('cut_attack_surface', 'my', 'TRIM_UNUSED_KSYMS', 'y'),
609              modules_not_set)]
610     l += [KconfigCheck('cut_attack_surface', 'my', 'BPF_UNPRIV_DEFAULT_OFF', 'y')] # see kernel.unprivileged_bpf_disabled
611     l += [KconfigCheck('cut_attack_surface', 'my', 'MMIOTRACE', 'is not set')] # refers to LOCKDOWN (permissive)
612     l += [KconfigCheck('cut_attack_surface', 'my', 'LIVEPATCH', 'is not set')]
613     l += [KconfigCheck('cut_attack_surface', 'my', 'IP_DCCP', 'is not set')]
614     l += [KconfigCheck('cut_attack_surface', 'my', 'IP_SCTP', 'is not set')]
615     l += [KconfigCheck('cut_attack_surface', 'my', 'FTRACE', 'is not set')] # refers to LOCKDOWN
616     l += [KconfigCheck('cut_attack_surface', 'my', 'VIDEO_VIVID', 'is not set')]
617     l += [KconfigCheck('cut_attack_surface', 'my', 'INPUT_EVBUG', 'is not set')] # Can be used as a keylogger
618
619     # 'harden_userspace'
620     if arch in ('X86_64', 'ARM64', 'X86_32'):
621         l += [KconfigCheck('harden_userspace', 'defconfig', 'INTEGRITY', 'y')]
622     if arch == 'ARM':
623         l += [KconfigCheck('harden_userspace', 'my', 'INTEGRITY', 'y')]
624     if arch == 'ARM64':
625         l += [KconfigCheck('harden_userspace', 'defconfig', 'ARM64_MTE', 'y')]
626     if arch in ('ARM', 'X86_32'):
627         l += [KconfigCheck('harden_userspace', 'defconfig', 'VMSPLIT_3G', 'y')]
628     if arch in ('X86_64', 'ARM64'):
629         l += [KconfigCheck('harden_userspace', 'clipos', 'ARCH_MMAP_RND_BITS', '32')]
630     if arch in ('X86_32', 'ARM'):
631         l += [KconfigCheck('harden_userspace', 'my', 'ARCH_MMAP_RND_BITS', '16')]
632
633 #   l += [KconfigCheck('feature_test', 'my', 'LKDTM', 'm')] # only for debugging!
634
635
636 def print_unknown_options(checklist, parsed_options):
637     known_options = []
638
639     for o1 in checklist:
640         if o1.type != 'complex':
641             known_options.append(o1.name)
642             continue
643         for o2 in o1.opts:
644             if o2.type != 'complex':
645                 if hasattr(o2, 'name'):
646                     known_options.append(o2.name)
647                 continue
648             for o3 in o2.opts:
649                 if o3.type == 'complex':
650                     sys.exit('[!] ERROR: unexpected ComplexOptCheck inside {}'.format(o2.name))
651                 if hasattr(o3, 'name'):
652                     known_options.append(o3.name)
653
654     for option, value in parsed_options.items():
655         if option not in known_options:
656             print('[?] No check for option {} ({})'.format(option, value))
657
658
659 def print_checklist(mode, checklist, with_results):
660     if mode == 'json':
661         output = []
662         for o in checklist:
663             output.append(o.json_dump(with_results))
664         print(json.dumps(output))
665         return
666
667     # table header
668     sep_line_len = 91
669     if with_results:
670         sep_line_len += 30
671     print('=' * sep_line_len)
672     print('{:^40}|{:^7}|{:^12}|{:^10}|{:^18}'.format('option name', 'type', 'desired val', 'decision', 'reason'), end='')
673     if with_results:
674         print('| {}'.format('check result'), end='')
675     print()
676     print('=' * sep_line_len)
677
678     # table contents
679     for opt in checklist:
680         if with_results:
681             if mode == 'show_ok':
682                 if not opt.result.startswith('OK'):
683                     continue
684             if mode == 'show_fail':
685                 if not opt.result.startswith('FAIL'):
686                     continue
687         opt.table_print(mode, with_results)
688         print()
689         if mode == 'verbose':
690             print('-' * sep_line_len)
691     print()
692
693     # final score
694     if with_results:
695         fail_count = len(list(filter(lambda opt: opt.result.startswith('FAIL'), checklist)))
696         fail_suppressed = ''
697         ok_count = len(list(filter(lambda opt: opt.result.startswith('OK'), checklist)))
698         ok_suppressed = ''
699         if mode == 'show_ok':
700             fail_suppressed = ' (suppressed in output)'
701         if mode == 'show_fail':
702             ok_suppressed = ' (suppressed in output)'
703         if mode != 'json':
704             print('[+] Config check is finished: \'OK\' - {}{} / \'FAIL\' - {}{}'.format(ok_count, ok_suppressed, fail_count, fail_suppressed))
705
706
707 def populate_simple_opt_with_data(opt, data, data_type):
708     if opt.type == 'complex':
709         sys.exit('[!] ERROR: unexpected ComplexOptCheck {}: {}'.format(opt.name, vars(opt)))
710     if data_type not in TYPES_OF_CHECKS:
711         sys.exit('[!] ERROR: invalid data type "{}"'.format(data_type))
712
713     if data_type != opt.type:
714         return
715
716     if data_type == 'kconfig':
717         opt.state = data.get(opt.name, None)
718     elif data_type == 'version':
719         opt.ver = data
720
721
722 def populate_opt_with_data(opt, data, data_type):
723     if opt.type == 'complex':
724         for o in opt.opts:
725             if o.type == 'complex':
726                 # Recursion for nested ComplexOptCheck objects
727                 populate_opt_with_data(o, data, data_type)
728             else:
729                 populate_simple_opt_with_data(o, data, data_type)
730     else:
731         if opt.type != 'kconfig':
732             sys.exit('[!] ERROR: bad type "{}" for a simple check {}'.format(opt.type, opt.name))
733         populate_simple_opt_with_data(opt, data, data_type)
734
735
736 def populate_with_data(checklist, data, data_type):
737     for opt in checklist:
738         populate_opt_with_data(opt, data, data_type)
739
740
741 def perform_checks(checklist):
742     for opt in checklist:
743         opt.check()
744
745
746 def parse_kconfig_file(parsed_options, fname):
747     with open(fname, 'r') as f:
748         opt_is_on = re.compile("CONFIG_[a-zA-Z0-9_]*=[a-zA-Z0-9_\"]*")
749         opt_is_off = re.compile("# CONFIG_[a-zA-Z0-9_]* is not set")
750
751         for line in f.readlines():
752             line = line.strip()
753             option = None
754             value = None
755
756             if opt_is_on.match(line):
757                 option, value = line.split('=', 1)
758             elif opt_is_off.match(line):
759                 option, value = line[2:].split(' ', 1)
760                 if value != 'is not set':
761                     sys.exit('[!] ERROR: bad disabled kconfig option "{}"'.format(line))
762
763             if option in parsed_options:
764                 sys.exit('[!] ERROR: kconfig option "{}" exists multiple times'.format(line))
765
766             if option:
767                 parsed_options[option] = value
768
769         return parsed_options
770
771
772 def main():
773     # Report modes:
774     #   * verbose mode for
775     #     - reporting about unknown kernel options in the kconfig
776     #     - verbose printing of ComplexOptCheck items
777     #   * json mode for printing the results in JSON format
778     report_modes = ['verbose', 'json', 'show_ok', 'show_fail']
779     supported_archs = ['X86_64', 'X86_32', 'ARM64', 'ARM']
780     parser = ArgumentParser(prog='kconfig-hardened-check',
781                             description='A tool for checking the security hardening options of the Linux kernel')
782     parser.add_argument('--version', action='version', version='%(prog)s ' + __version__)
783     parser.add_argument('-p', '--print', choices=supported_archs,
784                         help='print security hardening preferences for the selected architecture')
785     parser.add_argument('-c', '--config',
786                         help='check the kernel kconfig file against these preferences')
787     parser.add_argument('-m', '--mode', choices=report_modes,
788                         help='choose the report mode')
789     args = parser.parse_args()
790
791     mode = None
792     if args.mode:
793         mode = args.mode
794         if mode != 'json':
795             print('[+] Special report mode: {}'.format(mode))
796
797     config_checklist = []
798
799     if args.config:
800         if mode != 'json':
801             print('[+] Kconfig file to check: {}'.format(args.config))
802
803         arch, msg = detect_arch(args.config, supported_archs)
804         if not arch:
805             sys.exit('[!] ERROR: {}'.format(msg))
806         if mode != 'json':
807             print('[+] Detected architecture: {}'.format(arch))
808
809         kernel_version, msg = detect_version(args.config)
810         if not kernel_version:
811             sys.exit('[!] ERROR: {}'.format(msg))
812         if mode != 'json':
813             print('[+] Detected kernel version: {}.{}'.format(kernel_version[0], kernel_version[1]))
814
815         # add relevant kconfig checks to the checklist
816         add_kconfig_checks(config_checklist, arch)
817
818         # populate the checklist with the parsed kconfig data
819         parsed_kconfig_options = OrderedDict()
820         parse_kconfig_file(parsed_kconfig_options, args.config)
821         populate_with_data(config_checklist, parsed_kconfig_options, 'kconfig')
822         populate_with_data(config_checklist, kernel_version, 'version')
823
824         # now everything is ready for performing the checks
825         perform_checks(config_checklist)
826
827         # finally print the results
828         if mode == 'verbose':
829             print_unknown_options(config_checklist, parsed_kconfig_options)
830         print_checklist(mode, config_checklist, True)
831
832         sys.exit(0)
833
834     if args.print:
835         if mode in ('show_ok', 'show_fail'):
836             sys.exit('[!] ERROR: wrong mode "{}" for --print'.format(mode))
837         arch = args.print
838         add_kconfig_checks(config_checklist, arch)
839         if mode != 'json':
840             print('[+] Printing kernel security hardening preferences for {}...'.format(arch))
841         print_checklist(mode, config_checklist, False)
842         sys.exit(0)
843
844     parser.print_help()
845     sys.exit(0)
846
847 if __name__ == '__main__':
848     main()