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