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