blob: ef0db33275d957d52a2da21a1931870df53ed8d3 [file] [log] [blame]
Gilles Peskine15c2cbf2020-06-25 18:36:28 +02001#!/usr/bin/env python3
2
3"""Analyze the test outcomes from a full CI run.
4
5This script can also run on outcomes from a partial run, but the results are
6less likely to be useful.
7"""
8
9import argparse
10import sys
11import traceback
Przemek Stekiel85c54ea2022-11-17 11:50:23 +010012import re
Valerio Settia2663322023-03-24 08:20:18 +010013import subprocess
14import os
Pengyu Lv18908ec2023-11-28 12:11:52 +080015import typing
Gilles Peskine15c2cbf2020-06-25 18:36:28 +020016
Gilles Peskine8d3c70a2020-06-25 18:37:43 +020017import check_test_cases
18
Pengyu Lvc2e8f3a2023-11-28 17:22:04 +080019
Pengyu Lv550cd6f2023-11-29 09:17:59 +080020# `ComponentOutcomes` is a named tuple which is defined as:
Pengyu Lvc2e8f3a2023-11-28 17:22:04 +080021# ComponentOutcomes(
22# successes = {
23# "<suite_case>",
24# ...
25# },
26# failures = {
27# "<suite_case>",
28# ...
29# }
30# )
31# suite_case = "<suite>;<case>"
Pengyu Lv18908ec2023-11-28 12:11:52 +080032ComponentOutcomes = typing.NamedTuple('ComponentOutcomes',
33 [('successes', typing.Set[str]),
34 ('failures', typing.Set[str])])
35
Pengyu Lvc2e8f3a2023-11-28 17:22:04 +080036# `Outcomes` is a representation of the outcomes file,
37# which defined as:
38# Outcomes = {
39# "<component>": ComponentOutcomes,
40# ...
41# }
42Outcomes = typing.Dict[str, ComponentOutcomes]
43
44
Gilles Peskine15c2cbf2020-06-25 18:36:28 +020045class Results:
46 """Process analysis results."""
47
48 def __init__(self):
49 self.error_count = 0
50 self.warning_count = 0
51
Valerio Setti2cff8202023-10-18 14:36:47 +020052 def new_section(self, fmt, *args, **kwargs):
53 self._print_line('\n*** ' + fmt + ' ***\n', *args, **kwargs)
54
Valerio Settiaaef0bc2023-10-10 09:42:13 +020055 def info(self, fmt, *args, **kwargs):
Valerio Setti8070dbe2023-10-17 12:29:30 +020056 self._print_line('Info: ' + fmt, *args, **kwargs)
Gilles Peskine15c2cbf2020-06-25 18:36:28 +020057
58 def error(self, fmt, *args, **kwargs):
Gilles Peskine15c2cbf2020-06-25 18:36:28 +020059 self.error_count += 1
Valerio Setti8070dbe2023-10-17 12:29:30 +020060 self._print_line('Error: ' + fmt, *args, **kwargs)
Gilles Peskine15c2cbf2020-06-25 18:36:28 +020061
62 def warning(self, fmt, *args, **kwargs):
Gilles Peskine15c2cbf2020-06-25 18:36:28 +020063 self.warning_count += 1
Valerio Setti8070dbe2023-10-17 12:29:30 +020064 self._print_line('Warning: ' + fmt, *args, **kwargs)
Gilles Peskine15c2cbf2020-06-25 18:36:28 +020065
Valerio Setti3f339892023-10-17 10:42:11 +020066 @staticmethod
Valerio Setti8070dbe2023-10-17 12:29:30 +020067 def _print_line(fmt, *args, **kwargs):
Valerio Setti735794c2023-10-18 08:05:15 +020068 sys.stderr.write((fmt + '\n').format(*args, **kwargs))
Gilles Peskine15c2cbf2020-06-25 18:36:28 +020069
Pengyu Lvc2e8f3a2023-11-28 17:22:04 +080070def execute_reference_driver_tests(results: Results, ref_component: str, driver_component: str, \
71 outcome_file: str) -> None:
Valerio Setti22992a02023-03-29 11:15:28 +020072 """Run the tests specified in ref_component and driver_component. Results
73 are stored in the output_file and they will be used for the following
Valerio Settia2663322023-03-24 08:20:18 +010074 coverage analysis"""
Pengyu Lv20e3ca32023-11-28 15:30:03 +080075 results.new_section("Test {} and {}", ref_component, driver_component)
Valerio Settia2663322023-03-24 08:20:18 +010076
77 shell_command = "tests/scripts/all.sh --outcome-file " + outcome_file + \
78 " " + ref_component + " " + driver_component
Valerio Setti39d4b9d2023-10-18 14:30:03 +020079 results.info("Running: {}", shell_command)
Valerio Settia2663322023-03-24 08:20:18 +010080 ret_val = subprocess.run(shell_command.split(), check=False).returncode
81
82 if ret_val != 0:
Valerio Settif075e472023-10-17 11:03:16 +020083 results.error("failed to run reference/driver components")
Valerio Settia2663322023-03-24 08:20:18 +010084
Gilles Peskine82b16722024-09-16 19:57:10 +020085IgnoreEntry = typing.Union[str, typing.Pattern]
86
87def name_matches_pattern(name: str, str_or_re: IgnoreEntry) -> bool:
Manuel Pégourié-Gonnard881ce012023-10-18 10:22:07 +020088 """Check if name matches a pattern, that may be a string or regex.
89 - If the pattern is a string, name must be equal to match.
90 - If the pattern is a regex, name must fully match.
91 """
Manuel Pégourié-Gonnardb2695432023-10-23 09:30:40 +020092 # The CI's python is too old for re.Pattern
93 #if isinstance(str_or_re, re.Pattern):
94 if not isinstance(str_or_re, str):
Pengyu Lvc2e8f3a2023-11-28 17:22:04 +080095 return str_or_re.fullmatch(name) is not None
Manuel Pégourié-Gonnard881ce012023-10-18 10:22:07 +020096 else:
Manuel Pégourié-Gonnard9d9c2342023-10-26 09:37:40 +020097 return str_or_re == name
Manuel Pégourié-Gonnard881ce012023-10-18 10:22:07 +020098
Pengyu Lvc2e8f3a2023-11-28 17:22:04 +080099def read_outcome_file(outcome_file: str) -> Outcomes:
Gilles Peskine15c2cbf2020-06-25 18:36:28 +0200100 """Parse an outcome file and return an outcome collection.
Pengyu Lvc2e8f3a2023-11-28 17:22:04 +0800101 """
Gilles Peskine15c2cbf2020-06-25 18:36:28 +0200102 outcomes = {}
103 with open(outcome_file, 'r', encoding='utf-8') as input_file:
104 for line in input_file:
Pengyu Lvdd1d6a72023-11-27 17:57:31 +0800105 (_platform, component, suite, case, result, _cause) = line.split(';')
Pengyu Lv451ec8a2023-11-28 17:59:05 +0800106 # Note that `component` is not unique. If a test case passes on Linux
107 # and fails on FreeBSD, it'll end up in both the successes set and
108 # the failures set.
Pengyu Lv31a9b782023-11-23 14:15:37 +0800109 suite_case = ';'.join([suite, case])
Pengyu Lvdd1d6a72023-11-27 17:57:31 +0800110 if component not in outcomes:
Pengyu Lv18908ec2023-11-28 12:11:52 +0800111 outcomes[component] = ComponentOutcomes(set(), set())
Gilles Peskine15c2cbf2020-06-25 18:36:28 +0200112 if result == 'PASS':
Pengyu Lv18908ec2023-11-28 12:11:52 +0800113 outcomes[component].successes.add(suite_case)
Gilles Peskine15c2cbf2020-06-25 18:36:28 +0200114 elif result == 'FAIL':
Pengyu Lv18908ec2023-11-28 12:11:52 +0800115 outcomes[component].failures.add(suite_case)
Pengyu Lva4428582023-11-22 19:02:15 +0800116
Gilles Peskine15c2cbf2020-06-25 18:36:28 +0200117 return outcomes
118
Gilles Peskine19ef1ae2024-09-16 19:12:09 +0200119
120class Task:
121 """Base class for outcome analysis tasks."""
122
Gilles Peskine02976052024-09-16 20:44:15 +0200123 # Override the following in child classes.
124 # Map test suite names (with the test_suite_prefix) to a list of ignored
125 # test cases. Each element in the list can be either a string or a regex;
126 # see the `name_matches_pattern` function.
127 IGNORED_TESTS = {} #type: typing.Dict[str, typing.List[IgnoreEntry]]
128
Gilles Peskine19ef1ae2024-09-16 19:12:09 +0200129 def __init__(self, options) -> None:
130 """Pass command line options to the tasks.
131
132 Each task decides which command line options it cares about.
133 """
134 pass
135
Gilles Peskinef646dbf2024-09-16 19:15:29 +0200136 def section_name(self) -> str:
137 """The section name to use in results."""
138
Gilles Peskinedba80102024-09-16 20:52:58 +0200139 def ignored_tests(self, test_suite: str) -> typing.Iterator[IgnoreEntry]:
140 """Generate the ignore list for the specified test suite."""
141 if test_suite in self.IGNORED_TESTS:
142 yield from self.IGNORED_TESTS[test_suite]
143 pos = test_suite.find('.')
144 if pos != -1:
145 base_test_suite = test_suite[:pos]
146 if base_test_suite in self.IGNORED_TESTS:
147 yield from self.IGNORED_TESTS[base_test_suite]
148
149 def is_test_case_ignored(self, test_suite: str, test_string: str) -> bool:
Gilles Peskine02976052024-09-16 20:44:15 +0200150 """Check if the specified test case is ignored."""
Gilles Peskinedba80102024-09-16 20:52:58 +0200151 for str_or_re in self.ignored_tests(test_suite):
Gilles Peskine02976052024-09-16 20:44:15 +0200152 if name_matches_pattern(test_string, str_or_re):
153 return True
154 return False
155
Gilles Peskine19ef1ae2024-09-16 19:12:09 +0200156 def run(self, results: Results, outcomes: Outcomes):
157 """Run the analysis on the specified outcomes.
158
159 Signal errors via the results objects
160 """
161 raise NotImplementedError
162
163
Gilles Peskinef646dbf2024-09-16 19:15:29 +0200164class CoverageTask(Task):
165 """Analyze test coverage."""
166
Gilles Peskine54cfe772024-09-16 20:56:43 +0200167 IGNORED_TESTS = {
168 'test_suite_psa_crypto_metadata': [
169 # Algorithm not supported yet
170 'Asymmetric signature: pure EdDSA',
171 # Algorithm not supported yet
172 'Cipher: XTS',
173 ],
174 }
Gilles Peskinef646dbf2024-09-16 19:15:29 +0200175
176 def __init__(self, options) -> None:
177 super().__init__(options)
178 self.full_coverage = options.full_coverage #type: bool
179
180 @staticmethod
181 def section_name() -> str:
182 return "Analyze coverage"
183
Gilles Peskineb4daeb42024-09-16 20:32:59 +0200184 def run(self, results: Results, outcomes: Outcomes) -> None:
Gilles Peskine3f5022e2024-09-16 20:23:40 +0200185 """Check that all available test cases are executed at least once."""
186 # Make sure that the generated data files are present (and up-to-date).
187 # This allows analyze_outcomes.py to run correctly on a fresh Git
188 # checkout.
189 cp = subprocess.run(['make', 'generated_files'],
190 cwd='tests',
191 stdout=subprocess.PIPE, stderr=subprocess.STDOUT,
192 check=False)
193 if cp.returncode != 0:
194 sys.stderr.write(cp.stdout.decode('utf-8'))
195 results.error("Failed \"make generated_files\" in tests. "
196 "Coverage analysis may be incorrect.")
197 available = check_test_cases.collect_available_test_cases()
198 for suite_case in available:
199 hit = any(suite_case in comp_outcomes.successes or
200 suite_case in comp_outcomes.failures
201 for comp_outcomes in outcomes.values())
Gilles Peskine54cfe772024-09-16 20:56:43 +0200202 (test_suite, test_description) = suite_case.split(';')
203 ignored = self.is_test_case_ignored(test_suite, test_description)
Gilles Peskine3f5022e2024-09-16 20:23:40 +0200204
Gilles Peskine54cfe772024-09-16 20:56:43 +0200205 if not hit and not ignored:
Gilles Peskineb4daeb42024-09-16 20:32:59 +0200206 if self.full_coverage:
Gilles Peskine3f5022e2024-09-16 20:23:40 +0200207 results.error('Test case not executed: {}', suite_case)
208 else:
209 results.warning('Test case not executed: {}', suite_case)
Gilles Peskine54cfe772024-09-16 20:56:43 +0200210 elif hit and ignored:
Gilles Peskine3f5022e2024-09-16 20:23:40 +0200211 # Test Case should be removed from the allow list.
Gilles Peskineb4daeb42024-09-16 20:32:59 +0200212 if self.full_coverage:
Gilles Peskine3f5022e2024-09-16 20:23:40 +0200213 results.error('Allow listed test case was executed: {}', suite_case)
214 else:
215 results.warning('Allow listed test case was executed: {}', suite_case)
216
Gilles Peskinef646dbf2024-09-16 19:15:29 +0200217
Gilles Peskine82b16722024-09-16 19:57:10 +0200218class DriverVSReference(Task):
219 """Compare outcomes from testing with and without a driver.
220
221 There are 2 options to use analyze_driver_vs_reference_xxx locally:
222 1. Run tests and then analysis:
223 - tests/scripts/all.sh --outcome-file "$PWD/out.csv" <component_ref> <component_driver>
224 - tests/scripts/analyze_outcomes.py out.csv analyze_driver_vs_reference_xxx
225 2. Let this script run both automatically:
226 - tests/scripts/analyze_outcomes.py out.csv analyze_driver_vs_reference_xxx
227 """
228
229 # Override the following in child classes.
230 # Configuration name (all.sh component) used as the reference.
231 REFERENCE = ''
232 # Configuration name (all.sh component) used as the driver.
233 DRIVER = ''
234 # Ignored test suites (without the test_suite_ prefix).
235 IGNORED_SUITES = [] #type: typing.List[str]
Gilles Peskine82b16722024-09-16 19:57:10 +0200236
Gilles Peskineb4daeb42024-09-16 20:32:59 +0200237 def __init__(self, options) -> None:
238 super().__init__(options)
239 self.ignored_suites = frozenset('test_suite_' + x
240 for x in self.IGNORED_SUITES)
241
Gilles Peskine82b16722024-09-16 19:57:10 +0200242 def section_name(self) -> str:
243 return f"Analyze driver {self.DRIVER} vs reference {self.REFERENCE}"
244
Gilles Peskineb4daeb42024-09-16 20:32:59 +0200245 def run(self, results: Results, outcomes: Outcomes) -> None:
Gilles Peskine3f5022e2024-09-16 20:23:40 +0200246 """Check that all tests passing in the driver component are also
247 passing in the corresponding reference component.
248 Skip:
249 - full test suites provided in ignored_suites list
250 - only some specific test inside a test suite, for which the corresponding
251 output string is provided
252 """
Gilles Peskineb4daeb42024-09-16 20:32:59 +0200253 ref_outcomes = outcomes.get("component_" + self.REFERENCE)
254 driver_outcomes = outcomes.get("component_" + self.DRIVER)
Gilles Peskine3f5022e2024-09-16 20:23:40 +0200255
256 if ref_outcomes is None or driver_outcomes is None:
257 results.error("required components are missing: bad outcome file?")
258 return
259
260 if not ref_outcomes.successes:
261 results.error("no passing test in reference component: bad outcome file?")
262 return
263
264 for suite_case in ref_outcomes.successes:
265 # suite_case is like "test_suite_foo.bar;Description of test case"
266 (full_test_suite, test_string) = suite_case.split(';')
267 test_suite = full_test_suite.split('.')[0] # retrieve main part of test suite name
268
269 # Immediately skip fully-ignored test suites
Gilles Peskineb4daeb42024-09-16 20:32:59 +0200270 if test_suite in self.ignored_suites or \
271 full_test_suite in self.ignored_suites:
Gilles Peskine3f5022e2024-09-16 20:23:40 +0200272 continue
273
274 # For ignored test cases inside test suites, just remember and:
275 # don't issue an error if they're skipped with drivers,
276 # but issue an error if they're not (means we have a bad entry).
Gilles Peskine02976052024-09-16 20:44:15 +0200277 ignored = self.is_test_case_ignored(full_test_suite, test_string)
Gilles Peskine3f5022e2024-09-16 20:23:40 +0200278
279 if not ignored and not suite_case in driver_outcomes.successes:
280 results.error("SKIP/FAIL -> PASS: {}", suite_case)
281 if ignored and suite_case in driver_outcomes.successes:
282 results.error("uselessly ignored: {}", suite_case)
283
Gilles Peskine82b16722024-09-16 19:57:10 +0200284
Gilles Peskine9df375b2024-09-16 20:14:26 +0200285# The names that we give to classes derived from DriverVSReference do not
286# follow the usual naming convention, because it's more readable to use
287# underscores and parts of the configuration names. Also, these classes
288# are just there to specify some data, so they don't need repetitive
289# documentation.
290#pylint: disable=invalid-name,missing-class-docstring
291
292class DriverVSReference_hash(DriverVSReference):
293 REFERENCE = 'test_psa_crypto_config_reference_hash_use_psa'
294 DRIVER = 'test_psa_crypto_config_accel_hash_use_psa'
295 IGNORED_SUITES = [
296 'shax', 'mdx', # the software implementations that are being excluded
297 'md.psa', # purposefully depends on whether drivers are present
298 'psa_crypto_low_hash.generated', # testing the builtins
299 ]
300 IGNORED_TESTS = {
301 'test_suite_config': [
302 re.compile(r'.*\bMBEDTLS_(MD5|RIPEMD160|SHA[0-9]+)_.*'),
303 ],
304 'test_suite_platform': [
305 # Incompatible with sanitizers (e.g. ASan). If the driver
306 # component uses a sanitizer but the reference component
307 # doesn't, we have a PASS vs SKIP mismatch.
308 'Check mbedtls_calloc overallocation',
309 ],
310 }
311
312class DriverVSReference_hmac(DriverVSReference):
313 REFERENCE = 'test_psa_crypto_config_reference_hmac'
314 DRIVER = 'test_psa_crypto_config_accel_hmac'
315 IGNORED_SUITES = [
316 # These suites require legacy hash support, which is disabled
317 # in the accelerated component.
318 'shax', 'mdx',
319 # This suite tests builtins directly, but these are missing
320 # in the accelerated case.
321 'psa_crypto_low_hash.generated',
322 ]
323 IGNORED_TESTS = {
324 'test_suite_config': [
325 re.compile(r'.*\bMBEDTLS_(MD5|RIPEMD160|SHA[0-9]+)_.*'),
326 re.compile(r'.*\bMBEDTLS_MD_C\b')
327 ],
328 'test_suite_md': [
329 # Builtin HMAC is not supported in the accelerate component.
330 re.compile('.*HMAC.*'),
331 # Following tests make use of functions which are not available
332 # when MD_C is disabled, as it happens in the accelerated
333 # test component.
334 re.compile('generic .* Hash file .*'),
335 'MD list',
336 ],
337 'test_suite_md.psa': [
338 # "legacy only" tests require hash algorithms to be NOT
339 # accelerated, but this of course false for the accelerated
340 # test component.
341 re.compile('PSA dispatch .* legacy only'),
342 ],
343 'test_suite_platform': [
344 # Incompatible with sanitizers (e.g. ASan). If the driver
345 # component uses a sanitizer but the reference component
346 # doesn't, we have a PASS vs SKIP mismatch.
347 'Check mbedtls_calloc overallocation',
348 ],
349 }
350
351class DriverVSReference_cipher_aead_cmac(DriverVSReference):
352 REFERENCE = 'test_psa_crypto_config_reference_cipher_aead_cmac'
353 DRIVER = 'test_psa_crypto_config_accel_cipher_aead_cmac'
354 # Modules replaced by drivers.
355 IGNORED_SUITES = [
356 # low-level (block/stream) cipher modules
357 'aes', 'aria', 'camellia', 'des', 'chacha20',
358 # AEAD modes and CMAC
359 'ccm', 'chachapoly', 'cmac', 'gcm',
360 # The Cipher abstraction layer
361 'cipher',
362 ]
363 IGNORED_TESTS = {
364 'test_suite_config': [
365 re.compile(r'.*\bMBEDTLS_(AES|ARIA|CAMELLIA|CHACHA20|DES)_.*'),
366 re.compile(r'.*\bMBEDTLS_(CCM|CHACHAPOLY|CMAC|GCM)_.*'),
367 re.compile(r'.*\bMBEDTLS_AES(\w+)_C\b.*'),
368 re.compile(r'.*\bMBEDTLS_CIPHER_.*'),
369 ],
370 # PEM decryption is not supported so far.
371 # The rest of PEM (write, unencrypted read) works though.
372 'test_suite_pem': [
373 re.compile(r'PEM read .*(AES|DES|\bencrypt).*'),
374 ],
375 'test_suite_platform': [
376 # Incompatible with sanitizers (e.g. ASan). If the driver
377 # component uses a sanitizer but the reference component
378 # doesn't, we have a PASS vs SKIP mismatch.
379 'Check mbedtls_calloc overallocation',
380 ],
381 # Following tests depend on AES_C/DES_C but are not about
382 # them really, just need to know some error code is there.
383 'test_suite_error': [
384 'Low and high error',
385 'Single low error'
386 ],
387 # Similar to test_suite_error above.
388 'test_suite_version': [
389 'Check for MBEDTLS_AES_C when already present',
390 ],
391 # The en/decryption part of PKCS#12 is not supported so far.
392 # The rest of PKCS#12 (key derivation) works though.
393 'test_suite_pkcs12': [
394 re.compile(r'PBE Encrypt, .*'),
395 re.compile(r'PBE Decrypt, .*'),
396 ],
397 # The en/decryption part of PKCS#5 is not supported so far.
398 # The rest of PKCS#5 (PBKDF2) works though.
399 'test_suite_pkcs5': [
400 re.compile(r'PBES2 Encrypt, .*'),
401 re.compile(r'PBES2 Decrypt .*'),
402 ],
403 # Encrypted keys are not supported so far.
404 # pylint: disable=line-too-long
405 'test_suite_pkparse': [
406 'Key ASN1 (Encrypted key PKCS12, trailing garbage data)',
407 'Key ASN1 (Encrypted key PKCS5, trailing garbage data)',
408 re.compile(r'Parse (RSA|EC) Key .*\(.* ([Ee]ncrypted|password).*\)'),
409 ],
410 # Encrypted keys are not supported so far.
411 'ssl-opt': [
412 'TLS: password protected server key',
413 'TLS: password protected client key',
414 'TLS: password protected server key, two certificates',
415 ],
416 }
417
418class DriverVSReference_ecp_light_only(DriverVSReference):
419 REFERENCE = 'test_psa_crypto_config_reference_ecc_ecp_light_only'
420 DRIVER = 'test_psa_crypto_config_accel_ecc_ecp_light_only'
421 IGNORED_SUITES = [
422 # Modules replaced by drivers
423 'ecdsa', 'ecdh', 'ecjpake',
424 ]
425 IGNORED_TESTS = {
426 'test_suite_config': [
427 re.compile(r'.*\bMBEDTLS_(ECDH|ECDSA|ECJPAKE|ECP)_.*'),
428 ],
429 'test_suite_platform': [
430 # Incompatible with sanitizers (e.g. ASan). If the driver
431 # component uses a sanitizer but the reference component
432 # doesn't, we have a PASS vs SKIP mismatch.
433 'Check mbedtls_calloc overallocation',
434 ],
435 # This test wants a legacy function that takes f_rng, p_rng
436 # arguments, and uses legacy ECDSA for that. The test is
437 # really about the wrapper around the PSA RNG, not ECDSA.
438 'test_suite_random': [
439 'PSA classic wrapper: ECDSA signature (SECP256R1)',
440 ],
441 # In the accelerated test ECP_C is not set (only ECP_LIGHT is)
442 # so we must ignore disparities in the tests for which ECP_C
443 # is required.
444 'test_suite_ecp': [
445 re.compile(r'ECP check public-private .*'),
446 re.compile(r'ECP calculate public: .*'),
447 re.compile(r'ECP gen keypair .*'),
448 re.compile(r'ECP point muladd .*'),
449 re.compile(r'ECP point multiplication .*'),
450 re.compile(r'ECP test vectors .*'),
451 ],
452 'test_suite_ssl': [
453 # This deprecated function is only present when ECP_C is On.
454 'Test configuration of groups for DHE through mbedtls_ssl_conf_curves()',
455 ],
456 }
457
458class DriverVSReference_no_ecp_at_all(DriverVSReference):
459 REFERENCE = 'test_psa_crypto_config_reference_ecc_no_ecp_at_all'
460 DRIVER = 'test_psa_crypto_config_accel_ecc_no_ecp_at_all'
461 IGNORED_SUITES = [
462 # Modules replaced by drivers
463 'ecp', 'ecdsa', 'ecdh', 'ecjpake',
464 ]
465 IGNORED_TESTS = {
466 'test_suite_config': [
467 re.compile(r'.*\bMBEDTLS_(ECDH|ECDSA|ECJPAKE|ECP)_.*'),
468 re.compile(r'.*\bMBEDTLS_PK_PARSE_EC_COMPRESSED\b.*'),
469 ],
470 'test_suite_platform': [
471 # Incompatible with sanitizers (e.g. ASan). If the driver
472 # component uses a sanitizer but the reference component
473 # doesn't, we have a PASS vs SKIP mismatch.
474 'Check mbedtls_calloc overallocation',
475 ],
476 # See ecp_light_only
477 'test_suite_random': [
478 'PSA classic wrapper: ECDSA signature (SECP256R1)',
479 ],
480 'test_suite_pkparse': [
481 # When PK_PARSE_C and ECP_C are defined then PK_PARSE_EC_COMPRESSED
482 # is automatically enabled in build_info.h (backward compatibility)
483 # even if it is disabled in config_psa_crypto_no_ecp_at_all(). As a
484 # consequence compressed points are supported in the reference
485 # component but not in the accelerated one, so they should be skipped
486 # while checking driver's coverage.
487 re.compile(r'Parse EC Key .*compressed\)'),
488 re.compile(r'Parse Public EC Key .*compressed\)'),
489 ],
490 # See ecp_light_only
491 'test_suite_ssl': [
492 'Test configuration of groups for DHE through mbedtls_ssl_conf_curves()',
493 ],
494 }
495
496class DriverVSReference_ecc_no_bignum(DriverVSReference):
497 REFERENCE = 'test_psa_crypto_config_reference_ecc_no_bignum'
498 DRIVER = 'test_psa_crypto_config_accel_ecc_no_bignum'
499 IGNORED_SUITES = [
500 # Modules replaced by drivers
501 'ecp', 'ecdsa', 'ecdh', 'ecjpake',
502 'bignum_core', 'bignum_random', 'bignum_mod', 'bignum_mod_raw',
503 'bignum.generated', 'bignum.misc',
504 ]
505 IGNORED_TESTS = {
506 'test_suite_config': [
507 re.compile(r'.*\bMBEDTLS_BIGNUM_C\b.*'),
508 re.compile(r'.*\bMBEDTLS_(ECDH|ECDSA|ECJPAKE|ECP)_.*'),
509 re.compile(r'.*\bMBEDTLS_PK_PARSE_EC_COMPRESSED\b.*'),
510 ],
511 'test_suite_platform': [
512 # Incompatible with sanitizers (e.g. ASan). If the driver
513 # component uses a sanitizer but the reference component
514 # doesn't, we have a PASS vs SKIP mismatch.
515 'Check mbedtls_calloc overallocation',
516 ],
517 # See ecp_light_only
518 'test_suite_random': [
519 'PSA classic wrapper: ECDSA signature (SECP256R1)',
520 ],
521 # See no_ecp_at_all
522 'test_suite_pkparse': [
523 re.compile(r'Parse EC Key .*compressed\)'),
524 re.compile(r'Parse Public EC Key .*compressed\)'),
525 ],
526 'test_suite_asn1parse': [
527 'INTEGER too large for mpi',
528 ],
529 'test_suite_asn1write': [
530 re.compile(r'ASN.1 Write mpi.*'),
531 ],
532 'test_suite_debug': [
533 re.compile(r'Debug print mbedtls_mpi.*'),
534 ],
535 # See ecp_light_only
536 'test_suite_ssl': [
537 'Test configuration of groups for DHE through mbedtls_ssl_conf_curves()',
538 ],
539 }
540
541class DriverVSReference_ecc_ffdh_no_bignum(DriverVSReference):
542 REFERENCE = 'test_psa_crypto_config_reference_ecc_ffdh_no_bignum'
543 DRIVER = 'test_psa_crypto_config_accel_ecc_ffdh_no_bignum'
544 IGNORED_SUITES = [
545 # Modules replaced by drivers
546 'ecp', 'ecdsa', 'ecdh', 'ecjpake', 'dhm',
547 'bignum_core', 'bignum_random', 'bignum_mod', 'bignum_mod_raw',
548 'bignum.generated', 'bignum.misc',
549 ]
550 IGNORED_TESTS = {
551 'ssl-opt': [
552 # DHE support in TLS 1.2 requires built-in MBEDTLS_DHM_C
553 # (because it needs custom groups, which PSA does not
554 # provide), even with MBEDTLS_USE_PSA_CRYPTO.
555 re.compile(r'PSK callback:.*\bdhe-psk\b.*'),
556 ],
557 'test_suite_config': [
558 re.compile(r'.*\bMBEDTLS_BIGNUM_C\b.*'),
559 re.compile(r'.*\bMBEDTLS_DHM_C\b.*'),
560 re.compile(r'.*\bMBEDTLS_(ECDH|ECDSA|ECJPAKE|ECP)_.*'),
561 re.compile(r'.*\bMBEDTLS_KEY_EXCHANGE_DHE_PSK_ENABLED\b.*'),
562 re.compile(r'.*\bMBEDTLS_PK_PARSE_EC_COMPRESSED\b.*'),
563 ],
564 'test_suite_platform': [
565 # Incompatible with sanitizers (e.g. ASan). If the driver
566 # component uses a sanitizer but the reference component
567 # doesn't, we have a PASS vs SKIP mismatch.
568 'Check mbedtls_calloc overallocation',
569 ],
570 # See ecp_light_only
571 'test_suite_random': [
572 'PSA classic wrapper: ECDSA signature (SECP256R1)',
573 ],
574 # See no_ecp_at_all
575 'test_suite_pkparse': [
576 re.compile(r'Parse EC Key .*compressed\)'),
577 re.compile(r'Parse Public EC Key .*compressed\)'),
578 ],
579 'test_suite_asn1parse': [
580 'INTEGER too large for mpi',
581 ],
582 'test_suite_asn1write': [
583 re.compile(r'ASN.1 Write mpi.*'),
584 ],
585 'test_suite_debug': [
586 re.compile(r'Debug print mbedtls_mpi.*'),
587 ],
588 # See ecp_light_only
589 'test_suite_ssl': [
590 'Test configuration of groups for DHE through mbedtls_ssl_conf_curves()',
591 ],
592 }
593
594class DriverVSReference_ffdh_alg(DriverVSReference):
595 REFERENCE = 'test_psa_crypto_config_reference_ffdh'
596 DRIVER = 'test_psa_crypto_config_accel_ffdh'
597 IGNORED_SUITES = ['dhm']
598 IGNORED_TESTS = {
599 'test_suite_config': [
600 re.compile(r'.*\bMBEDTLS_DHM_C\b.*'),
601 ],
602 'test_suite_platform': [
603 # Incompatible with sanitizers (e.g. ASan). If the driver
604 # component uses a sanitizer but the reference component
605 # doesn't, we have a PASS vs SKIP mismatch.
606 'Check mbedtls_calloc overallocation',
607 ],
608 }
609
610class DriverVSReference_tfm_config(DriverVSReference):
611 REFERENCE = 'test_tfm_config_no_p256m'
612 DRIVER = 'test_tfm_config_p256m_driver_accel_ec'
613 IGNORED_SUITES = [
614 # Modules replaced by drivers
615 'asn1parse', 'asn1write',
616 'ecp', 'ecdsa', 'ecdh', 'ecjpake',
617 'bignum_core', 'bignum_random', 'bignum_mod', 'bignum_mod_raw',
618 'bignum.generated', 'bignum.misc',
619 ]
620 IGNORED_TESTS = {
621 'test_suite_config': [
622 re.compile(r'.*\bMBEDTLS_BIGNUM_C\b.*'),
623 re.compile(r'.*\bMBEDTLS_(ASN1\w+)_C\b.*'),
624 re.compile(r'.*\bMBEDTLS_(ECDH|ECDSA|ECP)_.*'),
625 re.compile(r'.*\bMBEDTLS_PSA_P256M_DRIVER_ENABLED\b.*')
626 ],
627 'test_suite_config.crypto_combinations': [
628 'Config: ECC: Weierstrass curves only',
629 ],
630 'test_suite_platform': [
631 # Incompatible with sanitizers (e.g. ASan). If the driver
632 # component uses a sanitizer but the reference component
633 # doesn't, we have a PASS vs SKIP mismatch.
634 'Check mbedtls_calloc overallocation',
635 ],
636 # See ecp_light_only
637 'test_suite_random': [
638 'PSA classic wrapper: ECDSA signature (SECP256R1)',
639 ],
640 }
641
642class DriverVSReference_rsa(DriverVSReference):
643 REFERENCE = 'test_psa_crypto_config_reference_rsa_crypto'
644 DRIVER = 'test_psa_crypto_config_accel_rsa_crypto'
645 IGNORED_SUITES = [
646 # Modules replaced by drivers.
647 'rsa', 'pkcs1_v15', 'pkcs1_v21',
648 # We temporarily don't care about PK stuff.
649 'pk', 'pkwrite', 'pkparse'
650 ]
651 IGNORED_TESTS = {
652 'test_suite_config': [
653 re.compile(r'.*\bMBEDTLS_(PKCS1|RSA)_.*'),
654 re.compile(r'.*\bMBEDTLS_GENPRIME\b.*')
655 ],
656 'test_suite_platform': [
657 # Incompatible with sanitizers (e.g. ASan). If the driver
658 # component uses a sanitizer but the reference component
659 # doesn't, we have a PASS vs SKIP mismatch.
660 'Check mbedtls_calloc overallocation',
661 ],
662 # Following tests depend on RSA_C but are not about
663 # them really, just need to know some error code is there.
664 'test_suite_error': [
665 'Low and high error',
666 'Single high error'
667 ],
668 # Constant time operations only used for PKCS1_V15
669 'test_suite_constant_time': [
670 re.compile(r'mbedtls_ct_zeroize_if .*'),
671 re.compile(r'mbedtls_ct_memmove_left .*')
672 ],
673 'test_suite_psa_crypto': [
674 # We don't support generate_key_custom entry points
675 # in drivers yet.
676 re.compile(r'PSA generate key custom: RSA, e=.*'),
677 re.compile(r'PSA generate key ext: RSA, e=.*'),
678 ],
679 }
680
681class DriverVSReference_block_cipher_dispatch(DriverVSReference):
682 REFERENCE = 'test_full_block_cipher_legacy_dispatch'
683 DRIVER = 'test_full_block_cipher_psa_dispatch'
684 IGNORED_SUITES = [
685 # Skipped in the accelerated component
686 'aes', 'aria', 'camellia',
687 # These require AES_C, ARIA_C or CAMELLIA_C to be enabled in
688 # order for the cipher module (actually cipher_wrapper) to work
689 # properly. However these symbols are disabled in the accelerated
690 # component so we ignore them.
691 'cipher.ccm', 'cipher.gcm', 'cipher.aes', 'cipher.aria',
692 'cipher.camellia',
693 ]
694 IGNORED_TESTS = {
695 'test_suite_config': [
696 re.compile(r'.*\bMBEDTLS_(AES|ARIA|CAMELLIA)_.*'),
697 re.compile(r'.*\bMBEDTLS_AES(\w+)_C\b.*'),
698 ],
699 'test_suite_cmac': [
700 # Following tests require AES_C/ARIA_C/CAMELLIA_C to be enabled,
701 # but these are not available in the accelerated component.
702 'CMAC null arguments',
703 re.compile('CMAC.* (AES|ARIA|Camellia).*'),
704 ],
705 'test_suite_cipher.padding': [
706 # Following tests require AES_C/CAMELLIA_C to be enabled,
707 # but these are not available in the accelerated component.
708 re.compile('Set( non-existent)? padding with (AES|CAMELLIA).*'),
709 ],
710 'test_suite_pkcs5': [
711 # The AES part of PKCS#5 PBES2 is not yet supported.
712 # The rest of PKCS#5 (PBKDF2) works, though.
713 re.compile(r'PBES2 .* AES-.*')
714 ],
715 'test_suite_pkparse': [
716 # PEM (called by pkparse) requires AES_C in order to decrypt
717 # the key, but this is not available in the accelerated
718 # component.
719 re.compile('Parse RSA Key.*(password|AES-).*'),
720 ],
721 'test_suite_pem': [
722 # Following tests require AES_C, but this is diabled in the
723 # accelerated component.
724 re.compile('PEM read .*AES.*'),
725 'PEM read (unknown encryption algorithm)',
726 ],
727 'test_suite_error': [
728 # Following tests depend on AES_C but are not about them
729 # really, just need to know some error code is there.
730 'Single low error',
731 'Low and high error',
732 ],
733 'test_suite_version': [
734 # Similar to test_suite_error above.
735 'Check for MBEDTLS_AES_C when already present',
736 ],
737 'test_suite_platform': [
738 # Incompatible with sanitizers (e.g. ASan). If the driver
739 # component uses a sanitizer but the reference component
740 # doesn't, we have a PASS vs SKIP mismatch.
741 'Check mbedtls_calloc overallocation',
742 ],
743 }
744
745#pylint: enable=invalid-name,missing-class-docstring
746
747
Gilles Peskine82b16722024-09-16 19:57:10 +0200748
Przemek Stekiel6856f4c2022-11-09 10:50:29 +0100749# List of tasks with a function that can handle this task and additional arguments if required
Valerio Settidfd7ca62023-10-09 16:30:11 +0200750KNOWN_TASKS = {
Gilles Peskinef646dbf2024-09-16 19:15:29 +0200751 'analyze_coverage': CoverageTask,
Gilles Peskine9df375b2024-09-16 20:14:26 +0200752 'analyze_driver_vs_reference_hash': DriverVSReference_hash,
753 'analyze_driver_vs_reference_hmac': DriverVSReference_hmac,
754 'analyze_driver_vs_reference_cipher_aead_cmac': DriverVSReference_cipher_aead_cmac,
755 'analyze_driver_vs_reference_ecp_light_only': DriverVSReference_ecp_light_only,
756 'analyze_driver_vs_reference_no_ecp_at_all': DriverVSReference_no_ecp_at_all,
757 'analyze_driver_vs_reference_ecc_no_bignum': DriverVSReference_ecc_no_bignum,
758 'analyze_driver_vs_reference_ecc_ffdh_no_bignum': DriverVSReference_ecc_ffdh_no_bignum,
759 'analyze_driver_vs_reference_ffdh_alg': DriverVSReference_ffdh_alg,
760 'analyze_driver_vs_reference_tfm_config': DriverVSReference_tfm_config,
761 'analyze_driver_vs_reference_rsa': DriverVSReference_rsa,
762 'analyze_block_cipher_dispatch': DriverVSReference_block_cipher_dispatch,
Przemek Stekiel4d13c832022-10-26 16:11:26 +0200763}
Przemek Stekiel4d13c832022-10-26 16:11:26 +0200764
Gilles Peskine9df375b2024-09-16 20:14:26 +0200765
Gilles Peskine15c2cbf2020-06-25 18:36:28 +0200766def main():
Valerio Settif075e472023-10-17 11:03:16 +0200767 main_results = Results()
Valerio Settiaaef0bc2023-10-10 09:42:13 +0200768
Gilles Peskine15c2cbf2020-06-25 18:36:28 +0200769 try:
770 parser = argparse.ArgumentParser(description=__doc__)
Przemek Stekiel58bbc232022-10-24 08:10:10 +0200771 parser.add_argument('outcomes', metavar='OUTCOMES.CSV',
Gilles Peskine15c2cbf2020-06-25 18:36:28 +0200772 help='Outcome file to analyze')
Valerio Settidfd7ca62023-10-09 16:30:11 +0200773 parser.add_argument('specified_tasks', default='all', nargs='?',
Przemek Stekiel992de3c2022-11-09 13:54:49 +0100774 help='Analysis to be done. By default, run all tasks. '
775 'With one or more TASK, run only those. '
776 'TASK can be the name of a single task or '
Przemek Stekiel85c54ea2022-11-17 11:50:23 +0100777 'comma/space-separated list of tasks. ')
Przemek Stekiel992de3c2022-11-09 13:54:49 +0100778 parser.add_argument('--list', action='store_true',
779 help='List all available tasks and exit.')
Tomás Gonzálezb401e112023-08-11 15:22:04 +0100780 parser.add_argument('--require-full-coverage', action='store_true',
781 dest='full_coverage', help="Require all available "
782 "test cases to be executed and issue an error "
783 "otherwise. This flag is ignored if 'task' is "
784 "neither 'all' nor 'analyze_coverage'")
Gilles Peskine15c2cbf2020-06-25 18:36:28 +0200785 options = parser.parse_args()
Przemek Stekiel4e955902022-10-21 13:42:08 +0200786
Przemek Stekiel992de3c2022-11-09 13:54:49 +0100787 if options.list:
Valerio Settidfd7ca62023-10-09 16:30:11 +0200788 for task in KNOWN_TASKS:
Valerio Setti5329ff02023-10-17 09:44:36 +0200789 print(task)
Przemek Stekiel992de3c2022-11-09 13:54:49 +0100790 sys.exit(0)
791
Valerio Settidfd7ca62023-10-09 16:30:11 +0200792 if options.specified_tasks == 'all':
793 tasks_list = KNOWN_TASKS.keys()
Przemek Stekiel992de3c2022-11-09 13:54:49 +0100794 else:
Valerio Settidfd7ca62023-10-09 16:30:11 +0200795 tasks_list = re.split(r'[, ]+', options.specified_tasks)
Valerio Settidfd7ca62023-10-09 16:30:11 +0200796 for task in tasks_list:
797 if task not in KNOWN_TASKS:
Manuel Pégourié-Gonnard62d61312023-10-20 10:51:57 +0200798 sys.stderr.write('invalid task: {}\n'.format(task))
Valerio Settifb2750e2023-10-17 10:11:45 +0200799 sys.exit(2)
Przemek Stekiel992de3c2022-11-09 13:54:49 +0100800
Pengyu Lvdd1d6a72023-11-27 17:57:31 +0800801 # If the outcome file exists, parse it once and share the result
802 # among tasks to improve performance.
Pengyu Lv20e3ca32023-11-28 15:30:03 +0800803 # Otherwise, it will be generated by execute_reference_driver_tests.
804 if not os.path.exists(options.outcomes):
805 if len(tasks_list) > 1:
806 sys.stderr.write("mutiple tasks found, please provide a valid outcomes file.\n")
807 sys.exit(2)
808
809 task_name = tasks_list[0]
810 task = KNOWN_TASKS[task_name]
Gilles Peskine82b16722024-09-16 19:57:10 +0200811 if not issubclass(task, DriverVSReference):
Pengyu Lv20e3ca32023-11-28 15:30:03 +0800812 sys.stderr.write("please provide valid outcomes file for {}.\n".format(task_name))
813 sys.exit(2)
Pengyu Lv20e3ca32023-11-28 15:30:03 +0800814 execute_reference_driver_tests(main_results,
Gilles Peskine82b16722024-09-16 19:57:10 +0200815 task.REFERENCE,
816 task.DRIVER,
Pengyu Lv20e3ca32023-11-28 15:30:03 +0800817 options.outcomes)
818
819 outcomes = read_outcome_file(options.outcomes)
Pengyu Lva6cf5d62023-11-22 11:35:21 +0800820
Gilles Peskine19ef1ae2024-09-16 19:12:09 +0200821 for task_name in tasks_list:
822 task_constructor = KNOWN_TASKS[task_name]
Gilles Peskine0f31f762024-09-16 20:15:58 +0200823 task = task_constructor(options)
824 main_results.new_section(task.section_name())
825 task.run(main_results, outcomes)
Tomás Gonzálezb401e112023-08-11 15:22:04 +0100826
Valerio Settif6f64cf2023-10-17 12:28:26 +0200827 main_results.info("Overall results: {} warnings and {} errors",
828 main_results.warning_count, main_results.error_count)
Przemek Stekiel4e955902022-10-21 13:42:08 +0200829
Valerio Setti8d178be2023-10-17 12:23:55 +0200830 sys.exit(0 if (main_results.error_count == 0) else 1)
Valerio Settiaaef0bc2023-10-10 09:42:13 +0200831
Gilles Peskine15c2cbf2020-06-25 18:36:28 +0200832 except Exception: # pylint: disable=broad-except
833 # Print the backtrace and exit explicitly with our chosen status.
834 traceback.print_exc()
835 sys.exit(120)
836
837if __name__ == '__main__':
838 main()