blob: 7b815e485a84ad03d86f94c10f1765de6db497ef [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 Mezei92065ed2024-06-07 13:47:59 +020055 # pylint: disable=unused-argument
Gabor Mezeiee521b62024-06-07 13:50:41 +020056 def __init__(self):
Gilles Peskineb4063892019-07-27 21:36:44 +020057 self.settings = {}
58
59 def __contains__(self, name):
60 """True if the given symbol is active (i.e. set).
61
62 False if the given symbol is not set, even if a definition
63 is present but commented out.
64 """
65 return name in self.settings and self.settings[name].active
66
67 def all(self, *names):
68 """True if all the elements of names are active (i.e. set)."""
69 return all(self.__contains__(name) for name in names)
70
71 def any(self, *names):
72 """True if at least one symbol in names are active (i.e. set)."""
73 return any(self.__contains__(name) for name in names)
74
75 def known(self, name):
76 """True if a #define for name is present, whether it's commented out or not."""
77 return name in self.settings
78
79 def __getitem__(self, name):
80 """Get the value of name, i.e. what the preprocessor symbol expands to.
81
82 If name is not known, raise KeyError. name does not need to be active.
83 """
84 return self.settings[name].value
85
86 def get(self, name, default=None):
87 """Get the value of name. If name is inactive (not set), return default.
88
89 If a #define for name is present and not commented out, return
90 its expansion, even if this is the empty string.
91
92 If a #define for name is present but commented out, return default.
93 """
94 if name in self.settings:
95 return self.settings[name].value
96 else:
97 return default
98
99 def __setitem__(self, name, value):
100 """If name is known, set its value.
101
102 If name is not known, raise KeyError.
103 """
Gabor Mezeic659c1b2024-08-06 17:37:55 +0200104 setting = self.settings[name]
105 if setting.configfile and setting != value:
106 setting.configfile.modified = True
Gilles Peskineb4063892019-07-27 21:36:44 +0200107
Gabor Mezeic659c1b2024-08-06 17:37:55 +0200108 setting.value = value
109
110 def set(self, name, value=None, configfile=None):
Gilles Peskineb4063892019-07-27 21:36:44 +0200111 """Set name to the given value and make it active.
112
113 If value is None and name is already known, don't change its value.
Gabor Mezeic659c1b2024-08-06 17:37:55 +0200114 If value is None and name is not known, set its value.
Gilles Peskineb4063892019-07-27 21:36:44 +0200115 """
116 if name in self.settings:
Gabor Mezeic659c1b2024-08-06 17:37:55 +0200117 setting = self.settings[name]
118 if setting.configfile and (setting.value != value or not setting.active):
119 setting.configfile.modified = True
Gilles Peskineb4063892019-07-27 21:36:44 +0200120 if value is not None:
Gabor Mezeic659c1b2024-08-06 17:37:55 +0200121 setting.value = value
122 setting.active = True
Gilles Peskineb4063892019-07-27 21:36:44 +0200123 else:
Gabor Mezeic659c1b2024-08-06 17:37:55 +0200124 self.settings[name] = Setting(True, name, value=value, configfile=configfile)
125 if configfile:
126 self.settings[name].configfile.modified = True
Gilles Peskineb4063892019-07-27 21:36:44 +0200127
128 def unset(self, name):
129 """Make name unset (inactive).
130
Gilles Peskine55cc4db2019-08-01 23:13:23 +0200131 name remains known if it was known before.
Gilles Peskineb4063892019-07-27 21:36:44 +0200132 """
Gilles Peskine55cc4db2019-08-01 23:13:23 +0200133 if name not in self.settings:
134 return
Gabor Mezeic5ff33c2024-06-28 17:46:44 +0200135
136 setting = self.settings[name]
137 # Check if modifying the config file
138 if setting.configfile and setting.active:
139 setting.configfile.modified = True
140
141 setting.active = False
Gilles Peskineb4063892019-07-27 21:36:44 +0200142
143 def adapt(self, adapter):
144 """Run adapter on each known symbol and (de)activate it accordingly.
145
146 `adapter` must be a function that returns a boolean. It is called as
Gilles Peskine53d41ae2019-07-27 23:31:53 +0200147 `adapter(name, active, section)` for each setting, where `active` is
148 `True` if `name` is set and `False` if `name` is known but unset,
149 and `section` is the name of the section containing `name`. If
Gilles Peskineb4063892019-07-27 21:36:44 +0200150 `adapter` returns `True`, then set `name` (i.e. make it active),
151 otherwise unset `name` (i.e. make it known but inactive).
152 """
153 for setting in self.settings.values():
Gabor Mezeic5ff33c2024-06-28 17:46:44 +0200154 is_active = setting.active
Gilles Peskine53d41ae2019-07-27 23:31:53 +0200155 setting.active = adapter(setting.name, setting.active,
156 setting.section)
Gabor Mezeic5ff33c2024-06-28 17:46:44 +0200157 # Check if modifying the config file
158 if setting.configfile and setting.active != is_active:
159 setting.configfile.modified = True
Gilles Peskineb4063892019-07-27 21:36:44 +0200160
Gilles Peskine8e90cf42021-05-27 22:12:57 +0200161 def change_matching(self, regexs, enable):
162 """Change all symbols matching one of the regexs to the desired state."""
163 if not regexs:
164 return
165 regex = re.compile('|'.join(regexs))
166 for setting in self.settings.values():
167 if regex.search(setting.name):
Gabor Mezeic5ff33c2024-06-28 17:46:44 +0200168 # Check if modifying the config file
169 if setting.configfile and setting.active != enable:
170 setting.configfile.modified = True
Gilles Peskine8e90cf42021-05-27 22:12:57 +0200171 setting.active = enable
172
Gilles Peskine53d41ae2019-07-27 23:31:53 +0200173def is_full_section(section):
Gabor Mezeide6e1922024-06-28 17:10:50 +0200174 """Is this section affected by "config.py full" and friends?
175
176 In a config file where the sections are not used the whole config file
177 is an empty section (with value None) and the whole file is affected.
178 """
Gabor Mezei3678dee2024-06-04 19:58:43 +0200179 return section is None or section.endswith('support') or section.endswith('modules')
Gilles Peskine53d41ae2019-07-27 23:31:53 +0200180
181def realfull_adapter(_name, active, section):
Gilles Peskineba4162a2022-04-11 17:04:38 +0200182 """Activate all symbols found in the global and boolean feature sections.
183
184 This is intended for building the documentation, including the
185 documentation of settings that are activated by defining an optional
186 preprocessor macro.
187
188 Do not activate definitions in the section containing symbols that are
189 supposed to be defined and documented in their own module.
190 """
191 if section == 'Module configuration options':
Gilles Peskine53d41ae2019-07-27 23:31:53 +0200192 return active
Gilles Peskineb4063892019-07-27 21:36:44 +0200193 return True
194
Gabor Mezei542fd382024-06-10 14:07:42 +0200195PSA_UNSUPPORTED_FEATURE = frozenset([
Gabor Mezei3678dee2024-06-04 19:58:43 +0200196 'PSA_WANT_ALG_CBC_MAC',
197 'PSA_WANT_ALG_XTS',
198 'PSA_WANT_KEY_TYPE_RSA_KEY_PAIR_DERIVE',
199 'PSA_WANT_KEY_TYPE_DH_KEY_PAIR_DERIVE'
200])
201
Gabor Mezei542fd382024-06-10 14:07:42 +0200202PSA_DEPRECATED_FEATURE = frozenset([
Gabor Mezei3678dee2024-06-04 19:58:43 +0200203 'PSA_WANT_KEY_TYPE_ECC_KEY_PAIR',
204 'PSA_WANT_KEY_TYPE_RSA_KEY_PAIR'
205])
206
Gabor Mezei542fd382024-06-10 14:07:42 +0200207PSA_UNSTABLE_FEATURE = frozenset([
Gabor Mezei3678dee2024-06-04 19:58:43 +0200208 'PSA_WANT_ECC_SECP_K1_224'
209])
210
Gabor Mezei9b0f9e72024-06-26 18:08:17 +0200211EXCLUDE_FROM_CRYPTO = PSA_UNSUPPORTED_FEATURE | \
212 PSA_DEPRECATED_FEATURE | \
213 PSA_UNSTABLE_FEATURE
Gabor Mezei542fd382024-06-10 14:07:42 +0200214
Gilles Peskinecfffc282020-04-12 13:55:45 +0200215# The goal of the full configuration is to have everything that can be tested
216# together. This includes deprecated or insecure options. It excludes:
217# * Options that require additional build dependencies or unusual hardware.
218# * Options that make testing less effective.
Gilles Peskinec9d04332020-04-16 20:50:17 +0200219# * Options that are incompatible with other options, or more generally that
220# interact with other parts of the code in such a way that a bulk enabling
221# is not a good way to test them.
Gilles Peskinecfffc282020-04-12 13:55:45 +0200222# * Options that remove features.
Gilles Peskinebbaa2b72020-04-12 13:33:57 +0200223EXCLUDE_FROM_FULL = frozenset([
Gilles Peskinecfffc282020-04-12 13:55:45 +0200224 #pylint: disable=line-too-long
Yanray Wanga8704672023-04-20 17:16:48 +0800225 'MBEDTLS_AES_ONLY_128_BIT_KEY_LENGTH', # interacts with CTR_DRBG_128_BIT_KEY
Gilles Peskinea8861e02023-09-05 20:20:51 +0200226 'MBEDTLS_AES_USE_HARDWARE_ONLY', # hardware dependency
Yanray Wang42be1ba2023-11-23 14:28:47 +0800227 'MBEDTLS_BLOCK_CIPHER_NO_DECRYPT', # incompatible with ECB in PSA, CBC/XTS/NIST_KW/DES
Gilles Peskinec9d04332020-04-16 20:50:17 +0200228 'MBEDTLS_CTR_DRBG_USE_128_BIT_KEY', # interacts with ENTROPY_FORCE_SHA256
Gilles Peskinecfffc282020-04-12 13:55:45 +0200229 'MBEDTLS_DEPRECATED_REMOVED', # conflicts with deprecated options
Gilles Peskine90581ee2020-04-12 14:02:47 +0200230 'MBEDTLS_DEPRECATED_WARNING', # conflicts with deprecated options
Gilles Peskinec9d04332020-04-16 20:50:17 +0200231 'MBEDTLS_ECDH_VARIANT_EVEREST_ENABLED', # influences the use of ECDH in TLS
Janos Follath5b7c38f2023-08-01 08:51:12 +0100232 'MBEDTLS_ECP_WITH_MPI_UINT', # disables the default ECP and is experimental
Gilles Peskinec9d04332020-04-16 20:50:17 +0200233 'MBEDTLS_ENTROPY_FORCE_SHA256', # interacts with CTR_DRBG_128_BIT_KEY
Gilles Peskinecfffc282020-04-12 13:55:45 +0200234 'MBEDTLS_HAVE_SSE2', # hardware dependency
235 'MBEDTLS_MEMORY_BACKTRACE', # depends on MEMORY_BUFFER_ALLOC_C
236 'MBEDTLS_MEMORY_BUFFER_ALLOC_C', # makes sanitizers (e.g. ASan) less effective
237 'MBEDTLS_MEMORY_DEBUG', # depends on MEMORY_BUFFER_ALLOC_C
Gilles Peskinec9d04332020-04-16 20:50:17 +0200238 'MBEDTLS_NO_64BIT_MULTIPLICATION', # influences anything that uses bignum
Gilles Peskinecfffc282020-04-12 13:55:45 +0200239 'MBEDTLS_NO_DEFAULT_ENTROPY_SOURCES', # removes a feature
240 'MBEDTLS_NO_PLATFORM_ENTROPY', # removes a feature
Gilles Peskinec9d04332020-04-16 20:50:17 +0200241 'MBEDTLS_NO_UDBL_DIVISION', # influences anything that uses bignum
Gilles Peskineefaee9a2023-09-20 20:49:47 +0200242 'MBEDTLS_PSA_P256M_DRIVER_ENABLED', # influences SECP256R1 KeyGen/ECDH/ECDSA
Gilles Peskinecfffc282020-04-12 13:55:45 +0200243 'MBEDTLS_PLATFORM_NO_STD_FUNCTIONS', # removes a feature
David Horstmann6f8c95b2024-03-14 14:52:45 +0000244 'MBEDTLS_PSA_ASSUME_EXCLUSIVE_BUFFERS', # removes a feature
Gilles Peskinef08b3f82020-11-13 17:36:48 +0100245 'MBEDTLS_PSA_CRYPTO_EXTERNAL_RNG', # behavior change + build dependency
Ronald Cronc3623db2020-10-29 10:51:32 +0100246 'MBEDTLS_PSA_CRYPTO_KEY_ID_ENCODES_OWNER', # incompatible with USE_PSA_CRYPTO
Gilles Peskinecfffc282020-04-12 13:55:45 +0200247 'MBEDTLS_PSA_CRYPTO_SPM', # platform dependency (PSA SPM)
Gilles Peskinea08def92023-04-28 21:01:49 +0200248 'MBEDTLS_PSA_INJECT_ENTROPY', # conflicts with platform entropy sources
Gilles Peskinec9d04332020-04-16 20:50:17 +0200249 'MBEDTLS_RSA_NO_CRT', # influences the use of RSA in X.509 and TLS
Tom Cosgrove87fbfb52022-03-15 10:51:52 +0000250 'MBEDTLS_SHA256_USE_A64_CRYPTO_ONLY', # interacts with *_USE_A64_CRYPTO_IF_PRESENT
Dave Rodgman9be3cf02023-10-11 14:47:55 +0100251 'MBEDTLS_SHA256_USE_ARMV8_A_CRYPTO_ONLY', # interacts with *_USE_ARMV8_A_CRYPTO_IF_PRESENT
Tom Cosgrove87fbfb52022-03-15 10:51:52 +0000252 'MBEDTLS_SHA512_USE_A64_CRYPTO_ONLY', # interacts with *_USE_A64_CRYPTO_IF_PRESENT
Dave Rodgman7cb635a2023-10-12 16:14:51 +0100253 'MBEDTLS_SHA256_USE_A64_CRYPTO_IF_PRESENT', # setting *_USE_ARMV8_A_CRYPTO is sufficient
Manuel Pégourié-Gonnard6240def2020-07-10 09:35:54 +0200254 'MBEDTLS_TEST_CONSTANT_FLOW_MEMSAN', # build dependency (clang+memsan)
Manuel Pégourié-Gonnard73afa372020-08-19 10:27:38 +0200255 'MBEDTLS_TEST_CONSTANT_FLOW_VALGRIND', # build dependency (valgrind headers)
Hanno Beckere1113562019-06-12 13:59:14 +0100256 'MBEDTLS_X509_REMOVE_INFO', # removes a feature
Gabor Mezei542fd382024-06-10 14:07:42 +0200257 *PSA_UNSUPPORTED_FEATURE,
258 *PSA_DEPRECATED_FEATURE,
259 *PSA_UNSTABLE_FEATURE
Gilles Peskinebbaa2b72020-04-12 13:33:57 +0200260])
261
Gilles Peskine32e889d2020-04-12 23:43:28 +0200262def is_seamless_alt(name):
Gilles Peskinec34faba2020-04-20 15:44:14 +0200263 """Whether the xxx_ALT symbol should be included in the full configuration.
Gilles Peskine32e889d2020-04-12 23:43:28 +0200264
Gilles Peskinec34faba2020-04-20 15:44:14 +0200265 Include alternative implementations of platform functions, which are
Gilles Peskine32e889d2020-04-12 23:43:28 +0200266 configurable function pointers that default to the built-in function.
267 This way we test that the function pointers exist and build correctly
268 without changing the behavior, and tests can verify that the function
269 pointers are used by modifying those pointers.
270
271 Exclude alternative implementations of library functions since they require
272 an implementation of the relevant functions and an xxx_alt.h header.
273 """
Gilles Peskinea8861e02023-09-05 20:20:51 +0200274 if name in (
275 'MBEDTLS_PLATFORM_GMTIME_R_ALT',
276 'MBEDTLS_PLATFORM_SETUP_TEARDOWN_ALT',
277 'MBEDTLS_PLATFORM_MS_TIME_ALT',
278 'MBEDTLS_PLATFORM_ZEROIZE_ALT',
279 ):
Gilles Peskinec34faba2020-04-20 15:44:14 +0200280 # Similar to non-platform xxx_ALT, requires platform_alt.h
281 return False
Gilles Peskine32e889d2020-04-12 23:43:28 +0200282 return name.startswith('MBEDTLS_PLATFORM_')
283
Gilles Peskine53d41ae2019-07-27 23:31:53 +0200284def include_in_full(name):
285 """Rules for symbols in the "full" configuration."""
Gabor Mezei542fd382024-06-10 14:07:42 +0200286 if name in EXCLUDE_FROM_FULL:
Gilles Peskine53d41ae2019-07-27 23:31:53 +0200287 return False
288 if name.endswith('_ALT'):
Gilles Peskine32e889d2020-04-12 23:43:28 +0200289 return is_seamless_alt(name)
Gilles Peskine53d41ae2019-07-27 23:31:53 +0200290 return True
291
292def full_adapter(name, active, section):
293 """Config adapter for "full"."""
294 if not is_full_section(section):
295 return active
296 return include_in_full(name)
297
Gilles Peskinecfffc282020-04-12 13:55:45 +0200298# The baremetal configuration excludes options that require a library or
299# operating system feature that is typically not present on bare metal
300# systems. Features that are excluded from "full" won't be in "baremetal"
301# either (unless explicitly turned on in baremetal_adapter) so they don't
302# need to be repeated here.
Gilles Peskinebbaa2b72020-04-12 13:33:57 +0200303EXCLUDE_FROM_BAREMETAL = frozenset([
Gilles Peskinecfffc282020-04-12 13:55:45 +0200304 #pylint: disable=line-too-long
Gilles Peskine98f8f952020-04-20 15:38:39 +0200305 'MBEDTLS_ENTROPY_NV_SEED', # requires a filesystem and FS_IO or alternate NV seed hooks
Gilles Peskinecfffc282020-04-12 13:55:45 +0200306 'MBEDTLS_FS_IO', # requires a filesystem
Gilles Peskinecfffc282020-04-12 13:55:45 +0200307 'MBEDTLS_HAVE_TIME', # requires a clock
308 'MBEDTLS_HAVE_TIME_DATE', # requires a clock
309 'MBEDTLS_NET_C', # requires POSIX-like networking
310 'MBEDTLS_PLATFORM_FPRINTF_ALT', # requires FILE* from stdio.h
Gilles Peskine98f8f952020-04-20 15:38:39 +0200311 'MBEDTLS_PLATFORM_NV_SEED_ALT', # requires a filesystem and ENTROPY_NV_SEED
312 'MBEDTLS_PLATFORM_TIME_ALT', # requires a clock and HAVE_TIME
313 'MBEDTLS_PSA_CRYPTO_SE_C', # requires a filesystem and PSA_CRYPTO_STORAGE_C
Gilles Peskinecfffc282020-04-12 13:55:45 +0200314 'MBEDTLS_PSA_CRYPTO_STORAGE_C', # requires a filesystem
315 'MBEDTLS_PSA_ITS_FILE_C', # requires a filesystem
316 'MBEDTLS_THREADING_C', # requires a threading interface
317 'MBEDTLS_THREADING_PTHREAD', # requires pthread
318 'MBEDTLS_TIMING_C', # requires a clock
Dave Rodgman9be3cf02023-10-11 14:47:55 +0100319 'MBEDTLS_SHA256_USE_A64_CRYPTO_IF_PRESENT', # requires an OS for runtime-detection
Dave Rodgman5b89c552023-10-10 14:59:02 +0100320 'MBEDTLS_SHA256_USE_ARMV8_A_CRYPTO_IF_PRESENT', # requires an OS for runtime-detection
Dave Rodgmanbe7915a2023-10-11 10:46:38 +0100321 'MBEDTLS_SHA512_USE_A64_CRYPTO_IF_PRESENT', # requires an OS for runtime-detection
Gilles Peskinebbaa2b72020-04-12 13:33:57 +0200322])
323
Gilles Peskine53d41ae2019-07-27 23:31:53 +0200324def keep_in_baremetal(name):
325 """Rules for symbols in the "baremetal" configuration."""
Gilles Peskinebbaa2b72020-04-12 13:33:57 +0200326 if name in EXCLUDE_FROM_BAREMETAL:
Gilles Peskine53d41ae2019-07-27 23:31:53 +0200327 return False
328 return True
329
330def baremetal_adapter(name, active, section):
331 """Config adapter for "baremetal"."""
332 if not is_full_section(section):
333 return active
334 if name == 'MBEDTLS_NO_PLATFORM_ENTROPY':
Gilles Peskinecfffc282020-04-12 13:55:45 +0200335 # No OS-provided entropy source
Gilles Peskine53d41ae2019-07-27 23:31:53 +0200336 return True
337 return include_in_full(name) and keep_in_baremetal(name)
338
Gilles Peskine120f29d2021-09-01 19:51:19 +0200339# This set contains options that are mostly for debugging or test purposes,
340# and therefore should be excluded when doing code size measurements.
341# Options that are their own module (such as MBEDTLS_ERROR_C) are not listed
342# and therefore will be included when doing code size measurements.
343EXCLUDE_FOR_SIZE = frozenset([
344 'MBEDTLS_DEBUG_C', # large code size increase in TLS
345 'MBEDTLS_SELF_TEST', # increases the size of many modules
346 'MBEDTLS_TEST_HOOKS', # only useful with the hosted test framework, increases code size
347])
348
349def baremetal_size_adapter(name, active, section):
350 if name in EXCLUDE_FOR_SIZE:
351 return False
352 return baremetal_adapter(name, active, section)
353
Gilles Peskine31987c62020-01-31 14:23:30 +0100354def include_in_crypto(name):
355 """Rules for symbols in a crypto configuration."""
356 if name.startswith('MBEDTLS_X509_') or \
357 name.startswith('MBEDTLS_SSL_') or \
358 name.startswith('MBEDTLS_KEY_EXCHANGE_'):
359 return False
360 if name in [
Gilles Peskinecfffc282020-04-12 13:55:45 +0200361 'MBEDTLS_DEBUG_C', # part of libmbedtls
362 'MBEDTLS_NET_C', # part of libmbedtls
Nayna Jainc9deb182020-11-16 19:03:12 +0000363 'MBEDTLS_PKCS7_C', # part of libmbedx509
Gilles Peskine31987c62020-01-31 14:23:30 +0100364 ]:
365 return False
Gabor Mezei542fd382024-06-10 14:07:42 +0200366 if name in EXCLUDE_FROM_CRYPTO:
367 return False
Gilles Peskine31987c62020-01-31 14:23:30 +0100368 return True
369
370def crypto_adapter(adapter):
371 """Modify an adapter to disable non-crypto symbols.
372
373 ``crypto_adapter(adapter)(name, active, section)`` is like
374 ``adapter(name, active, section)``, but unsets all X.509 and TLS symbols.
375 """
376 def continuation(name, active, section):
377 if not include_in_crypto(name):
378 return False
379 if adapter is None:
380 return active
381 return adapter(name, active, section)
382 return continuation
383
Gilles Peskineed5c21d2022-06-27 23:02:09 +0200384DEPRECATED = frozenset([
385 'MBEDTLS_PSA_CRYPTO_SE_C',
Gabor Mezei542fd382024-06-10 14:07:42 +0200386 *PSA_DEPRECATED_FEATURE
Gilles Peskineed5c21d2022-06-27 23:02:09 +0200387])
Gilles Peskine30de2e82020-04-20 21:39:22 +0200388def no_deprecated_adapter(adapter):
Gilles Peskinebe1d6092020-04-12 14:17:16 +0200389 """Modify an adapter to disable deprecated symbols.
390
Gilles Peskine30de2e82020-04-20 21:39:22 +0200391 ``no_deprecated_adapter(adapter)(name, active, section)`` is like
Gilles Peskinebe1d6092020-04-12 14:17:16 +0200392 ``adapter(name, active, section)``, but unsets all deprecated symbols
393 and sets ``MBEDTLS_DEPRECATED_REMOVED``.
394 """
395 def continuation(name, active, section):
396 if name == 'MBEDTLS_DEPRECATED_REMOVED':
397 return True
Gilles Peskineed5c21d2022-06-27 23:02:09 +0200398 if name in DEPRECATED:
399 return False
Gilles Peskinebe1d6092020-04-12 14:17:16 +0200400 if adapter is None:
401 return active
402 return adapter(name, active, section)
403 return continuation
404
Paul Elliottfb81f772023-10-18 17:44:59 +0100405def no_platform_adapter(adapter):
406 """Modify an adapter to disable platform symbols.
407
408 ``no_platform_adapter(adapter)(name, active, section)`` is like
409 ``adapter(name, active, section)``, but unsets all platform symbols other
410 ``than MBEDTLS_PLATFORM_C.
411 """
412 def continuation(name, active, section):
413 # Allow MBEDTLS_PLATFORM_C but remove all other platform symbols.
414 if name.startswith('MBEDTLS_PLATFORM_') and name != 'MBEDTLS_PLATFORM_C':
415 return False
416 if adapter is None:
417 return active
418 return adapter(name, active, section)
419 return continuation
420
Gabor Mezei3678dee2024-06-04 19:58:43 +0200421class ConfigFile(metaclass=ABCMeta):
Gabor Mezei62a9bd02024-06-07 13:44:40 +0200422 """Representation of a configuration file."""
423
Gabor Mezei93a6d1f2024-06-26 18:01:09 +0200424 def __init__(self, default_path, name, filename=None):
Gabor Mezei62a9bd02024-06-07 13:44:40 +0200425 """Check if the config file exists."""
Gilles Peskineb4063892019-07-27 21:36:44 +0200426 if filename is None:
Gabor Mezei3678dee2024-06-04 19:58:43 +0200427 for candidate in default_path:
Gilles Peskinece674a92020-03-24 15:37:00 +0100428 if os.path.lexists(candidate):
429 filename = candidate
Gilles Peskine208e4ec2019-07-29 23:43:20 +0200430 break
Gilles Peskinece674a92020-03-24 15:37:00 +0100431 else:
Gabor Mezei8d72ac62024-06-28 17:18:37 +0200432 raise FileNotFoundError(f'{name} configuration file not found: '
433 f'{filename if filename else default_path}')
Gilles Peskineb4063892019-07-27 21:36:44 +0200434
Gabor Mezei3678dee2024-06-04 19:58:43 +0200435 self.filename = filename
436 self.templates = []
437 self.current_section = None
438 self.inclusion_guard = None
Gabor Mezei8a64d8e2024-06-10 15:23:43 +0200439 self.modified = False
Gilles Peskineb4063892019-07-27 21:36:44 +0200440
441 _define_line_regexp = (r'(?P<indentation>\s*)' +
442 r'(?P<commented_out>(//\s*)?)' +
443 r'(?P<define>#\s*define\s+)' +
444 r'(?P<name>\w+)' +
445 r'(?P<arguments>(?:\((?:\w|\s|,)*\))?)' +
446 r'(?P<separator>\s*)' +
447 r'(?P<value>.*)')
Gilles Peskine9ba9c212024-05-23 15:03:43 +0200448 _ifndef_line_regexp = r'#ifndef (?P<inclusion_guard>\w+)'
Gilles Peskine53d41ae2019-07-27 23:31:53 +0200449 _section_line_regexp = (r'\s*/?\*+\s*[\\@]name\s+SECTION:\s*' +
450 r'(?P<section>.*)[ */]*')
451 _config_line_regexp = re.compile(r'|'.join([_define_line_regexp,
Gilles Peskine9ba9c212024-05-23 15:03:43 +0200452 _ifndef_line_regexp,
Gilles Peskine53d41ae2019-07-27 23:31:53 +0200453 _section_line_regexp]))
Gilles Peskineb4063892019-07-27 21:36:44 +0200454 def _parse_line(self, line):
Gabor Mezei62a9bd02024-06-07 13:44:40 +0200455 """Parse a line in the config file, save the templates representing the lines
456 and return the corresponding setting element.
457 """
Gabor Mezei4706fe72024-07-08 17:00:55 +0200458
Gilles Peskineb4063892019-07-27 21:36:44 +0200459 line = line.rstrip('\r\n')
Gilles Peskine53d41ae2019-07-27 23:31:53 +0200460 m = re.match(self._config_line_regexp, line)
461 if m is None:
Gabor Mezei3678dee2024-06-04 19:58:43 +0200462 self.templates.append(line)
463 return None
Gilles Peskine53d41ae2019-07-27 23:31:53 +0200464 elif m.group('section'):
465 self.current_section = m.group('section')
Gabor Mezei3678dee2024-06-04 19:58:43 +0200466 self.templates.append(line)
467 return None
Gilles Peskine9ba9c212024-05-23 15:03:43 +0200468 elif m.group('inclusion_guard') and self.inclusion_guard is None:
469 self.inclusion_guard = m.group('inclusion_guard')
Gabor Mezei3678dee2024-06-04 19:58:43 +0200470 self.templates.append(line)
471 return None
Gilles Peskine53d41ae2019-07-27 23:31:53 +0200472 else:
Gilles Peskineb4063892019-07-27 21:36:44 +0200473 active = not m.group('commented_out')
474 name = m.group('name')
475 value = m.group('value')
Gilles Peskine9ba9c212024-05-23 15:03:43 +0200476 if name == self.inclusion_guard and value == '':
477 # The file double-inclusion guard is not an option.
Gabor Mezei3678dee2024-06-04 19:58:43 +0200478 self.templates.append(line)
479 return None
Gilles Peskineb4063892019-07-27 21:36:44 +0200480 template = (name,
481 m.group('indentation'),
482 m.group('define') + name +
483 m.group('arguments') + m.group('separator'))
Gabor Mezei3678dee2024-06-04 19:58:43 +0200484 self.templates.append(template)
Gilles Peskineb4063892019-07-27 21:36:44 +0200485
Gabor Mezei3678dee2024-06-04 19:58:43 +0200486 return (active, name, value, self.current_section)
487
488 def parse_file(self):
Gabor Mezei62a9bd02024-06-07 13:44:40 +0200489 """Parse the whole file and return the settings."""
Gabor Mezei4706fe72024-07-08 17:00:55 +0200490
Gabor Mezei3678dee2024-06-04 19:58:43 +0200491 with open(self.filename, 'r', encoding='utf-8') as file:
492 for line in file:
493 setting = self._parse_line(line)
494 if setting is not None:
495 yield setting
496 self.current_section = None
497
Gabor Mezeie7742b32024-06-26 18:04:09 +0200498 #pylint: disable=no-self-use
499 def _format_template(self, setting, indent, middle):
Gabor Mezei4706fe72024-07-08 17:00:55 +0200500 """Build a line for the config file for the given setting.
Gabor Mezeie7742b32024-06-26 18:04:09 +0200501
502 The line has the form "<indent>#define <name> <value>"
503 where <middle> is "#define <name> ".
504 """
Gabor Mezei4706fe72024-07-08 17:00:55 +0200505
Gabor Mezeie7742b32024-06-26 18:04:09 +0200506 value = setting.value
507 if value is None:
508 value = ''
509 # Normally the whitespace to separate the symbol name from the
510 # value is part of middle, and there's no whitespace for a symbol
511 # with no value. But if a symbol has been changed from having a
512 # value to not having one, the whitespace is wrong, so fix it.
513 if value:
514 if middle[-1] not in '\t ':
515 middle += ' '
516 else:
517 middle = middle.rstrip()
518 return ''.join([indent,
519 '' if setting.active else '//',
520 middle,
521 value]).rstrip()
Gabor Mezei3678dee2024-06-04 19:58:43 +0200522
523 def write_to_stream(self, settings, output):
524 """Write the whole configuration to output."""
Gabor Mezei4706fe72024-07-08 17:00:55 +0200525
Gabor Mezei3678dee2024-06-04 19:58:43 +0200526 for template in self.templates:
527 if isinstance(template, str):
528 line = template
529 else:
Gabor Mezeie7742b32024-06-26 18:04:09 +0200530 name, indent, middle = template
531 line = self._format_template(settings[name], indent, middle)
Gabor Mezei3678dee2024-06-04 19:58:43 +0200532 output.write(line + '\n')
533
534 def write(self, settings, filename=None):
535 """Write the whole configuration to the file it was read from.
536
537 If filename is specified, write to this file instead.
538 """
Gabor Mezei4706fe72024-07-08 17:00:55 +0200539
Gabor Mezei3678dee2024-06-04 19:58:43 +0200540 if filename is None:
541 filename = self.filename
Gabor Mezei8a64d8e2024-06-10 15:23:43 +0200542
543 # Not modified so no need to write to the file
544 if not self.modified and filename == self.filename:
545 return
546
Gabor Mezei3678dee2024-06-04 19:58:43 +0200547 with open(filename, 'w', encoding='utf-8') as output:
548 self.write_to_stream(settings, output)
549
Gabor Mezeif77722d2024-06-28 16:49:33 +0200550class MbedTLSConfigFile(ConfigFile):
Gabor Mezei62a9bd02024-06-07 13:44:40 +0200551 """Representation of an MbedTLS configuration file."""
552
Gabor Mezei3678dee2024-06-04 19:58:43 +0200553 _path_in_tree = 'include/mbedtls/mbedtls_config.h'
554 default_path = [_path_in_tree,
555 os.path.join(os.path.dirname(__file__),
556 os.pardir,
557 _path_in_tree),
558 os.path.join(os.path.dirname(os.path.abspath(os.path.dirname(__file__))),
559 _path_in_tree)]
560
561 def __init__(self, filename=None):
Gabor Mezei93a6d1f2024-06-26 18:01:09 +0200562 super().__init__(self.default_path, 'Mbed TLS', filename)
Gabor Mezei3678dee2024-06-04 19:58:43 +0200563 self.current_section = 'header'
564
Gabor Mezei3678dee2024-06-04 19:58:43 +0200565class CryptoConfigFile(ConfigFile):
Gabor Mezei4706fe72024-07-08 17:00:55 +0200566 """Representation of a Crypto configuration file."""
Gabor Mezei62a9bd02024-06-07 13:44:40 +0200567
Gabor Mezei3de65862024-07-08 16:14:10 +0200568 # Temporary, while Mbed TLS does not just rely on the TF-PSA-Crypto
569 # build system to build its crypto library. When it does, the
570 # condition can just be removed.
571 _path_in_tree = 'include/psa/crypto_config.h' \
572 if os.path.isfile('include/psa/crypto_config.h') else \
573 'tf-psa-crypto/include/psa/crypto_config.h'
Gabor Mezei3678dee2024-06-04 19:58:43 +0200574 default_path = [_path_in_tree,
575 os.path.join(os.path.dirname(__file__),
576 os.pardir,
577 _path_in_tree),
578 os.path.join(os.path.dirname(os.path.abspath(os.path.dirname(__file__))),
579 _path_in_tree)]
580
581 def __init__(self, filename=None):
Gabor Mezei93a6d1f2024-06-26 18:01:09 +0200582 super().__init__(self.default_path, 'Crypto', filename)
Gabor Mezei3678dee2024-06-04 19:58:43 +0200583
Gabor Mezeif77722d2024-06-28 16:49:33 +0200584class MbedTLSConfig(Config):
Gabor Mezei62a9bd02024-06-07 13:44:40 +0200585 """Representation of the Mbed TLS configuration.
Gabor Mezei3678dee2024-06-04 19:58:43 +0200586
587 See the documentation of the `Config` class for methods to query
588 and modify the configuration.
589 """
Gabor Mezei4706fe72024-07-08 17:00:55 +0200590
Gabor Mezeiee521b62024-06-07 13:50:41 +0200591 def __init__(self, filename=None):
Gabor Mezei3678dee2024-06-04 19:58:43 +0200592 """Read the Mbed TLS configuration file."""
Gabor Mezei4706fe72024-07-08 17:00:55 +0200593
Gabor Mezei3678dee2024-06-04 19:58:43 +0200594 super().__init__()
Gabor Mezeif77722d2024-06-28 16:49:33 +0200595 self.configfile = MbedTLSConfigFile(filename)
Gabor Mezeic5ff33c2024-06-28 17:46:44 +0200596 self.settings.update({name: Setting(active, name, value, section, self.configfile)
Gabor Mezei92065ed2024-06-07 13:47:59 +0200597 for (active, name, value, section)
Gabor Mezeiee521b62024-06-07 13:50:41 +0200598 in self.configfile.parse_file()})
Gabor Mezei3678dee2024-06-04 19:58:43 +0200599
Gabor Mezeic659c1b2024-08-06 17:37:55 +0200600 #pylint: disable=arguments-differ
Gabor Mezei3678dee2024-06-04 19:58:43 +0200601 def set(self, name, value=None):
Gabor Mezei4706fe72024-07-08 17:00:55 +0200602 """Set name to the given value and make it active."""
603
Gabor Mezei3678dee2024-06-04 19:58:43 +0200604 if name not in self.settings:
Gabor Mezeiee521b62024-06-07 13:50:41 +0200605 self.configfile.templates.append((name, '', '#define ' + name + ' '))
606
Gabor Mezei3678dee2024-06-04 19:58:43 +0200607 super().set(name, value)
Gilles Peskineb4063892019-07-27 21:36:44 +0200608
609 def write(self, filename=None):
Gabor Mezei62a9bd02024-06-07 13:44:40 +0200610 """Write the whole configuration to the file it was read from.
611
612 If filename is specified, write to this file instead.
613 """
Gabor Mezei4706fe72024-07-08 17:00:55 +0200614
Gabor Mezeiee521b62024-06-07 13:50:41 +0200615 self.configfile.write(self.settings, filename)
Gilles Peskineb4063892019-07-27 21:36:44 +0200616
Gabor Mezeiee521b62024-06-07 13:50:41 +0200617 def filename(self):
Gabor Mezei4706fe72024-07-08 17:00:55 +0200618 """Get the name of the config file."""
619
Gabor Mezeiee521b62024-06-07 13:50:41 +0200620 return self.configfile.filename
Gabor Mezei3678dee2024-06-04 19:58:43 +0200621
622class CryptoConfig(Config):
Gabor Mezei62a9bd02024-06-07 13:44:40 +0200623 """Representation of the PSA crypto configuration.
Gabor Mezei3678dee2024-06-04 19:58:43 +0200624
625 See the documentation of the `Config` class for methods to query
626 and modify the configuration.
627 """
Gabor Mezei4706fe72024-07-08 17:00:55 +0200628
Gabor Mezeiee521b62024-06-07 13:50:41 +0200629 def __init__(self, filename=None):
Gabor Mezei3678dee2024-06-04 19:58:43 +0200630 """Read the PSA crypto configuration file."""
Gabor Mezei4706fe72024-07-08 17:00:55 +0200631
Gabor Mezei3678dee2024-06-04 19:58:43 +0200632 super().__init__()
Gabor Mezeiee521b62024-06-07 13:50:41 +0200633 self.configfile = CryptoConfigFile(filename)
Gabor Mezeic5ff33c2024-06-28 17:46:44 +0200634 self.settings.update({name: Setting(active, name, value, section, self.configfile)
Gabor Mezei92065ed2024-06-07 13:47:59 +0200635 for (active, name, value, section)
Gabor Mezeiee521b62024-06-07 13:50:41 +0200636 in self.configfile.parse_file()})
Gabor Mezei3678dee2024-06-04 19:58:43 +0200637
Gabor Mezeic659c1b2024-08-06 17:37:55 +0200638 #pylint: disable=arguments-differ
Gabor Mezeid723b512024-06-07 15:31:52 +0200639 def set(self, name, value='1'):
Gabor Mezei4706fe72024-07-08 17:00:55 +0200640 """Set name to the given value and make it active."""
641
Gabor Mezei542fd382024-06-10 14:07:42 +0200642 if name in PSA_UNSUPPORTED_FEATURE:
Gabor Mezei92065ed2024-06-07 13:47:59 +0200643 raise ValueError(f'Feature is unsupported: \'{name}\'')
Gabor Mezei542fd382024-06-10 14:07:42 +0200644 if name in PSA_UNSTABLE_FEATURE:
Gabor Mezei92065ed2024-06-07 13:47:59 +0200645 raise ValueError(f'Feature is unstable: \'{name}\'')
Gabor Mezei3678dee2024-06-04 19:58:43 +0200646
647 if name not in self.settings:
Gabor Mezeiee521b62024-06-07 13:50:41 +0200648 self.configfile.templates.append((name, '', '#define ' + name + ' '))
649
Gabor Mezei3678dee2024-06-04 19:58:43 +0200650 super().set(name, value)
651
652 def write(self, filename=None):
Gabor Mezei62a9bd02024-06-07 13:44:40 +0200653 """Write the whole configuration to the file it was read from.
654
655 If filename is specified, write to this file instead.
656 """
Gabor Mezei4706fe72024-07-08 17:00:55 +0200657
Gabor Mezeiee521b62024-06-07 13:50:41 +0200658 self.configfile.write(self.settings, filename)
Gabor Mezei3678dee2024-06-04 19:58:43 +0200659
Gabor Mezeiee521b62024-06-07 13:50:41 +0200660 def filename(self):
Gabor Mezei4706fe72024-07-08 17:00:55 +0200661 """Get the name of the config file."""
662
Gabor Mezeiee521b62024-06-07 13:50:41 +0200663 return self.configfile.filename
Gabor Mezei3678dee2024-06-04 19:58:43 +0200664
Gabor Mezei33dd2932024-06-28 17:51:58 +0200665class CombinedConfig(Config):
Gabor Mezei62a9bd02024-06-07 13:44:40 +0200666 """Representation of MbedTLS and PSA crypto configuration
667
668 See the documentation of the `Config` class for methods to query
669 and modify the configuration.
670 """
Gabor Mezei3678dee2024-06-04 19:58:43 +0200671
Gabor Mezei3e2a5502024-06-28 17:27:19 +0200672 def __init__(self, *configs):
Gabor Mezeiee521b62024-06-07 13:50:41 +0200673 super().__init__()
Gabor Mezei3e2a5502024-06-28 17:27:19 +0200674 for config in configs:
675 if isinstance(config, MbedTLSConfigFile):
676 self.mbedtls_configfile = config
677 elif isinstance(config, CryptoConfigFile):
678 self.crypto_configfile = config
679 else:
680 raise ValueError(f'Invalid configfile: {config}')
681
Gabor Mezeiee521b62024-06-07 13:50:41 +0200682 self.settings.update({name: Setting(active, name, value, section, configfile)
683 for configfile in [self.mbedtls_configfile, self.crypto_configfile]
684 for (active, name, value, section) in configfile.parse_file()})
Gabor Mezei3678dee2024-06-04 19:58:43 +0200685
686 _crypto_regexp = re.compile(r'$PSA_.*')
Gabor Mezeiee521b62024-06-07 13:50:41 +0200687 def _get_configfile(self, name):
Gabor Mezei4706fe72024-07-08 17:00:55 +0200688 """Find a config type for a setting name"""
689
Gabor Mezeiee521b62024-06-07 13:50:41 +0200690 if name in self.settings:
691 return self.settings[name].configfile
692 elif re.match(self._crypto_regexp, name):
693 return self.crypto_configfile
Gabor Mezei3678dee2024-06-04 19:58:43 +0200694 else:
Gabor Mezeiee521b62024-06-07 13:50:41 +0200695 return self.mbedtls_configfile
Gabor Mezei3678dee2024-06-04 19:58:43 +0200696
Gabor Mezeic659c1b2024-08-06 17:37:55 +0200697 #pylint: disable=arguments-differ
Gabor Mezei3678dee2024-06-04 19:58:43 +0200698 def set(self, name, value=None):
Gabor Mezei4706fe72024-07-08 17:00:55 +0200699 """Set name to the given value and make it active."""
700
Gabor Mezeiee521b62024-06-07 13:50:41 +0200701 configfile = self._get_configfile(name)
Gabor Mezei3678dee2024-06-04 19:58:43 +0200702
Gabor Mezeiee521b62024-06-07 13:50:41 +0200703 if configfile == self.crypto_configfile:
Gabor Mezei542fd382024-06-10 14:07:42 +0200704 if name in PSA_UNSUPPORTED_FEATURE:
Gabor Mezeiee521b62024-06-07 13:50:41 +0200705 raise ValueError(f'Feature is unsupported: \'{name}\'')
Gabor Mezei542fd382024-06-10 14:07:42 +0200706 if name in PSA_UNSTABLE_FEATURE:
Gabor Mezeiee521b62024-06-07 13:50:41 +0200707 raise ValueError(f'Feature is unstable: \'{name}\'')
708
Gabor Mezeid723b512024-06-07 15:31:52 +0200709 # The default value in the crypto config is '1'
710 if not value:
711 value = '1'
712
Gabor Mezeic659c1b2024-08-06 17:37:55 +0200713 if name not in self.settings:
Gabor Mezeiee521b62024-06-07 13:50:41 +0200714 configfile.templates.append((name, '', '#define ' + name + ' '))
715
Gabor Mezeic659c1b2024-08-06 17:37:55 +0200716 super().set(name, value, configfile)
Gabor Mezeiee521b62024-06-07 13:50:41 +0200717
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())