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,invalid-name,too-many-branches
14 from __future__ import annotations
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]
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, **kwargs) -> None:
137 super().__init__(*args, **kwargs)
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, int, int]
165 self.result = None # type: str | None
168 def opt_type(self) -> str:
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'
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}'
181 if self.ver[0] < self.ver_expected[0]:
182 self.result = f'FAIL: version < {self.ver_expected}'
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}'
188 if self.ver[1] < self.ver_expected[1]:
189 self.result = f'FAIL: version < {self.ver_expected}'
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}'
195 self.result = f'FAIL: version < {self.ver_expected}'
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='')
201 print(f'| {colorize_result(self.result)}', end='')
204 class ComplexOptCheck:
205 def __init__(self, *opts: AnyOptCheckType) -> None:
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
216 def opt_type(self) -> str:
220 def name(self) -> str:
221 assert hasattr(self.opts[0], 'name') # true for SimpleNamedOptCheckTypes
222 return self.opts[0].name
225 def expected(self) -> str:
226 assert hasattr(self.opts[0], 'expected') # true for SimpleNamedOptCheckTypes
227 return self.opts[0].expected
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='')
234 print(f'| {colorize_result(self.result)}', end='')
237 o.table_print(mode, with_results)
240 o.table_print(mode, False)
242 print(f'| {colorize_result(self.result)}', end='')
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)
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')
255 class OR(ComplexOptCheck):
256 # self.opts[0] is the option that this OR-check is about.
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):
263 assert(opt.result), 'unexpected empty result of the OR sub-check'
264 if opt.result.startswith('OK'):
265 self.result = opt.result
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
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'
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'
284 self.result = self.opts[0].result
287 class AND(ComplexOptCheck):
288 # self.opts[0] is the option that this AND-check is about.
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))):
296 assert(opt.result), 'unexpected empty result of the AND sub-check'
298 self.result = opt.result
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
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'
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'
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)
330 # 2) complex objects that may contain complex and simple objects
331 ComplexOptCheckType = Union[OR, AND]
332 ComplexOptCheckTypes = (OR, AND)
334 # 3) objects that can be added to the checklist
335 ChecklistObjType = Union[KconfigCheck, CmdlineCheck, SysctlCheck, OR, AND]
337 # 4) all existing objects
338 AnyOptCheckType = Union[KconfigCheck, CmdlineCheck, SysctlCheck, VersionCheck, OR, AND]
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'
347 if data_type != opt.opt_type:
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))
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}"'
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)
371 assert(isinstance(opt, ComplexOptCheckTypes)), \
372 f'unexpected object {opt} with opt_type "{opt.opt_type}"'
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)
379 # Recursion for nested ComplexOptCheck objects
380 populate_opt_with_data(o, data, data_type)
383 def populate_with_data(checklist: List, data: TupleOrOrderedDict, data_type: str) -> None:
384 for opt in checklist:
385 populate_opt_with_data(opt, data, data_type)
388 def override_expected_value(checklist: List, name: str, new_val: str) -> None:
389 for opt in checklist:
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
396 def perform_checks(checklist: List) -> None:
397 for opt in checklist:
401 def print_unknown_options(checklist: List, parsed_options: OrderedDict[str, str], opt_type: str) -> None:
405 if o1.opt_type != 'complex':
406 known_options.append(o1.name)
409 if o2.opt_type != 'complex':
410 if hasattr(o2, 'name'):
411 known_options.append(o2.name)
414 assert(o3.opt_type != 'complex'), \
415 f'unexpected ComplexOptCheck inside {o2.name}'
416 if hasattr(o3, 'name'):
417 known_options.append(o3.name)
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})')