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
16 from typing import Optional, Dict, Tuple
17 StrOrNone = Optional[str]
18 TupleOrNone = Optional[Tuple]
20 GREEN_COLOR = '\x1b[32m'
21 RED_COLOR = '\x1b[31m'
24 def colorize_result(input_text):
25 if input_text is None or not sys.stdout.isatty():
27 if input_text.startswith('OK'):
30 assert(input_text.startswith('FAIL:')), f'unexpected result "{input_text}"'
32 return f'{color}{input_text}{COLOR_END}'
36 def __init__(self, reason: str, decision: str, name: str, expected: str):
37 assert(name and name == name.strip() and len(name.split()) == 1), \
38 f'invalid name "{name}" for {self.__class__.__name__}'
41 assert(decision and decision == decision.strip() and len(decision.split()) == 1), \
42 f'invalid decision "{decision}" for "{name}" check'
43 self.decision = decision
45 assert(reason and reason == reason.strip() and len(reason.split()) == 1), \
46 f'invalid reason "{reason}" for "{name}" check'
49 assert(expected and expected == expected.strip()), \
50 f'invalid expected value "{expected}" for "{name}" check (1)'
51 val_len = len(expected.split())
53 assert(expected in ('is not set', 'is not off')), \
54 f'invalid expected value "{expected}" for "{name}" check (2)'
56 assert(expected == 'is present'), \
57 f'invalid expected value "{expected}" for "{name}" check (3)'
59 assert(val_len == 1), \
60 f'invalid expected value "{expected}" for "{name}" check (4)'
61 self.expected = expected
70 def set_state(self, data):
71 assert(data is None or isinstance(data, str)), \
72 f'invalid state "{data}" for "{self.name}" check'
76 # handle the 'is present' check
77 if self.expected == 'is present':
78 if self.state is None:
79 self.result = 'FAIL: is not present'
81 self.result = 'OK: is present'
84 # handle the 'is not off' option check
85 if self.expected == 'is not off':
86 if self.state == 'off':
87 self.result = 'FAIL: is off'
88 elif self.state == '0':
89 self.result = 'FAIL: is off, "0"'
90 elif self.state is None:
91 self.result = 'FAIL: is off, not found'
93 self.result = f'OK: is not off, "{self.state}"'
96 # handle the option value check
97 if self.expected == self.state:
99 elif self.state is None:
100 if self.expected == 'is not set':
101 self.result = 'OK: is not found'
103 self.result = 'FAIL: is not found'
105 self.result = f'FAIL: "{self.state}"'
107 def table_print(self, _mode, with_results: bool):
108 print(f'{self.name:<40}|{self.opt_type:^7}|{self.expected:^12}|{self.decision:^10}|{self.reason:^18}', end='')
110 print(f'| {colorize_result(self.result)}', end='')
112 def json_dump(self, with_results: bool) -> Dict:
114 "option_name": self.name,
115 "type": self.opt_type,
116 "desired_val": self.expected,
117 "decision": self.decision,
118 "reason": self.reason,
121 assert self.result, f'unexpected empty result in {self.name}'
122 dump["check_result"] = self.result
123 dump["check_result_bool"] = self.result.startswith('OK')
127 class KconfigCheck(OptCheck):
128 def __init__(self, *args, **kwargs):
129 super().__init__(*args, **kwargs)
130 self.name = f'CONFIG_{self.name}'
137 class CmdlineCheck(OptCheck):
143 class SysctlCheck(OptCheck):
150 def __init__(self, ver_expected: Tuple):
151 assert(ver_expected and isinstance(ver_expected, tuple) and len(ver_expected) == 3), \
152 f'invalid expected version "{ver_expected}" for VersionCheck (1)'
153 assert(all(map(lambda x: isinstance(x, int), ver_expected))), \
154 f'invalid expected version "{ver_expected}" for VersionCheck (2)'
155 self.ver_expected = ver_expected
163 def set_state(self, data: Tuple):
164 assert(data and isinstance(data, tuple) and len(data) >= 3), \
165 f'invalid version "{data}" for VersionCheck'
169 if self.ver[0] > self.ver_expected[0]:
170 self.result = f'OK: version >= {self.ver_expected}'
172 if self.ver[0] < self.ver_expected[0]:
173 self.result = f'FAIL: version < {self.ver_expected}'
175 # self.ver[0] and self.ver_expected[0] are equal
176 if self.ver[1] > self.ver_expected[1]:
177 self.result = f'OK: version >= {self.ver_expected}'
179 if self.ver[1] < self.ver_expected[1]:
180 self.result = f'FAIL: version < {self.ver_expected}'
182 # self.ver[1] and self.ver_expected[1] are equal too
183 if self.ver[2] >= self.ver_expected[2]:
184 self.result = f'OK: version >= {self.ver_expected}'
186 self.result = f'FAIL: version < {self.ver_expected}'
188 def table_print(self, _mode, with_results: bool):
189 ver_req = f'kernel version >= {self.ver_expected}'
190 print(f'{ver_req:<91}', end='')
192 print(f'| {colorize_result(self.result)}', end='')
195 class ComplexOptCheck:
196 def __init__(self, *opts):
199 f'empty {self.__class__.__name__} check'
200 assert(len(self.opts) != 1), \
201 f'useless {self.__class__.__name__} check: {opts}'
202 assert(isinstance(opts[0], (KconfigCheck, CmdlineCheck, SysctlCheck))), \
203 f'invalid {self.__class__.__name__} check: {opts}'
212 return self.opts[0].name
216 return self.opts[0].expected
218 def table_print(self, mode: str, with_results: bool):
219 if mode == 'verbose':
220 class_name = f'<<< {self.__class__.__name__} >>>'
221 print(f' {class_name:87}', end='')
223 print(f'| {colorize_result(self.result)}', end='')
226 o.table_print(mode, with_results)
229 o.table_print(mode, False)
231 print(f'| {colorize_result(self.result)}', end='')
233 def json_dump(self, with_results: bool) -> Dict:
234 dump = self.opts[0].json_dump(False)
236 # Add the 'check_result' and 'check_result_bool' keys to the dictionary
237 assert self.result, f'unexpected empty result in {self.name}'
238 dump["check_result"] = self.result
239 dump["check_result_bool"] = self.result.startswith('OK')
243 class OR(ComplexOptCheck):
244 # self.opts[0] is the option that this OR-check is about.
246 # OR(<X_is_hardened>, <X_is_disabled>)
247 # OR(<X_is_hardened>, <old_X_is_hardened>)
249 for i, opt in enumerate(self.opts):
251 if opt.result.startswith('OK'):
252 self.result = opt.result
253 # Add more info for additional checks:
255 if opt.result == 'OK':
256 self.result = f'OK: {opt.name} is "{opt.expected}"'
257 elif opt.result == 'OK: is not found':
258 self.result = f'OK: {opt.name} is not found'
259 elif opt.result == 'OK: is present':
260 self.result = f'OK: {opt.name} is present'
261 elif opt.result.startswith('OK: is not off'):
262 self.result = f'OK: {opt.name} is not off'
264 # VersionCheck provides enough info
265 assert(opt.result.startswith('OK: version')), \
266 f'unexpected OK description "{opt.result}"'
268 self.result = self.opts[0].result
271 class AND(ComplexOptCheck):
272 # self.opts[0] is the option that this AND-check is about.
274 # AND(<suboption>, <main_option>)
275 # Suboption is not checked if checking of the main_option is failed.
276 # AND(<X_is_disabled>, <old_X_is_disabled>)
278 for i, opt in reversed(list(enumerate(self.opts))):
281 self.result = opt.result
283 if not opt.result.startswith('OK'):
284 # This FAIL is caused by additional checks,
285 # and not by the main option that this AND-check is about.
286 # Describe the reason of the FAIL.
287 if opt.result.startswith('FAIL: \"') or opt.result == 'FAIL: is not found':
288 self.result = f'FAIL: {opt.name} is not "{opt.expected}"'
289 elif opt.result == 'FAIL: is not present':
290 self.result = f'FAIL: {opt.name} is not present'
291 elif opt.result in ('FAIL: is off', 'FAIL: is off, "0"'):
292 self.result = f'FAIL: {opt.name} is off'
293 elif opt.result == 'FAIL: is off, not found':
294 self.result = f'FAIL: {opt.name} is off, not found'
296 # VersionCheck provides enough info
297 self.result = opt.result
298 assert(opt.result.startswith('FAIL: version')), \
299 f'unexpected FAIL description "{opt.result}"'
303 SIMPLE_OPTION_TYPES = ('kconfig', 'cmdline', 'sysctl', 'version')
306 def populate_simple_opt_with_data(opt, data, data_type: str):
307 assert(opt.opt_type != 'complex'), \
308 f'unexpected ComplexOptCheck "{opt.name}"'
309 assert(opt.opt_type in SIMPLE_OPTION_TYPES), \
310 f'invalid opt_type "{opt.opt_type}"'
311 assert(data_type in SIMPLE_OPTION_TYPES), \
312 f'invalid data_type "{data_type}"'
316 if data_type != opt.opt_type:
319 if data_type in ('kconfig', 'cmdline', 'sysctl'):
320 opt.set_state(data.get(opt.name, None))
322 assert(data_type == 'version'), \
323 f'unexpected data_type "{data_type}"'
327 def populate_opt_with_data(opt, data, data_type):
328 assert(opt.opt_type != 'version'), 'a single VersionCheck is useless'
329 if opt.opt_type != 'complex':
330 populate_simple_opt_with_data(opt, data, data_type)
333 if o.opt_type != 'complex':
334 populate_simple_opt_with_data(o, data, data_type)
336 # Recursion for nested ComplexOptCheck objects
337 populate_opt_with_data(o, data, data_type)
340 def populate_with_data(checklist, data, data_type):
341 for opt in checklist:
342 populate_opt_with_data(opt, data, data_type)
345 def override_expected_value(checklist, name, new_val):
346 for opt in checklist:
348 assert(opt.opt_type in ('kconfig', 'cmdline', 'sysctl')), \
349 f'overriding an expected value for "{opt.opt_type}" checks is not supported yet'
350 opt.expected = new_val
353 def perform_checks(checklist):
354 for opt in checklist: