blob: 188b68d1d531e17054a65bc7b3c026eb96603034 [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 Peskine8d3c70a2020-06-25 18:37:43 +020017import check_test_cases
18
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 Peskine54cfe772024-09-16 20:56:43 +0200170 IGNORED_TESTS = {
171 'test_suite_psa_crypto_metadata': [
172 # Algorithm not supported yet
173 'Asymmetric signature: pure EdDSA',
174 # Algorithm not supported yet
175 'Cipher: XTS',
176 ],
177 }
Gilles Peskinef646dbf2024-09-16 19:15:29 +0200178
179 def __init__(self, options) -> None:
180 super().__init__(options)
181 self.full_coverage = options.full_coverage #type: bool
182
183 @staticmethod
184 def section_name() -> str:
185 return "Analyze coverage"
186
Gilles Peskineb4daeb42024-09-16 20:32:59 +0200187 def run(self, results: Results, outcomes: Outcomes) -> None:
Gilles Peskine3f5022e2024-09-16 20:23:40 +0200188 """Check that all available test cases are executed at least once."""
189 # Make sure that the generated data files are present (and up-to-date).
190 # This allows analyze_outcomes.py to run correctly on a fresh Git
191 # checkout.
192 cp = subprocess.run(['make', 'generated_files'],
193 cwd='tests',
194 stdout=subprocess.PIPE, stderr=subprocess.STDOUT,
195 check=False)
196 if cp.returncode != 0:
197 sys.stderr.write(cp.stdout.decode('utf-8'))
198 results.error("Failed \"make generated_files\" in tests. "
199 "Coverage analysis may be incorrect.")
200 available = check_test_cases.collect_available_test_cases()
201 for suite_case in available:
202 hit = any(suite_case in comp_outcomes.successes or
203 suite_case in comp_outcomes.failures
204 for comp_outcomes in outcomes.values())
Gilles Peskine54cfe772024-09-16 20:56:43 +0200205 (test_suite, test_description) = suite_case.split(';')
206 ignored = self.is_test_case_ignored(test_suite, test_description)
Gilles Peskine3f5022e2024-09-16 20:23:40 +0200207
Gilles Peskine54cfe772024-09-16 20:56:43 +0200208 if not hit and not ignored:
Gilles Peskineb4daeb42024-09-16 20:32:59 +0200209 if self.full_coverage:
Gilles Peskine3f5022e2024-09-16 20:23:40 +0200210 results.error('Test case not executed: {}', suite_case)
211 else:
212 results.warning('Test case not executed: {}', suite_case)
Gilles Peskine54cfe772024-09-16 20:56:43 +0200213 elif hit and ignored:
Gilles Peskine0930b332024-09-26 19:54:38 +0200214 # If a test case is no longer always skipped, we should remove
215 # it from the ignore list.
Gilles Peskineb4daeb42024-09-16 20:32:59 +0200216 if self.full_coverage:
Gilles Peskine0930b332024-09-26 19:54:38 +0200217 results.error('Test case was executed but marked as ignored for coverage: {}',
218 suite_case)
Gilles Peskine3f5022e2024-09-16 20:23:40 +0200219 else:
Gilles Peskine0930b332024-09-26 19:54:38 +0200220 results.warning('Test case was executed but marked as ignored for coverage: {}',
221 suite_case)
Gilles Peskine3f5022e2024-09-16 20:23:40 +0200222
Gilles Peskinef646dbf2024-09-16 19:15:29 +0200223
Gilles Peskine82b16722024-09-16 19:57:10 +0200224class DriverVSReference(Task):
225 """Compare outcomes from testing with and without a driver.
226
227 There are 2 options to use analyze_driver_vs_reference_xxx locally:
228 1. Run tests and then analysis:
229 - tests/scripts/all.sh --outcome-file "$PWD/out.csv" <component_ref> <component_driver>
230 - tests/scripts/analyze_outcomes.py out.csv analyze_driver_vs_reference_xxx
231 2. Let this script run both automatically:
232 - tests/scripts/analyze_outcomes.py out.csv analyze_driver_vs_reference_xxx
233 """
234
235 # Override the following in child classes.
236 # Configuration name (all.sh component) used as the reference.
237 REFERENCE = ''
238 # Configuration name (all.sh component) used as the driver.
239 DRIVER = ''
240 # Ignored test suites (without the test_suite_ prefix).
241 IGNORED_SUITES = [] #type: typing.List[str]
Gilles Peskine82b16722024-09-16 19:57:10 +0200242
Gilles Peskineb4daeb42024-09-16 20:32:59 +0200243 def __init__(self, options) -> None:
244 super().__init__(options)
245 self.ignored_suites = frozenset('test_suite_' + x
246 for x in self.IGNORED_SUITES)
247
Gilles Peskine82b16722024-09-16 19:57:10 +0200248 def section_name(self) -> str:
249 return f"Analyze driver {self.DRIVER} vs reference {self.REFERENCE}"
250
Gilles Peskineb4daeb42024-09-16 20:32:59 +0200251 def run(self, results: Results, outcomes: Outcomes) -> None:
Gilles Peskine3f5022e2024-09-16 20:23:40 +0200252 """Check that all tests passing in the driver component are also
253 passing in the corresponding reference component.
254 Skip:
255 - full test suites provided in ignored_suites list
256 - only some specific test inside a test suite, for which the corresponding
257 output string is provided
258 """
Gilles Peskineb4daeb42024-09-16 20:32:59 +0200259 ref_outcomes = outcomes.get("component_" + self.REFERENCE)
260 driver_outcomes = outcomes.get("component_" + self.DRIVER)
Gilles Peskine3f5022e2024-09-16 20:23:40 +0200261
262 if ref_outcomes is None or driver_outcomes is None:
263 results.error("required components are missing: bad outcome file?")
264 return
265
266 if not ref_outcomes.successes:
267 results.error("no passing test in reference component: bad outcome file?")
268 return
269
270 for suite_case in ref_outcomes.successes:
271 # suite_case is like "test_suite_foo.bar;Description of test case"
272 (full_test_suite, test_string) = suite_case.split(';')
273 test_suite = full_test_suite.split('.')[0] # retrieve main part of test suite name
274
275 # Immediately skip fully-ignored test suites
Gilles Peskineb4daeb42024-09-16 20:32:59 +0200276 if test_suite in self.ignored_suites or \
277 full_test_suite in self.ignored_suites:
Gilles Peskine3f5022e2024-09-16 20:23:40 +0200278 continue
279
280 # For ignored test cases inside test suites, just remember and:
281 # don't issue an error if they're skipped with drivers,
282 # but issue an error if they're not (means we have a bad entry).
Gilles Peskine02976052024-09-16 20:44:15 +0200283 ignored = self.is_test_case_ignored(full_test_suite, test_string)
Gilles Peskine3f5022e2024-09-16 20:23:40 +0200284
285 if not ignored and not suite_case in driver_outcomes.successes:
286 results.error("SKIP/FAIL -> PASS: {}", suite_case)
287 if ignored and suite_case in driver_outcomes.successes:
288 results.error("uselessly ignored: {}", suite_case)
289
Gilles Peskine82b16722024-09-16 19:57:10 +0200290
Gilles Peskine9df375b2024-09-16 20:14:26 +0200291# The names that we give to classes derived from DriverVSReference do not
292# follow the usual naming convention, because it's more readable to use
293# underscores and parts of the configuration names. Also, these classes
294# are just there to specify some data, so they don't need repetitive
295# documentation.
296#pylint: disable=invalid-name,missing-class-docstring
297
298class DriverVSReference_hash(DriverVSReference):
299 REFERENCE = 'test_psa_crypto_config_reference_hash_use_psa'
300 DRIVER = 'test_psa_crypto_config_accel_hash_use_psa'
301 IGNORED_SUITES = [
302 'shax', 'mdx', # the software implementations that are being excluded
303 'md.psa', # purposefully depends on whether drivers are present
304 'psa_crypto_low_hash.generated', # testing the builtins
305 ]
306 IGNORED_TESTS = {
307 'test_suite_config': [
308 re.compile(r'.*\bMBEDTLS_(MD5|RIPEMD160|SHA[0-9]+)_.*'),
309 ],
310 'test_suite_platform': [
311 # Incompatible with sanitizers (e.g. ASan). If the driver
312 # component uses a sanitizer but the reference component
313 # doesn't, we have a PASS vs SKIP mismatch.
314 'Check mbedtls_calloc overallocation',
315 ],
316 }
317
318class DriverVSReference_hmac(DriverVSReference):
319 REFERENCE = 'test_psa_crypto_config_reference_hmac'
320 DRIVER = 'test_psa_crypto_config_accel_hmac'
321 IGNORED_SUITES = [
322 # These suites require legacy hash support, which is disabled
323 # in the accelerated component.
324 'shax', 'mdx',
325 # This suite tests builtins directly, but these are missing
326 # in the accelerated case.
327 'psa_crypto_low_hash.generated',
328 ]
329 IGNORED_TESTS = {
330 'test_suite_config': [
331 re.compile(r'.*\bMBEDTLS_(MD5|RIPEMD160|SHA[0-9]+)_.*'),
332 re.compile(r'.*\bMBEDTLS_MD_C\b')
333 ],
334 'test_suite_md': [
335 # Builtin HMAC is not supported in the accelerate component.
336 re.compile('.*HMAC.*'),
337 # Following tests make use of functions which are not available
338 # when MD_C is disabled, as it happens in the accelerated
339 # test component.
340 re.compile('generic .* Hash file .*'),
341 'MD list',
342 ],
343 'test_suite_md.psa': [
344 # "legacy only" tests require hash algorithms to be NOT
345 # accelerated, but this of course false for the accelerated
346 # test component.
347 re.compile('PSA dispatch .* legacy only'),
348 ],
349 'test_suite_platform': [
350 # Incompatible with sanitizers (e.g. ASan). If the driver
351 # component uses a sanitizer but the reference component
352 # doesn't, we have a PASS vs SKIP mismatch.
353 'Check mbedtls_calloc overallocation',
354 ],
355 }
356
357class DriverVSReference_cipher_aead_cmac(DriverVSReference):
358 REFERENCE = 'test_psa_crypto_config_reference_cipher_aead_cmac'
359 DRIVER = 'test_psa_crypto_config_accel_cipher_aead_cmac'
360 # Modules replaced by drivers.
361 IGNORED_SUITES = [
362 # low-level (block/stream) cipher modules
363 'aes', 'aria', 'camellia', 'des', 'chacha20',
364 # AEAD modes and CMAC
365 'ccm', 'chachapoly', 'cmac', 'gcm',
366 # The Cipher abstraction layer
367 'cipher',
368 ]
369 IGNORED_TESTS = {
370 'test_suite_config': [
371 re.compile(r'.*\bMBEDTLS_(AES|ARIA|CAMELLIA|CHACHA20|DES)_.*'),
372 re.compile(r'.*\bMBEDTLS_(CCM|CHACHAPOLY|CMAC|GCM)_.*'),
373 re.compile(r'.*\bMBEDTLS_AES(\w+)_C\b.*'),
374 re.compile(r'.*\bMBEDTLS_CIPHER_.*'),
375 ],
376 # PEM decryption is not supported so far.
377 # The rest of PEM (write, unencrypted read) works though.
378 'test_suite_pem': [
379 re.compile(r'PEM read .*(AES|DES|\bencrypt).*'),
380 ],
381 'test_suite_platform': [
382 # Incompatible with sanitizers (e.g. ASan). If the driver
383 # component uses a sanitizer but the reference component
384 # doesn't, we have a PASS vs SKIP mismatch.
385 'Check mbedtls_calloc overallocation',
386 ],
387 # Following tests depend on AES_C/DES_C but are not about
388 # them really, just need to know some error code is there.
389 'test_suite_error': [
390 'Low and high error',
391 'Single low error'
392 ],
393 # Similar to test_suite_error above.
394 'test_suite_version': [
395 'Check for MBEDTLS_AES_C when already present',
396 ],
397 # The en/decryption part of PKCS#12 is not supported so far.
398 # The rest of PKCS#12 (key derivation) works though.
399 'test_suite_pkcs12': [
400 re.compile(r'PBE Encrypt, .*'),
401 re.compile(r'PBE Decrypt, .*'),
402 ],
403 # The en/decryption part of PKCS#5 is not supported so far.
404 # The rest of PKCS#5 (PBKDF2) works though.
405 'test_suite_pkcs5': [
406 re.compile(r'PBES2 Encrypt, .*'),
407 re.compile(r'PBES2 Decrypt .*'),
408 ],
409 # Encrypted keys are not supported so far.
410 # pylint: disable=line-too-long
411 'test_suite_pkparse': [
412 'Key ASN1 (Encrypted key PKCS12, trailing garbage data)',
413 'Key ASN1 (Encrypted key PKCS5, trailing garbage data)',
414 re.compile(r'Parse (RSA|EC) Key .*\(.* ([Ee]ncrypted|password).*\)'),
415 ],
416 # Encrypted keys are not supported so far.
417 'ssl-opt': [
418 'TLS: password protected server key',
419 'TLS: password protected client key',
420 'TLS: password protected server key, two certificates',
421 ],
422 }
423
424class DriverVSReference_ecp_light_only(DriverVSReference):
425 REFERENCE = 'test_psa_crypto_config_reference_ecc_ecp_light_only'
426 DRIVER = 'test_psa_crypto_config_accel_ecc_ecp_light_only'
427 IGNORED_SUITES = [
428 # Modules replaced by drivers
429 'ecdsa', 'ecdh', 'ecjpake',
430 ]
431 IGNORED_TESTS = {
432 'test_suite_config': [
433 re.compile(r'.*\bMBEDTLS_(ECDH|ECDSA|ECJPAKE|ECP)_.*'),
434 ],
435 'test_suite_platform': [
436 # Incompatible with sanitizers (e.g. ASan). If the driver
437 # component uses a sanitizer but the reference component
438 # doesn't, we have a PASS vs SKIP mismatch.
439 'Check mbedtls_calloc overallocation',
440 ],
441 # This test wants a legacy function that takes f_rng, p_rng
442 # arguments, and uses legacy ECDSA for that. The test is
443 # really about the wrapper around the PSA RNG, not ECDSA.
444 'test_suite_random': [
445 'PSA classic wrapper: ECDSA signature (SECP256R1)',
446 ],
447 # In the accelerated test ECP_C is not set (only ECP_LIGHT is)
448 # so we must ignore disparities in the tests for which ECP_C
449 # is required.
450 'test_suite_ecp': [
451 re.compile(r'ECP check public-private .*'),
452 re.compile(r'ECP calculate public: .*'),
453 re.compile(r'ECP gen keypair .*'),
454 re.compile(r'ECP point muladd .*'),
455 re.compile(r'ECP point multiplication .*'),
456 re.compile(r'ECP test vectors .*'),
457 ],
458 'test_suite_ssl': [
459 # This deprecated function is only present when ECP_C is On.
460 'Test configuration of groups for DHE through mbedtls_ssl_conf_curves()',
461 ],
462 }
463
464class DriverVSReference_no_ecp_at_all(DriverVSReference):
465 REFERENCE = 'test_psa_crypto_config_reference_ecc_no_ecp_at_all'
466 DRIVER = 'test_psa_crypto_config_accel_ecc_no_ecp_at_all'
467 IGNORED_SUITES = [
468 # Modules replaced by drivers
469 'ecp', 'ecdsa', 'ecdh', 'ecjpake',
470 ]
471 IGNORED_TESTS = {
472 'test_suite_config': [
473 re.compile(r'.*\bMBEDTLS_(ECDH|ECDSA|ECJPAKE|ECP)_.*'),
474 re.compile(r'.*\bMBEDTLS_PK_PARSE_EC_COMPRESSED\b.*'),
475 ],
476 'test_suite_platform': [
477 # Incompatible with sanitizers (e.g. ASan). If the driver
478 # component uses a sanitizer but the reference component
479 # doesn't, we have a PASS vs SKIP mismatch.
480 'Check mbedtls_calloc overallocation',
481 ],
482 # See ecp_light_only
483 'test_suite_random': [
484 'PSA classic wrapper: ECDSA signature (SECP256R1)',
485 ],
486 'test_suite_pkparse': [
487 # When PK_PARSE_C and ECP_C are defined then PK_PARSE_EC_COMPRESSED
488 # is automatically enabled in build_info.h (backward compatibility)
489 # even if it is disabled in config_psa_crypto_no_ecp_at_all(). As a
490 # consequence compressed points are supported in the reference
491 # component but not in the accelerated one, so they should be skipped
492 # while checking driver's coverage.
493 re.compile(r'Parse EC Key .*compressed\)'),
494 re.compile(r'Parse Public EC Key .*compressed\)'),
495 ],
496 # See ecp_light_only
497 'test_suite_ssl': [
498 'Test configuration of groups for DHE through mbedtls_ssl_conf_curves()',
499 ],
500 }
501
502class DriverVSReference_ecc_no_bignum(DriverVSReference):
503 REFERENCE = 'test_psa_crypto_config_reference_ecc_no_bignum'
504 DRIVER = 'test_psa_crypto_config_accel_ecc_no_bignum'
505 IGNORED_SUITES = [
506 # Modules replaced by drivers
507 'ecp', 'ecdsa', 'ecdh', 'ecjpake',
508 'bignum_core', 'bignum_random', 'bignum_mod', 'bignum_mod_raw',
509 'bignum.generated', 'bignum.misc',
510 ]
511 IGNORED_TESTS = {
512 'test_suite_config': [
513 re.compile(r'.*\bMBEDTLS_BIGNUM_C\b.*'),
514 re.compile(r'.*\bMBEDTLS_(ECDH|ECDSA|ECJPAKE|ECP)_.*'),
515 re.compile(r'.*\bMBEDTLS_PK_PARSE_EC_COMPRESSED\b.*'),
516 ],
517 'test_suite_platform': [
518 # Incompatible with sanitizers (e.g. ASan). If the driver
519 # component uses a sanitizer but the reference component
520 # doesn't, we have a PASS vs SKIP mismatch.
521 'Check mbedtls_calloc overallocation',
522 ],
523 # See ecp_light_only
524 'test_suite_random': [
525 'PSA classic wrapper: ECDSA signature (SECP256R1)',
526 ],
527 # See no_ecp_at_all
528 'test_suite_pkparse': [
529 re.compile(r'Parse EC Key .*compressed\)'),
530 re.compile(r'Parse Public EC Key .*compressed\)'),
531 ],
532 'test_suite_asn1parse': [
533 'INTEGER too large for mpi',
534 ],
535 'test_suite_asn1write': [
536 re.compile(r'ASN.1 Write mpi.*'),
537 ],
538 'test_suite_debug': [
539 re.compile(r'Debug print mbedtls_mpi.*'),
540 ],
541 # See ecp_light_only
542 'test_suite_ssl': [
543 'Test configuration of groups for DHE through mbedtls_ssl_conf_curves()',
544 ],
545 }
546
547class DriverVSReference_ecc_ffdh_no_bignum(DriverVSReference):
548 REFERENCE = 'test_psa_crypto_config_reference_ecc_ffdh_no_bignum'
549 DRIVER = 'test_psa_crypto_config_accel_ecc_ffdh_no_bignum'
550 IGNORED_SUITES = [
551 # Modules replaced by drivers
552 'ecp', 'ecdsa', 'ecdh', 'ecjpake', 'dhm',
553 'bignum_core', 'bignum_random', 'bignum_mod', 'bignum_mod_raw',
554 'bignum.generated', 'bignum.misc',
555 ]
556 IGNORED_TESTS = {
557 'ssl-opt': [
558 # DHE support in TLS 1.2 requires built-in MBEDTLS_DHM_C
559 # (because it needs custom groups, which PSA does not
560 # provide), even with MBEDTLS_USE_PSA_CRYPTO.
561 re.compile(r'PSK callback:.*\bdhe-psk\b.*'),
562 ],
563 'test_suite_config': [
564 re.compile(r'.*\bMBEDTLS_BIGNUM_C\b.*'),
565 re.compile(r'.*\bMBEDTLS_DHM_C\b.*'),
566 re.compile(r'.*\bMBEDTLS_(ECDH|ECDSA|ECJPAKE|ECP)_.*'),
567 re.compile(r'.*\bMBEDTLS_KEY_EXCHANGE_DHE_PSK_ENABLED\b.*'),
568 re.compile(r'.*\bMBEDTLS_PK_PARSE_EC_COMPRESSED\b.*'),
569 ],
570 'test_suite_platform': [
571 # Incompatible with sanitizers (e.g. ASan). If the driver
572 # component uses a sanitizer but the reference component
573 # doesn't, we have a PASS vs SKIP mismatch.
574 'Check mbedtls_calloc overallocation',
575 ],
576 # See ecp_light_only
577 'test_suite_random': [
578 'PSA classic wrapper: ECDSA signature (SECP256R1)',
579 ],
580 # See no_ecp_at_all
581 'test_suite_pkparse': [
582 re.compile(r'Parse EC Key .*compressed\)'),
583 re.compile(r'Parse Public EC Key .*compressed\)'),
584 ],
585 'test_suite_asn1parse': [
586 'INTEGER too large for mpi',
587 ],
588 'test_suite_asn1write': [
589 re.compile(r'ASN.1 Write mpi.*'),
590 ],
591 'test_suite_debug': [
592 re.compile(r'Debug print mbedtls_mpi.*'),
593 ],
594 # See ecp_light_only
595 'test_suite_ssl': [
596 'Test configuration of groups for DHE through mbedtls_ssl_conf_curves()',
597 ],
598 }
599
600class DriverVSReference_ffdh_alg(DriverVSReference):
601 REFERENCE = 'test_psa_crypto_config_reference_ffdh'
602 DRIVER = 'test_psa_crypto_config_accel_ffdh'
603 IGNORED_SUITES = ['dhm']
604 IGNORED_TESTS = {
605 'test_suite_config': [
606 re.compile(r'.*\bMBEDTLS_DHM_C\b.*'),
607 ],
608 'test_suite_platform': [
609 # Incompatible with sanitizers (e.g. ASan). If the driver
610 # component uses a sanitizer but the reference component
611 # doesn't, we have a PASS vs SKIP mismatch.
612 'Check mbedtls_calloc overallocation',
613 ],
614 }
615
616class DriverVSReference_tfm_config(DriverVSReference):
617 REFERENCE = 'test_tfm_config_no_p256m'
618 DRIVER = 'test_tfm_config_p256m_driver_accel_ec'
619 IGNORED_SUITES = [
620 # Modules replaced by drivers
621 'asn1parse', 'asn1write',
622 'ecp', 'ecdsa', 'ecdh', 'ecjpake',
623 'bignum_core', 'bignum_random', 'bignum_mod', 'bignum_mod_raw',
624 'bignum.generated', 'bignum.misc',
625 ]
626 IGNORED_TESTS = {
627 'test_suite_config': [
628 re.compile(r'.*\bMBEDTLS_BIGNUM_C\b.*'),
629 re.compile(r'.*\bMBEDTLS_(ASN1\w+)_C\b.*'),
630 re.compile(r'.*\bMBEDTLS_(ECDH|ECDSA|ECP)_.*'),
631 re.compile(r'.*\bMBEDTLS_PSA_P256M_DRIVER_ENABLED\b.*')
632 ],
633 'test_suite_config.crypto_combinations': [
634 'Config: ECC: Weierstrass curves only',
635 ],
636 'test_suite_platform': [
637 # Incompatible with sanitizers (e.g. ASan). If the driver
638 # component uses a sanitizer but the reference component
639 # doesn't, we have a PASS vs SKIP mismatch.
640 'Check mbedtls_calloc overallocation',
641 ],
642 # See ecp_light_only
643 'test_suite_random': [
644 'PSA classic wrapper: ECDSA signature (SECP256R1)',
645 ],
646 }
647
648class DriverVSReference_rsa(DriverVSReference):
649 REFERENCE = 'test_psa_crypto_config_reference_rsa_crypto'
650 DRIVER = 'test_psa_crypto_config_accel_rsa_crypto'
651 IGNORED_SUITES = [
652 # Modules replaced by drivers.
653 'rsa', 'pkcs1_v15', 'pkcs1_v21',
654 # We temporarily don't care about PK stuff.
655 'pk', 'pkwrite', 'pkparse'
656 ]
657 IGNORED_TESTS = {
658 'test_suite_config': [
659 re.compile(r'.*\bMBEDTLS_(PKCS1|RSA)_.*'),
660 re.compile(r'.*\bMBEDTLS_GENPRIME\b.*')
661 ],
662 'test_suite_platform': [
663 # Incompatible with sanitizers (e.g. ASan). If the driver
664 # component uses a sanitizer but the reference component
665 # doesn't, we have a PASS vs SKIP mismatch.
666 'Check mbedtls_calloc overallocation',
667 ],
668 # Following tests depend on RSA_C but are not about
669 # them really, just need to know some error code is there.
670 'test_suite_error': [
671 'Low and high error',
672 'Single high error'
673 ],
674 # Constant time operations only used for PKCS1_V15
675 'test_suite_constant_time': [
676 re.compile(r'mbedtls_ct_zeroize_if .*'),
677 re.compile(r'mbedtls_ct_memmove_left .*')
678 ],
679 'test_suite_psa_crypto': [
680 # We don't support generate_key_custom entry points
681 # in drivers yet.
682 re.compile(r'PSA generate key custom: RSA, e=.*'),
683 re.compile(r'PSA generate key ext: RSA, e=.*'),
684 ],
685 }
686
687class DriverVSReference_block_cipher_dispatch(DriverVSReference):
688 REFERENCE = 'test_full_block_cipher_legacy_dispatch'
689 DRIVER = 'test_full_block_cipher_psa_dispatch'
690 IGNORED_SUITES = [
691 # Skipped in the accelerated component
692 'aes', 'aria', 'camellia',
693 # These require AES_C, ARIA_C or CAMELLIA_C to be enabled in
694 # order for the cipher module (actually cipher_wrapper) to work
695 # properly. However these symbols are disabled in the accelerated
696 # component so we ignore them.
697 'cipher.ccm', 'cipher.gcm', 'cipher.aes', 'cipher.aria',
698 'cipher.camellia',
699 ]
700 IGNORED_TESTS = {
701 'test_suite_config': [
702 re.compile(r'.*\bMBEDTLS_(AES|ARIA|CAMELLIA)_.*'),
703 re.compile(r'.*\bMBEDTLS_AES(\w+)_C\b.*'),
704 ],
705 'test_suite_cmac': [
706 # Following tests require AES_C/ARIA_C/CAMELLIA_C to be enabled,
707 # but these are not available in the accelerated component.
708 'CMAC null arguments',
709 re.compile('CMAC.* (AES|ARIA|Camellia).*'),
710 ],
711 'test_suite_cipher.padding': [
712 # Following tests require AES_C/CAMELLIA_C to be enabled,
713 # but these are not available in the accelerated component.
714 re.compile('Set( non-existent)? padding with (AES|CAMELLIA).*'),
715 ],
716 'test_suite_pkcs5': [
717 # The AES part of PKCS#5 PBES2 is not yet supported.
718 # The rest of PKCS#5 (PBKDF2) works, though.
719 re.compile(r'PBES2 .* AES-.*')
720 ],
721 'test_suite_pkparse': [
722 # PEM (called by pkparse) requires AES_C in order to decrypt
723 # the key, but this is not available in the accelerated
724 # component.
725 re.compile('Parse RSA Key.*(password|AES-).*'),
726 ],
727 'test_suite_pem': [
728 # Following tests require AES_C, but this is diabled in the
729 # accelerated component.
730 re.compile('PEM read .*AES.*'),
731 'PEM read (unknown encryption algorithm)',
732 ],
733 'test_suite_error': [
734 # Following tests depend on AES_C but are not about them
735 # really, just need to know some error code is there.
736 'Single low error',
737 'Low and high error',
738 ],
739 'test_suite_version': [
740 # Similar to test_suite_error above.
741 'Check for MBEDTLS_AES_C when already present',
742 ],
743 'test_suite_platform': [
744 # Incompatible with sanitizers (e.g. ASan). If the driver
745 # component uses a sanitizer but the reference component
746 # doesn't, we have a PASS vs SKIP mismatch.
747 'Check mbedtls_calloc overallocation',
748 ],
749 }
750
751#pylint: enable=invalid-name,missing-class-docstring
752
753
Gilles Peskine82b16722024-09-16 19:57:10 +0200754
Przemek Stekiel6856f4c2022-11-09 10:50:29 +0100755# List of tasks with a function that can handle this task and additional arguments if required
Valerio Settidfd7ca62023-10-09 16:30:11 +0200756KNOWN_TASKS = {
Gilles Peskinef646dbf2024-09-16 19:15:29 +0200757 'analyze_coverage': CoverageTask,
Gilles Peskine9df375b2024-09-16 20:14:26 +0200758 'analyze_driver_vs_reference_hash': DriverVSReference_hash,
759 'analyze_driver_vs_reference_hmac': DriverVSReference_hmac,
760 'analyze_driver_vs_reference_cipher_aead_cmac': DriverVSReference_cipher_aead_cmac,
761 'analyze_driver_vs_reference_ecp_light_only': DriverVSReference_ecp_light_only,
762 'analyze_driver_vs_reference_no_ecp_at_all': DriverVSReference_no_ecp_at_all,
763 'analyze_driver_vs_reference_ecc_no_bignum': DriverVSReference_ecc_no_bignum,
764 'analyze_driver_vs_reference_ecc_ffdh_no_bignum': DriverVSReference_ecc_ffdh_no_bignum,
765 'analyze_driver_vs_reference_ffdh_alg': DriverVSReference_ffdh_alg,
766 'analyze_driver_vs_reference_tfm_config': DriverVSReference_tfm_config,
767 'analyze_driver_vs_reference_rsa': DriverVSReference_rsa,
768 'analyze_block_cipher_dispatch': DriverVSReference_block_cipher_dispatch,
Przemek Stekiel4d13c832022-10-26 16:11:26 +0200769}
Przemek Stekiel4d13c832022-10-26 16:11:26 +0200770
Gilles Peskine9df375b2024-09-16 20:14:26 +0200771
Gilles Peskine15c2cbf2020-06-25 18:36:28 +0200772def main():
Valerio Settif075e472023-10-17 11:03:16 +0200773 main_results = Results()
Valerio Settiaaef0bc2023-10-10 09:42:13 +0200774
Gilles Peskine15c2cbf2020-06-25 18:36:28 +0200775 try:
776 parser = argparse.ArgumentParser(description=__doc__)
Przemek Stekiel58bbc232022-10-24 08:10:10 +0200777 parser.add_argument('outcomes', metavar='OUTCOMES.CSV',
Gilles Peskine15c2cbf2020-06-25 18:36:28 +0200778 help='Outcome file to analyze')
Valerio Settidfd7ca62023-10-09 16:30:11 +0200779 parser.add_argument('specified_tasks', default='all', nargs='?',
Przemek Stekiel992de3c2022-11-09 13:54:49 +0100780 help='Analysis to be done. By default, run all tasks. '
781 'With one or more TASK, run only those. '
782 'TASK can be the name of a single task or '
Przemek Stekiel85c54ea2022-11-17 11:50:23 +0100783 'comma/space-separated list of tasks. ')
Przemek Stekiel992de3c2022-11-09 13:54:49 +0100784 parser.add_argument('--list', action='store_true',
785 help='List all available tasks and exit.')
Tomás Gonzálezb401e112023-08-11 15:22:04 +0100786 parser.add_argument('--require-full-coverage', action='store_true',
787 dest='full_coverage', help="Require all available "
788 "test cases to be executed and issue an error "
789 "otherwise. This flag is ignored if 'task' is "
790 "neither 'all' nor 'analyze_coverage'")
Gilles Peskine15c2cbf2020-06-25 18:36:28 +0200791 options = parser.parse_args()
Przemek Stekiel4e955902022-10-21 13:42:08 +0200792
Przemek Stekiel992de3c2022-11-09 13:54:49 +0100793 if options.list:
Valerio Settidfd7ca62023-10-09 16:30:11 +0200794 for task in KNOWN_TASKS:
Valerio Setti5329ff02023-10-17 09:44:36 +0200795 print(task)
Przemek Stekiel992de3c2022-11-09 13:54:49 +0100796 sys.exit(0)
797
Valerio Settidfd7ca62023-10-09 16:30:11 +0200798 if options.specified_tasks == 'all':
799 tasks_list = KNOWN_TASKS.keys()
Przemek Stekiel992de3c2022-11-09 13:54:49 +0100800 else:
Valerio Settidfd7ca62023-10-09 16:30:11 +0200801 tasks_list = re.split(r'[, ]+', options.specified_tasks)
Valerio Settidfd7ca62023-10-09 16:30:11 +0200802 for task in tasks_list:
803 if task not in KNOWN_TASKS:
Manuel Pégourié-Gonnard62d61312023-10-20 10:51:57 +0200804 sys.stderr.write('invalid task: {}\n'.format(task))
Valerio Settifb2750e2023-10-17 10:11:45 +0200805 sys.exit(2)
Przemek Stekiel992de3c2022-11-09 13:54:49 +0100806
Pengyu Lvdd1d6a72023-11-27 17:57:31 +0800807 # If the outcome file exists, parse it once and share the result
808 # among tasks to improve performance.
Pengyu Lv20e3ca32023-11-28 15:30:03 +0800809 # Otherwise, it will be generated by execute_reference_driver_tests.
810 if not os.path.exists(options.outcomes):
811 if len(tasks_list) > 1:
812 sys.stderr.write("mutiple tasks found, please provide a valid outcomes file.\n")
813 sys.exit(2)
814
815 task_name = tasks_list[0]
816 task = KNOWN_TASKS[task_name]
Gilles Peskine82b16722024-09-16 19:57:10 +0200817 if not issubclass(task, DriverVSReference):
Pengyu Lv20e3ca32023-11-28 15:30:03 +0800818 sys.stderr.write("please provide valid outcomes file for {}.\n".format(task_name))
819 sys.exit(2)
Pengyu Lv20e3ca32023-11-28 15:30:03 +0800820 execute_reference_driver_tests(main_results,
Gilles Peskine82b16722024-09-16 19:57:10 +0200821 task.REFERENCE,
822 task.DRIVER,
Pengyu Lv20e3ca32023-11-28 15:30:03 +0800823 options.outcomes)
824
825 outcomes = read_outcome_file(options.outcomes)
Pengyu Lva6cf5d62023-11-22 11:35:21 +0800826
Gilles Peskine19ef1ae2024-09-16 19:12:09 +0200827 for task_name in tasks_list:
828 task_constructor = KNOWN_TASKS[task_name]
Gilles Peskine0f31f762024-09-16 20:15:58 +0200829 task = task_constructor(options)
830 main_results.new_section(task.section_name())
831 task.run(main_results, outcomes)
Tomás Gonzálezb401e112023-08-11 15:22:04 +0100832
Valerio Settif6f64cf2023-10-17 12:28:26 +0200833 main_results.info("Overall results: {} warnings and {} errors",
834 main_results.warning_count, main_results.error_count)
Przemek Stekiel4e955902022-10-21 13:42:08 +0200835
Valerio Setti8d178be2023-10-17 12:23:55 +0200836 sys.exit(0 if (main_results.error_count == 0) else 1)
Valerio Settiaaef0bc2023-10-10 09:42:13 +0200837
Gilles Peskine15c2cbf2020-06-25 18:36:28 +0200838 except Exception: # pylint: disable=broad-except
839 # Print the backtrace and exit explicitly with our chosen status.
840 traceback.print_exc()
841 sys.exit(120)
842
843if __name__ == '__main__':
844 main()