blob: 17dac4fc11b604acc7224e7b06df97288d5228a3 [file] [log] [blame]
Gilles Peskineb4063892019-07-27 21:36:44 +02001#!/usr/bin/env python3
2
Gabor Mezei9f2b8172024-08-06 12:02:18 +02003"""Mbed TLS and PSA configuration file manipulation library and tool
Gilles Peskineb4063892019-07-27 21:36:44 +02004
Fredrik Hessecc207bc2021-09-28 21:06:08 +02005Basic usage, to read the Mbed TLS configuration:
Gabor Mezei9f2b8172024-08-06 12:02:18 +02006 config = CombinedConfigFile()
Gilles Peskineb4063892019-07-27 21:36:44 +02007 if 'MBEDTLS_RSA_C' in config: print('RSA is enabled')
8"""
9
Bence Szépkúti1e148272020-08-07 13:07:28 +020010## Copyright The Mbed TLS Contributors
Dave Rodgman16799db2023-11-02 19:47:20 +000011## SPDX-License-Identifier: Apache-2.0 OR GPL-2.0-or-later
Gilles Peskineb4063892019-07-27 21:36:44 +020012##
Gilles Peskineb4063892019-07-27 21:36:44 +020013
Gilles Peskine208e4ec2019-07-29 23:43:20 +020014import os
Gilles Peskineb4063892019-07-27 21:36:44 +020015import re
16
Gabor Mezeie7742b32024-06-26 18:04:09 +020017from abc import ABCMeta
Gabor Mezei3678dee2024-06-04 19:58:43 +020018
Gilles Peskineb4063892019-07-27 21:36:44 +020019class Setting:
Gabor Mezei9f2b8172024-08-06 12:02:18 +020020 """Representation of one Mbed TLS mbedtls_config.h pr PSA crypto_config.h setting.
Gilles Peskineb4063892019-07-27 21:36:44 +020021
22 Fields:
23 * name: the symbol name ('MBEDTLS_xxx').
24 * value: the value of the macro. The empty string for a plain #define
25 with no value.
26 * active: True if name is defined, False if a #define for name is
Bence Szépkútibb0cfeb2021-05-28 09:42:25 +020027 present in mbedtls_config.h but commented out.
Gilles Peskine53d41ae2019-07-27 23:31:53 +020028 * section: the name of the section that contains this symbol.
Gilles Peskineb4063892019-07-27 21:36:44 +020029 """
Gabor Mezei92065ed2024-06-07 13:47:59 +020030 # pylint: disable=too-few-public-methods, too-many-arguments
Gabor Mezei3678dee2024-06-04 19:58:43 +020031 def __init__(self, active, name, value='', section=None, configfile=None):
Gilles Peskineb4063892019-07-27 21:36:44 +020032 self.active = active
33 self.name = name
34 self.value = value
Gilles Peskine53d41ae2019-07-27 23:31:53 +020035 self.section = section
Gabor Mezei3678dee2024-06-04 19:58:43 +020036 self.configfile = configfile
Gilles Peskineb4063892019-07-27 21:36:44 +020037
38class Config:
Gabor Mezei9f2b8172024-08-06 12:02:18 +020039 """Representation of the Mbed TLS and PSA configuration.
Gilles Peskineb4063892019-07-27 21:36:44 +020040
41 In the documentation of this class, a symbol is said to be *active*
42 if there is a #define for it that is not commented out, and *known*
43 if there is a #define for it whether commented out or not.
44
45 This class supports the following protocols:
Gilles Peskinec190c902019-08-01 23:31:05 +020046 * `name in config` is `True` if the symbol `name` is active, `False`
47 otherwise (whether `name` is inactive or not known).
48 * `config[name]` is the value of the macro `name`. If `name` is inactive,
49 raise `KeyError` (even if `name` is known).
Gilles Peskineb4063892019-07-27 21:36:44 +020050 * `config[name] = value` sets the value associated to `name`. `name`
51 must be known, but does not need to be set. This does not cause
52 name to become set.
53 """
54
Gabor Mezei92065ed2024-06-07 13:47:59 +020055 # pylint: disable=unused-argument
Gabor Mezeiee521b62024-06-07 13:50:41 +020056 def __init__(self):
Gilles Peskineb4063892019-07-27 21:36:44 +020057 self.settings = {}
58
59 def __contains__(self, name):
60 """True if the given symbol is active (i.e. set).
61
62 False if the given symbol is not set, even if a definition
63 is present but commented out.
64 """
65 return name in self.settings and self.settings[name].active
66
67 def all(self, *names):
68 """True if all the elements of names are active (i.e. set)."""
69 return all(self.__contains__(name) for name in names)
70
71 def any(self, *names):
72 """True if at least one symbol in names are active (i.e. set)."""
73 return any(self.__contains__(name) for name in names)
74
75 def known(self, name):
76 """True if a #define for name is present, whether it's commented out or not."""
77 return name in self.settings
78
79 def __getitem__(self, name):
80 """Get the value of name, i.e. what the preprocessor symbol expands to.
81
82 If name is not known, raise KeyError. name does not need to be active.
83 """
84 return self.settings[name].value
85
86 def get(self, name, default=None):
87 """Get the value of name. If name is inactive (not set), return default.
88
89 If a #define for name is present and not commented out, return
90 its expansion, even if this is the empty string.
91
92 If a #define for name is present but commented out, return default.
93 """
94 if name in self.settings:
95 return self.settings[name].value
96 else:
97 return default
98
99 def __setitem__(self, name, value):
100 """If name is known, set its value.
101
102 If name is not known, raise KeyError.
103 """
104 self.settings[name].value = value
105
106 def set(self, name, value=None):
107 """Set name to the given value and make it active.
108
109 If value is None and name is already known, don't change its value.
110 If value is None and name is not known, set its value to the empty
111 string.
112 """
113 if name in self.settings:
114 if value is not None:
115 self.settings[name].value = value
116 self.settings[name].active = True
117 else:
118 self.settings[name] = Setting(True, name, value=value)
119
120 def unset(self, name):
121 """Make name unset (inactive).
122
Gilles Peskine55cc4db2019-08-01 23:13:23 +0200123 name remains known if it was known before.
Gilles Peskineb4063892019-07-27 21:36:44 +0200124 """
Gilles Peskine55cc4db2019-08-01 23:13:23 +0200125 if name not in self.settings:
126 return
Gabor Mezeic5ff33c2024-06-28 17:46:44 +0200127
128 setting = self.settings[name]
129 # Check if modifying the config file
130 if setting.configfile and setting.active:
131 setting.configfile.modified = True
132
133 setting.active = False
Gilles Peskineb4063892019-07-27 21:36:44 +0200134
135 def adapt(self, adapter):
136 """Run adapter on each known symbol and (de)activate it accordingly.
137
138 `adapter` must be a function that returns a boolean. It is called as
Gilles Peskine53d41ae2019-07-27 23:31:53 +0200139 `adapter(name, active, section)` for each setting, where `active` is
140 `True` if `name` is set and `False` if `name` is known but unset,
141 and `section` is the name of the section containing `name`. If
Gilles Peskineb4063892019-07-27 21:36:44 +0200142 `adapter` returns `True`, then set `name` (i.e. make it active),
143 otherwise unset `name` (i.e. make it known but inactive).
144 """
145 for setting in self.settings.values():
Gabor Mezeic5ff33c2024-06-28 17:46:44 +0200146 is_active = setting.active
Gilles Peskine53d41ae2019-07-27 23:31:53 +0200147 setting.active = adapter(setting.name, setting.active,
148 setting.section)
Gabor Mezeic5ff33c2024-06-28 17:46:44 +0200149 # Check if modifying the config file
150 if setting.configfile and setting.active != is_active:
151 setting.configfile.modified = True
Gilles Peskineb4063892019-07-27 21:36:44 +0200152
Gilles Peskine8e90cf42021-05-27 22:12:57 +0200153 def change_matching(self, regexs, enable):
154 """Change all symbols matching one of the regexs to the desired state."""
155 if not regexs:
156 return
157 regex = re.compile('|'.join(regexs))
158 for setting in self.settings.values():
159 if regex.search(setting.name):
Gabor Mezeic5ff33c2024-06-28 17:46:44 +0200160 # Check if modifying the config file
161 if setting.configfile and setting.active != enable:
162 setting.configfile.modified = True
Gilles Peskine8e90cf42021-05-27 22:12:57 +0200163 setting.active = enable
164
Gilles Peskine53d41ae2019-07-27 23:31:53 +0200165def is_full_section(section):
Gabor Mezeide6e1922024-06-28 17:10:50 +0200166 """Is this section affected by "config.py full" and friends?
167
168 In a config file where the sections are not used the whole config file
169 is an empty section (with value None) and the whole file is affected.
170 """
Gabor Mezei3678dee2024-06-04 19:58:43 +0200171 return section is None or section.endswith('support') or section.endswith('modules')
Gilles Peskine53d41ae2019-07-27 23:31:53 +0200172
173def realfull_adapter(_name, active, section):
Gilles Peskineba4162a2022-04-11 17:04:38 +0200174 """Activate all symbols found in the global and boolean feature sections.
175
176 This is intended for building the documentation, including the
177 documentation of settings that are activated by defining an optional
178 preprocessor macro.
179
180 Do not activate definitions in the section containing symbols that are
181 supposed to be defined and documented in their own module.
182 """
183 if section == 'Module configuration options':
Gilles Peskine53d41ae2019-07-27 23:31:53 +0200184 return active
Gilles Peskineb4063892019-07-27 21:36:44 +0200185 return True
186
Gabor Mezei542fd382024-06-10 14:07:42 +0200187PSA_UNSUPPORTED_FEATURE = frozenset([
Gabor Mezei3678dee2024-06-04 19:58:43 +0200188 'PSA_WANT_ALG_CBC_MAC',
189 'PSA_WANT_ALG_XTS',
190 'PSA_WANT_KEY_TYPE_RSA_KEY_PAIR_DERIVE',
191 'PSA_WANT_KEY_TYPE_DH_KEY_PAIR_DERIVE'
192])
193
Gabor Mezei542fd382024-06-10 14:07:42 +0200194PSA_DEPRECATED_FEATURE = frozenset([
Gabor Mezei3678dee2024-06-04 19:58:43 +0200195 'PSA_WANT_KEY_TYPE_ECC_KEY_PAIR',
196 'PSA_WANT_KEY_TYPE_RSA_KEY_PAIR'
197])
198
Gabor Mezei542fd382024-06-10 14:07:42 +0200199PSA_UNSTABLE_FEATURE = frozenset([
Gabor Mezei3678dee2024-06-04 19:58:43 +0200200 'PSA_WANT_ECC_SECP_K1_224'
201])
202
Gabor Mezei9b0f9e72024-06-26 18:08:17 +0200203EXCLUDE_FROM_CRYPTO = PSA_UNSUPPORTED_FEATURE | \
204 PSA_DEPRECATED_FEATURE | \
205 PSA_UNSTABLE_FEATURE
Gabor Mezei542fd382024-06-10 14:07:42 +0200206
Gilles Peskinecfffc282020-04-12 13:55:45 +0200207# The goal of the full configuration is to have everything that can be tested
208# together. This includes deprecated or insecure options. It excludes:
209# * Options that require additional build dependencies or unusual hardware.
210# * Options that make testing less effective.
Gilles Peskinec9d04332020-04-16 20:50:17 +0200211# * Options that are incompatible with other options, or more generally that
212# interact with other parts of the code in such a way that a bulk enabling
213# is not a good way to test them.
Gilles Peskinecfffc282020-04-12 13:55:45 +0200214# * Options that remove features.
Gilles Peskinebbaa2b72020-04-12 13:33:57 +0200215EXCLUDE_FROM_FULL = frozenset([
Gilles Peskinecfffc282020-04-12 13:55:45 +0200216 #pylint: disable=line-too-long
Yanray Wanga8704672023-04-20 17:16:48 +0800217 'MBEDTLS_AES_ONLY_128_BIT_KEY_LENGTH', # interacts with CTR_DRBG_128_BIT_KEY
Gilles Peskinea8861e02023-09-05 20:20:51 +0200218 'MBEDTLS_AES_USE_HARDWARE_ONLY', # hardware dependency
Yanray Wang42be1ba2023-11-23 14:28:47 +0800219 'MBEDTLS_BLOCK_CIPHER_NO_DECRYPT', # incompatible with ECB in PSA, CBC/XTS/NIST_KW/DES
Gilles Peskinec9d04332020-04-16 20:50:17 +0200220 'MBEDTLS_CTR_DRBG_USE_128_BIT_KEY', # interacts with ENTROPY_FORCE_SHA256
Gilles Peskinecfffc282020-04-12 13:55:45 +0200221 'MBEDTLS_DEPRECATED_REMOVED', # conflicts with deprecated options
Gilles Peskine90581ee2020-04-12 14:02:47 +0200222 'MBEDTLS_DEPRECATED_WARNING', # conflicts with deprecated options
Gilles Peskinec9d04332020-04-16 20:50:17 +0200223 'MBEDTLS_ECDH_VARIANT_EVEREST_ENABLED', # influences the use of ECDH in TLS
Janos Follath5b7c38f2023-08-01 08:51:12 +0100224 'MBEDTLS_ECP_WITH_MPI_UINT', # disables the default ECP and is experimental
Gilles Peskinec9d04332020-04-16 20:50:17 +0200225 'MBEDTLS_ENTROPY_FORCE_SHA256', # interacts with CTR_DRBG_128_BIT_KEY
Gilles Peskinecfffc282020-04-12 13:55:45 +0200226 'MBEDTLS_HAVE_SSE2', # hardware dependency
227 'MBEDTLS_MEMORY_BACKTRACE', # depends on MEMORY_BUFFER_ALLOC_C
228 'MBEDTLS_MEMORY_BUFFER_ALLOC_C', # makes sanitizers (e.g. ASan) less effective
229 'MBEDTLS_MEMORY_DEBUG', # depends on MEMORY_BUFFER_ALLOC_C
Gilles Peskinec9d04332020-04-16 20:50:17 +0200230 'MBEDTLS_NO_64BIT_MULTIPLICATION', # influences anything that uses bignum
Gilles Peskinecfffc282020-04-12 13:55:45 +0200231 'MBEDTLS_NO_DEFAULT_ENTROPY_SOURCES', # removes a feature
232 'MBEDTLS_NO_PLATFORM_ENTROPY', # removes a feature
Gilles Peskinec9d04332020-04-16 20:50:17 +0200233 'MBEDTLS_NO_UDBL_DIVISION', # influences anything that uses bignum
Gilles Peskineefaee9a2023-09-20 20:49:47 +0200234 'MBEDTLS_PSA_P256M_DRIVER_ENABLED', # influences SECP256R1 KeyGen/ECDH/ECDSA
Gilles Peskinecfffc282020-04-12 13:55:45 +0200235 'MBEDTLS_PLATFORM_NO_STD_FUNCTIONS', # removes a feature
David Horstmann6f8c95b2024-03-14 14:52:45 +0000236 'MBEDTLS_PSA_ASSUME_EXCLUSIVE_BUFFERS', # removes a feature
Gilles Peskinef08b3f82020-11-13 17:36:48 +0100237 'MBEDTLS_PSA_CRYPTO_EXTERNAL_RNG', # behavior change + build dependency
Ronald Cronc3623db2020-10-29 10:51:32 +0100238 'MBEDTLS_PSA_CRYPTO_KEY_ID_ENCODES_OWNER', # incompatible with USE_PSA_CRYPTO
Gilles Peskinecfffc282020-04-12 13:55:45 +0200239 'MBEDTLS_PSA_CRYPTO_SPM', # platform dependency (PSA SPM)
Gilles Peskinea08def92023-04-28 21:01:49 +0200240 'MBEDTLS_PSA_INJECT_ENTROPY', # conflicts with platform entropy sources
Gilles Peskinec9d04332020-04-16 20:50:17 +0200241 'MBEDTLS_RSA_NO_CRT', # influences the use of RSA in X.509 and TLS
Tom Cosgrove87fbfb52022-03-15 10:51:52 +0000242 'MBEDTLS_SHA256_USE_A64_CRYPTO_ONLY', # interacts with *_USE_A64_CRYPTO_IF_PRESENT
Dave Rodgman9be3cf02023-10-11 14:47:55 +0100243 'MBEDTLS_SHA256_USE_ARMV8_A_CRYPTO_ONLY', # interacts with *_USE_ARMV8_A_CRYPTO_IF_PRESENT
Tom Cosgrove87fbfb52022-03-15 10:51:52 +0000244 'MBEDTLS_SHA512_USE_A64_CRYPTO_ONLY', # interacts with *_USE_A64_CRYPTO_IF_PRESENT
Dave Rodgman7cb635a2023-10-12 16:14:51 +0100245 'MBEDTLS_SHA256_USE_A64_CRYPTO_IF_PRESENT', # setting *_USE_ARMV8_A_CRYPTO is sufficient
Manuel Pégourié-Gonnard6240def2020-07-10 09:35:54 +0200246 'MBEDTLS_TEST_CONSTANT_FLOW_MEMSAN', # build dependency (clang+memsan)
Manuel Pégourié-Gonnard73afa372020-08-19 10:27:38 +0200247 'MBEDTLS_TEST_CONSTANT_FLOW_VALGRIND', # build dependency (valgrind headers)
Hanno Beckere1113562019-06-12 13:59:14 +0100248 'MBEDTLS_X509_REMOVE_INFO', # removes a feature
Gabor Mezei542fd382024-06-10 14:07:42 +0200249 *PSA_UNSUPPORTED_FEATURE,
250 *PSA_DEPRECATED_FEATURE,
251 *PSA_UNSTABLE_FEATURE
Gilles Peskinebbaa2b72020-04-12 13:33:57 +0200252])
253
Gilles Peskine32e889d2020-04-12 23:43:28 +0200254def is_seamless_alt(name):
Gilles Peskinec34faba2020-04-20 15:44:14 +0200255 """Whether the xxx_ALT symbol should be included in the full configuration.
Gilles Peskine32e889d2020-04-12 23:43:28 +0200256
Gilles Peskinec34faba2020-04-20 15:44:14 +0200257 Include alternative implementations of platform functions, which are
Gilles Peskine32e889d2020-04-12 23:43:28 +0200258 configurable function pointers that default to the built-in function.
259 This way we test that the function pointers exist and build correctly
260 without changing the behavior, and tests can verify that the function
261 pointers are used by modifying those pointers.
262
263 Exclude alternative implementations of library functions since they require
264 an implementation of the relevant functions and an xxx_alt.h header.
265 """
Gilles Peskinea8861e02023-09-05 20:20:51 +0200266 if name in (
267 'MBEDTLS_PLATFORM_GMTIME_R_ALT',
268 'MBEDTLS_PLATFORM_SETUP_TEARDOWN_ALT',
269 'MBEDTLS_PLATFORM_MS_TIME_ALT',
270 'MBEDTLS_PLATFORM_ZEROIZE_ALT',
271 ):
Gilles Peskinec34faba2020-04-20 15:44:14 +0200272 # Similar to non-platform xxx_ALT, requires platform_alt.h
273 return False
Gilles Peskine32e889d2020-04-12 23:43:28 +0200274 return name.startswith('MBEDTLS_PLATFORM_')
275
Gilles Peskine53d41ae2019-07-27 23:31:53 +0200276def include_in_full(name):
277 """Rules for symbols in the "full" configuration."""
Gabor Mezei542fd382024-06-10 14:07:42 +0200278 if name in EXCLUDE_FROM_FULL:
Gilles Peskine53d41ae2019-07-27 23:31:53 +0200279 return False
280 if name.endswith('_ALT'):
Gilles Peskine32e889d2020-04-12 23:43:28 +0200281 return is_seamless_alt(name)
Gilles Peskine53d41ae2019-07-27 23:31:53 +0200282 return True
283
284def full_adapter(name, active, section):
285 """Config adapter for "full"."""
286 if not is_full_section(section):
287 return active
288 return include_in_full(name)
289
Gilles Peskinecfffc282020-04-12 13:55:45 +0200290# The baremetal configuration excludes options that require a library or
291# operating system feature that is typically not present on bare metal
292# systems. Features that are excluded from "full" won't be in "baremetal"
293# either (unless explicitly turned on in baremetal_adapter) so they don't
294# need to be repeated here.
Gilles Peskinebbaa2b72020-04-12 13:33:57 +0200295EXCLUDE_FROM_BAREMETAL = frozenset([
Gilles Peskinecfffc282020-04-12 13:55:45 +0200296 #pylint: disable=line-too-long
Gilles Peskine98f8f952020-04-20 15:38:39 +0200297 'MBEDTLS_ENTROPY_NV_SEED', # requires a filesystem and FS_IO or alternate NV seed hooks
Gilles Peskinecfffc282020-04-12 13:55:45 +0200298 'MBEDTLS_FS_IO', # requires a filesystem
Gilles Peskinecfffc282020-04-12 13:55:45 +0200299 'MBEDTLS_HAVE_TIME', # requires a clock
300 'MBEDTLS_HAVE_TIME_DATE', # requires a clock
301 'MBEDTLS_NET_C', # requires POSIX-like networking
302 'MBEDTLS_PLATFORM_FPRINTF_ALT', # requires FILE* from stdio.h
Gilles Peskine98f8f952020-04-20 15:38:39 +0200303 'MBEDTLS_PLATFORM_NV_SEED_ALT', # requires a filesystem and ENTROPY_NV_SEED
304 'MBEDTLS_PLATFORM_TIME_ALT', # requires a clock and HAVE_TIME
305 'MBEDTLS_PSA_CRYPTO_SE_C', # requires a filesystem and PSA_CRYPTO_STORAGE_C
Gilles Peskinecfffc282020-04-12 13:55:45 +0200306 'MBEDTLS_PSA_CRYPTO_STORAGE_C', # requires a filesystem
307 'MBEDTLS_PSA_ITS_FILE_C', # requires a filesystem
308 'MBEDTLS_THREADING_C', # requires a threading interface
309 'MBEDTLS_THREADING_PTHREAD', # requires pthread
310 'MBEDTLS_TIMING_C', # requires a clock
Dave Rodgman9be3cf02023-10-11 14:47:55 +0100311 'MBEDTLS_SHA256_USE_A64_CRYPTO_IF_PRESENT', # requires an OS for runtime-detection
Dave Rodgman5b89c552023-10-10 14:59:02 +0100312 'MBEDTLS_SHA256_USE_ARMV8_A_CRYPTO_IF_PRESENT', # requires an OS for runtime-detection
Dave Rodgmanbe7915a2023-10-11 10:46:38 +0100313 'MBEDTLS_SHA512_USE_A64_CRYPTO_IF_PRESENT', # requires an OS for runtime-detection
Gilles Peskinebbaa2b72020-04-12 13:33:57 +0200314])
315
Gilles Peskine53d41ae2019-07-27 23:31:53 +0200316def keep_in_baremetal(name):
317 """Rules for symbols in the "baremetal" configuration."""
Gilles Peskinebbaa2b72020-04-12 13:33:57 +0200318 if name in EXCLUDE_FROM_BAREMETAL:
Gilles Peskine53d41ae2019-07-27 23:31:53 +0200319 return False
320 return True
321
322def baremetal_adapter(name, active, section):
323 """Config adapter for "baremetal"."""
324 if not is_full_section(section):
325 return active
326 if name == 'MBEDTLS_NO_PLATFORM_ENTROPY':
Gilles Peskinecfffc282020-04-12 13:55:45 +0200327 # No OS-provided entropy source
Gilles Peskine53d41ae2019-07-27 23:31:53 +0200328 return True
329 return include_in_full(name) and keep_in_baremetal(name)
330
Gilles Peskine120f29d2021-09-01 19:51:19 +0200331# This set contains options that are mostly for debugging or test purposes,
332# and therefore should be excluded when doing code size measurements.
333# Options that are their own module (such as MBEDTLS_ERROR_C) are not listed
334# and therefore will be included when doing code size measurements.
335EXCLUDE_FOR_SIZE = frozenset([
336 'MBEDTLS_DEBUG_C', # large code size increase in TLS
337 'MBEDTLS_SELF_TEST', # increases the size of many modules
338 'MBEDTLS_TEST_HOOKS', # only useful with the hosted test framework, increases code size
339])
340
341def baremetal_size_adapter(name, active, section):
342 if name in EXCLUDE_FOR_SIZE:
343 return False
344 return baremetal_adapter(name, active, section)
345
Gilles Peskine31987c62020-01-31 14:23:30 +0100346def include_in_crypto(name):
347 """Rules for symbols in a crypto configuration."""
348 if name.startswith('MBEDTLS_X509_') or \
349 name.startswith('MBEDTLS_SSL_') or \
350 name.startswith('MBEDTLS_KEY_EXCHANGE_'):
351 return False
352 if name in [
Gilles Peskinecfffc282020-04-12 13:55:45 +0200353 'MBEDTLS_DEBUG_C', # part of libmbedtls
354 'MBEDTLS_NET_C', # part of libmbedtls
Nayna Jainc9deb182020-11-16 19:03:12 +0000355 'MBEDTLS_PKCS7_C', # part of libmbedx509
Gilles Peskine31987c62020-01-31 14:23:30 +0100356 ]:
357 return False
Gabor Mezei542fd382024-06-10 14:07:42 +0200358 if name in EXCLUDE_FROM_CRYPTO:
359 return False
Gilles Peskine31987c62020-01-31 14:23:30 +0100360 return True
361
362def crypto_adapter(adapter):
363 """Modify an adapter to disable non-crypto symbols.
364
365 ``crypto_adapter(adapter)(name, active, section)`` is like
366 ``adapter(name, active, section)``, but unsets all X.509 and TLS symbols.
367 """
368 def continuation(name, active, section):
369 if not include_in_crypto(name):
370 return False
371 if adapter is None:
372 return active
373 return adapter(name, active, section)
374 return continuation
375
Gilles Peskineed5c21d2022-06-27 23:02:09 +0200376DEPRECATED = frozenset([
377 'MBEDTLS_PSA_CRYPTO_SE_C',
Gabor Mezei542fd382024-06-10 14:07:42 +0200378 *PSA_DEPRECATED_FEATURE
Gilles Peskineed5c21d2022-06-27 23:02:09 +0200379])
Gilles Peskine30de2e82020-04-20 21:39:22 +0200380def no_deprecated_adapter(adapter):
Gilles Peskinebe1d6092020-04-12 14:17:16 +0200381 """Modify an adapter to disable deprecated symbols.
382
Gilles Peskine30de2e82020-04-20 21:39:22 +0200383 ``no_deprecated_adapter(adapter)(name, active, section)`` is like
Gilles Peskinebe1d6092020-04-12 14:17:16 +0200384 ``adapter(name, active, section)``, but unsets all deprecated symbols
385 and sets ``MBEDTLS_DEPRECATED_REMOVED``.
386 """
387 def continuation(name, active, section):
388 if name == 'MBEDTLS_DEPRECATED_REMOVED':
389 return True
Gilles Peskineed5c21d2022-06-27 23:02:09 +0200390 if name in DEPRECATED:
391 return False
Gilles Peskinebe1d6092020-04-12 14:17:16 +0200392 if adapter is None:
393 return active
394 return adapter(name, active, section)
395 return continuation
396
Paul Elliottfb81f772023-10-18 17:44:59 +0100397def no_platform_adapter(adapter):
398 """Modify an adapter to disable platform symbols.
399
400 ``no_platform_adapter(adapter)(name, active, section)`` is like
401 ``adapter(name, active, section)``, but unsets all platform symbols other
402 ``than MBEDTLS_PLATFORM_C.
403 """
404 def continuation(name, active, section):
405 # Allow MBEDTLS_PLATFORM_C but remove all other platform symbols.
406 if name.startswith('MBEDTLS_PLATFORM_') and name != 'MBEDTLS_PLATFORM_C':
407 return False
408 if adapter is None:
409 return active
410 return adapter(name, active, section)
411 return continuation
412
Gabor Mezei3678dee2024-06-04 19:58:43 +0200413class ConfigFile(metaclass=ABCMeta):
Gabor Mezei62a9bd02024-06-07 13:44:40 +0200414 """Representation of a configuration file."""
415
Gabor Mezei93a6d1f2024-06-26 18:01:09 +0200416 def __init__(self, default_path, name, filename=None):
Gabor Mezei62a9bd02024-06-07 13:44:40 +0200417 """Check if the config file exists."""
Gilles Peskineb4063892019-07-27 21:36:44 +0200418 if filename is None:
Gabor Mezei3678dee2024-06-04 19:58:43 +0200419 for candidate in default_path:
Gilles Peskinece674a92020-03-24 15:37:00 +0100420 if os.path.lexists(candidate):
421 filename = candidate
Gilles Peskine208e4ec2019-07-29 23:43:20 +0200422 break
Gilles Peskinece674a92020-03-24 15:37:00 +0100423 else:
Gabor Mezei8d72ac62024-06-28 17:18:37 +0200424 raise FileNotFoundError(f'{name} configuration file not found: '
425 f'{filename if filename else default_path}')
Gilles Peskineb4063892019-07-27 21:36:44 +0200426
Gabor Mezei3678dee2024-06-04 19:58:43 +0200427 self.filename = filename
428 self.templates = []
429 self.current_section = None
430 self.inclusion_guard = None
Gabor Mezei8a64d8e2024-06-10 15:23:43 +0200431 self.modified = False
Gilles Peskineb4063892019-07-27 21:36:44 +0200432
433 _define_line_regexp = (r'(?P<indentation>\s*)' +
434 r'(?P<commented_out>(//\s*)?)' +
435 r'(?P<define>#\s*define\s+)' +
436 r'(?P<name>\w+)' +
437 r'(?P<arguments>(?:\((?:\w|\s|,)*\))?)' +
438 r'(?P<separator>\s*)' +
439 r'(?P<value>.*)')
Gilles Peskine9ba9c212024-05-23 15:03:43 +0200440 _ifndef_line_regexp = r'#ifndef (?P<inclusion_guard>\w+)'
Gilles Peskine53d41ae2019-07-27 23:31:53 +0200441 _section_line_regexp = (r'\s*/?\*+\s*[\\@]name\s+SECTION:\s*' +
442 r'(?P<section>.*)[ */]*')
443 _config_line_regexp = re.compile(r'|'.join([_define_line_regexp,
Gilles Peskine9ba9c212024-05-23 15:03:43 +0200444 _ifndef_line_regexp,
Gilles Peskine53d41ae2019-07-27 23:31:53 +0200445 _section_line_regexp]))
Gilles Peskineb4063892019-07-27 21:36:44 +0200446 def _parse_line(self, line):
Gabor Mezei62a9bd02024-06-07 13:44:40 +0200447 """Parse a line in the config file, save the templates representing the lines
448 and return the corresponding setting element.
449 """
Gabor Mezei4706fe72024-07-08 17:00:55 +0200450
Gilles Peskineb4063892019-07-27 21:36:44 +0200451 line = line.rstrip('\r\n')
Gilles Peskine53d41ae2019-07-27 23:31:53 +0200452 m = re.match(self._config_line_regexp, line)
453 if m is None:
Gabor Mezei3678dee2024-06-04 19:58:43 +0200454 self.templates.append(line)
455 return None
Gilles Peskine53d41ae2019-07-27 23:31:53 +0200456 elif m.group('section'):
457 self.current_section = m.group('section')
Gabor Mezei3678dee2024-06-04 19:58:43 +0200458 self.templates.append(line)
459 return None
Gilles Peskine9ba9c212024-05-23 15:03:43 +0200460 elif m.group('inclusion_guard') and self.inclusion_guard is None:
461 self.inclusion_guard = m.group('inclusion_guard')
Gabor Mezei3678dee2024-06-04 19:58:43 +0200462 self.templates.append(line)
463 return None
Gilles Peskine53d41ae2019-07-27 23:31:53 +0200464 else:
Gilles Peskineb4063892019-07-27 21:36:44 +0200465 active = not m.group('commented_out')
466 name = m.group('name')
467 value = m.group('value')
Gilles Peskine9ba9c212024-05-23 15:03:43 +0200468 if name == self.inclusion_guard and value == '':
469 # The file double-inclusion guard is not an option.
Gabor Mezei3678dee2024-06-04 19:58:43 +0200470 self.templates.append(line)
471 return None
Gilles Peskineb4063892019-07-27 21:36:44 +0200472 template = (name,
473 m.group('indentation'),
474 m.group('define') + name +
475 m.group('arguments') + m.group('separator'))
Gabor Mezei3678dee2024-06-04 19:58:43 +0200476 self.templates.append(template)
Gilles Peskineb4063892019-07-27 21:36:44 +0200477
Gabor Mezei3678dee2024-06-04 19:58:43 +0200478 return (active, name, value, self.current_section)
479
480 def parse_file(self):
Gabor Mezei62a9bd02024-06-07 13:44:40 +0200481 """Parse the whole file and return the settings."""
Gabor Mezei4706fe72024-07-08 17:00:55 +0200482
Gabor Mezei3678dee2024-06-04 19:58:43 +0200483 with open(self.filename, 'r', encoding='utf-8') as file:
484 for line in file:
485 setting = self._parse_line(line)
486 if setting is not None:
487 yield setting
488 self.current_section = None
489
Gabor Mezeie7742b32024-06-26 18:04:09 +0200490 #pylint: disable=no-self-use
491 def _format_template(self, setting, indent, middle):
Gabor Mezei4706fe72024-07-08 17:00:55 +0200492 """Build a line for the config file for the given setting.
Gabor Mezeie7742b32024-06-26 18:04:09 +0200493
494 The line has the form "<indent>#define <name> <value>"
495 where <middle> is "#define <name> ".
496 """
Gabor Mezei4706fe72024-07-08 17:00:55 +0200497
Gabor Mezeie7742b32024-06-26 18:04:09 +0200498 value = setting.value
499 if value is None:
500 value = ''
501 # Normally the whitespace to separate the symbol name from the
502 # value is part of middle, and there's no whitespace for a symbol
503 # with no value. But if a symbol has been changed from having a
504 # value to not having one, the whitespace is wrong, so fix it.
505 if value:
506 if middle[-1] not in '\t ':
507 middle += ' '
508 else:
509 middle = middle.rstrip()
510 return ''.join([indent,
511 '' if setting.active else '//',
512 middle,
513 value]).rstrip()
Gabor Mezei3678dee2024-06-04 19:58:43 +0200514
515 def write_to_stream(self, settings, output):
516 """Write the whole configuration to output."""
Gabor Mezei4706fe72024-07-08 17:00:55 +0200517
Gabor Mezei3678dee2024-06-04 19:58:43 +0200518 for template in self.templates:
519 if isinstance(template, str):
520 line = template
521 else:
Gabor Mezeie7742b32024-06-26 18:04:09 +0200522 name, indent, middle = template
523 line = self._format_template(settings[name], indent, middle)
Gabor Mezei3678dee2024-06-04 19:58:43 +0200524 output.write(line + '\n')
525
526 def write(self, settings, filename=None):
527 """Write the whole configuration to the file it was read from.
528
529 If filename is specified, write to this file instead.
530 """
Gabor Mezei4706fe72024-07-08 17:00:55 +0200531
Gabor Mezei3678dee2024-06-04 19:58:43 +0200532 if filename is None:
533 filename = self.filename
Gabor Mezei8a64d8e2024-06-10 15:23:43 +0200534
535 # Not modified so no need to write to the file
536 if not self.modified and filename == self.filename:
537 return
538
Gabor Mezei3678dee2024-06-04 19:58:43 +0200539 with open(filename, 'w', encoding='utf-8') as output:
540 self.write_to_stream(settings, output)
541
Gabor Mezeif77722d2024-06-28 16:49:33 +0200542class MbedTLSConfigFile(ConfigFile):
Gabor Mezei62a9bd02024-06-07 13:44:40 +0200543 """Representation of an MbedTLS configuration file."""
544
Gabor Mezei3678dee2024-06-04 19:58:43 +0200545 _path_in_tree = 'include/mbedtls/mbedtls_config.h'
546 default_path = [_path_in_tree,
547 os.path.join(os.path.dirname(__file__),
548 os.pardir,
549 _path_in_tree),
550 os.path.join(os.path.dirname(os.path.abspath(os.path.dirname(__file__))),
551 _path_in_tree)]
552
553 def __init__(self, filename=None):
Gabor Mezei93a6d1f2024-06-26 18:01:09 +0200554 super().__init__(self.default_path, 'Mbed TLS', filename)
Gabor Mezei3678dee2024-06-04 19:58:43 +0200555 self.current_section = 'header'
556
Gabor Mezei3678dee2024-06-04 19:58:43 +0200557class CryptoConfigFile(ConfigFile):
Gabor Mezei4706fe72024-07-08 17:00:55 +0200558 """Representation of a Crypto configuration file."""
Gabor Mezei62a9bd02024-06-07 13:44:40 +0200559
Gabor Mezei3de65862024-07-08 16:14:10 +0200560 # Temporary, while Mbed TLS does not just rely on the TF-PSA-Crypto
561 # build system to build its crypto library. When it does, the
562 # condition can just be removed.
563 _path_in_tree = 'include/psa/crypto_config.h' \
564 if os.path.isfile('include/psa/crypto_config.h') else \
565 'tf-psa-crypto/include/psa/crypto_config.h'
Gabor Mezei3678dee2024-06-04 19:58:43 +0200566 default_path = [_path_in_tree,
567 os.path.join(os.path.dirname(__file__),
568 os.pardir,
569 _path_in_tree),
570 os.path.join(os.path.dirname(os.path.abspath(os.path.dirname(__file__))),
571 _path_in_tree)]
572
573 def __init__(self, filename=None):
Gabor Mezei93a6d1f2024-06-26 18:01:09 +0200574 super().__init__(self.default_path, 'Crypto', filename)
Gabor Mezei3678dee2024-06-04 19:58:43 +0200575
Gabor Mezeif77722d2024-06-28 16:49:33 +0200576class MbedTLSConfig(Config):
Gabor Mezei62a9bd02024-06-07 13:44:40 +0200577 """Representation of the Mbed TLS configuration.
Gabor Mezei3678dee2024-06-04 19:58:43 +0200578
579 See the documentation of the `Config` class for methods to query
580 and modify the configuration.
581 """
Gabor Mezei4706fe72024-07-08 17:00:55 +0200582
Gabor Mezeiee521b62024-06-07 13:50:41 +0200583 def __init__(self, filename=None):
Gabor Mezei3678dee2024-06-04 19:58:43 +0200584 """Read the Mbed TLS configuration file."""
Gabor Mezei4706fe72024-07-08 17:00:55 +0200585
Gabor Mezei3678dee2024-06-04 19:58:43 +0200586 super().__init__()
Gabor Mezeif77722d2024-06-28 16:49:33 +0200587 self.configfile = MbedTLSConfigFile(filename)
Gabor Mezeic5ff33c2024-06-28 17:46:44 +0200588 self.settings.update({name: Setting(active, name, value, section, self.configfile)
Gabor Mezei92065ed2024-06-07 13:47:59 +0200589 for (active, name, value, section)
Gabor Mezeiee521b62024-06-07 13:50:41 +0200590 in self.configfile.parse_file()})
Gabor Mezei3678dee2024-06-04 19:58:43 +0200591
592 def set(self, name, value=None):
Gabor Mezei4706fe72024-07-08 17:00:55 +0200593 """Set name to the given value and make it active."""
594
Gabor Mezei3678dee2024-06-04 19:58:43 +0200595 if name not in self.settings:
Gabor Mezeiee521b62024-06-07 13:50:41 +0200596 self.configfile.templates.append((name, '', '#define ' + name + ' '))
597
Gabor Mezei3678dee2024-06-04 19:58:43 +0200598 super().set(name, value)
Gilles Peskineb4063892019-07-27 21:36:44 +0200599
600 def write(self, filename=None):
Gabor Mezei62a9bd02024-06-07 13:44:40 +0200601 """Write the whole configuration to the file it was read from.
602
603 If filename is specified, write to this file instead.
604 """
Gabor Mezei4706fe72024-07-08 17:00:55 +0200605
Gabor Mezeiee521b62024-06-07 13:50:41 +0200606 self.configfile.write(self.settings, filename)
Gilles Peskineb4063892019-07-27 21:36:44 +0200607
Gabor Mezeiee521b62024-06-07 13:50:41 +0200608 def filename(self):
Gabor Mezei4706fe72024-07-08 17:00:55 +0200609 """Get the name of the config file."""
610
Gabor Mezeiee521b62024-06-07 13:50:41 +0200611 return self.configfile.filename
Gabor Mezei3678dee2024-06-04 19:58:43 +0200612
613class CryptoConfig(Config):
Gabor Mezei62a9bd02024-06-07 13:44:40 +0200614 """Representation of the PSA crypto configuration.
Gabor Mezei3678dee2024-06-04 19:58:43 +0200615
616 See the documentation of the `Config` class for methods to query
617 and modify the configuration.
618 """
Gabor Mezei4706fe72024-07-08 17:00:55 +0200619
Gabor Mezeiee521b62024-06-07 13:50:41 +0200620 def __init__(self, filename=None):
Gabor Mezei3678dee2024-06-04 19:58:43 +0200621 """Read the PSA crypto configuration file."""
Gabor Mezei4706fe72024-07-08 17:00:55 +0200622
Gabor Mezei3678dee2024-06-04 19:58:43 +0200623 super().__init__()
Gabor Mezeiee521b62024-06-07 13:50:41 +0200624 self.configfile = CryptoConfigFile(filename)
Gabor Mezeic5ff33c2024-06-28 17:46:44 +0200625 self.settings.update({name: Setting(active, name, value, section, self.configfile)
Gabor Mezei92065ed2024-06-07 13:47:59 +0200626 for (active, name, value, section)
Gabor Mezeiee521b62024-06-07 13:50:41 +0200627 in self.configfile.parse_file()})
Gabor Mezei3678dee2024-06-04 19:58:43 +0200628
Gabor Mezeid723b512024-06-07 15:31:52 +0200629 def set(self, name, value='1'):
Gabor Mezei4706fe72024-07-08 17:00:55 +0200630 """Set name to the given value and make it active."""
631
Gabor Mezei542fd382024-06-10 14:07:42 +0200632 if name in PSA_UNSUPPORTED_FEATURE:
Gabor Mezei92065ed2024-06-07 13:47:59 +0200633 raise ValueError(f'Feature is unsupported: \'{name}\'')
Gabor Mezei542fd382024-06-10 14:07:42 +0200634 if name in PSA_UNSTABLE_FEATURE:
Gabor Mezei92065ed2024-06-07 13:47:59 +0200635 raise ValueError(f'Feature is unstable: \'{name}\'')
Gabor Mezei3678dee2024-06-04 19:58:43 +0200636
637 if name not in self.settings:
Gabor Mezeiee521b62024-06-07 13:50:41 +0200638 self.configfile.templates.append((name, '', '#define ' + name + ' '))
639
Gabor Mezei3678dee2024-06-04 19:58:43 +0200640 super().set(name, value)
641
642 def write(self, filename=None):
Gabor Mezei62a9bd02024-06-07 13:44:40 +0200643 """Write the whole configuration to the file it was read from.
644
645 If filename is specified, write to this file instead.
646 """
Gabor Mezei4706fe72024-07-08 17:00:55 +0200647
Gabor Mezeiee521b62024-06-07 13:50:41 +0200648 self.configfile.write(self.settings, filename)
Gabor Mezei3678dee2024-06-04 19:58:43 +0200649
Gabor Mezeiee521b62024-06-07 13:50:41 +0200650 def filename(self):
Gabor Mezei4706fe72024-07-08 17:00:55 +0200651 """Get the name of the config file."""
652
Gabor Mezeiee521b62024-06-07 13:50:41 +0200653 return self.configfile.filename
Gabor Mezei3678dee2024-06-04 19:58:43 +0200654
Gabor Mezei33dd2932024-06-28 17:51:58 +0200655class CombinedConfig(Config):
Gabor Mezei62a9bd02024-06-07 13:44:40 +0200656 """Representation of MbedTLS and PSA crypto configuration
657
658 See the documentation of the `Config` class for methods to query
659 and modify the configuration.
660 """
Gabor Mezei3678dee2024-06-04 19:58:43 +0200661
Gabor Mezei3e2a5502024-06-28 17:27:19 +0200662 def __init__(self, *configs):
Gabor Mezeiee521b62024-06-07 13:50:41 +0200663 super().__init__()
Gabor Mezei3e2a5502024-06-28 17:27:19 +0200664 for config in configs:
665 if isinstance(config, MbedTLSConfigFile):
666 self.mbedtls_configfile = config
667 elif isinstance(config, CryptoConfigFile):
668 self.crypto_configfile = config
669 else:
670 raise ValueError(f'Invalid configfile: {config}')
671
Gabor Mezeiee521b62024-06-07 13:50:41 +0200672 self.settings.update({name: Setting(active, name, value, section, configfile)
673 for configfile in [self.mbedtls_configfile, self.crypto_configfile]
674 for (active, name, value, section) in configfile.parse_file()})
Gabor Mezei3678dee2024-06-04 19:58:43 +0200675
676 _crypto_regexp = re.compile(r'$PSA_.*')
Gabor Mezeiee521b62024-06-07 13:50:41 +0200677 def _get_configfile(self, name):
Gabor Mezei4706fe72024-07-08 17:00:55 +0200678 """Find a config type for a setting name"""
679
Gabor Mezeiee521b62024-06-07 13:50:41 +0200680 if name in self.settings:
681 return self.settings[name].configfile
682 elif re.match(self._crypto_regexp, name):
683 return self.crypto_configfile
Gabor Mezei3678dee2024-06-04 19:58:43 +0200684 else:
Gabor Mezeiee521b62024-06-07 13:50:41 +0200685 return self.mbedtls_configfile
Gabor Mezei3678dee2024-06-04 19:58:43 +0200686
Gabor Mezei8a64d8e2024-06-10 15:23:43 +0200687 def __setitem__(self, name, value):
688 super().__setitem__(name, value)
689 self.settings[name].configfile.modified = True
690
Gabor Mezei3678dee2024-06-04 19:58:43 +0200691 def set(self, name, value=None):
Gabor Mezei4706fe72024-07-08 17:00:55 +0200692 """Set name to the given value and make it active."""
693
Gabor Mezeiee521b62024-06-07 13:50:41 +0200694 configfile = self._get_configfile(name)
Gabor Mezei3678dee2024-06-04 19:58:43 +0200695
Gabor Mezeiee521b62024-06-07 13:50:41 +0200696 if configfile == self.crypto_configfile:
Gabor Mezei542fd382024-06-10 14:07:42 +0200697 if name in PSA_UNSUPPORTED_FEATURE:
Gabor Mezeiee521b62024-06-07 13:50:41 +0200698 raise ValueError(f'Feature is unsupported: \'{name}\'')
Gabor Mezei542fd382024-06-10 14:07:42 +0200699 if name in PSA_UNSTABLE_FEATURE:
Gabor Mezeiee521b62024-06-07 13:50:41 +0200700 raise ValueError(f'Feature is unstable: \'{name}\'')
701
Gabor Mezeid723b512024-06-07 15:31:52 +0200702 # The default value in the crypto config is '1'
703 if not value:
704 value = '1'
705
Gabor Mezei8a64d8e2024-06-10 15:23:43 +0200706 if name in self.settings:
707 setting = self.settings[name]
708 if not setting.active or (value is not None and setting.value != value):
709 configfile.modified = True
710 else:
Gabor Mezeiee521b62024-06-07 13:50:41 +0200711 configfile.templates.append((name, '', '#define ' + name + ' '))
Gabor Mezei8a64d8e2024-06-10 15:23:43 +0200712 configfile.modified = True
Gabor Mezeiee521b62024-06-07 13:50:41 +0200713
714 super().set(name, value)
715
Gabor Mezei3678dee2024-06-04 19:58:43 +0200716 def write(self, mbedtls_file=None, crypto_file=None):
Gabor Mezei62a9bd02024-06-07 13:44:40 +0200717 """Write the whole configuration to the file it was read from.
718
719 If mbedtls_file or crypto_file is specified, write the specific configuration
720 to the corresponding file instead.
721 """
Gabor Mezei4706fe72024-07-08 17:00:55 +0200722
Gabor Mezeiee521b62024-06-07 13:50:41 +0200723 self.mbedtls_configfile.write(self.settings, mbedtls_file)
724 self.crypto_configfile.write(self.settings, crypto_file)
Gabor Mezei3678dee2024-06-04 19:58:43 +0200725
Gabor Mezeiee521b62024-06-07 13:50:41 +0200726 def filename(self, name=None):
Gabor Mezei4706fe72024-07-08 17:00:55 +0200727 """Get the names of the config files.
728
729 If 'name' is specified return the name of the config file where it is defined.
730 """
731
Gabor Mezeiee521b62024-06-07 13:50:41 +0200732 if not name:
733 return [config.filename for config in [self.mbedtls_configfile, self.crypto_configfile]]
734
735 return self._get_configfile(name).filename
Gilles Peskineb4063892019-07-27 21:36:44 +0200736
737if __name__ == '__main__':
Gabor Mezei92065ed2024-06-07 13:47:59 +0200738 #pylint: disable=too-many-statements
Gilles Peskineb4063892019-07-27 21:36:44 +0200739 def main():
Bence Szépkútibb0cfeb2021-05-28 09:42:25 +0200740 """Command line mbedtls_config.h manipulation tool."""
Gilles Peskineb4063892019-07-27 21:36:44 +0200741 parser = argparse.ArgumentParser(description="""
Fredrik Hesse0ec8a902021-10-04 22:13:51 +0200742 Mbed TLS configuration file manipulation tool.
Gilles Peskineb4063892019-07-27 21:36:44 +0200743 """)
744 parser.add_argument('--file', '-f',
745 help="""File to read (and modify if requested).
746 Default: {}.
Gabor Mezeif77722d2024-06-28 16:49:33 +0200747 """.format(MbedTLSConfigFile.default_path))
Gabor Mezei3678dee2024-06-04 19:58:43 +0200748 parser.add_argument('--cryptofile', '-c',
749 help="""Crypto file to read (and modify if requested).
750 Default: {}.
751 """.format(CryptoConfigFile.default_path))
Gilles Peskineb4063892019-07-27 21:36:44 +0200752 parser.add_argument('--force', '-o',
Gilles Peskine435ce222019-08-01 23:13:47 +0200753 action='store_true',
Gilles Peskineb4063892019-07-27 21:36:44 +0200754 help="""For the set command, if SYMBOL is not
755 present, add a definition for it.""")
Gilles Peskinec190c902019-08-01 23:31:05 +0200756 parser.add_argument('--write', '-w', metavar='FILE',
Gilles Peskine40f103c2019-07-27 23:44:01 +0200757 help="""File to write to instead of the input file.""")
Gilles Peskineb4063892019-07-27 21:36:44 +0200758 subparsers = parser.add_subparsers(dest='command',
759 title='Commands')
760 parser_get = subparsers.add_parser('get',
761 help="""Find the value of SYMBOL
762 and print it. Exit with
763 status 0 if a #define for SYMBOL is
764 found, 1 otherwise.
765 """)
766 parser_get.add_argument('symbol', metavar='SYMBOL')
767 parser_set = subparsers.add_parser('set',
768 help="""Set SYMBOL to VALUE.
769 If VALUE is omitted, just uncomment
770 the #define for SYMBOL.
771 Error out of a line defining
772 SYMBOL (commented or not) is not
773 found, unless --force is passed.
774 """)
775 parser_set.add_argument('symbol', metavar='SYMBOL')
Gilles Peskine0c7fcd22019-08-01 23:14:00 +0200776 parser_set.add_argument('value', metavar='VALUE', nargs='?',
777 default='')
Gilles Peskine8e90cf42021-05-27 22:12:57 +0200778 parser_set_all = subparsers.add_parser('set-all',
779 help="""Uncomment all #define
780 whose name contains a match for
781 REGEX.""")
782 parser_set_all.add_argument('regexs', metavar='REGEX', nargs='*')
Gilles Peskineb4063892019-07-27 21:36:44 +0200783 parser_unset = subparsers.add_parser('unset',
784 help="""Comment out the #define
785 for SYMBOL. Do nothing if none
786 is present.""")
787 parser_unset.add_argument('symbol', metavar='SYMBOL')
Gilles Peskine8e90cf42021-05-27 22:12:57 +0200788 parser_unset_all = subparsers.add_parser('unset-all',
789 help="""Comment out all #define
790 whose name contains a match for
791 REGEX.""")
792 parser_unset_all.add_argument('regexs', metavar='REGEX', nargs='*')
Gilles Peskineb4063892019-07-27 21:36:44 +0200793
794 def add_adapter(name, function, description):
795 subparser = subparsers.add_parser(name, help=description)
796 subparser.set_defaults(adapter=function)
Gilles Peskine53d41ae2019-07-27 23:31:53 +0200797 add_adapter('baremetal', baremetal_adapter,
798 """Like full, but exclude features that require platform
799 features such as file input-output.""")
Gilles Peskine120f29d2021-09-01 19:51:19 +0200800 add_adapter('baremetal_size', baremetal_size_adapter,
801 """Like baremetal, but exclude debugging features.
802 Useful for code size measurements.""")
Gilles Peskine53d41ae2019-07-27 23:31:53 +0200803 add_adapter('full', full_adapter,
804 """Uncomment most features.
805 Exclude alternative implementations and platform support
806 options, as well as some options that are awkward to test.
807 """)
Gilles Peskine30de2e82020-04-20 21:39:22 +0200808 add_adapter('full_no_deprecated', no_deprecated_adapter(full_adapter),
Gilles Peskinebe1d6092020-04-12 14:17:16 +0200809 """Uncomment most non-deprecated features.
810 Like "full", but without deprecated features.
811 """)
Paul Elliottfb81f772023-10-18 17:44:59 +0100812 add_adapter('full_no_platform', no_platform_adapter(full_adapter),
813 """Uncomment most non-platform features.
814 Like "full", but without platform features.
815 """)
Gilles Peskineb4063892019-07-27 21:36:44 +0200816 add_adapter('realfull', realfull_adapter,
Gilles Peskine53d41ae2019-07-27 23:31:53 +0200817 """Uncomment all boolean #defines.
818 Suitable for generating documentation, but not for building.""")
Gilles Peskine31987c62020-01-31 14:23:30 +0100819 add_adapter('crypto', crypto_adapter(None),
820 """Only include crypto features. Exclude X.509 and TLS.""")
821 add_adapter('crypto_baremetal', crypto_adapter(baremetal_adapter),
822 """Like baremetal, but with only crypto features,
823 excluding X.509 and TLS.""")
824 add_adapter('crypto_full', crypto_adapter(full_adapter),
825 """Like full, but with only crypto features,
826 excluding X.509 and TLS.""")
Gilles Peskineb4063892019-07-27 21:36:44 +0200827
828 args = parser.parse_args()
Gabor Mezei33dd2932024-06-28 17:51:58 +0200829 config = CombinedConfig(MbedTLSConfigFile(args.file), CryptoConfigFile(args.cryptofile))
Gilles Peskine90b30b62019-07-28 00:36:53 +0200830 if args.command is None:
831 parser.print_help()
832 return 1
833 elif args.command == 'get':
Gilles Peskineb4063892019-07-27 21:36:44 +0200834 if args.symbol in config:
835 value = config[args.symbol]
836 if value:
837 sys.stdout.write(value + '\n')
Gilles Peskinee22a4da2020-03-24 15:43:49 +0100838 return 0 if args.symbol in config else 1
Gilles Peskineb4063892019-07-27 21:36:44 +0200839 elif args.command == 'set':
Gilles Peskine98eb3652019-07-28 16:39:19 +0200840 if not args.force and args.symbol not in config.settings:
Gilles Peskineb4063892019-07-27 21:36:44 +0200841 sys.stderr.write("A #define for the symbol {} "
Gilles Peskine221df1e2019-08-01 23:14:29 +0200842 "was not found in {}\n"
Gabor Mezei3678dee2024-06-04 19:58:43 +0200843 .format(args.symbol, config.filename(args.symbol)))
Gilles Peskineb4063892019-07-27 21:36:44 +0200844 return 1
845 config.set(args.symbol, value=args.value)
Gilles Peskine8e90cf42021-05-27 22:12:57 +0200846 elif args.command == 'set-all':
847 config.change_matching(args.regexs, True)
Gilles Peskineb4063892019-07-27 21:36:44 +0200848 elif args.command == 'unset':
849 config.unset(args.symbol)
Gilles Peskine8e90cf42021-05-27 22:12:57 +0200850 elif args.command == 'unset-all':
851 config.change_matching(args.regexs, False)
Gilles Peskineb4063892019-07-27 21:36:44 +0200852 else:
853 config.adapt(args.adapter)
Gilles Peskine40f103c2019-07-27 23:44:01 +0200854 config.write(args.write)
Gilles Peskinee22a4da2020-03-24 15:43:49 +0100855 return 0
Gilles Peskineb4063892019-07-27 21:36:44 +0200856
857 # Import modules only used by main only if main is defined and called.
858 # pylint: disable=wrong-import-position
859 import argparse
860 import sys
861 sys.exit(main())