Add more typing annotations to engine.py
[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 from __future__ import annotations
15 import sys
16
17 from typing import Union, Optional, List, Dict, OrderedDict, Tuple
18 StrOrNone = Optional[str]
19 TupleOrNone = Optional[Tuple]
20 TupleOrOrderedDict = Union[Tuple, OrderedDict[str, str]]
21 StrOrBool = Union[str, bool]
22
23 GREEN_COLOR = '\x1b[32m'
24 RED_COLOR = '\x1b[31m'
25 COLOR_END = '\x1b[0m'
26
27
28 def colorize_result(input_text: StrOrNone) -> StrOrNone:
29     if input_text is None or not sys.stdout.isatty():
30         return input_text
31     if input_text.startswith('OK'):
32         color = GREEN_COLOR
33     else:
34         assert(input_text.startswith('FAIL:')), f'unexpected result "{input_text}"'
35         color = RED_COLOR
36     return f'{color}{input_text}{COLOR_END}'
37
38
39 class OptCheck:
40     def __init__(self, reason: str, decision: str, name: str, expected: str) -> None:
41         assert(name and name == name.strip() and len(name.split()) == 1), \
42                f'invalid name "{name}" for {self.__class__.__name__}'
43         self.name = name
44
45         assert(decision and decision == decision.strip() and len(decision.split()) == 1), \
46                f'invalid decision "{decision}" for "{name}" check'
47         self.decision = decision
48
49         assert(reason and reason == reason.strip() and len(reason.split()) == 1), \
50                f'invalid reason "{reason}" for "{name}" check'
51         self.reason = reason
52
53         assert(expected and expected == expected.strip()), \
54                f'invalid expected value "{expected}" for "{name}" check (1)'
55         val_len = len(expected.split())
56         if val_len == 3:
57             assert(expected in ('is not set', 'is not off')), \
58                    f'invalid expected value "{expected}" for "{name}" check (2)'
59         elif val_len == 2:
60             assert(expected == 'is present'), \
61                    f'invalid expected value "{expected}" for "{name}" check (3)'
62         else:
63             assert(val_len == 1), \
64                    f'invalid expected value "{expected}" for "{name}" check (4)'
65         self.expected = expected
66
67         self.state = None # type: str | None
68         self.result = None # type: str | None
69
70     @property
71     def opt_type(self) -> StrOrNone:
72         return None
73
74     def set_state(self, data: StrOrNone) -> None:
75         assert(data is None or isinstance(data, str)), \
76                f'invalid state "{data}" for "{self.name}" check'
77         self.state = data
78
79     def check(self) -> None:
80         # handle the 'is present' check
81         if self.expected == 'is present':
82             if self.state is None:
83                 self.result = 'FAIL: is not present'
84             else:
85                 self.result = 'OK: is present'
86             return
87
88         # handle the 'is not off' option check
89         if self.expected == 'is not off':
90             if self.state == 'off':
91                 self.result = 'FAIL: is off'
92             elif self.state == '0':
93                 self.result = 'FAIL: is off, "0"'
94             elif self.state is None:
95                 self.result = 'FAIL: is off, not found'
96             else:
97                 self.result = f'OK: is not off, "{self.state}"'
98             return
99
100         # handle the option value check
101         if self.expected == self.state:
102             self.result = 'OK'
103         elif self.state is None:
104             if self.expected == 'is not set':
105                 self.result = 'OK: is not found'
106             else:
107                 self.result = 'FAIL: is not found'
108         else:
109             self.result = f'FAIL: "{self.state}"'
110
111     def table_print(self, _mode: StrOrNone, with_results: bool) -> None:
112         print(f'{self.name:<40}|{self.opt_type:^7}|{self.expected:^12}|{self.decision:^10}|{self.reason:^18}', end='')
113         if with_results:
114             print(f'| {colorize_result(self.result)}', end='')
115
116     def json_dump(self, with_results: bool) -> Dict[str, StrOrBool]:
117         dump = {
118             "option_name": self.name,
119             "type": self.opt_type,
120             "desired_val": self.expected,
121             "decision": self.decision,
122             "reason": self.reason,
123         } # type: Dict[str, StrOrBool]
124         if with_results:
125             assert self.result, f'unexpected empty result in {self.name}'
126             dump["check_result"] = self.result
127             dump["check_result_bool"] = self.result.startswith('OK')
128         return dump
129
130
131 class KconfigCheck(OptCheck):
132     def __init__(self, *args, **kwargs) -> None:
133         super().__init__(*args, **kwargs)
134         self.name = f'CONFIG_{self.name}'
135
136     @property
137     def opt_type(self) -> str:
138         return 'kconfig'
139
140
141 class CmdlineCheck(OptCheck):
142     @property
143     def opt_type(self) -> str:
144         return 'cmdline'
145
146
147 class SysctlCheck(OptCheck):
148     @property
149     def opt_type(self) -> str:
150         return 'sysctl'
151
152
153 class VersionCheck:
154     def __init__(self, ver_expected: Tuple[int, int, int]) -> None:
155         assert(ver_expected and isinstance(ver_expected, tuple) and len(ver_expected) == 3), \
156                f'invalid expected version "{ver_expected}" for VersionCheck (1)'
157         assert(all(map(lambda x: isinstance(x, int), ver_expected))), \
158                f'invalid expected version "{ver_expected}" for VersionCheck (2)'
159         self.ver_expected = ver_expected
160         self.ver = ()
161         self.result = None # type: str | None
162
163     @property
164     def opt_type(self) -> str:
165         return 'version'
166
167     def set_state(self, data: Tuple) -> None:
168         assert(data and isinstance(data, tuple) and len(data) >= 3), \
169                f'invalid version "{data}" for VersionCheck'
170         self.ver = data[:3]
171
172     def check(self) -> None:
173         if self.ver[0] > self.ver_expected[0]:
174             self.result = f'OK: version >= {self.ver_expected}'
175             return
176         if self.ver[0] < self.ver_expected[0]:
177             self.result = f'FAIL: version < {self.ver_expected}'
178             return
179         # self.ver[0] and self.ver_expected[0] are equal
180         if self.ver[1] > self.ver_expected[1]:
181             self.result = f'OK: version >= {self.ver_expected}'
182             return
183         if self.ver[1] < self.ver_expected[1]:
184             self.result = f'FAIL: version < {self.ver_expected}'
185             return
186         # self.ver[1] and self.ver_expected[1] are equal too
187         if self.ver[2] >= self.ver_expected[2]:
188             self.result = f'OK: version >= {self.ver_expected}'
189             return
190         self.result = f'FAIL: version < {self.ver_expected}'
191
192     def table_print(self, _mode: StrOrNone, with_results: bool) -> None:
193         ver_req = f'kernel version >= {self.ver_expected}'
194         print(f'{ver_req:<91}', end='')
195         if with_results:
196             print(f'| {colorize_result(self.result)}', end='')
197
198
199 class ComplexOptCheck:
200     def __init__(self, *opts: AnyOptCheckType) -> None:
201         self.opts = opts
202         assert(self.opts), \
203                f'empty {self.__class__.__name__} check'
204         assert(len(self.opts) != 1), \
205                f'useless {self.__class__.__name__} check: {opts}'
206         assert(isinstance(opts[0], (KconfigCheck, CmdlineCheck, SysctlCheck))), \
207                f'invalid {self.__class__.__name__} check: {opts}'
208         self.result = None # type: str | None
209
210     @property
211     def opt_type(self) -> str:
212         return 'complex'
213
214     @property
215     def name(self) -> str:
216         return self.opts[0].name
217
218     @property
219     def expected(self) -> str:
220         return self.opts[0].expected
221
222     def table_print(self, mode: StrOrNone, with_results: bool) -> None:
223         if mode == 'verbose':
224             class_name = f'<<< {self.__class__.__name__} >>>'
225             print(f'    {class_name:87}', end='')
226             if with_results:
227                 print(f'| {colorize_result(self.result)}', end='')
228             for o in self.opts:
229                 print()
230                 o.table_print(mode, with_results)
231         else:
232             o = self.opts[0]
233             o.table_print(mode, False)
234             if with_results:
235                 print(f'| {colorize_result(self.result)}', end='')
236
237     def json_dump(self, with_results: bool) -> Dict[str, StrOrBool]:
238         dump = self.opts[0].json_dump(False)
239         if with_results:
240             # Add the 'check_result' and 'check_result_bool' keys to the dictionary
241             assert self.result, f'unexpected empty result in {self.name}'
242             dump["check_result"] = self.result
243             dump["check_result_bool"] = self.result.startswith('OK')
244         return dump
245
246
247 class OR(ComplexOptCheck):
248     # self.opts[0] is the option that this OR-check is about.
249     # Use cases:
250     #     OR(<X_is_hardened>, <X_is_disabled>)
251     #     OR(<X_is_hardened>, <old_X_is_hardened>)
252     def check(self) -> None:
253         for i, opt in enumerate(self.opts):
254             opt.check()
255             if opt.result.startswith('OK'):
256                 self.result = opt.result
257                 # Add more info for additional checks:
258                 if i != 0:
259                     if opt.result == 'OK':
260                         self.result = f'OK: {opt.name} is "{opt.expected}"'
261                     elif opt.result == 'OK: is not found':
262                         self.result = f'OK: {opt.name} is not found'
263                     elif opt.result == 'OK: is present':
264                         self.result = f'OK: {opt.name} is present'
265                     elif opt.result.startswith('OK: is not off'):
266                         self.result = f'OK: {opt.name} is not off'
267                     else:
268                         # VersionCheck provides enough info
269                         assert(opt.result.startswith('OK: version')), \
270                                f'unexpected OK description "{opt.result}"'
271                 return
272         self.result = self.opts[0].result
273
274
275 class AND(ComplexOptCheck):
276     # self.opts[0] is the option that this AND-check is about.
277     # Use cases:
278     #     AND(<suboption>, <main_option>)
279     #       Suboption is not checked if checking of the main_option is failed.
280     #     AND(<X_is_disabled>, <old_X_is_disabled>)
281     def check(self) -> None:
282         for i, opt in reversed(list(enumerate(self.opts))):
283             opt.check()
284             if i == 0:
285                 self.result = opt.result
286                 return
287             if not opt.result.startswith('OK'):
288                 # This FAIL is caused by additional checks,
289                 # and not by the main option that this AND-check is about.
290                 # Describe the reason of the FAIL.
291                 if opt.result.startswith('FAIL: \"') or opt.result == 'FAIL: is not found':
292                     self.result = f'FAIL: {opt.name} is not "{opt.expected}"'
293                 elif opt.result == 'FAIL: is not present':
294                     self.result = f'FAIL: {opt.name} is not present'
295                 elif opt.result in ('FAIL: is off', 'FAIL: is off, "0"'):
296                     self.result = f'FAIL: {opt.name} is off'
297                 elif opt.result == 'FAIL: is off, not found':
298                     self.result = f'FAIL: {opt.name} is off, not found'
299                 else:
300                     # VersionCheck provides enough info
301                     self.result = opt.result
302                     assert(opt.result.startswith('FAIL: version')), \
303                            f'unexpected FAIL description "{opt.result}"'
304                 return
305
306
307 # All classes are declared, let's define typing:
308 #  1) basic simple check objects
309 SIMPLE_OPTION_TYPES = ('kconfig', 'cmdline', 'sysctl', 'version')
310 SimpleOptCheckType = Union[KconfigCheck, CmdlineCheck, SysctlCheck, VersionCheck]
311 SimpleOptCheckTypes = (KconfigCheck, CmdlineCheck, SysctlCheck, VersionCheck)
312
313 #  2) complex objects that may contain complex and simple objects
314 ComplexOptCheckType = Union[OR, AND]
315 ComplexOptCheckTypes = (OR, AND)
316
317 #  3) objects that can be added to the checklist
318 ChecklistObjType = Union[KconfigCheck, CmdlineCheck, SysctlCheck, OR, AND]
319
320 #  4) all existing objects
321 AnyOptCheckType = Union[KconfigCheck, CmdlineCheck, SysctlCheck, VersionCheck, OR, AND]
322
323
324 def populate_simple_opt_with_data(opt: SimpleOptCheckType, data: TupleOrOrderedDict, data_type: str) -> None:
325     assert(opt.opt_type != 'complex'), \
326            f'unexpected ComplexOptCheck "{opt.name}"'
327     assert(opt.opt_type in SIMPLE_OPTION_TYPES), \
328            f'invalid opt_type "{opt.opt_type}"'
329     assert(data_type in SIMPLE_OPTION_TYPES), \
330            f'invalid data_type "{data_type}"'
331     assert(data), \
332            'empty data'
333
334     if data_type != opt.opt_type:
335         return
336
337     if data_type in ('kconfig', 'cmdline', 'sysctl'):
338         opt.set_state(data.get(opt.name, None))
339     else:
340         assert(data_type == 'version'), \
341                f'unexpected data_type "{data_type}"'
342         opt.set_state(data)
343
344
345 def populate_opt_with_data(opt: AnyOptCheckType, data: TupleOrOrderedDict, data_type: str) -> None:
346     assert(opt.opt_type != 'version'), 'a single VersionCheck is useless'
347     if opt.opt_type != 'complex':
348         populate_simple_opt_with_data(opt, data, data_type)
349     else:
350         for o in opt.opts:
351             if o.opt_type != 'complex':
352                 populate_simple_opt_with_data(o, data, data_type)
353             else:
354                 # Recursion for nested ComplexOptCheck objects
355                 populate_opt_with_data(o, data, data_type)
356
357
358 def populate_with_data(checklist: List, data: TupleOrOrderedDict, data_type: str) -> None:
359     for opt in checklist:
360         populate_opt_with_data(opt, data, data_type)
361
362
363 def override_expected_value(checklist: List, name: str, new_val: str) -> None:
364     for opt in checklist:
365         if opt.name == name:
366             assert(opt.opt_type in ('kconfig', 'cmdline', 'sysctl')), \
367                    f'overriding an expected value for "{opt.opt_type}" checks is not supported yet'
368             opt.expected = new_val
369
370
371 def perform_checks(checklist: List) -> None:
372     for opt in checklist:
373         opt.check()
374
375
376 def print_unknown_options(checklist: List, parsed_options: OrderedDict[str, str], opt_type: str) -> None:
377     known_options = []
378
379     for o1 in checklist:
380         if o1.opt_type != 'complex':
381             known_options.append(o1.name)
382             continue
383         for o2 in o1.opts:
384             if o2.opt_type != 'complex':
385                 if hasattr(o2, 'name'):
386                     known_options.append(o2.name)
387                 continue
388             for o3 in o2.opts:
389                 assert(o3.opt_type != 'complex'), \
390                        f'unexpected ComplexOptCheck inside {o2.name}'
391                 if hasattr(o3, 'name'):
392                     known_options.append(o3.name)
393
394     for option, value in parsed_options.items():
395         if option not in known_options:
396             print(f'[?] No check for {opt_type} option {option} ({value})')