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