Merge remote-tracking branch 'origin/pylint'
[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,too-many-branches
13
14 from __future__ import annotations
15 import sys
16
17 from typing import Union, Optional, List, Dict, Tuple
18 StrOrNone = Optional[str]
19 TupleOrNone = Optional[Tuple[int, ...]]
20 DictOrTuple = Union[Dict[str, str], Tuple[int, ...]]
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: str) -> None:
137         super().__init__(*args)
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, ...]
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[int, ...]) -> None:
172         assert(data and isinstance(data, tuple) and len(data) >= 3), \
173                f'invalid version "{data}" for VersionCheck (1)'
174         assert(all(map(lambda x: isinstance(x, int), data))), \
175                f'invalid version "{data}" for VersionCheck (2)'
176         self.ver = data[:3]
177
178     def check(self) -> None:
179         assert(self.ver[0] >= 2), 'not initialized kernel version'
180         if self.ver[0] > self.ver_expected[0]:
181             self.result = f'OK: version >= {self.ver_expected}'
182             return
183         if self.ver[0] < self.ver_expected[0]:
184             self.result = f'FAIL: version < {self.ver_expected}'
185             return
186         # self.ver[0] and self.ver_expected[0] are equal
187         if self.ver[1] > self.ver_expected[1]:
188             self.result = f'OK: version >= {self.ver_expected}'
189             return
190         if self.ver[1] < self.ver_expected[1]:
191             self.result = f'FAIL: version < {self.ver_expected}'
192             return
193         # self.ver[1] and self.ver_expected[1] are equal too
194         if self.ver[2] >= self.ver_expected[2]:
195             self.result = f'OK: version >= {self.ver_expected}'
196             return
197         self.result = f'FAIL: version < {self.ver_expected}'
198
199     def table_print(self, _mode: StrOrNone, with_results: bool) -> None:
200         ver_req = f'kernel version >= {self.ver_expected}'
201         print(f'{ver_req:<91}', end='')
202         if with_results:
203             print(f'| {colorize_result(self.result)}', end='')
204
205
206 class ComplexOptCheck:
207     def __init__(self, *opts: AnyOptCheckType) -> None:
208         self.opts = opts
209         assert(self.opts), \
210                f'empty {self.__class__.__name__} check'
211         assert(len(self.opts) != 1), \
212                f'useless {self.__class__.__name__} check: {opts}'
213         assert(isinstance(self.opts[0], SimpleNamedOptCheckTypes)), \
214                f'invalid {self.__class__.__name__} check: {opts}'
215         self.result = None # type: str | None
216
217     @property
218     def opt_type(self) -> str:
219         return 'complex'
220
221     @property
222     def name(self) -> str:
223         assert hasattr(self.opts[0], 'name') # true for SimpleNamedOptCheckTypes
224         return self.opts[0].name
225
226     @property
227     def expected(self) -> str:
228         assert hasattr(self.opts[0], 'expected') # true for SimpleNamedOptCheckTypes
229         return self.opts[0].expected
230
231     def table_print(self, mode: StrOrNone, with_results: bool) -> None:
232         if mode == 'verbose':
233             class_name = f'<<< {self.__class__.__name__} >>>'
234             print(f'    {class_name:87}', end='')
235             if with_results:
236                 print(f'| {colorize_result(self.result)}', end='')
237             for o in self.opts:
238                 print()
239                 o.table_print(mode, with_results)
240         else:
241             o = self.opts[0]
242             o.table_print(mode, False)
243             if with_results:
244                 print(f'| {colorize_result(self.result)}', end='')
245
246     def json_dump(self, with_results: bool) -> Dict[str, StrOrBool]:
247         assert hasattr(self.opts[0], 'json_dump') # true for SimpleNamedOptCheckTypes
248         dump = self.opts[0].json_dump(False)
249         if with_results:
250             # Add the 'check_result' and 'check_result_bool' keys to the dictionary
251             assert(self.result), f'unexpected empty result in {self.name}'
252             dump["check_result"] = self.result
253             dump["check_result_bool"] = self.result.startswith('OK')
254         return dump
255
256
257 class OR(ComplexOptCheck):
258     # self.opts[0] is the option that this OR-check is about.
259     # Use cases:
260     #     OR(<X_is_hardened>, <X_is_disabled>)
261     #     OR(<X_is_hardened>, <old_X_is_hardened>)
262     def check(self) -> None:
263         for i, opt in enumerate(self.opts):
264             opt.check()
265             assert(opt.result), 'unexpected empty result of the OR sub-check'
266             if opt.result.startswith('OK'):
267                 self.result = opt.result
268                 if i != 0:
269                     # Add more info for additional checks:
270                     if isinstance(opt, VersionCheck):
271                         assert(opt.result.startswith('OK: version')), \
272                                f'unexpected VersionCheck result {opt.result}'
273                         # VersionCheck provides enough info, nothing to add
274                     else:
275                         if opt.result == 'OK':
276                             self.result = f'OK: {opt.name} is "{opt.expected}"'
277                         elif opt.result == 'OK: is not found':
278                             self.result = f'OK: {opt.name} is not found'
279                         elif opt.result == 'OK: is present':
280                             self.result = f'OK: {opt.name} is present'
281                         else:
282                             assert(opt.result.startswith('OK: is not off')), \
283                                    f'unexpected OK description "{opt.result}"'
284                             self.result = f'OK: {opt.name} is not off'
285                 return
286         self.result = self.opts[0].result
287
288
289 class AND(ComplexOptCheck):
290     # self.opts[0] is the option that this AND-check is about.
291     # Use cases:
292     #     AND(<suboption>, <main_option>)
293     #       Suboption is not checked if checking of the main_option is failed.
294     #     AND(<X_is_disabled>, <old_X_is_disabled>)
295     def check(self) -> None:
296         for i, opt in reversed(list(enumerate(self.opts))):
297             opt.check()
298             assert(opt.result), 'unexpected empty result of the AND sub-check'
299             if i == 0:
300                 self.result = opt.result
301                 return
302             if not opt.result.startswith('OK'):
303                 # This FAIL is caused by additional checks,
304                 # and not by the main option that this AND-check is about.
305                 # Describe the reason of the FAIL.
306                 if isinstance(opt, VersionCheck):
307                     assert(opt.result.startswith('FAIL: version')), \
308                            f'unexpected VersionCheck result {opt.result}'
309                     self.result = opt.result # VersionCheck provides enough info
310                 else:
311                     if opt.result.startswith('FAIL: \"') or opt.result == 'FAIL: is not found':
312                         self.result = f'FAIL: {opt.name} is not "{opt.expected}"'
313                     elif opt.result == 'FAIL: is not present':
314                         self.result = f'FAIL: {opt.name} is not present'
315                     elif opt.result in ('FAIL: is off', 'FAIL: is off, "0"'):
316                         self.result = f'FAIL: {opt.name} is off'
317                     else:
318                         assert(opt.result == 'FAIL: is off, not found'), \
319                                f'unexpected FAIL description "{opt.result}"'
320                         self.result = f'FAIL: {opt.name} is off, not found'
321                 return
322
323
324 # All classes are declared, let's define typing:
325 #  1) basic simple check objects
326 SIMPLE_OPTION_TYPES = ('kconfig', 'cmdline', 'sysctl', 'version')
327 SimpleOptCheckType = Union[KconfigCheck, CmdlineCheck, SysctlCheck, VersionCheck]
328 SimpleOptCheckTypes = (KconfigCheck, CmdlineCheck, SysctlCheck, VersionCheck)
329 SimpleNamedOptCheckType = Union[KconfigCheck, CmdlineCheck, SysctlCheck]
330 SimpleNamedOptCheckTypes = (KconfigCheck, CmdlineCheck, SysctlCheck)
331
332 #  2) complex objects that may contain complex and simple objects
333 ComplexOptCheckType = Union[OR, AND]
334 ComplexOptCheckTypes = (OR, AND)
335
336 #  3) objects that can be added to the checklist
337 ChecklistObjType = Union[KconfigCheck, CmdlineCheck, SysctlCheck, OR, AND]
338
339 #  4) all existing objects
340 AnyOptCheckType = Union[KconfigCheck, CmdlineCheck, SysctlCheck, VersionCheck, OR, AND]
341
342
343 def populate_simple_opt_with_data(opt: SimpleOptCheckType, data: DictOrTuple, data_type: str) -> None:
344     assert(opt.opt_type != 'complex'), f'unexpected opt_type "{opt.opt_type}" for {opt}'
345     assert(opt.opt_type in SIMPLE_OPTION_TYPES), f'invalid opt_type "{opt.opt_type}"'
346     assert(data_type in SIMPLE_OPTION_TYPES), f'invalid data_type "{data_type}"'
347     assert(data), 'empty data'
348
349     if data_type != opt.opt_type:
350         return
351
352     if data_type in ('kconfig', 'cmdline', 'sysctl'):
353         assert(isinstance(data, dict)), \
354                f'unexpected data with data_type {data_type}'
355         assert(isinstance(opt, SimpleNamedOptCheckTypes)), \
356                f'unexpected VersionCheck with opt_type "{opt.opt_type}"'
357         opt.set_state(data.get(opt.name, None))
358     else:
359         assert(isinstance(data, tuple)), \
360                f'unexpected verion data with data_type {data_type}'
361         assert(isinstance(opt, VersionCheck) and data_type == 'version'), \
362                f'unexpected data_type "{data_type}"'
363         opt.set_state(data)
364
365
366 def populate_opt_with_data(opt: AnyOptCheckType, data: DictOrTuple, data_type: str) -> None:
367     assert(opt.opt_type != 'version'), 'a single VersionCheck is useless'
368     if opt.opt_type != 'complex':
369         assert(isinstance(opt, SimpleOptCheckTypes)), \
370                f'unexpected object {opt} with opt_type "{opt.opt_type}"'
371         populate_simple_opt_with_data(opt, data, data_type)
372     else:
373         assert(isinstance(opt, ComplexOptCheckTypes)), \
374                f'unexpected object {opt} with opt_type "{opt.opt_type}"'
375         for o in opt.opts:
376             if o.opt_type != 'complex':
377                 assert(isinstance(o, SimpleOptCheckTypes)), \
378                        f'unexpected object {o} with opt_type "{o.opt_type}"'
379                 populate_simple_opt_with_data(o, data, data_type)
380             else:
381                 # Recursion for nested ComplexOptCheck objects
382                 populate_opt_with_data(o, data, data_type)
383
384
385 def populate_with_data(checklist: List[ChecklistObjType], data: DictOrTuple, data_type: str) -> None:
386     for opt in checklist:
387         populate_opt_with_data(opt, data, data_type)
388
389
390 def override_expected_value(checklist: List[ChecklistObjType], name: str, new_val: str) -> None:
391     for opt in checklist:
392         if opt.name == name:
393             assert(isinstance(opt, SimpleNamedOptCheckTypes)), \
394                    f'overriding an expected value for {opt}" is not supported yet'
395             opt.expected = new_val
396
397
398 def perform_checks(checklist: List[ChecklistObjType]) -> None:
399     for opt in checklist:
400         opt.check()
401
402
403 def print_unknown_options(checklist: List[ChecklistObjType], parsed_options: Dict[str, str], opt_type: str) -> None:
404     known_options = []
405
406     for o1 in checklist:
407         if isinstance(o1, SimpleOptCheckTypes):
408             assert(o1.opt_type != 'complex'), f'{o1} with complex opt_type'
409             assert(not isinstance(o1, VersionCheck)), 'single VersionCheck in checklist'
410             known_options.append(o1.name)
411             continue
412         for o2 in o1.opts:
413             if isinstance(o2, SimpleOptCheckTypes):
414                 assert(o2.opt_type != 'complex'), f'{o2} with complex opt_type'
415                 if hasattr(o2, 'name'):
416                     known_options.append(o2.name)
417                 continue
418             for o3 in o2.opts:
419                 assert(isinstance(o3, SimpleOptCheckTypes)), \
420                        f'unexpected ComplexOptCheck inside {o2.name}'
421                 assert(o3.opt_type != 'complex'), f'{o3} with complex opt_type'
422                 if hasattr(o3, 'name'):
423                     known_options.append(o3.name)
424
425     for option, value in parsed_options.items():
426         if option not in known_options:
427             print(f'[?] No check for {opt_type} option {option} ({value})')