blob: 6a1c171c9411527af723252f41f687975ad86ef5 [file] [log] [blame]
Gilles Peskineb39e3ec2019-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 Kurek3322c222022-10-04 15:02:41 -040031class Colors: # pylint: disable=too-few-public-methods
Gilles Peskine0fa7cbe2019-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 Kurek3322c222022-10-04 15:02:41 -040042 """Initialize color profile according to passed options."""
Gilles Peskine0fa7cbe2019-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 Peskineb39e3ec2019-01-29 08:50:20 +010059 """Print a status message."""
Andrzej Kurek3322c222022-10-04 15:02:41 -040060 if color is not None:
Gilles Peskine0fa7cbe2019-01-29 18:48:48 +010061 prefix = color[0] + prefix
62 suffix = suffix + color[1]
63 sys.stderr.write(prefix + ' ' + text + suffix + '\n')
Gilles Peskine46c82562019-01-29 18:42:55 +010064 sys.stderr.flush()
Gilles Peskineb39e3ec2019-01-29 08:50:20 +010065
Gilles Peskine54aa5c62019-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 Peskineb39e3ec2019-01-29 08:50:20 +010071def backup_config(options):
Andrzej Kureke05b17f2022-09-28 03:17:56 -040072 """Back up the library configuration file (mbedtls_config.h).
Gilles Peskinebf7537d2019-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 Peskineb39e3ec2019-01-29 08:50:20 +010080
Gilles Peskinebf7537d2019-01-29 18:52:16 +010081def restore_config(options):
Andrzej Kureke05b17f2022-09-28 03:17:56 -040082 """Restore the library configuration file (mbedtls_config.h).
Gilles Peskinebf7537d2019-01-29 18:52:16 +010083Remove the backup file if it was saved earlier."""
84 if options.own_backup:
Gilles Peskineb39e3ec2019-01-29 08:50:20 +010085 shutil.move(options.config_backup, options.config)
86 else:
87 shutil.copy(options.config_backup, options.config)
Gilles Peskinebf7537d2019-01-29 18:52:16 +010088
Gilles Peskine54aa5c62019-01-29 18:46:34 +010089def run_config_pl(options, args):
Andrzej Kurek3322c222022-10-04 15:02:41 -040090 """Run scripts/config.py with the specified arguments."""
91 cmd = ['scripts/config.py']
Andrzej Kureke05b17f2022-09-28 03:17:56 -040092 if options.config != 'include/mbedtls/mbedtls_config.h':
Gilles Peskine54aa5c62019-01-29 18:46:34 +010093 cmd += ['--file', options.config]
94 cmd += args
95 log_command(cmd)
96 subprocess.check_call(cmd)
Gilles Peskineb39e3ec2019-01-29 08:50:20 +010097
Andrzej Kurek3322c222022-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'])
Andrzej Kurek2f8ac282022-10-07 16:07:58 -0400108 run_config_pl(options, ['unset', 'MBEDTLS_TEST_HOOKS'])
Andrzej Kurek3322c222022-10-04 15:02:41 -0400109
110def collect_config_symbols(options):
111 """Read the list of settings from mbedtls_config.h.
112Return them in a generator."""
113 with open(options.config, encoding="utf-8") as config_file:
114 rx = re.compile(r'\s*(?://\s*)?#define\s+(\w+)\s*(?:$|/[/*])')
115 for line in config_file:
116 m = re.match(rx, line)
117 if m:
118 yield m.group(1)
119
Gilles Peskineb39e3ec2019-01-29 08:50:20 +0100120class Job:
121 """A job builds the library in a specific configuration and runs some tests."""
122 def __init__(self, name, config_settings, commands):
123 """Build a job object.
124The job uses the configuration described by config_settings. This is a
125dictionary where the keys are preprocessor symbols and the values are
126booleans or strings. A boolean indicates whether or not to #define the
127symbol. With a string, the symbol is #define'd to that value.
128After setting the configuration, the job runs the programs specified by
129commands. This is a list of lists of strings; each list of string is a
130command name and its arguments and is passed to subprocess.call with
131shell=False."""
132 self.name = name
133 self.config_settings = config_settings
134 self.commands = commands
135
Gilles Peskine0fa7cbe2019-01-29 18:48:48 +0100136 def announce(self, colors, what):
Gilles Peskineb39e3ec2019-01-29 08:50:20 +0100137 '''Announce the start or completion of a job.
138If what is None, announce the start of the job.
139If what is True, announce that the job has passed.
140If what is False, announce that the job has failed.'''
141 if what is True:
Gilles Peskine0fa7cbe2019-01-29 18:48:48 +0100142 log_line(self.name + ' PASSED', color=colors.green)
Gilles Peskineb39e3ec2019-01-29 08:50:20 +0100143 elif what is False:
Gilles Peskine0fa7cbe2019-01-29 18:48:48 +0100144 log_line(self.name + ' FAILED', color=colors.red)
Gilles Peskineb39e3ec2019-01-29 08:50:20 +0100145 else:
146 log_line('starting ' + self.name)
147
Gilles Peskine54aa5c62019-01-29 18:46:34 +0100148 def configure(self, options):
Gilles Peskineb39e3ec2019-01-29 08:50:20 +0100149 '''Set library configuration options as required for the job.
150config_file_name indicates which file to modify.'''
Andrzej Kurek3322c222022-10-04 15:02:41 -0400151 set_reference_config(options)
Gilles Peskineb39e3ec2019-01-29 08:50:20 +0100152 for key, value in sorted(self.config_settings.items()):
153 if value is True:
154 args = ['set', key]
155 elif value is False:
156 args = ['unset', key]
157 else:
158 args = ['set', key, value]
Gilles Peskine54aa5c62019-01-29 18:46:34 +0100159 run_config_pl(options, args)
Gilles Peskineb39e3ec2019-01-29 08:50:20 +0100160
161 def test(self, options):
162 '''Run the job's build and test commands.
163Return True if all the commands succeed and False otherwise.
164If options.keep_going is false, stop as soon as one command fails. Otherwise
165run all the commands, except that if the first command fails, none of the
166other commands are run (typically, the first command is a build command
167and subsequent commands are tests that cannot run if the build failed).'''
168 built = False
169 success = True
170 for command in self.commands:
Gilles Peskine54aa5c62019-01-29 18:46:34 +0100171 log_command(command)
Gilles Peskineb39e3ec2019-01-29 08:50:20 +0100172 ret = subprocess.call(command)
173 if ret != 0:
174 if command[0] not in ['make', options.make_command]:
175 log_line('*** [{}] Error {}'.format(' '.join(command), ret))
176 if not options.keep_going or not built:
177 return False
178 success = False
179 built = True
180 return success
181
182# SSL/TLS versions up to 1.1 and corresponding options. These require
183# both MD5 and SHA-1.
Andrzej Kurek202932f2022-10-04 16:22:22 -0400184SSL_PRE_1_2_DEPENDENCIES = ['MBEDTLS_SSL_CBC_RECORD_SPLITTING',
Gilles Peskineb39e3ec2019-01-29 08:50:20 +0100185 'MBEDTLS_SSL_PROTO_SSL3',
186 'MBEDTLS_SSL_PROTO_TLS1',
187 'MBEDTLS_SSL_PROTO_TLS1_1']
188
189# If the configuration option A requires B, make sure that
Andrzej Kurek202932f2022-10-04 16:22:22 -0400190# B in REVERSE_DEPENDENCIES[A].
Gilles Peskine584c24a2019-01-29 19:30:40 +0100191# All the information here should be contained in check_config.h. This
192# file includes a copy because it changes rarely and it would be a pain
193# to extract automatically.
Andrzej Kurek202932f2022-10-04 16:22:22 -0400194REVERSE_DEPENDENCIES = {
Gilles Peskine34a15572019-01-29 23:12:28 +0100195 'MBEDTLS_AES_C': ['MBEDTLS_CTR_DRBG_C',
Andrzej Kureke05b17f2022-09-28 03:17:56 -0400196 'MBEDTLS_NIST_KW_C'],
Gilles Peskine34a15572019-01-29 23:12:28 +0100197 'MBEDTLS_CHACHA20_C': ['MBEDTLS_CHACHAPOLY_C'],
Andrzej Kureke05b17f2022-09-28 03:17:56 -0400198 'MBEDTLS_ECDSA_C': ['MBEDTLS_KEY_EXCHANGE_ECDHE_ECDSA_ENABLED',
199 'MBEDTLS_KEY_EXCHANGE_ECDH_ECDSA_ENABLED'],
Gilles Peskineb39e3ec2019-01-29 08:50:20 +0100200 'MBEDTLS_ECP_C': ['MBEDTLS_ECDSA_C',
201 'MBEDTLS_ECDH_C',
202 'MBEDTLS_ECJPAKE_C',
203 'MBEDTLS_KEY_EXCHANGE_ECDH_ECDSA_ENABLED',
204 'MBEDTLS_KEY_EXCHANGE_ECDH_RSA_ENABLED',
205 'MBEDTLS_KEY_EXCHANGE_ECDHE_PSK_ENABLED',
206 'MBEDTLS_KEY_EXCHANGE_ECDHE_RSA_ENABLED',
Andrzej Kureke05b17f2022-09-28 03:17:56 -0400207 'MBEDTLS_KEY_EXCHANGE_ECDHE_ECDSA_ENABLED',
208 'MBEDTLS_KEY_EXCHANGE_ECJPAKE_ENABLED'],
Gilles Peskine584c24a2019-01-29 19:30:40 +0100209 'MBEDTLS_ECP_DP_SECP256R1_ENABLED': ['MBEDTLS_KEY_EXCHANGE_ECJPAKE_ENABLED'],
Andrzej Kurek202932f2022-10-04 16:22:22 -0400210 'MBEDTLS_MD5_C': SSL_PRE_1_2_DEPENDENCIES,
Gilles Peskineb39e3ec2019-01-29 08:50:20 +0100211 'MBEDTLS_PKCS1_V21': ['MBEDTLS_X509_RSASSA_PSS_SUPPORT'],
212 'MBEDTLS_PKCS1_V15': ['MBEDTLS_KEY_EXCHANGE_DHE_RSA_ENABLED',
213 'MBEDTLS_KEY_EXCHANGE_ECDHE_RSA_ENABLED',
214 'MBEDTLS_KEY_EXCHANGE_RSA_PSK_ENABLED',
215 'MBEDTLS_KEY_EXCHANGE_RSA_ENABLED'],
216 'MBEDTLS_RSA_C': ['MBEDTLS_X509_RSASSA_PSS_SUPPORT',
217 'MBEDTLS_KEY_EXCHANGE_DHE_RSA_ENABLED',
218 'MBEDTLS_KEY_EXCHANGE_ECDHE_RSA_ENABLED',
219 'MBEDTLS_KEY_EXCHANGE_RSA_PSK_ENABLED',
Andrzej Kureke05b17f2022-09-28 03:17:56 -0400220 'MBEDTLS_KEY_EXCHANGE_RSA_ENABLED',
221 'MBEDTLS_KEY_EXCHANGE_ECDH_RSA_ENABLED'],
Andrzej Kurek202932f2022-10-04 16:22:22 -0400222 'MBEDTLS_SHA1_C': SSL_PRE_1_2_DEPENDENCIES,
Gilles Peskine584c24a2019-01-29 19:30:40 +0100223 'MBEDTLS_SHA256_C': ['MBEDTLS_KEY_EXCHANGE_ECJPAKE_ENABLED',
Andrzej Kureke05b17f2022-09-28 03:17:56 -0400224 'MBEDTLS_ENTROPY_FORCE_SHA256',
225 'MBEDTLS_SHA224_C',
226 'MBEDTLS_SHA256_USE_A64_CRYPTO_IF_PRESENT',
227 'MBEDTLS_SHA256_USE_A64_CRYPTO_ONLY',
228 'MBEDTLS_SSL_PROTO_TLS1_3'],
229 'MBEDTLS_SHA512_C': ['MBEDTLS_SHA384_C',
230 'MBEDTLS_SHA512_USE_A64_CRYPTO_IF_PRESENT',
231 'MBEDTLS_SHA512_USE_A64_CRYPTO_ONLY'],
232 'MBEDTLS_SHA224_C': ['MBEDTLS_KEY_EXCHANGE_ECJPAKE_ENABLED',
233 'MBEDTLS_ENTROPY_FORCE_SHA256',
234 'MBEDTLS_SHA256_C',
235 'MBEDTLS_SHA256_USE_A64_CRYPTO_IF_PRESENT',
236 'MBEDTLS_SHA256_USE_A64_CRYPTO_ONLY'],
237 'MBEDTLS_SHA384_C': ['MBEDTLS_SSL_PROTO_TLS1_3'],
238 'MBEDTLS_X509_RSASSA_PSS_SUPPORT': []
Gilles Peskineb39e3ec2019-01-29 08:50:20 +0100239}
240
Andrzej Kureke05b17f2022-09-28 03:17:56 -0400241# If an option is tested in an exclusive test, alter the following defines.
242# These are not neccesarily dependencies, but just minimal required changes
243# if a given define is the only one enabled from an exclusive group.
Andrzej Kurek202932f2022-10-04 16:22:22 -0400244EXCLUSIVE_GROUPS = {
Andrzej Kureke05b17f2022-09-28 03:17:56 -0400245 'MBEDTLS_SHA224_C': ['MBEDTLS_SHA256_C'],
246 'MBEDTLS_SHA384_C': ['MBEDTLS_SHA512_C'],
Andrzej Kurekeabeb302022-10-17 07:52:51 -0400247 'MBEDTLS_SHA512_C': ['!MBEDTLS_SSL_COOKIE_C'],
Andrzej Kureke05b17f2022-09-28 03:17:56 -0400248 'MBEDTLS_ECP_DP_CURVE448_ENABLED': ['!MBEDTLS_ECDSA_C',
Andrzej Kurek0e8b2d72022-10-04 11:14:59 -0400249 '!MBEDTLS_ECDSA_DETERMINISTIC',
250 '!MBEDTLS_KEY_EXCHANGE_ECDHE_ECDSA_ENABLED',
251 '!MBEDTLS_KEY_EXCHANGE_ECDH_ECDSA_ENABLED',
252 '!MBEDTLS_ECJPAKE_C',
253 '!MBEDTLS_KEY_EXCHANGE_ECJPAKE_ENABLED'],
Andrzej Kureke05b17f2022-09-28 03:17:56 -0400254 'MBEDTLS_ECP_DP_CURVE25519_ENABLED': ['!MBEDTLS_ECDSA_C',
Andrzej Kurek0e8b2d72022-10-04 11:14:59 -0400255 '!MBEDTLS_ECDSA_DETERMINISTIC',
256 '!MBEDTLS_KEY_EXCHANGE_ECDHE_ECDSA_ENABLED',
257 '!MBEDTLS_KEY_EXCHANGE_ECDH_ECDSA_ENABLED',
258 '!MBEDTLS_ECJPAKE_C',
259 '!MBEDTLS_KEY_EXCHANGE_ECJPAKE_ENABLED'],
Andrzej Kureke05b17f2022-09-28 03:17:56 -0400260 'MBEDTLS_ARIA_C': ['!MBEDTLS_CMAC_C'],
261 'MBEDTLS_CAMELLIA_C': ['!MBEDTLS_CMAC_C'],
262 'MBEDTLS_CHACHA20_C': ['!MBEDTLS_CMAC_C', '!MBEDTLS_CCM_C', '!MBEDTLS_GCM_C'],
263 'MBEDTLS_DES_C': ['!MBEDTLS_CCM_C', '!MBEDTLS_GCM_C'],
264}
265def handle_exclusive_groups(config_settings, symbol):
266 """For every symbol tested in an exclusive group check if there are other
267defines to be altered. """
Andrzej Kurek202932f2022-10-04 16:22:22 -0400268 for dep in EXCLUSIVE_GROUPS.get(symbol, []):
Andrzej Kureke05b17f2022-09-28 03:17:56 -0400269 unset = dep.startswith('!')
270 if unset:
Andrzej Kurek0e8b2d72022-10-04 11:14:59 -0400271 dep = dep[1:]
Andrzej Kureke05b17f2022-09-28 03:17:56 -0400272 config_settings[dep] = not unset
273
Gilles Peskineb39e3ec2019-01-29 08:50:20 +0100274def turn_off_dependencies(config_settings):
275 """For every option turned off config_settings, also turn off what depends on it.
276An option O is turned off if config_settings[O] is False."""
277 for key, value in sorted(config_settings.items()):
278 if value is not False:
279 continue
Andrzej Kurek202932f2022-10-04 16:22:22 -0400280 for dep in REVERSE_DEPENDENCIES.get(key, []):
Gilles Peskineb39e3ec2019-01-29 08:50:20 +0100281 config_settings[dep] = False
282
Andrzej Kurek228b12c2022-10-06 18:52:44 -0400283class BaseDomain: # pylint: disable=too-few-public-methods, unused-argument
284 """A base class for all domains."""
285 def __init__(self, symbols, commands, exclude):
286 """Initialize the jobs container"""
287 self.jobs = []
288
289class ExclusiveDomain(BaseDomain): # pylint: disable=too-few-public-methods
Gilles Peskineb39e3ec2019-01-29 08:50:20 +0100290 """A domain consisting of a set of conceptually-equivalent settings.
291Establish a list of configuration symbols. For each symbol, run a test job
Andrzej Kurekfe469492022-10-06 16:57:38 -0400292with this symbol set and the others unset."""
Gilles Peskineb1284cf2019-01-29 18:56:03 +0100293 def __init__(self, symbols, commands, exclude=None):
294 """Build a domain for the specified list of configuration symbols.
Andrzej Kurekfe469492022-10-06 16:57:38 -0400295The domain contains a set of jobs that enable one of the elements
296of symbols and disable the others.
Gilles Peskineb1284cf2019-01-29 18:56:03 +0100297Each job runs the specified commands.
298If exclude is a regular expression, skip generated jobs whose description
299would match this regular expression."""
Andrzej Kurek228b12c2022-10-06 18:52:44 -0400300 super().__init__(symbols, commands, exclude)
Andrzej Kurekfe469492022-10-06 16:57:38 -0400301 base_config_settings = {}
302 for symbol in symbols:
303 base_config_settings[symbol] = False
304 for symbol in symbols:
305 description = symbol
306 if exclude and re.match(exclude, description):
307 continue
308 config_settings = base_config_settings.copy()
309 config_settings[symbol] = True
310 handle_exclusive_groups(config_settings, symbol)
311 turn_off_dependencies(config_settings)
312 job = Job(description, config_settings, commands)
313 self.jobs.append(job)
Gilles Peskineb39e3ec2019-01-29 08:50:20 +0100314
Andrzej Kurek228b12c2022-10-06 18:52:44 -0400315class ComplementaryDomain(BaseDomain): # pylint: disable=too-few-public-methods
Gilles Peskineb39e3ec2019-01-29 08:50:20 +0100316 """A domain consisting of a set of loosely-related settings.
317Establish a list of configuration symbols. For each symbol, run a test job
318with this symbol unset."""
Andrzej Kurek228b12c2022-10-06 18:52:44 -0400319 def __init__(self, symbols, commands, exclude=None):
Gilles Peskineb1284cf2019-01-29 18:56:03 +0100320 """Build a domain for the specified list of configuration symbols.
321Each job in the domain disables one of the specified symbols.
322Each job runs the specified commands."""
Andrzej Kurek228b12c2022-10-06 18:52:44 -0400323 super().__init__(symbols, commands, exclude)
Gilles Peskineb39e3ec2019-01-29 08:50:20 +0100324 for symbol in symbols:
325 description = '!' + symbol
Andrzej Kurek228b12c2022-10-06 18:52:44 -0400326 if exclude and re.match(exclude, description):
327 continue
Gilles Peskineb39e3ec2019-01-29 08:50:20 +0100328 config_settings = {symbol: False}
329 turn_off_dependencies(config_settings)
330 job = Job(description, config_settings, commands)
331 self.jobs.append(job)
332
Andrzej Kurek228b12c2022-10-06 18:52:44 -0400333class DualDomain(ExclusiveDomain, ComplementaryDomain): # pylint: disable=too-few-public-methods
334 """A domain that contains both the ExclusiveDomain and BaseDomain tests"""
335 def __init__(self, symbols, commands, exclude=None):
336 super().__init__(symbols=symbols, commands=commands, exclude=exclude)
337
Andrzej Kurek3322c222022-10-04 15:02:41 -0400338class CipherInfo: # pylint: disable=too-few-public-methods
Gilles Peskine34a15572019-01-29 23:12:28 +0100339 """Collect data about cipher.h."""
Andrzej Kurek3322c222022-10-04 15:02:41 -0400340 def __init__(self):
Gilles Peskine34a15572019-01-29 23:12:28 +0100341 self.base_symbols = set()
Andrzej Kurek3322c222022-10-04 15:02:41 -0400342 with open('include/mbedtls/cipher.h', encoding="utf-8") as fh:
Gilles Peskine34a15572019-01-29 23:12:28 +0100343 for line in fh:
344 m = re.match(r' *MBEDTLS_CIPHER_ID_(\w+),', line)
345 if m and m.group(1) not in ['NONE', 'NULL', '3DES']:
346 self.base_symbols.add('MBEDTLS_' + m.group(1) + '_C')
347
Gilles Peskineb39e3ec2019-01-29 08:50:20 +0100348class DomainData:
Andrzej Kurek3322c222022-10-04 15:02:41 -0400349 """A container for domains and jobs, used to structurize testing."""
Gilles Peskineb39e3ec2019-01-29 08:50:20 +0100350 def config_symbols_matching(self, regexp):
Andrzej Kureke05b17f2022-09-28 03:17:56 -0400351 """List the mbedtls_config.h settings matching regexp."""
Gilles Peskineb39e3ec2019-01-29 08:50:20 +0100352 return [symbol for symbol in self.all_config_symbols
353 if re.match(regexp, symbol)]
354
355 def __init__(self, options):
356 """Gather data about the library and establish a list of domains to test."""
357 build_command = [options.make_command, 'CFLAGS=-Werror']
358 build_and_test = [build_command, [options.make_command, 'test']]
Andrzej Kurek3322c222022-10-04 15:02:41 -0400359 self.all_config_symbols = set(collect_config_symbols(options))
Gilles Peskineb39e3ec2019-01-29 08:50:20 +0100360 # Find hash modules by name.
361 hash_symbols = self.config_symbols_matching(r'MBEDTLS_(MD|RIPEMD|SHA)[0-9]+_C\Z')
362 # Find elliptic curve enabling macros by name.
363 curve_symbols = self.config_symbols_matching(r'MBEDTLS_ECP_DP_\w+_ENABLED\Z')
364 # Find key exchange enabling macros by name.
365 key_exchange_symbols = self.config_symbols_matching(r'MBEDTLS_KEY_EXCHANGE_\w+_ENABLED\Z')
Gilles Peskine34a15572019-01-29 23:12:28 +0100366 # Find cipher IDs (block permutations and stream ciphers --- chaining
367 # and padding modes are exercised separately) information by parsing
Andrzej Kureke05b17f2022-09-28 03:17:56 -0400368 # cipher.h, as the information is not readily available in mbedtls_config.h.
369
Andrzej Kurek3322c222022-10-04 15:02:41 -0400370 cipher_info = CipherInfo()
Gilles Peskine34a15572019-01-29 23:12:28 +0100371 # Find block cipher chaining and padding mode enabling macros by name.
372 cipher_chaining_symbols = self.config_symbols_matching(r'MBEDTLS_CIPHER_MODE_\w+\Z')
373 cipher_padding_symbols = self.config_symbols_matching(r'MBEDTLS_CIPHER_PADDING_\w+\Z')
Gilles Peskineb39e3ec2019-01-29 08:50:20 +0100374 self.domains = {
Gilles Peskine34a15572019-01-29 23:12:28 +0100375 # Cipher IDs, chaining modes and padding modes. Run the test suites.
376 'cipher_id': ExclusiveDomain(cipher_info.base_symbols,
377 build_and_test),
378 'cipher_chaining': ExclusiveDomain(cipher_chaining_symbols,
379 build_and_test),
380 'cipher_padding': ExclusiveDomain(cipher_padding_symbols,
381 build_and_test),
Gilles Peskineb39e3ec2019-01-29 08:50:20 +0100382 # Elliptic curves. Run the test suites.
383 'curves': ExclusiveDomain(curve_symbols, build_and_test),
384 # Hash algorithms. Exclude configurations with only one
Andrzej Kureke05b17f2022-09-28 03:17:56 -0400385 # hash which is obsolete. Run the test suites. Exclude
386 # SHA512 and SHA256, as these are tested with SHA384 and SHA224.
Andrzej Kurek228b12c2022-10-06 18:52:44 -0400387 'hashes': DualDomain(hash_symbols, build_and_test,
388 exclude=r'MBEDTLS_(MD|RIPEMD|SHA1_|SHA256_|SHA512_)' \
389 '|!MBEDTLS_(SHA256_|SHA512_)'),
Gilles Peskinec3b4dee2019-01-29 19:33:05 +0100390 # Key exchange types. Only build the library and the sample
391 # programs.
392 'kex': ExclusiveDomain(key_exchange_symbols,
393 [build_command + ['lib'],
394 build_command + ['-C', 'programs']]),
Gilles Peskineb39e3ec2019-01-29 08:50:20 +0100395 'pkalgs': ComplementaryDomain(['MBEDTLS_ECDSA_C',
396 'MBEDTLS_ECP_C',
397 'MBEDTLS_PKCS1_V21',
398 'MBEDTLS_PKCS1_V15',
399 'MBEDTLS_RSA_C',
400 'MBEDTLS_X509_RSASSA_PSS_SUPPORT'],
401 build_and_test),
402 }
403 self.jobs = {}
404 for domain in self.domains.values():
405 for job in domain.jobs:
406 self.jobs[job.name] = job
407
408 def get_jobs(self, name):
409 """Return the list of jobs identified by the given name.
410A name can either be the name of a domain or the name of one specific job."""
411 if name in self.domains:
412 return sorted(self.domains[name].jobs, key=lambda job: job.name)
413 else:
414 return [self.jobs[name]]
415
Gilles Peskine0fa7cbe2019-01-29 18:48:48 +0100416def run(options, job, colors=NO_COLORS):
Gilles Peskineb39e3ec2019-01-29 08:50:20 +0100417 """Run the specified job (a Job instance)."""
418 subprocess.check_call([options.make_command, 'clean'])
Gilles Peskine0fa7cbe2019-01-29 18:48:48 +0100419 job.announce(colors, None)
Gilles Peskine54aa5c62019-01-29 18:46:34 +0100420 job.configure(options)
Gilles Peskineb39e3ec2019-01-29 08:50:20 +0100421 success = job.test(options)
Gilles Peskine0fa7cbe2019-01-29 18:48:48 +0100422 job.announce(colors, success)
Gilles Peskineb39e3ec2019-01-29 08:50:20 +0100423 return success
424
Andrzej Kurek3322c222022-10-04 15:02:41 -0400425def run_tests(options, domain_data):
Gilles Peskineb39e3ec2019-01-29 08:50:20 +0100426 """Run the desired jobs.
427domain_data should be a DomainData instance that describes the available
428domains and jobs.
429Run the jobs listed in options.domains."""
430 if not hasattr(options, 'config_backup'):
431 options.config_backup = options.config + '.bak'
Gilles Peskine0fa7cbe2019-01-29 18:48:48 +0100432 colors = Colors(options)
Gilles Peskineb39e3ec2019-01-29 08:50:20 +0100433 jobs = []
434 failures = []
435 successes = []
436 for name in options.domains:
437 jobs += domain_data.get_jobs(name)
438 backup_config(options)
439 try:
440 for job in jobs:
Gilles Peskine0fa7cbe2019-01-29 18:48:48 +0100441 success = run(options, job, colors=colors)
Gilles Peskineb39e3ec2019-01-29 08:50:20 +0100442 if not success:
443 if options.keep_going:
444 failures.append(job.name)
445 else:
446 return False
447 else:
448 successes.append(job.name)
Gilles Peskinebf7537d2019-01-29 18:52:16 +0100449 restore_config(options)
450 except:
451 # Restore the configuration, except in stop-on-error mode if there
452 # was an error, where we leave the failing configuration up for
453 # developer convenience.
Gilles Peskineb39e3ec2019-01-29 08:50:20 +0100454 if options.keep_going:
Gilles Peskinebf7537d2019-01-29 18:52:16 +0100455 restore_config(options)
456 raise
Gilles Peskinee85163b2019-01-29 18:50:03 +0100457 if successes:
458 log_line('{} passed'.format(' '.join(successes)), color=colors.bold_green)
Gilles Peskineb39e3ec2019-01-29 08:50:20 +0100459 if failures:
Gilles Peskinee85163b2019-01-29 18:50:03 +0100460 log_line('{} FAILED'.format(' '.join(failures)), color=colors.bold_red)
Gilles Peskineb39e3ec2019-01-29 08:50:20 +0100461 return False
462 else:
Gilles Peskineb39e3ec2019-01-29 08:50:20 +0100463 return True
464
Andrzej Kurek3322c222022-10-04 15:02:41 -0400465def main():
Gilles Peskineb39e3ec2019-01-29 08:50:20 +0100466 try:
467 parser = argparse.ArgumentParser(description=__doc__)
Gilles Peskine0fa7cbe2019-01-29 18:48:48 +0100468 parser.add_argument('--color', metavar='WHEN',
469 help='Colorize the output (always/auto/never)',
470 choices=['always', 'auto', 'never'], default='auto')
Gilles Peskineb39e3ec2019-01-29 08:50:20 +0100471 parser.add_argument('-c', '--config', metavar='FILE',
472 help='Configuration file to modify',
Andrzej Kureke05b17f2022-09-28 03:17:56 -0400473 default='include/mbedtls/mbedtls_config.h')
Gilles Peskineb39e3ec2019-01-29 08:50:20 +0100474 parser.add_argument('-C', '--directory', metavar='DIR',
475 help='Change to this directory before anything else',
476 default='.')
477 parser.add_argument('-k', '--keep-going',
478 help='Try all configurations even if some fail (default)',
479 action='store_true', dest='keep_going', default=True)
480 parser.add_argument('-e', '--no-keep-going',
481 help='Stop as soon as a configuration fails',
482 action='store_false', dest='keep_going')
483 parser.add_argument('--list-jobs',
484 help='List supported jobs and exit',
485 action='append_const', dest='list', const='jobs')
486 parser.add_argument('--list-domains',
487 help='List supported domains and exit',
488 action='append_const', dest='list', const='domains')
489 parser.add_argument('--make-command', metavar='CMD',
490 help='Command to run instead of make (e.g. gmake)',
491 action='store', default='make')
492 parser.add_argument('domains', metavar='DOMAIN', nargs='*',
Andrzej Kurek3322c222022-10-04 15:02:41 -0400493 help='The domain(s) to test (default: all). This can \
494 be also a list of jobs to run.',
Gilles Peskineb39e3ec2019-01-29 08:50:20 +0100495 default=True)
496 options = parser.parse_args()
497 os.chdir(options.directory)
498 domain_data = DomainData(options)
Andrzej Kurek3322c222022-10-04 15:02:41 -0400499 if options.domains is True:
Gilles Peskineb39e3ec2019-01-29 08:50:20 +0100500 options.domains = sorted(domain_data.domains.keys())
501 if options.list:
Andrzej Kurek3322c222022-10-04 15:02:41 -0400502 for arg in options.list:
503 for domain_name in sorted(getattr(domain_data, arg).keys()):
504 print(domain_name)
505 sys.exit(0)
Gilles Peskineb39e3ec2019-01-29 08:50:20 +0100506 else:
Andrzej Kurek3322c222022-10-04 15:02:41 -0400507 sys.exit(0 if run_tests(options, domain_data) else 1)
508 except Exception: # pylint: disable=broad-except
Gilles Peskineb39e3ec2019-01-29 08:50:20 +0100509 traceback.print_exc()
Andrzej Kurek3322c222022-10-04 15:02:41 -0400510 sys.exit(3)
511
512if __name__ == '__main__':
513 main()