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