blob: 77a09ad9c50539599a4ee5c31f983ab8d8e1116a [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.
Gabor Mezeid53080d2024-08-27 14:06:54 +020029 * configfile: the file the settings is defined
Gilles Peskineb4063892019-07-27 21:36:44 +020030 """
Gabor Mezei92065ed2024-06-07 13:47:59 +020031 # pylint: disable=too-few-public-methods, too-many-arguments
Gabor Mezeid53080d2024-08-27 14:06:54 +020032 def __init__(self, configfile, active, name, value='', section=None):
Gilles Peskineb4063892019-07-27 21:36:44 +020033 self.active = active
34 self.name = name
35 self.value = value
Gilles Peskine53d41ae2019-07-27 23:31:53 +020036 self.section = section
Gabor Mezei3678dee2024-06-04 19:58:43 +020037 self.configfile = configfile
Gilles Peskineb4063892019-07-27 21:36:44 +020038
39class Config:
Gabor Mezei9f2b8172024-08-06 12:02:18 +020040 """Representation of the Mbed TLS and PSA configuration.
Gilles Peskineb4063892019-07-27 21:36:44 +020041
42 In the documentation of this class, a symbol is said to be *active*
43 if there is a #define for it that is not commented out, and *known*
44 if there is a #define for it whether commented out or not.
45
46 This class supports the following protocols:
Gilles Peskinec190c902019-08-01 23:31:05 +020047 * `name in config` is `True` if the symbol `name` is active, `False`
48 otherwise (whether `name` is inactive or not known).
49 * `config[name]` is the value of the macro `name`. If `name` is inactive,
50 raise `KeyError` (even if `name` is known).
Gilles Peskineb4063892019-07-27 21:36:44 +020051 * `config[name] = value` sets the value associated to `name`. `name`
52 must be known, but does not need to be set. This does not cause
53 name to become set.
54 """
55
Gabor Mezeiee521b62024-06-07 13:50:41 +020056 def __init__(self):
Gilles Peskineb4063892019-07-27 21:36:44 +020057 self.settings = {}
Gabor Mezeid53080d2024-08-27 14:06:54 +020058 self.configfiles = []
Gilles Peskineb4063892019-07-27 21:36:44 +020059
60 def __contains__(self, name):
61 """True if the given symbol is active (i.e. set).
62
63 False if the given symbol is not set, even if a definition
64 is present but commented out.
65 """
66 return name in self.settings and self.settings[name].active
67
68 def all(self, *names):
69 """True if all the elements of names are active (i.e. set)."""
Gabor Mezeidaf807f2024-08-14 11:33:46 +020070 return all(name in self for name in names)
Gilles Peskineb4063892019-07-27 21:36:44 +020071
72 def any(self, *names):
73 """True if at least one symbol in names are active (i.e. set)."""
Gabor Mezeidaf807f2024-08-14 11:33:46 +020074 return any(name in self for name in names)
Gilles Peskineb4063892019-07-27 21:36:44 +020075
76 def known(self, name):
77 """True if a #define for name is present, whether it's commented out or not."""
78 return name in self.settings
79
80 def __getitem__(self, name):
81 """Get the value of name, i.e. what the preprocessor symbol expands to.
82
83 If name is not known, raise KeyError. name does not need to be active.
84 """
85 return self.settings[name].value
86
87 def get(self, name, default=None):
88 """Get the value of name. If name is inactive (not set), return default.
89
90 If a #define for name is present and not commented out, return
91 its expansion, even if this is the empty string.
92
93 If a #define for name is present but commented out, return default.
94 """
95 if name in self.settings:
96 return self.settings[name].value
97 else:
98 return default
99
100 def __setitem__(self, name, value):
101 """If name is known, set its value.
102
103 If name is not known, raise KeyError.
104 """
Gabor Mezeic659c1b2024-08-06 17:37:55 +0200105 setting = self.settings[name]
Gabor Mezeid53080d2024-08-27 14:06:54 +0200106 if setting != value:
Gabor Mezeic659c1b2024-08-06 17:37:55 +0200107 setting.configfile.modified = True
Gilles Peskineb4063892019-07-27 21:36:44 +0200108
Gabor Mezeic659c1b2024-08-06 17:37:55 +0200109 setting.value = value
110
Gabor Mezeid53080d2024-08-27 14:06:54 +0200111 def set(self, name, value=None):
Gilles Peskineb4063892019-07-27 21:36:44 +0200112 """Set name to the given value and make it active.
113
114 If value is None and name is already known, don't change its value.
Gabor Mezeic659c1b2024-08-06 17:37:55 +0200115 If value is None and name is not known, set its value.
Gilles Peskineb4063892019-07-27 21:36:44 +0200116 """
117 if name in self.settings:
Gabor Mezeic659c1b2024-08-06 17:37:55 +0200118 setting = self.settings[name]
Gabor Mezeid53080d2024-08-27 14:06:54 +0200119 if setting.value != value or not setting.active:
Gabor Mezeic659c1b2024-08-06 17:37:55 +0200120 setting.configfile.modified = True
Gilles Peskineb4063892019-07-27 21:36:44 +0200121 if value is not None:
Gabor Mezeic659c1b2024-08-06 17:37:55 +0200122 setting.value = value
123 setting.active = True
Gilles Peskineb4063892019-07-27 21:36:44 +0200124 else:
Gabor Mezeid53080d2024-08-27 14:06:54 +0200125 configfile = self._get_configfile(name)
126 self.settings[name] = Setting(configfile, True, name, value=value)
127 configfile.modified = True
Gilles Peskineb4063892019-07-27 21:36:44 +0200128
129 def unset(self, name):
130 """Make name unset (inactive).
131
Gilles Peskine55cc4db2019-08-01 23:13:23 +0200132 name remains known if it was known before.
Gilles Peskineb4063892019-07-27 21:36:44 +0200133 """
Gilles Peskine55cc4db2019-08-01 23:13:23 +0200134 if name not in self.settings:
135 return
Gabor Mezeic5ff33c2024-06-28 17:46:44 +0200136
137 setting = self.settings[name]
138 # Check if modifying the config file
Gabor Mezeid53080d2024-08-27 14:06:54 +0200139 if setting.active:
Gabor Mezeic5ff33c2024-06-28 17:46:44 +0200140 setting.configfile.modified = True
141
142 setting.active = False
Gilles Peskineb4063892019-07-27 21:36:44 +0200143
144 def adapt(self, adapter):
145 """Run adapter on each known symbol and (de)activate it accordingly.
146
147 `adapter` must be a function that returns a boolean. It is called as
Gilles Peskine53d41ae2019-07-27 23:31:53 +0200148 `adapter(name, active, section)` for each setting, where `active` is
149 `True` if `name` is set and `False` if `name` is known but unset,
150 and `section` is the name of the section containing `name`. If
Gilles Peskineb4063892019-07-27 21:36:44 +0200151 `adapter` returns `True`, then set `name` (i.e. make it active),
152 otherwise unset `name` (i.e. make it known but inactive).
153 """
154 for setting in self.settings.values():
Gabor Mezeic5ff33c2024-06-28 17:46:44 +0200155 is_active = setting.active
Gilles Peskine53d41ae2019-07-27 23:31:53 +0200156 setting.active = adapter(setting.name, setting.active,
157 setting.section)
Gabor Mezeic5ff33c2024-06-28 17:46:44 +0200158 # Check if modifying the config file
Gabor Mezeid53080d2024-08-27 14:06:54 +0200159 if setting.active != is_active:
Gabor Mezeic5ff33c2024-06-28 17:46:44 +0200160 setting.configfile.modified = True
Gilles Peskineb4063892019-07-27 21:36:44 +0200161
Gilles Peskine8e90cf42021-05-27 22:12:57 +0200162 def change_matching(self, regexs, enable):
163 """Change all symbols matching one of the regexs to the desired state."""
164 if not regexs:
165 return
166 regex = re.compile('|'.join(regexs))
167 for setting in self.settings.values():
168 if regex.search(setting.name):
Gabor Mezeic5ff33c2024-06-28 17:46:44 +0200169 # Check if modifying the config file
Gabor Mezeid53080d2024-08-27 14:06:54 +0200170 if setting.active != enable:
Gabor Mezeic5ff33c2024-06-28 17:46:44 +0200171 setting.configfile.modified = True
Gilles Peskine8e90cf42021-05-27 22:12:57 +0200172 setting.active = enable
173
Gabor Mezeid53080d2024-08-27 14:06:54 +0200174 def _get_configfile(self, name=None):
175 """Find a config for a setting name.
176
177 If more then one configfile is used this function must be overridden.
178 """
179
180 if name and name in self.settings:
181 return self.get(name).configfile
182 return self.configfiles[0]
183
184 def write(self, filename=None):
185 """Write the whole configuration to the file it was read from.
186
187 If filename is specified, write to this file instead.
188 """
189
190 for configfile in self.configfiles:
191 configfile.write(self.settings, filename)
192
193 def filename(self, name=None):
194 """Get the name of the config file."""
195
196 return self._get_configfile(name).filename
197
Gilles Peskine53d41ae2019-07-27 23:31:53 +0200198def is_full_section(section):
Gabor Mezeide6e1922024-06-28 17:10:50 +0200199 """Is this section affected by "config.py full" and friends?
200
201 In a config file where the sections are not used the whole config file
202 is an empty section (with value None) and the whole file is affected.
203 """
Gabor Mezei3678dee2024-06-04 19:58:43 +0200204 return section is None or section.endswith('support') or section.endswith('modules')
Gilles Peskine53d41ae2019-07-27 23:31:53 +0200205
206def realfull_adapter(_name, active, section):
Gilles Peskineba4162a2022-04-11 17:04:38 +0200207 """Activate all symbols found in the global and boolean feature sections.
208
209 This is intended for building the documentation, including the
210 documentation of settings that are activated by defining an optional
211 preprocessor macro.
212
213 Do not activate definitions in the section containing symbols that are
214 supposed to be defined and documented in their own module.
215 """
216 if section == 'Module configuration options':
Gilles Peskine53d41ae2019-07-27 23:31:53 +0200217 return active
Gilles Peskineb4063892019-07-27 21:36:44 +0200218 return True
219
Gabor Mezei542fd382024-06-10 14:07:42 +0200220PSA_UNSUPPORTED_FEATURE = frozenset([
Gabor Mezei3678dee2024-06-04 19:58:43 +0200221 'PSA_WANT_ALG_CBC_MAC',
222 'PSA_WANT_ALG_XTS',
223 'PSA_WANT_KEY_TYPE_RSA_KEY_PAIR_DERIVE',
224 'PSA_WANT_KEY_TYPE_DH_KEY_PAIR_DERIVE'
225])
226
Gabor Mezei542fd382024-06-10 14:07:42 +0200227PSA_DEPRECATED_FEATURE = frozenset([
Gabor Mezei3678dee2024-06-04 19:58:43 +0200228 'PSA_WANT_KEY_TYPE_ECC_KEY_PAIR',
229 'PSA_WANT_KEY_TYPE_RSA_KEY_PAIR'
230])
231
Gabor Mezei542fd382024-06-10 14:07:42 +0200232PSA_UNSTABLE_FEATURE = frozenset([
Gabor Mezei3678dee2024-06-04 19:58:43 +0200233 'PSA_WANT_ECC_SECP_K1_224'
234])
235
Gabor Mezei9b0f9e72024-06-26 18:08:17 +0200236EXCLUDE_FROM_CRYPTO = PSA_UNSUPPORTED_FEATURE | \
237 PSA_DEPRECATED_FEATURE | \
238 PSA_UNSTABLE_FEATURE
Gabor Mezei542fd382024-06-10 14:07:42 +0200239
Gilles Peskinecfffc282020-04-12 13:55:45 +0200240# The goal of the full configuration is to have everything that can be tested
241# together. This includes deprecated or insecure options. It excludes:
242# * Options that require additional build dependencies or unusual hardware.
243# * Options that make testing less effective.
Gilles Peskinec9d04332020-04-16 20:50:17 +0200244# * Options that are incompatible with other options, or more generally that
245# interact with other parts of the code in such a way that a bulk enabling
246# is not a good way to test them.
Gilles Peskinecfffc282020-04-12 13:55:45 +0200247# * Options that remove features.
Gilles Peskinebbaa2b72020-04-12 13:33:57 +0200248EXCLUDE_FROM_FULL = frozenset([
Gilles Peskinecfffc282020-04-12 13:55:45 +0200249 #pylint: disable=line-too-long
Yanray Wanga8704672023-04-20 17:16:48 +0800250 'MBEDTLS_AES_ONLY_128_BIT_KEY_LENGTH', # interacts with CTR_DRBG_128_BIT_KEY
Gilles Peskinea8861e02023-09-05 20:20:51 +0200251 'MBEDTLS_AES_USE_HARDWARE_ONLY', # hardware dependency
Yanray Wang42be1ba2023-11-23 14:28:47 +0800252 'MBEDTLS_BLOCK_CIPHER_NO_DECRYPT', # incompatible with ECB in PSA, CBC/XTS/NIST_KW/DES
Gilles Peskinec9d04332020-04-16 20:50:17 +0200253 'MBEDTLS_CTR_DRBG_USE_128_BIT_KEY', # interacts with ENTROPY_FORCE_SHA256
Gilles Peskinecfffc282020-04-12 13:55:45 +0200254 'MBEDTLS_DEPRECATED_REMOVED', # conflicts with deprecated options
Gilles Peskine90581ee2020-04-12 14:02:47 +0200255 'MBEDTLS_DEPRECATED_WARNING', # conflicts with deprecated options
Gilles Peskinec9d04332020-04-16 20:50:17 +0200256 'MBEDTLS_ECDH_VARIANT_EVEREST_ENABLED', # influences the use of ECDH in TLS
Janos Follath5b7c38f2023-08-01 08:51:12 +0100257 'MBEDTLS_ECP_WITH_MPI_UINT', # disables the default ECP and is experimental
Gilles Peskinec9d04332020-04-16 20:50:17 +0200258 'MBEDTLS_ENTROPY_FORCE_SHA256', # interacts with CTR_DRBG_128_BIT_KEY
Gilles Peskinecfffc282020-04-12 13:55:45 +0200259 'MBEDTLS_HAVE_SSE2', # hardware dependency
260 'MBEDTLS_MEMORY_BACKTRACE', # depends on MEMORY_BUFFER_ALLOC_C
261 'MBEDTLS_MEMORY_BUFFER_ALLOC_C', # makes sanitizers (e.g. ASan) less effective
262 'MBEDTLS_MEMORY_DEBUG', # depends on MEMORY_BUFFER_ALLOC_C
Gilles Peskinec9d04332020-04-16 20:50:17 +0200263 'MBEDTLS_NO_64BIT_MULTIPLICATION', # influences anything that uses bignum
Gilles Peskinecfffc282020-04-12 13:55:45 +0200264 'MBEDTLS_NO_DEFAULT_ENTROPY_SOURCES', # removes a feature
265 'MBEDTLS_NO_PLATFORM_ENTROPY', # removes a feature
Gilles Peskinec9d04332020-04-16 20:50:17 +0200266 'MBEDTLS_NO_UDBL_DIVISION', # influences anything that uses bignum
Gilles Peskineefaee9a2023-09-20 20:49:47 +0200267 'MBEDTLS_PSA_P256M_DRIVER_ENABLED', # influences SECP256R1 KeyGen/ECDH/ECDSA
Gilles Peskinecfffc282020-04-12 13:55:45 +0200268 'MBEDTLS_PLATFORM_NO_STD_FUNCTIONS', # removes a feature
David Horstmann6f8c95b2024-03-14 14:52:45 +0000269 'MBEDTLS_PSA_ASSUME_EXCLUSIVE_BUFFERS', # removes a feature
Gilles Peskinef08b3f82020-11-13 17:36:48 +0100270 'MBEDTLS_PSA_CRYPTO_EXTERNAL_RNG', # behavior change + build dependency
Ronald Cronc3623db2020-10-29 10:51:32 +0100271 'MBEDTLS_PSA_CRYPTO_KEY_ID_ENCODES_OWNER', # incompatible with USE_PSA_CRYPTO
Gilles Peskinecfffc282020-04-12 13:55:45 +0200272 'MBEDTLS_PSA_CRYPTO_SPM', # platform dependency (PSA SPM)
Gilles Peskinea08def92023-04-28 21:01:49 +0200273 'MBEDTLS_PSA_INJECT_ENTROPY', # conflicts with platform entropy sources
Gilles Peskinec9d04332020-04-16 20:50:17 +0200274 'MBEDTLS_RSA_NO_CRT', # influences the use of RSA in X.509 and TLS
Tom Cosgrove87fbfb52022-03-15 10:51:52 +0000275 'MBEDTLS_SHA256_USE_A64_CRYPTO_ONLY', # interacts with *_USE_A64_CRYPTO_IF_PRESENT
Dave Rodgman9be3cf02023-10-11 14:47:55 +0100276 'MBEDTLS_SHA256_USE_ARMV8_A_CRYPTO_ONLY', # interacts with *_USE_ARMV8_A_CRYPTO_IF_PRESENT
Tom Cosgrove87fbfb52022-03-15 10:51:52 +0000277 'MBEDTLS_SHA512_USE_A64_CRYPTO_ONLY', # interacts with *_USE_A64_CRYPTO_IF_PRESENT
Dave Rodgman7cb635a2023-10-12 16:14:51 +0100278 'MBEDTLS_SHA256_USE_A64_CRYPTO_IF_PRESENT', # setting *_USE_ARMV8_A_CRYPTO is sufficient
Manuel Pégourié-Gonnard6240def2020-07-10 09:35:54 +0200279 'MBEDTLS_TEST_CONSTANT_FLOW_MEMSAN', # build dependency (clang+memsan)
Manuel Pégourié-Gonnard73afa372020-08-19 10:27:38 +0200280 'MBEDTLS_TEST_CONSTANT_FLOW_VALGRIND', # build dependency (valgrind headers)
Hanno Beckere1113562019-06-12 13:59:14 +0100281 'MBEDTLS_X509_REMOVE_INFO', # removes a feature
Gabor Mezei542fd382024-06-10 14:07:42 +0200282 *PSA_UNSUPPORTED_FEATURE,
283 *PSA_DEPRECATED_FEATURE,
284 *PSA_UNSTABLE_FEATURE
Gilles Peskinebbaa2b72020-04-12 13:33:57 +0200285])
286
Gilles Peskine32e889d2020-04-12 23:43:28 +0200287def is_seamless_alt(name):
Gilles Peskinec34faba2020-04-20 15:44:14 +0200288 """Whether the xxx_ALT symbol should be included in the full configuration.
Gilles Peskine32e889d2020-04-12 23:43:28 +0200289
Gilles Peskinec34faba2020-04-20 15:44:14 +0200290 Include alternative implementations of platform functions, which are
Gilles Peskine32e889d2020-04-12 23:43:28 +0200291 configurable function pointers that default to the built-in function.
292 This way we test that the function pointers exist and build correctly
293 without changing the behavior, and tests can verify that the function
294 pointers are used by modifying those pointers.
295
296 Exclude alternative implementations of library functions since they require
297 an implementation of the relevant functions and an xxx_alt.h header.
298 """
Gilles Peskinea8861e02023-09-05 20:20:51 +0200299 if name in (
300 'MBEDTLS_PLATFORM_GMTIME_R_ALT',
301 'MBEDTLS_PLATFORM_SETUP_TEARDOWN_ALT',
302 'MBEDTLS_PLATFORM_MS_TIME_ALT',
303 'MBEDTLS_PLATFORM_ZEROIZE_ALT',
304 ):
Gilles Peskinec34faba2020-04-20 15:44:14 +0200305 # Similar to non-platform xxx_ALT, requires platform_alt.h
306 return False
Gilles Peskine32e889d2020-04-12 23:43:28 +0200307 return name.startswith('MBEDTLS_PLATFORM_')
308
Gilles Peskine53d41ae2019-07-27 23:31:53 +0200309def include_in_full(name):
310 """Rules for symbols in the "full" configuration."""
Gabor Mezei542fd382024-06-10 14:07:42 +0200311 if name in EXCLUDE_FROM_FULL:
Gilles Peskine53d41ae2019-07-27 23:31:53 +0200312 return False
313 if name.endswith('_ALT'):
Gilles Peskine32e889d2020-04-12 23:43:28 +0200314 return is_seamless_alt(name)
Gilles Peskine53d41ae2019-07-27 23:31:53 +0200315 return True
316
317def full_adapter(name, active, section):
318 """Config adapter for "full"."""
319 if not is_full_section(section):
320 return active
321 return include_in_full(name)
322
Gilles Peskinecfffc282020-04-12 13:55:45 +0200323# The baremetal configuration excludes options that require a library or
324# operating system feature that is typically not present on bare metal
325# systems. Features that are excluded from "full" won't be in "baremetal"
326# either (unless explicitly turned on in baremetal_adapter) so they don't
327# need to be repeated here.
Gilles Peskinebbaa2b72020-04-12 13:33:57 +0200328EXCLUDE_FROM_BAREMETAL = frozenset([
Gilles Peskinecfffc282020-04-12 13:55:45 +0200329 #pylint: disable=line-too-long
Gilles Peskine98f8f952020-04-20 15:38:39 +0200330 'MBEDTLS_ENTROPY_NV_SEED', # requires a filesystem and FS_IO or alternate NV seed hooks
Gilles Peskinecfffc282020-04-12 13:55:45 +0200331 'MBEDTLS_FS_IO', # requires a filesystem
Gilles Peskinecfffc282020-04-12 13:55:45 +0200332 'MBEDTLS_HAVE_TIME', # requires a clock
333 'MBEDTLS_HAVE_TIME_DATE', # requires a clock
334 'MBEDTLS_NET_C', # requires POSIX-like networking
335 'MBEDTLS_PLATFORM_FPRINTF_ALT', # requires FILE* from stdio.h
Gilles Peskine98f8f952020-04-20 15:38:39 +0200336 'MBEDTLS_PLATFORM_NV_SEED_ALT', # requires a filesystem and ENTROPY_NV_SEED
337 'MBEDTLS_PLATFORM_TIME_ALT', # requires a clock and HAVE_TIME
338 'MBEDTLS_PSA_CRYPTO_SE_C', # requires a filesystem and PSA_CRYPTO_STORAGE_C
Gilles Peskinecfffc282020-04-12 13:55:45 +0200339 'MBEDTLS_PSA_CRYPTO_STORAGE_C', # requires a filesystem
340 'MBEDTLS_PSA_ITS_FILE_C', # requires a filesystem
341 'MBEDTLS_THREADING_C', # requires a threading interface
342 'MBEDTLS_THREADING_PTHREAD', # requires pthread
343 'MBEDTLS_TIMING_C', # requires a clock
Dave Rodgman9be3cf02023-10-11 14:47:55 +0100344 'MBEDTLS_SHA256_USE_A64_CRYPTO_IF_PRESENT', # requires an OS for runtime-detection
Dave Rodgman5b89c552023-10-10 14:59:02 +0100345 'MBEDTLS_SHA256_USE_ARMV8_A_CRYPTO_IF_PRESENT', # requires an OS for runtime-detection
Dave Rodgmanbe7915a2023-10-11 10:46:38 +0100346 'MBEDTLS_SHA512_USE_A64_CRYPTO_IF_PRESENT', # requires an OS for runtime-detection
Gilles Peskinebbaa2b72020-04-12 13:33:57 +0200347])
348
Gilles Peskine53d41ae2019-07-27 23:31:53 +0200349def keep_in_baremetal(name):
350 """Rules for symbols in the "baremetal" configuration."""
Gilles Peskinebbaa2b72020-04-12 13:33:57 +0200351 if name in EXCLUDE_FROM_BAREMETAL:
Gilles Peskine53d41ae2019-07-27 23:31:53 +0200352 return False
353 return True
354
355def baremetal_adapter(name, active, section):
356 """Config adapter for "baremetal"."""
357 if not is_full_section(section):
358 return active
359 if name == 'MBEDTLS_NO_PLATFORM_ENTROPY':
Gilles Peskinecfffc282020-04-12 13:55:45 +0200360 # No OS-provided entropy source
Gilles Peskine53d41ae2019-07-27 23:31:53 +0200361 return True
362 return include_in_full(name) and keep_in_baremetal(name)
363
Gilles Peskine120f29d2021-09-01 19:51:19 +0200364# This set contains options that are mostly for debugging or test purposes,
365# and therefore should be excluded when doing code size measurements.
366# Options that are their own module (such as MBEDTLS_ERROR_C) are not listed
367# and therefore will be included when doing code size measurements.
368EXCLUDE_FOR_SIZE = frozenset([
369 'MBEDTLS_DEBUG_C', # large code size increase in TLS
370 'MBEDTLS_SELF_TEST', # increases the size of many modules
371 'MBEDTLS_TEST_HOOKS', # only useful with the hosted test framework, increases code size
372])
373
374def baremetal_size_adapter(name, active, section):
375 if name in EXCLUDE_FOR_SIZE:
376 return False
377 return baremetal_adapter(name, active, section)
378
Gilles Peskine31987c62020-01-31 14:23:30 +0100379def include_in_crypto(name):
380 """Rules for symbols in a crypto configuration."""
381 if name.startswith('MBEDTLS_X509_') or \
382 name.startswith('MBEDTLS_SSL_') or \
383 name.startswith('MBEDTLS_KEY_EXCHANGE_'):
384 return False
385 if name in [
Gilles Peskinecfffc282020-04-12 13:55:45 +0200386 'MBEDTLS_DEBUG_C', # part of libmbedtls
387 'MBEDTLS_NET_C', # part of libmbedtls
Nayna Jainc9deb182020-11-16 19:03:12 +0000388 'MBEDTLS_PKCS7_C', # part of libmbedx509
Gilles Peskine31987c62020-01-31 14:23:30 +0100389 ]:
390 return False
Gabor Mezei542fd382024-06-10 14:07:42 +0200391 if name in EXCLUDE_FROM_CRYPTO:
392 return False
Gilles Peskine31987c62020-01-31 14:23:30 +0100393 return True
394
395def crypto_adapter(adapter):
396 """Modify an adapter to disable non-crypto symbols.
397
398 ``crypto_adapter(adapter)(name, active, section)`` is like
399 ``adapter(name, active, section)``, but unsets all X.509 and TLS symbols.
400 """
401 def continuation(name, active, section):
402 if not include_in_crypto(name):
403 return False
404 if adapter is None:
405 return active
406 return adapter(name, active, section)
407 return continuation
408
Gilles Peskineed5c21d2022-06-27 23:02:09 +0200409DEPRECATED = frozenset([
410 'MBEDTLS_PSA_CRYPTO_SE_C',
Gabor Mezei542fd382024-06-10 14:07:42 +0200411 *PSA_DEPRECATED_FEATURE
Gilles Peskineed5c21d2022-06-27 23:02:09 +0200412])
Gilles Peskine30de2e82020-04-20 21:39:22 +0200413def no_deprecated_adapter(adapter):
Gilles Peskinebe1d6092020-04-12 14:17:16 +0200414 """Modify an adapter to disable deprecated symbols.
415
Gilles Peskine30de2e82020-04-20 21:39:22 +0200416 ``no_deprecated_adapter(adapter)(name, active, section)`` is like
Gilles Peskinebe1d6092020-04-12 14:17:16 +0200417 ``adapter(name, active, section)``, but unsets all deprecated symbols
418 and sets ``MBEDTLS_DEPRECATED_REMOVED``.
419 """
420 def continuation(name, active, section):
421 if name == 'MBEDTLS_DEPRECATED_REMOVED':
422 return True
Gilles Peskineed5c21d2022-06-27 23:02:09 +0200423 if name in DEPRECATED:
424 return False
Gilles Peskinebe1d6092020-04-12 14:17:16 +0200425 if adapter is None:
426 return active
427 return adapter(name, active, section)
428 return continuation
429
Paul Elliottfb81f772023-10-18 17:44:59 +0100430def no_platform_adapter(adapter):
431 """Modify an adapter to disable platform symbols.
432
433 ``no_platform_adapter(adapter)(name, active, section)`` is like
434 ``adapter(name, active, section)``, but unsets all platform symbols other
435 ``than MBEDTLS_PLATFORM_C.
436 """
437 def continuation(name, active, section):
438 # Allow MBEDTLS_PLATFORM_C but remove all other platform symbols.
439 if name.startswith('MBEDTLS_PLATFORM_') and name != 'MBEDTLS_PLATFORM_C':
440 return False
441 if adapter is None:
442 return active
443 return adapter(name, active, section)
444 return continuation
445
Gabor Mezei3678dee2024-06-04 19:58:43 +0200446class ConfigFile(metaclass=ABCMeta):
Gabor Mezei62a9bd02024-06-07 13:44:40 +0200447 """Representation of a configuration file."""
448
Gabor Mezei93a6d1f2024-06-26 18:01:09 +0200449 def __init__(self, default_path, name, filename=None):
Gabor Mezei62a9bd02024-06-07 13:44:40 +0200450 """Check if the config file exists."""
Gilles Peskineb4063892019-07-27 21:36:44 +0200451 if filename is None:
Gabor Mezei3678dee2024-06-04 19:58:43 +0200452 for candidate in default_path:
Gilles Peskinece674a92020-03-24 15:37:00 +0100453 if os.path.lexists(candidate):
454 filename = candidate
Gilles Peskine208e4ec2019-07-29 23:43:20 +0200455 break
Gilles Peskinece674a92020-03-24 15:37:00 +0100456 else:
Gabor Mezei8d72ac62024-06-28 17:18:37 +0200457 raise FileNotFoundError(f'{name} configuration file not found: '
458 f'{filename if filename else default_path}')
Gilles Peskineb4063892019-07-27 21:36:44 +0200459
Gabor Mezei3678dee2024-06-04 19:58:43 +0200460 self.filename = filename
461 self.templates = []
462 self.current_section = None
463 self.inclusion_guard = None
Gabor Mezei8a64d8e2024-06-10 15:23:43 +0200464 self.modified = False
Gilles Peskineb4063892019-07-27 21:36:44 +0200465
466 _define_line_regexp = (r'(?P<indentation>\s*)' +
467 r'(?P<commented_out>(//\s*)?)' +
468 r'(?P<define>#\s*define\s+)' +
469 r'(?P<name>\w+)' +
470 r'(?P<arguments>(?:\((?:\w|\s|,)*\))?)' +
471 r'(?P<separator>\s*)' +
472 r'(?P<value>.*)')
Gilles Peskine9ba9c212024-05-23 15:03:43 +0200473 _ifndef_line_regexp = r'#ifndef (?P<inclusion_guard>\w+)'
Gilles Peskine53d41ae2019-07-27 23:31:53 +0200474 _section_line_regexp = (r'\s*/?\*+\s*[\\@]name\s+SECTION:\s*' +
475 r'(?P<section>.*)[ */]*')
476 _config_line_regexp = re.compile(r'|'.join([_define_line_regexp,
Gilles Peskine9ba9c212024-05-23 15:03:43 +0200477 _ifndef_line_regexp,
Gilles Peskine53d41ae2019-07-27 23:31:53 +0200478 _section_line_regexp]))
Gilles Peskineb4063892019-07-27 21:36:44 +0200479 def _parse_line(self, line):
Gabor Mezei62a9bd02024-06-07 13:44:40 +0200480 """Parse a line in the config file, save the templates representing the lines
481 and return the corresponding setting element.
482 """
Gabor Mezei4706fe72024-07-08 17:00:55 +0200483
Gilles Peskineb4063892019-07-27 21:36:44 +0200484 line = line.rstrip('\r\n')
Gilles Peskine53d41ae2019-07-27 23:31:53 +0200485 m = re.match(self._config_line_regexp, line)
486 if m is None:
Gabor Mezei3678dee2024-06-04 19:58:43 +0200487 self.templates.append(line)
488 return None
Gilles Peskine53d41ae2019-07-27 23:31:53 +0200489 elif m.group('section'):
490 self.current_section = m.group('section')
Gabor Mezei3678dee2024-06-04 19:58:43 +0200491 self.templates.append(line)
492 return None
Gilles Peskine9ba9c212024-05-23 15:03:43 +0200493 elif m.group('inclusion_guard') and self.inclusion_guard is None:
494 self.inclusion_guard = m.group('inclusion_guard')
Gabor Mezei3678dee2024-06-04 19:58:43 +0200495 self.templates.append(line)
496 return None
Gilles Peskine53d41ae2019-07-27 23:31:53 +0200497 else:
Gilles Peskineb4063892019-07-27 21:36:44 +0200498 active = not m.group('commented_out')
499 name = m.group('name')
500 value = m.group('value')
Gilles Peskine9ba9c212024-05-23 15:03:43 +0200501 if name == self.inclusion_guard and value == '':
502 # The file double-inclusion guard is not an option.
Gabor Mezei3678dee2024-06-04 19:58:43 +0200503 self.templates.append(line)
504 return None
Gilles Peskineb4063892019-07-27 21:36:44 +0200505 template = (name,
506 m.group('indentation'),
507 m.group('define') + name +
508 m.group('arguments') + m.group('separator'))
Gabor Mezei3678dee2024-06-04 19:58:43 +0200509 self.templates.append(template)
Gilles Peskineb4063892019-07-27 21:36:44 +0200510
Gabor Mezei3678dee2024-06-04 19:58:43 +0200511 return (active, name, value, self.current_section)
512
513 def parse_file(self):
Gabor Mezei62a9bd02024-06-07 13:44:40 +0200514 """Parse the whole file and return the settings."""
Gabor Mezei4706fe72024-07-08 17:00:55 +0200515
Gabor Mezei3678dee2024-06-04 19:58:43 +0200516 with open(self.filename, 'r', encoding='utf-8') as file:
517 for line in file:
518 setting = self._parse_line(line)
519 if setting is not None:
520 yield setting
521 self.current_section = None
522
Gabor Mezeie7742b32024-06-26 18:04:09 +0200523 #pylint: disable=no-self-use
524 def _format_template(self, setting, indent, middle):
Gabor Mezei4706fe72024-07-08 17:00:55 +0200525 """Build a line for the config file for the given setting.
Gabor Mezeie7742b32024-06-26 18:04:09 +0200526
527 The line has the form "<indent>#define <name> <value>"
528 where <middle> is "#define <name> ".
529 """
Gabor Mezei4706fe72024-07-08 17:00:55 +0200530
Gabor Mezeie7742b32024-06-26 18:04:09 +0200531 value = setting.value
532 if value is None:
533 value = ''
534 # Normally the whitespace to separate the symbol name from the
535 # value is part of middle, and there's no whitespace for a symbol
536 # with no value. But if a symbol has been changed from having a
537 # value to not having one, the whitespace is wrong, so fix it.
538 if value:
539 if middle[-1] not in '\t ':
540 middle += ' '
541 else:
542 middle = middle.rstrip()
543 return ''.join([indent,
544 '' if setting.active else '//',
545 middle,
546 value]).rstrip()
Gabor Mezei3678dee2024-06-04 19:58:43 +0200547
548 def write_to_stream(self, settings, output):
549 """Write the whole configuration to output."""
Gabor Mezei4706fe72024-07-08 17:00:55 +0200550
Gabor Mezei3678dee2024-06-04 19:58:43 +0200551 for template in self.templates:
552 if isinstance(template, str):
553 line = template
554 else:
Gabor Mezeie7742b32024-06-26 18:04:09 +0200555 name, indent, middle = template
556 line = self._format_template(settings[name], indent, middle)
Gabor Mezei3678dee2024-06-04 19:58:43 +0200557 output.write(line + '\n')
558
559 def write(self, settings, filename=None):
560 """Write the whole configuration to the file it was read from.
561
562 If filename is specified, write to this file instead.
563 """
Gabor Mezei4706fe72024-07-08 17:00:55 +0200564
Gabor Mezei3678dee2024-06-04 19:58:43 +0200565 if filename is None:
566 filename = self.filename
Gabor Mezei8a64d8e2024-06-10 15:23:43 +0200567
568 # Not modified so no need to write to the file
569 if not self.modified and filename == self.filename:
570 return
571
Gabor Mezei3678dee2024-06-04 19:58:43 +0200572 with open(filename, 'w', encoding='utf-8') as output:
573 self.write_to_stream(settings, output)
574
Gabor Mezeif77722d2024-06-28 16:49:33 +0200575class MbedTLSConfigFile(ConfigFile):
Gabor Mezei62a9bd02024-06-07 13:44:40 +0200576 """Representation of an MbedTLS configuration file."""
577
Gabor Mezei3678dee2024-06-04 19:58:43 +0200578 _path_in_tree = 'include/mbedtls/mbedtls_config.h'
579 default_path = [_path_in_tree,
580 os.path.join(os.path.dirname(__file__),
581 os.pardir,
582 _path_in_tree),
583 os.path.join(os.path.dirname(os.path.abspath(os.path.dirname(__file__))),
584 _path_in_tree)]
585
586 def __init__(self, filename=None):
Gabor Mezei93a6d1f2024-06-26 18:01:09 +0200587 super().__init__(self.default_path, 'Mbed TLS', filename)
Gabor Mezei3678dee2024-06-04 19:58:43 +0200588 self.current_section = 'header'
589
Gabor Mezei3678dee2024-06-04 19:58:43 +0200590class CryptoConfigFile(ConfigFile):
Gabor Mezei4706fe72024-07-08 17:00:55 +0200591 """Representation of a Crypto configuration file."""
Gabor Mezei62a9bd02024-06-07 13:44:40 +0200592
Gabor Mezei3de65862024-07-08 16:14:10 +0200593 # Temporary, while Mbed TLS does not just rely on the TF-PSA-Crypto
594 # build system to build its crypto library. When it does, the
595 # condition can just be removed.
596 _path_in_tree = 'include/psa/crypto_config.h' \
597 if os.path.isfile('include/psa/crypto_config.h') else \
598 'tf-psa-crypto/include/psa/crypto_config.h'
Gabor Mezei3678dee2024-06-04 19:58:43 +0200599 default_path = [_path_in_tree,
600 os.path.join(os.path.dirname(__file__),
601 os.pardir,
602 _path_in_tree),
603 os.path.join(os.path.dirname(os.path.abspath(os.path.dirname(__file__))),
604 _path_in_tree)]
605
606 def __init__(self, filename=None):
Gabor Mezei93a6d1f2024-06-26 18:01:09 +0200607 super().__init__(self.default_path, 'Crypto', filename)
Gabor Mezei3678dee2024-06-04 19:58:43 +0200608
Gabor Mezeif77722d2024-06-28 16:49:33 +0200609class MbedTLSConfig(Config):
Gabor Mezei62a9bd02024-06-07 13:44:40 +0200610 """Representation of the Mbed TLS configuration.
Gabor Mezei3678dee2024-06-04 19:58:43 +0200611
612 See the documentation of the `Config` class for methods to query
613 and modify the configuration.
614 """
Gabor Mezei4706fe72024-07-08 17:00:55 +0200615
Gabor Mezeiee521b62024-06-07 13:50:41 +0200616 def __init__(self, filename=None):
Gabor Mezei3678dee2024-06-04 19:58:43 +0200617 """Read the Mbed TLS configuration file."""
Gabor Mezei4706fe72024-07-08 17:00:55 +0200618
Gabor Mezei3678dee2024-06-04 19:58:43 +0200619 super().__init__()
Gabor Mezeid53080d2024-08-27 14:06:54 +0200620 configfile = MbedTLSConfigFile(filename)
621 self.configfiles.append(configfile)
622 self.settings.update({name: Setting(configfile, active, name, value, section)
Gabor Mezei92065ed2024-06-07 13:47:59 +0200623 for (active, name, value, section)
Gabor Mezeid53080d2024-08-27 14:06:54 +0200624 in configfile.parse_file()})
Gabor Mezei3678dee2024-06-04 19:58:43 +0200625
626 def set(self, name, value=None):
Gabor Mezei4706fe72024-07-08 17:00:55 +0200627 """Set name to the given value and make it active."""
628
Gabor Mezei3678dee2024-06-04 19:58:43 +0200629 if name not in self.settings:
Gabor Mezeid53080d2024-08-27 14:06:54 +0200630 self._get_configfile().templates.append((name, '', '#define ' + name + ' '))
Gabor Mezeiee521b62024-06-07 13:50:41 +0200631
Gabor Mezei3678dee2024-06-04 19:58:43 +0200632 super().set(name, value)
Gilles Peskineb4063892019-07-27 21:36:44 +0200633
Gabor Mezei3678dee2024-06-04 19:58:43 +0200634class CryptoConfig(Config):
Gabor Mezei62a9bd02024-06-07 13:44:40 +0200635 """Representation of the PSA crypto configuration.
Gabor Mezei3678dee2024-06-04 19:58:43 +0200636
637 See the documentation of the `Config` class for methods to query
638 and modify the configuration.
639 """
Gabor Mezei4706fe72024-07-08 17:00:55 +0200640
Gabor Mezeiee521b62024-06-07 13:50:41 +0200641 def __init__(self, filename=None):
Gabor Mezei3678dee2024-06-04 19:58:43 +0200642 """Read the PSA crypto configuration file."""
Gabor Mezei4706fe72024-07-08 17:00:55 +0200643
Gabor Mezei3678dee2024-06-04 19:58:43 +0200644 super().__init__()
Gabor Mezeid53080d2024-08-27 14:06:54 +0200645 configfile = CryptoConfigFile(filename)
646 self.configfiles.append(configfile)
647 self.settings.update({name: Setting(configfile, active, name, value, section)
Gabor Mezei92065ed2024-06-07 13:47:59 +0200648 for (active, name, value, section)
Gabor Mezeid53080d2024-08-27 14:06:54 +0200649 in configfile.parse_file()})
Gabor Mezei3678dee2024-06-04 19:58:43 +0200650
Gabor Mezeid723b512024-06-07 15:31:52 +0200651 def set(self, name, value='1'):
Gabor Mezei4706fe72024-07-08 17:00:55 +0200652 """Set name to the given value and make it active."""
653
Gabor Mezei542fd382024-06-10 14:07:42 +0200654 if name in PSA_UNSUPPORTED_FEATURE:
Gabor Mezei92065ed2024-06-07 13:47:59 +0200655 raise ValueError(f'Feature is unsupported: \'{name}\'')
Gabor Mezei542fd382024-06-10 14:07:42 +0200656 if name in PSA_UNSTABLE_FEATURE:
Gabor Mezei92065ed2024-06-07 13:47:59 +0200657 raise ValueError(f'Feature is unstable: \'{name}\'')
Gabor Mezei3678dee2024-06-04 19:58:43 +0200658
659 if name not in self.settings:
Gabor Mezeid53080d2024-08-27 14:06:54 +0200660 self._get_configfile().templates.append((name, '', '#define ' + name + ' '))
Gabor Mezeiee521b62024-06-07 13:50:41 +0200661
Gabor Mezei3678dee2024-06-04 19:58:43 +0200662 super().set(name, value)
663
Gabor Mezei33dd2932024-06-28 17:51:58 +0200664class CombinedConfig(Config):
Gabor Mezei62a9bd02024-06-07 13:44:40 +0200665 """Representation of MbedTLS and PSA crypto configuration
666
667 See the documentation of the `Config` class for methods to query
668 and modify the configuration.
669 """
Gabor Mezei3678dee2024-06-04 19:58:43 +0200670
Gabor Mezei3e2a5502024-06-28 17:27:19 +0200671 def __init__(self, *configs):
Gabor Mezeiee521b62024-06-07 13:50:41 +0200672 super().__init__()
Gabor Mezei3e2a5502024-06-28 17:27:19 +0200673 for config in configs:
674 if isinstance(config, MbedTLSConfigFile):
675 self.mbedtls_configfile = config
676 elif isinstance(config, CryptoConfigFile):
677 self.crypto_configfile = config
678 else:
679 raise ValueError(f'Invalid configfile: {config}')
Gabor Mezeid53080d2024-08-27 14:06:54 +0200680 self.configfiles.append(config)
Gabor Mezei3e2a5502024-06-28 17:27:19 +0200681
Gabor Mezeid53080d2024-08-27 14:06:54 +0200682 self.settings.update({name: Setting(configfile, active, name, value, section)
Gabor Mezeiee521b62024-06-07 13:50:41 +0200683 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 Mezeid53080d2024-08-27 14:06:54 +0200687 def _get_configfile(self, name=None):
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
697 def set(self, name, value=None):
Gabor Mezei4706fe72024-07-08 17:00:55 +0200698 """Set name to the given value and make it active."""
699
Gabor Mezeiee521b62024-06-07 13:50:41 +0200700 configfile = self._get_configfile(name)
Gabor Mezei3678dee2024-06-04 19:58:43 +0200701
Gabor Mezeiee521b62024-06-07 13:50:41 +0200702 if configfile == self.crypto_configfile:
Gabor Mezei542fd382024-06-10 14:07:42 +0200703 if name in PSA_UNSUPPORTED_FEATURE:
Gabor Mezeiee521b62024-06-07 13:50:41 +0200704 raise ValueError(f'Feature is unsupported: \'{name}\'')
Gabor Mezei542fd382024-06-10 14:07:42 +0200705 if name in PSA_UNSTABLE_FEATURE:
Gabor Mezeiee521b62024-06-07 13:50:41 +0200706 raise ValueError(f'Feature is unstable: \'{name}\'')
707
Gabor Mezeid723b512024-06-07 15:31:52 +0200708 # The default value in the crypto config is '1'
709 if not value:
710 value = '1'
711
Gabor Mezeic659c1b2024-08-06 17:37:55 +0200712 if name not in self.settings:
Gabor Mezeiee521b62024-06-07 13:50:41 +0200713 configfile.templates.append((name, '', '#define ' + name + ' '))
714
Gabor Mezeid53080d2024-08-27 14:06:54 +0200715 super().set(name, value)
Gabor Mezeiee521b62024-06-07 13:50:41 +0200716
Gabor Mezeidaf807f2024-08-14 11:33:46 +0200717 #pylint: disable=arguments-differ
Gabor Mezei3678dee2024-06-04 19:58:43 +0200718 def write(self, mbedtls_file=None, crypto_file=None):
Gabor Mezei62a9bd02024-06-07 13:44:40 +0200719 """Write the whole configuration to the file it was read from.
720
721 If mbedtls_file or crypto_file is specified, write the specific configuration
722 to the corresponding file instead.
723 """
Gabor Mezei4706fe72024-07-08 17:00:55 +0200724
Gabor Mezeiee521b62024-06-07 13:50:41 +0200725 self.mbedtls_configfile.write(self.settings, mbedtls_file)
726 self.crypto_configfile.write(self.settings, crypto_file)
Gabor Mezei3678dee2024-06-04 19:58:43 +0200727
Gabor Mezeiee521b62024-06-07 13:50:41 +0200728 def filename(self, name=None):
Gabor Mezei4706fe72024-07-08 17:00:55 +0200729 """Get the names of the config files.
730
731 If 'name' is specified return the name of the config file where it is defined.
732 """
733
Gabor Mezeiee521b62024-06-07 13:50:41 +0200734 if not name:
735 return [config.filename for config in [self.mbedtls_configfile, self.crypto_configfile]]
736
737 return self._get_configfile(name).filename
Gilles Peskineb4063892019-07-27 21:36:44 +0200738
739if __name__ == '__main__':
Gabor Mezei92065ed2024-06-07 13:47:59 +0200740 #pylint: disable=too-many-statements
Gilles Peskineb4063892019-07-27 21:36:44 +0200741 def main():
Bence Szépkútibb0cfeb2021-05-28 09:42:25 +0200742 """Command line mbedtls_config.h manipulation tool."""
Gilles Peskineb4063892019-07-27 21:36:44 +0200743 parser = argparse.ArgumentParser(description="""
Fredrik Hesse0ec8a902021-10-04 22:13:51 +0200744 Mbed TLS configuration file manipulation tool.
Gilles Peskineb4063892019-07-27 21:36:44 +0200745 """)
746 parser.add_argument('--file', '-f',
747 help="""File to read (and modify if requested).
748 Default: {}.
Gabor Mezeif77722d2024-06-28 16:49:33 +0200749 """.format(MbedTLSConfigFile.default_path))
Gabor Mezei3678dee2024-06-04 19:58:43 +0200750 parser.add_argument('--cryptofile', '-c',
751 help="""Crypto file to read (and modify if requested).
752 Default: {}.
753 """.format(CryptoConfigFile.default_path))
Gilles Peskineb4063892019-07-27 21:36:44 +0200754 parser.add_argument('--force', '-o',
Gilles Peskine435ce222019-08-01 23:13:47 +0200755 action='store_true',
Gilles Peskineb4063892019-07-27 21:36:44 +0200756 help="""For the set command, if SYMBOL is not
757 present, add a definition for it.""")
Gilles Peskinec190c902019-08-01 23:31:05 +0200758 parser.add_argument('--write', '-w', metavar='FILE',
Gilles Peskine40f103c2019-07-27 23:44:01 +0200759 help="""File to write to instead of the input file.""")
Gilles Peskineb4063892019-07-27 21:36:44 +0200760 subparsers = parser.add_subparsers(dest='command',
761 title='Commands')
762 parser_get = subparsers.add_parser('get',
763 help="""Find the value of SYMBOL
764 and print it. Exit with
765 status 0 if a #define for SYMBOL is
766 found, 1 otherwise.
767 """)
768 parser_get.add_argument('symbol', metavar='SYMBOL')
769 parser_set = subparsers.add_parser('set',
770 help="""Set SYMBOL to VALUE.
771 If VALUE is omitted, just uncomment
772 the #define for SYMBOL.
773 Error out of a line defining
774 SYMBOL (commented or not) is not
775 found, unless --force is passed.
776 """)
777 parser_set.add_argument('symbol', metavar='SYMBOL')
Gilles Peskine0c7fcd22019-08-01 23:14:00 +0200778 parser_set.add_argument('value', metavar='VALUE', nargs='?',
779 default='')
Gilles Peskine8e90cf42021-05-27 22:12:57 +0200780 parser_set_all = subparsers.add_parser('set-all',
781 help="""Uncomment all #define
782 whose name contains a match for
783 REGEX.""")
784 parser_set_all.add_argument('regexs', metavar='REGEX', nargs='*')
Gilles Peskineb4063892019-07-27 21:36:44 +0200785 parser_unset = subparsers.add_parser('unset',
786 help="""Comment out the #define
787 for SYMBOL. Do nothing if none
788 is present.""")
789 parser_unset.add_argument('symbol', metavar='SYMBOL')
Gilles Peskine8e90cf42021-05-27 22:12:57 +0200790 parser_unset_all = subparsers.add_parser('unset-all',
791 help="""Comment out all #define
792 whose name contains a match for
793 REGEX.""")
794 parser_unset_all.add_argument('regexs', metavar='REGEX', nargs='*')
Gilles Peskineb4063892019-07-27 21:36:44 +0200795
796 def add_adapter(name, function, description):
797 subparser = subparsers.add_parser(name, help=description)
798 subparser.set_defaults(adapter=function)
Gilles Peskine53d41ae2019-07-27 23:31:53 +0200799 add_adapter('baremetal', baremetal_adapter,
800 """Like full, but exclude features that require platform
801 features such as file input-output.""")
Gilles Peskine120f29d2021-09-01 19:51:19 +0200802 add_adapter('baremetal_size', baremetal_size_adapter,
803 """Like baremetal, but exclude debugging features.
804 Useful for code size measurements.""")
Gilles Peskine53d41ae2019-07-27 23:31:53 +0200805 add_adapter('full', full_adapter,
806 """Uncomment most features.
807 Exclude alternative implementations and platform support
808 options, as well as some options that are awkward to test.
809 """)
Gilles Peskine30de2e82020-04-20 21:39:22 +0200810 add_adapter('full_no_deprecated', no_deprecated_adapter(full_adapter),
Gilles Peskinebe1d6092020-04-12 14:17:16 +0200811 """Uncomment most non-deprecated features.
812 Like "full", but without deprecated features.
813 """)
Paul Elliottfb81f772023-10-18 17:44:59 +0100814 add_adapter('full_no_platform', no_platform_adapter(full_adapter),
815 """Uncomment most non-platform features.
816 Like "full", but without platform features.
817 """)
Gilles Peskineb4063892019-07-27 21:36:44 +0200818 add_adapter('realfull', realfull_adapter,
Gilles Peskine53d41ae2019-07-27 23:31:53 +0200819 """Uncomment all boolean #defines.
820 Suitable for generating documentation, but not for building.""")
Gilles Peskine31987c62020-01-31 14:23:30 +0100821 add_adapter('crypto', crypto_adapter(None),
822 """Only include crypto features. Exclude X.509 and TLS.""")
823 add_adapter('crypto_baremetal', crypto_adapter(baremetal_adapter),
824 """Like baremetal, but with only crypto features,
825 excluding X.509 and TLS.""")
826 add_adapter('crypto_full', crypto_adapter(full_adapter),
827 """Like full, but with only crypto features,
828 excluding X.509 and TLS.""")
Gilles Peskineb4063892019-07-27 21:36:44 +0200829
830 args = parser.parse_args()
Gabor Mezei33dd2932024-06-28 17:51:58 +0200831 config = CombinedConfig(MbedTLSConfigFile(args.file), CryptoConfigFile(args.cryptofile))
Gilles Peskine90b30b62019-07-28 00:36:53 +0200832 if args.command is None:
833 parser.print_help()
834 return 1
835 elif args.command == 'get':
Gilles Peskineb4063892019-07-27 21:36:44 +0200836 if args.symbol in config:
837 value = config[args.symbol]
838 if value:
839 sys.stdout.write(value + '\n')
Gilles Peskinee22a4da2020-03-24 15:43:49 +0100840 return 0 if args.symbol in config else 1
Gilles Peskineb4063892019-07-27 21:36:44 +0200841 elif args.command == 'set':
Gilles Peskine98eb3652019-07-28 16:39:19 +0200842 if not args.force and args.symbol not in config.settings:
Gilles Peskineb4063892019-07-27 21:36:44 +0200843 sys.stderr.write("A #define for the symbol {} "
Gilles Peskine221df1e2019-08-01 23:14:29 +0200844 "was not found in {}\n"
Gabor Mezei3678dee2024-06-04 19:58:43 +0200845 .format(args.symbol, config.filename(args.symbol)))
Gilles Peskineb4063892019-07-27 21:36:44 +0200846 return 1
847 config.set(args.symbol, value=args.value)
Gilles Peskine8e90cf42021-05-27 22:12:57 +0200848 elif args.command == 'set-all':
849 config.change_matching(args.regexs, True)
Gilles Peskineb4063892019-07-27 21:36:44 +0200850 elif args.command == 'unset':
851 config.unset(args.symbol)
Gilles Peskine8e90cf42021-05-27 22:12:57 +0200852 elif args.command == 'unset-all':
853 config.change_matching(args.regexs, False)
Gilles Peskineb4063892019-07-27 21:36:44 +0200854 else:
855 config.adapt(args.adapter)
Gilles Peskine40f103c2019-07-27 23:44:01 +0200856 config.write(args.write)
Gilles Peskinee22a4da2020-03-24 15:43:49 +0100857 return 0
Gilles Peskineb4063892019-07-27 21:36:44 +0200858
859 # Import modules only used by main only if main is defined and called.
860 # pylint: disable=wrong-import-position
861 import argparse
862 import sys
863 sys.exit(main())