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