52ae76153ae15ef55f11b48c73782a44e0342e01
[kconfig-hardened-check.git] / kernel_hardening_checker / engine.py
1 #!/usr/bin/env python3
2
3 """
4 This tool is for checking the security hardening options of the Linux kernel.
5
6 Author: Alexander Popov <alex.popov@linux.com>
7
8 This module is the engine of checks.
9 """
10
11 # pylint: disable=missing-class-docstring,missing-function-docstring
12 # pylint: disable=line-too-long,invalid-name,too-many-branches
13
14 GREEN_COLOR = '\x1b[32m'
15 RED_COLOR = '\x1b[31m'
16 COLOR_END = '\x1b[0m'
17
18 def colorize_result(input_text):
19     if input_text is None:
20         return input_text
21     if input_text.startswith('OK'):
22         color = GREEN_COLOR
23     else:
24         assert(input_text.startswith('FAIL:')), f'unexpected result "{input_text}"'
25         color = RED_COLOR
26     return f'{color}{input_text}{COLOR_END}'
27
28
29 class OptCheck:
30     def __init__(self, reason, decision, name, expected):
31         assert(name and name == name.strip() and len(name.split()) == 1), \
32                f'invalid name "{name}" for {self.__class__.__name__}'
33         self.name = name
34
35         assert(decision and decision == decision.strip() and len(decision.split()) == 1), \
36                f'invalid decision "{decision}" for "{name}" check'
37         self.decision = decision
38
39         assert(reason and reason == reason.strip() and len(reason.split()) == 1), \
40                f'invalid reason "{reason}" for "{name}" check'
41         self.reason = reason
42
43         assert(expected and expected == expected.strip()), \
44                f'invalid expected value "{expected}" for "{name}" check (1)'
45         val_len = len(expected.split())
46         if val_len == 3:
47             assert(expected in ('is not set', 'is not off')), \
48                    f'invalid expected value "{expected}" for "{name}" check (2)'
49         elif val_len == 2:
50             assert(expected == 'is present'), \
51                    f'invalid expected value "{expected}" for "{name}" check (3)'
52         else:
53             assert(val_len == 1), \
54                    f'invalid expected value "{expected}" for "{name}" check (4)'
55         self.expected = expected
56
57         self.state = None
58         self.result = None
59
60     @property
61     def type(self):
62         return None
63
64     def check(self):
65         # handle the 'is present' check
66         if self.expected == 'is present':
67             if self.state is None:
68                 self.result = 'FAIL: is not present'
69             else:
70                 self.result = 'OK: is present'
71             return
72
73         # handle the 'is not off' option check
74         if self.expected == 'is not off':
75             if self.state == 'off':
76                 self.result = 'FAIL: is off'
77             elif self.state == '0':
78                 self.result = 'FAIL: is off, "0"'
79             elif self.state is None:
80                 self.result = 'FAIL: is off, not found'
81             else:
82                 self.result = f'OK: is not off, "{self.state}"'
83             return
84
85         # handle the option value check
86         if self.expected == self.state:
87             self.result = 'OK'
88         elif self.state is None:
89             if self.expected == 'is not set':
90                 self.result = 'OK: is not found'
91             else:
92                 self.result = 'FAIL: is not found'
93         else:
94             self.result = f'FAIL: "{self.state}"'
95
96     def table_print(self, _mode, with_results):
97         print(f'{self.name:<40}|{self.type:^7}|{self.expected:^12}|{self.decision:^10}|{self.reason:^18}', end='')
98         if with_results:
99             print(f'| {colorize_result(self.result)}', end='')
100
101     def json_dump(self, with_results):
102         dump = [self.name, self.type, self.expected, self.decision, self.reason]
103         if with_results:
104             dump.append(self.result)
105         return dump
106
107
108 class KconfigCheck(OptCheck):
109     def __init__(self, *args, **kwargs):
110         super().__init__(*args, **kwargs)
111         self.name = f'CONFIG_{self.name}'
112
113     @property
114     def type(self):
115         return 'kconfig'
116
117
118 class CmdlineCheck(OptCheck):
119     @property
120     def type(self):
121         return 'cmdline'
122
123
124 class SysctlCheck(OptCheck):
125     @property
126     def type(self):
127         return 'sysctl'
128
129
130 class VersionCheck:
131     def __init__(self, ver_expected):
132         assert(ver_expected and isinstance(ver_expected, tuple) and len(ver_expected) == 2), \
133                f'invalid version "{ver_expected}" for VersionCheck'
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 = f'OK: version >= {self.ver_expected[0]}.{self.ver_expected[1]}'
145             return
146         if self.ver[0] < self.ver_expected[0]:
147             self.result = f'FAIL: version < {self.ver_expected[0]}.{self.ver_expected[1]}'
148             return
149         if self.ver[1] >= self.ver_expected[1]:
150             self.result = f'OK: version >= {self.ver_expected[0]}.{self.ver_expected[1]}'
151             return
152         self.result = f'FAIL: version < {self.ver_expected[0]}.{self.ver_expected[1]}'
153
154     def table_print(self, _mode, with_results):
155         ver_req = f'kernel version >= {self.ver_expected[0]}.{self.ver_expected[1]}'
156         print(f'{ver_req:<91}', end='')
157         if with_results:
158             print(f'| {colorize_result(self.result)}', end='')
159
160
161 class ComplexOptCheck:
162     def __init__(self, *opts):
163         self.opts = opts
164         assert(self.opts), \
165                f'empty {self.__class__.__name__} check'
166         assert(len(self.opts) != 1), \
167                f'useless {self.__class__.__name__} check: {opts}'
168         assert(isinstance(opts[0], (KconfigCheck, CmdlineCheck, SysctlCheck))), \
169                f'invalid {self.__class__.__name__} check: {opts}'
170         self.result = None
171
172     @property
173     def type(self):
174         return 'complex'
175
176     @property
177     def name(self):
178         return self.opts[0].name
179
180     @property
181     def expected(self):
182         return self.opts[0].expected
183
184     def table_print(self, mode, with_results):
185         if mode == 'verbose':
186             class_name = f'<<< {self.__class__.__name__} >>>'
187             print(f'    {class_name:87}', end='')
188             if with_results:
189                 print(f'| {colorize_result(self.result)}', end='')
190             for o in self.opts:
191                 print()
192                 o.table_print(mode, with_results)
193         else:
194             o = self.opts[0]
195             o.table_print(mode, False)
196             if with_results:
197                 print(f'| {colorize_result(self.result)}', end='')
198
199     def json_dump(self, with_results):
200         dump = self.opts[0].json_dump(False)
201         if with_results:
202             dump.append(self.result)
203         return dump
204
205
206 class OR(ComplexOptCheck):
207     # self.opts[0] is the option that this OR-check is about.
208     # Use cases:
209     #     OR(<X_is_hardened>, <X_is_disabled>)
210     #     OR(<X_is_hardened>, <old_X_is_hardened>)
211     def check(self):
212         for i, opt in enumerate(self.opts):
213             opt.check()
214             if opt.result.startswith('OK'):
215                 self.result = opt.result
216                 # Add more info for additional checks:
217                 if i != 0:
218                     if opt.result == 'OK':
219                         self.result = f'OK: {opt.name} is "{opt.expected}"'
220                     elif opt.result == 'OK: is not found':
221                         self.result = f'OK: {opt.name} is not found'
222                     elif opt.result == 'OK: is present':
223                         self.result = f'OK: {opt.name} is present'
224                     elif opt.result.startswith('OK: is not off'):
225                         self.result = f'OK: {opt.name} is not off'
226                     else:
227                         # VersionCheck provides enough info
228                         assert(opt.result.startswith('OK: version')), \
229                                f'unexpected OK description "{opt.result}"'
230                 return
231         self.result = self.opts[0].result
232
233
234 class AND(ComplexOptCheck):
235     # self.opts[0] is the option that this AND-check is about.
236     # Use cases:
237     #     AND(<suboption>, <main_option>)
238     #       Suboption is not checked if checking of the main_option is failed.
239     #     AND(<X_is_disabled>, <old_X_is_disabled>)
240     def check(self):
241         for i, opt in reversed(list(enumerate(self.opts))):
242             opt.check()
243             if i == 0:
244                 self.result = opt.result
245                 return
246             if not opt.result.startswith('OK'):
247                 # This FAIL is caused by additional checks,
248                 # and not by the main option that this AND-check is about.
249                 # Describe the reason of the FAIL.
250                 if opt.result.startswith('FAIL: \"') or opt.result == 'FAIL: is not found':
251                     self.result = f'FAIL: {opt.name} is not "{opt.expected}"'
252                 elif opt.result == 'FAIL: is not present':
253                     self.result = f'FAIL: {opt.name} is not present'
254                 elif opt.result in ('FAIL: is off', 'FAIL: is off, "0"'):
255                     self.result = f'FAIL: {opt.name} is off'
256                 elif opt.result == 'FAIL: is off, not found':
257                     self.result = f'FAIL: {opt.name} is off, not found'
258                 else:
259                     # VersionCheck provides enough info
260                     self.result = opt.result
261                     assert(opt.result.startswith('FAIL: version')), \
262                            f'unexpected FAIL description "{opt.result}"'
263                 return
264
265
266 SIMPLE_OPTION_TYPES = ('kconfig', 'cmdline', 'sysctl', 'version')
267
268
269 def populate_simple_opt_with_data(opt, data, data_type):
270     assert(opt.type != 'complex'), \
271            f'unexpected ComplexOptCheck "{opt.name}"'
272     assert(opt.type in SIMPLE_OPTION_TYPES), \
273            f'invalid opt type "{opt.type}"'
274     assert(data_type in SIMPLE_OPTION_TYPES), \
275            f'invalid data type "{data_type}"'
276     assert(data), \
277            'empty data'
278
279     if data_type != opt.type:
280         return
281
282     if data_type in ('kconfig', 'cmdline', 'sysctl'):
283         opt.state = data.get(opt.name, None)
284     else:
285         assert(data_type == 'version'), \
286                f'unexpected data type "{data_type}"'
287         opt.ver = data
288
289
290 def populate_opt_with_data(opt, data, data_type):
291     assert(opt.type != 'version'), 'a single VersionCheck is useless'
292     if opt.type != 'complex':
293         populate_simple_opt_with_data(opt, data, data_type)
294     else:
295         for o in opt.opts:
296             if o.type != 'complex':
297                 populate_simple_opt_with_data(o, data, data_type)
298             else:
299                 # Recursion for nested ComplexOptCheck objects
300                 populate_opt_with_data(o, data, data_type)
301
302
303 def populate_with_data(checklist, data, data_type):
304     for opt in checklist:
305         populate_opt_with_data(opt, data, data_type)
306
307
308 def override_expected_value(checklist, name, new_val):
309     for opt in checklist:
310         if opt.name == name:
311             assert(opt.type in ('kconfig', 'cmdline', 'sysctl')), \
312                    f'overriding an expected value for "{opt.type}" checks is not supported yet'
313             opt.expected = new_val
314
315
316 def perform_checks(checklist):
317     for opt in checklist:
318         opt.check()