blob: d2735ee214447bb044543869a9111fb10db038cd [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
Gabor Mezei24d7cc72024-08-06 15:11:24 +020014import argparse
Gilles Peskine208e4ec2019-07-29 23:43:20 +020015import os
Gilles Peskineb4063892019-07-27 21:36:44 +020016import re
Gabor Mezei24d7cc72024-08-06 15:11:24 +020017import sys
Gilles Peskineb4063892019-07-27 21:36:44 +020018
Gabor Mezeie7742b32024-06-26 18:04:09 +020019from abc import ABCMeta
Gabor Mezei3678dee2024-06-04 19:58:43 +020020
Gilles Peskineb4063892019-07-27 21:36:44 +020021class Setting:
Gabor Mezei9f2b8172024-08-06 12:02:18 +020022 """Representation of one Mbed TLS mbedtls_config.h pr PSA crypto_config.h setting.
Gilles Peskineb4063892019-07-27 21:36:44 +020023
24 Fields:
25 * name: the symbol name ('MBEDTLS_xxx').
26 * value: the value of the macro. The empty string for a plain #define
27 with no value.
28 * active: True if name is defined, False if a #define for name is
Bence Szépkútibb0cfeb2021-05-28 09:42:25 +020029 present in mbedtls_config.h but commented out.
Gilles Peskine53d41ae2019-07-27 23:31:53 +020030 * section: the name of the section that contains this symbol.
Gabor Mezeid53080d2024-08-27 14:06:54 +020031 * configfile: the file the settings is defined
Gilles Peskineb4063892019-07-27 21:36:44 +020032 """
Gabor Mezei92065ed2024-06-07 13:47:59 +020033 # pylint: disable=too-few-public-methods, too-many-arguments
Gabor Mezeid53080d2024-08-27 14:06:54 +020034 def __init__(self, configfile, active, name, value='', section=None):
Gilles Peskineb4063892019-07-27 21:36:44 +020035 self.active = active
36 self.name = name
37 self.value = value
Gilles Peskine53d41ae2019-07-27 23:31:53 +020038 self.section = section
Gabor Mezei3678dee2024-06-04 19:58:43 +020039 self.configfile = configfile
Gilles Peskineb4063892019-07-27 21:36:44 +020040
41class Config:
Gabor Mezei9f2b8172024-08-06 12:02:18 +020042 """Representation of the Mbed TLS and PSA configuration.
Gilles Peskineb4063892019-07-27 21:36:44 +020043
44 In the documentation of this class, a symbol is said to be *active*
45 if there is a #define for it that is not commented out, and *known*
46 if there is a #define for it whether commented out or not.
47
48 This class supports the following protocols:
Gilles Peskinec190c902019-08-01 23:31:05 +020049 * `name in config` is `True` if the symbol `name` is active, `False`
50 otherwise (whether `name` is inactive or not known).
51 * `config[name]` is the value of the macro `name`. If `name` is inactive,
52 raise `KeyError` (even if `name` is known).
Gilles Peskineb4063892019-07-27 21:36:44 +020053 * `config[name] = value` sets the value associated to `name`. `name`
54 must be known, but does not need to be set. This does not cause
55 name to become set.
56 """
57
Gabor Mezeiee521b62024-06-07 13:50:41 +020058 def __init__(self):
Gilles Peskineb4063892019-07-27 21:36:44 +020059 self.settings = {}
Gabor Mezeid53080d2024-08-27 14:06:54 +020060 self.configfiles = []
Gilles Peskineb4063892019-07-27 21:36:44 +020061
62 def __contains__(self, name):
63 """True if the given symbol is active (i.e. set).
64
65 False if the given symbol is not set, even if a definition
66 is present but commented out.
67 """
68 return name in self.settings and self.settings[name].active
69
70 def all(self, *names):
71 """True if all the elements of names are active (i.e. set)."""
Gabor Mezeidaf807f2024-08-14 11:33:46 +020072 return all(name in self for name in names)
Gilles Peskineb4063892019-07-27 21:36:44 +020073
74 def any(self, *names):
75 """True if at least one symbol in names are active (i.e. set)."""
Gabor Mezeidaf807f2024-08-14 11:33:46 +020076 return any(name in self for name in names)
Gilles Peskineb4063892019-07-27 21:36:44 +020077
78 def known(self, name):
79 """True if a #define for name is present, whether it's commented out or not."""
80 return name in self.settings
81
82 def __getitem__(self, name):
83 """Get the value of name, i.e. what the preprocessor symbol expands to.
84
85 If name is not known, raise KeyError. name does not need to be active.
86 """
87 return self.settings[name].value
88
89 def get(self, name, default=None):
90 """Get the value of name. If name is inactive (not set), return default.
91
92 If a #define for name is present and not commented out, return
93 its expansion, even if this is the empty string.
94
95 If a #define for name is present but commented out, return default.
96 """
97 if name in self.settings:
98 return self.settings[name].value
99 else:
100 return default
101
102 def __setitem__(self, name, value):
103 """If name is known, set its value.
104
105 If name is not known, raise KeyError.
106 """
Gabor Mezeic659c1b2024-08-06 17:37:55 +0200107 setting = self.settings[name]
Gabor Mezeid53080d2024-08-27 14:06:54 +0200108 if setting != value:
Gabor Mezeic659c1b2024-08-06 17:37:55 +0200109 setting.configfile.modified = True
Gilles Peskineb4063892019-07-27 21:36:44 +0200110
Gabor Mezeic659c1b2024-08-06 17:37:55 +0200111 setting.value = value
112
Gabor Mezeid53080d2024-08-27 14:06:54 +0200113 def set(self, name, value=None):
Gilles Peskineb4063892019-07-27 21:36:44 +0200114 """Set name to the given value and make it active.
115
116 If value is None and name is already known, don't change its value.
Gabor Mezeic659c1b2024-08-06 17:37:55 +0200117 If value is None and name is not known, set its value.
Gilles Peskineb4063892019-07-27 21:36:44 +0200118 """
119 if name in self.settings:
Gabor Mezeic659c1b2024-08-06 17:37:55 +0200120 setting = self.settings[name]
Gabor Mezeid53080d2024-08-27 14:06:54 +0200121 if setting.value != value or not setting.active:
Gabor Mezeic659c1b2024-08-06 17:37:55 +0200122 setting.configfile.modified = True
Gilles Peskineb4063892019-07-27 21:36:44 +0200123 if value is not None:
Gabor Mezeic659c1b2024-08-06 17:37:55 +0200124 setting.value = value
125 setting.active = True
Gilles Peskineb4063892019-07-27 21:36:44 +0200126 else:
Gabor Mezeid53080d2024-08-27 14:06:54 +0200127 configfile = self._get_configfile(name)
128 self.settings[name] = Setting(configfile, True, name, value=value)
129 configfile.modified = True
Gilles Peskineb4063892019-07-27 21:36:44 +0200130
131 def unset(self, name):
132 """Make name unset (inactive).
133
Gilles Peskine55cc4db2019-08-01 23:13:23 +0200134 name remains known if it was known before.
Gilles Peskineb4063892019-07-27 21:36:44 +0200135 """
Gilles Peskine55cc4db2019-08-01 23:13:23 +0200136 if name not in self.settings:
137 return
Gabor Mezeic5ff33c2024-06-28 17:46:44 +0200138
139 setting = self.settings[name]
140 # Check if modifying the config file
Gabor Mezeid53080d2024-08-27 14:06:54 +0200141 if setting.active:
Gabor Mezeic5ff33c2024-06-28 17:46:44 +0200142 setting.configfile.modified = True
143
144 setting.active = False
Gilles Peskineb4063892019-07-27 21:36:44 +0200145
146 def adapt(self, adapter):
147 """Run adapter on each known symbol and (de)activate it accordingly.
148
149 `adapter` must be a function that returns a boolean. It is called as
Gilles Peskine53d41ae2019-07-27 23:31:53 +0200150 `adapter(name, active, section)` for each setting, where `active` is
151 `True` if `name` is set and `False` if `name` is known but unset,
152 and `section` is the name of the section containing `name`. If
Gilles Peskineb4063892019-07-27 21:36:44 +0200153 `adapter` returns `True`, then set `name` (i.e. make it active),
154 otherwise unset `name` (i.e. make it known but inactive).
155 """
156 for setting in self.settings.values():
Gabor Mezeic5ff33c2024-06-28 17:46:44 +0200157 is_active = setting.active
Gilles Peskine53d41ae2019-07-27 23:31:53 +0200158 setting.active = adapter(setting.name, setting.active,
159 setting.section)
Gabor Mezeic5ff33c2024-06-28 17:46:44 +0200160 # Check if modifying the config file
Gabor Mezeid53080d2024-08-27 14:06:54 +0200161 if setting.active != is_active:
Gabor Mezeic5ff33c2024-06-28 17:46:44 +0200162 setting.configfile.modified = True
Gilles Peskineb4063892019-07-27 21:36:44 +0200163
Gilles Peskine8e90cf42021-05-27 22:12:57 +0200164 def change_matching(self, regexs, enable):
165 """Change all symbols matching one of the regexs to the desired state."""
166 if not regexs:
167 return
168 regex = re.compile('|'.join(regexs))
169 for setting in self.settings.values():
170 if regex.search(setting.name):
Gabor Mezeic5ff33c2024-06-28 17:46:44 +0200171 # Check if modifying the config file
Gabor Mezeid53080d2024-08-27 14:06:54 +0200172 if setting.active != enable:
Gabor Mezeic5ff33c2024-06-28 17:46:44 +0200173 setting.configfile.modified = True
Gilles Peskine8e90cf42021-05-27 22:12:57 +0200174 setting.active = enable
175
Gabor Mezeid53080d2024-08-27 14:06:54 +0200176 def _get_configfile(self, name=None):
177 """Find a config for a setting name.
178
179 If more then one configfile is used this function must be overridden.
180 """
181
182 if name and name in self.settings:
183 return self.get(name).configfile
184 return self.configfiles[0]
185
186 def write(self, filename=None):
187 """Write the whole configuration to the file it was read from.
188
189 If filename is specified, write to this file instead.
190 """
191
192 for configfile in self.configfiles:
193 configfile.write(self.settings, filename)
194
195 def filename(self, name=None):
196 """Get the name of the config file."""
197
198 return self._get_configfile(name).filename
199
Gilles Peskine53d41ae2019-07-27 23:31:53 +0200200def is_full_section(section):
Gabor Mezeide6e1922024-06-28 17:10:50 +0200201 """Is this section affected by "config.py full" and friends?
202
203 In a config file where the sections are not used the whole config file
204 is an empty section (with value None) and the whole file is affected.
205 """
Gabor Mezei3678dee2024-06-04 19:58:43 +0200206 return section is None or section.endswith('support') or section.endswith('modules')
Gilles Peskine53d41ae2019-07-27 23:31:53 +0200207
208def realfull_adapter(_name, active, section):
Gilles Peskineba4162a2022-04-11 17:04:38 +0200209 """Activate all symbols found in the global and boolean feature sections.
210
211 This is intended for building the documentation, including the
212 documentation of settings that are activated by defining an optional
213 preprocessor macro.
214
215 Do not activate definitions in the section containing symbols that are
216 supposed to be defined and documented in their own module.
217 """
218 if section == 'Module configuration options':
Gilles Peskine53d41ae2019-07-27 23:31:53 +0200219 return active
Gilles Peskineb4063892019-07-27 21:36:44 +0200220 return True
221
Gabor Mezei542fd382024-06-10 14:07:42 +0200222PSA_UNSUPPORTED_FEATURE = frozenset([
Gabor Mezei3678dee2024-06-04 19:58:43 +0200223 'PSA_WANT_ALG_CBC_MAC',
224 'PSA_WANT_ALG_XTS',
225 'PSA_WANT_KEY_TYPE_RSA_KEY_PAIR_DERIVE',
226 'PSA_WANT_KEY_TYPE_DH_KEY_PAIR_DERIVE'
227])
228
Gabor Mezei542fd382024-06-10 14:07:42 +0200229PSA_DEPRECATED_FEATURE = frozenset([
Gabor Mezei3678dee2024-06-04 19:58:43 +0200230 'PSA_WANT_KEY_TYPE_ECC_KEY_PAIR',
231 'PSA_WANT_KEY_TYPE_RSA_KEY_PAIR'
232])
233
Gabor Mezei542fd382024-06-10 14:07:42 +0200234PSA_UNSTABLE_FEATURE = frozenset([
Gabor Mezei3678dee2024-06-04 19:58:43 +0200235 'PSA_WANT_ECC_SECP_K1_224'
236])
237
Gabor Mezei9b0f9e72024-06-26 18:08:17 +0200238EXCLUDE_FROM_CRYPTO = PSA_UNSUPPORTED_FEATURE | \
239 PSA_DEPRECATED_FEATURE | \
240 PSA_UNSTABLE_FEATURE
Gabor Mezei542fd382024-06-10 14:07:42 +0200241
Gilles Peskinecfffc282020-04-12 13:55:45 +0200242# The goal of the full configuration is to have everything that can be tested
243# together. This includes deprecated or insecure options. It excludes:
244# * Options that require additional build dependencies or unusual hardware.
245# * Options that make testing less effective.
Gilles Peskinec9d04332020-04-16 20:50:17 +0200246# * Options that are incompatible with other options, or more generally that
247# interact with other parts of the code in such a way that a bulk enabling
248# is not a good way to test them.
Gilles Peskinecfffc282020-04-12 13:55:45 +0200249# * Options that remove features.
Gilles Peskinebbaa2b72020-04-12 13:33:57 +0200250EXCLUDE_FROM_FULL = frozenset([
Gilles Peskinecfffc282020-04-12 13:55:45 +0200251 #pylint: disable=line-too-long
Yanray Wanga8704672023-04-20 17:16:48 +0800252 'MBEDTLS_AES_ONLY_128_BIT_KEY_LENGTH', # interacts with CTR_DRBG_128_BIT_KEY
Gilles Peskinea8861e02023-09-05 20:20:51 +0200253 'MBEDTLS_AES_USE_HARDWARE_ONLY', # hardware dependency
Yanray Wang42be1ba2023-11-23 14:28:47 +0800254 'MBEDTLS_BLOCK_CIPHER_NO_DECRYPT', # incompatible with ECB in PSA, CBC/XTS/NIST_KW/DES
Gilles Peskinec9d04332020-04-16 20:50:17 +0200255 'MBEDTLS_CTR_DRBG_USE_128_BIT_KEY', # interacts with ENTROPY_FORCE_SHA256
Gilles Peskinecfffc282020-04-12 13:55:45 +0200256 'MBEDTLS_DEPRECATED_REMOVED', # conflicts with deprecated options
Gilles Peskine90581ee2020-04-12 14:02:47 +0200257 'MBEDTLS_DEPRECATED_WARNING', # conflicts with deprecated options
Gilles Peskinec9d04332020-04-16 20:50:17 +0200258 'MBEDTLS_ECDH_VARIANT_EVEREST_ENABLED', # influences the use of ECDH in TLS
Janos Follath5b7c38f2023-08-01 08:51:12 +0100259 'MBEDTLS_ECP_WITH_MPI_UINT', # disables the default ECP and is experimental
Gilles Peskinec9d04332020-04-16 20:50:17 +0200260 'MBEDTLS_ENTROPY_FORCE_SHA256', # interacts with CTR_DRBG_128_BIT_KEY
Gilles Peskinecfffc282020-04-12 13:55:45 +0200261 'MBEDTLS_HAVE_SSE2', # hardware dependency
262 'MBEDTLS_MEMORY_BACKTRACE', # depends on MEMORY_BUFFER_ALLOC_C
263 'MBEDTLS_MEMORY_BUFFER_ALLOC_C', # makes sanitizers (e.g. ASan) less effective
264 'MBEDTLS_MEMORY_DEBUG', # depends on MEMORY_BUFFER_ALLOC_C
Gilles Peskinec9d04332020-04-16 20:50:17 +0200265 'MBEDTLS_NO_64BIT_MULTIPLICATION', # influences anything that uses bignum
Gilles Peskinecfffc282020-04-12 13:55:45 +0200266 'MBEDTLS_NO_DEFAULT_ENTROPY_SOURCES', # removes a feature
267 'MBEDTLS_NO_PLATFORM_ENTROPY', # removes a feature
Gilles Peskinec9d04332020-04-16 20:50:17 +0200268 'MBEDTLS_NO_UDBL_DIVISION', # influences anything that uses bignum
Gilles Peskineefaee9a2023-09-20 20:49:47 +0200269 'MBEDTLS_PSA_P256M_DRIVER_ENABLED', # influences SECP256R1 KeyGen/ECDH/ECDSA
Gilles Peskinecfffc282020-04-12 13:55:45 +0200270 'MBEDTLS_PLATFORM_NO_STD_FUNCTIONS', # removes a feature
David Horstmann6f8c95b2024-03-14 14:52:45 +0000271 'MBEDTLS_PSA_ASSUME_EXCLUSIVE_BUFFERS', # removes a feature
Gilles Peskinef08b3f82020-11-13 17:36:48 +0100272 'MBEDTLS_PSA_CRYPTO_EXTERNAL_RNG', # behavior change + build dependency
Ronald Cronc3623db2020-10-29 10:51:32 +0100273 'MBEDTLS_PSA_CRYPTO_KEY_ID_ENCODES_OWNER', # incompatible with USE_PSA_CRYPTO
Gilles Peskinecfffc282020-04-12 13:55:45 +0200274 'MBEDTLS_PSA_CRYPTO_SPM', # platform dependency (PSA SPM)
Gilles Peskinea08def92023-04-28 21:01:49 +0200275 'MBEDTLS_PSA_INJECT_ENTROPY', # conflicts with platform entropy sources
Gilles Peskinec9d04332020-04-16 20:50:17 +0200276 'MBEDTLS_RSA_NO_CRT', # influences the use of RSA in X.509 and TLS
Tom Cosgrove87fbfb52022-03-15 10:51:52 +0000277 'MBEDTLS_SHA256_USE_A64_CRYPTO_ONLY', # interacts with *_USE_A64_CRYPTO_IF_PRESENT
Dave Rodgman9be3cf02023-10-11 14:47:55 +0100278 'MBEDTLS_SHA256_USE_ARMV8_A_CRYPTO_ONLY', # interacts with *_USE_ARMV8_A_CRYPTO_IF_PRESENT
Tom Cosgrove87fbfb52022-03-15 10:51:52 +0000279 'MBEDTLS_SHA512_USE_A64_CRYPTO_ONLY', # interacts with *_USE_A64_CRYPTO_IF_PRESENT
Dave Rodgman7cb635a2023-10-12 16:14:51 +0100280 'MBEDTLS_SHA256_USE_A64_CRYPTO_IF_PRESENT', # setting *_USE_ARMV8_A_CRYPTO is sufficient
Manuel Pégourié-Gonnard6240def2020-07-10 09:35:54 +0200281 'MBEDTLS_TEST_CONSTANT_FLOW_MEMSAN', # build dependency (clang+memsan)
Manuel Pégourié-Gonnard73afa372020-08-19 10:27:38 +0200282 'MBEDTLS_TEST_CONSTANT_FLOW_VALGRIND', # build dependency (valgrind headers)
Hanno Beckere1113562019-06-12 13:59:14 +0100283 'MBEDTLS_X509_REMOVE_INFO', # removes a feature
Gabor Mezei542fd382024-06-10 14:07:42 +0200284 *PSA_UNSUPPORTED_FEATURE,
285 *PSA_DEPRECATED_FEATURE,
286 *PSA_UNSTABLE_FEATURE
Gilles Peskinebbaa2b72020-04-12 13:33:57 +0200287])
288
Gilles Peskine32e889d2020-04-12 23:43:28 +0200289def is_seamless_alt(name):
Gilles Peskinec34faba2020-04-20 15:44:14 +0200290 """Whether the xxx_ALT symbol should be included in the full configuration.
Gilles Peskine32e889d2020-04-12 23:43:28 +0200291
Gilles Peskinec34faba2020-04-20 15:44:14 +0200292 Include alternative implementations of platform functions, which are
Gilles Peskine32e889d2020-04-12 23:43:28 +0200293 configurable function pointers that default to the built-in function.
294 This way we test that the function pointers exist and build correctly
295 without changing the behavior, and tests can verify that the function
296 pointers are used by modifying those pointers.
297
298 Exclude alternative implementations of library functions since they require
299 an implementation of the relevant functions and an xxx_alt.h header.
300 """
Gilles Peskinea8861e02023-09-05 20:20:51 +0200301 if name in (
302 'MBEDTLS_PLATFORM_GMTIME_R_ALT',
303 'MBEDTLS_PLATFORM_SETUP_TEARDOWN_ALT',
304 'MBEDTLS_PLATFORM_MS_TIME_ALT',
305 'MBEDTLS_PLATFORM_ZEROIZE_ALT',
306 ):
Gilles Peskinec34faba2020-04-20 15:44:14 +0200307 # Similar to non-platform xxx_ALT, requires platform_alt.h
308 return False
Gilles Peskine32e889d2020-04-12 23:43:28 +0200309 return name.startswith('MBEDTLS_PLATFORM_')
310
Gilles Peskine53d41ae2019-07-27 23:31:53 +0200311def include_in_full(name):
312 """Rules for symbols in the "full" configuration."""
Gabor Mezei542fd382024-06-10 14:07:42 +0200313 if name in EXCLUDE_FROM_FULL:
Gilles Peskine53d41ae2019-07-27 23:31:53 +0200314 return False
315 if name.endswith('_ALT'):
Gilles Peskine32e889d2020-04-12 23:43:28 +0200316 return is_seamless_alt(name)
Gilles Peskine53d41ae2019-07-27 23:31:53 +0200317 return True
318
319def full_adapter(name, active, section):
320 """Config adapter for "full"."""
321 if not is_full_section(section):
322 return active
323 return include_in_full(name)
324
Gilles Peskinecfffc282020-04-12 13:55:45 +0200325# The baremetal configuration excludes options that require a library or
326# operating system feature that is typically not present on bare metal
327# systems. Features that are excluded from "full" won't be in "baremetal"
328# either (unless explicitly turned on in baremetal_adapter) so they don't
329# need to be repeated here.
Gilles Peskinebbaa2b72020-04-12 13:33:57 +0200330EXCLUDE_FROM_BAREMETAL = frozenset([
Gilles Peskinecfffc282020-04-12 13:55:45 +0200331 #pylint: disable=line-too-long
Gilles Peskine98f8f952020-04-20 15:38:39 +0200332 'MBEDTLS_ENTROPY_NV_SEED', # requires a filesystem and FS_IO or alternate NV seed hooks
Gilles Peskinecfffc282020-04-12 13:55:45 +0200333 'MBEDTLS_FS_IO', # requires a filesystem
Gilles Peskinecfffc282020-04-12 13:55:45 +0200334 'MBEDTLS_HAVE_TIME', # requires a clock
335 'MBEDTLS_HAVE_TIME_DATE', # requires a clock
336 'MBEDTLS_NET_C', # requires POSIX-like networking
337 'MBEDTLS_PLATFORM_FPRINTF_ALT', # requires FILE* from stdio.h
Gilles Peskine98f8f952020-04-20 15:38:39 +0200338 'MBEDTLS_PLATFORM_NV_SEED_ALT', # requires a filesystem and ENTROPY_NV_SEED
339 'MBEDTLS_PLATFORM_TIME_ALT', # requires a clock and HAVE_TIME
340 'MBEDTLS_PSA_CRYPTO_SE_C', # requires a filesystem and PSA_CRYPTO_STORAGE_C
Gilles Peskinecfffc282020-04-12 13:55:45 +0200341 'MBEDTLS_PSA_CRYPTO_STORAGE_C', # requires a filesystem
342 'MBEDTLS_PSA_ITS_FILE_C', # requires a filesystem
343 'MBEDTLS_THREADING_C', # requires a threading interface
344 'MBEDTLS_THREADING_PTHREAD', # requires pthread
345 'MBEDTLS_TIMING_C', # requires a clock
Dave Rodgman9be3cf02023-10-11 14:47:55 +0100346 'MBEDTLS_SHA256_USE_A64_CRYPTO_IF_PRESENT', # requires an OS for runtime-detection
Dave Rodgman5b89c552023-10-10 14:59:02 +0100347 'MBEDTLS_SHA256_USE_ARMV8_A_CRYPTO_IF_PRESENT', # requires an OS for runtime-detection
Dave Rodgmanbe7915a2023-10-11 10:46:38 +0100348 'MBEDTLS_SHA512_USE_A64_CRYPTO_IF_PRESENT', # requires an OS for runtime-detection
Gilles Peskinebbaa2b72020-04-12 13:33:57 +0200349])
350
Gilles Peskine53d41ae2019-07-27 23:31:53 +0200351def keep_in_baremetal(name):
352 """Rules for symbols in the "baremetal" configuration."""
Gilles Peskinebbaa2b72020-04-12 13:33:57 +0200353 if name in EXCLUDE_FROM_BAREMETAL:
Gilles Peskine53d41ae2019-07-27 23:31:53 +0200354 return False
355 return True
356
357def baremetal_adapter(name, active, section):
358 """Config adapter for "baremetal"."""
359 if not is_full_section(section):
360 return active
361 if name == 'MBEDTLS_NO_PLATFORM_ENTROPY':
Gilles Peskinecfffc282020-04-12 13:55:45 +0200362 # No OS-provided entropy source
Gilles Peskine53d41ae2019-07-27 23:31:53 +0200363 return True
364 return include_in_full(name) and keep_in_baremetal(name)
365
Gilles Peskine120f29d2021-09-01 19:51:19 +0200366# This set contains options that are mostly for debugging or test purposes,
367# and therefore should be excluded when doing code size measurements.
368# Options that are their own module (such as MBEDTLS_ERROR_C) are not listed
369# and therefore will be included when doing code size measurements.
370EXCLUDE_FOR_SIZE = frozenset([
371 'MBEDTLS_DEBUG_C', # large code size increase in TLS
372 'MBEDTLS_SELF_TEST', # increases the size of many modules
373 'MBEDTLS_TEST_HOOKS', # only useful with the hosted test framework, increases code size
374])
375
376def baremetal_size_adapter(name, active, section):
377 if name in EXCLUDE_FOR_SIZE:
378 return False
379 return baremetal_adapter(name, active, section)
380
Gilles Peskine31987c62020-01-31 14:23:30 +0100381def include_in_crypto(name):
382 """Rules for symbols in a crypto configuration."""
383 if name.startswith('MBEDTLS_X509_') or \
384 name.startswith('MBEDTLS_SSL_') or \
385 name.startswith('MBEDTLS_KEY_EXCHANGE_'):
386 return False
387 if name in [
Gilles Peskinecfffc282020-04-12 13:55:45 +0200388 'MBEDTLS_DEBUG_C', # part of libmbedtls
389 'MBEDTLS_NET_C', # part of libmbedtls
Nayna Jainc9deb182020-11-16 19:03:12 +0000390 'MBEDTLS_PKCS7_C', # part of libmbedx509
Gilles Peskine31987c62020-01-31 14:23:30 +0100391 ]:
392 return False
Gabor Mezei542fd382024-06-10 14:07:42 +0200393 if name in EXCLUDE_FROM_CRYPTO:
394 return False
Gilles Peskine31987c62020-01-31 14:23:30 +0100395 return True
396
397def crypto_adapter(adapter):
398 """Modify an adapter to disable non-crypto symbols.
399
400 ``crypto_adapter(adapter)(name, active, section)`` is like
401 ``adapter(name, active, section)``, but unsets all X.509 and TLS symbols.
402 """
403 def continuation(name, active, section):
404 if not include_in_crypto(name):
405 return False
406 if adapter is None:
407 return active
408 return adapter(name, active, section)
409 return continuation
410
Gilles Peskineed5c21d2022-06-27 23:02:09 +0200411DEPRECATED = frozenset([
412 'MBEDTLS_PSA_CRYPTO_SE_C',
Gabor Mezei542fd382024-06-10 14:07:42 +0200413 *PSA_DEPRECATED_FEATURE
Gilles Peskineed5c21d2022-06-27 23:02:09 +0200414])
Gilles Peskine30de2e82020-04-20 21:39:22 +0200415def no_deprecated_adapter(adapter):
Gilles Peskinebe1d6092020-04-12 14:17:16 +0200416 """Modify an adapter to disable deprecated symbols.
417
Gilles Peskine30de2e82020-04-20 21:39:22 +0200418 ``no_deprecated_adapter(adapter)(name, active, section)`` is like
Gilles Peskinebe1d6092020-04-12 14:17:16 +0200419 ``adapter(name, active, section)``, but unsets all deprecated symbols
420 and sets ``MBEDTLS_DEPRECATED_REMOVED``.
421 """
422 def continuation(name, active, section):
423 if name == 'MBEDTLS_DEPRECATED_REMOVED':
424 return True
Gilles Peskineed5c21d2022-06-27 23:02:09 +0200425 if name in DEPRECATED:
426 return False
Gilles Peskinebe1d6092020-04-12 14:17:16 +0200427 if adapter is None:
428 return active
429 return adapter(name, active, section)
430 return continuation
431
Paul Elliottfb81f772023-10-18 17:44:59 +0100432def no_platform_adapter(adapter):
433 """Modify an adapter to disable platform symbols.
434
435 ``no_platform_adapter(adapter)(name, active, section)`` is like
436 ``adapter(name, active, section)``, but unsets all platform symbols other
437 ``than MBEDTLS_PLATFORM_C.
438 """
439 def continuation(name, active, section):
440 # Allow MBEDTLS_PLATFORM_C but remove all other platform symbols.
441 if name.startswith('MBEDTLS_PLATFORM_') and name != 'MBEDTLS_PLATFORM_C':
442 return False
443 if adapter is None:
444 return active
445 return adapter(name, active, section)
446 return continuation
447
Gabor Mezei3678dee2024-06-04 19:58:43 +0200448class ConfigFile(metaclass=ABCMeta):
Gabor Mezei62a9bd02024-06-07 13:44:40 +0200449 """Representation of a configuration file."""
450
Gabor Mezei93a6d1f2024-06-26 18:01:09 +0200451 def __init__(self, default_path, name, filename=None):
Gabor Mezei62a9bd02024-06-07 13:44:40 +0200452 """Check if the config file exists."""
Gilles Peskineb4063892019-07-27 21:36:44 +0200453 if filename is None:
Gabor Mezei3678dee2024-06-04 19:58:43 +0200454 for candidate in default_path:
Gilles Peskinece674a92020-03-24 15:37:00 +0100455 if os.path.lexists(candidate):
456 filename = candidate
Gilles Peskine208e4ec2019-07-29 23:43:20 +0200457 break
Gilles Peskinece674a92020-03-24 15:37:00 +0100458 else:
Gabor Mezei8d72ac62024-06-28 17:18:37 +0200459 raise FileNotFoundError(f'{name} configuration file not found: '
460 f'{filename if filename else default_path}')
Gilles Peskineb4063892019-07-27 21:36:44 +0200461
Gabor Mezei3678dee2024-06-04 19:58:43 +0200462 self.filename = filename
463 self.templates = []
464 self.current_section = None
465 self.inclusion_guard = None
Gabor Mezei8a64d8e2024-06-10 15:23:43 +0200466 self.modified = False
Gilles Peskineb4063892019-07-27 21:36:44 +0200467
468 _define_line_regexp = (r'(?P<indentation>\s*)' +
469 r'(?P<commented_out>(//\s*)?)' +
470 r'(?P<define>#\s*define\s+)' +
471 r'(?P<name>\w+)' +
472 r'(?P<arguments>(?:\((?:\w|\s|,)*\))?)' +
473 r'(?P<separator>\s*)' +
474 r'(?P<value>.*)')
Gilles Peskine9ba9c212024-05-23 15:03:43 +0200475 _ifndef_line_regexp = r'#ifndef (?P<inclusion_guard>\w+)'
Gilles Peskine53d41ae2019-07-27 23:31:53 +0200476 _section_line_regexp = (r'\s*/?\*+\s*[\\@]name\s+SECTION:\s*' +
477 r'(?P<section>.*)[ */]*')
478 _config_line_regexp = re.compile(r'|'.join([_define_line_regexp,
Gilles Peskine9ba9c212024-05-23 15:03:43 +0200479 _ifndef_line_regexp,
Gilles Peskine53d41ae2019-07-27 23:31:53 +0200480 _section_line_regexp]))
Gilles Peskineb4063892019-07-27 21:36:44 +0200481 def _parse_line(self, line):
Gabor Mezei62a9bd02024-06-07 13:44:40 +0200482 """Parse a line in the config file, save the templates representing the lines
483 and return the corresponding setting element.
484 """
Gabor Mezei4706fe72024-07-08 17:00:55 +0200485
Gilles Peskineb4063892019-07-27 21:36:44 +0200486 line = line.rstrip('\r\n')
Gilles Peskine53d41ae2019-07-27 23:31:53 +0200487 m = re.match(self._config_line_regexp, line)
488 if m is None:
Gabor Mezei3678dee2024-06-04 19:58:43 +0200489 self.templates.append(line)
490 return None
Gilles Peskine53d41ae2019-07-27 23:31:53 +0200491 elif m.group('section'):
492 self.current_section = m.group('section')
Gabor Mezei3678dee2024-06-04 19:58:43 +0200493 self.templates.append(line)
494 return None
Gilles Peskine9ba9c212024-05-23 15:03:43 +0200495 elif m.group('inclusion_guard') and self.inclusion_guard is None:
496 self.inclusion_guard = m.group('inclusion_guard')
Gabor Mezei3678dee2024-06-04 19:58:43 +0200497 self.templates.append(line)
498 return None
Gilles Peskine53d41ae2019-07-27 23:31:53 +0200499 else:
Gilles Peskineb4063892019-07-27 21:36:44 +0200500 active = not m.group('commented_out')
501 name = m.group('name')
502 value = m.group('value')
Gilles Peskine9ba9c212024-05-23 15:03:43 +0200503 if name == self.inclusion_guard and value == '':
504 # The file double-inclusion guard is not an option.
Gabor Mezei3678dee2024-06-04 19:58:43 +0200505 self.templates.append(line)
506 return None
Gilles Peskineb4063892019-07-27 21:36:44 +0200507 template = (name,
508 m.group('indentation'),
509 m.group('define') + name +
510 m.group('arguments') + m.group('separator'))
Gabor Mezei3678dee2024-06-04 19:58:43 +0200511 self.templates.append(template)
Gilles Peskineb4063892019-07-27 21:36:44 +0200512
Gabor Mezei3678dee2024-06-04 19:58:43 +0200513 return (active, name, value, self.current_section)
514
515 def parse_file(self):
Gabor Mezei62a9bd02024-06-07 13:44:40 +0200516 """Parse the whole file and return the settings."""
Gabor Mezei4706fe72024-07-08 17:00:55 +0200517
Gabor Mezei3678dee2024-06-04 19:58:43 +0200518 with open(self.filename, 'r', encoding='utf-8') as file:
519 for line in file:
520 setting = self._parse_line(line)
521 if setting is not None:
522 yield setting
523 self.current_section = None
524
Gabor Mezeie7742b32024-06-26 18:04:09 +0200525 #pylint: disable=no-self-use
526 def _format_template(self, setting, indent, middle):
Gabor Mezei4706fe72024-07-08 17:00:55 +0200527 """Build a line for the config file for the given setting.
Gabor Mezeie7742b32024-06-26 18:04:09 +0200528
529 The line has the form "<indent>#define <name> <value>"
530 where <middle> is "#define <name> ".
531 """
Gabor Mezei4706fe72024-07-08 17:00:55 +0200532
Gabor Mezeie7742b32024-06-26 18:04:09 +0200533 value = setting.value
534 if value is None:
535 value = ''
536 # Normally the whitespace to separate the symbol name from the
537 # value is part of middle, and there's no whitespace for a symbol
538 # with no value. But if a symbol has been changed from having a
539 # value to not having one, the whitespace is wrong, so fix it.
540 if value:
541 if middle[-1] not in '\t ':
542 middle += ' '
543 else:
544 middle = middle.rstrip()
545 return ''.join([indent,
546 '' if setting.active else '//',
547 middle,
548 value]).rstrip()
Gabor Mezei3678dee2024-06-04 19:58:43 +0200549
550 def write_to_stream(self, settings, output):
551 """Write the whole configuration to output."""
Gabor Mezei4706fe72024-07-08 17:00:55 +0200552
Gabor Mezei3678dee2024-06-04 19:58:43 +0200553 for template in self.templates:
554 if isinstance(template, str):
555 line = template
556 else:
Gabor Mezeie7742b32024-06-26 18:04:09 +0200557 name, indent, middle = template
558 line = self._format_template(settings[name], indent, middle)
Gabor Mezei3678dee2024-06-04 19:58:43 +0200559 output.write(line + '\n')
560
561 def write(self, settings, filename=None):
562 """Write the whole configuration to the file it was read from.
563
564 If filename is specified, write to this file instead.
565 """
Gabor Mezei4706fe72024-07-08 17:00:55 +0200566
Gabor Mezei3678dee2024-06-04 19:58:43 +0200567 if filename is None:
568 filename = self.filename
Gabor Mezei8a64d8e2024-06-10 15:23:43 +0200569
570 # Not modified so no need to write to the file
571 if not self.modified and filename == self.filename:
572 return
573
Gabor Mezei3678dee2024-06-04 19:58:43 +0200574 with open(filename, 'w', encoding='utf-8') as output:
575 self.write_to_stream(settings, output)
576
Gabor Mezeif77722d2024-06-28 16:49:33 +0200577class MbedTLSConfigFile(ConfigFile):
Gabor Mezei62a9bd02024-06-07 13:44:40 +0200578 """Representation of an MbedTLS configuration file."""
579
Gabor Mezei3678dee2024-06-04 19:58:43 +0200580 _path_in_tree = 'include/mbedtls/mbedtls_config.h'
581 default_path = [_path_in_tree,
582 os.path.join(os.path.dirname(__file__),
583 os.pardir,
584 _path_in_tree),
585 os.path.join(os.path.dirname(os.path.abspath(os.path.dirname(__file__))),
586 _path_in_tree)]
587
588 def __init__(self, filename=None):
Gabor Mezei93a6d1f2024-06-26 18:01:09 +0200589 super().__init__(self.default_path, 'Mbed TLS', filename)
Gabor Mezei3678dee2024-06-04 19:58:43 +0200590 self.current_section = 'header'
591
Gabor Mezei3678dee2024-06-04 19:58:43 +0200592class CryptoConfigFile(ConfigFile):
Gabor Mezei4706fe72024-07-08 17:00:55 +0200593 """Representation of a Crypto configuration file."""
Gabor Mezei62a9bd02024-06-07 13:44:40 +0200594
Gabor Mezei3de65862024-07-08 16:14:10 +0200595 # Temporary, while Mbed TLS does not just rely on the TF-PSA-Crypto
596 # build system to build its crypto library. When it does, the
597 # condition can just be removed.
Gabor Mezei776ee902024-09-09 17:00:50 +0200598 _path_in_tree = ('include/psa/crypto_config.h'
599 if not os.path.isdir(os.path.join(os.path.dirname(__file__),
600 os.pardir,
601 'tf-psa-crypto')) else
602 'tf-psa-crypto/include/psa/crypto_config.h')
Gabor Mezei3678dee2024-06-04 19:58:43 +0200603 default_path = [_path_in_tree,
604 os.path.join(os.path.dirname(__file__),
605 os.pardir,
606 _path_in_tree),
607 os.path.join(os.path.dirname(os.path.abspath(os.path.dirname(__file__))),
608 _path_in_tree)]
609
610 def __init__(self, filename=None):
Gabor Mezei93a6d1f2024-06-26 18:01:09 +0200611 super().__init__(self.default_path, 'Crypto', filename)
Gabor Mezei3678dee2024-06-04 19:58:43 +0200612
Gabor Mezeif77722d2024-06-28 16:49:33 +0200613class MbedTLSConfig(Config):
Gabor Mezei62a9bd02024-06-07 13:44:40 +0200614 """Representation of the Mbed TLS configuration.
Gabor Mezei3678dee2024-06-04 19:58:43 +0200615
616 See the documentation of the `Config` class for methods to query
617 and modify the configuration.
618 """
Gabor Mezei4706fe72024-07-08 17:00:55 +0200619
Gabor Mezeiee521b62024-06-07 13:50:41 +0200620 def __init__(self, filename=None):
Gabor Mezei3678dee2024-06-04 19:58:43 +0200621 """Read the Mbed TLS configuration file."""
Gabor Mezei4706fe72024-07-08 17:00:55 +0200622
Gabor Mezei3678dee2024-06-04 19:58:43 +0200623 super().__init__()
Gabor Mezeid53080d2024-08-27 14:06:54 +0200624 configfile = MbedTLSConfigFile(filename)
625 self.configfiles.append(configfile)
626 self.settings.update({name: Setting(configfile, active, name, value, section)
Gabor Mezei92065ed2024-06-07 13:47:59 +0200627 for (active, name, value, section)
Gabor Mezeid53080d2024-08-27 14:06:54 +0200628 in configfile.parse_file()})
Gabor Mezei3678dee2024-06-04 19:58:43 +0200629
630 def set(self, name, value=None):
Gabor Mezei4706fe72024-07-08 17:00:55 +0200631 """Set name to the given value and make it active."""
632
Gabor Mezei3678dee2024-06-04 19:58:43 +0200633 if name not in self.settings:
Gabor Mezeid53080d2024-08-27 14:06:54 +0200634 self._get_configfile().templates.append((name, '', '#define ' + name + ' '))
Gabor Mezeiee521b62024-06-07 13:50:41 +0200635
Gabor Mezei3678dee2024-06-04 19:58:43 +0200636 super().set(name, value)
Gilles Peskineb4063892019-07-27 21:36:44 +0200637
Gabor Mezei3678dee2024-06-04 19:58:43 +0200638class CryptoConfig(Config):
Gabor Mezei62a9bd02024-06-07 13:44:40 +0200639 """Representation of the PSA crypto configuration.
Gabor Mezei3678dee2024-06-04 19:58:43 +0200640
641 See the documentation of the `Config` class for methods to query
642 and modify the configuration.
643 """
Gabor Mezei4706fe72024-07-08 17:00:55 +0200644
Gabor Mezeiee521b62024-06-07 13:50:41 +0200645 def __init__(self, filename=None):
Gabor Mezei3678dee2024-06-04 19:58:43 +0200646 """Read the PSA crypto configuration file."""
Gabor Mezei4706fe72024-07-08 17:00:55 +0200647
Gabor Mezei3678dee2024-06-04 19:58:43 +0200648 super().__init__()
Gabor Mezeid53080d2024-08-27 14:06:54 +0200649 configfile = CryptoConfigFile(filename)
650 self.configfiles.append(configfile)
651 self.settings.update({name: Setting(configfile, active, name, value, section)
Gabor Mezei92065ed2024-06-07 13:47:59 +0200652 for (active, name, value, section)
Gabor Mezeid53080d2024-08-27 14:06:54 +0200653 in configfile.parse_file()})
Gabor Mezei3678dee2024-06-04 19:58:43 +0200654
Gabor Mezeid723b512024-06-07 15:31:52 +0200655 def set(self, name, value='1'):
Gabor Mezei4706fe72024-07-08 17:00:55 +0200656 """Set name to the given value and make it active."""
657
Gabor Mezei542fd382024-06-10 14:07:42 +0200658 if name in PSA_UNSUPPORTED_FEATURE:
Gabor Mezei92065ed2024-06-07 13:47:59 +0200659 raise ValueError(f'Feature is unsupported: \'{name}\'')
Gabor Mezei542fd382024-06-10 14:07:42 +0200660 if name in PSA_UNSTABLE_FEATURE:
Gabor Mezei92065ed2024-06-07 13:47:59 +0200661 raise ValueError(f'Feature is unstable: \'{name}\'')
Gabor Mezei3678dee2024-06-04 19:58:43 +0200662
663 if name not in self.settings:
Gabor Mezeid53080d2024-08-27 14:06:54 +0200664 self._get_configfile().templates.append((name, '', '#define ' + name + ' '))
Gabor Mezeiee521b62024-06-07 13:50:41 +0200665
Gabor Mezei3678dee2024-06-04 19:58:43 +0200666 super().set(name, value)
667
Gabor Mezei33dd2932024-06-28 17:51:58 +0200668class CombinedConfig(Config):
Gabor Mezei62a9bd02024-06-07 13:44:40 +0200669 """Representation of MbedTLS and PSA crypto configuration
670
671 See the documentation of the `Config` class for methods to query
672 and modify the configuration.
673 """
Gabor Mezei3678dee2024-06-04 19:58:43 +0200674
Gabor Mezei3e2a5502024-06-28 17:27:19 +0200675 def __init__(self, *configs):
Gabor Mezeiee521b62024-06-07 13:50:41 +0200676 super().__init__()
Gabor Mezei3e2a5502024-06-28 17:27:19 +0200677 for config in configs:
678 if isinstance(config, MbedTLSConfigFile):
679 self.mbedtls_configfile = config
680 elif isinstance(config, CryptoConfigFile):
681 self.crypto_configfile = config
682 else:
683 raise ValueError(f'Invalid configfile: {config}')
Gabor Mezeid53080d2024-08-27 14:06:54 +0200684 self.configfiles.append(config)
Gabor Mezei3e2a5502024-06-28 17:27:19 +0200685
Gabor Mezeid53080d2024-08-27 14:06:54 +0200686 self.settings.update({name: Setting(configfile, active, name, value, section)
Gabor Mezeiee521b62024-06-07 13:50:41 +0200687 for configfile in [self.mbedtls_configfile, self.crypto_configfile]
688 for (active, name, value, section) in configfile.parse_file()})
Gabor Mezei3678dee2024-06-04 19:58:43 +0200689
690 _crypto_regexp = re.compile(r'$PSA_.*')
Gabor Mezeid53080d2024-08-27 14:06:54 +0200691 def _get_configfile(self, name=None):
Gabor Mezei4706fe72024-07-08 17:00:55 +0200692 """Find a config type for a setting name"""
693
Gabor Mezeiee521b62024-06-07 13:50:41 +0200694 if name in self.settings:
695 return self.settings[name].configfile
696 elif re.match(self._crypto_regexp, name):
697 return self.crypto_configfile
Gabor Mezei3678dee2024-06-04 19:58:43 +0200698 else:
Gabor Mezeiee521b62024-06-07 13:50:41 +0200699 return self.mbedtls_configfile
Gabor Mezei3678dee2024-06-04 19:58:43 +0200700
701 def set(self, name, value=None):
Gabor Mezei4706fe72024-07-08 17:00:55 +0200702 """Set name to the given value and make it active."""
703
Gabor Mezeiee521b62024-06-07 13:50:41 +0200704 configfile = self._get_configfile(name)
Gabor Mezei3678dee2024-06-04 19:58:43 +0200705
Gabor Mezeiee521b62024-06-07 13:50:41 +0200706 if configfile == self.crypto_configfile:
Gabor Mezei542fd382024-06-10 14:07:42 +0200707 if name in PSA_UNSUPPORTED_FEATURE:
Gabor Mezeiee521b62024-06-07 13:50:41 +0200708 raise ValueError(f'Feature is unsupported: \'{name}\'')
Gabor Mezei542fd382024-06-10 14:07:42 +0200709 if name in PSA_UNSTABLE_FEATURE:
Gabor Mezeiee521b62024-06-07 13:50:41 +0200710 raise ValueError(f'Feature is unstable: \'{name}\'')
711
Gabor Mezeid723b512024-06-07 15:31:52 +0200712 # The default value in the crypto config is '1'
713 if not value:
714 value = '1'
715
Gabor Mezeic659c1b2024-08-06 17:37:55 +0200716 if name not in self.settings:
Gabor Mezeiee521b62024-06-07 13:50:41 +0200717 configfile.templates.append((name, '', '#define ' + name + ' '))
718
Gabor Mezeid53080d2024-08-27 14:06:54 +0200719 super().set(name, value)
Gabor Mezeiee521b62024-06-07 13:50:41 +0200720
Gabor Mezeidaf807f2024-08-14 11:33:46 +0200721 #pylint: disable=arguments-differ
Gabor Mezei3678dee2024-06-04 19:58:43 +0200722 def write(self, mbedtls_file=None, crypto_file=None):
Gabor Mezei62a9bd02024-06-07 13:44:40 +0200723 """Write the whole configuration to the file it was read from.
724
725 If mbedtls_file or crypto_file is specified, write the specific configuration
726 to the corresponding file instead.
727 """
Gabor Mezei4706fe72024-07-08 17:00:55 +0200728
Gabor Mezeiee521b62024-06-07 13:50:41 +0200729 self.mbedtls_configfile.write(self.settings, mbedtls_file)
730 self.crypto_configfile.write(self.settings, crypto_file)
Gabor Mezei3678dee2024-06-04 19:58:43 +0200731
Gabor Mezeiee521b62024-06-07 13:50:41 +0200732 def filename(self, name=None):
Gabor Mezei4706fe72024-07-08 17:00:55 +0200733 """Get the names of the config files.
734
735 If 'name' is specified return the name of the config file where it is defined.
736 """
737
Gabor Mezeiee521b62024-06-07 13:50:41 +0200738 if not name:
739 return [config.filename for config in [self.mbedtls_configfile, self.crypto_configfile]]
740
741 return self._get_configfile(name).filename
Gilles Peskineb4063892019-07-27 21:36:44 +0200742
Gabor Mezei24d7cc72024-08-06 15:11:24 +0200743
744class ConfigTool(metaclass=ABCMeta):
745 """Command line config manipulation tool.
746
747 Custom parser option can be added by overriding 'custom_parser_options'.
748 """
749
750 def __init__(self, file_type):
751 """Create parser for config manipulation tool."""
752
753 self.parser = argparse.ArgumentParser(description="""
754 Configuration file manipulation tool.""")
755 self.subparsers = self.parser.add_subparsers(dest='command',
756 title='Commands')
757 self._common_parser_options(file_type)
758 self.custom_parser_options()
759 self.parser_args = self.parser.parse_args()
760 self.config = Config() # Make the pylint happy
761
762 def add_adapter(self, name, function, description):
763 """Creates a command in the tool for a configuration adapter."""
764
765 subparser = self.subparsers.add_parser(name, help=description)
766 subparser.set_defaults(adapter=function)
767
768 def _common_parser_options(self, file_type):
769 """Common parser options for config manipulation tool."""
770
771 self.parser.add_argument('--file', '-f',
772 help="""File to read (and modify if requested).
773 Default: {}.
774 """.format(file_type.default_path))
775 self.parser.add_argument('--force', '-o',
776 action='store_true',
777 help="""For the set command, if SYMBOL is not
778 present, add a definition for it.""")
779 self.parser.add_argument('--write', '-w', metavar='FILE',
780 help="""File to write to instead of the input file.""")
781
782 parser_get = self.subparsers.add_parser('get',
783 help="""Find the value of SYMBOL
784 and print it. Exit with
785 status 0 if a #define for SYMBOL is
786 found, 1 otherwise.
787 """)
Gilles Peskineb4063892019-07-27 21:36:44 +0200788 parser_get.add_argument('symbol', metavar='SYMBOL')
Gabor Mezei24d7cc72024-08-06 15:11:24 +0200789 parser_set = self.subparsers.add_parser('set',
790 help="""Set SYMBOL to VALUE.
791 If VALUE is omitted, just uncomment
792 the #define for SYMBOL.
793 Error out of a line defining
794 SYMBOL (commented or not) is not
795 found, unless --force is passed.
796 """)
Gilles Peskineb4063892019-07-27 21:36:44 +0200797 parser_set.add_argument('symbol', metavar='SYMBOL')
Gilles Peskine0c7fcd22019-08-01 23:14:00 +0200798 parser_set.add_argument('value', metavar='VALUE', nargs='?',
799 default='')
Gabor Mezei24d7cc72024-08-06 15:11:24 +0200800 parser_set_all = self.subparsers.add_parser('set-all',
801 help="""Uncomment all #define
802 whose name contains a match for
803 REGEX.""")
Gilles Peskine8e90cf42021-05-27 22:12:57 +0200804 parser_set_all.add_argument('regexs', metavar='REGEX', nargs='*')
Gabor Mezei24d7cc72024-08-06 15:11:24 +0200805 parser_unset = self.subparsers.add_parser('unset',
806 help="""Comment out the #define
807 for SYMBOL. Do nothing if none
808 is present.""")
Gilles Peskineb4063892019-07-27 21:36:44 +0200809 parser_unset.add_argument('symbol', metavar='SYMBOL')
Gabor Mezei24d7cc72024-08-06 15:11:24 +0200810 parser_unset_all = self.subparsers.add_parser('unset-all',
811 help="""Comment out all #define
812 whose name contains a match for
813 REGEX.""")
Gilles Peskine8e90cf42021-05-27 22:12:57 +0200814 parser_unset_all.add_argument('regexs', metavar='REGEX', nargs='*')
Gilles Peskineb4063892019-07-27 21:36:44 +0200815
Gabor Mezei24d7cc72024-08-06 15:11:24 +0200816 def custom_parser_options(self):
817 """Adds custom options for the parser. Designed for overridden by descendant."""
818 pass
819
820 def main(self):
821 """Common main fuction for config manipulation tool."""
822
823 if self.parser_args.command is None:
824 self.parser.print_help()
825 return 1
826 if self.parser_args.command == 'get':
827 if self.parser_args.symbol in self.config:
828 value = self.config[self.parser_args.symbol]
829 if value:
830 sys.stdout.write(value + '\n')
831 return 0 if self.parser_args.symbol in self.config else 1
832 elif self.parser_args.command == 'set':
833 if not self.parser_args.force and self.parser_args.symbol not in self.config.settings:
834 sys.stderr.write(
835 "A #define for the symbol {} was not found in {}\n"
836 .format(self.parser_args.symbol,
837 self.config.filename(self.parser_args.symbol)))
838 return 1
839 self.config.set(self.parser_args.symbol, value=self.parser_args.value)
840 elif self.parser_args.command == 'set-all':
841 self.config.change_matching(self.parser_args.regexs, True)
842 elif self.parser_args.command == 'unset':
843 self.config.unset(self.parser_args.symbol)
844 elif self.parser_args.command == 'unset-all':
845 self.config.change_matching(self.parser_args.regexs, False)
846 else:
847 self.config.adapt(self.parser_args.adapter)
848 self.config.write(self.parser_args.write)
849
850 return 0
851
852
853class MbedTLSConfigTool(ConfigTool):
854 """Command line mbedtls_config.h and crypto_config.h manipulation tool."""
855
856 def __init__(self):
857 super().__init__(MbedTLSConfigFile)
858 self.config = CombinedConfig(MbedTLSConfigFile(self.parser_args.file),
859 CryptoConfigFile(self.parser_args.cryptofile))
860
861 def custom_parser_options(self):
862 """Adds MbedTLS specific options for the parser."""
863
864 self.parser.add_argument('--cryptofile', '-c',
865 help="""Crypto file to read (and modify if requested).
866 Default: {}.
867 """.format(CryptoConfigFile.default_path))
868
Gilles Peskine53d41ae2019-07-27 23:31:53 +0200869 add_adapter('baremetal', baremetal_adapter,
870 """Like full, but exclude features that require platform
871 features such as file input-output.""")
Gilles Peskine120f29d2021-09-01 19:51:19 +0200872 add_adapter('baremetal_size', baremetal_size_adapter,
873 """Like baremetal, but exclude debugging features.
874 Useful for code size measurements.""")
Gilles Peskine53d41ae2019-07-27 23:31:53 +0200875 add_adapter('full', full_adapter,
876 """Uncomment most features.
877 Exclude alternative implementations and platform support
878 options, as well as some options that are awkward to test.
879 """)
Gilles Peskine30de2e82020-04-20 21:39:22 +0200880 add_adapter('full_no_deprecated', no_deprecated_adapter(full_adapter),
Gilles Peskinebe1d6092020-04-12 14:17:16 +0200881 """Uncomment most non-deprecated features.
882 Like "full", but without deprecated features.
883 """)
Paul Elliottfb81f772023-10-18 17:44:59 +0100884 add_adapter('full_no_platform', no_platform_adapter(full_adapter),
885 """Uncomment most non-platform features.
886 Like "full", but without platform features.
887 """)
Gilles Peskineb4063892019-07-27 21:36:44 +0200888 add_adapter('realfull', realfull_adapter,
Gilles Peskine53d41ae2019-07-27 23:31:53 +0200889 """Uncomment all boolean #defines.
890 Suitable for generating documentation, but not for building.""")
Gilles Peskine31987c62020-01-31 14:23:30 +0100891 add_adapter('crypto', crypto_adapter(None),
892 """Only include crypto features. Exclude X.509 and TLS.""")
893 add_adapter('crypto_baremetal', crypto_adapter(baremetal_adapter),
894 """Like baremetal, but with only crypto features,
895 excluding X.509 and TLS.""")
896 add_adapter('crypto_full', crypto_adapter(full_adapter),
897 """Like full, but with only crypto features,
898 excluding X.509 and TLS.""")
Gilles Peskineb4063892019-07-27 21:36:44 +0200899
Gilles Peskineb4063892019-07-27 21:36:44 +0200900
Gabor Mezei24d7cc72024-08-06 15:11:24 +0200901if __name__ == '__main__':
902 sys.exit(MbedTLSConfigTool().main())