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 name == name.strip() and len(name.split()) == 1), \
42 f'invalid name "{name}" for {self.__class__.__name__}'
45 assert(decision and decision == decision.strip() and len(decision.split()) == 1), \
46 f'invalid decision "{decision}" for "{name}" check'
47 self.decision = decision
49 assert(reason and reason == reason.strip() and len(reason.split()) == 1), \
50 f'invalid reason "{reason}" for "{name}" check'
53 assert(expected and expected == expected.strip()), \
54 f'invalid expected value "{expected}" for "{name}" check (1)'
55 val_len = len(expected.split())
57 assert(expected in ('is not set', 'is not off')), \
58 f'invalid expected value "{expected}" for "{name}" check (2)'
60 assert(expected == 'is present'), \
61 f'invalid expected value "{expected}" for "{name}" check (3)'
63 assert(val_len == 1), \
64 f'invalid expected value "{expected}" for "{name}" check (4)'
65 self.expected = expected
67 self.state = None # type: str | None
68 self.result = None # type: str | None
71 def opt_type(self) -> StrOrNone:
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'
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'
85 self.result = 'OK: is present'
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'
97 self.result = f'OK: is not off, "{self.state}"'
100 # handle the option value check
101 if self.expected == self.state:
103 elif self.state is None:
104 if self.expected == 'is not set':
105 self.result = 'OK: is not found'
107 self.result = 'FAIL: is not found'
109 self.result = f'FAIL: "{self.state}"'
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='')
114 print(f'| {colorize_result(self.result)}', end='')
116 def json_dump(self, with_results: bool) -> Dict[str, StrOrBool]:
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]
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')
131 class KconfigCheck(OptCheck):
132 def __init__(self, *args, **kwargs) -> None:
133 super().__init__(*args, **kwargs)
134 self.name = f'CONFIG_{self.name}'
137 def opt_type(self) -> str:
141 class CmdlineCheck(OptCheck):
143 def opt_type(self) -> str:
147 class SysctlCheck(OptCheck):
149 def opt_type(self) -> str:
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
161 self.result = None # type: str | None
164 def opt_type(self) -> str:
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'
172 def check(self) -> None:
173 if self.ver[0] > self.ver_expected[0]:
174 self.result = f'OK: version >= {self.ver_expected}'
176 if self.ver[0] < self.ver_expected[0]:
177 self.result = f'FAIL: version < {self.ver_expected}'
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}'
183 if self.ver[1] < self.ver_expected[1]:
184 self.result = f'FAIL: version < {self.ver_expected}'
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}'
190 self.result = f'FAIL: version < {self.ver_expected}'
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='')
196 print(f'| {colorize_result(self.result)}', end='')
199 class ComplexOptCheck:
200 def __init__(self, *opts: AnyOptCheckType) -> None:
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
211 def opt_type(self) -> str:
215 def name(self) -> str:
216 return self.opts[0].name
219 def expected(self) -> str:
220 return self.opts[0].expected
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='')
227 print(f'| {colorize_result(self.result)}', end='')
230 o.table_print(mode, with_results)
233 o.table_print(mode, False)
235 print(f'| {colorize_result(self.result)}', end='')
237 def json_dump(self, with_results: bool) -> Dict[str, StrOrBool]:
238 dump = self.opts[0].json_dump(False)
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')
247 class OR(ComplexOptCheck):
248 # self.opts[0] is the option that this OR-check is about.
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):
255 if opt.result.startswith('OK'):
256 self.result = opt.result
257 # Add more info for additional checks:
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'
268 # VersionCheck provides enough info
269 assert(opt.result.startswith('OK: version')), \
270 f'unexpected OK description "{opt.result}"'
272 self.result = self.opts[0].result
275 class AND(ComplexOptCheck):
276 # self.opts[0] is the option that this AND-check is about.
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))):
285 self.result = opt.result
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'
300 # VersionCheck provides enough info
301 self.result = opt.result
302 assert(opt.result.startswith('FAIL: version')), \
303 f'unexpected FAIL description "{opt.result}"'
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)
313 # 2) complex objects that may contain complex and simple objects
314 ComplexOptCheckType = Union[OR, AND]
315 ComplexOptCheckTypes = (OR, AND)
317 # 3) objects that can be added to the checklist
318 ChecklistObjType = Union[KconfigCheck, CmdlineCheck, SysctlCheck, OR, AND]
320 # 4) all existing objects
321 AnyOptCheckType = Union[KconfigCheck, CmdlineCheck, SysctlCheck, VersionCheck, OR, AND]
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}"'
334 if data_type != opt.opt_type:
337 if data_type in ('kconfig', 'cmdline', 'sysctl'):
338 opt.set_state(data.get(opt.name, None))
340 assert(data_type == 'version'), \
341 f'unexpected data_type "{data_type}"'
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)
351 if o.opt_type != 'complex':
352 populate_simple_opt_with_data(o, data, data_type)
354 # Recursion for nested ComplexOptCheck objects
355 populate_opt_with_data(o, data, data_type)
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)
363 def override_expected_value(checklist: List, name: str, new_val: str) -> None:
364 for opt in checklist:
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
371 def perform_checks(checklist: List) -> None:
372 for opt in checklist:
376 def print_unknown_options(checklist: List, parsed_options: OrderedDict[str, str], opt_type: str) -> None:
380 if o1.opt_type != 'complex':
381 known_options.append(o1.name)
384 if o2.opt_type != 'complex':
385 if hasattr(o2, 'name'):
386 known_options.append(o2.name)
389 assert(o3.opt_type != 'complex'), \
390 f'unexpected ComplexOptCheck inside {o2.name}'
391 if hasattr(o3, 'name'):
392 known_options.append(o3.name)
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})')