Rename kconfig-hardened-check into kernel-hardening-checker (#85)
[kconfig-hardened-check.git] / kernel_hardening_checker / engine.py
1 #!/usr/bin/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,invalid-name,too-many-branches
13
14 GREEN_COLOR = '\x1b[32m'
15 RED_COLOR = '\x1b[31m'
16 COLOR_END = '\x1b[0m'
17
18 def colorize_result(input_text):
19     if input_text is None:
20         return input_text
21     if input_text.startswith('OK'):
22         color = GREEN_COLOR
23     elif input_text.startswith('FAIL:'):
24         color = RED_COLOR
25     else:
26         assert(False), f'unexpected result "{input_text}"'
27     return f'{color}{input_text}{COLOR_END}'
28
29
30 class OptCheck:
31     def __init__(self, reason, decision, name, expected):
32         assert(name and name == name.strip() and len(name.split()) == 1), \
33                f'invalid name "{name}" for {self.__class__.__name__}'
34         self.name = name
35
36         assert(decision and decision == decision.strip() and len(decision.split()) == 1), \
37                f'invalid decision "{decision}" for "{name}" check'
38         self.decision = decision
39
40         assert(reason and reason == reason.strip() and len(reason.split()) == 1), \
41                f'invalid reason "{reason}" for "{name}" check'
42         self.reason = reason
43
44         assert(expected and expected == expected.strip()), \
45                f'invalid expected value "{expected}" for "{name}" check (1)'
46         val_len = len(expected.split())
47         if val_len == 3:
48             assert(expected in ('is not set', 'is not off')), \
49                    f'invalid expected value "{expected}" for "{name}" check (2)'
50         elif val_len == 2:
51             assert(expected == 'is present'), \
52                    f'invalid expected value "{expected}" for "{name}" check (3)'
53         else:
54             assert(val_len == 1), \
55                    f'invalid expected value "{expected}" for "{name}" check (4)'
56         self.expected = expected
57
58         self.state = None
59         self.result = None
60
61     def check(self):
62         # handle the 'is present' check
63         if self.expected == 'is present':
64             if self.state is None:
65                 self.result = 'FAIL: is not present'
66             else:
67                 self.result = 'OK: is present'
68             return
69
70         # handle the 'is not off' option check
71         if self.expected == 'is not off':
72             if self.state == 'off':
73                 self.result = 'FAIL: is off'
74             elif self.state == '0':
75                 self.result = 'FAIL: is off, "0"'
76             elif self.state is None:
77                 self.result = 'FAIL: is off, not found'
78             else:
79                 self.result = f'OK: is not off, "{self.state}"'
80             return
81
82         # handle the option value check
83         if self.expected == self.state:
84             self.result = 'OK'
85         elif self.state is None:
86             if self.expected == 'is not set':
87                 self.result = 'OK: is not found'
88             else:
89                 self.result = 'FAIL: is not found'
90         else:
91             self.result = f'FAIL: "{self.state}"'
92
93     def table_print(self, _mode, with_results):
94         print(f'{self.name:<40}|{self.type:^7}|{self.expected:^12}|{self.decision:^10}|{self.reason:^18}', end='')
95         if with_results:
96             print(f'| {colorize_result(self.result)}', end='')
97
98     def json_dump(self, with_results):
99         dump = [self.name, self.type, self.expected, self.decision, self.reason]
100         if with_results:
101             dump.append(self.result)
102         return dump
103
104
105 class KconfigCheck(OptCheck):
106     def __init__(self, *args, **kwargs):
107         super().__init__(*args, **kwargs)
108         self.name = 'CONFIG_' + self.name
109
110     @property
111     def type(self):
112         return 'kconfig'
113
114
115 class CmdlineCheck(OptCheck):
116     @property
117     def type(self):
118         return 'cmdline'
119
120
121 class SysctlCheck(OptCheck):
122     @property
123     def type(self):
124         return 'sysctl'
125
126
127 class VersionCheck:
128     def __init__(self, ver_expected):
129         assert(ver_expected and isinstance(ver_expected, tuple) and len(ver_expected) == 2), \
130                f'invalid version "{ver_expected}" for VersionCheck'
131         self.ver_expected = ver_expected
132         self.ver = ()
133         self.result = None
134
135     @property
136     def type(self):
137         return 'version'
138
139     def check(self):
140         if self.ver[0] > self.ver_expected[0]:
141             self.result = f'OK: version >= {self.ver_expected[0]}.{self.ver_expected[1]}'
142             return
143         if self.ver[0] < self.ver_expected[0]:
144             self.result = f'FAIL: version < {self.ver_expected[0]}.{self.ver_expected[1]}'
145             return
146         if self.ver[1] >= self.ver_expected[1]:
147             self.result = f'OK: version >= {self.ver_expected[0]}.{self.ver_expected[1]}'
148             return
149         self.result = f'FAIL: version < {self.ver_expected[0]}.{self.ver_expected[1]}'
150
151     def table_print(self, _mode, with_results):
152         ver_req = f'kernel version >= {self.ver_expected[0]}.{self.ver_expected[1]}'
153         print(f'{ver_req:<91}', end='')
154         if with_results:
155             print(f'| {colorize_result(self.result)}', end='')
156
157
158 class ComplexOptCheck:
159     def __init__(self, *opts):
160         self.opts = opts
161         assert(self.opts), \
162                f'empty {self.__class__.__name__} check'
163         assert(len(self.opts) != 1), \
164                f'useless {self.__class__.__name__} check: {opts}'
165         assert(isinstance(opts[0], (KconfigCheck, CmdlineCheck, SysctlCheck))), \
166                f'invalid {self.__class__.__name__} check: {opts}'
167         self.result = None
168
169     @property
170     def type(self):
171         return 'complex'
172
173     @property
174     def name(self):
175         return self.opts[0].name
176
177     @property
178     def expected(self):
179         return self.opts[0].expected
180
181     def table_print(self, mode, with_results):
182         if mode == 'verbose':
183             print(f'    {"<<< " + self.__class__.__name__ + " >>>":87}', end='')
184             if with_results:
185                 print(f'| {colorize_result(self.result)}', end='')
186             for o in self.opts:
187                 print()
188                 o.table_print(mode, with_results)
189         else:
190             o = self.opts[0]
191             o.table_print(mode, False)
192             if with_results:
193                 print(f'| {colorize_result(self.result)}', end='')
194
195     def json_dump(self, with_results):
196         dump = self.opts[0].json_dump(False)
197         if with_results:
198             dump.append(self.result)
199         return dump
200
201
202 class OR(ComplexOptCheck):
203     # self.opts[0] is the option that this OR-check is about.
204     # Use cases:
205     #     OR(<X_is_hardened>, <X_is_disabled>)
206     #     OR(<X_is_hardened>, <old_X_is_hardened>)
207     def check(self):
208         for i, opt in enumerate(self.opts):
209             opt.check()
210             if opt.result.startswith('OK'):
211                 self.result = opt.result
212                 # Add more info for additional checks:
213                 if i != 0:
214                     if opt.result == 'OK':
215                         self.result = f'OK: {opt.name} is "{opt.expected}"'
216                     elif opt.result == 'OK: is not found':
217                         self.result = f'OK: {opt.name} is not found'
218                     elif opt.result == 'OK: is present':
219                         self.result = f'OK: {opt.name} is present'
220                     elif opt.result.startswith('OK: is not off'):
221                         self.result = f'OK: {opt.name} is not off'
222                     else:
223                         # VersionCheck provides enough info
224                         assert(opt.result.startswith('OK: version')), \
225                                f'unexpected OK description "{opt.result}"'
226                 return
227         self.result = self.opts[0].result
228
229
230 class AND(ComplexOptCheck):
231     # self.opts[0] is the option that this AND-check is about.
232     # Use cases:
233     #     AND(<suboption>, <main_option>)
234     #       Suboption is not checked if checking of the main_option is failed.
235     #     AND(<X_is_disabled>, <old_X_is_disabled>)
236     def check(self):
237         for i, opt in reversed(list(enumerate(self.opts))):
238             opt.check()
239             if i == 0:
240                 self.result = opt.result
241                 return
242             if not opt.result.startswith('OK'):
243                 # This FAIL is caused by additional checks,
244                 # and not by the main option that this AND-check is about.
245                 # Describe the reason of the FAIL.
246                 if opt.result.startswith('FAIL: \"') or opt.result == 'FAIL: is not found':
247                     self.result = f'FAIL: {opt.name} is not "{opt.expected}"'
248                 elif opt.result == 'FAIL: is not present':
249                     self.result = f'FAIL: {opt.name} is not present'
250                 elif opt.result in ('FAIL: is off', 'FAIL: is off, "0"'):
251                     self.result = f'FAIL: {opt.name} is off'
252                 elif opt.result == 'FAIL: is off, not found':
253                     self.result = f'FAIL: {opt.name} is off, not found'
254                 else:
255                     # VersionCheck provides enough info
256                     self.result = opt.result
257                     assert(opt.result.startswith('FAIL: version')), \
258                            f'unexpected FAIL description "{opt.result}"'
259                 return
260
261
262 SIMPLE_OPTION_TYPES = ('kconfig', 'cmdline', 'sysctl', 'version')
263
264
265 def populate_simple_opt_with_data(opt, data, data_type):
266     assert(opt.type != 'complex'), \
267            f'unexpected ComplexOptCheck "{opt.name}"'
268     assert(opt.type in SIMPLE_OPTION_TYPES), \
269            f'invalid opt type "{opt.type}"'
270     assert(data_type in SIMPLE_OPTION_TYPES), \
271            f'invalid data type "{data_type}"'
272     assert(data), \
273            'empty data'
274
275     if data_type != opt.type:
276         return
277
278     if data_type in ('kconfig', 'cmdline', 'sysctl'):
279         opt.state = data.get(opt.name, None)
280     else:
281         assert(data_type == 'version'), \
282                f'unexpected data type "{data_type}"'
283         opt.ver = data
284
285
286 def populate_opt_with_data(opt, data, data_type):
287     assert(opt.type != 'version'), 'a single VersionCheck is useless'
288     if opt.type != 'complex':
289         populate_simple_opt_with_data(opt, data, data_type)
290     else:
291         for o in opt.opts:
292             if o.type != 'complex':
293                 populate_simple_opt_with_data(o, data, data_type)
294             else:
295                 # Recursion for nested ComplexOptCheck objects
296                 populate_opt_with_data(o, data, data_type)
297
298
299 def populate_with_data(checklist, data, data_type):
300     for opt in checklist:
301         populate_opt_with_data(opt, data, data_type)
302
303
304 def override_expected_value(checklist, name, new_val):
305     for opt in checklist:
306         if opt.name == name:
307             assert(opt.type in ('kconfig', 'cmdline', 'sysctl')), \
308                    f'overriding an expected value for "{opt.type}" checks is not supported yet'
309             opt.expected = new_val
310
311
312 def perform_checks(checklist):
313     for opt in checklist:
314         opt.check()