blob: 2d7750f77e26d28057c1c5732186fa7b99da6e0c [file] [log] [blame]
Gilles Peskinef5ea1972019-01-29 08:50:20 +01001#!/usr/bin/env python3
2
3# Copyright (c) 2018, Arm Limited, All Rights Reserved.
4# SPDX-License-Identifier: Apache-2.0
5#
6# Licensed under the Apache License, Version 2.0 (the "License"); you may
7# not use this file except in compliance with the License.
8# You may obtain a copy of the License at
9#
10# http://www.apache.org/licenses/LICENSE-2.0
11#
12# Unless required by applicable law or agreed to in writing, software
13# distributed under the License is distributed on an "AS IS" BASIS, WITHOUT
14# WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
15# See the License for the specific language governing permissions and
16# limitations under the License.
17#
18# This file is part of Mbed TLS (https://tls.mbed.org)
19
20"""Test Mbed TLS with a subset of algorithms.
21"""
22
23import argparse
24import os
25import re
26import shutil
27import subprocess
28import sys
29import traceback
30
Andrzej Kurekb95ba9a2022-10-04 15:02:41 -040031class Colors: # pylint: disable=too-few-public-methods
Gilles Peskinefd1d69c2019-01-29 18:48:48 +010032 """Minimalistic support for colored output.
33Each field of an object of this class is either None if colored output
34is not possible or not desired, or a pair of strings (start, stop) such
35that outputting start switches the text color to the desired color and
36stop switches the text color back to the default."""
37 red = None
38 green = None
39 bold_red = None
40 bold_green = None
41 def __init__(self, options=None):
Andrzej Kurekb95ba9a2022-10-04 15:02:41 -040042 """Initialize color profile according to passed options."""
Gilles Peskinefd1d69c2019-01-29 18:48:48 +010043 if not options or options.color in ['no', 'never']:
44 want_color = False
45 elif options.color in ['yes', 'always']:
46 want_color = True
47 else:
48 want_color = sys.stderr.isatty()
49 if want_color:
50 # Assume ANSI compatible terminal
51 normal = '\033[0m'
52 self.red = ('\033[31m', normal)
53 self.green = ('\033[32m', normal)
54 self.bold_red = ('\033[1;31m', normal)
55 self.bold_green = ('\033[1;32m', normal)
56NO_COLORS = Colors(None)
57
58def log_line(text, prefix='depends.py:', suffix='', color=None):
Gilles Peskinef5ea1972019-01-29 08:50:20 +010059 """Print a status message."""
Andrzej Kurekb95ba9a2022-10-04 15:02:41 -040060 if color is not None:
Gilles Peskinefd1d69c2019-01-29 18:48:48 +010061 prefix = color[0] + prefix
62 suffix = suffix + color[1]
63 sys.stderr.write(prefix + ' ' + text + suffix + '\n')
Gilles Peskinee6a60db2019-01-29 18:42:55 +010064 sys.stderr.flush()
Gilles Peskinef5ea1972019-01-29 08:50:20 +010065
Gilles Peskined43ce2b2019-01-29 18:46:34 +010066def log_command(cmd):
67 """Print a trace of the specified command.
68cmd is a list of strings: a command name and its arguments."""
69 log_line(' '.join(cmd), prefix='+')
70
Gilles Peskinef5ea1972019-01-29 08:50:20 +010071def backup_config(options):
Andrzej Kurek90686252022-09-28 03:17:56 -040072 """Back up the library configuration file (mbedtls_config.h).
Gilles Peskine88e8dd62019-01-29 18:52:16 +010073If the backup file already exists, it is presumed to be the desired backup,
74so don't make another backup."""
75 if os.path.exists(options.config_backup):
76 options.own_backup = False
77 else:
78 options.own_backup = True
79 shutil.copy(options.config, options.config_backup)
Gilles Peskinef5ea1972019-01-29 08:50:20 +010080
Gilles Peskine88e8dd62019-01-29 18:52:16 +010081def restore_config(options):
Andrzej Kurek90686252022-09-28 03:17:56 -040082 """Restore the library configuration file (mbedtls_config.h).
Gilles Peskine88e8dd62019-01-29 18:52:16 +010083Remove the backup file if it was saved earlier."""
84 if options.own_backup:
Gilles Peskinef5ea1972019-01-29 08:50:20 +010085 shutil.move(options.config_backup, options.config)
86 else:
87 shutil.copy(options.config_backup, options.config)
Gilles Peskine88e8dd62019-01-29 18:52:16 +010088
Gilles Peskined43ce2b2019-01-29 18:46:34 +010089def run_config_pl(options, args):
Andrzej Kurekb95ba9a2022-10-04 15:02:41 -040090 """Run scripts/config.py with the specified arguments."""
91 cmd = ['scripts/config.py']
Andrzej Kurek90686252022-09-28 03:17:56 -040092 if options.config != 'include/mbedtls/mbedtls_config.h':
Gilles Peskined43ce2b2019-01-29 18:46:34 +010093 cmd += ['--file', options.config]
94 cmd += args
95 log_command(cmd)
96 subprocess.check_call(cmd)
Gilles Peskinef5ea1972019-01-29 08:50:20 +010097
Andrzej Kurekb95ba9a2022-10-04 15:02:41 -040098def set_reference_config(options):
99 """Change the library configuration file (mbedtls_config.h) to the reference state.
100The reference state is the one from which the tested configurations are
101derived."""
102 # Turn off memory management options that are not relevant to
103 # the tests and slow them down.
104 run_config_pl(options, ['full'])
105 run_config_pl(options, ['unset', 'MBEDTLS_MEMORY_BACKTRACE'])
106 run_config_pl(options, ['unset', 'MBEDTLS_MEMORY_BUFFER_ALLOC_C'])
107 run_config_pl(options, ['unset', 'MBEDTLS_MEMORY_DEBUG'])
108
109def collect_config_symbols(options):
110 """Read the list of settings from mbedtls_config.h.
111Return them in a generator."""
112 with open(options.config, encoding="utf-8") as config_file:
113 rx = re.compile(r'\s*(?://\s*)?#define\s+(\w+)\s*(?:$|/[/*])')
114 for line in config_file:
115 m = re.match(rx, line)
116 if m:
117 yield m.group(1)
118
Gilles Peskinef5ea1972019-01-29 08:50:20 +0100119class Job:
120 """A job builds the library in a specific configuration and runs some tests."""
121 def __init__(self, name, config_settings, commands):
122 """Build a job object.
123The job uses the configuration described by config_settings. This is a
124dictionary where the keys are preprocessor symbols and the values are
125booleans or strings. A boolean indicates whether or not to #define the
126symbol. With a string, the symbol is #define'd to that value.
127After setting the configuration, the job runs the programs specified by
128commands. This is a list of lists of strings; each list of string is a
129command name and its arguments and is passed to subprocess.call with
130shell=False."""
131 self.name = name
132 self.config_settings = config_settings
133 self.commands = commands
134
Gilles Peskinefd1d69c2019-01-29 18:48:48 +0100135 def announce(self, colors, what):
Gilles Peskinef5ea1972019-01-29 08:50:20 +0100136 '''Announce the start or completion of a job.
137If what is None, announce the start of the job.
138If what is True, announce that the job has passed.
139If what is False, announce that the job has failed.'''
140 if what is True:
Gilles Peskinefd1d69c2019-01-29 18:48:48 +0100141 log_line(self.name + ' PASSED', color=colors.green)
Gilles Peskinef5ea1972019-01-29 08:50:20 +0100142 elif what is False:
Gilles Peskinefd1d69c2019-01-29 18:48:48 +0100143 log_line(self.name + ' FAILED', color=colors.red)
Gilles Peskinef5ea1972019-01-29 08:50:20 +0100144 else:
145 log_line('starting ' + self.name)
146
Gilles Peskined43ce2b2019-01-29 18:46:34 +0100147 def configure(self, options):
Gilles Peskinef5ea1972019-01-29 08:50:20 +0100148 '''Set library configuration options as required for the job.
149config_file_name indicates which file to modify.'''
Andrzej Kurekb95ba9a2022-10-04 15:02:41 -0400150 set_reference_config(options)
Gilles Peskinef5ea1972019-01-29 08:50:20 +0100151 for key, value in sorted(self.config_settings.items()):
152 if value is True:
153 args = ['set', key]
154 elif value is False:
155 args = ['unset', key]
156 else:
157 args = ['set', key, value]
Gilles Peskined43ce2b2019-01-29 18:46:34 +0100158 run_config_pl(options, args)
Gilles Peskinef5ea1972019-01-29 08:50:20 +0100159
160 def test(self, options):
161 '''Run the job's build and test commands.
162Return True if all the commands succeed and False otherwise.
163If options.keep_going is false, stop as soon as one command fails. Otherwise
164run all the commands, except that if the first command fails, none of the
165other commands are run (typically, the first command is a build command
166and subsequent commands are tests that cannot run if the build failed).'''
167 built = False
168 success = True
169 for command in self.commands:
Gilles Peskined43ce2b2019-01-29 18:46:34 +0100170 log_command(command)
Gilles Peskinef5ea1972019-01-29 08:50:20 +0100171 ret = subprocess.call(command)
172 if ret != 0:
173 if command[0] not in ['make', options.make_command]:
174 log_line('*** [{}] Error {}'.format(' '.join(command), ret))
175 if not options.keep_going or not built:
176 return False
177 success = False
178 built = True
179 return success
180
181# SSL/TLS versions up to 1.1 and corresponding options. These require
182# both MD5 and SHA-1.
Andrzej Kurekfb3e27e2022-10-04 16:22:22 -0400183SSL_PRE_1_2_DEPENDENCIES = ['MBEDTLS_SSL_CBC_RECORD_SPLITTING',
Gilles Peskinef5ea1972019-01-29 08:50:20 +0100184 'MBEDTLS_SSL_PROTO_SSL3',
185 'MBEDTLS_SSL_PROTO_TLS1',
186 'MBEDTLS_SSL_PROTO_TLS1_1']
187
188# If the configuration option A requires B, make sure that
Andrzej Kurekfb3e27e2022-10-04 16:22:22 -0400189# B in REVERSE_DEPENDENCIES[A].
Gilles Peskineb81f4062019-01-29 19:30:40 +0100190# All the information here should be contained in check_config.h. This
191# file includes a copy because it changes rarely and it would be a pain
192# to extract automatically.
Andrzej Kurekfb3e27e2022-10-04 16:22:22 -0400193REVERSE_DEPENDENCIES = {
Gilles Peskine3ce0e322019-01-29 23:12:28 +0100194 'MBEDTLS_AES_C': ['MBEDTLS_CTR_DRBG_C',
Andrzej Kurek90686252022-09-28 03:17:56 -0400195 'MBEDTLS_NIST_KW_C'],
Gilles Peskine3ce0e322019-01-29 23:12:28 +0100196 'MBEDTLS_CHACHA20_C': ['MBEDTLS_CHACHAPOLY_C'],
Andrzej Kurek90686252022-09-28 03:17:56 -0400197 'MBEDTLS_ECDSA_C': ['MBEDTLS_KEY_EXCHANGE_ECDHE_ECDSA_ENABLED',
198 'MBEDTLS_KEY_EXCHANGE_ECDH_ECDSA_ENABLED'],
Gilles Peskinef5ea1972019-01-29 08:50:20 +0100199 'MBEDTLS_ECP_C': ['MBEDTLS_ECDSA_C',
200 'MBEDTLS_ECDH_C',
201 'MBEDTLS_ECJPAKE_C',
202 'MBEDTLS_KEY_EXCHANGE_ECDH_ECDSA_ENABLED',
203 'MBEDTLS_KEY_EXCHANGE_ECDH_RSA_ENABLED',
204 'MBEDTLS_KEY_EXCHANGE_ECDHE_PSK_ENABLED',
205 'MBEDTLS_KEY_EXCHANGE_ECDHE_RSA_ENABLED',
Andrzej Kurek90686252022-09-28 03:17:56 -0400206 'MBEDTLS_KEY_EXCHANGE_ECDHE_ECDSA_ENABLED',
207 'MBEDTLS_KEY_EXCHANGE_ECJPAKE_ENABLED'],
Gilles Peskineb81f4062019-01-29 19:30:40 +0100208 'MBEDTLS_ECP_DP_SECP256R1_ENABLED': ['MBEDTLS_KEY_EXCHANGE_ECJPAKE_ENABLED'],
Andrzej Kurekfb3e27e2022-10-04 16:22:22 -0400209 'MBEDTLS_MD5_C': SSL_PRE_1_2_DEPENDENCIES,
Gilles Peskinef5ea1972019-01-29 08:50:20 +0100210 'MBEDTLS_PKCS1_V21': ['MBEDTLS_X509_RSASSA_PSS_SUPPORT'],
211 'MBEDTLS_PKCS1_V15': ['MBEDTLS_KEY_EXCHANGE_DHE_RSA_ENABLED',
212 'MBEDTLS_KEY_EXCHANGE_ECDHE_RSA_ENABLED',
213 'MBEDTLS_KEY_EXCHANGE_RSA_PSK_ENABLED',
214 'MBEDTLS_KEY_EXCHANGE_RSA_ENABLED'],
215 'MBEDTLS_RSA_C': ['MBEDTLS_X509_RSASSA_PSS_SUPPORT',
216 'MBEDTLS_KEY_EXCHANGE_DHE_RSA_ENABLED',
217 'MBEDTLS_KEY_EXCHANGE_ECDHE_RSA_ENABLED',
218 'MBEDTLS_KEY_EXCHANGE_RSA_PSK_ENABLED',
Andrzej Kurek90686252022-09-28 03:17:56 -0400219 'MBEDTLS_KEY_EXCHANGE_RSA_ENABLED',
220 'MBEDTLS_KEY_EXCHANGE_ECDH_RSA_ENABLED'],
Andrzej Kurekfb3e27e2022-10-04 16:22:22 -0400221 'MBEDTLS_SHA1_C': SSL_PRE_1_2_DEPENDENCIES,
Gilles Peskineb81f4062019-01-29 19:30:40 +0100222 'MBEDTLS_SHA256_C': ['MBEDTLS_KEY_EXCHANGE_ECJPAKE_ENABLED',
Andrzej Kurek90686252022-09-28 03:17:56 -0400223 'MBEDTLS_ENTROPY_FORCE_SHA256',
224 'MBEDTLS_SHA224_C',
225 'MBEDTLS_SHA256_USE_A64_CRYPTO_IF_PRESENT',
226 'MBEDTLS_SHA256_USE_A64_CRYPTO_ONLY',
227 'MBEDTLS_SSL_PROTO_TLS1_3'],
228 'MBEDTLS_SHA512_C': ['MBEDTLS_SHA384_C',
229 'MBEDTLS_SHA512_USE_A64_CRYPTO_IF_PRESENT',
230 'MBEDTLS_SHA512_USE_A64_CRYPTO_ONLY'],
231 'MBEDTLS_SHA224_C': ['MBEDTLS_KEY_EXCHANGE_ECJPAKE_ENABLED',
232 'MBEDTLS_ENTROPY_FORCE_SHA256',
233 'MBEDTLS_SHA256_C',
234 'MBEDTLS_SHA256_USE_A64_CRYPTO_IF_PRESENT',
235 'MBEDTLS_SHA256_USE_A64_CRYPTO_ONLY'],
236 'MBEDTLS_SHA384_C': ['MBEDTLS_SSL_PROTO_TLS1_3'],
237 'MBEDTLS_X509_RSASSA_PSS_SUPPORT': []
Gilles Peskinef5ea1972019-01-29 08:50:20 +0100238}
239
Andrzej Kurek90686252022-09-28 03:17:56 -0400240# If an option is tested in an exclusive test, alter the following defines.
241# These are not neccesarily dependencies, but just minimal required changes
242# if a given define is the only one enabled from an exclusive group.
Andrzej Kurekfb3e27e2022-10-04 16:22:22 -0400243EXCLUSIVE_GROUPS = {
Andrzej Kurek90686252022-09-28 03:17:56 -0400244 'MBEDTLS_SHA224_C': ['MBEDTLS_SHA256_C'],
245 'MBEDTLS_SHA384_C': ['MBEDTLS_SHA512_C'],
246 'MBEDTLS_ECP_DP_CURVE448_ENABLED': ['!MBEDTLS_ECDSA_C',
Andrzej Kurek798f5c22022-10-04 11:14:59 -0400247 '!MBEDTLS_ECDSA_DETERMINISTIC',
248 '!MBEDTLS_KEY_EXCHANGE_ECDHE_ECDSA_ENABLED',
249 '!MBEDTLS_KEY_EXCHANGE_ECDH_ECDSA_ENABLED',
250 '!MBEDTLS_ECJPAKE_C',
251 '!MBEDTLS_KEY_EXCHANGE_ECJPAKE_ENABLED'],
Andrzej Kurek90686252022-09-28 03:17:56 -0400252 'MBEDTLS_ECP_DP_CURVE25519_ENABLED': ['!MBEDTLS_ECDSA_C',
Andrzej Kurek798f5c22022-10-04 11:14:59 -0400253 '!MBEDTLS_ECDSA_DETERMINISTIC',
254 '!MBEDTLS_KEY_EXCHANGE_ECDHE_ECDSA_ENABLED',
255 '!MBEDTLS_KEY_EXCHANGE_ECDH_ECDSA_ENABLED',
256 '!MBEDTLS_ECJPAKE_C',
257 '!MBEDTLS_KEY_EXCHANGE_ECJPAKE_ENABLED'],
Andrzej Kurek90686252022-09-28 03:17:56 -0400258 'MBEDTLS_ARIA_C': ['!MBEDTLS_CMAC_C'],
259 'MBEDTLS_CAMELLIA_C': ['!MBEDTLS_CMAC_C'],
260 'MBEDTLS_CHACHA20_C': ['!MBEDTLS_CMAC_C', '!MBEDTLS_CCM_C', '!MBEDTLS_GCM_C'],
261 'MBEDTLS_DES_C': ['!MBEDTLS_CCM_C', '!MBEDTLS_GCM_C'],
262}
263def handle_exclusive_groups(config_settings, symbol):
264 """For every symbol tested in an exclusive group check if there are other
265defines to be altered. """
Andrzej Kurekfb3e27e2022-10-04 16:22:22 -0400266 for dep in EXCLUSIVE_GROUPS.get(symbol, []):
Andrzej Kurek90686252022-09-28 03:17:56 -0400267 unset = dep.startswith('!')
268 if unset:
Andrzej Kurek798f5c22022-10-04 11:14:59 -0400269 dep = dep[1:]
Andrzej Kurek90686252022-09-28 03:17:56 -0400270 config_settings[dep] = not unset
271
Gilles Peskinef5ea1972019-01-29 08:50:20 +0100272def turn_off_dependencies(config_settings):
273 """For every option turned off config_settings, also turn off what depends on it.
274An option O is turned off if config_settings[O] is False."""
275 for key, value in sorted(config_settings.items()):
276 if value is not False:
277 continue
Andrzej Kurekfb3e27e2022-10-04 16:22:22 -0400278 for dep in REVERSE_DEPENDENCIES.get(key, []):
Gilles Peskinef5ea1972019-01-29 08:50:20 +0100279 config_settings[dep] = False
280
Andrzej Kurek068a73f2022-10-06 18:52:44 -0400281class BaseDomain: # pylint: disable=too-few-public-methods, unused-argument
282 """A base class for all domains."""
283 def __init__(self, symbols, commands, exclude):
284 """Initialize the jobs container"""
285 self.jobs = []
286
287class ExclusiveDomain(BaseDomain): # pylint: disable=too-few-public-methods
Gilles Peskinef5ea1972019-01-29 08:50:20 +0100288 """A domain consisting of a set of conceptually-equivalent settings.
289Establish a list of configuration symbols. For each symbol, run a test job
Andrzej Kurek2e105b52022-10-06 16:57:38 -0400290with this symbol set and the others unset."""
Gilles Peskine3dd0dab2019-01-29 18:56:03 +0100291 def __init__(self, symbols, commands, exclude=None):
292 """Build a domain for the specified list of configuration symbols.
Andrzej Kurek2e105b52022-10-06 16:57:38 -0400293The domain contains a set of jobs that enable one of the elements
294of symbols and disable the others.
Gilles Peskine3dd0dab2019-01-29 18:56:03 +0100295Each job runs the specified commands.
296If exclude is a regular expression, skip generated jobs whose description
297would match this regular expression."""
Andrzej Kurek068a73f2022-10-06 18:52:44 -0400298 super().__init__(symbols, commands, exclude)
Andrzej Kurek2e105b52022-10-06 16:57:38 -0400299 base_config_settings = {}
300 for symbol in symbols:
301 base_config_settings[symbol] = False
302 for symbol in symbols:
303 description = symbol
304 if exclude and re.match(exclude, description):
305 continue
306 config_settings = base_config_settings.copy()
307 config_settings[symbol] = True
308 handle_exclusive_groups(config_settings, symbol)
309 turn_off_dependencies(config_settings)
310 job = Job(description, config_settings, commands)
311 self.jobs.append(job)
Gilles Peskinef5ea1972019-01-29 08:50:20 +0100312
Andrzej Kurek068a73f2022-10-06 18:52:44 -0400313class ComplementaryDomain(BaseDomain): # pylint: disable=too-few-public-methods
Gilles Peskinef5ea1972019-01-29 08:50:20 +0100314 """A domain consisting of a set of loosely-related settings.
315Establish a list of configuration symbols. For each symbol, run a test job
316with this symbol unset."""
Andrzej Kurek068a73f2022-10-06 18:52:44 -0400317 def __init__(self, symbols, commands, exclude=None):
Gilles Peskine3dd0dab2019-01-29 18:56:03 +0100318 """Build a domain for the specified list of configuration symbols.
319Each job in the domain disables one of the specified symbols.
320Each job runs the specified commands."""
Andrzej Kurek068a73f2022-10-06 18:52:44 -0400321 super().__init__(symbols, commands, exclude)
Gilles Peskinef5ea1972019-01-29 08:50:20 +0100322 for symbol in symbols:
323 description = '!' + symbol
Andrzej Kurek068a73f2022-10-06 18:52:44 -0400324 if exclude and re.match(exclude, description):
325 continue
Gilles Peskinef5ea1972019-01-29 08:50:20 +0100326 config_settings = {symbol: False}
327 turn_off_dependencies(config_settings)
328 job = Job(description, config_settings, commands)
329 self.jobs.append(job)
330
Andrzej Kurek068a73f2022-10-06 18:52:44 -0400331class DualDomain(ExclusiveDomain, ComplementaryDomain): # pylint: disable=too-few-public-methods
332 """A domain that contains both the ExclusiveDomain and BaseDomain tests"""
333 def __init__(self, symbols, commands, exclude=None):
334 super().__init__(symbols=symbols, commands=commands, exclude=exclude)
335
Andrzej Kurekb95ba9a2022-10-04 15:02:41 -0400336class CipherInfo: # pylint: disable=too-few-public-methods
Gilles Peskine3ce0e322019-01-29 23:12:28 +0100337 """Collect data about cipher.h."""
Andrzej Kurekb95ba9a2022-10-04 15:02:41 -0400338 def __init__(self):
Gilles Peskine3ce0e322019-01-29 23:12:28 +0100339 self.base_symbols = set()
Andrzej Kurekb95ba9a2022-10-04 15:02:41 -0400340 with open('include/mbedtls/cipher.h', encoding="utf-8") as fh:
Gilles Peskine3ce0e322019-01-29 23:12:28 +0100341 for line in fh:
342 m = re.match(r' *MBEDTLS_CIPHER_ID_(\w+),', line)
343 if m and m.group(1) not in ['NONE', 'NULL', '3DES']:
344 self.base_symbols.add('MBEDTLS_' + m.group(1) + '_C')
345
Gilles Peskinef5ea1972019-01-29 08:50:20 +0100346class DomainData:
Andrzej Kurekb95ba9a2022-10-04 15:02:41 -0400347 """A container for domains and jobs, used to structurize testing."""
Gilles Peskinef5ea1972019-01-29 08:50:20 +0100348 def config_symbols_matching(self, regexp):
Andrzej Kurek90686252022-09-28 03:17:56 -0400349 """List the mbedtls_config.h settings matching regexp."""
Gilles Peskinef5ea1972019-01-29 08:50:20 +0100350 return [symbol for symbol in self.all_config_symbols
351 if re.match(regexp, symbol)]
352
353 def __init__(self, options):
354 """Gather data about the library and establish a list of domains to test."""
355 build_command = [options.make_command, 'CFLAGS=-Werror']
356 build_and_test = [build_command, [options.make_command, 'test']]
Andrzej Kurekb95ba9a2022-10-04 15:02:41 -0400357 self.all_config_symbols = set(collect_config_symbols(options))
Gilles Peskinef5ea1972019-01-29 08:50:20 +0100358 # Find hash modules by name.
359 hash_symbols = self.config_symbols_matching(r'MBEDTLS_(MD|RIPEMD|SHA)[0-9]+_C\Z')
360 # Find elliptic curve enabling macros by name.
361 curve_symbols = self.config_symbols_matching(r'MBEDTLS_ECP_DP_\w+_ENABLED\Z')
362 # Find key exchange enabling macros by name.
363 key_exchange_symbols = self.config_symbols_matching(r'MBEDTLS_KEY_EXCHANGE_\w+_ENABLED\Z')
Gilles Peskine3ce0e322019-01-29 23:12:28 +0100364 # Find cipher IDs (block permutations and stream ciphers --- chaining
365 # and padding modes are exercised separately) information by parsing
Andrzej Kurek90686252022-09-28 03:17:56 -0400366 # cipher.h, as the information is not readily available in mbedtls_config.h.
367
Andrzej Kurekb95ba9a2022-10-04 15:02:41 -0400368 cipher_info = CipherInfo()
Gilles Peskine3ce0e322019-01-29 23:12:28 +0100369 # Find block cipher chaining and padding mode enabling macros by name.
370 cipher_chaining_symbols = self.config_symbols_matching(r'MBEDTLS_CIPHER_MODE_\w+\Z')
371 cipher_padding_symbols = self.config_symbols_matching(r'MBEDTLS_CIPHER_PADDING_\w+\Z')
Gilles Peskinef5ea1972019-01-29 08:50:20 +0100372 self.domains = {
Gilles Peskine3ce0e322019-01-29 23:12:28 +0100373 # Cipher IDs, chaining modes and padding modes. Run the test suites.
374 'cipher_id': ExclusiveDomain(cipher_info.base_symbols,
375 build_and_test),
376 'cipher_chaining': ExclusiveDomain(cipher_chaining_symbols,
377 build_and_test),
378 'cipher_padding': ExclusiveDomain(cipher_padding_symbols,
379 build_and_test),
Gilles Peskinef5ea1972019-01-29 08:50:20 +0100380 # Elliptic curves. Run the test suites.
381 'curves': ExclusiveDomain(curve_symbols, build_and_test),
382 # Hash algorithms. Exclude configurations with only one
Andrzej Kurek90686252022-09-28 03:17:56 -0400383 # hash which is obsolete. Run the test suites. Exclude
384 # SHA512 and SHA256, as these are tested with SHA384 and SHA224.
Andrzej Kurek068a73f2022-10-06 18:52:44 -0400385 'hashes': DualDomain(hash_symbols, build_and_test,
386 exclude=r'MBEDTLS_(MD|RIPEMD|SHA1_|SHA256_|SHA512_)' \
387 '|!MBEDTLS_(SHA256_|SHA512_)'),
Gilles Peskine7088a732019-01-29 19:33:05 +0100388 # Key exchange types. Only build the library and the sample
389 # programs.
390 'kex': ExclusiveDomain(key_exchange_symbols,
391 [build_command + ['lib'],
392 build_command + ['-C', 'programs']]),
Gilles Peskinef5ea1972019-01-29 08:50:20 +0100393 'pkalgs': ComplementaryDomain(['MBEDTLS_ECDSA_C',
394 'MBEDTLS_ECP_C',
395 'MBEDTLS_PKCS1_V21',
396 'MBEDTLS_PKCS1_V15',
397 'MBEDTLS_RSA_C',
398 'MBEDTLS_X509_RSASSA_PSS_SUPPORT'],
399 build_and_test),
400 }
401 self.jobs = {}
402 for domain in self.domains.values():
403 for job in domain.jobs:
404 self.jobs[job.name] = job
405
406 def get_jobs(self, name):
407 """Return the list of jobs identified by the given name.
408A name can either be the name of a domain or the name of one specific job."""
409 if name in self.domains:
410 return sorted(self.domains[name].jobs, key=lambda job: job.name)
411 else:
412 return [self.jobs[name]]
413
Gilles Peskinefd1d69c2019-01-29 18:48:48 +0100414def run(options, job, colors=NO_COLORS):
Gilles Peskinef5ea1972019-01-29 08:50:20 +0100415 """Run the specified job (a Job instance)."""
416 subprocess.check_call([options.make_command, 'clean'])
Gilles Peskinefd1d69c2019-01-29 18:48:48 +0100417 job.announce(colors, None)
Gilles Peskined43ce2b2019-01-29 18:46:34 +0100418 job.configure(options)
Gilles Peskinef5ea1972019-01-29 08:50:20 +0100419 success = job.test(options)
Gilles Peskinefd1d69c2019-01-29 18:48:48 +0100420 job.announce(colors, success)
Gilles Peskinef5ea1972019-01-29 08:50:20 +0100421 return success
422
Andrzej Kurekb95ba9a2022-10-04 15:02:41 -0400423def run_tests(options, domain_data):
Gilles Peskinef5ea1972019-01-29 08:50:20 +0100424 """Run the desired jobs.
425domain_data should be a DomainData instance that describes the available
426domains and jobs.
427Run the jobs listed in options.domains."""
428 if not hasattr(options, 'config_backup'):
429 options.config_backup = options.config + '.bak'
Gilles Peskinefd1d69c2019-01-29 18:48:48 +0100430 colors = Colors(options)
Gilles Peskinef5ea1972019-01-29 08:50:20 +0100431 jobs = []
432 failures = []
433 successes = []
434 for name in options.domains:
435 jobs += domain_data.get_jobs(name)
436 backup_config(options)
437 try:
438 for job in jobs:
Gilles Peskinefd1d69c2019-01-29 18:48:48 +0100439 success = run(options, job, colors=colors)
Gilles Peskinef5ea1972019-01-29 08:50:20 +0100440 if not success:
441 if options.keep_going:
442 failures.append(job.name)
443 else:
444 return False
445 else:
446 successes.append(job.name)
Gilles Peskine88e8dd62019-01-29 18:52:16 +0100447 restore_config(options)
448 except:
449 # Restore the configuration, except in stop-on-error mode if there
450 # was an error, where we leave the failing configuration up for
451 # developer convenience.
Gilles Peskinef5ea1972019-01-29 08:50:20 +0100452 if options.keep_going:
Gilles Peskine88e8dd62019-01-29 18:52:16 +0100453 restore_config(options)
454 raise
Gilles Peskinedc68f612019-01-29 18:50:03 +0100455 if successes:
456 log_line('{} passed'.format(' '.join(successes)), color=colors.bold_green)
Gilles Peskinef5ea1972019-01-29 08:50:20 +0100457 if failures:
Gilles Peskinedc68f612019-01-29 18:50:03 +0100458 log_line('{} FAILED'.format(' '.join(failures)), color=colors.bold_red)
Gilles Peskinef5ea1972019-01-29 08:50:20 +0100459 return False
460 else:
Gilles Peskinef5ea1972019-01-29 08:50:20 +0100461 return True
462
Andrzej Kurekb95ba9a2022-10-04 15:02:41 -0400463def main():
Gilles Peskinef5ea1972019-01-29 08:50:20 +0100464 try:
465 parser = argparse.ArgumentParser(description=__doc__)
Gilles Peskinefd1d69c2019-01-29 18:48:48 +0100466 parser.add_argument('--color', metavar='WHEN',
467 help='Colorize the output (always/auto/never)',
468 choices=['always', 'auto', 'never'], default='auto')
Gilles Peskinef5ea1972019-01-29 08:50:20 +0100469 parser.add_argument('-c', '--config', metavar='FILE',
470 help='Configuration file to modify',
Andrzej Kurek90686252022-09-28 03:17:56 -0400471 default='include/mbedtls/mbedtls_config.h')
Gilles Peskinef5ea1972019-01-29 08:50:20 +0100472 parser.add_argument('-C', '--directory', metavar='DIR',
473 help='Change to this directory before anything else',
474 default='.')
475 parser.add_argument('-k', '--keep-going',
476 help='Try all configurations even if some fail (default)',
477 action='store_true', dest='keep_going', default=True)
478 parser.add_argument('-e', '--no-keep-going',
479 help='Stop as soon as a configuration fails',
480 action='store_false', dest='keep_going')
481 parser.add_argument('--list-jobs',
482 help='List supported jobs and exit',
483 action='append_const', dest='list', const='jobs')
484 parser.add_argument('--list-domains',
485 help='List supported domains and exit',
486 action='append_const', dest='list', const='domains')
487 parser.add_argument('--make-command', metavar='CMD',
488 help='Command to run instead of make (e.g. gmake)',
489 action='store', default='make')
490 parser.add_argument('domains', metavar='DOMAIN', nargs='*',
Andrzej Kurekb95ba9a2022-10-04 15:02:41 -0400491 help='The domain(s) to test (default: all). This can \
492 be also a list of jobs to run.',
Gilles Peskinef5ea1972019-01-29 08:50:20 +0100493 default=True)
494 options = parser.parse_args()
495 os.chdir(options.directory)
496 domain_data = DomainData(options)
Andrzej Kurekb95ba9a2022-10-04 15:02:41 -0400497 if options.domains is True:
Gilles Peskinef5ea1972019-01-29 08:50:20 +0100498 options.domains = sorted(domain_data.domains.keys())
499 if options.list:
Andrzej Kurekb95ba9a2022-10-04 15:02:41 -0400500 for arg in options.list:
501 for domain_name in sorted(getattr(domain_data, arg).keys()):
502 print(domain_name)
503 sys.exit(0)
Gilles Peskinef5ea1972019-01-29 08:50:20 +0100504 else:
Andrzej Kurekb95ba9a2022-10-04 15:02:41 -0400505 sys.exit(0 if run_tests(options, domain_data) else 1)
506 except Exception: # pylint: disable=broad-except
Gilles Peskinef5ea1972019-01-29 08:50:20 +0100507 traceback.print_exc()
Andrzej Kurekb95ba9a2022-10-04 15:02:41 -0400508 sys.exit(3)
509
510if __name__ == '__main__':
511 main()