blob: 89b05a689a2afba63515961439f4dd72c2d17094 [file] [log] [blame]
Gilles Peskineb4063892019-07-27 21:36:44 +02001#!/usr/bin/env python3
2
Gabor Mezei9f2b8172024-08-06 12:02:18 +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 Mezei9f2b8172024-08-06 12:02:18 +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
16
Gabor Mezeie7742b32024-06-26 18:04:09 +020017from abc import ABCMeta
Gabor Mezei3678dee2024-06-04 19:58:43 +020018
Gilles Peskineb4063892019-07-27 21:36:44 +020019class Setting:
Gabor Mezei9f2b8172024-08-06 12:02:18 +020020 """Representation of one Mbed TLS mbedtls_config.h pr PSA crypto_config.h setting.
Gilles Peskineb4063892019-07-27 21:36:44 +020021
22 Fields:
23 * name: the symbol name ('MBEDTLS_xxx').
24 * value: the value of the macro. The empty string for a plain #define
25 with no value.
26 * active: True if name is defined, False if a #define for name is
Bence Szépkútibb0cfeb2021-05-28 09:42:25 +020027 present in mbedtls_config.h but commented out.
Gilles Peskine53d41ae2019-07-27 23:31:53 +020028 * section: the name of the section that contains this symbol.
Gilles Peskineb4063892019-07-27 21:36:44 +020029 """
Gabor Mezei92065ed2024-06-07 13:47:59 +020030 # pylint: disable=too-few-public-methods, too-many-arguments
Gabor Mezei3678dee2024-06-04 19:58:43 +020031 def __init__(self, active, name, value='', section=None, configfile=None):
Gilles Peskineb4063892019-07-27 21:36:44 +020032 self.active = active
33 self.name = name
34 self.value = value
Gilles Peskine53d41ae2019-07-27 23:31:53 +020035 self.section = section
Gabor Mezei3678dee2024-06-04 19:58:43 +020036 self.configfile = configfile
Gilles Peskineb4063892019-07-27 21:36:44 +020037
38class Config:
Gabor Mezei9f2b8172024-08-06 12:02:18 +020039 """Representation of the Mbed TLS and PSA configuration.
Gilles Peskineb4063892019-07-27 21:36:44 +020040
41 In the documentation of this class, a symbol is said to be *active*
42 if there is a #define for it that is not commented out, and *known*
43 if there is a #define for it whether commented out or not.
44
45 This class supports the following protocols:
Gilles Peskinec190c902019-08-01 23:31:05 +020046 * `name in config` is `True` if the symbol `name` is active, `False`
47 otherwise (whether `name` is inactive or not known).
48 * `config[name]` is the value of the macro `name`. If `name` is inactive,
49 raise `KeyError` (even if `name` is known).
Gilles Peskineb4063892019-07-27 21:36:44 +020050 * `config[name] = value` sets the value associated to `name`. `name`
51 must be known, but does not need to be set. This does not cause
52 name to become set.
53 """
54
Gabor Mezeiee521b62024-06-07 13:50:41 +020055 def __init__(self):
Gilles Peskineb4063892019-07-27 21:36:44 +020056 self.settings = {}
57
58 def __contains__(self, name):
59 """True if the given symbol is active (i.e. set).
60
61 False if the given symbol is not set, even if a definition
62 is present but commented out.
63 """
64 return name in self.settings and self.settings[name].active
65
66 def all(self, *names):
67 """True if all the elements of names are active (i.e. set)."""
Gabor Mezeidaf807f2024-08-14 11:33:46 +020068 return all(name in self for name in names)
Gilles Peskineb4063892019-07-27 21:36:44 +020069
70 def any(self, *names):
71 """True if at least one symbol in names are active (i.e. set)."""
Gabor Mezeidaf807f2024-08-14 11:33:46 +020072 return any(name in self for name in names)
Gilles Peskineb4063892019-07-27 21:36:44 +020073
74 def known(self, name):
75 """True if a #define for name is present, whether it's commented out or not."""
76 return name in self.settings
77
78 def __getitem__(self, name):
79 """Get the value of name, i.e. what the preprocessor symbol expands to.
80
81 If name is not known, raise KeyError. name does not need to be active.
82 """
83 return self.settings[name].value
84
85 def get(self, name, default=None):
86 """Get the value of name. If name is inactive (not set), return default.
87
88 If a #define for name is present and not commented out, return
89 its expansion, even if this is the empty string.
90
91 If a #define for name is present but commented out, return default.
92 """
93 if name in self.settings:
94 return self.settings[name].value
95 else:
96 return default
97
98 def __setitem__(self, name, value):
99 """If name is known, set its value.
100
101 If name is not known, raise KeyError.
102 """
Gabor Mezeic659c1b2024-08-06 17:37:55 +0200103 setting = self.settings[name]
104 if setting.configfile and setting != value:
105 setting.configfile.modified = True
Gilles Peskineb4063892019-07-27 21:36:44 +0200106
Gabor Mezeic659c1b2024-08-06 17:37:55 +0200107 setting.value = value
108
109 def set(self, name, value=None, configfile=None):
Gilles Peskineb4063892019-07-27 21:36:44 +0200110 """Set name to the given value and make it active.
111
112 If value is None and name is already known, don't change its value.
Gabor Mezeic659c1b2024-08-06 17:37:55 +0200113 If value is None and name is not known, set its value.
Gilles Peskineb4063892019-07-27 21:36:44 +0200114 """
115 if name in self.settings:
Gabor Mezeic659c1b2024-08-06 17:37:55 +0200116 setting = self.settings[name]
117 if setting.configfile and (setting.value != value or not setting.active):
118 setting.configfile.modified = True
Gilles Peskineb4063892019-07-27 21:36:44 +0200119 if value is not None:
Gabor Mezeic659c1b2024-08-06 17:37:55 +0200120 setting.value = value
121 setting.active = True
Gilles Peskineb4063892019-07-27 21:36:44 +0200122 else:
Gabor Mezeic659c1b2024-08-06 17:37:55 +0200123 self.settings[name] = Setting(True, name, value=value, configfile=configfile)
124 if configfile:
125 self.settings[name].configfile.modified = True
Gilles Peskineb4063892019-07-27 21:36:44 +0200126
127 def unset(self, name):
128 """Make name unset (inactive).
129
Gilles Peskine55cc4db2019-08-01 23:13:23 +0200130 name remains known if it was known before.
Gilles Peskineb4063892019-07-27 21:36:44 +0200131 """
Gilles Peskine55cc4db2019-08-01 23:13:23 +0200132 if name not in self.settings:
133 return
Gabor Mezeic5ff33c2024-06-28 17:46:44 +0200134
135 setting = self.settings[name]
136 # Check if modifying the config file
137 if setting.configfile and setting.active:
138 setting.configfile.modified = True
139
140 setting.active = False
Gilles Peskineb4063892019-07-27 21:36:44 +0200141
142 def adapt(self, adapter):
143 """Run adapter on each known symbol and (de)activate it accordingly.
144
145 `adapter` must be a function that returns a boolean. It is called as
Gilles Peskine53d41ae2019-07-27 23:31:53 +0200146 `adapter(name, active, section)` for each setting, where `active` is
147 `True` if `name` is set and `False` if `name` is known but unset,
148 and `section` is the name of the section containing `name`. If
Gilles Peskineb4063892019-07-27 21:36:44 +0200149 `adapter` returns `True`, then set `name` (i.e. make it active),
150 otherwise unset `name` (i.e. make it known but inactive).
151 """
152 for setting in self.settings.values():
Gabor Mezeic5ff33c2024-06-28 17:46:44 +0200153 is_active = setting.active
Gilles Peskine53d41ae2019-07-27 23:31:53 +0200154 setting.active = adapter(setting.name, setting.active,
155 setting.section)
Gabor Mezeic5ff33c2024-06-28 17:46:44 +0200156 # Check if modifying the config file
157 if setting.configfile and setting.active != is_active:
158 setting.configfile.modified = True
Gilles Peskineb4063892019-07-27 21:36:44 +0200159
Gilles Peskine8e90cf42021-05-27 22:12:57 +0200160 def change_matching(self, regexs, enable):
161 """Change all symbols matching one of the regexs to the desired state."""
162 if not regexs:
163 return
164 regex = re.compile('|'.join(regexs))
165 for setting in self.settings.values():
166 if regex.search(setting.name):
Gabor Mezeic5ff33c2024-06-28 17:46:44 +0200167 # Check if modifying the config file
168 if setting.configfile and setting.active != enable:
169 setting.configfile.modified = True
Gilles Peskine8e90cf42021-05-27 22:12:57 +0200170 setting.active = enable
171
Gilles Peskine53d41ae2019-07-27 23:31:53 +0200172def is_full_section(section):
Gabor Mezeide6e1922024-06-28 17:10:50 +0200173 """Is this section affected by "config.py full" and friends?
174
175 In a config file where the sections are not used the whole config file
176 is an empty section (with value None) and the whole file is affected.
177 """
Gabor Mezei3678dee2024-06-04 19:58:43 +0200178 return section is None or section.endswith('support') or section.endswith('modules')
Gilles Peskine53d41ae2019-07-27 23:31:53 +0200179
180def realfull_adapter(_name, active, section):
Gilles Peskineba4162a2022-04-11 17:04:38 +0200181 """Activate all symbols found in the global and boolean feature sections.
182
183 This is intended for building the documentation, including the
184 documentation of settings that are activated by defining an optional
185 preprocessor macro.
186
187 Do not activate definitions in the section containing symbols that are
188 supposed to be defined and documented in their own module.
189 """
190 if section == 'Module configuration options':
Gilles Peskine53d41ae2019-07-27 23:31:53 +0200191 return active
Gilles Peskineb4063892019-07-27 21:36:44 +0200192 return True
193
Gabor Mezei542fd382024-06-10 14:07:42 +0200194PSA_UNSUPPORTED_FEATURE = frozenset([
Gabor Mezei3678dee2024-06-04 19:58:43 +0200195 'PSA_WANT_ALG_CBC_MAC',
196 'PSA_WANT_ALG_XTS',
197 'PSA_WANT_KEY_TYPE_RSA_KEY_PAIR_DERIVE',
198 'PSA_WANT_KEY_TYPE_DH_KEY_PAIR_DERIVE'
199])
200
Gabor Mezei542fd382024-06-10 14:07:42 +0200201PSA_DEPRECATED_FEATURE = frozenset([
Gabor Mezei3678dee2024-06-04 19:58:43 +0200202 'PSA_WANT_KEY_TYPE_ECC_KEY_PAIR',
203 'PSA_WANT_KEY_TYPE_RSA_KEY_PAIR'
204])
205
Gabor Mezei542fd382024-06-10 14:07:42 +0200206PSA_UNSTABLE_FEATURE = frozenset([
Gabor Mezei3678dee2024-06-04 19:58:43 +0200207 'PSA_WANT_ECC_SECP_K1_224'
208])
209
Gabor Mezei9b0f9e72024-06-26 18:08:17 +0200210EXCLUDE_FROM_CRYPTO = PSA_UNSUPPORTED_FEATURE | \
211 PSA_DEPRECATED_FEATURE | \
212 PSA_UNSTABLE_FEATURE
Gabor Mezei542fd382024-06-10 14:07:42 +0200213
Gilles Peskinecfffc282020-04-12 13:55:45 +0200214# The goal of the full configuration is to have everything that can be tested
215# together. This includes deprecated or insecure options. It excludes:
216# * Options that require additional build dependencies or unusual hardware.
217# * Options that make testing less effective.
Gilles Peskinec9d04332020-04-16 20:50:17 +0200218# * Options that are incompatible with other options, or more generally that
219# interact with other parts of the code in such a way that a bulk enabling
220# is not a good way to test them.
Gilles Peskinecfffc282020-04-12 13:55:45 +0200221# * Options that remove features.
Gilles Peskinebbaa2b72020-04-12 13:33:57 +0200222EXCLUDE_FROM_FULL = frozenset([
Gilles Peskinecfffc282020-04-12 13:55:45 +0200223 #pylint: disable=line-too-long
Yanray Wanga8704672023-04-20 17:16:48 +0800224 'MBEDTLS_AES_ONLY_128_BIT_KEY_LENGTH', # interacts with CTR_DRBG_128_BIT_KEY
Gilles Peskinea8861e02023-09-05 20:20:51 +0200225 'MBEDTLS_AES_USE_HARDWARE_ONLY', # hardware dependency
Yanray Wang42be1ba2023-11-23 14:28:47 +0800226 'MBEDTLS_BLOCK_CIPHER_NO_DECRYPT', # incompatible with ECB in PSA, CBC/XTS/NIST_KW/DES
Gilles Peskinec9d04332020-04-16 20:50:17 +0200227 'MBEDTLS_CTR_DRBG_USE_128_BIT_KEY', # interacts with ENTROPY_FORCE_SHA256
Gilles Peskinecfffc282020-04-12 13:55:45 +0200228 'MBEDTLS_DEPRECATED_REMOVED', # conflicts with deprecated options
Gilles Peskine90581ee2020-04-12 14:02:47 +0200229 'MBEDTLS_DEPRECATED_WARNING', # conflicts with deprecated options
Gilles Peskinec9d04332020-04-16 20:50:17 +0200230 'MBEDTLS_ECDH_VARIANT_EVEREST_ENABLED', # influences the use of ECDH in TLS
Janos Follath5b7c38f2023-08-01 08:51:12 +0100231 'MBEDTLS_ECP_WITH_MPI_UINT', # disables the default ECP and is experimental
Gilles Peskinec9d04332020-04-16 20:50:17 +0200232 'MBEDTLS_ENTROPY_FORCE_SHA256', # interacts with CTR_DRBG_128_BIT_KEY
Gilles Peskinecfffc282020-04-12 13:55:45 +0200233 'MBEDTLS_HAVE_SSE2', # hardware dependency
234 'MBEDTLS_MEMORY_BACKTRACE', # depends on MEMORY_BUFFER_ALLOC_C
235 'MBEDTLS_MEMORY_BUFFER_ALLOC_C', # makes sanitizers (e.g. ASan) less effective
236 'MBEDTLS_MEMORY_DEBUG', # depends on MEMORY_BUFFER_ALLOC_C
Gilles Peskinec9d04332020-04-16 20:50:17 +0200237 'MBEDTLS_NO_64BIT_MULTIPLICATION', # influences anything that uses bignum
Gilles Peskinecfffc282020-04-12 13:55:45 +0200238 'MBEDTLS_NO_DEFAULT_ENTROPY_SOURCES', # removes a feature
239 'MBEDTLS_NO_PLATFORM_ENTROPY', # removes a feature
Gilles Peskinec9d04332020-04-16 20:50:17 +0200240 'MBEDTLS_NO_UDBL_DIVISION', # influences anything that uses bignum
Gilles Peskineefaee9a2023-09-20 20:49:47 +0200241 'MBEDTLS_PSA_P256M_DRIVER_ENABLED', # influences SECP256R1 KeyGen/ECDH/ECDSA
Gilles Peskinecfffc282020-04-12 13:55:45 +0200242 'MBEDTLS_PLATFORM_NO_STD_FUNCTIONS', # removes a feature
David Horstmann6f8c95b2024-03-14 14:52:45 +0000243 'MBEDTLS_PSA_ASSUME_EXCLUSIVE_BUFFERS', # removes a feature
Gilles Peskinef08b3f82020-11-13 17:36:48 +0100244 'MBEDTLS_PSA_CRYPTO_EXTERNAL_RNG', # behavior change + build dependency
Ronald Cronc3623db2020-10-29 10:51:32 +0100245 'MBEDTLS_PSA_CRYPTO_KEY_ID_ENCODES_OWNER', # incompatible with USE_PSA_CRYPTO
Gilles Peskinecfffc282020-04-12 13:55:45 +0200246 'MBEDTLS_PSA_CRYPTO_SPM', # platform dependency (PSA SPM)
Gilles Peskinea08def92023-04-28 21:01:49 +0200247 'MBEDTLS_PSA_INJECT_ENTROPY', # conflicts with platform entropy sources
Gilles Peskinec9d04332020-04-16 20:50:17 +0200248 'MBEDTLS_RSA_NO_CRT', # influences the use of RSA in X.509 and TLS
Tom Cosgrove87fbfb52022-03-15 10:51:52 +0000249 'MBEDTLS_SHA256_USE_A64_CRYPTO_ONLY', # interacts with *_USE_A64_CRYPTO_IF_PRESENT
Dave Rodgman9be3cf02023-10-11 14:47:55 +0100250 'MBEDTLS_SHA256_USE_ARMV8_A_CRYPTO_ONLY', # interacts with *_USE_ARMV8_A_CRYPTO_IF_PRESENT
Tom Cosgrove87fbfb52022-03-15 10:51:52 +0000251 'MBEDTLS_SHA512_USE_A64_CRYPTO_ONLY', # interacts with *_USE_A64_CRYPTO_IF_PRESENT
Dave Rodgman7cb635a2023-10-12 16:14:51 +0100252 'MBEDTLS_SHA256_USE_A64_CRYPTO_IF_PRESENT', # setting *_USE_ARMV8_A_CRYPTO is sufficient
Manuel Pégourié-Gonnard6240def2020-07-10 09:35:54 +0200253 'MBEDTLS_TEST_CONSTANT_FLOW_MEMSAN', # build dependency (clang+memsan)
Manuel Pégourié-Gonnard73afa372020-08-19 10:27:38 +0200254 'MBEDTLS_TEST_CONSTANT_FLOW_VALGRIND', # build dependency (valgrind headers)
Hanno Beckere1113562019-06-12 13:59:14 +0100255 'MBEDTLS_X509_REMOVE_INFO', # removes a feature
Gabor Mezei542fd382024-06-10 14:07:42 +0200256 *PSA_UNSUPPORTED_FEATURE,
257 *PSA_DEPRECATED_FEATURE,
258 *PSA_UNSTABLE_FEATURE
Gilles Peskinebbaa2b72020-04-12 13:33:57 +0200259])
260
Gilles Peskine32e889d2020-04-12 23:43:28 +0200261def is_seamless_alt(name):
Gilles Peskinec34faba2020-04-20 15:44:14 +0200262 """Whether the xxx_ALT symbol should be included in the full configuration.
Gilles Peskine32e889d2020-04-12 23:43:28 +0200263
Gilles Peskinec34faba2020-04-20 15:44:14 +0200264 Include alternative implementations of platform functions, which are
Gilles Peskine32e889d2020-04-12 23:43:28 +0200265 configurable function pointers that default to the built-in function.
266 This way we test that the function pointers exist and build correctly
267 without changing the behavior, and tests can verify that the function
268 pointers are used by modifying those pointers.
269
270 Exclude alternative implementations of library functions since they require
271 an implementation of the relevant functions and an xxx_alt.h header.
272 """
Gilles Peskinea8861e02023-09-05 20:20:51 +0200273 if name in (
274 'MBEDTLS_PLATFORM_GMTIME_R_ALT',
275 'MBEDTLS_PLATFORM_SETUP_TEARDOWN_ALT',
276 'MBEDTLS_PLATFORM_MS_TIME_ALT',
277 'MBEDTLS_PLATFORM_ZEROIZE_ALT',
278 ):
Gilles Peskinec34faba2020-04-20 15:44:14 +0200279 # Similar to non-platform xxx_ALT, requires platform_alt.h
280 return False
Gilles Peskine32e889d2020-04-12 23:43:28 +0200281 return name.startswith('MBEDTLS_PLATFORM_')
282
Gilles Peskine53d41ae2019-07-27 23:31:53 +0200283def include_in_full(name):
284 """Rules for symbols in the "full" configuration."""
Gabor Mezei542fd382024-06-10 14:07:42 +0200285 if name in EXCLUDE_FROM_FULL:
Gilles Peskine53d41ae2019-07-27 23:31:53 +0200286 return False
287 if name.endswith('_ALT'):
Gilles Peskine32e889d2020-04-12 23:43:28 +0200288 return is_seamless_alt(name)
Gilles Peskine53d41ae2019-07-27 23:31:53 +0200289 return True
290
291def full_adapter(name, active, section):
292 """Config adapter for "full"."""
293 if not is_full_section(section):
294 return active
295 return include_in_full(name)
296
Gilles Peskinecfffc282020-04-12 13:55:45 +0200297# The baremetal configuration excludes options that require a library or
298# operating system feature that is typically not present on bare metal
299# systems. Features that are excluded from "full" won't be in "baremetal"
300# either (unless explicitly turned on in baremetal_adapter) so they don't
301# need to be repeated here.
Gilles Peskinebbaa2b72020-04-12 13:33:57 +0200302EXCLUDE_FROM_BAREMETAL = frozenset([
Gilles Peskinecfffc282020-04-12 13:55:45 +0200303 #pylint: disable=line-too-long
Gilles Peskine98f8f952020-04-20 15:38:39 +0200304 'MBEDTLS_ENTROPY_NV_SEED', # requires a filesystem and FS_IO or alternate NV seed hooks
Gilles Peskinecfffc282020-04-12 13:55:45 +0200305 'MBEDTLS_FS_IO', # requires a filesystem
Gilles Peskinecfffc282020-04-12 13:55:45 +0200306 'MBEDTLS_HAVE_TIME', # requires a clock
307 'MBEDTLS_HAVE_TIME_DATE', # requires a clock
308 'MBEDTLS_NET_C', # requires POSIX-like networking
309 'MBEDTLS_PLATFORM_FPRINTF_ALT', # requires FILE* from stdio.h
Gilles Peskine98f8f952020-04-20 15:38:39 +0200310 'MBEDTLS_PLATFORM_NV_SEED_ALT', # requires a filesystem and ENTROPY_NV_SEED
311 'MBEDTLS_PLATFORM_TIME_ALT', # requires a clock and HAVE_TIME
312 'MBEDTLS_PSA_CRYPTO_SE_C', # requires a filesystem and PSA_CRYPTO_STORAGE_C
Gilles Peskinecfffc282020-04-12 13:55:45 +0200313 'MBEDTLS_PSA_CRYPTO_STORAGE_C', # requires a filesystem
314 'MBEDTLS_PSA_ITS_FILE_C', # requires a filesystem
315 'MBEDTLS_THREADING_C', # requires a threading interface
316 'MBEDTLS_THREADING_PTHREAD', # requires pthread
317 'MBEDTLS_TIMING_C', # requires a clock
Dave Rodgman9be3cf02023-10-11 14:47:55 +0100318 'MBEDTLS_SHA256_USE_A64_CRYPTO_IF_PRESENT', # requires an OS for runtime-detection
Dave Rodgman5b89c552023-10-10 14:59:02 +0100319 'MBEDTLS_SHA256_USE_ARMV8_A_CRYPTO_IF_PRESENT', # requires an OS for runtime-detection
Dave Rodgmanbe7915a2023-10-11 10:46:38 +0100320 'MBEDTLS_SHA512_USE_A64_CRYPTO_IF_PRESENT', # requires an OS for runtime-detection
Gilles Peskinebbaa2b72020-04-12 13:33:57 +0200321])
322
Gilles Peskine53d41ae2019-07-27 23:31:53 +0200323def keep_in_baremetal(name):
324 """Rules for symbols in the "baremetal" configuration."""
Gilles Peskinebbaa2b72020-04-12 13:33:57 +0200325 if name in EXCLUDE_FROM_BAREMETAL:
Gilles Peskine53d41ae2019-07-27 23:31:53 +0200326 return False
327 return True
328
329def baremetal_adapter(name, active, section):
330 """Config adapter for "baremetal"."""
331 if not is_full_section(section):
332 return active
333 if name == 'MBEDTLS_NO_PLATFORM_ENTROPY':
Gilles Peskinecfffc282020-04-12 13:55:45 +0200334 # No OS-provided entropy source
Gilles Peskine53d41ae2019-07-27 23:31:53 +0200335 return True
336 return include_in_full(name) and keep_in_baremetal(name)
337
Gilles Peskine120f29d2021-09-01 19:51:19 +0200338# This set contains options that are mostly for debugging or test purposes,
339# and therefore should be excluded when doing code size measurements.
340# Options that are their own module (such as MBEDTLS_ERROR_C) are not listed
341# and therefore will be included when doing code size measurements.
342EXCLUDE_FOR_SIZE = frozenset([
343 'MBEDTLS_DEBUG_C', # large code size increase in TLS
344 'MBEDTLS_SELF_TEST', # increases the size of many modules
345 'MBEDTLS_TEST_HOOKS', # only useful with the hosted test framework, increases code size
346])
347
348def baremetal_size_adapter(name, active, section):
349 if name in EXCLUDE_FOR_SIZE:
350 return False
351 return baremetal_adapter(name, active, section)
352
Gilles Peskine31987c62020-01-31 14:23:30 +0100353def include_in_crypto(name):
354 """Rules for symbols in a crypto configuration."""
355 if name.startswith('MBEDTLS_X509_') or \
356 name.startswith('MBEDTLS_SSL_') or \
357 name.startswith('MBEDTLS_KEY_EXCHANGE_'):
358 return False
359 if name in [
Gilles Peskinecfffc282020-04-12 13:55:45 +0200360 'MBEDTLS_DEBUG_C', # part of libmbedtls
361 'MBEDTLS_NET_C', # part of libmbedtls
Nayna Jainc9deb182020-11-16 19:03:12 +0000362 'MBEDTLS_PKCS7_C', # part of libmbedx509
Gilles Peskine31987c62020-01-31 14:23:30 +0100363 ]:
364 return False
Gabor Mezei542fd382024-06-10 14:07:42 +0200365 if name in EXCLUDE_FROM_CRYPTO:
366 return False
Gilles Peskine31987c62020-01-31 14:23:30 +0100367 return True
368
369def crypto_adapter(adapter):
370 """Modify an adapter to disable non-crypto symbols.
371
372 ``crypto_adapter(adapter)(name, active, section)`` is like
373 ``adapter(name, active, section)``, but unsets all X.509 and TLS symbols.
374 """
375 def continuation(name, active, section):
376 if not include_in_crypto(name):
377 return False
378 if adapter is None:
379 return active
380 return adapter(name, active, section)
381 return continuation
382
Gilles Peskineed5c21d2022-06-27 23:02:09 +0200383DEPRECATED = frozenset([
384 'MBEDTLS_PSA_CRYPTO_SE_C',
Gabor Mezei542fd382024-06-10 14:07:42 +0200385 *PSA_DEPRECATED_FEATURE
Gilles Peskineed5c21d2022-06-27 23:02:09 +0200386])
Gilles Peskine30de2e82020-04-20 21:39:22 +0200387def no_deprecated_adapter(adapter):
Gilles Peskinebe1d6092020-04-12 14:17:16 +0200388 """Modify an adapter to disable deprecated symbols.
389
Gilles Peskine30de2e82020-04-20 21:39:22 +0200390 ``no_deprecated_adapter(adapter)(name, active, section)`` is like
Gilles Peskinebe1d6092020-04-12 14:17:16 +0200391 ``adapter(name, active, section)``, but unsets all deprecated symbols
392 and sets ``MBEDTLS_DEPRECATED_REMOVED``.
393 """
394 def continuation(name, active, section):
395 if name == 'MBEDTLS_DEPRECATED_REMOVED':
396 return True
Gilles Peskineed5c21d2022-06-27 23:02:09 +0200397 if name in DEPRECATED:
398 return False
Gilles Peskinebe1d6092020-04-12 14:17:16 +0200399 if adapter is None:
400 return active
401 return adapter(name, active, section)
402 return continuation
403
Paul Elliottfb81f772023-10-18 17:44:59 +0100404def no_platform_adapter(adapter):
405 """Modify an adapter to disable platform symbols.
406
407 ``no_platform_adapter(adapter)(name, active, section)`` is like
408 ``adapter(name, active, section)``, but unsets all platform symbols other
409 ``than MBEDTLS_PLATFORM_C.
410 """
411 def continuation(name, active, section):
412 # Allow MBEDTLS_PLATFORM_C but remove all other platform symbols.
413 if name.startswith('MBEDTLS_PLATFORM_') and name != 'MBEDTLS_PLATFORM_C':
414 return False
415 if adapter is None:
416 return active
417 return adapter(name, active, section)
418 return continuation
419
Gabor Mezei3678dee2024-06-04 19:58:43 +0200420class ConfigFile(metaclass=ABCMeta):
Gabor Mezei62a9bd02024-06-07 13:44:40 +0200421 """Representation of a configuration file."""
422
Gabor Mezei93a6d1f2024-06-26 18:01:09 +0200423 def __init__(self, default_path, name, filename=None):
Gabor Mezei62a9bd02024-06-07 13:44:40 +0200424 """Check if the config file exists."""
Gilles Peskineb4063892019-07-27 21:36:44 +0200425 if filename is None:
Gabor Mezei3678dee2024-06-04 19:58:43 +0200426 for candidate in default_path:
Gilles Peskinece674a92020-03-24 15:37:00 +0100427 if os.path.lexists(candidate):
428 filename = candidate
Gilles Peskine208e4ec2019-07-29 23:43:20 +0200429 break
Gilles Peskinece674a92020-03-24 15:37:00 +0100430 else:
Gabor Mezei8d72ac62024-06-28 17:18:37 +0200431 raise FileNotFoundError(f'{name} configuration file not found: '
432 f'{filename if filename else default_path}')
Gilles Peskineb4063892019-07-27 21:36:44 +0200433
Gabor Mezei3678dee2024-06-04 19:58:43 +0200434 self.filename = filename
435 self.templates = []
436 self.current_section = None
437 self.inclusion_guard = None
Gabor Mezei8a64d8e2024-06-10 15:23:43 +0200438 self.modified = False
Gilles Peskineb4063892019-07-27 21:36:44 +0200439
440 _define_line_regexp = (r'(?P<indentation>\s*)' +
441 r'(?P<commented_out>(//\s*)?)' +
442 r'(?P<define>#\s*define\s+)' +
443 r'(?P<name>\w+)' +
444 r'(?P<arguments>(?:\((?:\w|\s|,)*\))?)' +
445 r'(?P<separator>\s*)' +
446 r'(?P<value>.*)')
Gilles Peskine9ba9c212024-05-23 15:03:43 +0200447 _ifndef_line_regexp = r'#ifndef (?P<inclusion_guard>\w+)'
Gilles Peskine53d41ae2019-07-27 23:31:53 +0200448 _section_line_regexp = (r'\s*/?\*+\s*[\\@]name\s+SECTION:\s*' +
449 r'(?P<section>.*)[ */]*')
450 _config_line_regexp = re.compile(r'|'.join([_define_line_regexp,
Gilles Peskine9ba9c212024-05-23 15:03:43 +0200451 _ifndef_line_regexp,
Gilles Peskine53d41ae2019-07-27 23:31:53 +0200452 _section_line_regexp]))
Gilles Peskineb4063892019-07-27 21:36:44 +0200453 def _parse_line(self, line):
Gabor Mezei62a9bd02024-06-07 13:44:40 +0200454 """Parse a line in the config file, save the templates representing the lines
455 and return the corresponding setting element.
456 """
Gabor Mezei4706fe72024-07-08 17:00:55 +0200457
Gilles Peskineb4063892019-07-27 21:36:44 +0200458 line = line.rstrip('\r\n')
Gilles Peskine53d41ae2019-07-27 23:31:53 +0200459 m = re.match(self._config_line_regexp, line)
460 if m is None:
Gabor Mezei3678dee2024-06-04 19:58:43 +0200461 self.templates.append(line)
462 return None
Gilles Peskine53d41ae2019-07-27 23:31:53 +0200463 elif m.group('section'):
464 self.current_section = m.group('section')
Gabor Mezei3678dee2024-06-04 19:58:43 +0200465 self.templates.append(line)
466 return None
Gilles Peskine9ba9c212024-05-23 15:03:43 +0200467 elif m.group('inclusion_guard') and self.inclusion_guard is None:
468 self.inclusion_guard = m.group('inclusion_guard')
Gabor Mezei3678dee2024-06-04 19:58:43 +0200469 self.templates.append(line)
470 return None
Gilles Peskine53d41ae2019-07-27 23:31:53 +0200471 else:
Gilles Peskineb4063892019-07-27 21:36:44 +0200472 active = not m.group('commented_out')
473 name = m.group('name')
474 value = m.group('value')
Gilles Peskine9ba9c212024-05-23 15:03:43 +0200475 if name == self.inclusion_guard and value == '':
476 # The file double-inclusion guard is not an option.
Gabor Mezei3678dee2024-06-04 19:58:43 +0200477 self.templates.append(line)
478 return None
Gilles Peskineb4063892019-07-27 21:36:44 +0200479 template = (name,
480 m.group('indentation'),
481 m.group('define') + name +
482 m.group('arguments') + m.group('separator'))
Gabor Mezei3678dee2024-06-04 19:58:43 +0200483 self.templates.append(template)
Gilles Peskineb4063892019-07-27 21:36:44 +0200484
Gabor Mezei3678dee2024-06-04 19:58:43 +0200485 return (active, name, value, self.current_section)
486
487 def parse_file(self):
Gabor Mezei62a9bd02024-06-07 13:44:40 +0200488 """Parse the whole file and return the settings."""
Gabor Mezei4706fe72024-07-08 17:00:55 +0200489
Gabor Mezei3678dee2024-06-04 19:58:43 +0200490 with open(self.filename, 'r', encoding='utf-8') as file:
491 for line in file:
492 setting = self._parse_line(line)
493 if setting is not None:
494 yield setting
495 self.current_section = None
496
Gabor Mezeie7742b32024-06-26 18:04:09 +0200497 #pylint: disable=no-self-use
498 def _format_template(self, setting, indent, middle):
Gabor Mezei4706fe72024-07-08 17:00:55 +0200499 """Build a line for the config file for the given setting.
Gabor Mezeie7742b32024-06-26 18:04:09 +0200500
501 The line has the form "<indent>#define <name> <value>"
502 where <middle> is "#define <name> ".
503 """
Gabor Mezei4706fe72024-07-08 17:00:55 +0200504
Gabor Mezeie7742b32024-06-26 18:04:09 +0200505 value = setting.value
506 if value is None:
507 value = ''
508 # Normally the whitespace to separate the symbol name from the
509 # value is part of middle, and there's no whitespace for a symbol
510 # with no value. But if a symbol has been changed from having a
511 # value to not having one, the whitespace is wrong, so fix it.
512 if value:
513 if middle[-1] not in '\t ':
514 middle += ' '
515 else:
516 middle = middle.rstrip()
517 return ''.join([indent,
518 '' if setting.active else '//',
519 middle,
520 value]).rstrip()
Gabor Mezei3678dee2024-06-04 19:58:43 +0200521
522 def write_to_stream(self, settings, output):
523 """Write the whole configuration to output."""
Gabor Mezei4706fe72024-07-08 17:00:55 +0200524
Gabor Mezei3678dee2024-06-04 19:58:43 +0200525 for template in self.templates:
526 if isinstance(template, str):
527 line = template
528 else:
Gabor Mezeie7742b32024-06-26 18:04:09 +0200529 name, indent, middle = template
530 line = self._format_template(settings[name], indent, middle)
Gabor Mezei3678dee2024-06-04 19:58:43 +0200531 output.write(line + '\n')
532
533 def write(self, settings, filename=None):
534 """Write the whole configuration to the file it was read from.
535
536 If filename is specified, write to this file instead.
537 """
Gabor Mezei4706fe72024-07-08 17:00:55 +0200538
Gabor Mezei3678dee2024-06-04 19:58:43 +0200539 if filename is None:
540 filename = self.filename
Gabor Mezei8a64d8e2024-06-10 15:23:43 +0200541
542 # Not modified so no need to write to the file
543 if not self.modified and filename == self.filename:
544 return
545
Gabor Mezei3678dee2024-06-04 19:58:43 +0200546 with open(filename, 'w', encoding='utf-8') as output:
547 self.write_to_stream(settings, output)
548
Gabor Mezeif77722d2024-06-28 16:49:33 +0200549class MbedTLSConfigFile(ConfigFile):
Gabor Mezei62a9bd02024-06-07 13:44:40 +0200550 """Representation of an MbedTLS configuration file."""
551
Gabor Mezei3678dee2024-06-04 19:58:43 +0200552 _path_in_tree = 'include/mbedtls/mbedtls_config.h'
553 default_path = [_path_in_tree,
554 os.path.join(os.path.dirname(__file__),
555 os.pardir,
556 _path_in_tree),
557 os.path.join(os.path.dirname(os.path.abspath(os.path.dirname(__file__))),
558 _path_in_tree)]
559
560 def __init__(self, filename=None):
Gabor Mezei93a6d1f2024-06-26 18:01:09 +0200561 super().__init__(self.default_path, 'Mbed TLS', filename)
Gabor Mezei3678dee2024-06-04 19:58:43 +0200562 self.current_section = 'header'
563
Gabor Mezei3678dee2024-06-04 19:58:43 +0200564class CryptoConfigFile(ConfigFile):
Gabor Mezei4706fe72024-07-08 17:00:55 +0200565 """Representation of a Crypto configuration file."""
Gabor Mezei62a9bd02024-06-07 13:44:40 +0200566
Gabor Mezei3de65862024-07-08 16:14:10 +0200567 # Temporary, while Mbed TLS does not just rely on the TF-PSA-Crypto
568 # build system to build its crypto library. When it does, the
569 # condition can just be removed.
570 _path_in_tree = 'include/psa/crypto_config.h' \
571 if os.path.isfile('include/psa/crypto_config.h') else \
572 'tf-psa-crypto/include/psa/crypto_config.h'
Gabor Mezei3678dee2024-06-04 19:58:43 +0200573 default_path = [_path_in_tree,
574 os.path.join(os.path.dirname(__file__),
575 os.pardir,
576 _path_in_tree),
577 os.path.join(os.path.dirname(os.path.abspath(os.path.dirname(__file__))),
578 _path_in_tree)]
579
580 def __init__(self, filename=None):
Gabor Mezei93a6d1f2024-06-26 18:01:09 +0200581 super().__init__(self.default_path, 'Crypto', filename)
Gabor Mezei3678dee2024-06-04 19:58:43 +0200582
Gabor Mezeif77722d2024-06-28 16:49:33 +0200583class MbedTLSConfig(Config):
Gabor Mezei62a9bd02024-06-07 13:44:40 +0200584 """Representation of the Mbed TLS configuration.
Gabor Mezei3678dee2024-06-04 19:58:43 +0200585
586 See the documentation of the `Config` class for methods to query
587 and modify the configuration.
588 """
Gabor Mezei4706fe72024-07-08 17:00:55 +0200589
Gabor Mezeiee521b62024-06-07 13:50:41 +0200590 def __init__(self, filename=None):
Gabor Mezei3678dee2024-06-04 19:58:43 +0200591 """Read the Mbed TLS configuration file."""
Gabor Mezei4706fe72024-07-08 17:00:55 +0200592
Gabor Mezei3678dee2024-06-04 19:58:43 +0200593 super().__init__()
Gabor Mezeif77722d2024-06-28 16:49:33 +0200594 self.configfile = MbedTLSConfigFile(filename)
Gabor Mezeic5ff33c2024-06-28 17:46:44 +0200595 self.settings.update({name: Setting(active, name, value, section, self.configfile)
Gabor Mezei92065ed2024-06-07 13:47:59 +0200596 for (active, name, value, section)
Gabor Mezeiee521b62024-06-07 13:50:41 +0200597 in self.configfile.parse_file()})
Gabor Mezei3678dee2024-06-04 19:58:43 +0200598
Gabor Mezeic659c1b2024-08-06 17:37:55 +0200599 #pylint: disable=arguments-differ
Gabor Mezei3678dee2024-06-04 19:58:43 +0200600 def set(self, name, value=None):
Gabor Mezei4706fe72024-07-08 17:00:55 +0200601 """Set name to the given value and make it active."""
602
Gabor Mezei3678dee2024-06-04 19:58:43 +0200603 if name not in self.settings:
Gabor Mezeiee521b62024-06-07 13:50:41 +0200604 self.configfile.templates.append((name, '', '#define ' + name + ' '))
605
Gabor Mezei3678dee2024-06-04 19:58:43 +0200606 super().set(name, value)
Gilles Peskineb4063892019-07-27 21:36:44 +0200607
608 def write(self, filename=None):
Gabor Mezei62a9bd02024-06-07 13:44:40 +0200609 """Write the whole configuration to the file it was read from.
610
611 If filename is specified, write to this file instead.
612 """
Gabor Mezei4706fe72024-07-08 17:00:55 +0200613
Gabor Mezeiee521b62024-06-07 13:50:41 +0200614 self.configfile.write(self.settings, filename)
Gilles Peskineb4063892019-07-27 21:36:44 +0200615
Gabor Mezeiee521b62024-06-07 13:50:41 +0200616 def filename(self):
Gabor Mezei4706fe72024-07-08 17:00:55 +0200617 """Get the name of the config file."""
618
Gabor Mezeiee521b62024-06-07 13:50:41 +0200619 return self.configfile.filename
Gabor Mezei3678dee2024-06-04 19:58:43 +0200620
621class CryptoConfig(Config):
Gabor Mezei62a9bd02024-06-07 13:44:40 +0200622 """Representation of the PSA crypto configuration.
Gabor Mezei3678dee2024-06-04 19:58:43 +0200623
624 See the documentation of the `Config` class for methods to query
625 and modify the configuration.
626 """
Gabor Mezei4706fe72024-07-08 17:00:55 +0200627
Gabor Mezeiee521b62024-06-07 13:50:41 +0200628 def __init__(self, filename=None):
Gabor Mezei3678dee2024-06-04 19:58:43 +0200629 """Read the PSA crypto configuration file."""
Gabor Mezei4706fe72024-07-08 17:00:55 +0200630
Gabor Mezei3678dee2024-06-04 19:58:43 +0200631 super().__init__()
Gabor Mezeiee521b62024-06-07 13:50:41 +0200632 self.configfile = CryptoConfigFile(filename)
Gabor Mezeic5ff33c2024-06-28 17:46:44 +0200633 self.settings.update({name: Setting(active, name, value, section, self.configfile)
Gabor Mezei92065ed2024-06-07 13:47:59 +0200634 for (active, name, value, section)
Gabor Mezeiee521b62024-06-07 13:50:41 +0200635 in self.configfile.parse_file()})
Gabor Mezei3678dee2024-06-04 19:58:43 +0200636
Gabor Mezeic659c1b2024-08-06 17:37:55 +0200637 #pylint: disable=arguments-differ
Gabor Mezeid723b512024-06-07 15:31:52 +0200638 def set(self, name, value='1'):
Gabor Mezei4706fe72024-07-08 17:00:55 +0200639 """Set name to the given value and make it active."""
640
Gabor Mezei542fd382024-06-10 14:07:42 +0200641 if name in PSA_UNSUPPORTED_FEATURE:
Gabor Mezei92065ed2024-06-07 13:47:59 +0200642 raise ValueError(f'Feature is unsupported: \'{name}\'')
Gabor Mezei542fd382024-06-10 14:07:42 +0200643 if name in PSA_UNSTABLE_FEATURE:
Gabor Mezei92065ed2024-06-07 13:47:59 +0200644 raise ValueError(f'Feature is unstable: \'{name}\'')
Gabor Mezei3678dee2024-06-04 19:58:43 +0200645
646 if name not in self.settings:
Gabor Mezeiee521b62024-06-07 13:50:41 +0200647 self.configfile.templates.append((name, '', '#define ' + name + ' '))
648
Gabor Mezei3678dee2024-06-04 19:58:43 +0200649 super().set(name, value)
650
651 def write(self, filename=None):
Gabor Mezei62a9bd02024-06-07 13:44:40 +0200652 """Write the whole configuration to the file it was read from.
653
654 If filename is specified, write to this file instead.
655 """
Gabor Mezei4706fe72024-07-08 17:00:55 +0200656
Gabor Mezeiee521b62024-06-07 13:50:41 +0200657 self.configfile.write(self.settings, filename)
Gabor Mezei3678dee2024-06-04 19:58:43 +0200658
Gabor Mezeiee521b62024-06-07 13:50:41 +0200659 def filename(self):
Gabor Mezei4706fe72024-07-08 17:00:55 +0200660 """Get the name of the config file."""
661
Gabor Mezeiee521b62024-06-07 13:50:41 +0200662 return self.configfile.filename
Gabor Mezei3678dee2024-06-04 19:58:43 +0200663
Gabor Mezei33dd2932024-06-28 17:51:58 +0200664class CombinedConfig(Config):
Gabor Mezei62a9bd02024-06-07 13:44:40 +0200665 """Representation of MbedTLS and PSA crypto configuration
666
667 See the documentation of the `Config` class for methods to query
668 and modify the configuration.
669 """
Gabor Mezei3678dee2024-06-04 19:58:43 +0200670
Gabor Mezei3e2a5502024-06-28 17:27:19 +0200671 def __init__(self, *configs):
Gabor Mezeiee521b62024-06-07 13:50:41 +0200672 super().__init__()
Gabor Mezei3e2a5502024-06-28 17:27:19 +0200673 for config in configs:
674 if isinstance(config, MbedTLSConfigFile):
675 self.mbedtls_configfile = config
676 elif isinstance(config, CryptoConfigFile):
677 self.crypto_configfile = config
678 else:
679 raise ValueError(f'Invalid configfile: {config}')
680
Gabor Mezeiee521b62024-06-07 13:50:41 +0200681 self.settings.update({name: Setting(active, name, value, section, configfile)
682 for configfile in [self.mbedtls_configfile, self.crypto_configfile]
683 for (active, name, value, section) in configfile.parse_file()})
Gabor Mezei3678dee2024-06-04 19:58:43 +0200684
685 _crypto_regexp = re.compile(r'$PSA_.*')
Gabor Mezeiee521b62024-06-07 13:50:41 +0200686 def _get_configfile(self, name):
Gabor Mezei4706fe72024-07-08 17:00:55 +0200687 """Find a config type for a setting name"""
688
Gabor Mezeiee521b62024-06-07 13:50:41 +0200689 if name in self.settings:
690 return self.settings[name].configfile
691 elif re.match(self._crypto_regexp, name):
692 return self.crypto_configfile
Gabor Mezei3678dee2024-06-04 19:58:43 +0200693 else:
Gabor Mezeiee521b62024-06-07 13:50:41 +0200694 return self.mbedtls_configfile
Gabor Mezei3678dee2024-06-04 19:58:43 +0200695
Gabor Mezeic659c1b2024-08-06 17:37:55 +0200696 #pylint: disable=arguments-differ
Gabor Mezei3678dee2024-06-04 19:58:43 +0200697 def set(self, name, value=None):
Gabor Mezei4706fe72024-07-08 17:00:55 +0200698 """Set name to the given value and make it active."""
699
Gabor Mezeiee521b62024-06-07 13:50:41 +0200700 configfile = self._get_configfile(name)
Gabor Mezei3678dee2024-06-04 19:58:43 +0200701
Gabor Mezeiee521b62024-06-07 13:50:41 +0200702 if configfile == self.crypto_configfile:
Gabor Mezei542fd382024-06-10 14:07:42 +0200703 if name in PSA_UNSUPPORTED_FEATURE:
Gabor Mezeiee521b62024-06-07 13:50:41 +0200704 raise ValueError(f'Feature is unsupported: \'{name}\'')
Gabor Mezei542fd382024-06-10 14:07:42 +0200705 if name in PSA_UNSTABLE_FEATURE:
Gabor Mezeiee521b62024-06-07 13:50:41 +0200706 raise ValueError(f'Feature is unstable: \'{name}\'')
707
Gabor Mezeid723b512024-06-07 15:31:52 +0200708 # The default value in the crypto config is '1'
709 if not value:
710 value = '1'
711
Gabor Mezeic659c1b2024-08-06 17:37:55 +0200712 if name not in self.settings:
Gabor Mezeiee521b62024-06-07 13:50:41 +0200713 configfile.templates.append((name, '', '#define ' + name + ' '))
714
Gabor Mezeic659c1b2024-08-06 17:37:55 +0200715 super().set(name, value, configfile)
Gabor Mezeiee521b62024-06-07 13:50:41 +0200716
Gabor Mezeidaf807f2024-08-14 11:33:46 +0200717 #pylint: disable=arguments-differ
Gabor Mezei3678dee2024-06-04 19:58:43 +0200718 def write(self, mbedtls_file=None, crypto_file=None):
Gabor Mezei62a9bd02024-06-07 13:44:40 +0200719 """Write the whole configuration to the file it was read from.
720
721 If mbedtls_file or crypto_file is specified, write the specific configuration
722 to the corresponding file instead.
723 """
Gabor Mezei4706fe72024-07-08 17:00:55 +0200724
Gabor Mezeiee521b62024-06-07 13:50:41 +0200725 self.mbedtls_configfile.write(self.settings, mbedtls_file)
726 self.crypto_configfile.write(self.settings, crypto_file)
Gabor Mezei3678dee2024-06-04 19:58:43 +0200727
Gabor Mezeiee521b62024-06-07 13:50:41 +0200728 def filename(self, name=None):
Gabor Mezei4706fe72024-07-08 17:00:55 +0200729 """Get the names of the config files.
730
731 If 'name' is specified return the name of the config file where it is defined.
732 """
733
Gabor Mezeiee521b62024-06-07 13:50:41 +0200734 if not name:
735 return [config.filename for config in [self.mbedtls_configfile, self.crypto_configfile]]
736
737 return self._get_configfile(name).filename
Gilles Peskineb4063892019-07-27 21:36:44 +0200738
739if __name__ == '__main__':
Gabor Mezei92065ed2024-06-07 13:47:59 +0200740 #pylint: disable=too-many-statements
Gilles Peskineb4063892019-07-27 21:36:44 +0200741 def main():
Bence Szépkútibb0cfeb2021-05-28 09:42:25 +0200742 """Command line mbedtls_config.h manipulation tool."""
Gilles Peskineb4063892019-07-27 21:36:44 +0200743 parser = argparse.ArgumentParser(description="""
Fredrik Hesse0ec8a902021-10-04 22:13:51 +0200744 Mbed TLS configuration file manipulation tool.
Gilles Peskineb4063892019-07-27 21:36:44 +0200745 """)
746 parser.add_argument('--file', '-f',
747 help="""File to read (and modify if requested).
748 Default: {}.
Gabor Mezeif77722d2024-06-28 16:49:33 +0200749 """.format(MbedTLSConfigFile.default_path))
Gabor Mezei3678dee2024-06-04 19:58:43 +0200750 parser.add_argument('--cryptofile', '-c',
751 help="""Crypto file to read (and modify if requested).
752 Default: {}.
753 """.format(CryptoConfigFile.default_path))
Gilles Peskineb4063892019-07-27 21:36:44 +0200754 parser.add_argument('--force', '-o',
Gilles Peskine435ce222019-08-01 23:13:47 +0200755 action='store_true',
Gilles Peskineb4063892019-07-27 21:36:44 +0200756 help="""For the set command, if SYMBOL is not
757 present, add a definition for it.""")
Gilles Peskinec190c902019-08-01 23:31:05 +0200758 parser.add_argument('--write', '-w', metavar='FILE',
Gilles Peskine40f103c2019-07-27 23:44:01 +0200759 help="""File to write to instead of the input file.""")
Gilles Peskineb4063892019-07-27 21:36:44 +0200760 subparsers = parser.add_subparsers(dest='command',
761 title='Commands')
762 parser_get = subparsers.add_parser('get',
763 help="""Find the value of SYMBOL
764 and print it. Exit with
765 status 0 if a #define for SYMBOL is
766 found, 1 otherwise.
767 """)
768 parser_get.add_argument('symbol', metavar='SYMBOL')
769 parser_set = subparsers.add_parser('set',
770 help="""Set SYMBOL to VALUE.
771 If VALUE is omitted, just uncomment
772 the #define for SYMBOL.
773 Error out of a line defining
774 SYMBOL (commented or not) is not
775 found, unless --force is passed.
776 """)
777 parser_set.add_argument('symbol', metavar='SYMBOL')
Gilles Peskine0c7fcd22019-08-01 23:14:00 +0200778 parser_set.add_argument('value', metavar='VALUE', nargs='?',
779 default='')
Gilles Peskine8e90cf42021-05-27 22:12:57 +0200780 parser_set_all = subparsers.add_parser('set-all',
781 help="""Uncomment all #define
782 whose name contains a match for
783 REGEX.""")
784 parser_set_all.add_argument('regexs', metavar='REGEX', nargs='*')
Gilles Peskineb4063892019-07-27 21:36:44 +0200785 parser_unset = subparsers.add_parser('unset',
786 help="""Comment out the #define
787 for SYMBOL. Do nothing if none
788 is present.""")
789 parser_unset.add_argument('symbol', metavar='SYMBOL')
Gilles Peskine8e90cf42021-05-27 22:12:57 +0200790 parser_unset_all = subparsers.add_parser('unset-all',
791 help="""Comment out all #define
792 whose name contains a match for
793 REGEX.""")
794 parser_unset_all.add_argument('regexs', metavar='REGEX', nargs='*')
Gilles Peskineb4063892019-07-27 21:36:44 +0200795
796 def add_adapter(name, function, description):
797 subparser = subparsers.add_parser(name, help=description)
798 subparser.set_defaults(adapter=function)
Gilles Peskine53d41ae2019-07-27 23:31:53 +0200799 add_adapter('baremetal', baremetal_adapter,
800 """Like full, but exclude features that require platform
801 features such as file input-output.""")
Gilles Peskine120f29d2021-09-01 19:51:19 +0200802 add_adapter('baremetal_size', baremetal_size_adapter,
803 """Like baremetal, but exclude debugging features.
804 Useful for code size measurements.""")
Gilles Peskine53d41ae2019-07-27 23:31:53 +0200805 add_adapter('full', full_adapter,
806 """Uncomment most features.
807 Exclude alternative implementations and platform support
808 options, as well as some options that are awkward to test.
809 """)
Gilles Peskine30de2e82020-04-20 21:39:22 +0200810 add_adapter('full_no_deprecated', no_deprecated_adapter(full_adapter),
Gilles Peskinebe1d6092020-04-12 14:17:16 +0200811 """Uncomment most non-deprecated features.
812 Like "full", but without deprecated features.
813 """)
Paul Elliottfb81f772023-10-18 17:44:59 +0100814 add_adapter('full_no_platform', no_platform_adapter(full_adapter),
815 """Uncomment most non-platform features.
816 Like "full", but without platform features.
817 """)
Gilles Peskineb4063892019-07-27 21:36:44 +0200818 add_adapter('realfull', realfull_adapter,
Gilles Peskine53d41ae2019-07-27 23:31:53 +0200819 """Uncomment all boolean #defines.
820 Suitable for generating documentation, but not for building.""")
Gilles Peskine31987c62020-01-31 14:23:30 +0100821 add_adapter('crypto', crypto_adapter(None),
822 """Only include crypto features. Exclude X.509 and TLS.""")
823 add_adapter('crypto_baremetal', crypto_adapter(baremetal_adapter),
824 """Like baremetal, but with only crypto features,
825 excluding X.509 and TLS.""")
826 add_adapter('crypto_full', crypto_adapter(full_adapter),
827 """Like full, but with only crypto features,
828 excluding X.509 and TLS.""")
Gilles Peskineb4063892019-07-27 21:36:44 +0200829
830 args = parser.parse_args()
Gabor Mezei33dd2932024-06-28 17:51:58 +0200831 config = CombinedConfig(MbedTLSConfigFile(args.file), CryptoConfigFile(args.cryptofile))
Gilles Peskine90b30b62019-07-28 00:36:53 +0200832 if args.command is None:
833 parser.print_help()
834 return 1
835 elif args.command == 'get':
Gilles Peskineb4063892019-07-27 21:36:44 +0200836 if args.symbol in config:
837 value = config[args.symbol]
838 if value:
839 sys.stdout.write(value + '\n')
Gilles Peskinee22a4da2020-03-24 15:43:49 +0100840 return 0 if args.symbol in config else 1
Gilles Peskineb4063892019-07-27 21:36:44 +0200841 elif args.command == 'set':
Gilles Peskine98eb3652019-07-28 16:39:19 +0200842 if not args.force and args.symbol not in config.settings:
Gilles Peskineb4063892019-07-27 21:36:44 +0200843 sys.stderr.write("A #define for the symbol {} "
Gilles Peskine221df1e2019-08-01 23:14:29 +0200844 "was not found in {}\n"
Gabor Mezei3678dee2024-06-04 19:58:43 +0200845 .format(args.symbol, config.filename(args.symbol)))
Gilles Peskineb4063892019-07-27 21:36:44 +0200846 return 1
847 config.set(args.symbol, value=args.value)
Gilles Peskine8e90cf42021-05-27 22:12:57 +0200848 elif args.command == 'set-all':
849 config.change_matching(args.regexs, True)
Gilles Peskineb4063892019-07-27 21:36:44 +0200850 elif args.command == 'unset':
851 config.unset(args.symbol)
Gilles Peskine8e90cf42021-05-27 22:12:57 +0200852 elif args.command == 'unset-all':
853 config.change_matching(args.regexs, False)
Gilles Peskineb4063892019-07-27 21:36:44 +0200854 else:
855 config.adapt(args.adapter)
Gilles Peskine40f103c2019-07-27 23:44:01 +0200856 config.write(args.write)
Gilles Peskinee22a4da2020-03-24 15:43:49 +0100857 return 0
Gilles Peskineb4063892019-07-27 21:36:44 +0200858
859 # Import modules only used by main only if main is defined and called.
860 # pylint: disable=wrong-import-position
861 import argparse
862 import sys
863 sys.exit(main())