4 This tool is for checking the security hardening options of the Linux kernel.
6 Author: Alexander Popov <alex.popov@linux.com>
8 This module is the engine of checks.
11 # pylint: disable=missing-class-docstring,missing-function-docstring
12 # pylint: disable=line-too-long,too-many-branches
14 from __future__ import annotations
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]
23 GREEN_COLOR = '\x1b[32m'
24 RED_COLOR = '\x1b[31m'
28 def colorize_result(input_text: StrOrNone) -> StrOrNone:
29 if input_text is None or not sys.stdout.isatty():
31 if input_text.startswith('OK'):
34 assert(input_text.startswith('FAIL:')), f'unexpected result "{input_text}"'
36 return f'{color}{input_text}{COLOR_END}'
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__}'
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
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'
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())
60 assert(expected in ('is not set', 'is not off')), \
61 f'invalid expected value "{expected}" for "{name}" check (2)'
63 assert(expected == 'is present'), \
64 f'invalid expected value "{expected}" for "{name}" check (3)'
66 assert(val_len == 1), \
67 f'invalid expected value "{expected}" for "{name}" check (4)'
68 self.expected = expected
70 self.state = None # type: str | None
71 self.result = None # type: str | None
74 def opt_type(self) -> StrOrNone:
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'
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'
88 self.result = 'OK: is present'
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'
100 self.result = f'OK: is not off, "{self.state}"'
103 # handle the option value check
104 if self.expected == self.state:
106 elif self.state is None:
107 if self.expected == 'is not set':
108 self.result = 'OK: is not found'
110 self.result = 'FAIL: is not found'
112 self.result = f'FAIL: "{self.state}"'
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='')
117 print(f'| {colorize_result(self.result)}', end='')
119 def json_dump(self, with_results: bool) -> Dict[str, StrOrBool]:
120 assert(self.opt_type), f'unexpected empty opt_type in {self.name}'
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]
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')
135 class KconfigCheck(OptCheck):
136 def __init__(self, *args: str) -> None:
137 super().__init__(*args)
138 self.name = f'CONFIG_{self.name}'
141 def opt_type(self) -> str:
145 class CmdlineCheck(OptCheck):
147 def opt_type(self) -> str:
151 class SysctlCheck(OptCheck):
153 def opt_type(self) -> str:
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
168 def opt_type(self) -> str:
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)'
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}'
183 if self.ver[0] < self.ver_expected[0]:
184 self.result = f'FAIL: version < {self.ver_expected}'
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}'
190 if self.ver[1] < self.ver_expected[1]:
191 self.result = f'FAIL: version < {self.ver_expected}'
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}'
197 self.result = f'FAIL: version < {self.ver_expected}'
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='')
203 print(f'| {colorize_result(self.result)}', end='')
206 class ComplexOptCheck:
207 def __init__(self, *opts: AnyOptCheckType) -> None:
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
218 def opt_type(self) -> str:
222 def name(self) -> str:
223 assert hasattr(self.opts[0], 'name') # true for SimpleNamedOptCheckTypes
224 return self.opts[0].name
227 def expected(self) -> str:
228 assert hasattr(self.opts[0], 'expected') # true for SimpleNamedOptCheckTypes
229 return self.opts[0].expected
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='')
236 print(f'| {colorize_result(self.result)}', end='')
239 o.table_print(mode, with_results)
242 o.table_print(mode, False)
244 print(f'| {colorize_result(self.result)}', end='')
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)
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')
257 class OR(ComplexOptCheck):
258 # self.opts[0] is the option that this OR-check is about.
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):
265 assert(opt.result), 'unexpected empty result of the OR sub-check'
266 if opt.result.startswith('OK'):
267 self.result = opt.result
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
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'
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'
286 self.result = self.opts[0].result
289 class AND(ComplexOptCheck):
290 # self.opts[0] is the option that this AND-check is about.
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))):
298 assert(opt.result), 'unexpected empty result of the AND sub-check'
300 self.result = opt.result
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
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'
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'
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)
332 # 2) complex objects that may contain complex and simple objects
333 ComplexOptCheckType = Union[OR, AND]
334 ComplexOptCheckTypes = (OR, AND)
336 # 3) objects that can be added to the checklist
337 ChecklistObjType = Union[KconfigCheck, CmdlineCheck, SysctlCheck, OR, AND]
339 # 4) all existing objects
340 AnyOptCheckType = Union[KconfigCheck, CmdlineCheck, SysctlCheck, VersionCheck, OR, AND]
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'
349 if data_type != opt.opt_type:
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))
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}"'
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)
373 assert(isinstance(opt, ComplexOptCheckTypes)), \
374 f'unexpected object {opt} with opt_type "{opt.opt_type}"'
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)
381 # Recursion for nested ComplexOptCheck objects
382 populate_opt_with_data(o, data, data_type)
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)
390 def override_expected_value(checklist: List[ChecklistObjType], name: str, new_val: str) -> None:
391 for opt in checklist:
393 assert(isinstance(opt, SimpleNamedOptCheckTypes)), \
394 f'overriding an expected value for {opt}" is not supported yet'
395 opt.expected = new_val
398 def perform_checks(checklist: List[ChecklistObjType]) -> None:
399 for opt in checklist:
403 def print_unknown_options(checklist: List[ChecklistObjType], parsed_options: Dict[str, str], opt_type: str) -> None:
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)
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)
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)
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})')