blob: 3e8a2b0e63a1f5eb89b5b73cf4aece49f7083d54 [file] [log] [blame]
Gilles Peskineb39e3ec2019-01-29 08:50:20 +01001#!/usr/bin/env python3
2
Andrzej Kurek629c4122022-10-17 08:34:40 -04003# Copyright (c) 2022, Arm Limited, All Rights Reserved.
Gilles Peskineb39e3ec2019-01-29 08:50:20 +01004# 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
Gilles Peskineb39e3ec2019-01-29 08:50:20 +010020"""
Andrzej Kurek01af84a2022-10-09 05:29:44 -040021Test Mbed TLS with a subset of algorithms.
Gilles Peskineb39e3ec2019-01-29 08:50:20 +010022
Andrzej Kurek01af84a2022-10-09 05:29:44 -040023This script can be divided into several steps:
24
25First, include/mbedtls/mbedtls_config.h or a different config file passed
Andrzej Kurek3f930122022-10-26 08:08:26 -040026in the arguments is parsed to extract any configuration options (using config.py).
Andrzej Kurek01af84a2022-10-09 05:29:44 -040027
28Then, test domains (groups of jobs, tests) are built based on predefined data
29collected in the DomainData class. Here, each domain has five major traits:
Andrzej Kurek629c4122022-10-17 08:34:40 -040030- domain name, can be used to run only specific tests via command-line;
Andrzej Kurek01af84a2022-10-09 05:29:44 -040031- configuration building method, described in detail below;
32- list of symbols passed to the configuration building method;
33- commands to be run on each job (only build, build and test, or any other custom);
34- optional list of symbols to be excluded from testing.
35
36The configuration building method can be one of the three following:
37
38- ComplementaryDomain - build a job for each passed symbol by disabling a single
39 symbol and its reverse dependencies (defined in REVERSE_DEPENDENCIES);
40
41- ExclusiveDomain - build a job where, for each passed symbol, only this particular
42 one is defined and other symbols from the list are unset. For each job look for
43 any non-standard symbols to set/unset in EXCLUSIVE_GROUPS. These are usually not
44 direct dependencies, but rather non-trivial results of other configs missing. Then
45 look for any unset symbols and handle their reverse dependencies.
46 Examples of EXCLUSIVE_GROUPS usage:
Andrzej Kurek629c4122022-10-17 08:34:40 -040047 - MBEDTLS_SHA256 job turns off all hashes except SHA256, however, when investigating
48 reverse dependencies, SHA224 is found to depend on SHA256, so it is disabled,
49 and then SHA256 is found to depend on SHA224, so it is also disabled. To handle
50 this, there's a field in EXCLUSIVE_GROUPS that states that in a SHA256 test SHA224
Andrzej Kurek01af84a2022-10-09 05:29:44 -040051 should also be enabled before processing reverse dependencies:
Andrzej Kurek629c4122022-10-17 08:34:40 -040052 'MBEDTLS_SHA256_C': ['+MBEDTLS_SHA224_C']
Andrzej Kurek01af84a2022-10-09 05:29:44 -040053 - MBEDTLS_SHA512_C job turns off all hashes except SHA512. MBEDTLS_SSL_COOKIE_C
54 requires either SHA256 or SHA384 to work, so it also has to be disabled.
55 This is not a dependency on SHA512_C, but a result of an exclusive domain
56 config building method. Relevant field:
Andrzej Kurek629c4122022-10-17 08:34:40 -040057 'MBEDTLS_SHA512_C': ['-MBEDTLS_SSL_COOKIE_C'],
Andrzej Kurek01af84a2022-10-09 05:29:44 -040058
59- DualDomain - combination of the two above - both complementary and exclusive domain
60 job generation code will be run. Currently only used for hashes.
61
62Lastly, the collected jobs are executed and (optionally) tested, with
63error reporting and coloring as configured in options. Each test starts with
64a full config without a couple of slowing down or unnecessary options
65(see set_reference_config), then the specific job config is derived.
66"""
Gilles Peskineb39e3ec2019-01-29 08:50:20 +010067import argparse
68import os
69import re
70import shutil
71import subprocess
72import sys
73import traceback
Andrzej Kurek576803f2023-01-24 07:40:42 -050074from typing import Union
75
Andrzej Kurek3b0215d2023-01-23 07:19:22 -050076# Add the Mbed TLS Python library directory to the module search path
Andrzej Kurek3f930122022-10-26 08:08:26 -040077import scripts_path # pylint: disable=unused-import
78import config
79
Andrzej Kurek3322c222022-10-04 15:02:41 -040080class Colors: # pylint: disable=too-few-public-methods
Gilles Peskine0fa7cbe2019-01-29 18:48:48 +010081 """Minimalistic support for colored output.
82Each field of an object of this class is either None if colored output
83is not possible or not desired, or a pair of strings (start, stop) such
84that outputting start switches the text color to the desired color and
85stop switches the text color back to the default."""
86 red = None
87 green = None
Andrzej Kurek3f930122022-10-26 08:08:26 -040088 cyan = None
Gilles Peskine0fa7cbe2019-01-29 18:48:48 +010089 bold_red = None
90 bold_green = None
91 def __init__(self, options=None):
Andrzej Kurek3322c222022-10-04 15:02:41 -040092 """Initialize color profile according to passed options."""
Gilles Peskine0fa7cbe2019-01-29 18:48:48 +010093 if not options or options.color in ['no', 'never']:
94 want_color = False
95 elif options.color in ['yes', 'always']:
96 want_color = True
97 else:
98 want_color = sys.stderr.isatty()
99 if want_color:
100 # Assume ANSI compatible terminal
101 normal = '\033[0m'
102 self.red = ('\033[31m', normal)
103 self.green = ('\033[32m', normal)
Andrzej Kurek3f930122022-10-26 08:08:26 -0400104 self.cyan = ('\033[36m', normal)
Gilles Peskine0fa7cbe2019-01-29 18:48:48 +0100105 self.bold_red = ('\033[1;31m', normal)
106 self.bold_green = ('\033[1;32m', normal)
107NO_COLORS = Colors(None)
108
109def log_line(text, prefix='depends.py:', suffix='', color=None):
Gilles Peskineb39e3ec2019-01-29 08:50:20 +0100110 """Print a status message."""
Andrzej Kurek3322c222022-10-04 15:02:41 -0400111 if color is not None:
Gilles Peskine0fa7cbe2019-01-29 18:48:48 +0100112 prefix = color[0] + prefix
113 suffix = suffix + color[1]
114 sys.stderr.write(prefix + ' ' + text + suffix + '\n')
Gilles Peskine46c82562019-01-29 18:42:55 +0100115 sys.stderr.flush()
Gilles Peskineb39e3ec2019-01-29 08:50:20 +0100116
Gilles Peskine54aa5c62019-01-29 18:46:34 +0100117def log_command(cmd):
118 """Print a trace of the specified command.
119cmd is a list of strings: a command name and its arguments."""
120 log_line(' '.join(cmd), prefix='+')
121
Gilles Peskineb39e3ec2019-01-29 08:50:20 +0100122def backup_config(options):
Andrzej Kureke05b17f2022-09-28 03:17:56 -0400123 """Back up the library configuration file (mbedtls_config.h).
Gilles Peskinebf7537d2019-01-29 18:52:16 +0100124If the backup file already exists, it is presumed to be the desired backup,
125so don't make another backup."""
126 if os.path.exists(options.config_backup):
127 options.own_backup = False
128 else:
129 options.own_backup = True
130 shutil.copy(options.config, options.config_backup)
Gilles Peskineb39e3ec2019-01-29 08:50:20 +0100131
Gilles Peskinebf7537d2019-01-29 18:52:16 +0100132def restore_config(options):
Andrzej Kureke05b17f2022-09-28 03:17:56 -0400133 """Restore the library configuration file (mbedtls_config.h).
Gilles Peskinebf7537d2019-01-29 18:52:16 +0100134Remove the backup file if it was saved earlier."""
135 if options.own_backup:
Gilles Peskineb39e3ec2019-01-29 08:50:20 +0100136 shutil.move(options.config_backup, options.config)
137 else:
138 shutil.copy(options.config_backup, options.config)
Gilles Peskinebf7537d2019-01-29 18:52:16 +0100139
Andrzej Kurek3f930122022-10-26 08:08:26 -0400140def option_exists(conf, option):
Andrzej Kurek81cf5ad2023-02-06 10:48:43 +0100141 return option in conf.settings
Gilles Peskineb39e3ec2019-01-29 08:50:20 +0100142
Andrzej Kurek576803f2023-01-24 07:40:42 -0500143def set_config_option_value(conf, option, colors, value: Union[bool, str]):
144 """Set/unset a configuration option, optionally specifying a value.
145value can be either True/False (set/unset config option), or a string,
146which will make a symbol defined with a certain value."""
Andrzej Kurek3f930122022-10-26 08:08:26 -0400147 if not option_exists(conf, option):
148 log_line('Symbol {} was not found in {}'.format(option, conf.filename), color=colors.red)
149 return False
Andrzej Kurek3f930122022-10-26 08:08:26 -0400150
Andrzej Kurek3b0215d2023-01-23 07:19:22 -0500151 if value is False:
152 log_command(['config.py', 'unset', option])
153 conf.unset(option)
Andrzej Kurek72082dc2023-02-06 10:49:46 +0100154 elif value is True:
155 log_command(['config.py', 'set', option])
156 conf.set(option)
Andrzej Kurek3b0215d2023-01-23 07:19:22 -0500157 else:
Andrzej Kurek72082dc2023-02-06 10:49:46 +0100158 log_command(['config.py', 'set', option, value])
159 conf.set(option, value)
Andrzej Kurek3f930122022-10-26 08:08:26 -0400160 return True
161
162def set_reference_config(conf, options, colors):
Andrzej Kurek3322c222022-10-04 15:02:41 -0400163 """Change the library configuration file (mbedtls_config.h) to the reference state.
164The reference state is the one from which the tested configurations are
165derived."""
Andrzej Kureka0cb4fa2022-10-14 07:06:43 -0400166 # Turn off options that are not relevant to the tests and slow them down.
Andrzej Kurek3f930122022-10-26 08:08:26 -0400167 log_command(['config.py', 'full'])
168 conf.adapt(config.full_adapter)
Andrzej Kurek3b0215d2023-01-23 07:19:22 -0500169 set_config_option_value(conf, 'MBEDTLS_TEST_HOOKS', colors, False)
Andrzej Kurek2c7993c2022-10-24 10:41:20 -0400170 if options.unset_use_psa:
Andrzej Kurek3b0215d2023-01-23 07:19:22 -0500171 set_config_option_value(conf, 'MBEDTLS_USE_PSA_CRYPTO', colors, False)
Andrzej Kurek3322c222022-10-04 15:02:41 -0400172
Gilles Peskineb39e3ec2019-01-29 08:50:20 +0100173class Job:
174 """A job builds the library in a specific configuration and runs some tests."""
175 def __init__(self, name, config_settings, commands):
176 """Build a job object.
177The job uses the configuration described by config_settings. This is a
178dictionary where the keys are preprocessor symbols and the values are
179booleans or strings. A boolean indicates whether or not to #define the
180symbol. With a string, the symbol is #define'd to that value.
181After setting the configuration, the job runs the programs specified by
182commands. This is a list of lists of strings; each list of string is a
183command name and its arguments and is passed to subprocess.call with
184shell=False."""
185 self.name = name
186 self.config_settings = config_settings
187 self.commands = commands
188
Gilles Peskine0fa7cbe2019-01-29 18:48:48 +0100189 def announce(self, colors, what):
Gilles Peskineb39e3ec2019-01-29 08:50:20 +0100190 '''Announce the start or completion of a job.
191If what is None, announce the start of the job.
192If what is True, announce that the job has passed.
193If what is False, announce that the job has failed.'''
194 if what is True:
Gilles Peskine0fa7cbe2019-01-29 18:48:48 +0100195 log_line(self.name + ' PASSED', color=colors.green)
Gilles Peskineb39e3ec2019-01-29 08:50:20 +0100196 elif what is False:
Gilles Peskine0fa7cbe2019-01-29 18:48:48 +0100197 log_line(self.name + ' FAILED', color=colors.red)
Gilles Peskineb39e3ec2019-01-29 08:50:20 +0100198 else:
Andrzej Kurek3f930122022-10-26 08:08:26 -0400199 log_line('starting ' + self.name, color=colors.cyan)
Gilles Peskineb39e3ec2019-01-29 08:50:20 +0100200
Andrzej Kurek3f930122022-10-26 08:08:26 -0400201 def configure(self, conf, options, colors):
Andrzej Kureka0cb4fa2022-10-14 07:06:43 -0400202 '''Set library configuration options as required for the job.'''
Andrzej Kurek3f930122022-10-26 08:08:26 -0400203 set_reference_config(conf, options, colors)
Gilles Peskineb39e3ec2019-01-29 08:50:20 +0100204 for key, value in sorted(self.config_settings.items()):
Andrzej Kurek3b0215d2023-01-23 07:19:22 -0500205 ret = set_config_option_value(conf, key, colors, value)
Andrzej Kurek3f930122022-10-26 08:08:26 -0400206 if ret is False:
207 return False
208 return True
Gilles Peskineb39e3ec2019-01-29 08:50:20 +0100209
210 def test(self, options):
211 '''Run the job's build and test commands.
212Return True if all the commands succeed and False otherwise.
213If options.keep_going is false, stop as soon as one command fails. Otherwise
214run all the commands, except that if the first command fails, none of the
215other commands are run (typically, the first command is a build command
216and subsequent commands are tests that cannot run if the build failed).'''
217 built = False
218 success = True
219 for command in self.commands:
Gilles Peskine54aa5c62019-01-29 18:46:34 +0100220 log_command(command)
Gilles Peskineb39e3ec2019-01-29 08:50:20 +0100221 ret = subprocess.call(command)
222 if ret != 0:
223 if command[0] not in ['make', options.make_command]:
224 log_line('*** [{}] Error {}'.format(' '.join(command), ret))
225 if not options.keep_going or not built:
226 return False
227 success = False
228 built = True
229 return success
230
Gilles Peskineb39e3ec2019-01-29 08:50:20 +0100231# If the configuration option A requires B, make sure that
Andrzej Kurek202932f2022-10-04 16:22:22 -0400232# B in REVERSE_DEPENDENCIES[A].
Gilles Peskine584c24a2019-01-29 19:30:40 +0100233# All the information here should be contained in check_config.h. This
234# file includes a copy because it changes rarely and it would be a pain
235# to extract automatically.
Andrzej Kurek202932f2022-10-04 16:22:22 -0400236REVERSE_DEPENDENCIES = {
Gilles Peskine34a15572019-01-29 23:12:28 +0100237 'MBEDTLS_AES_C': ['MBEDTLS_CTR_DRBG_C',
Andrzej Kureke05b17f2022-09-28 03:17:56 -0400238 'MBEDTLS_NIST_KW_C'],
Gilles Peskine34a15572019-01-29 23:12:28 +0100239 'MBEDTLS_CHACHA20_C': ['MBEDTLS_CHACHAPOLY_C'],
Andrzej Kureke05b17f2022-09-28 03:17:56 -0400240 'MBEDTLS_ECDSA_C': ['MBEDTLS_KEY_EXCHANGE_ECDHE_ECDSA_ENABLED',
241 'MBEDTLS_KEY_EXCHANGE_ECDH_ECDSA_ENABLED'],
Gilles Peskineb39e3ec2019-01-29 08:50:20 +0100242 'MBEDTLS_ECP_C': ['MBEDTLS_ECDSA_C',
243 'MBEDTLS_ECDH_C',
244 'MBEDTLS_ECJPAKE_C',
245 'MBEDTLS_KEY_EXCHANGE_ECDH_ECDSA_ENABLED',
246 'MBEDTLS_KEY_EXCHANGE_ECDH_RSA_ENABLED',
247 'MBEDTLS_KEY_EXCHANGE_ECDHE_PSK_ENABLED',
248 'MBEDTLS_KEY_EXCHANGE_ECDHE_RSA_ENABLED',
Andrzej Kureke05b17f2022-09-28 03:17:56 -0400249 'MBEDTLS_KEY_EXCHANGE_ECDHE_ECDSA_ENABLED',
Ronald Crond8d2ea52022-10-04 15:48:06 +0200250 'MBEDTLS_KEY_EXCHANGE_ECJPAKE_ENABLED',
251 'MBEDTLS_SSL_TLS1_3_KEY_EXCHANGE_MODE_EPHEMERAL_ENABLED',
252 'MBEDTLS_SSL_TLS1_3_KEY_EXCHANGE_MODE_PSK_EPHEMERAL_ENABLED'],
Gilles Peskine584c24a2019-01-29 19:30:40 +0100253 'MBEDTLS_ECP_DP_SECP256R1_ENABLED': ['MBEDTLS_KEY_EXCHANGE_ECJPAKE_ENABLED'],
Gilles Peskineb39e3ec2019-01-29 08:50:20 +0100254 'MBEDTLS_PKCS1_V21': ['MBEDTLS_X509_RSASSA_PSS_SUPPORT'],
255 'MBEDTLS_PKCS1_V15': ['MBEDTLS_KEY_EXCHANGE_DHE_RSA_ENABLED',
256 'MBEDTLS_KEY_EXCHANGE_ECDHE_RSA_ENABLED',
257 'MBEDTLS_KEY_EXCHANGE_RSA_PSK_ENABLED',
258 'MBEDTLS_KEY_EXCHANGE_RSA_ENABLED'],
259 'MBEDTLS_RSA_C': ['MBEDTLS_X509_RSASSA_PSS_SUPPORT',
260 'MBEDTLS_KEY_EXCHANGE_DHE_RSA_ENABLED',
261 'MBEDTLS_KEY_EXCHANGE_ECDHE_RSA_ENABLED',
262 'MBEDTLS_KEY_EXCHANGE_RSA_PSK_ENABLED',
Andrzej Kureke05b17f2022-09-28 03:17:56 -0400263 'MBEDTLS_KEY_EXCHANGE_RSA_ENABLED',
264 'MBEDTLS_KEY_EXCHANGE_ECDH_RSA_ENABLED'],
Gilles Peskine584c24a2019-01-29 19:30:40 +0100265 'MBEDTLS_SHA256_C': ['MBEDTLS_KEY_EXCHANGE_ECJPAKE_ENABLED',
Andrzej Kureke05b17f2022-09-28 03:17:56 -0400266 'MBEDTLS_ENTROPY_FORCE_SHA256',
267 'MBEDTLS_SHA224_C',
268 'MBEDTLS_SHA256_USE_A64_CRYPTO_IF_PRESENT',
Andrzej Kurek22b959d2022-10-16 12:51:41 -0400269 'MBEDTLS_SHA256_USE_A64_CRYPTO_ONLY',
270 'MBEDTLS_LMS_C',
271 'MBEDTLS_LMS_PRIVATE'],
Andrzej Kureke05b17f2022-09-28 03:17:56 -0400272 'MBEDTLS_SHA512_C': ['MBEDTLS_SHA384_C',
273 'MBEDTLS_SHA512_USE_A64_CRYPTO_IF_PRESENT',
274 'MBEDTLS_SHA512_USE_A64_CRYPTO_ONLY'],
275 'MBEDTLS_SHA224_C': ['MBEDTLS_KEY_EXCHANGE_ECJPAKE_ENABLED',
276 'MBEDTLS_ENTROPY_FORCE_SHA256',
277 'MBEDTLS_SHA256_C',
278 'MBEDTLS_SHA256_USE_A64_CRYPTO_IF_PRESENT',
279 'MBEDTLS_SHA256_USE_A64_CRYPTO_ONLY'],
Andrzej Kureke05b17f2022-09-28 03:17:56 -0400280 'MBEDTLS_X509_RSASSA_PSS_SUPPORT': []
Gilles Peskineb39e3ec2019-01-29 08:50:20 +0100281}
282
Andrzej Kureke05b17f2022-09-28 03:17:56 -0400283# If an option is tested in an exclusive test, alter the following defines.
Andrzej Kurek01af84a2022-10-09 05:29:44 -0400284# These are not necessarily dependencies, but just minimal required changes
Andrzej Kureke05b17f2022-09-28 03:17:56 -0400285# if a given define is the only one enabled from an exclusive group.
Andrzej Kurek202932f2022-10-04 16:22:22 -0400286EXCLUSIVE_GROUPS = {
Andrzej Kurek65b2ac12022-10-14 08:09:16 -0400287 'MBEDTLS_SHA256_C': ['+MBEDTLS_SHA224_C'],
288 'MBEDTLS_SHA384_C': ['+MBEDTLS_SHA512_C'],
289 'MBEDTLS_SHA512_C': ['-MBEDTLS_SSL_COOKIE_C',
290 '-MBEDTLS_SSL_PROTO_TLS1_3'],
291 'MBEDTLS_ECP_DP_CURVE448_ENABLED': ['-MBEDTLS_ECDSA_C',
292 '-MBEDTLS_ECDSA_DETERMINISTIC',
293 '-MBEDTLS_KEY_EXCHANGE_ECDHE_ECDSA_ENABLED',
294 '-MBEDTLS_KEY_EXCHANGE_ECDH_ECDSA_ENABLED',
295 '-MBEDTLS_ECJPAKE_C',
296 '-MBEDTLS_KEY_EXCHANGE_ECJPAKE_ENABLED'],
297 'MBEDTLS_ECP_DP_CURVE25519_ENABLED': ['-MBEDTLS_ECDSA_C',
298 '-MBEDTLS_ECDSA_DETERMINISTIC',
299 '-MBEDTLS_KEY_EXCHANGE_ECDHE_ECDSA_ENABLED',
300 '-MBEDTLS_KEY_EXCHANGE_ECDH_ECDSA_ENABLED',
301 '-MBEDTLS_ECJPAKE_C',
302 '-MBEDTLS_KEY_EXCHANGE_ECJPAKE_ENABLED'],
303 'MBEDTLS_ARIA_C': ['-MBEDTLS_CMAC_C'],
304 'MBEDTLS_CAMELLIA_C': ['-MBEDTLS_CMAC_C'],
305 'MBEDTLS_CHACHA20_C': ['-MBEDTLS_CMAC_C', '-MBEDTLS_CCM_C', '-MBEDTLS_GCM_C'],
306 'MBEDTLS_DES_C': ['-MBEDTLS_CCM_C',
307 '-MBEDTLS_GCM_C',
308 '-MBEDTLS_SSL_TICKET_C',
309 '-MBEDTLS_SSL_CONTEXT_SERIALIZATION'],
Andrzej Kureke05b17f2022-09-28 03:17:56 -0400310}
311def handle_exclusive_groups(config_settings, symbol):
312 """For every symbol tested in an exclusive group check if there are other
313defines to be altered. """
Andrzej Kurek202932f2022-10-04 16:22:22 -0400314 for dep in EXCLUSIVE_GROUPS.get(symbol, []):
Andrzej Kurek65b2ac12022-10-14 08:09:16 -0400315 unset = dep.startswith('-')
316 dep = dep[1:]
Andrzej Kureke05b17f2022-09-28 03:17:56 -0400317 config_settings[dep] = not unset
318
Gilles Peskineb39e3ec2019-01-29 08:50:20 +0100319def turn_off_dependencies(config_settings):
320 """For every option turned off config_settings, also turn off what depends on it.
321An option O is turned off if config_settings[O] is False."""
322 for key, value in sorted(config_settings.items()):
323 if value is not False:
324 continue
Andrzej Kurek202932f2022-10-04 16:22:22 -0400325 for dep in REVERSE_DEPENDENCIES.get(key, []):
Gilles Peskineb39e3ec2019-01-29 08:50:20 +0100326 config_settings[dep] = False
327
Andrzej Kurek228b12c2022-10-06 18:52:44 -0400328class BaseDomain: # pylint: disable=too-few-public-methods, unused-argument
329 """A base class for all domains."""
330 def __init__(self, symbols, commands, exclude):
331 """Initialize the jobs container"""
332 self.jobs = []
333
334class ExclusiveDomain(BaseDomain): # pylint: disable=too-few-public-methods
Gilles Peskineb39e3ec2019-01-29 08:50:20 +0100335 """A domain consisting of a set of conceptually-equivalent settings.
336Establish a list of configuration symbols. For each symbol, run a test job
Andrzej Kurekfe469492022-10-06 16:57:38 -0400337with this symbol set and the others unset."""
Gilles Peskineb1284cf2019-01-29 18:56:03 +0100338 def __init__(self, symbols, commands, exclude=None):
339 """Build a domain for the specified list of configuration symbols.
Andrzej Kurekfe469492022-10-06 16:57:38 -0400340The domain contains a set of jobs that enable one of the elements
341of symbols and disable the others.
Gilles Peskineb1284cf2019-01-29 18:56:03 +0100342Each job runs the specified commands.
343If exclude is a regular expression, skip generated jobs whose description
344would match this regular expression."""
Andrzej Kurek228b12c2022-10-06 18:52:44 -0400345 super().__init__(symbols, commands, exclude)
Andrzej Kurekfe469492022-10-06 16:57:38 -0400346 base_config_settings = {}
347 for symbol in symbols:
348 base_config_settings[symbol] = False
349 for symbol in symbols:
350 description = symbol
351 if exclude and re.match(exclude, description):
352 continue
353 config_settings = base_config_settings.copy()
354 config_settings[symbol] = True
355 handle_exclusive_groups(config_settings, symbol)
356 turn_off_dependencies(config_settings)
357 job = Job(description, config_settings, commands)
358 self.jobs.append(job)
Gilles Peskineb39e3ec2019-01-29 08:50:20 +0100359
Andrzej Kurek228b12c2022-10-06 18:52:44 -0400360class ComplementaryDomain(BaseDomain): # pylint: disable=too-few-public-methods
Gilles Peskineb39e3ec2019-01-29 08:50:20 +0100361 """A domain consisting of a set of loosely-related settings.
362Establish a list of configuration symbols. For each symbol, run a test job
Andrzej Kureka0cb4fa2022-10-14 07:06:43 -0400363with this symbol unset.
364If exclude is a regular expression, skip generated jobs whose description
365would match this regular expression."""
Andrzej Kurek228b12c2022-10-06 18:52:44 -0400366 def __init__(self, symbols, commands, exclude=None):
Gilles Peskineb1284cf2019-01-29 18:56:03 +0100367 """Build a domain for the specified list of configuration symbols.
368Each job in the domain disables one of the specified symbols.
369Each job runs the specified commands."""
Andrzej Kurek228b12c2022-10-06 18:52:44 -0400370 super().__init__(symbols, commands, exclude)
Gilles Peskineb39e3ec2019-01-29 08:50:20 +0100371 for symbol in symbols:
372 description = '!' + symbol
Andrzej Kurek228b12c2022-10-06 18:52:44 -0400373 if exclude and re.match(exclude, description):
374 continue
Gilles Peskineb39e3ec2019-01-29 08:50:20 +0100375 config_settings = {symbol: False}
376 turn_off_dependencies(config_settings)
377 job = Job(description, config_settings, commands)
378 self.jobs.append(job)
379
Andrzej Kurek228b12c2022-10-06 18:52:44 -0400380class DualDomain(ExclusiveDomain, ComplementaryDomain): # pylint: disable=too-few-public-methods
Andrzej Kureka0cb4fa2022-10-14 07:06:43 -0400381 """A domain that contains both the ExclusiveDomain and BaseDomain tests.
Andrzej Kurekf4b18672022-10-14 07:57:00 -0400382Both parent class __init__ calls are performed in any order and
Andrzej Kureka0cb4fa2022-10-14 07:06:43 -0400383each call adds respective jobs. The job array initialization is done once in
384BaseDomain, before the parent __init__ calls."""
Andrzej Kurek228b12c2022-10-06 18:52:44 -0400385
Andrzej Kurek3322c222022-10-04 15:02:41 -0400386class CipherInfo: # pylint: disable=too-few-public-methods
Gilles Peskine34a15572019-01-29 23:12:28 +0100387 """Collect data about cipher.h."""
Andrzej Kurek3322c222022-10-04 15:02:41 -0400388 def __init__(self):
Gilles Peskine34a15572019-01-29 23:12:28 +0100389 self.base_symbols = set()
Andrzej Kurek3322c222022-10-04 15:02:41 -0400390 with open('include/mbedtls/cipher.h', encoding="utf-8") as fh:
Gilles Peskine34a15572019-01-29 23:12:28 +0100391 for line in fh:
392 m = re.match(r' *MBEDTLS_CIPHER_ID_(\w+),', line)
393 if m and m.group(1) not in ['NONE', 'NULL', '3DES']:
394 self.base_symbols.add('MBEDTLS_' + m.group(1) + '_C')
395
Gilles Peskineb39e3ec2019-01-29 08:50:20 +0100396class DomainData:
Andrzej Kurek3322c222022-10-04 15:02:41 -0400397 """A container for domains and jobs, used to structurize testing."""
Gilles Peskineb39e3ec2019-01-29 08:50:20 +0100398 def config_symbols_matching(self, regexp):
Andrzej Kureke05b17f2022-09-28 03:17:56 -0400399 """List the mbedtls_config.h settings matching regexp."""
Gilles Peskineb39e3ec2019-01-29 08:50:20 +0100400 return [symbol for symbol in self.all_config_symbols
401 if re.match(regexp, symbol)]
402
Andrzej Kurek3f930122022-10-26 08:08:26 -0400403 def __init__(self, options, conf):
Gilles Peskineb39e3ec2019-01-29 08:50:20 +0100404 """Gather data about the library and establish a list of domains to test."""
405 build_command = [options.make_command, 'CFLAGS=-Werror']
406 build_and_test = [build_command, [options.make_command, 'test']]
Andrzej Kurek3f930122022-10-26 08:08:26 -0400407 self.all_config_symbols = set(conf.settings.keys())
Gilles Peskineb39e3ec2019-01-29 08:50:20 +0100408 # Find hash modules by name.
409 hash_symbols = self.config_symbols_matching(r'MBEDTLS_(MD|RIPEMD|SHA)[0-9]+_C\Z')
410 # Find elliptic curve enabling macros by name.
411 curve_symbols = self.config_symbols_matching(r'MBEDTLS_ECP_DP_\w+_ENABLED\Z')
412 # Find key exchange enabling macros by name.
413 key_exchange_symbols = self.config_symbols_matching(r'MBEDTLS_KEY_EXCHANGE_\w+_ENABLED\Z')
Gilles Peskine34a15572019-01-29 23:12:28 +0100414 # Find cipher IDs (block permutations and stream ciphers --- chaining
415 # and padding modes are exercised separately) information by parsing
Andrzej Kureke05b17f2022-09-28 03:17:56 -0400416 # cipher.h, as the information is not readily available in mbedtls_config.h.
Andrzej Kurek3322c222022-10-04 15:02:41 -0400417 cipher_info = CipherInfo()
Gilles Peskine34a15572019-01-29 23:12:28 +0100418 # Find block cipher chaining and padding mode enabling macros by name.
419 cipher_chaining_symbols = self.config_symbols_matching(r'MBEDTLS_CIPHER_MODE_\w+\Z')
420 cipher_padding_symbols = self.config_symbols_matching(r'MBEDTLS_CIPHER_PADDING_\w+\Z')
Gilles Peskineb39e3ec2019-01-29 08:50:20 +0100421 self.domains = {
Gilles Peskine34a15572019-01-29 23:12:28 +0100422 # Cipher IDs, chaining modes and padding modes. Run the test suites.
423 'cipher_id': ExclusiveDomain(cipher_info.base_symbols,
424 build_and_test),
425 'cipher_chaining': ExclusiveDomain(cipher_chaining_symbols,
426 build_and_test),
427 'cipher_padding': ExclusiveDomain(cipher_padding_symbols,
428 build_and_test),
Gilles Peskineb39e3ec2019-01-29 08:50:20 +0100429 # Elliptic curves. Run the test suites.
430 'curves': ExclusiveDomain(curve_symbols, build_and_test),
Andrzej Kureka0cb4fa2022-10-14 07:06:43 -0400431 # Hash algorithms. Exclude three groups:
432 # - Exclusive domain of MD, RIPEMD, SHA1 (obsolete);
433 # - Exclusive domain of SHA224 (tested with and depends on SHA256);
434 # - Complementary domain of SHA224 and SHA384 - tested with and depend
435 # on SHA256 and SHA512, respectively.
Andrzej Kurek228b12c2022-10-06 18:52:44 -0400436 'hashes': DualDomain(hash_symbols, build_and_test,
Andrzej Kureka0cb4fa2022-10-14 07:06:43 -0400437 exclude=r'MBEDTLS_(MD|RIPEMD|SHA1_)' \
438 '|MBEDTLS_SHA224_'\
439 '|!MBEDTLS_(SHA224_|SHA384_)'),
Gilles Peskinec3b4dee2019-01-29 19:33:05 +0100440 # Key exchange types. Only build the library and the sample
441 # programs.
442 'kex': ExclusiveDomain(key_exchange_symbols,
443 [build_command + ['lib'],
444 build_command + ['-C', 'programs']]),
Gilles Peskineb39e3ec2019-01-29 08:50:20 +0100445 'pkalgs': ComplementaryDomain(['MBEDTLS_ECDSA_C',
446 'MBEDTLS_ECP_C',
447 'MBEDTLS_PKCS1_V21',
448 'MBEDTLS_PKCS1_V15',
449 'MBEDTLS_RSA_C',
450 'MBEDTLS_X509_RSASSA_PSS_SUPPORT'],
451 build_and_test),
452 }
453 self.jobs = {}
454 for domain in self.domains.values():
455 for job in domain.jobs:
456 self.jobs[job.name] = job
457
458 def get_jobs(self, name):
459 """Return the list of jobs identified by the given name.
460A name can either be the name of a domain or the name of one specific job."""
461 if name in self.domains:
462 return sorted(self.domains[name].jobs, key=lambda job: job.name)
463 else:
464 return [self.jobs[name]]
465
Andrzej Kurek3f930122022-10-26 08:08:26 -0400466def run(options, job, conf, colors=NO_COLORS):
Gilles Peskineb39e3ec2019-01-29 08:50:20 +0100467 """Run the specified job (a Job instance)."""
468 subprocess.check_call([options.make_command, 'clean'])
Gilles Peskine0fa7cbe2019-01-29 18:48:48 +0100469 job.announce(colors, None)
Andrzej Kurek3f930122022-10-26 08:08:26 -0400470 if not job.configure(conf, options, colors):
471 job.announce(colors, False)
472 return False
473 conf.write()
Gilles Peskineb39e3ec2019-01-29 08:50:20 +0100474 success = job.test(options)
Gilles Peskine0fa7cbe2019-01-29 18:48:48 +0100475 job.announce(colors, success)
Gilles Peskineb39e3ec2019-01-29 08:50:20 +0100476 return success
477
Andrzej Kurek3f930122022-10-26 08:08:26 -0400478def run_tests(options, domain_data, conf):
Gilles Peskineb39e3ec2019-01-29 08:50:20 +0100479 """Run the desired jobs.
480domain_data should be a DomainData instance that describes the available
481domains and jobs.
Andrzej Kurekb8a97e72022-10-17 08:39:09 -0400482Run the jobs listed in options.tasks."""
Gilles Peskineb39e3ec2019-01-29 08:50:20 +0100483 if not hasattr(options, 'config_backup'):
484 options.config_backup = options.config + '.bak'
Gilles Peskine0fa7cbe2019-01-29 18:48:48 +0100485 colors = Colors(options)
Gilles Peskineb39e3ec2019-01-29 08:50:20 +0100486 jobs = []
487 failures = []
488 successes = []
Andrzej Kurekb8a97e72022-10-17 08:39:09 -0400489 for name in options.tasks:
Gilles Peskineb39e3ec2019-01-29 08:50:20 +0100490 jobs += domain_data.get_jobs(name)
491 backup_config(options)
492 try:
493 for job in jobs:
Andrzej Kurek3f930122022-10-26 08:08:26 -0400494 success = run(options, job, conf, colors=colors)
Gilles Peskineb39e3ec2019-01-29 08:50:20 +0100495 if not success:
496 if options.keep_going:
497 failures.append(job.name)
498 else:
499 return False
500 else:
501 successes.append(job.name)
Gilles Peskinebf7537d2019-01-29 18:52:16 +0100502 restore_config(options)
503 except:
504 # Restore the configuration, except in stop-on-error mode if there
505 # was an error, where we leave the failing configuration up for
506 # developer convenience.
Gilles Peskineb39e3ec2019-01-29 08:50:20 +0100507 if options.keep_going:
Gilles Peskinebf7537d2019-01-29 18:52:16 +0100508 restore_config(options)
509 raise
Gilles Peskinee85163b2019-01-29 18:50:03 +0100510 if successes:
511 log_line('{} passed'.format(' '.join(successes)), color=colors.bold_green)
Gilles Peskineb39e3ec2019-01-29 08:50:20 +0100512 if failures:
Gilles Peskinee85163b2019-01-29 18:50:03 +0100513 log_line('{} FAILED'.format(' '.join(failures)), color=colors.bold_red)
Gilles Peskineb39e3ec2019-01-29 08:50:20 +0100514 return False
515 else:
Gilles Peskineb39e3ec2019-01-29 08:50:20 +0100516 return True
517
Andrzej Kurek3322c222022-10-04 15:02:41 -0400518def main():
Gilles Peskineb39e3ec2019-01-29 08:50:20 +0100519 try:
Andrzej Kurek01af84a2022-10-09 05:29:44 -0400520 parser = argparse.ArgumentParser(
521 formatter_class=argparse.RawDescriptionHelpFormatter,
522 description=
523 "Test Mbed TLS with a subset of algorithms.\n\n"
524 "Example usage:\n"
Andrzej Kurek629c4122022-10-17 08:34:40 -0400525 r"./tests/scripts/depends.py \!MBEDTLS_SHA1_C MBEDTLS_SHA256_C""\n"
Andrzej Kurek01af84a2022-10-09 05:29:44 -0400526 "./tests/scripts/depends.py MBEDTLS_AES_C hashes\n"
527 "./tests/scripts/depends.py cipher_id cipher_chaining\n")
Gilles Peskine0fa7cbe2019-01-29 18:48:48 +0100528 parser.add_argument('--color', metavar='WHEN',
529 help='Colorize the output (always/auto/never)',
530 choices=['always', 'auto', 'never'], default='auto')
Gilles Peskineb39e3ec2019-01-29 08:50:20 +0100531 parser.add_argument('-c', '--config', metavar='FILE',
532 help='Configuration file to modify',
Andrzej Kureke05b17f2022-09-28 03:17:56 -0400533 default='include/mbedtls/mbedtls_config.h')
Gilles Peskineb39e3ec2019-01-29 08:50:20 +0100534 parser.add_argument('-C', '--directory', metavar='DIR',
535 help='Change to this directory before anything else',
536 default='.')
537 parser.add_argument('-k', '--keep-going',
538 help='Try all configurations even if some fail (default)',
539 action='store_true', dest='keep_going', default=True)
540 parser.add_argument('-e', '--no-keep-going',
541 help='Stop as soon as a configuration fails',
542 action='store_false', dest='keep_going')
543 parser.add_argument('--list-jobs',
544 help='List supported jobs and exit',
545 action='append_const', dest='list', const='jobs')
546 parser.add_argument('--list-domains',
547 help='List supported domains and exit',
548 action='append_const', dest='list', const='domains')
549 parser.add_argument('--make-command', metavar='CMD',
550 help='Command to run instead of make (e.g. gmake)',
551 action='store', default='make')
Andrzej Kurek2c7993c2022-10-24 10:41:20 -0400552 parser.add_argument('--unset-use-psa',
553 help='Unset MBEDTLS_USE_PSA_CRYPTO before any test',
554 action='store_true', dest='unset_use_psa')
Andrzej Kurekb8a97e72022-10-17 08:39:09 -0400555 parser.add_argument('tasks', metavar='TASKS', nargs='*',
556 help='The domain(s) or job(s) to test (default: all).',
Gilles Peskineb39e3ec2019-01-29 08:50:20 +0100557 default=True)
558 options = parser.parse_args()
559 os.chdir(options.directory)
Andrzej Kurek3f930122022-10-26 08:08:26 -0400560 conf = config.ConfigFile(options.config)
561 domain_data = DomainData(options, conf)
562
Andrzej Kurekb8a97e72022-10-17 08:39:09 -0400563 if options.tasks is True:
564 options.tasks = sorted(domain_data.domains.keys())
Gilles Peskineb39e3ec2019-01-29 08:50:20 +0100565 if options.list:
Andrzej Kurek3322c222022-10-04 15:02:41 -0400566 for arg in options.list:
567 for domain_name in sorted(getattr(domain_data, arg).keys()):
568 print(domain_name)
569 sys.exit(0)
Gilles Peskineb39e3ec2019-01-29 08:50:20 +0100570 else:
Andrzej Kurek3f930122022-10-26 08:08:26 -0400571 sys.exit(0 if run_tests(options, domain_data, conf) else 1)
Andrzej Kurek3322c222022-10-04 15:02:41 -0400572 except Exception: # pylint: disable=broad-except
Gilles Peskineb39e3ec2019-01-29 08:50:20 +0100573 traceback.print_exc()
Andrzej Kurek3322c222022-10-04 15:02:41 -0400574 sys.exit(3)
575
576if __name__ == '__main__':
577 main()