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