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