blob: 8123ea1ef50b51bf5d258003b3e985ca51ee3d07 [file] [log] [blame]
Gilles Peskine15c2cbf2020-06-25 18:36:28 +02001#!/usr/bin/env python3
2
3"""Analyze the test outcomes from a full CI run.
4
5This script can also run on outcomes from a partial run, but the results are
6less likely to be useful.
7"""
8
9import argparse
10import sys
11import traceback
Przemek Stekiel85c54ea2022-11-17 11:50:23 +010012import re
Valerio Settia2663322023-03-24 08:20:18 +010013import subprocess
14import os
Pengyu Lv18908ec2023-11-28 12:11:52 +080015import typing
Gilles Peskine15c2cbf2020-06-25 18:36:28 +020016
Gilles Peskinec8c83d02024-10-03 17:35:52 +020017import collect_test_cases
Gilles Peskine8d3c70a2020-06-25 18:37:43 +020018
Pengyu Lvc2e8f3a2023-11-28 17:22:04 +080019
Pengyu Lv550cd6f2023-11-29 09:17:59 +080020# `ComponentOutcomes` is a named tuple which is defined as:
Pengyu Lvc2e8f3a2023-11-28 17:22:04 +080021# ComponentOutcomes(
22# successes = {
23# "<suite_case>",
24# ...
25# },
26# failures = {
27# "<suite_case>",
28# ...
29# }
30# )
31# suite_case = "<suite>;<case>"
Pengyu Lv18908ec2023-11-28 12:11:52 +080032ComponentOutcomes = typing.NamedTuple('ComponentOutcomes',
33 [('successes', typing.Set[str]),
34 ('failures', typing.Set[str])])
35
Pengyu Lvc2e8f3a2023-11-28 17:22:04 +080036# `Outcomes` is a representation of the outcomes file,
37# which defined as:
38# Outcomes = {
39# "<component>": ComponentOutcomes,
40# ...
41# }
42Outcomes = typing.Dict[str, ComponentOutcomes]
43
44
Gilles Peskine15c2cbf2020-06-25 18:36:28 +020045class Results:
46 """Process analysis results."""
47
48 def __init__(self):
49 self.error_count = 0
50 self.warning_count = 0
51
Valerio Setti2cff8202023-10-18 14:36:47 +020052 def new_section(self, fmt, *args, **kwargs):
53 self._print_line('\n*** ' + fmt + ' ***\n', *args, **kwargs)
54
Valerio Settiaaef0bc2023-10-10 09:42:13 +020055 def info(self, fmt, *args, **kwargs):
Valerio Setti8070dbe2023-10-17 12:29:30 +020056 self._print_line('Info: ' + fmt, *args, **kwargs)
Gilles Peskine15c2cbf2020-06-25 18:36:28 +020057
58 def error(self, fmt, *args, **kwargs):
Gilles Peskine15c2cbf2020-06-25 18:36:28 +020059 self.error_count += 1
Valerio Setti8070dbe2023-10-17 12:29:30 +020060 self._print_line('Error: ' + fmt, *args, **kwargs)
Gilles Peskine15c2cbf2020-06-25 18:36:28 +020061
62 def warning(self, fmt, *args, **kwargs):
Gilles Peskine15c2cbf2020-06-25 18:36:28 +020063 self.warning_count += 1
Valerio Setti8070dbe2023-10-17 12:29:30 +020064 self._print_line('Warning: ' + fmt, *args, **kwargs)
Gilles Peskine15c2cbf2020-06-25 18:36:28 +020065
Valerio Setti3f339892023-10-17 10:42:11 +020066 @staticmethod
Valerio Setti8070dbe2023-10-17 12:29:30 +020067 def _print_line(fmt, *args, **kwargs):
Valerio Setti735794c2023-10-18 08:05:15 +020068 sys.stderr.write((fmt + '\n').format(*args, **kwargs))
Gilles Peskine15c2cbf2020-06-25 18:36:28 +020069
Pengyu Lvc2e8f3a2023-11-28 17:22:04 +080070def execute_reference_driver_tests(results: Results, ref_component: str, driver_component: str, \
71 outcome_file: str) -> None:
Valerio Setti22992a02023-03-29 11:15:28 +020072 """Run the tests specified in ref_component and driver_component. Results
73 are stored in the output_file and they will be used for the following
Valerio Settia2663322023-03-24 08:20:18 +010074 coverage analysis"""
Pengyu Lv20e3ca32023-11-28 15:30:03 +080075 results.new_section("Test {} and {}", ref_component, driver_component)
Valerio Settia2663322023-03-24 08:20:18 +010076
77 shell_command = "tests/scripts/all.sh --outcome-file " + outcome_file + \
78 " " + ref_component + " " + driver_component
Valerio Setti39d4b9d2023-10-18 14:30:03 +020079 results.info("Running: {}", shell_command)
Valerio Settia2663322023-03-24 08:20:18 +010080 ret_val = subprocess.run(shell_command.split(), check=False).returncode
81
82 if ret_val != 0:
Valerio Settif075e472023-10-17 11:03:16 +020083 results.error("failed to run reference/driver components")
Valerio Settia2663322023-03-24 08:20:18 +010084
Gilles Peskine82b16722024-09-16 19:57:10 +020085IgnoreEntry = typing.Union[str, typing.Pattern]
86
87def name_matches_pattern(name: str, str_or_re: IgnoreEntry) -> bool:
Manuel Pégourié-Gonnard881ce012023-10-18 10:22:07 +020088 """Check if name matches a pattern, that may be a string or regex.
89 - If the pattern is a string, name must be equal to match.
90 - If the pattern is a regex, name must fully match.
91 """
Manuel Pégourié-Gonnardb2695432023-10-23 09:30:40 +020092 # The CI's python is too old for re.Pattern
93 #if isinstance(str_or_re, re.Pattern):
94 if not isinstance(str_or_re, str):
Pengyu Lvc2e8f3a2023-11-28 17:22:04 +080095 return str_or_re.fullmatch(name) is not None
Manuel Pégourié-Gonnard881ce012023-10-18 10:22:07 +020096 else:
Manuel Pégourié-Gonnard9d9c2342023-10-26 09:37:40 +020097 return str_or_re == name
Manuel Pégourié-Gonnard881ce012023-10-18 10:22:07 +020098
Pengyu Lvc2e8f3a2023-11-28 17:22:04 +080099def read_outcome_file(outcome_file: str) -> Outcomes:
Gilles Peskine15c2cbf2020-06-25 18:36:28 +0200100 """Parse an outcome file and return an outcome collection.
Pengyu Lvc2e8f3a2023-11-28 17:22:04 +0800101 """
Gilles Peskine15c2cbf2020-06-25 18:36:28 +0200102 outcomes = {}
103 with open(outcome_file, 'r', encoding='utf-8') as input_file:
104 for line in input_file:
Pengyu Lvdd1d6a72023-11-27 17:57:31 +0800105 (_platform, component, suite, case, result, _cause) = line.split(';')
Pengyu Lv451ec8a2023-11-28 17:59:05 +0800106 # Note that `component` is not unique. If a test case passes on Linux
107 # and fails on FreeBSD, it'll end up in both the successes set and
108 # the failures set.
Pengyu Lv31a9b782023-11-23 14:15:37 +0800109 suite_case = ';'.join([suite, case])
Pengyu Lvdd1d6a72023-11-27 17:57:31 +0800110 if component not in outcomes:
Pengyu Lv18908ec2023-11-28 12:11:52 +0800111 outcomes[component] = ComponentOutcomes(set(), set())
Gilles Peskine15c2cbf2020-06-25 18:36:28 +0200112 if result == 'PASS':
Pengyu Lv18908ec2023-11-28 12:11:52 +0800113 outcomes[component].successes.add(suite_case)
Gilles Peskine15c2cbf2020-06-25 18:36:28 +0200114 elif result == 'FAIL':
Pengyu Lv18908ec2023-11-28 12:11:52 +0800115 outcomes[component].failures.add(suite_case)
Pengyu Lva4428582023-11-22 19:02:15 +0800116
Gilles Peskine15c2cbf2020-06-25 18:36:28 +0200117 return outcomes
118
Gilles Peskine19ef1ae2024-09-16 19:12:09 +0200119
120class Task:
121 """Base class for outcome analysis tasks."""
122
Gilles Peskine02976052024-09-16 20:44:15 +0200123 # Override the following in child classes.
124 # Map test suite names (with the test_suite_prefix) to a list of ignored
125 # test cases. Each element in the list can be either a string or a regex;
126 # see the `name_matches_pattern` function.
127 IGNORED_TESTS = {} #type: typing.Dict[str, typing.List[IgnoreEntry]]
128
Gilles Peskine19ef1ae2024-09-16 19:12:09 +0200129 def __init__(self, options) -> None:
130 """Pass command line options to the tasks.
131
132 Each task decides which command line options it cares about.
133 """
134 pass
135
Gilles Peskinef646dbf2024-09-16 19:15:29 +0200136 def section_name(self) -> str:
137 """The section name to use in results."""
138
Gilles Peskinedba80102024-09-16 20:52:58 +0200139 def ignored_tests(self, test_suite: str) -> typing.Iterator[IgnoreEntry]:
140 """Generate the ignore list for the specified test suite."""
141 if test_suite in self.IGNORED_TESTS:
142 yield from self.IGNORED_TESTS[test_suite]
143 pos = test_suite.find('.')
144 if pos != -1:
145 base_test_suite = test_suite[:pos]
146 if base_test_suite in self.IGNORED_TESTS:
147 yield from self.IGNORED_TESTS[base_test_suite]
148
149 def is_test_case_ignored(self, test_suite: str, test_string: str) -> bool:
Gilles Peskine02976052024-09-16 20:44:15 +0200150 """Check if the specified test case is ignored."""
Gilles Peskinedba80102024-09-16 20:52:58 +0200151 for str_or_re in self.ignored_tests(test_suite):
Gilles Peskine02976052024-09-16 20:44:15 +0200152 if name_matches_pattern(test_string, str_or_re):
153 return True
154 return False
155
Gilles Peskine19ef1ae2024-09-16 19:12:09 +0200156 def run(self, results: Results, outcomes: Outcomes):
157 """Run the analysis on the specified outcomes.
158
159 Signal errors via the results objects
160 """
161 raise NotImplementedError
162
163
Gilles Peskinef646dbf2024-09-16 19:15:29 +0200164class CoverageTask(Task):
165 """Analyze test coverage."""
166
Gilles Peskine0930b332024-09-26 19:54:38 +0200167 # Test cases whose suite and description are matched by an entry in
168 # IGNORED_TESTS are expected to be never executed.
169 # All other test cases are expected to be executed at least once.
Gilles Peskinef646dbf2024-09-16 19:15:29 +0200170
171 def __init__(self, options) -> None:
172 super().__init__(options)
173 self.full_coverage = options.full_coverage #type: bool
174
175 @staticmethod
176 def section_name() -> str:
177 return "Analyze coverage"
178
Gilles Peskineb4daeb42024-09-16 20:32:59 +0200179 def run(self, results: Results, outcomes: Outcomes) -> None:
Gilles Peskine3f5022e2024-09-16 20:23:40 +0200180 """Check that all available test cases are executed at least once."""
181 # Make sure that the generated data files are present (and up-to-date).
182 # This allows analyze_outcomes.py to run correctly on a fresh Git
183 # checkout.
184 cp = subprocess.run(['make', 'generated_files'],
185 cwd='tests',
186 stdout=subprocess.PIPE, stderr=subprocess.STDOUT,
187 check=False)
188 if cp.returncode != 0:
189 sys.stderr.write(cp.stdout.decode('utf-8'))
190 results.error("Failed \"make generated_files\" in tests. "
191 "Coverage analysis may be incorrect.")
Gilles Peskinec8c83d02024-10-03 17:35:52 +0200192 available = collect_test_cases.collect_available_test_cases()
Gilles Peskine3f5022e2024-09-16 20:23:40 +0200193 for suite_case in available:
194 hit = any(suite_case in comp_outcomes.successes or
195 suite_case in comp_outcomes.failures
196 for comp_outcomes in outcomes.values())
Gilles Peskine54cfe772024-09-16 20:56:43 +0200197 (test_suite, test_description) = suite_case.split(';')
198 ignored = self.is_test_case_ignored(test_suite, test_description)
Gilles Peskine3f5022e2024-09-16 20:23:40 +0200199
Gilles Peskine54cfe772024-09-16 20:56:43 +0200200 if not hit and not ignored:
Gilles Peskineb4daeb42024-09-16 20:32:59 +0200201 if self.full_coverage:
Gilles Peskine3f5022e2024-09-16 20:23:40 +0200202 results.error('Test case not executed: {}', suite_case)
203 else:
204 results.warning('Test case not executed: {}', suite_case)
Gilles Peskine54cfe772024-09-16 20:56:43 +0200205 elif hit and ignored:
Gilles Peskine0930b332024-09-26 19:54:38 +0200206 # If a test case is no longer always skipped, we should remove
207 # it from the ignore list.
Gilles Peskineb4daeb42024-09-16 20:32:59 +0200208 if self.full_coverage:
Gilles Peskine0930b332024-09-26 19:54:38 +0200209 results.error('Test case was executed but marked as ignored for coverage: {}',
210 suite_case)
Gilles Peskine3f5022e2024-09-16 20:23:40 +0200211 else:
Gilles Peskine0930b332024-09-26 19:54:38 +0200212 results.warning('Test case was executed but marked as ignored for coverage: {}',
213 suite_case)
Gilles Peskine3f5022e2024-09-16 20:23:40 +0200214
Gilles Peskinef646dbf2024-09-16 19:15:29 +0200215
Gilles Peskine82b16722024-09-16 19:57:10 +0200216class DriverVSReference(Task):
217 """Compare outcomes from testing with and without a driver.
218
219 There are 2 options to use analyze_driver_vs_reference_xxx locally:
220 1. Run tests and then analysis:
221 - tests/scripts/all.sh --outcome-file "$PWD/out.csv" <component_ref> <component_driver>
222 - tests/scripts/analyze_outcomes.py out.csv analyze_driver_vs_reference_xxx
223 2. Let this script run both automatically:
224 - tests/scripts/analyze_outcomes.py out.csv analyze_driver_vs_reference_xxx
225 """
226
227 # Override the following in child classes.
228 # Configuration name (all.sh component) used as the reference.
229 REFERENCE = ''
230 # Configuration name (all.sh component) used as the driver.
231 DRIVER = ''
232 # Ignored test suites (without the test_suite_ prefix).
233 IGNORED_SUITES = [] #type: typing.List[str]
Gilles Peskine82b16722024-09-16 19:57:10 +0200234
Gilles Peskineb4daeb42024-09-16 20:32:59 +0200235 def __init__(self, options) -> None:
236 super().__init__(options)
237 self.ignored_suites = frozenset('test_suite_' + x
238 for x in self.IGNORED_SUITES)
239
Gilles Peskine82b16722024-09-16 19:57:10 +0200240 def section_name(self) -> str:
241 return f"Analyze driver {self.DRIVER} vs reference {self.REFERENCE}"
242
Gilles Peskineb4daeb42024-09-16 20:32:59 +0200243 def run(self, results: Results, outcomes: Outcomes) -> None:
Gilles Peskine3f5022e2024-09-16 20:23:40 +0200244 """Check that all tests passing in the driver component are also
245 passing in the corresponding reference component.
246 Skip:
247 - full test suites provided in ignored_suites list
248 - only some specific test inside a test suite, for which the corresponding
249 output string is provided
250 """
Gilles Peskineb4daeb42024-09-16 20:32:59 +0200251 ref_outcomes = outcomes.get("component_" + self.REFERENCE)
252 driver_outcomes = outcomes.get("component_" + self.DRIVER)
Gilles Peskine3f5022e2024-09-16 20:23:40 +0200253
254 if ref_outcomes is None or driver_outcomes is None:
255 results.error("required components are missing: bad outcome file?")
256 return
257
258 if not ref_outcomes.successes:
259 results.error("no passing test in reference component: bad outcome file?")
260 return
261
262 for suite_case in ref_outcomes.successes:
263 # suite_case is like "test_suite_foo.bar;Description of test case"
264 (full_test_suite, test_string) = suite_case.split(';')
265 test_suite = full_test_suite.split('.')[0] # retrieve main part of test suite name
266
267 # Immediately skip fully-ignored test suites
Gilles Peskineb4daeb42024-09-16 20:32:59 +0200268 if test_suite in self.ignored_suites or \
269 full_test_suite in self.ignored_suites:
Gilles Peskine3f5022e2024-09-16 20:23:40 +0200270 continue
271
272 # For ignored test cases inside test suites, just remember and:
273 # don't issue an error if they're skipped with drivers,
274 # but issue an error if they're not (means we have a bad entry).
Gilles Peskine02976052024-09-16 20:44:15 +0200275 ignored = self.is_test_case_ignored(full_test_suite, test_string)
Gilles Peskine3f5022e2024-09-16 20:23:40 +0200276
277 if not ignored and not suite_case in driver_outcomes.successes:
278 results.error("SKIP/FAIL -> PASS: {}", suite_case)
279 if ignored and suite_case in driver_outcomes.successes:
280 results.error("uselessly ignored: {}", suite_case)
281
Gilles Peskine82b16722024-09-16 19:57:10 +0200282
Gilles Peskine9df375b2024-09-16 20:14:26 +0200283# The names that we give to classes derived from DriverVSReference do not
284# follow the usual naming convention, because it's more readable to use
285# underscores and parts of the configuration names. Also, these classes
286# are just there to specify some data, so they don't need repetitive
287# documentation.
288#pylint: disable=invalid-name,missing-class-docstring
289
290class DriverVSReference_hash(DriverVSReference):
291 REFERENCE = 'test_psa_crypto_config_reference_hash_use_psa'
292 DRIVER = 'test_psa_crypto_config_accel_hash_use_psa'
293 IGNORED_SUITES = [
294 'shax', 'mdx', # the software implementations that are being excluded
295 'md.psa', # purposefully depends on whether drivers are present
296 'psa_crypto_low_hash.generated', # testing the builtins
297 ]
298 IGNORED_TESTS = {
299 'test_suite_config': [
300 re.compile(r'.*\bMBEDTLS_(MD5|RIPEMD160|SHA[0-9]+)_.*'),
301 ],
302 'test_suite_platform': [
303 # Incompatible with sanitizers (e.g. ASan). If the driver
304 # component uses a sanitizer but the reference component
305 # doesn't, we have a PASS vs SKIP mismatch.
306 'Check mbedtls_calloc overallocation',
307 ],
308 }
309
310class DriverVSReference_hmac(DriverVSReference):
311 REFERENCE = 'test_psa_crypto_config_reference_hmac'
312 DRIVER = 'test_psa_crypto_config_accel_hmac'
313 IGNORED_SUITES = [
314 # These suites require legacy hash support, which is disabled
315 # in the accelerated component.
316 'shax', 'mdx',
317 # This suite tests builtins directly, but these are missing
318 # in the accelerated case.
319 'psa_crypto_low_hash.generated',
320 ]
321 IGNORED_TESTS = {
322 'test_suite_config': [
323 re.compile(r'.*\bMBEDTLS_(MD5|RIPEMD160|SHA[0-9]+)_.*'),
324 re.compile(r'.*\bMBEDTLS_MD_C\b')
325 ],
326 'test_suite_md': [
327 # Builtin HMAC is not supported in the accelerate component.
328 re.compile('.*HMAC.*'),
329 # Following tests make use of functions which are not available
330 # when MD_C is disabled, as it happens in the accelerated
331 # test component.
332 re.compile('generic .* Hash file .*'),
333 'MD list',
334 ],
335 'test_suite_md.psa': [
336 # "legacy only" tests require hash algorithms to be NOT
337 # accelerated, but this of course false for the accelerated
338 # test component.
339 re.compile('PSA dispatch .* legacy only'),
340 ],
341 'test_suite_platform': [
342 # Incompatible with sanitizers (e.g. ASan). If the driver
343 # component uses a sanitizer but the reference component
344 # doesn't, we have a PASS vs SKIP mismatch.
345 'Check mbedtls_calloc overallocation',
346 ],
347 }
348
349class DriverVSReference_cipher_aead_cmac(DriverVSReference):
350 REFERENCE = 'test_psa_crypto_config_reference_cipher_aead_cmac'
351 DRIVER = 'test_psa_crypto_config_accel_cipher_aead_cmac'
352 # Modules replaced by drivers.
353 IGNORED_SUITES = [
354 # low-level (block/stream) cipher modules
355 'aes', 'aria', 'camellia', 'des', 'chacha20',
356 # AEAD modes and CMAC
357 'ccm', 'chachapoly', 'cmac', 'gcm',
358 # The Cipher abstraction layer
359 'cipher',
360 ]
361 IGNORED_TESTS = {
362 'test_suite_config': [
363 re.compile(r'.*\bMBEDTLS_(AES|ARIA|CAMELLIA|CHACHA20|DES)_.*'),
364 re.compile(r'.*\bMBEDTLS_(CCM|CHACHAPOLY|CMAC|GCM)_.*'),
365 re.compile(r'.*\bMBEDTLS_AES(\w+)_C\b.*'),
366 re.compile(r'.*\bMBEDTLS_CIPHER_.*'),
367 ],
368 # PEM decryption is not supported so far.
369 # The rest of PEM (write, unencrypted read) works though.
370 'test_suite_pem': [
371 re.compile(r'PEM read .*(AES|DES|\bencrypt).*'),
372 ],
373 'test_suite_platform': [
374 # Incompatible with sanitizers (e.g. ASan). If the driver
375 # component uses a sanitizer but the reference component
376 # doesn't, we have a PASS vs SKIP mismatch.
377 'Check mbedtls_calloc overallocation',
378 ],
379 # Following tests depend on AES_C/DES_C but are not about
380 # them really, just need to know some error code is there.
381 'test_suite_error': [
382 'Low and high error',
383 'Single low error'
384 ],
385 # Similar to test_suite_error above.
386 'test_suite_version': [
387 'Check for MBEDTLS_AES_C when already present',
388 ],
389 # The en/decryption part of PKCS#12 is not supported so far.
390 # The rest of PKCS#12 (key derivation) works though.
391 'test_suite_pkcs12': [
392 re.compile(r'PBE Encrypt, .*'),
393 re.compile(r'PBE Decrypt, .*'),
394 ],
395 # The en/decryption part of PKCS#5 is not supported so far.
396 # The rest of PKCS#5 (PBKDF2) works though.
397 'test_suite_pkcs5': [
398 re.compile(r'PBES2 Encrypt, .*'),
399 re.compile(r'PBES2 Decrypt .*'),
400 ],
401 # Encrypted keys are not supported so far.
402 # pylint: disable=line-too-long
403 'test_suite_pkparse': [
404 'Key ASN1 (Encrypted key PKCS12, trailing garbage data)',
405 'Key ASN1 (Encrypted key PKCS5, trailing garbage data)',
406 re.compile(r'Parse (RSA|EC) Key .*\(.* ([Ee]ncrypted|password).*\)'),
407 ],
408 # Encrypted keys are not supported so far.
409 'ssl-opt': [
410 'TLS: password protected server key',
411 'TLS: password protected client key',
412 'TLS: password protected server key, two certificates',
413 ],
414 }
415
416class DriverVSReference_ecp_light_only(DriverVSReference):
417 REFERENCE = 'test_psa_crypto_config_reference_ecc_ecp_light_only'
418 DRIVER = 'test_psa_crypto_config_accel_ecc_ecp_light_only'
419 IGNORED_SUITES = [
420 # Modules replaced by drivers
421 'ecdsa', 'ecdh', 'ecjpake',
422 ]
423 IGNORED_TESTS = {
424 'test_suite_config': [
425 re.compile(r'.*\bMBEDTLS_(ECDH|ECDSA|ECJPAKE|ECP)_.*'),
426 ],
427 'test_suite_platform': [
428 # Incompatible with sanitizers (e.g. ASan). If the driver
429 # component uses a sanitizer but the reference component
430 # doesn't, we have a PASS vs SKIP mismatch.
431 'Check mbedtls_calloc overallocation',
432 ],
433 # This test wants a legacy function that takes f_rng, p_rng
434 # arguments, and uses legacy ECDSA for that. The test is
435 # really about the wrapper around the PSA RNG, not ECDSA.
436 'test_suite_random': [
437 'PSA classic wrapper: ECDSA signature (SECP256R1)',
438 ],
439 # In the accelerated test ECP_C is not set (only ECP_LIGHT is)
440 # so we must ignore disparities in the tests for which ECP_C
441 # is required.
442 'test_suite_ecp': [
443 re.compile(r'ECP check public-private .*'),
444 re.compile(r'ECP calculate public: .*'),
445 re.compile(r'ECP gen keypair .*'),
446 re.compile(r'ECP point muladd .*'),
447 re.compile(r'ECP point multiplication .*'),
448 re.compile(r'ECP test vectors .*'),
449 ],
450 'test_suite_ssl': [
451 # This deprecated function is only present when ECP_C is On.
452 'Test configuration of groups for DHE through mbedtls_ssl_conf_curves()',
453 ],
454 }
455
456class DriverVSReference_no_ecp_at_all(DriverVSReference):
457 REFERENCE = 'test_psa_crypto_config_reference_ecc_no_ecp_at_all'
458 DRIVER = 'test_psa_crypto_config_accel_ecc_no_ecp_at_all'
459 IGNORED_SUITES = [
460 # Modules replaced by drivers
461 'ecp', 'ecdsa', 'ecdh', 'ecjpake',
462 ]
463 IGNORED_TESTS = {
464 'test_suite_config': [
465 re.compile(r'.*\bMBEDTLS_(ECDH|ECDSA|ECJPAKE|ECP)_.*'),
466 re.compile(r'.*\bMBEDTLS_PK_PARSE_EC_COMPRESSED\b.*'),
467 ],
468 'test_suite_platform': [
469 # Incompatible with sanitizers (e.g. ASan). If the driver
470 # component uses a sanitizer but the reference component
471 # doesn't, we have a PASS vs SKIP mismatch.
472 'Check mbedtls_calloc overallocation',
473 ],
474 # See ecp_light_only
475 'test_suite_random': [
476 'PSA classic wrapper: ECDSA signature (SECP256R1)',
477 ],
478 'test_suite_pkparse': [
479 # When PK_PARSE_C and ECP_C are defined then PK_PARSE_EC_COMPRESSED
480 # is automatically enabled in build_info.h (backward compatibility)
481 # even if it is disabled in config_psa_crypto_no_ecp_at_all(). As a
482 # consequence compressed points are supported in the reference
483 # component but not in the accelerated one, so they should be skipped
484 # while checking driver's coverage.
485 re.compile(r'Parse EC Key .*compressed\)'),
486 re.compile(r'Parse Public EC Key .*compressed\)'),
487 ],
488 # See ecp_light_only
489 'test_suite_ssl': [
490 'Test configuration of groups for DHE through mbedtls_ssl_conf_curves()',
491 ],
492 }
493
494class DriverVSReference_ecc_no_bignum(DriverVSReference):
495 REFERENCE = 'test_psa_crypto_config_reference_ecc_no_bignum'
496 DRIVER = 'test_psa_crypto_config_accel_ecc_no_bignum'
497 IGNORED_SUITES = [
498 # Modules replaced by drivers
499 'ecp', 'ecdsa', 'ecdh', 'ecjpake',
500 'bignum_core', 'bignum_random', 'bignum_mod', 'bignum_mod_raw',
501 'bignum.generated', 'bignum.misc',
502 ]
503 IGNORED_TESTS = {
504 'test_suite_config': [
505 re.compile(r'.*\bMBEDTLS_BIGNUM_C\b.*'),
506 re.compile(r'.*\bMBEDTLS_(ECDH|ECDSA|ECJPAKE|ECP)_.*'),
507 re.compile(r'.*\bMBEDTLS_PK_PARSE_EC_COMPRESSED\b.*'),
508 ],
509 'test_suite_platform': [
510 # Incompatible with sanitizers (e.g. ASan). If the driver
511 # component uses a sanitizer but the reference component
512 # doesn't, we have a PASS vs SKIP mismatch.
513 'Check mbedtls_calloc overallocation',
514 ],
515 # See ecp_light_only
516 'test_suite_random': [
517 'PSA classic wrapper: ECDSA signature (SECP256R1)',
518 ],
519 # See no_ecp_at_all
520 'test_suite_pkparse': [
521 re.compile(r'Parse EC Key .*compressed\)'),
522 re.compile(r'Parse Public EC Key .*compressed\)'),
523 ],
524 'test_suite_asn1parse': [
525 'INTEGER too large for mpi',
526 ],
527 'test_suite_asn1write': [
528 re.compile(r'ASN.1 Write mpi.*'),
529 ],
530 'test_suite_debug': [
531 re.compile(r'Debug print mbedtls_mpi.*'),
532 ],
533 # See ecp_light_only
534 'test_suite_ssl': [
535 'Test configuration of groups for DHE through mbedtls_ssl_conf_curves()',
536 ],
537 }
538
539class DriverVSReference_ecc_ffdh_no_bignum(DriverVSReference):
540 REFERENCE = 'test_psa_crypto_config_reference_ecc_ffdh_no_bignum'
541 DRIVER = 'test_psa_crypto_config_accel_ecc_ffdh_no_bignum'
542 IGNORED_SUITES = [
543 # Modules replaced by drivers
544 'ecp', 'ecdsa', 'ecdh', 'ecjpake', 'dhm',
545 'bignum_core', 'bignum_random', 'bignum_mod', 'bignum_mod_raw',
546 'bignum.generated', 'bignum.misc',
547 ]
548 IGNORED_TESTS = {
549 'ssl-opt': [
550 # DHE support in TLS 1.2 requires built-in MBEDTLS_DHM_C
551 # (because it needs custom groups, which PSA does not
552 # provide), even with MBEDTLS_USE_PSA_CRYPTO.
553 re.compile(r'PSK callback:.*\bdhe-psk\b.*'),
554 ],
555 'test_suite_config': [
556 re.compile(r'.*\bMBEDTLS_BIGNUM_C\b.*'),
557 re.compile(r'.*\bMBEDTLS_DHM_C\b.*'),
558 re.compile(r'.*\bMBEDTLS_(ECDH|ECDSA|ECJPAKE|ECP)_.*'),
559 re.compile(r'.*\bMBEDTLS_KEY_EXCHANGE_DHE_PSK_ENABLED\b.*'),
560 re.compile(r'.*\bMBEDTLS_PK_PARSE_EC_COMPRESSED\b.*'),
561 ],
562 'test_suite_platform': [
563 # Incompatible with sanitizers (e.g. ASan). If the driver
564 # component uses a sanitizer but the reference component
565 # doesn't, we have a PASS vs SKIP mismatch.
566 'Check mbedtls_calloc overallocation',
567 ],
568 # See ecp_light_only
569 'test_suite_random': [
570 'PSA classic wrapper: ECDSA signature (SECP256R1)',
571 ],
572 # See no_ecp_at_all
573 'test_suite_pkparse': [
574 re.compile(r'Parse EC Key .*compressed\)'),
575 re.compile(r'Parse Public EC Key .*compressed\)'),
576 ],
577 'test_suite_asn1parse': [
578 'INTEGER too large for mpi',
579 ],
580 'test_suite_asn1write': [
581 re.compile(r'ASN.1 Write mpi.*'),
582 ],
583 'test_suite_debug': [
584 re.compile(r'Debug print mbedtls_mpi.*'),
585 ],
586 # See ecp_light_only
587 'test_suite_ssl': [
588 'Test configuration of groups for DHE through mbedtls_ssl_conf_curves()',
589 ],
590 }
591
592class DriverVSReference_ffdh_alg(DriverVSReference):
593 REFERENCE = 'test_psa_crypto_config_reference_ffdh'
594 DRIVER = 'test_psa_crypto_config_accel_ffdh'
595 IGNORED_SUITES = ['dhm']
596 IGNORED_TESTS = {
597 'test_suite_config': [
598 re.compile(r'.*\bMBEDTLS_DHM_C\b.*'),
599 ],
600 'test_suite_platform': [
601 # Incompatible with sanitizers (e.g. ASan). If the driver
602 # component uses a sanitizer but the reference component
603 # doesn't, we have a PASS vs SKIP mismatch.
604 'Check mbedtls_calloc overallocation',
605 ],
606 }
607
608class DriverVSReference_tfm_config(DriverVSReference):
609 REFERENCE = 'test_tfm_config_no_p256m'
610 DRIVER = 'test_tfm_config_p256m_driver_accel_ec'
611 IGNORED_SUITES = [
612 # Modules replaced by drivers
613 'asn1parse', 'asn1write',
614 'ecp', 'ecdsa', 'ecdh', 'ecjpake',
615 'bignum_core', 'bignum_random', 'bignum_mod', 'bignum_mod_raw',
616 'bignum.generated', 'bignum.misc',
617 ]
618 IGNORED_TESTS = {
619 'test_suite_config': [
620 re.compile(r'.*\bMBEDTLS_BIGNUM_C\b.*'),
621 re.compile(r'.*\bMBEDTLS_(ASN1\w+)_C\b.*'),
622 re.compile(r'.*\bMBEDTLS_(ECDH|ECDSA|ECP)_.*'),
623 re.compile(r'.*\bMBEDTLS_PSA_P256M_DRIVER_ENABLED\b.*')
624 ],
625 'test_suite_config.crypto_combinations': [
626 'Config: ECC: Weierstrass curves only',
627 ],
628 'test_suite_platform': [
629 # Incompatible with sanitizers (e.g. ASan). If the driver
630 # component uses a sanitizer but the reference component
631 # doesn't, we have a PASS vs SKIP mismatch.
632 'Check mbedtls_calloc overallocation',
633 ],
634 # See ecp_light_only
635 'test_suite_random': [
636 'PSA classic wrapper: ECDSA signature (SECP256R1)',
637 ],
638 }
639
640class DriverVSReference_rsa(DriverVSReference):
641 REFERENCE = 'test_psa_crypto_config_reference_rsa_crypto'
642 DRIVER = 'test_psa_crypto_config_accel_rsa_crypto'
643 IGNORED_SUITES = [
644 # Modules replaced by drivers.
645 'rsa', 'pkcs1_v15', 'pkcs1_v21',
646 # We temporarily don't care about PK stuff.
647 'pk', 'pkwrite', 'pkparse'
648 ]
649 IGNORED_TESTS = {
650 'test_suite_config': [
651 re.compile(r'.*\bMBEDTLS_(PKCS1|RSA)_.*'),
652 re.compile(r'.*\bMBEDTLS_GENPRIME\b.*')
653 ],
654 'test_suite_platform': [
655 # Incompatible with sanitizers (e.g. ASan). If the driver
656 # component uses a sanitizer but the reference component
657 # doesn't, we have a PASS vs SKIP mismatch.
658 'Check mbedtls_calloc overallocation',
659 ],
660 # Following tests depend on RSA_C but are not about
661 # them really, just need to know some error code is there.
662 'test_suite_error': [
663 'Low and high error',
664 'Single high error'
665 ],
666 # Constant time operations only used for PKCS1_V15
667 'test_suite_constant_time': [
668 re.compile(r'mbedtls_ct_zeroize_if .*'),
669 re.compile(r'mbedtls_ct_memmove_left .*')
670 ],
671 'test_suite_psa_crypto': [
672 # We don't support generate_key_custom entry points
673 # in drivers yet.
674 re.compile(r'PSA generate key custom: RSA, e=.*'),
675 re.compile(r'PSA generate key ext: RSA, e=.*'),
676 ],
677 }
678
679class DriverVSReference_block_cipher_dispatch(DriverVSReference):
680 REFERENCE = 'test_full_block_cipher_legacy_dispatch'
681 DRIVER = 'test_full_block_cipher_psa_dispatch'
682 IGNORED_SUITES = [
683 # Skipped in the accelerated component
684 'aes', 'aria', 'camellia',
685 # These require AES_C, ARIA_C or CAMELLIA_C to be enabled in
686 # order for the cipher module (actually cipher_wrapper) to work
687 # properly. However these symbols are disabled in the accelerated
688 # component so we ignore them.
689 'cipher.ccm', 'cipher.gcm', 'cipher.aes', 'cipher.aria',
690 'cipher.camellia',
691 ]
692 IGNORED_TESTS = {
693 'test_suite_config': [
694 re.compile(r'.*\bMBEDTLS_(AES|ARIA|CAMELLIA)_.*'),
695 re.compile(r'.*\bMBEDTLS_AES(\w+)_C\b.*'),
696 ],
697 'test_suite_cmac': [
698 # Following tests require AES_C/ARIA_C/CAMELLIA_C to be enabled,
699 # but these are not available in the accelerated component.
700 'CMAC null arguments',
701 re.compile('CMAC.* (AES|ARIA|Camellia).*'),
702 ],
703 'test_suite_cipher.padding': [
704 # Following tests require AES_C/CAMELLIA_C to be enabled,
705 # but these are not available in the accelerated component.
706 re.compile('Set( non-existent)? padding with (AES|CAMELLIA).*'),
707 ],
708 'test_suite_pkcs5': [
709 # The AES part of PKCS#5 PBES2 is not yet supported.
710 # The rest of PKCS#5 (PBKDF2) works, though.
711 re.compile(r'PBES2 .* AES-.*')
712 ],
713 'test_suite_pkparse': [
714 # PEM (called by pkparse) requires AES_C in order to decrypt
715 # the key, but this is not available in the accelerated
716 # component.
717 re.compile('Parse RSA Key.*(password|AES-).*'),
718 ],
719 'test_suite_pem': [
720 # Following tests require AES_C, but this is diabled in the
721 # accelerated component.
722 re.compile('PEM read .*AES.*'),
723 'PEM read (unknown encryption algorithm)',
724 ],
725 'test_suite_error': [
726 # Following tests depend on AES_C but are not about them
727 # really, just need to know some error code is there.
728 'Single low error',
729 'Low and high error',
730 ],
731 'test_suite_version': [
732 # Similar to test_suite_error above.
733 'Check for MBEDTLS_AES_C when already present',
734 ],
735 'test_suite_platform': [
736 # Incompatible with sanitizers (e.g. ASan). If the driver
737 # component uses a sanitizer but the reference component
738 # doesn't, we have a PASS vs SKIP mismatch.
739 'Check mbedtls_calloc overallocation',
740 ],
741 }
742
743#pylint: enable=invalid-name,missing-class-docstring
744
745
Gilles Peskine82b16722024-09-16 19:57:10 +0200746
Przemek Stekiel6856f4c2022-11-09 10:50:29 +0100747# List of tasks with a function that can handle this task and additional arguments if required
Valerio Settidfd7ca62023-10-09 16:30:11 +0200748KNOWN_TASKS = {
Gilles Peskinef646dbf2024-09-16 19:15:29 +0200749 'analyze_coverage': CoverageTask,
Gilles Peskine9df375b2024-09-16 20:14:26 +0200750 'analyze_driver_vs_reference_hash': DriverVSReference_hash,
751 'analyze_driver_vs_reference_hmac': DriverVSReference_hmac,
752 'analyze_driver_vs_reference_cipher_aead_cmac': DriverVSReference_cipher_aead_cmac,
753 'analyze_driver_vs_reference_ecp_light_only': DriverVSReference_ecp_light_only,
754 'analyze_driver_vs_reference_no_ecp_at_all': DriverVSReference_no_ecp_at_all,
755 'analyze_driver_vs_reference_ecc_no_bignum': DriverVSReference_ecc_no_bignum,
756 'analyze_driver_vs_reference_ecc_ffdh_no_bignum': DriverVSReference_ecc_ffdh_no_bignum,
757 'analyze_driver_vs_reference_ffdh_alg': DriverVSReference_ffdh_alg,
758 'analyze_driver_vs_reference_tfm_config': DriverVSReference_tfm_config,
759 'analyze_driver_vs_reference_rsa': DriverVSReference_rsa,
760 'analyze_block_cipher_dispatch': DriverVSReference_block_cipher_dispatch,
Przemek Stekiel4d13c832022-10-26 16:11:26 +0200761}
Przemek Stekiel4d13c832022-10-26 16:11:26 +0200762
Gilles Peskine9df375b2024-09-16 20:14:26 +0200763
Gilles Peskine15c2cbf2020-06-25 18:36:28 +0200764def main():
Valerio Settif075e472023-10-17 11:03:16 +0200765 main_results = Results()
Valerio Settiaaef0bc2023-10-10 09:42:13 +0200766
Gilles Peskine15c2cbf2020-06-25 18:36:28 +0200767 try:
768 parser = argparse.ArgumentParser(description=__doc__)
Przemek Stekiel58bbc232022-10-24 08:10:10 +0200769 parser.add_argument('outcomes', metavar='OUTCOMES.CSV',
Gilles Peskine15c2cbf2020-06-25 18:36:28 +0200770 help='Outcome file to analyze')
Valerio Settidfd7ca62023-10-09 16:30:11 +0200771 parser.add_argument('specified_tasks', default='all', nargs='?',
Przemek Stekiel992de3c2022-11-09 13:54:49 +0100772 help='Analysis to be done. By default, run all tasks. '
773 'With one or more TASK, run only those. '
774 'TASK can be the name of a single task or '
Przemek Stekiel85c54ea2022-11-17 11:50:23 +0100775 'comma/space-separated list of tasks. ')
Przemek Stekiel992de3c2022-11-09 13:54:49 +0100776 parser.add_argument('--list', action='store_true',
777 help='List all available tasks and exit.')
Tomás Gonzálezb401e112023-08-11 15:22:04 +0100778 parser.add_argument('--require-full-coverage', action='store_true',
779 dest='full_coverage', help="Require all available "
780 "test cases to be executed and issue an error "
781 "otherwise. This flag is ignored if 'task' is "
782 "neither 'all' nor 'analyze_coverage'")
Gilles Peskine15c2cbf2020-06-25 18:36:28 +0200783 options = parser.parse_args()
Przemek Stekiel4e955902022-10-21 13:42:08 +0200784
Przemek Stekiel992de3c2022-11-09 13:54:49 +0100785 if options.list:
Valerio Settidfd7ca62023-10-09 16:30:11 +0200786 for task in KNOWN_TASKS:
Valerio Setti5329ff02023-10-17 09:44:36 +0200787 print(task)
Przemek Stekiel992de3c2022-11-09 13:54:49 +0100788 sys.exit(0)
789
Valerio Settidfd7ca62023-10-09 16:30:11 +0200790 if options.specified_tasks == 'all':
791 tasks_list = KNOWN_TASKS.keys()
Przemek Stekiel992de3c2022-11-09 13:54:49 +0100792 else:
Valerio Settidfd7ca62023-10-09 16:30:11 +0200793 tasks_list = re.split(r'[, ]+', options.specified_tasks)
Valerio Settidfd7ca62023-10-09 16:30:11 +0200794 for task in tasks_list:
795 if task not in KNOWN_TASKS:
Manuel Pégourié-Gonnard62d61312023-10-20 10:51:57 +0200796 sys.stderr.write('invalid task: {}\n'.format(task))
Valerio Settifb2750e2023-10-17 10:11:45 +0200797 sys.exit(2)
Przemek Stekiel992de3c2022-11-09 13:54:49 +0100798
Pengyu Lvdd1d6a72023-11-27 17:57:31 +0800799 # If the outcome file exists, parse it once and share the result
800 # among tasks to improve performance.
Pengyu Lv20e3ca32023-11-28 15:30:03 +0800801 # Otherwise, it will be generated by execute_reference_driver_tests.
802 if not os.path.exists(options.outcomes):
803 if len(tasks_list) > 1:
804 sys.stderr.write("mutiple tasks found, please provide a valid outcomes file.\n")
805 sys.exit(2)
806
807 task_name = tasks_list[0]
808 task = KNOWN_TASKS[task_name]
Gilles Peskine82b16722024-09-16 19:57:10 +0200809 if not issubclass(task, DriverVSReference):
Pengyu Lv20e3ca32023-11-28 15:30:03 +0800810 sys.stderr.write("please provide valid outcomes file for {}.\n".format(task_name))
811 sys.exit(2)
Pengyu Lv20e3ca32023-11-28 15:30:03 +0800812 execute_reference_driver_tests(main_results,
Gilles Peskine82b16722024-09-16 19:57:10 +0200813 task.REFERENCE,
814 task.DRIVER,
Pengyu Lv20e3ca32023-11-28 15:30:03 +0800815 options.outcomes)
816
817 outcomes = read_outcome_file(options.outcomes)
Pengyu Lva6cf5d62023-11-22 11:35:21 +0800818
Gilles Peskine19ef1ae2024-09-16 19:12:09 +0200819 for task_name in tasks_list:
820 task_constructor = KNOWN_TASKS[task_name]
Gilles Peskine0f31f762024-09-16 20:15:58 +0200821 task = task_constructor(options)
822 main_results.new_section(task.section_name())
823 task.run(main_results, outcomes)
Tomás Gonzálezb401e112023-08-11 15:22:04 +0100824
Valerio Settif6f64cf2023-10-17 12:28:26 +0200825 main_results.info("Overall results: {} warnings and {} errors",
826 main_results.warning_count, main_results.error_count)
Przemek Stekiel4e955902022-10-21 13:42:08 +0200827
Valerio Setti8d178be2023-10-17 12:23:55 +0200828 sys.exit(0 if (main_results.error_count == 0) else 1)
Valerio Settiaaef0bc2023-10-10 09:42:13 +0200829
Gilles Peskine15c2cbf2020-06-25 18:36:28 +0200830 except Exception: # pylint: disable=broad-except
831 # Print the backtrace and exit explicitly with our chosen status.
832 traceback.print_exc()
833 sys.exit(120)
834
835if __name__ == '__main__':
836 main()