blob: f58efa62461ff804aeab31f9640a8b81ad67d04b [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
Gabor Mezeia12ed6b2024-09-09 17:20:49 +020021
Gilles Peskineb4063892019-07-27 21:36:44 +020022class Setting:
Gabor Mezei9f2b8172024-08-06 12:02:18 +020023 """Representation of one Mbed TLS mbedtls_config.h pr PSA crypto_config.h setting.
Gilles Peskineb4063892019-07-27 21:36:44 +020024
25 Fields:
26 * name: the symbol name ('MBEDTLS_xxx').
27 * value: the value of the macro. The empty string for a plain #define
28 with no value.
29 * active: True if name is defined, False if a #define for name is
Bence Szépkútibb0cfeb2021-05-28 09:42:25 +020030 present in mbedtls_config.h but commented out.
Gilles Peskine53d41ae2019-07-27 23:31:53 +020031 * section: the name of the section that contains this symbol.
Gabor Mezeid53080d2024-08-27 14:06:54 +020032 * configfile: the file the settings is defined
Gilles Peskineb4063892019-07-27 21:36:44 +020033 """
Gabor Mezei92065ed2024-06-07 13:47:59 +020034 # pylint: disable=too-few-public-methods, too-many-arguments
Gabor Mezeid53080d2024-08-27 14:06:54 +020035 def __init__(self, configfile, active, name, value='', section=None):
Gilles Peskineb4063892019-07-27 21:36:44 +020036 self.active = active
37 self.name = name
38 self.value = value
Gilles Peskine53d41ae2019-07-27 23:31:53 +020039 self.section = section
Gabor Mezei3678dee2024-06-04 19:58:43 +020040 self.configfile = configfile
Gilles Peskineb4063892019-07-27 21:36:44 +020041
Gabor Mezeia12ed6b2024-09-09 17:20:49 +020042
Gilles Peskineb4063892019-07-27 21:36:44 +020043class Config:
Gabor Mezei9f2b8172024-08-06 12:02:18 +020044 """Representation of the Mbed TLS and PSA configuration.
Gilles Peskineb4063892019-07-27 21:36:44 +020045
46 In the documentation of this class, a symbol is said to be *active*
47 if there is a #define for it that is not commented out, and *known*
48 if there is a #define for it whether commented out or not.
49
50 This class supports the following protocols:
Gilles Peskinec190c902019-08-01 23:31:05 +020051 * `name in config` is `True` if the symbol `name` is active, `False`
52 otherwise (whether `name` is inactive or not known).
53 * `config[name]` is the value of the macro `name`. If `name` is inactive,
54 raise `KeyError` (even if `name` is known).
Gilles Peskineb4063892019-07-27 21:36:44 +020055 * `config[name] = value` sets the value associated to `name`. `name`
56 must be known, but does not need to be set. This does not cause
57 name to become set.
58 """
59
Gabor Mezeiee521b62024-06-07 13:50:41 +020060 def __init__(self):
Gilles Peskineb4063892019-07-27 21:36:44 +020061 self.settings = {}
Gabor Mezeid53080d2024-08-27 14:06:54 +020062 self.configfiles = []
Gilles Peskineb4063892019-07-27 21:36:44 +020063
64 def __contains__(self, name):
65 """True if the given symbol is active (i.e. set).
66
67 False if the given symbol is not set, even if a definition
68 is present but commented out.
69 """
70 return name in self.settings and self.settings[name].active
71
72 def all(self, *names):
73 """True if all the elements of names are active (i.e. set)."""
Gabor Mezeidaf807f2024-08-14 11:33:46 +020074 return all(name in self for name in names)
Gilles Peskineb4063892019-07-27 21:36:44 +020075
76 def any(self, *names):
77 """True if at least one symbol in names are active (i.e. set)."""
Gabor Mezeidaf807f2024-08-14 11:33:46 +020078 return any(name in self for name in names)
Gilles Peskineb4063892019-07-27 21:36:44 +020079
80 def known(self, name):
81 """True if a #define for name is present, whether it's commented out or not."""
82 return name in self.settings
83
84 def __getitem__(self, name):
85 """Get the value of name, i.e. what the preprocessor symbol expands to.
86
87 If name is not known, raise KeyError. name does not need to be active.
88 """
89 return self.settings[name].value
90
91 def get(self, name, default=None):
92 """Get the value of name. If name is inactive (not set), return default.
93
94 If a #define for name is present and not commented out, return
95 its expansion, even if this is the empty string.
96
97 If a #define for name is present but commented out, return default.
98 """
99 if name in self.settings:
100 return self.settings[name].value
101 else:
102 return default
103
104 def __setitem__(self, name, value):
105 """If name is known, set its value.
106
107 If name is not known, raise KeyError.
108 """
Gabor Mezeic659c1b2024-08-06 17:37:55 +0200109 setting = self.settings[name]
Gabor Mezeid53080d2024-08-27 14:06:54 +0200110 if setting != value:
Gabor Mezeic659c1b2024-08-06 17:37:55 +0200111 setting.configfile.modified = True
Gilles Peskineb4063892019-07-27 21:36:44 +0200112
Gabor Mezeic659c1b2024-08-06 17:37:55 +0200113 setting.value = value
114
Gabor Mezeid53080d2024-08-27 14:06:54 +0200115 def set(self, name, value=None):
Gilles Peskineb4063892019-07-27 21:36:44 +0200116 """Set name to the given value and make it active.
117
118 If value is None and name is already known, don't change its value.
Gabor Mezeic659c1b2024-08-06 17:37:55 +0200119 If value is None and name is not known, set its value.
Gilles Peskineb4063892019-07-27 21:36:44 +0200120 """
121 if name in self.settings:
Gabor Mezeic659c1b2024-08-06 17:37:55 +0200122 setting = self.settings[name]
Gabor Mezeid53080d2024-08-27 14:06:54 +0200123 if setting.value != value or not setting.active:
Gabor Mezeic659c1b2024-08-06 17:37:55 +0200124 setting.configfile.modified = True
Gilles Peskineb4063892019-07-27 21:36:44 +0200125 if value is not None:
Gabor Mezeic659c1b2024-08-06 17:37:55 +0200126 setting.value = value
127 setting.active = True
Gilles Peskineb4063892019-07-27 21:36:44 +0200128 else:
Gabor Mezeid53080d2024-08-27 14:06:54 +0200129 configfile = self._get_configfile(name)
130 self.settings[name] = Setting(configfile, True, name, value=value)
131 configfile.modified = True
Gilles Peskineb4063892019-07-27 21:36:44 +0200132
133 def unset(self, name):
134 """Make name unset (inactive).
135
Gilles Peskine55cc4db2019-08-01 23:13:23 +0200136 name remains known if it was known before.
Gilles Peskineb4063892019-07-27 21:36:44 +0200137 """
Gilles Peskine55cc4db2019-08-01 23:13:23 +0200138 if name not in self.settings:
139 return
Gabor Mezeic5ff33c2024-06-28 17:46:44 +0200140
141 setting = self.settings[name]
142 # Check if modifying the config file
Gabor Mezeid53080d2024-08-27 14:06:54 +0200143 if setting.active:
Gabor Mezeic5ff33c2024-06-28 17:46:44 +0200144 setting.configfile.modified = True
145
146 setting.active = False
Gilles Peskineb4063892019-07-27 21:36:44 +0200147
148 def adapt(self, adapter):
149 """Run adapter on each known symbol and (de)activate it accordingly.
150
151 `adapter` must be a function that returns a boolean. It is called as
Gilles Peskine53d41ae2019-07-27 23:31:53 +0200152 `adapter(name, active, section)` for each setting, where `active` is
153 `True` if `name` is set and `False` if `name` is known but unset,
154 and `section` is the name of the section containing `name`. If
Gilles Peskineb4063892019-07-27 21:36:44 +0200155 `adapter` returns `True`, then set `name` (i.e. make it active),
156 otherwise unset `name` (i.e. make it known but inactive).
157 """
158 for setting in self.settings.values():
Gabor Mezeic5ff33c2024-06-28 17:46:44 +0200159 is_active = setting.active
Gilles Peskine53d41ae2019-07-27 23:31:53 +0200160 setting.active = adapter(setting.name, setting.active,
161 setting.section)
Gabor Mezeic5ff33c2024-06-28 17:46:44 +0200162 # Check if modifying the config file
Gabor Mezeid53080d2024-08-27 14:06:54 +0200163 if setting.active != is_active:
Gabor Mezeic5ff33c2024-06-28 17:46:44 +0200164 setting.configfile.modified = True
Gilles Peskineb4063892019-07-27 21:36:44 +0200165
Gilles Peskine8e90cf42021-05-27 22:12:57 +0200166 def change_matching(self, regexs, enable):
167 """Change all symbols matching one of the regexs to the desired state."""
168 if not regexs:
169 return
170 regex = re.compile('|'.join(regexs))
171 for setting in self.settings.values():
172 if regex.search(setting.name):
Gabor Mezeic5ff33c2024-06-28 17:46:44 +0200173 # Check if modifying the config file
Gabor Mezeid53080d2024-08-27 14:06:54 +0200174 if setting.active != enable:
Gabor Mezeic5ff33c2024-06-28 17:46:44 +0200175 setting.configfile.modified = True
Gilles Peskine8e90cf42021-05-27 22:12:57 +0200176 setting.active = enable
177
Gabor Mezeid53080d2024-08-27 14:06:54 +0200178 def _get_configfile(self, name=None):
179 """Find a config for a setting name.
180
181 If more then one configfile is used this function must be overridden.
182 """
183
184 if name and name in self.settings:
185 return self.get(name).configfile
186 return self.configfiles[0]
187
188 def write(self, filename=None):
189 """Write the whole configuration to the file it was read from.
190
191 If filename is specified, write to this file instead.
192 """
193
194 for configfile in self.configfiles:
195 configfile.write(self.settings, filename)
196
197 def filename(self, name=None):
198 """Get the name of the config file."""
199
200 return self._get_configfile(name).filename
201
Gabor Mezeia12ed6b2024-09-09 17:20:49 +0200202
Gilles Peskine53d41ae2019-07-27 23:31:53 +0200203def is_full_section(section):
Gabor Mezeide6e1922024-06-28 17:10:50 +0200204 """Is this section affected by "config.py full" and friends?
205
206 In a config file where the sections are not used the whole config file
207 is an empty section (with value None) and the whole file is affected.
208 """
Gabor Mezei3678dee2024-06-04 19:58:43 +0200209 return section is None or section.endswith('support') or section.endswith('modules')
Gilles Peskine53d41ae2019-07-27 23:31:53 +0200210
211def realfull_adapter(_name, active, section):
Gilles Peskineba4162a2022-04-11 17:04:38 +0200212 """Activate all symbols found in the global and boolean feature sections.
213
214 This is intended for building the documentation, including the
215 documentation of settings that are activated by defining an optional
216 preprocessor macro.
217
218 Do not activate definitions in the section containing symbols that are
219 supposed to be defined and documented in their own module.
220 """
221 if section == 'Module configuration options':
Gilles Peskine53d41ae2019-07-27 23:31:53 +0200222 return active
Gilles Peskineb4063892019-07-27 21:36:44 +0200223 return True
224
Gabor Mezei542fd382024-06-10 14:07:42 +0200225PSA_UNSUPPORTED_FEATURE = frozenset([
Gabor Mezei3678dee2024-06-04 19:58:43 +0200226 'PSA_WANT_ALG_CBC_MAC',
227 'PSA_WANT_ALG_XTS',
228 'PSA_WANT_KEY_TYPE_RSA_KEY_PAIR_DERIVE',
229 'PSA_WANT_KEY_TYPE_DH_KEY_PAIR_DERIVE'
230])
231
Gabor Mezei542fd382024-06-10 14:07:42 +0200232PSA_DEPRECATED_FEATURE = frozenset([
Gabor Mezei3678dee2024-06-04 19:58:43 +0200233 'PSA_WANT_KEY_TYPE_ECC_KEY_PAIR',
234 'PSA_WANT_KEY_TYPE_RSA_KEY_PAIR'
235])
236
Gabor Mezei542fd382024-06-10 14:07:42 +0200237PSA_UNSTABLE_FEATURE = frozenset([
Gabor Mezei3678dee2024-06-04 19:58:43 +0200238 'PSA_WANT_ECC_SECP_K1_224'
239])
240
Gabor Mezei9b0f9e72024-06-26 18:08:17 +0200241EXCLUDE_FROM_CRYPTO = PSA_UNSUPPORTED_FEATURE | \
242 PSA_DEPRECATED_FEATURE | \
243 PSA_UNSTABLE_FEATURE
Gabor Mezei542fd382024-06-10 14:07:42 +0200244
Gilles Peskinecfffc282020-04-12 13:55:45 +0200245# The goal of the full configuration is to have everything that can be tested
246# together. This includes deprecated or insecure options. It excludes:
247# * Options that require additional build dependencies or unusual hardware.
248# * Options that make testing less effective.
Gilles Peskinec9d04332020-04-16 20:50:17 +0200249# * Options that are incompatible with other options, or more generally that
250# interact with other parts of the code in such a way that a bulk enabling
251# is not a good way to test them.
Gilles Peskinecfffc282020-04-12 13:55:45 +0200252# * Options that remove features.
Gilles Peskinebbaa2b72020-04-12 13:33:57 +0200253EXCLUDE_FROM_FULL = frozenset([
Gilles Peskinecfffc282020-04-12 13:55:45 +0200254 #pylint: disable=line-too-long
Yanray Wanga8704672023-04-20 17:16:48 +0800255 'MBEDTLS_AES_ONLY_128_BIT_KEY_LENGTH', # interacts with CTR_DRBG_128_BIT_KEY
Gilles Peskinea8861e02023-09-05 20:20:51 +0200256 'MBEDTLS_AES_USE_HARDWARE_ONLY', # hardware dependency
Yanray Wang42be1ba2023-11-23 14:28:47 +0800257 'MBEDTLS_BLOCK_CIPHER_NO_DECRYPT', # incompatible with ECB in PSA, CBC/XTS/NIST_KW/DES
Gilles Peskinec9d04332020-04-16 20:50:17 +0200258 'MBEDTLS_CTR_DRBG_USE_128_BIT_KEY', # interacts with ENTROPY_FORCE_SHA256
Gilles Peskinecfffc282020-04-12 13:55:45 +0200259 'MBEDTLS_DEPRECATED_REMOVED', # conflicts with deprecated options
Gilles Peskine90581ee2020-04-12 14:02:47 +0200260 'MBEDTLS_DEPRECATED_WARNING', # conflicts with deprecated options
Gilles Peskinec9d04332020-04-16 20:50:17 +0200261 'MBEDTLS_ECDH_VARIANT_EVEREST_ENABLED', # influences the use of ECDH in TLS
Janos Follath5b7c38f2023-08-01 08:51:12 +0100262 'MBEDTLS_ECP_WITH_MPI_UINT', # disables the default ECP and is experimental
Gilles Peskinec9d04332020-04-16 20:50:17 +0200263 'MBEDTLS_ENTROPY_FORCE_SHA256', # interacts with CTR_DRBG_128_BIT_KEY
Gilles Peskinecfffc282020-04-12 13:55:45 +0200264 'MBEDTLS_HAVE_SSE2', # hardware dependency
265 'MBEDTLS_MEMORY_BACKTRACE', # depends on MEMORY_BUFFER_ALLOC_C
266 'MBEDTLS_MEMORY_BUFFER_ALLOC_C', # makes sanitizers (e.g. ASan) less effective
267 'MBEDTLS_MEMORY_DEBUG', # depends on MEMORY_BUFFER_ALLOC_C
Gilles Peskinec9d04332020-04-16 20:50:17 +0200268 'MBEDTLS_NO_64BIT_MULTIPLICATION', # influences anything that uses bignum
Gilles Peskinecfffc282020-04-12 13:55:45 +0200269 'MBEDTLS_NO_DEFAULT_ENTROPY_SOURCES', # removes a feature
270 'MBEDTLS_NO_PLATFORM_ENTROPY', # removes a feature
Gilles Peskinec9d04332020-04-16 20:50:17 +0200271 'MBEDTLS_NO_UDBL_DIVISION', # influences anything that uses bignum
Gilles Peskineefaee9a2023-09-20 20:49:47 +0200272 'MBEDTLS_PSA_P256M_DRIVER_ENABLED', # influences SECP256R1 KeyGen/ECDH/ECDSA
Gilles Peskinecfffc282020-04-12 13:55:45 +0200273 'MBEDTLS_PLATFORM_NO_STD_FUNCTIONS', # removes a feature
David Horstmann6f8c95b2024-03-14 14:52:45 +0000274 'MBEDTLS_PSA_ASSUME_EXCLUSIVE_BUFFERS', # removes a feature
Gilles Peskinef08b3f82020-11-13 17:36:48 +0100275 'MBEDTLS_PSA_CRYPTO_EXTERNAL_RNG', # behavior change + build dependency
Ronald Cronc3623db2020-10-29 10:51:32 +0100276 'MBEDTLS_PSA_CRYPTO_KEY_ID_ENCODES_OWNER', # incompatible with USE_PSA_CRYPTO
Gilles Peskinecfffc282020-04-12 13:55:45 +0200277 'MBEDTLS_PSA_CRYPTO_SPM', # platform dependency (PSA SPM)
Gilles Peskinea08def92023-04-28 21:01:49 +0200278 'MBEDTLS_PSA_INJECT_ENTROPY', # conflicts with platform entropy sources
Gilles Peskinec9d04332020-04-16 20:50:17 +0200279 'MBEDTLS_RSA_NO_CRT', # influences the use of RSA in X.509 and TLS
Tom Cosgrove87fbfb52022-03-15 10:51:52 +0000280 'MBEDTLS_SHA256_USE_A64_CRYPTO_ONLY', # interacts with *_USE_A64_CRYPTO_IF_PRESENT
Dave Rodgman9be3cf02023-10-11 14:47:55 +0100281 'MBEDTLS_SHA256_USE_ARMV8_A_CRYPTO_ONLY', # interacts with *_USE_ARMV8_A_CRYPTO_IF_PRESENT
Tom Cosgrove87fbfb52022-03-15 10:51:52 +0000282 'MBEDTLS_SHA512_USE_A64_CRYPTO_ONLY', # interacts with *_USE_A64_CRYPTO_IF_PRESENT
Dave Rodgman7cb635a2023-10-12 16:14:51 +0100283 'MBEDTLS_SHA256_USE_A64_CRYPTO_IF_PRESENT', # setting *_USE_ARMV8_A_CRYPTO is sufficient
Manuel Pégourié-Gonnard6240def2020-07-10 09:35:54 +0200284 'MBEDTLS_TEST_CONSTANT_FLOW_MEMSAN', # build dependency (clang+memsan)
Manuel Pégourié-Gonnard73afa372020-08-19 10:27:38 +0200285 'MBEDTLS_TEST_CONSTANT_FLOW_VALGRIND', # build dependency (valgrind headers)
Hanno Beckere1113562019-06-12 13:59:14 +0100286 'MBEDTLS_X509_REMOVE_INFO', # removes a feature
Gabor Mezei542fd382024-06-10 14:07:42 +0200287 *PSA_UNSUPPORTED_FEATURE,
288 *PSA_DEPRECATED_FEATURE,
289 *PSA_UNSTABLE_FEATURE
Gilles Peskinebbaa2b72020-04-12 13:33:57 +0200290])
291
Gilles Peskine32e889d2020-04-12 23:43:28 +0200292def is_seamless_alt(name):
Gilles Peskinec34faba2020-04-20 15:44:14 +0200293 """Whether the xxx_ALT symbol should be included in the full configuration.
Gilles Peskine32e889d2020-04-12 23:43:28 +0200294
Gilles Peskinec34faba2020-04-20 15:44:14 +0200295 Include alternative implementations of platform functions, which are
Gilles Peskine32e889d2020-04-12 23:43:28 +0200296 configurable function pointers that default to the built-in function.
297 This way we test that the function pointers exist and build correctly
298 without changing the behavior, and tests can verify that the function
299 pointers are used by modifying those pointers.
300
301 Exclude alternative implementations of library functions since they require
302 an implementation of the relevant functions and an xxx_alt.h header.
303 """
Gilles Peskinea8861e02023-09-05 20:20:51 +0200304 if name in (
305 'MBEDTLS_PLATFORM_GMTIME_R_ALT',
306 'MBEDTLS_PLATFORM_SETUP_TEARDOWN_ALT',
307 'MBEDTLS_PLATFORM_MS_TIME_ALT',
308 'MBEDTLS_PLATFORM_ZEROIZE_ALT',
309 ):
Gilles Peskinec34faba2020-04-20 15:44:14 +0200310 # Similar to non-platform xxx_ALT, requires platform_alt.h
311 return False
Gilles Peskine32e889d2020-04-12 23:43:28 +0200312 return name.startswith('MBEDTLS_PLATFORM_')
313
Gilles Peskine53d41ae2019-07-27 23:31:53 +0200314def include_in_full(name):
315 """Rules for symbols in the "full" configuration."""
Gabor Mezei542fd382024-06-10 14:07:42 +0200316 if name in EXCLUDE_FROM_FULL:
Gilles Peskine53d41ae2019-07-27 23:31:53 +0200317 return False
318 if name.endswith('_ALT'):
Gilles Peskine32e889d2020-04-12 23:43:28 +0200319 return is_seamless_alt(name)
Gilles Peskine53d41ae2019-07-27 23:31:53 +0200320 return True
321
322def full_adapter(name, active, section):
323 """Config adapter for "full"."""
324 if not is_full_section(section):
325 return active
326 return include_in_full(name)
327
Gilles Peskinecfffc282020-04-12 13:55:45 +0200328# The baremetal configuration excludes options that require a library or
329# operating system feature that is typically not present on bare metal
330# systems. Features that are excluded from "full" won't be in "baremetal"
331# either (unless explicitly turned on in baremetal_adapter) so they don't
332# need to be repeated here.
Gilles Peskinebbaa2b72020-04-12 13:33:57 +0200333EXCLUDE_FROM_BAREMETAL = frozenset([
Gilles Peskinecfffc282020-04-12 13:55:45 +0200334 #pylint: disable=line-too-long
Gilles Peskine98f8f952020-04-20 15:38:39 +0200335 'MBEDTLS_ENTROPY_NV_SEED', # requires a filesystem and FS_IO or alternate NV seed hooks
Gilles Peskinecfffc282020-04-12 13:55:45 +0200336 'MBEDTLS_FS_IO', # requires a filesystem
Gilles Peskinecfffc282020-04-12 13:55:45 +0200337 'MBEDTLS_HAVE_TIME', # requires a clock
338 'MBEDTLS_HAVE_TIME_DATE', # requires a clock
339 'MBEDTLS_NET_C', # requires POSIX-like networking
340 'MBEDTLS_PLATFORM_FPRINTF_ALT', # requires FILE* from stdio.h
Gilles Peskine98f8f952020-04-20 15:38:39 +0200341 'MBEDTLS_PLATFORM_NV_SEED_ALT', # requires a filesystem and ENTROPY_NV_SEED
342 'MBEDTLS_PLATFORM_TIME_ALT', # requires a clock and HAVE_TIME
343 'MBEDTLS_PSA_CRYPTO_SE_C', # requires a filesystem and PSA_CRYPTO_STORAGE_C
Gilles Peskinecfffc282020-04-12 13:55:45 +0200344 'MBEDTLS_PSA_CRYPTO_STORAGE_C', # requires a filesystem
345 'MBEDTLS_PSA_ITS_FILE_C', # requires a filesystem
346 'MBEDTLS_THREADING_C', # requires a threading interface
347 'MBEDTLS_THREADING_PTHREAD', # requires pthread
348 'MBEDTLS_TIMING_C', # requires a clock
Dave Rodgman9be3cf02023-10-11 14:47:55 +0100349 'MBEDTLS_SHA256_USE_A64_CRYPTO_IF_PRESENT', # requires an OS for runtime-detection
Dave Rodgman5b89c552023-10-10 14:59:02 +0100350 'MBEDTLS_SHA256_USE_ARMV8_A_CRYPTO_IF_PRESENT', # requires an OS for runtime-detection
Dave Rodgmanbe7915a2023-10-11 10:46:38 +0100351 'MBEDTLS_SHA512_USE_A64_CRYPTO_IF_PRESENT', # requires an OS for runtime-detection
Gilles Peskinebbaa2b72020-04-12 13:33:57 +0200352])
353
Gilles Peskine53d41ae2019-07-27 23:31:53 +0200354def keep_in_baremetal(name):
355 """Rules for symbols in the "baremetal" configuration."""
Gilles Peskinebbaa2b72020-04-12 13:33:57 +0200356 if name in EXCLUDE_FROM_BAREMETAL:
Gilles Peskine53d41ae2019-07-27 23:31:53 +0200357 return False
358 return True
359
360def baremetal_adapter(name, active, section):
361 """Config adapter for "baremetal"."""
362 if not is_full_section(section):
363 return active
364 if name == 'MBEDTLS_NO_PLATFORM_ENTROPY':
Gilles Peskinecfffc282020-04-12 13:55:45 +0200365 # No OS-provided entropy source
Gilles Peskine53d41ae2019-07-27 23:31:53 +0200366 return True
367 return include_in_full(name) and keep_in_baremetal(name)
368
Gilles Peskine120f29d2021-09-01 19:51:19 +0200369# This set contains options that are mostly for debugging or test purposes,
370# and therefore should be excluded when doing code size measurements.
371# Options that are their own module (such as MBEDTLS_ERROR_C) are not listed
372# and therefore will be included when doing code size measurements.
373EXCLUDE_FOR_SIZE = frozenset([
374 'MBEDTLS_DEBUG_C', # large code size increase in TLS
375 'MBEDTLS_SELF_TEST', # increases the size of many modules
376 'MBEDTLS_TEST_HOOKS', # only useful with the hosted test framework, increases code size
377])
378
379def baremetal_size_adapter(name, active, section):
380 if name in EXCLUDE_FOR_SIZE:
381 return False
382 return baremetal_adapter(name, active, section)
383
Gilles Peskine31987c62020-01-31 14:23:30 +0100384def include_in_crypto(name):
385 """Rules for symbols in a crypto configuration."""
386 if name.startswith('MBEDTLS_X509_') or \
387 name.startswith('MBEDTLS_SSL_') or \
388 name.startswith('MBEDTLS_KEY_EXCHANGE_'):
389 return False
390 if name in [
Gilles Peskinecfffc282020-04-12 13:55:45 +0200391 'MBEDTLS_DEBUG_C', # part of libmbedtls
392 'MBEDTLS_NET_C', # part of libmbedtls
Nayna Jainc9deb182020-11-16 19:03:12 +0000393 'MBEDTLS_PKCS7_C', # part of libmbedx509
Gilles Peskine31987c62020-01-31 14:23:30 +0100394 ]:
395 return False
Gabor Mezei542fd382024-06-10 14:07:42 +0200396 if name in EXCLUDE_FROM_CRYPTO:
397 return False
Gilles Peskine31987c62020-01-31 14:23:30 +0100398 return True
399
400def crypto_adapter(adapter):
401 """Modify an adapter to disable non-crypto symbols.
402
403 ``crypto_adapter(adapter)(name, active, section)`` is like
404 ``adapter(name, active, section)``, but unsets all X.509 and TLS symbols.
405 """
406 def continuation(name, active, section):
407 if not include_in_crypto(name):
408 return False
409 if adapter is None:
410 return active
411 return adapter(name, active, section)
412 return continuation
413
Gilles Peskineed5c21d2022-06-27 23:02:09 +0200414DEPRECATED = frozenset([
415 'MBEDTLS_PSA_CRYPTO_SE_C',
Gabor Mezei542fd382024-06-10 14:07:42 +0200416 *PSA_DEPRECATED_FEATURE
Gilles Peskineed5c21d2022-06-27 23:02:09 +0200417])
Gilles Peskine30de2e82020-04-20 21:39:22 +0200418def no_deprecated_adapter(adapter):
Gilles Peskinebe1d6092020-04-12 14:17:16 +0200419 """Modify an adapter to disable deprecated symbols.
420
Gilles Peskine30de2e82020-04-20 21:39:22 +0200421 ``no_deprecated_adapter(adapter)(name, active, section)`` is like
Gilles Peskinebe1d6092020-04-12 14:17:16 +0200422 ``adapter(name, active, section)``, but unsets all deprecated symbols
423 and sets ``MBEDTLS_DEPRECATED_REMOVED``.
424 """
425 def continuation(name, active, section):
426 if name == 'MBEDTLS_DEPRECATED_REMOVED':
427 return True
Gilles Peskineed5c21d2022-06-27 23:02:09 +0200428 if name in DEPRECATED:
429 return False
Gilles Peskinebe1d6092020-04-12 14:17:16 +0200430 if adapter is None:
431 return active
432 return adapter(name, active, section)
433 return continuation
434
Paul Elliottfb81f772023-10-18 17:44:59 +0100435def no_platform_adapter(adapter):
436 """Modify an adapter to disable platform symbols.
437
438 ``no_platform_adapter(adapter)(name, active, section)`` is like
439 ``adapter(name, active, section)``, but unsets all platform symbols other
440 ``than MBEDTLS_PLATFORM_C.
441 """
442 def continuation(name, active, section):
443 # Allow MBEDTLS_PLATFORM_C but remove all other platform symbols.
444 if name.startswith('MBEDTLS_PLATFORM_') and name != 'MBEDTLS_PLATFORM_C':
445 return False
446 if adapter is None:
447 return active
448 return adapter(name, active, section)
449 return continuation
450
Gabor Mezeia12ed6b2024-09-09 17:20:49 +0200451
Gabor Mezei3678dee2024-06-04 19:58:43 +0200452class ConfigFile(metaclass=ABCMeta):
Gabor Mezei62a9bd02024-06-07 13:44:40 +0200453 """Representation of a configuration file."""
454
Gabor Mezei93a6d1f2024-06-26 18:01:09 +0200455 def __init__(self, default_path, name, filename=None):
Gabor Mezei62a9bd02024-06-07 13:44:40 +0200456 """Check if the config file exists."""
Gilles Peskineb4063892019-07-27 21:36:44 +0200457 if filename is None:
Gabor Mezei3678dee2024-06-04 19:58:43 +0200458 for candidate in default_path:
Gilles Peskinece674a92020-03-24 15:37:00 +0100459 if os.path.lexists(candidate):
460 filename = candidate
Gilles Peskine208e4ec2019-07-29 23:43:20 +0200461 break
Gilles Peskinece674a92020-03-24 15:37:00 +0100462 else:
Gabor Mezei8d72ac62024-06-28 17:18:37 +0200463 raise FileNotFoundError(f'{name} configuration file not found: '
464 f'{filename if filename else default_path}')
Gilles Peskineb4063892019-07-27 21:36:44 +0200465
Gabor Mezei3678dee2024-06-04 19:58:43 +0200466 self.filename = filename
467 self.templates = []
468 self.current_section = None
469 self.inclusion_guard = None
Gabor Mezei8a64d8e2024-06-10 15:23:43 +0200470 self.modified = False
Gilles Peskineb4063892019-07-27 21:36:44 +0200471
472 _define_line_regexp = (r'(?P<indentation>\s*)' +
473 r'(?P<commented_out>(//\s*)?)' +
474 r'(?P<define>#\s*define\s+)' +
475 r'(?P<name>\w+)' +
476 r'(?P<arguments>(?:\((?:\w|\s|,)*\))?)' +
477 r'(?P<separator>\s*)' +
478 r'(?P<value>.*)')
Gilles Peskine9ba9c212024-05-23 15:03:43 +0200479 _ifndef_line_regexp = r'#ifndef (?P<inclusion_guard>\w+)'
Gilles Peskine53d41ae2019-07-27 23:31:53 +0200480 _section_line_regexp = (r'\s*/?\*+\s*[\\@]name\s+SECTION:\s*' +
481 r'(?P<section>.*)[ */]*')
482 _config_line_regexp = re.compile(r'|'.join([_define_line_regexp,
Gilles Peskine9ba9c212024-05-23 15:03:43 +0200483 _ifndef_line_regexp,
Gilles Peskine53d41ae2019-07-27 23:31:53 +0200484 _section_line_regexp]))
Gilles Peskineb4063892019-07-27 21:36:44 +0200485 def _parse_line(self, line):
Gabor Mezei62a9bd02024-06-07 13:44:40 +0200486 """Parse a line in the config file, save the templates representing the lines
487 and return the corresponding setting element.
488 """
Gabor Mezei4706fe72024-07-08 17:00:55 +0200489
Gilles Peskineb4063892019-07-27 21:36:44 +0200490 line = line.rstrip('\r\n')
Gilles Peskine53d41ae2019-07-27 23:31:53 +0200491 m = re.match(self._config_line_regexp, line)
492 if m is None:
Gabor Mezei3678dee2024-06-04 19:58:43 +0200493 self.templates.append(line)
494 return None
Gilles Peskine53d41ae2019-07-27 23:31:53 +0200495 elif m.group('section'):
496 self.current_section = m.group('section')
Gabor Mezei3678dee2024-06-04 19:58:43 +0200497 self.templates.append(line)
498 return None
Gilles Peskine9ba9c212024-05-23 15:03:43 +0200499 elif m.group('inclusion_guard') and self.inclusion_guard is None:
500 self.inclusion_guard = m.group('inclusion_guard')
Gabor Mezei3678dee2024-06-04 19:58:43 +0200501 self.templates.append(line)
502 return None
Gilles Peskine53d41ae2019-07-27 23:31:53 +0200503 else:
Gilles Peskineb4063892019-07-27 21:36:44 +0200504 active = not m.group('commented_out')
505 name = m.group('name')
506 value = m.group('value')
Gilles Peskine9ba9c212024-05-23 15:03:43 +0200507 if name == self.inclusion_guard and value == '':
508 # The file double-inclusion guard is not an option.
Gabor Mezei3678dee2024-06-04 19:58:43 +0200509 self.templates.append(line)
510 return None
Gilles Peskineb4063892019-07-27 21:36:44 +0200511 template = (name,
512 m.group('indentation'),
513 m.group('define') + name +
514 m.group('arguments') + m.group('separator'))
Gabor Mezei3678dee2024-06-04 19:58:43 +0200515 self.templates.append(template)
Gilles Peskineb4063892019-07-27 21:36:44 +0200516
Gabor Mezei3678dee2024-06-04 19:58:43 +0200517 return (active, name, value, self.current_section)
518
519 def parse_file(self):
Gabor Mezei62a9bd02024-06-07 13:44:40 +0200520 """Parse the whole file and return the settings."""
Gabor Mezei4706fe72024-07-08 17:00:55 +0200521
Gabor Mezei3678dee2024-06-04 19:58:43 +0200522 with open(self.filename, 'r', encoding='utf-8') as file:
523 for line in file:
524 setting = self._parse_line(line)
525 if setting is not None:
526 yield setting
527 self.current_section = None
528
Gabor Mezeie7742b32024-06-26 18:04:09 +0200529 #pylint: disable=no-self-use
530 def _format_template(self, setting, indent, middle):
Gabor Mezei4706fe72024-07-08 17:00:55 +0200531 """Build a line for the config file for the given setting.
Gabor Mezeie7742b32024-06-26 18:04:09 +0200532
533 The line has the form "<indent>#define <name> <value>"
534 where <middle> is "#define <name> ".
535 """
Gabor Mezei4706fe72024-07-08 17:00:55 +0200536
Gabor Mezeie7742b32024-06-26 18:04:09 +0200537 value = setting.value
538 if value is None:
539 value = ''
540 # Normally the whitespace to separate the symbol name from the
541 # value is part of middle, and there's no whitespace for a symbol
542 # with no value. But if a symbol has been changed from having a
543 # value to not having one, the whitespace is wrong, so fix it.
544 if value:
545 if middle[-1] not in '\t ':
546 middle += ' '
547 else:
548 middle = middle.rstrip()
549 return ''.join([indent,
550 '' if setting.active else '//',
551 middle,
552 value]).rstrip()
Gabor Mezei3678dee2024-06-04 19:58:43 +0200553
554 def write_to_stream(self, settings, output):
555 """Write the whole configuration to output."""
Gabor Mezei4706fe72024-07-08 17:00:55 +0200556
Gabor Mezei3678dee2024-06-04 19:58:43 +0200557 for template in self.templates:
558 if isinstance(template, str):
559 line = template
560 else:
Gabor Mezeie7742b32024-06-26 18:04:09 +0200561 name, indent, middle = template
562 line = self._format_template(settings[name], indent, middle)
Gabor Mezei3678dee2024-06-04 19:58:43 +0200563 output.write(line + '\n')
564
565 def write(self, settings, filename=None):
566 """Write the whole configuration to the file it was read from.
567
568 If filename is specified, write to this file instead.
569 """
Gabor Mezei4706fe72024-07-08 17:00:55 +0200570
Gabor Mezei3678dee2024-06-04 19:58:43 +0200571 if filename is None:
572 filename = self.filename
Gabor Mezei8a64d8e2024-06-10 15:23:43 +0200573
574 # Not modified so no need to write to the file
575 if not self.modified and filename == self.filename:
576 return
577
Gabor Mezei3678dee2024-06-04 19:58:43 +0200578 with open(filename, 'w', encoding='utf-8') as output:
579 self.write_to_stream(settings, output)
580
Gabor Mezeia12ed6b2024-09-09 17:20:49 +0200581
Gabor Mezeif77722d2024-06-28 16:49:33 +0200582class MbedTLSConfigFile(ConfigFile):
Gabor Mezei62a9bd02024-06-07 13:44:40 +0200583 """Representation of an MbedTLS configuration file."""
584
Gabor Mezei3678dee2024-06-04 19:58:43 +0200585 _path_in_tree = 'include/mbedtls/mbedtls_config.h'
586 default_path = [_path_in_tree,
587 os.path.join(os.path.dirname(__file__),
588 os.pardir,
589 _path_in_tree),
590 os.path.join(os.path.dirname(os.path.abspath(os.path.dirname(__file__))),
591 _path_in_tree)]
592
593 def __init__(self, filename=None):
Gabor Mezei93a6d1f2024-06-26 18:01:09 +0200594 super().__init__(self.default_path, 'Mbed TLS', filename)
Gabor Mezei3678dee2024-06-04 19:58:43 +0200595 self.current_section = 'header'
596
Gabor Mezeia12ed6b2024-09-09 17:20:49 +0200597
Gabor Mezei3678dee2024-06-04 19:58:43 +0200598class CryptoConfigFile(ConfigFile):
Gabor Mezei4706fe72024-07-08 17:00:55 +0200599 """Representation of a Crypto configuration file."""
Gabor Mezei62a9bd02024-06-07 13:44:40 +0200600
Gabor Mezei3de65862024-07-08 16:14:10 +0200601 # Temporary, while Mbed TLS does not just rely on the TF-PSA-Crypto
602 # build system to build its crypto library. When it does, the
603 # condition can just be removed.
Gabor Mezei776ee902024-09-09 17:00:50 +0200604 _path_in_tree = ('include/psa/crypto_config.h'
605 if not os.path.isdir(os.path.join(os.path.dirname(__file__),
606 os.pardir,
607 'tf-psa-crypto')) else
608 'tf-psa-crypto/include/psa/crypto_config.h')
Gabor Mezei3678dee2024-06-04 19:58:43 +0200609 default_path = [_path_in_tree,
610 os.path.join(os.path.dirname(__file__),
611 os.pardir,
612 _path_in_tree),
613 os.path.join(os.path.dirname(os.path.abspath(os.path.dirname(__file__))),
614 _path_in_tree)]
615
616 def __init__(self, filename=None):
Gabor Mezei93a6d1f2024-06-26 18:01:09 +0200617 super().__init__(self.default_path, 'Crypto', filename)
Gabor Mezei3678dee2024-06-04 19:58:43 +0200618
Gabor Mezeia12ed6b2024-09-09 17:20:49 +0200619
Gabor Mezeif77722d2024-06-28 16:49:33 +0200620class MbedTLSConfig(Config):
Gabor Mezei62a9bd02024-06-07 13:44:40 +0200621 """Representation of the Mbed TLS configuration.
Gabor Mezei3678dee2024-06-04 19:58:43 +0200622
623 See the documentation of the `Config` class for methods to query
624 and modify the configuration.
625 """
Gabor Mezei4706fe72024-07-08 17:00:55 +0200626
Gabor Mezeiee521b62024-06-07 13:50:41 +0200627 def __init__(self, filename=None):
Gabor Mezei3678dee2024-06-04 19:58:43 +0200628 """Read the Mbed TLS configuration file."""
Gabor Mezei4706fe72024-07-08 17:00:55 +0200629
Gabor Mezei3678dee2024-06-04 19:58:43 +0200630 super().__init__()
Gabor Mezeid53080d2024-08-27 14:06:54 +0200631 configfile = MbedTLSConfigFile(filename)
632 self.configfiles.append(configfile)
633 self.settings.update({name: Setting(configfile, active, name, value, section)
Gabor Mezei92065ed2024-06-07 13:47:59 +0200634 for (active, name, value, section)
Gabor Mezeid53080d2024-08-27 14:06:54 +0200635 in configfile.parse_file()})
Gabor Mezei3678dee2024-06-04 19:58:43 +0200636
637 def set(self, name, value=None):
Gabor Mezei4706fe72024-07-08 17:00:55 +0200638 """Set name to the given value and make it active."""
639
Gabor Mezei3678dee2024-06-04 19:58:43 +0200640 if name not in self.settings:
Gabor Mezeid53080d2024-08-27 14:06:54 +0200641 self._get_configfile().templates.append((name, '', '#define ' + name + ' '))
Gabor Mezeiee521b62024-06-07 13:50:41 +0200642
Gabor Mezei3678dee2024-06-04 19:58:43 +0200643 super().set(name, value)
Gilles Peskineb4063892019-07-27 21:36:44 +0200644
Gabor Mezeia12ed6b2024-09-09 17:20:49 +0200645
Gabor Mezei3678dee2024-06-04 19:58:43 +0200646class CryptoConfig(Config):
Gabor Mezei62a9bd02024-06-07 13:44:40 +0200647 """Representation of the PSA crypto configuration.
Gabor Mezei3678dee2024-06-04 19:58:43 +0200648
649 See the documentation of the `Config` class for methods to query
650 and modify the configuration.
651 """
Gabor Mezei4706fe72024-07-08 17:00:55 +0200652
Gabor Mezeiee521b62024-06-07 13:50:41 +0200653 def __init__(self, filename=None):
Gabor Mezei3678dee2024-06-04 19:58:43 +0200654 """Read the PSA crypto configuration file."""
Gabor Mezei4706fe72024-07-08 17:00:55 +0200655
Gabor Mezei3678dee2024-06-04 19:58:43 +0200656 super().__init__()
Gabor Mezeid53080d2024-08-27 14:06:54 +0200657 configfile = CryptoConfigFile(filename)
658 self.configfiles.append(configfile)
659 self.settings.update({name: Setting(configfile, active, name, value, section)
Gabor Mezei92065ed2024-06-07 13:47:59 +0200660 for (active, name, value, section)
Gabor Mezeid53080d2024-08-27 14:06:54 +0200661 in configfile.parse_file()})
Gabor Mezei3678dee2024-06-04 19:58:43 +0200662
Gabor Mezeid723b512024-06-07 15:31:52 +0200663 def set(self, name, value='1'):
Gabor Mezei4706fe72024-07-08 17:00:55 +0200664 """Set name to the given value and make it active."""
665
Gabor Mezei542fd382024-06-10 14:07:42 +0200666 if name in PSA_UNSUPPORTED_FEATURE:
Gabor Mezei92065ed2024-06-07 13:47:59 +0200667 raise ValueError(f'Feature is unsupported: \'{name}\'')
Gabor Mezei542fd382024-06-10 14:07:42 +0200668 if name in PSA_UNSTABLE_FEATURE:
Gabor Mezei92065ed2024-06-07 13:47:59 +0200669 raise ValueError(f'Feature is unstable: \'{name}\'')
Gabor Mezei3678dee2024-06-04 19:58:43 +0200670
671 if name not in self.settings:
Gabor Mezeid53080d2024-08-27 14:06:54 +0200672 self._get_configfile().templates.append((name, '', '#define ' + name + ' '))
Gabor Mezeiee521b62024-06-07 13:50:41 +0200673
Gabor Mezei3678dee2024-06-04 19:58:43 +0200674 super().set(name, value)
675
Gabor Mezeia12ed6b2024-09-09 17:20:49 +0200676
Gabor Mezei33dd2932024-06-28 17:51:58 +0200677class CombinedConfig(Config):
Gabor Mezei62a9bd02024-06-07 13:44:40 +0200678 """Representation of MbedTLS and PSA crypto configuration
679
680 See the documentation of the `Config` class for methods to query
681 and modify the configuration.
682 """
Gabor Mezei3678dee2024-06-04 19:58:43 +0200683
Gabor Mezei3e2a5502024-06-28 17:27:19 +0200684 def __init__(self, *configs):
Gabor Mezeiee521b62024-06-07 13:50:41 +0200685 super().__init__()
Gabor Mezei3e2a5502024-06-28 17:27:19 +0200686 for config in configs:
687 if isinstance(config, MbedTLSConfigFile):
688 self.mbedtls_configfile = config
689 elif isinstance(config, CryptoConfigFile):
690 self.crypto_configfile = config
691 else:
692 raise ValueError(f'Invalid configfile: {config}')
Gabor Mezeid53080d2024-08-27 14:06:54 +0200693 self.configfiles.append(config)
Gabor Mezei3e2a5502024-06-28 17:27:19 +0200694
Gabor Mezeid53080d2024-08-27 14:06:54 +0200695 self.settings.update({name: Setting(configfile, active, name, value, section)
Gabor Mezeiee521b62024-06-07 13:50:41 +0200696 for configfile in [self.mbedtls_configfile, self.crypto_configfile]
697 for (active, name, value, section) in configfile.parse_file()})
Gabor Mezei3678dee2024-06-04 19:58:43 +0200698
699 _crypto_regexp = re.compile(r'$PSA_.*')
Gabor Mezeid53080d2024-08-27 14:06:54 +0200700 def _get_configfile(self, name=None):
Gabor Mezei4706fe72024-07-08 17:00:55 +0200701 """Find a config type for a setting name"""
702
Gabor Mezeiee521b62024-06-07 13:50:41 +0200703 if name in self.settings:
704 return self.settings[name].configfile
705 elif re.match(self._crypto_regexp, name):
706 return self.crypto_configfile
Gabor Mezei3678dee2024-06-04 19:58:43 +0200707 else:
Gabor Mezeiee521b62024-06-07 13:50:41 +0200708 return self.mbedtls_configfile
Gabor Mezei3678dee2024-06-04 19:58:43 +0200709
710 def set(self, name, value=None):
Gabor Mezei4706fe72024-07-08 17:00:55 +0200711 """Set name to the given value and make it active."""
712
Gabor Mezeiee521b62024-06-07 13:50:41 +0200713 configfile = self._get_configfile(name)
Gabor Mezei3678dee2024-06-04 19:58:43 +0200714
Gabor Mezeiee521b62024-06-07 13:50:41 +0200715 if configfile == self.crypto_configfile:
Gabor Mezei542fd382024-06-10 14:07:42 +0200716 if name in PSA_UNSUPPORTED_FEATURE:
Gabor Mezeiee521b62024-06-07 13:50:41 +0200717 raise ValueError(f'Feature is unsupported: \'{name}\'')
Gabor Mezei542fd382024-06-10 14:07:42 +0200718 if name in PSA_UNSTABLE_FEATURE:
Gabor Mezeiee521b62024-06-07 13:50:41 +0200719 raise ValueError(f'Feature is unstable: \'{name}\'')
720
Gabor Mezeid723b512024-06-07 15:31:52 +0200721 # The default value in the crypto config is '1'
722 if not value:
723 value = '1'
724
Gabor Mezeic659c1b2024-08-06 17:37:55 +0200725 if name not in self.settings:
Gabor Mezeiee521b62024-06-07 13:50:41 +0200726 configfile.templates.append((name, '', '#define ' + name + ' '))
727
Gabor Mezeid53080d2024-08-27 14:06:54 +0200728 super().set(name, value)
Gabor Mezeiee521b62024-06-07 13:50:41 +0200729
Gabor Mezeidaf807f2024-08-14 11:33:46 +0200730 #pylint: disable=arguments-differ
Gabor Mezei3678dee2024-06-04 19:58:43 +0200731 def write(self, mbedtls_file=None, crypto_file=None):
Gabor Mezei62a9bd02024-06-07 13:44:40 +0200732 """Write the whole configuration to the file it was read from.
733
734 If mbedtls_file or crypto_file is specified, write the specific configuration
735 to the corresponding file instead.
736 """
Gabor Mezei4706fe72024-07-08 17:00:55 +0200737
Gabor Mezeiee521b62024-06-07 13:50:41 +0200738 self.mbedtls_configfile.write(self.settings, mbedtls_file)
739 self.crypto_configfile.write(self.settings, crypto_file)
Gabor Mezei3678dee2024-06-04 19:58:43 +0200740
Gabor Mezeiee521b62024-06-07 13:50:41 +0200741 def filename(self, name=None):
Gabor Mezei4706fe72024-07-08 17:00:55 +0200742 """Get the names of the config files.
743
744 If 'name' is specified return the name of the config file where it is defined.
745 """
746
Gabor Mezeiee521b62024-06-07 13:50:41 +0200747 if not name:
748 return [config.filename for config in [self.mbedtls_configfile, self.crypto_configfile]]
749
750 return self._get_configfile(name).filename
Gilles Peskineb4063892019-07-27 21:36:44 +0200751
Gabor Mezei24d7cc72024-08-06 15:11:24 +0200752
753class ConfigTool(metaclass=ABCMeta):
754 """Command line config manipulation tool.
755
756 Custom parser option can be added by overriding 'custom_parser_options'.
757 """
758
759 def __init__(self, file_type):
760 """Create parser for config manipulation tool."""
761
762 self.parser = argparse.ArgumentParser(description="""
763 Configuration file manipulation tool.""")
764 self.subparsers = self.parser.add_subparsers(dest='command',
765 title='Commands')
766 self._common_parser_options(file_type)
767 self.custom_parser_options()
768 self.parser_args = self.parser.parse_args()
769 self.config = Config() # Make the pylint happy
770
771 def add_adapter(self, name, function, description):
772 """Creates a command in the tool for a configuration adapter."""
773
774 subparser = self.subparsers.add_parser(name, help=description)
775 subparser.set_defaults(adapter=function)
776
777 def _common_parser_options(self, file_type):
778 """Common parser options for config manipulation tool."""
779
Gabor Mezeia12ed6b2024-09-09 17:20:49 +0200780 self.parser.add_argument(
781 '--file', '-f',
782 help="""File to read (and modify if requested). Default: {}.
783 """.format(file_type.default_path))
784 self.parser.add_argument(
785 '--force', '-o',
786 action='store_true',
787 help="""For the set command, if SYMBOL is not present, add a definition for it.""")
788 self.parser.add_argument(
789 '--write', '-w',
790 metavar='FILE',
791 help="""File to write to instead of the input file.""")
Gabor Mezei24d7cc72024-08-06 15:11:24 +0200792
Gabor Mezeia12ed6b2024-09-09 17:20:49 +0200793 parser_get = self.subparsers.add_parser(
794 'get',
795 help="""Find the value of SYMBOL and print it. Exit with
796 status 0 if a #define for SYMBOL is found, 1 otherwise.""")
Gilles Peskineb4063892019-07-27 21:36:44 +0200797 parser_get.add_argument('symbol', metavar='SYMBOL')
Gabor Mezeia12ed6b2024-09-09 17:20:49 +0200798 parser_set = self.subparsers.add_parser(
799 'set',
800 help="""Set SYMBOL to VALUE. If VALUE is omitted, just uncomment
801 the #define for SYMBOL. Error out of a line defining
802 SYMBOL (commented or not) is not found, unless --force is passed. """)
Gilles Peskineb4063892019-07-27 21:36:44 +0200803 parser_set.add_argument('symbol', metavar='SYMBOL')
Gabor Mezeia12ed6b2024-09-09 17:20:49 +0200804 parser_set.add_argument('value', metavar='VALUE', nargs='?', default='')
805 parser_set_all = self.subparsers.add_parser(
806 'set-all',
807 help="""Uncomment all #define whose name contains a match for REGEX.""")
Gilles Peskine8e90cf42021-05-27 22:12:57 +0200808 parser_set_all.add_argument('regexs', metavar='REGEX', nargs='*')
Gabor Mezeia12ed6b2024-09-09 17:20:49 +0200809 parser_unset = self.subparsers.add_parser(
810 'unset',
811 help="""Comment out the #define for SYMBOL. Do nothing if none is present.""")
Gilles Peskineb4063892019-07-27 21:36:44 +0200812 parser_unset.add_argument('symbol', metavar='SYMBOL')
Gabor Mezeia12ed6b2024-09-09 17:20:49 +0200813 parser_unset_all = self.subparsers.add_parser(
814 'unset-all',
815 help="""Comment out all #define whose name contains a match for REGEX.""")
Gilles Peskine8e90cf42021-05-27 22:12:57 +0200816 parser_unset_all.add_argument('regexs', metavar='REGEX', nargs='*')
Gilles Peskineb4063892019-07-27 21:36:44 +0200817
Gabor Mezei24d7cc72024-08-06 15:11:24 +0200818 def custom_parser_options(self):
819 """Adds custom options for the parser. Designed for overridden by descendant."""
820 pass
821
822 def main(self):
823 """Common main fuction for config manipulation tool."""
824
825 if self.parser_args.command is None:
826 self.parser.print_help()
827 return 1
828 if self.parser_args.command == 'get':
829 if self.parser_args.symbol in self.config:
830 value = self.config[self.parser_args.symbol]
831 if value:
832 sys.stdout.write(value + '\n')
833 return 0 if self.parser_args.symbol in self.config else 1
834 elif self.parser_args.command == 'set':
835 if not self.parser_args.force and self.parser_args.symbol not in self.config.settings:
836 sys.stderr.write(
837 "A #define for the symbol {} was not found in {}\n"
838 .format(self.parser_args.symbol,
839 self.config.filename(self.parser_args.symbol)))
840 return 1
841 self.config.set(self.parser_args.symbol, value=self.parser_args.value)
842 elif self.parser_args.command == 'set-all':
843 self.config.change_matching(self.parser_args.regexs, True)
844 elif self.parser_args.command == 'unset':
845 self.config.unset(self.parser_args.symbol)
846 elif self.parser_args.command == 'unset-all':
847 self.config.change_matching(self.parser_args.regexs, False)
848 else:
849 self.config.adapt(self.parser_args.adapter)
850 self.config.write(self.parser_args.write)
851
852 return 0
853
854
855class MbedTLSConfigTool(ConfigTool):
856 """Command line mbedtls_config.h and crypto_config.h manipulation tool."""
857
858 def __init__(self):
859 super().__init__(MbedTLSConfigFile)
860 self.config = CombinedConfig(MbedTLSConfigFile(self.parser_args.file),
861 CryptoConfigFile(self.parser_args.cryptofile))
862
863 def custom_parser_options(self):
864 """Adds MbedTLS specific options for the parser."""
865
Gabor Mezeia12ed6b2024-09-09 17:20:49 +0200866 self.parser.add_argument(
867 '--cryptofile', '-c',
868 help="""Crypto file to read (and modify if requested). Default: {}."""
869 .format(CryptoConfigFile.default_path))
Gabor Mezei24d7cc72024-08-06 15:11:24 +0200870
Gabor Mezeia12ed6b2024-09-09 17:20:49 +0200871 self.add_adapter(
872 'baremetal', baremetal_adapter,
873 """Like full, but exclude features that require platform features
874 such as file input-output.
875 """)
876 self.add_adapter(
877 'baremetal_size', baremetal_size_adapter,
878 """Like baremetal, but exclude debugging features. Useful for code size measurements.
879 """)
880 self.add_adapter(
881 'full', full_adapter,
882 """Uncomment most features.
883 Exclude alternative implementations and platform support options, as well as
884 some options that are awkward to test.
885 """)
886 self.add_adapter(
887 'full_no_deprecated', no_deprecated_adapter(full_adapter),
888 """Uncomment most non-deprecated features.
889 Like "full", but without deprecated features.
890 """)
891 self.add_adapter(
892 'full_no_platform', no_platform_adapter(full_adapter),
893 """Uncomment most non-platform features. Like "full", but without platform features.
894 """)
895 self.add_adapter(
896 'realfull', realfull_adapter,
897 """Uncomment all boolean #defines.
898 Suitable for generating documentation, but not for building.
899 """)
900 self.add_adapter(
901 'crypto', crypto_adapter(None),
902 """Only include crypto features. Exclude X.509 and TLS.""")
903 self.add_adapter(
904 'crypto_baremetal', crypto_adapter(baremetal_adapter),
905 """Like baremetal, but with only crypto features, excluding X.509 and TLS.""")
906 self.add_adapter(
907 'crypto_full', crypto_adapter(full_adapter),
908 """Like full, but with only crypto features, excluding X.509 and TLS.""")
Gilles Peskineb4063892019-07-27 21:36:44 +0200909
Gilles Peskineb4063892019-07-27 21:36:44 +0200910
Gabor Mezei24d7cc72024-08-06 15:11:24 +0200911if __name__ == '__main__':
912 sys.exit(MbedTLSConfigTool().main())