blob: 894c51d13c4513e1edd54544c0f27313ae7f2541 [file] [log] [blame]
Gilles Peskineb4063892019-07-27 21:36:44 +02001#!/usr/bin/env python3
2
Gabor Mezei634103c2024-09-11 13:08:21 +02003"""Mbed TLS and PSA configuration file manipulation library and tool
Gilles Peskineb4063892019-07-27 21:36:44 +02004
Fredrik Hessecc207bc2021-09-28 21:06:08 +02005Basic usage, to read the Mbed TLS configuration:
Gabor Mezei634103c2024-09-11 13:08:21 +02006 config = CombinedConfigFile()
Gilles Peskineb4063892019-07-27 21:36:44 +02007 if 'MBEDTLS_RSA_C' in config: print('RSA is enabled')
8"""
9
Bence Szépkúti1e148272020-08-07 13:07:28 +020010## Copyright The Mbed TLS Contributors
Dave Rodgman16799db2023-11-02 19:47:20 +000011## SPDX-License-Identifier: Apache-2.0 OR GPL-2.0-or-later
Gilles Peskineb4063892019-07-27 21:36:44 +020012##
Gilles Peskineb4063892019-07-27 21:36:44 +020013
Gilles Peskine208e4ec2019-07-29 23:43:20 +020014import os
Gilles Peskineb4063892019-07-27 21:36:44 +020015import re
Gabor Mezei634103c2024-09-11 13:08:21 +020016import sys
Gilles Peskineb4063892019-07-27 21:36:44 +020017
Gabor Mezei634103c2024-09-11 13:08:21 +020018import framework_scripts_path # pylint: disable=unused-import
19from mbedtls_framework import config_common
Gilles Peskineb4063892019-07-27 21:36:44 +020020
Gilles Peskine8e90cf42021-05-27 22:12:57 +020021
Gilles Peskine53d41ae2019-07-27 23:31:53 +020022def is_full_section(section):
Gabor Mezei634103c2024-09-11 13:08:21 +020023 """Is this section affected by "config.py full" and friends?
24
25 In a config file where the sections are not used the whole config file
26 is an empty section (with value None) and the whole file is affected.
27 """
28 return section is None or section.endswith('support') or section.endswith('modules')
Gilles Peskine53d41ae2019-07-27 23:31:53 +020029
30def realfull_adapter(_name, active, section):
Gilles Peskineba4162a2022-04-11 17:04:38 +020031 """Activate all symbols found in the global and boolean feature sections.
32
33 This is intended for building the documentation, including the
34 documentation of settings that are activated by defining an optional
35 preprocessor macro.
36
37 Do not activate definitions in the section containing symbols that are
38 supposed to be defined and documented in their own module.
39 """
40 if section == 'Module configuration options':
Gilles Peskine53d41ae2019-07-27 23:31:53 +020041 return active
Gilles Peskineb4063892019-07-27 21:36:44 +020042 return True
43
Gabor Mezei634103c2024-09-11 13:08:21 +020044PSA_UNSUPPORTED_FEATURE = frozenset([
45 'PSA_WANT_ALG_CBC_MAC',
46 'PSA_WANT_ALG_XTS',
47 'PSA_WANT_KEY_TYPE_RSA_KEY_PAIR_DERIVE',
48 'PSA_WANT_KEY_TYPE_DH_KEY_PAIR_DERIVE'
49])
50
51PSA_DEPRECATED_FEATURE = frozenset([
52 'PSA_WANT_KEY_TYPE_ECC_KEY_PAIR',
53 'PSA_WANT_KEY_TYPE_RSA_KEY_PAIR'
54])
55
56PSA_UNSTABLE_FEATURE = frozenset([
57 'PSA_WANT_ECC_SECP_K1_224'
58])
59
60EXCLUDE_FROM_CRYPTO = PSA_UNSUPPORTED_FEATURE | \
61 PSA_DEPRECATED_FEATURE | \
62 PSA_UNSTABLE_FEATURE
63
Gilles Peskinecfffc282020-04-12 13:55:45 +020064# The goal of the full configuration is to have everything that can be tested
65# together. This includes deprecated or insecure options. It excludes:
66# * Options that require additional build dependencies or unusual hardware.
67# * Options that make testing less effective.
Gilles Peskinec9d04332020-04-16 20:50:17 +020068# * Options that are incompatible with other options, or more generally that
69# interact with other parts of the code in such a way that a bulk enabling
70# is not a good way to test them.
Gilles Peskinecfffc282020-04-12 13:55:45 +020071# * Options that remove features.
Gilles Peskinebbaa2b72020-04-12 13:33:57 +020072EXCLUDE_FROM_FULL = frozenset([
Gilles Peskinecfffc282020-04-12 13:55:45 +020073 #pylint: disable=line-too-long
Yanray Wanga8704672023-04-20 17:16:48 +080074 'MBEDTLS_AES_ONLY_128_BIT_KEY_LENGTH', # interacts with CTR_DRBG_128_BIT_KEY
Gilles Peskinea8861e02023-09-05 20:20:51 +020075 'MBEDTLS_AES_USE_HARDWARE_ONLY', # hardware dependency
Yanray Wang42be1ba2023-11-23 14:28:47 +080076 'MBEDTLS_BLOCK_CIPHER_NO_DECRYPT', # incompatible with ECB in PSA, CBC/XTS/NIST_KW/DES
Gilles Peskinec9d04332020-04-16 20:50:17 +020077 'MBEDTLS_CTR_DRBG_USE_128_BIT_KEY', # interacts with ENTROPY_FORCE_SHA256
Gilles Peskinecfffc282020-04-12 13:55:45 +020078 'MBEDTLS_DEPRECATED_REMOVED', # conflicts with deprecated options
Gilles Peskine90581ee2020-04-12 14:02:47 +020079 'MBEDTLS_DEPRECATED_WARNING', # conflicts with deprecated options
Gilles Peskinec9d04332020-04-16 20:50:17 +020080 'MBEDTLS_ECDH_VARIANT_EVEREST_ENABLED', # influences the use of ECDH in TLS
Steven Cooreman77e09b62021-01-22 09:43:27 +010081 'MBEDTLS_ECP_NO_FALLBACK', # removes internal ECP implementation
Janos Follath5b7c38f2023-08-01 08:51:12 +010082 'MBEDTLS_ECP_WITH_MPI_UINT', # disables the default ECP and is experimental
Gilles Peskinec9d04332020-04-16 20:50:17 +020083 'MBEDTLS_ENTROPY_FORCE_SHA256', # interacts with CTR_DRBG_128_BIT_KEY
Gilles Peskinecfffc282020-04-12 13:55:45 +020084 'MBEDTLS_HAVE_SSE2', # hardware dependency
85 'MBEDTLS_MEMORY_BACKTRACE', # depends on MEMORY_BUFFER_ALLOC_C
86 'MBEDTLS_MEMORY_BUFFER_ALLOC_C', # makes sanitizers (e.g. ASan) less effective
87 'MBEDTLS_MEMORY_DEBUG', # depends on MEMORY_BUFFER_ALLOC_C
Gilles Peskinec9d04332020-04-16 20:50:17 +020088 'MBEDTLS_NO_64BIT_MULTIPLICATION', # influences anything that uses bignum
Gilles Peskinecfffc282020-04-12 13:55:45 +020089 'MBEDTLS_NO_DEFAULT_ENTROPY_SOURCES', # removes a feature
90 'MBEDTLS_NO_PLATFORM_ENTROPY', # removes a feature
Gilles Peskinec9d04332020-04-16 20:50:17 +020091 'MBEDTLS_NO_UDBL_DIVISION', # influences anything that uses bignum
Gilles Peskineefaee9a2023-09-20 20:49:47 +020092 'MBEDTLS_PSA_P256M_DRIVER_ENABLED', # influences SECP256R1 KeyGen/ECDH/ECDSA
Gilles Peskinecfffc282020-04-12 13:55:45 +020093 'MBEDTLS_PLATFORM_NO_STD_FUNCTIONS', # removes a feature
David Horstmann6f8c95b2024-03-14 14:52:45 +000094 'MBEDTLS_PSA_ASSUME_EXCLUSIVE_BUFFERS', # removes a feature
Gilles Peskinef08b3f82020-11-13 17:36:48 +010095 'MBEDTLS_PSA_CRYPTO_EXTERNAL_RNG', # behavior change + build dependency
Ronald Cronc3623db2020-10-29 10:51:32 +010096 'MBEDTLS_PSA_CRYPTO_KEY_ID_ENCODES_OWNER', # incompatible with USE_PSA_CRYPTO
Gilles Peskinecfffc282020-04-12 13:55:45 +020097 'MBEDTLS_PSA_CRYPTO_SPM', # platform dependency (PSA SPM)
Gilles Peskinea08def92023-04-28 21:01:49 +020098 'MBEDTLS_PSA_INJECT_ENTROPY', # conflicts with platform entropy sources
Gilles Peskinec9d04332020-04-16 20:50:17 +020099 'MBEDTLS_RSA_NO_CRT', # influences the use of RSA in X.509 and TLS
Tom Cosgrove87fbfb52022-03-15 10:51:52 +0000100 'MBEDTLS_SHA256_USE_A64_CRYPTO_ONLY', # interacts with *_USE_A64_CRYPTO_IF_PRESENT
Dave Rodgman9be3cf02023-10-11 14:47:55 +0100101 'MBEDTLS_SHA256_USE_ARMV8_A_CRYPTO_ONLY', # interacts with *_USE_ARMV8_A_CRYPTO_IF_PRESENT
Tom Cosgrove87fbfb52022-03-15 10:51:52 +0000102 'MBEDTLS_SHA512_USE_A64_CRYPTO_ONLY', # interacts with *_USE_A64_CRYPTO_IF_PRESENT
Dave Rodgman7cb635a2023-10-12 16:14:51 +0100103 'MBEDTLS_SHA256_USE_A64_CRYPTO_IF_PRESENT', # setting *_USE_ARMV8_A_CRYPTO is sufficient
Manuel Pégourié-Gonnard6240def2020-07-10 09:35:54 +0200104 'MBEDTLS_TEST_CONSTANT_FLOW_MEMSAN', # build dependency (clang+memsan)
Manuel Pégourié-Gonnard73afa372020-08-19 10:27:38 +0200105 'MBEDTLS_TEST_CONSTANT_FLOW_VALGRIND', # build dependency (valgrind headers)
Hanno Beckere1113562019-06-12 13:59:14 +0100106 'MBEDTLS_X509_REMOVE_INFO', # removes a feature
Gabor Mezei634103c2024-09-11 13:08:21 +0200107 *PSA_UNSUPPORTED_FEATURE,
108 *PSA_DEPRECATED_FEATURE,
109 *PSA_UNSTABLE_FEATURE
Gilles Peskinebbaa2b72020-04-12 13:33:57 +0200110])
111
Gilles Peskine32e889d2020-04-12 23:43:28 +0200112def is_seamless_alt(name):
Gilles Peskinec34faba2020-04-20 15:44:14 +0200113 """Whether the xxx_ALT symbol should be included in the full configuration.
Gilles Peskine32e889d2020-04-12 23:43:28 +0200114
Gilles Peskinec34faba2020-04-20 15:44:14 +0200115 Include alternative implementations of platform functions, which are
Gilles Peskine32e889d2020-04-12 23:43:28 +0200116 configurable function pointers that default to the built-in function.
117 This way we test that the function pointers exist and build correctly
118 without changing the behavior, and tests can verify that the function
119 pointers are used by modifying those pointers.
120
121 Exclude alternative implementations of library functions since they require
122 an implementation of the relevant functions and an xxx_alt.h header.
123 """
Gilles Peskinea8861e02023-09-05 20:20:51 +0200124 if name in (
125 'MBEDTLS_PLATFORM_GMTIME_R_ALT',
126 'MBEDTLS_PLATFORM_SETUP_TEARDOWN_ALT',
127 'MBEDTLS_PLATFORM_MS_TIME_ALT',
128 'MBEDTLS_PLATFORM_ZEROIZE_ALT',
129 ):
Gilles Peskinec34faba2020-04-20 15:44:14 +0200130 # Similar to non-platform xxx_ALT, requires platform_alt.h
131 return False
Gilles Peskine32e889d2020-04-12 23:43:28 +0200132 return name.startswith('MBEDTLS_PLATFORM_')
133
Gilles Peskine53d41ae2019-07-27 23:31:53 +0200134def include_in_full(name):
135 """Rules for symbols in the "full" configuration."""
Gilles Peskinebbaa2b72020-04-12 13:33:57 +0200136 if name in EXCLUDE_FROM_FULL:
Gilles Peskine53d41ae2019-07-27 23:31:53 +0200137 return False
138 if name.endswith('_ALT'):
Gilles Peskine32e889d2020-04-12 23:43:28 +0200139 return is_seamless_alt(name)
Gilles Peskine53d41ae2019-07-27 23:31:53 +0200140 return True
141
142def full_adapter(name, active, section):
143 """Config adapter for "full"."""
144 if not is_full_section(section):
145 return active
146 return include_in_full(name)
147
Gilles Peskinecfffc282020-04-12 13:55:45 +0200148# The baremetal configuration excludes options that require a library or
149# operating system feature that is typically not present on bare metal
150# systems. Features that are excluded from "full" won't be in "baremetal"
151# either (unless explicitly turned on in baremetal_adapter) so they don't
152# need to be repeated here.
Gilles Peskinebbaa2b72020-04-12 13:33:57 +0200153EXCLUDE_FROM_BAREMETAL = frozenset([
Gilles Peskinecfffc282020-04-12 13:55:45 +0200154 #pylint: disable=line-too-long
Gilles Peskine98f8f952020-04-20 15:38:39 +0200155 'MBEDTLS_ENTROPY_NV_SEED', # requires a filesystem and FS_IO or alternate NV seed hooks
Gilles Peskinecfffc282020-04-12 13:55:45 +0200156 'MBEDTLS_FS_IO', # requires a filesystem
Gilles Peskinecfffc282020-04-12 13:55:45 +0200157 'MBEDTLS_HAVE_TIME', # requires a clock
158 'MBEDTLS_HAVE_TIME_DATE', # requires a clock
159 'MBEDTLS_NET_C', # requires POSIX-like networking
160 'MBEDTLS_PLATFORM_FPRINTF_ALT', # requires FILE* from stdio.h
Gilles Peskine98f8f952020-04-20 15:38:39 +0200161 'MBEDTLS_PLATFORM_NV_SEED_ALT', # requires a filesystem and ENTROPY_NV_SEED
162 'MBEDTLS_PLATFORM_TIME_ALT', # requires a clock and HAVE_TIME
163 'MBEDTLS_PSA_CRYPTO_SE_C', # requires a filesystem and PSA_CRYPTO_STORAGE_C
Gilles Peskinecfffc282020-04-12 13:55:45 +0200164 'MBEDTLS_PSA_CRYPTO_STORAGE_C', # requires a filesystem
165 'MBEDTLS_PSA_ITS_FILE_C', # requires a filesystem
166 'MBEDTLS_THREADING_C', # requires a threading interface
167 'MBEDTLS_THREADING_PTHREAD', # requires pthread
168 'MBEDTLS_TIMING_C', # requires a clock
Dave Rodgman9be3cf02023-10-11 14:47:55 +0100169 'MBEDTLS_SHA256_USE_A64_CRYPTO_IF_PRESENT', # requires an OS for runtime-detection
Dave Rodgman5b89c552023-10-10 14:59:02 +0100170 'MBEDTLS_SHA256_USE_ARMV8_A_CRYPTO_IF_PRESENT', # requires an OS for runtime-detection
Dave Rodgmanbe7915a2023-10-11 10:46:38 +0100171 'MBEDTLS_SHA512_USE_A64_CRYPTO_IF_PRESENT', # requires an OS for runtime-detection
Gilles Peskinebbaa2b72020-04-12 13:33:57 +0200172])
173
Gilles Peskine53d41ae2019-07-27 23:31:53 +0200174def keep_in_baremetal(name):
175 """Rules for symbols in the "baremetal" configuration."""
Gilles Peskinebbaa2b72020-04-12 13:33:57 +0200176 if name in EXCLUDE_FROM_BAREMETAL:
Gilles Peskine53d41ae2019-07-27 23:31:53 +0200177 return False
178 return True
179
180def baremetal_adapter(name, active, section):
181 """Config adapter for "baremetal"."""
182 if not is_full_section(section):
183 return active
184 if name == 'MBEDTLS_NO_PLATFORM_ENTROPY':
Gilles Peskinecfffc282020-04-12 13:55:45 +0200185 # No OS-provided entropy source
Gilles Peskine53d41ae2019-07-27 23:31:53 +0200186 return True
187 return include_in_full(name) and keep_in_baremetal(name)
188
Gilles Peskine120f29d2021-09-01 19:51:19 +0200189# This set contains options that are mostly for debugging or test purposes,
190# and therefore should be excluded when doing code size measurements.
191# Options that are their own module (such as MBEDTLS_ERROR_C) are not listed
192# and therefore will be included when doing code size measurements.
193EXCLUDE_FOR_SIZE = frozenset([
194 'MBEDTLS_DEBUG_C', # large code size increase in TLS
195 'MBEDTLS_SELF_TEST', # increases the size of many modules
196 'MBEDTLS_TEST_HOOKS', # only useful with the hosted test framework, increases code size
197])
198
199def baremetal_size_adapter(name, active, section):
200 if name in EXCLUDE_FOR_SIZE:
201 return False
202 return baremetal_adapter(name, active, section)
203
Gilles Peskine31987c62020-01-31 14:23:30 +0100204def include_in_crypto(name):
205 """Rules for symbols in a crypto configuration."""
206 if name.startswith('MBEDTLS_X509_') or \
207 name.startswith('MBEDTLS_SSL_') or \
208 name.startswith('MBEDTLS_KEY_EXCHANGE_'):
209 return False
210 if name in [
Gilles Peskinecfffc282020-04-12 13:55:45 +0200211 'MBEDTLS_DEBUG_C', # part of libmbedtls
212 'MBEDTLS_NET_C', # part of libmbedtls
Nayna Jainc9deb182020-11-16 19:03:12 +0000213 'MBEDTLS_PKCS7_C', # part of libmbedx509
Gilles Peskine31987c62020-01-31 14:23:30 +0100214 ]:
215 return False
Gabor Mezei634103c2024-09-11 13:08:21 +0200216 if name in EXCLUDE_FROM_CRYPTO:
217 return False
Gilles Peskine31987c62020-01-31 14:23:30 +0100218 return True
219
220def crypto_adapter(adapter):
221 """Modify an adapter to disable non-crypto symbols.
222
223 ``crypto_adapter(adapter)(name, active, section)`` is like
224 ``adapter(name, active, section)``, but unsets all X.509 and TLS symbols.
225 """
226 def continuation(name, active, section):
227 if not include_in_crypto(name):
228 return False
229 if adapter is None:
230 return active
231 return adapter(name, active, section)
232 return continuation
233
Gilles Peskineed5c21d2022-06-27 23:02:09 +0200234DEPRECATED = frozenset([
235 'MBEDTLS_PSA_CRYPTO_SE_C',
Gabor Mezei634103c2024-09-11 13:08:21 +0200236 *PSA_DEPRECATED_FEATURE
Gilles Peskineed5c21d2022-06-27 23:02:09 +0200237])
Gilles Peskine30de2e82020-04-20 21:39:22 +0200238def no_deprecated_adapter(adapter):
Gilles Peskinebe1d6092020-04-12 14:17:16 +0200239 """Modify an adapter to disable deprecated symbols.
240
Gilles Peskine30de2e82020-04-20 21:39:22 +0200241 ``no_deprecated_adapter(adapter)(name, active, section)`` is like
Gilles Peskinebe1d6092020-04-12 14:17:16 +0200242 ``adapter(name, active, section)``, but unsets all deprecated symbols
243 and sets ``MBEDTLS_DEPRECATED_REMOVED``.
244 """
245 def continuation(name, active, section):
246 if name == 'MBEDTLS_DEPRECATED_REMOVED':
247 return True
Gilles Peskineed5c21d2022-06-27 23:02:09 +0200248 if name in DEPRECATED:
249 return False
Gilles Peskinebe1d6092020-04-12 14:17:16 +0200250 if adapter is None:
251 return active
252 return adapter(name, active, section)
253 return continuation
254
Paul Elliottfb81f772023-10-18 17:44:59 +0100255def no_platform_adapter(adapter):
256 """Modify an adapter to disable platform symbols.
257
258 ``no_platform_adapter(adapter)(name, active, section)`` is like
259 ``adapter(name, active, section)``, but unsets all platform symbols other
260 ``than MBEDTLS_PLATFORM_C.
261 """
262 def continuation(name, active, section):
263 # Allow MBEDTLS_PLATFORM_C but remove all other platform symbols.
264 if name.startswith('MBEDTLS_PLATFORM_') and name != 'MBEDTLS_PLATFORM_C':
265 return False
266 if adapter is None:
267 return active
268 return adapter(name, active, section)
269 return continuation
270
Gilles Peskineb4063892019-07-27 21:36:44 +0200271
Gabor Mezei634103c2024-09-11 13:08:21 +0200272class MbedTLSConfigFile(config_common.ConfigFile):
273 """Representation of an MbedTLS configuration file."""
Gilles Peskineb4063892019-07-27 21:36:44 +0200274
Bence Szépkútibb0cfeb2021-05-28 09:42:25 +0200275 _path_in_tree = 'include/mbedtls/mbedtls_config.h'
Gilles Peskine208e4ec2019-07-29 23:43:20 +0200276 default_path = [_path_in_tree,
277 os.path.join(os.path.dirname(__file__),
278 os.pardir,
279 _path_in_tree),
280 os.path.join(os.path.dirname(os.path.abspath(os.path.dirname(__file__))),
281 _path_in_tree)]
Gilles Peskineb4063892019-07-27 21:36:44 +0200282
283 def __init__(self, filename=None):
Gabor Mezei634103c2024-09-11 13:08:21 +0200284 super().__init__(self.default_path, 'Mbed TLS', filename)
Gilles Peskine53d41ae2019-07-27 23:31:53 +0200285 self.current_section = 'header'
Gabor Mezei634103c2024-09-11 13:08:21 +0200286
287
288class CryptoConfigFile(config_common.ConfigFile):
289 """Representation of a Crypto configuration file."""
290
291 # Temporary, while Mbed TLS does not just rely on the TF-PSA-Crypto
292 # build system to build its crypto library. When it does, the
293 # condition can just be removed.
294 _path_in_tree = ('include/psa/crypto_config.h'
295 if not os.path.isdir(os.path.join(os.path.dirname(__file__),
296 os.pardir,
297 'tf-psa-crypto')) else
298 'tf-psa-crypto/include/psa/crypto_config.h')
299 default_path = [_path_in_tree,
300 os.path.join(os.path.dirname(__file__),
301 os.pardir,
302 _path_in_tree),
303 os.path.join(os.path.dirname(os.path.abspath(os.path.dirname(__file__))),
304 _path_in_tree)]
305
306 def __init__(self, filename=None):
307 super().__init__(self.default_path, 'Crypto', filename)
308
309
310class MbedTLSConfig(config_common.Config):
311 """Representation of the Mbed TLS configuration.
312
313 See the documentation of the `Config` class for methods to query
314 and modify the configuration.
315 """
316
317 def __init__(self, filename=None):
318 """Read the Mbed TLS configuration file."""
319
320 super().__init__()
321 configfile = MbedTLSConfigFile(filename)
322 self.configfiles.append(configfile)
323 self.settings.update({name: config_common.Setting(configfile, active, name, value, section)
324 for (active, name, value, section)
325 in configfile.parse_file()})
Gilles Peskineb4063892019-07-27 21:36:44 +0200326
327 def set(self, name, value=None):
Gabor Mezei634103c2024-09-11 13:08:21 +0200328 """Set name to the given value and make it active."""
329
Gilles Peskineb4063892019-07-27 21:36:44 +0200330 if name not in self.settings:
Gabor Mezei634103c2024-09-11 13:08:21 +0200331 self._get_configfile().templates.append((name, '', '#define ' + name + ' '))
332
Gilles Peskineb4063892019-07-27 21:36:44 +0200333 super().set(name, value)
334
Gilles Peskineb4063892019-07-27 21:36:44 +0200335
Gabor Mezei634103c2024-09-11 13:08:21 +0200336class CryptoConfig(config_common.Config):
337 """Representation of the PSA crypto configuration.
Gilles Peskineb4063892019-07-27 21:36:44 +0200338
Gabor Mezei634103c2024-09-11 13:08:21 +0200339 See the documentation of the `Config` class for methods to query
340 and modify the configuration.
341 """
Gilles Peskineb4063892019-07-27 21:36:44 +0200342
Gabor Mezei634103c2024-09-11 13:08:21 +0200343 def __init__(self, filename=None):
344 """Read the PSA crypto configuration file."""
345
346 super().__init__()
347 configfile = CryptoConfigFile(filename)
348 self.configfiles.append(configfile)
349 self.settings.update({name: config_common.Setting(configfile, active, name, value, section)
350 for (active, name, value, section)
351 in configfile.parse_file()})
352
353 def set(self, name, value='1'):
354 """Set name to the given value and make it active."""
355
356 if name in PSA_UNSUPPORTED_FEATURE:
357 raise ValueError(f'Feature is unsupported: \'{name}\'')
358 if name in PSA_UNSTABLE_FEATURE:
359 raise ValueError(f'Feature is unstable: \'{name}\'')
360
361 if name not in self.settings:
362 self._get_configfile().templates.append((name, '', '#define ' + name + ' '))
363
364 super().set(name, value)
365
366
367class CombinedConfig(config_common.Config):
368 """Representation of MbedTLS and PSA crypto configuration
369
370 See the documentation of the `Config` class for methods to query
371 and modify the configuration.
372 """
373
374 def __init__(self, *configs):
375 super().__init__()
376 for config in configs:
377 if isinstance(config, MbedTLSConfigFile):
378 self.mbedtls_configfile = config
379 elif isinstance(config, CryptoConfigFile):
380 self.crypto_configfile = config
Gilles Peskineb4063892019-07-27 21:36:44 +0200381 else:
Gabor Mezei634103c2024-09-11 13:08:21 +0200382 raise ValueError(f'Invalid configfile: {config}')
383 self.configfiles.append(config)
Gilles Peskineb4063892019-07-27 21:36:44 +0200384
Gabor Mezei634103c2024-09-11 13:08:21 +0200385 self.settings.update({name: config_common.Setting(configfile, active, name, value, section)
386 for configfile in [self.mbedtls_configfile, self.crypto_configfile]
387 for (active, name, value, section) in configfile.parse_file()})
388
389 _crypto_regexp = re.compile(r'$PSA_.*')
390 def _get_configfile(self, name=None):
391 """Find a config type for a setting name"""
392
393 if name in self.settings:
394 return self.settings[name].configfile
395 elif re.match(self._crypto_regexp, name):
396 return self.crypto_configfile
397 else:
398 return self.mbedtls_configfile
399
400 def set(self, name, value=None):
401 """Set name to the given value and make it active."""
402
403 configfile = self._get_configfile(name)
404
405 if configfile == self.crypto_configfile:
406 if name in PSA_UNSUPPORTED_FEATURE:
407 raise ValueError(f'Feature is unsupported: \'{name}\'')
408 if name in PSA_UNSTABLE_FEATURE:
409 raise ValueError(f'Feature is unstable: \'{name}\'')
410
411 # The default value in the crypto config is '1'
412 if not value:
413 value = '1'
414
415 if name not in self.settings:
416 configfile.templates.append((name, '', '#define ' + name + ' '))
417
418 super().set(name, value)
419
420 #pylint: disable=arguments-differ
421 def write(self, mbedtls_file=None, crypto_file=None):
Gilles Peskineb4063892019-07-27 21:36:44 +0200422 """Write the whole configuration to the file it was read from.
423
Gabor Mezei634103c2024-09-11 13:08:21 +0200424 If mbedtls_file or crypto_file is specified, write the specific configuration
425 to the corresponding file instead.
Gabor Mezei3ae480b2024-09-18 13:02:16 +0200426
Gabor Mezeid72c9f92024-09-18 16:51:27 +0200427 Two file name parameters and not only one as in the super class as we handle
428 two configuration files in this class.
Gilles Peskineb4063892019-07-27 21:36:44 +0200429 """
Gabor Mezei634103c2024-09-11 13:08:21 +0200430
431 self.mbedtls_configfile.write(self.settings, mbedtls_file)
432 self.crypto_configfile.write(self.settings, crypto_file)
433
434 def filename(self, name=None):
Gabor Mezei3ae480b2024-09-18 13:02:16 +0200435 """Get the name of the config files.
Gabor Mezei634103c2024-09-11 13:08:21 +0200436
437 If 'name' is specified return the name of the config file where it is defined.
438 """
439
440 if not name:
441 return [config.filename for config in [self.mbedtls_configfile, self.crypto_configfile]]
442
443 return self._get_configfile(name).filename
444
445
446class MbedTLSConfigTool(config_common.ConfigTool):
447 """Command line mbedtls_config.h and crypto_config.h manipulation tool."""
448
449 def __init__(self):
450 super().__init__(MbedTLSConfigFile)
Gabor Mezei2285ed82024-09-18 13:02:42 +0200451 self.config = CombinedConfig(MbedTLSConfigFile(self.args.file),
452 CryptoConfigFile(self.args.cryptofile))
Gabor Mezei634103c2024-09-11 13:08:21 +0200453
454 def custom_parser_options(self):
455 """Adds MbedTLS specific options for the parser."""
456
457 self.parser.add_argument(
458 '--cryptofile', '-c',
459 help="""Crypto file to read (and modify if requested). Default: {}."""
460 .format(CryptoConfigFile.default_path))
461
462 self.add_adapter(
463 'baremetal', baremetal_adapter,
464 """Like full, but exclude features that require platform features
465 such as file input-output.
466 """)
467 self.add_adapter(
468 'baremetal_size', baremetal_size_adapter,
469 """Like baremetal, but exclude debugging features. Useful for code size measurements.
470 """)
471 self.add_adapter(
472 'full', full_adapter,
473 """Uncomment most features.
474 Exclude alternative implementations and platform support options, as well as
475 some options that are awkward to test.
476 """)
477 self.add_adapter(
478 'full_no_deprecated', no_deprecated_adapter(full_adapter),
479 """Uncomment most non-deprecated features.
480 Like "full", but without deprecated features.
481 """)
482 self.add_adapter(
483 'full_no_platform', no_platform_adapter(full_adapter),
484 """Uncomment most non-platform features. Like "full", but without platform features.
485 """)
486 self.add_adapter(
487 'realfull', realfull_adapter,
488 """Uncomment all boolean #defines.
489 Suitable for generating documentation, but not for building.
490 """)
491 self.add_adapter(
492 'crypto', crypto_adapter(None),
493 """Only include crypto features. Exclude X.509 and TLS.""")
494 self.add_adapter(
495 'crypto_baremetal', crypto_adapter(baremetal_adapter),
496 """Like baremetal, but with only crypto features, excluding X.509 and TLS.""")
497 self.add_adapter(
498 'crypto_full', crypto_adapter(full_adapter),
499 """Like full, but with only crypto features, excluding X.509 and TLS.""")
500
Gilles Peskineb4063892019-07-27 21:36:44 +0200501
502if __name__ == '__main__':
Gabor Mezei634103c2024-09-11 13:08:21 +0200503 sys.exit(MbedTLSConfigTool().main())