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