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