Add debian-sid-amd64.config
[kconfig-hardened-check.git] / kconfig-hardened-check.py
1 #!/usr/bin/python3
2
3 #
4 # This script helps me to check the Linux kernel Kconfig option list
5 # against my hardening preferences for x86_64. Let the computers do their job!
6 #
7 # Author: Alexander Popov <alex.popov@linux.com>
8 #
9 # Please don't cry if my Python code looks like C.
10 #
11
12 # N.B Hardening command line parameters:
13 #    page_poison=1
14 #    slub_debug=P
15 #    slab_nomerge
16 #    pti=on
17 #    kernel.kptr_restrict=1
18
19 import sys
20 from argparse import ArgumentParser
21 from collections import OrderedDict
22 import re
23
24 debug_mode = False  # set it to True to print the unknown options from the config
25 checklist = []
26
27
28 class OptCheck:
29     def __init__(self, name, expected, decision, reason):
30         self.name = name
31         self.expected = expected
32         self.decision = decision
33         self.reason = reason
34         self.state = None
35         self.result = None
36
37     def check(self):
38         if self.expected == self.state:
39             self.result = 'OK'
40         elif self.state is None:
41             if self.expected == 'is not set':
42                 self.result = 'OK: not found'
43             else:
44                 self.result = 'FAIL: not found'
45         else:
46             self.result = 'FAIL: "' + self.state + '"'
47
48     def __repr__(self):
49         return '{} = {}'.format(self.name, self.state)
50
51
52 def construct_opt_checks():
53     checklist.append(OptCheck('BUG',                     'y', 'ubuntu18', 'self_protection'))
54     checklist.append(OptCheck('PAGE_TABLE_ISOLATION',    'y', 'ubuntu18', 'self_protection'))
55     checklist.append(OptCheck('RETPOLINE',               'y', 'ubuntu18', 'self_protection'))
56     checklist.append(OptCheck('X86_64',                  'y', 'ubuntu18', 'self_protection'))
57     checklist.append(OptCheck('STRICT_KERNEL_RWX',       'y', 'ubuntu18', 'self_protection'))
58     checklist.append(OptCheck('STRICT_MODULE_RWX',       'y', 'ubuntu18', 'self_protection'))
59     checklist.append(OptCheck('DEBUG_WX',                'y', 'ubuntu18', 'self_protection'))
60     checklist.append(OptCheck('RANDOMIZE_BASE',          'y', 'ubuntu18', 'self_protection'))
61     checklist.append(OptCheck('RANDOMIZE_MEMORY',        'y', 'ubuntu18', 'self_protection'))
62     checklist.append(OptCheck('CC_STACKPROTECTOR',       'y', 'ubuntu18', 'self_protection'))
63     checklist.append(OptCheck('CC_STACKPROTECTOR_STRONG','y', 'ubuntu18', 'self_protection'))
64     checklist.append(OptCheck('VMAP_STACK',              'y', 'ubuntu18', 'self_protection'))
65     checklist.append(OptCheck('THREAD_INFO_IN_TASK',     'y', 'ubuntu18', 'self_protection'))
66     checklist.append(OptCheck('SCHED_STACK_END_CHECK',   'y', 'ubuntu18', 'self_protection'))
67     checklist.append(OptCheck('SLUB_DEBUG',              'y', 'ubuntu18', 'self_protection'))
68     checklist.append(OptCheck('SLAB_FREELIST_HARDENED',  'y', 'ubuntu18', 'self_protection'))
69     checklist.append(OptCheck('SLAB_FREELIST_RANDOM',    'y', 'ubuntu18', 'self_protection'))
70     checklist.append(OptCheck('HARDENED_USERCOPY',       'y', 'ubuntu18', 'self_protection'))
71     checklist.append(OptCheck('FORTIFY_SOURCE',          'y', 'ubuntu18', 'self_protection'))
72     checklist.append(OptCheck('MODULE_SIG',              'y', 'ubuntu18', 'self_protection'))
73     checklist.append(OptCheck('MODULE_SIG_ALL',          'y', 'ubuntu18', 'self_protection'))
74     checklist.append(OptCheck('MODULE_SIG_SHA512',       'y', 'ubuntu18', 'self_protection'))
75     checklist.append(OptCheck('SYN_COOKIES',             'y', 'ubuntu18', 'self_protection')) # another reason?
76     checklist.append(OptCheck('DEFAULT_MMAP_MIN_ADDR',   '65536', 'ubuntu18', 'self_protection'))
77
78     checklist.append(OptCheck('BUG_ON_DATA_CORRUPTION',           'y', 'kspp', 'self_protection'))
79     checklist.append(OptCheck('PAGE_POISONING',                   'y', 'kspp', 'self_protection'))
80     checklist.append(OptCheck('GCC_PLUGINS',                      'y', 'kspp', 'self_protection'))
81     checklist.append(OptCheck('GCC_PLUGIN_RANDSTRUCT',            'y', 'kspp', 'self_protection'))
82     checklist.append(OptCheck('GCC_PLUGIN_STRUCTLEAK',            'y', 'kspp', 'self_protection'))
83     checklist.append(OptCheck('GCC_PLUGIN_STRUCTLEAK_BYREF_ALL',  'y', 'kspp', 'self_protection'))
84     checklist.append(OptCheck('GCC_PLUGIN_LATENT_ENTROPY',        'y', 'kspp', 'self_protection'))
85     checklist.append(OptCheck('REFCOUNT_FULL',                    'y', 'kspp', 'self_protection'))
86     checklist.append(OptCheck('DEBUG_LIST',                       'y', 'kspp', 'self_protection'))
87     checklist.append(OptCheck('DEBUG_SG',                         'y', 'kspp', 'self_protection'))
88     checklist.append(OptCheck('DEBUG_CREDENTIALS',                'y', 'kspp', 'self_protection'))
89     checklist.append(OptCheck('DEBUG_NOTIFIERS',                  'y', 'kspp', 'self_protection'))
90     checklist.append(OptCheck('MODULE_SIG_FORCE',                 'y', 'kspp', 'self_protection'))
91     checklist.append(OptCheck('HARDENED_USERCOPY_FALLBACK',       'is not set', 'kspp', 'self_protection'))
92
93     checklist.append(OptCheck('GCC_PLUGIN_STACKLEAK',             'y', 'my', 'self_protection'))
94     checklist.append(OptCheck('SLUB_DEBUG_ON',                    'y', 'my', 'self_protection'))
95     checklist.append(OptCheck('SECURITY_DMESG_RESTRICT',          'y', 'my', 'self_protection'))
96     checklist.append(OptCheck('STATIC_USERMODEHELPER',            'y', 'my', 'self_protection')) # breaks systemd?
97     checklist.append(OptCheck('PAGE_POISONING_NO_SANITY',         'is not set', 'my', 'self_protection'))
98     checklist.append(OptCheck('PAGE_POISONING_ZERO',              'is not set', 'my', 'self_protection'))
99
100     checklist.append(OptCheck('SECURITY',                    'y', 'ubuntu18', 'security_policy'))
101     checklist.append(OptCheck('SECURITY_YAMA',               'y', 'ubuntu18', 'security_policy'))
102     checklist.append(OptCheck('SECURITY_SELINUX_DISABLE',    'is not set', 'ubuntu18', 'security_policy'))
103
104     checklist.append(OptCheck('SECCOMP',              'y', 'ubuntu18', 'cut_attack_surface'))
105     checklist.append(OptCheck('SECCOMP_FILTER',       'y', 'ubuntu18', 'cut_attack_surface'))
106     checklist.append(OptCheck('STRICT_DEVMEM',        'y', 'ubuntu18', 'cut_attack_surface'))
107     checklist.append(OptCheck('ACPI_CUSTOM_METHOD',   'is not set', 'ubuntu18', 'cut_attack_surface'))
108     checklist.append(OptCheck('COMPAT_BRK',           'is not set', 'ubuntu18', 'cut_attack_surface'))
109     checklist.append(OptCheck('DEVKMEM',              'is not set', 'ubuntu18', 'cut_attack_surface'))
110     checklist.append(OptCheck('COMPAT_VDSO',          'is not set', 'ubuntu18', 'cut_attack_surface'))
111     checklist.append(OptCheck('X86_PTDUMP',           'is not set', 'ubuntu18', 'cut_attack_surface'))
112     checklist.append(OptCheck('ZSMALLOC_STAT',        'is not set', 'ubuntu18', 'cut_attack_surface'))
113     checklist.append(OptCheck('PAGE_OWNER',           'is not set', 'ubuntu18', 'cut_attack_surface'))
114     checklist.append(OptCheck('DEBUG_KMEMLEAK',       'is not set', 'ubuntu18', 'cut_attack_surface'))
115     checklist.append(OptCheck('BINFMT_AOUT',          'is not set', 'ubuntu18', 'cut_attack_surface'))
116
117     checklist.append(OptCheck('IO_STRICT_DEVMEM',     'y', 'kspp', 'cut_attack_surface'))
118     checklist.append(OptCheck('LEGACY_VSYSCALL_NONE', 'y', 'kspp', 'cut_attack_surface')) # 'vsyscall=none'
119     checklist.append(OptCheck('BINFMT_MISC',          'is not set', 'kspp', 'cut_attack_surface'))
120     checklist.append(OptCheck('INET_DIAG',            'is not set', 'kspp', 'cut_attack_surface'))
121     checklist.append(OptCheck('KEXEC',                'is not set', 'kspp', 'cut_attack_surface'))
122     checklist.append(OptCheck('PROC_KCORE',           'is not set', 'kspp', 'cut_attack_surface'))
123     checklist.append(OptCheck('LEGACY_PTYS',          'is not set', 'kspp', 'cut_attack_surface'))
124     checklist.append(OptCheck('IA32_EMULATION',       'is not set', 'kspp', 'cut_attack_surface'))
125     checklist.append(OptCheck('X86_X32',              'is not set', 'kspp', 'cut_attack_surface'))
126     checklist.append(OptCheck('MODIFY_LDT_SYSCALL',   'is not set', 'kspp', 'cut_attack_surface'))
127     checklist.append(OptCheck('HIBERNATION',          'is not set', 'kspp', 'cut_attack_surface'))
128
129     checklist.append(OptCheck('KPROBES',                 'is not set', 'grsecurity', 'cut_attack_surface'))
130     checklist.append(OptCheck('UPROBES',                 'is not set', 'grsecurity', 'cut_attack_surface'))
131     checklist.append(OptCheck('GENERIC_TRACER',          'is not set', 'grsecurity', 'cut_attack_surface'))
132     checklist.append(OptCheck('PROC_VMCORE',             'is not set', 'grsecurity', 'cut_attack_surface'))
133     checklist.append(OptCheck('PROC_PAGE_MONITOR',       'is not set', 'grsecurity', 'cut_attack_surface'))
134     checklist.append(OptCheck('USELIB',                  'is not set', 'grsecurity', 'cut_attack_surface'))
135     checklist.append(OptCheck('CHECKPOINT_RESTORE',      'is not set', 'grsecurity', 'cut_attack_surface'))
136     checklist.append(OptCheck('USERFAULTFD',             'is not set', 'grsecurity', 'cut_attack_surface'))
137     checklist.append(OptCheck('HWPOISON_INJECT',         'is not set', 'grsecurity', 'cut_attack_surface'))
138     checklist.append(OptCheck('MEM_SOFT_DIRTY',          'is not set', 'grsecurity', 'cut_attack_surface'))
139     checklist.append(OptCheck('DEVPORT',                 'is not set', 'grsecurity', 'cut_attack_surface'))
140     checklist.append(OptCheck('DEBUG_FS',                'is not set', 'grsecurity', 'cut_attack_surface'))
141     checklist.append(OptCheck('NOTIFIER_ERROR_INJECTION','is not set', 'grsecurity', 'cut_attack_surface'))
142
143     checklist.append(OptCheck('KEXEC_FILE',           'is not set', 'my', 'cut_attack_surface'))
144     checklist.append(OptCheck('LIVEPATCH',            'is not set', 'my', 'cut_attack_surface'))
145     checklist.append(OptCheck('USER_NS',              'is not set', 'my', 'cut_attack_surface')) # user.max_user_namespaces=0
146     checklist.append(OptCheck('IP_DCCP',              'is not set', 'my', 'cut_attack_surface'))
147     checklist.append(OptCheck('IP_SCTP',              'is not set', 'my', 'cut_attack_surface'))
148     checklist.append(OptCheck('FTRACE',               'is not set', 'my', 'cut_attack_surface'))
149     checklist.append(OptCheck('PROFILING',            'is not set', 'my', 'cut_attack_surface'))
150     checklist.append(OptCheck('BPF_JIT',              'is not set', 'my', 'cut_attack_surface'))
151     checklist.append(OptCheck('BPF_SYSCALL',          'is not set', 'my', 'cut_attack_surface'))
152
153     checklist.append(OptCheck('ARCH_MMAP_RND_BITS',   '32', 'my', 'userspace_protection'))
154
155     checklist.append(OptCheck('LKDTM',    'm', 'my', 'feature_test'))
156
157
158 def print_opt_checks():
159     print('[+] Printing kernel hardening preferences...')
160     print('  {:<39}|{:^13}|{:^10}|{:^20}'.format('option name', 'desired val', 'decision', 'reason'))
161     print('  ======================================================================================')
162     for opt in checklist:
163         print('  CONFIG_{:<32}|{:^13}|{:^10}|{:^20}'.format(opt.name, opt.expected, opt.decision, opt.reason))
164     print()
165
166
167 def print_check_results():
168     print('  {:<39}|{:^13}|{:^10}|{:^20}||{:^20}'.format('option name', 'desired val', 'decision', 'reason', 'check result'))
169     print('  ===========================================================================================================')
170     for opt in checklist:
171         print('  CONFIG_{:<32}|{:^13}|{:^10}|{:^20}||{:^20}'.format(opt.name, opt.expected, opt.decision, opt.reason, opt.result))
172     print()
173
174
175 def get_option_state(options, name):
176     return options[name] if name in options else None
177
178
179 def perform_checks(parsed_options):
180     for opt in checklist:
181         opt.state = get_option_state(parsed_options, opt.name)
182         opt.check()
183
184
185 def check_config_file(fname):
186     with open(fname, 'r') as f:
187         parsed_options = OrderedDict()
188         opt_is_on = re.compile("CONFIG_[a-zA-Z0-9_]*=[a-zA-Z0-9_\"]*")
189         opt_is_off = re.compile("# CONFIG_[a-zA-Z0-9_]* is not set")
190
191         print('[+] Checking "{}" against hardening preferences...'.format(fname))
192         for line in f.readlines():
193             line = line.strip()
194             option = None
195             value = None
196
197             if opt_is_on.match(line):
198                 option, value = line[7:].split('=', 1)
199             elif opt_is_off.match(line):
200                 option, value = line[9:].split(' ', 1)
201                 if value != 'is not set':
202                     sys.exit('[!] ERROR: bad disabled config option "{}"'.format(line))
203
204             if option in parsed_options:
205                 sys.exit('[!] ERROR: config option "{}" exists multiple times'.format(line))
206
207             if option is not None:
208                 parsed_options[option] = value
209
210         perform_checks(parsed_options)
211
212         if debug_mode:
213             known_options = [opt.name for opt in checklist]
214             for option, value in parsed_options.items():
215                 if option not in known_options:
216                     print("DEBUG: dunno about option {} ({})".format(option, value))
217
218         print_check_results()
219
220
221 if __name__ == '__main__':
222     parser = ArgumentParser(description='Checks the hardening options in the Linux kernel config')
223     parser.add_argument('-p', '--print', action='store_true', help='print hardening preferences')
224     parser.add_argument('-c', '--config', help='check the config_file against these preferences')
225     parser.add_argument('--debug', action='store_true', help='enable internal debug mode')
226     args = parser.parse_args()
227
228     construct_opt_checks()
229
230     if args.print:
231         print_opt_checks()
232         sys.exit(0)
233
234     if args.debug:
235         debug_mode = True
236
237     if args.config:
238         check_config_file(args.config)
239         error_count = len(list(filter(lambda opt: opt.result.startswith('FAIL'), checklist)))
240         if error_count == 0:
241             print('[+] config check is PASSED')
242             sys.exit(0)
243         else:
244             sys.exit('[-] config check is NOT PASSED: {} errors'.format(error_count))
245
246     parser.print_help()