blob: 132b2d4479678f762b7b6d6640cbc79e2ca0b871 [file] [log] [blame]
Gilles Peskineb4063892019-07-27 21:36:44 +02001#!/usr/bin/env python3
2
3"""Mbed TLS configuration file manipulation library and tool
4
Fredrik Hessecc207bc2021-09-28 21:06:08 +02005Basic usage, to read the Mbed TLS configuration:
Gilles Peskineb4063892019-07-27 21:36:44 +02006 config = ConfigFile()
7 if 'MBEDTLS_RSA_C' in config: print('RSA is enabled')
8"""
9
Gilles Peskinecf425362022-10-10 22:52:30 +020010# Note that as long as Mbed TLS 2.28 LTS is maintained, the version of
11# this script in the mbedtls-2.28 branch must remain compatible with
12# Python 3.4. The version in development may only use more recent features
13# in parts that are not backported to 2.28.
14
Bence Szépkúti1e148272020-08-07 13:07:28 +020015## Copyright The Mbed TLS Contributors
Dave Rodgman16799db2023-11-02 19:47:20 +000016## SPDX-License-Identifier: Apache-2.0 OR GPL-2.0-or-later
Gilles Peskineb4063892019-07-27 21:36:44 +020017##
Gilles Peskineb4063892019-07-27 21:36:44 +020018
Gilles Peskine208e4ec2019-07-29 23:43:20 +020019import os
Gilles Peskineb4063892019-07-27 21:36:44 +020020import re
21
Gabor Mezeie7742b32024-06-26 18:04:09 +020022from abc import ABCMeta
Gabor Mezei3678dee2024-06-04 19:58:43 +020023
Gilles Peskineb4063892019-07-27 21:36:44 +020024class Setting:
Bence Szépkútibb0cfeb2021-05-28 09:42:25 +020025 """Representation of one Mbed TLS mbedtls_config.h setting.
Gilles Peskineb4063892019-07-27 21:36:44 +020026
27 Fields:
28 * name: the symbol name ('MBEDTLS_xxx').
29 * value: the value of the macro. The empty string for a plain #define
30 with no value.
31 * active: True if name is defined, False if a #define for name is
Bence Szépkútibb0cfeb2021-05-28 09:42:25 +020032 present in mbedtls_config.h but commented out.
Gilles Peskine53d41ae2019-07-27 23:31:53 +020033 * section: the name of the section that contains this symbol.
Gilles Peskineb4063892019-07-27 21:36:44 +020034 """
Gabor Mezei92065ed2024-06-07 13:47:59 +020035 # pylint: disable=too-few-public-methods, too-many-arguments
Gabor Mezei3678dee2024-06-04 19:58:43 +020036 def __init__(self, active, name, value='', section=None, configfile=None):
Gilles Peskineb4063892019-07-27 21:36:44 +020037 self.active = active
38 self.name = name
39 self.value = value
Gilles Peskine53d41ae2019-07-27 23:31:53 +020040 self.section = section
Gabor Mezei3678dee2024-06-04 19:58:43 +020041 self.configfile = configfile
Gilles Peskineb4063892019-07-27 21:36:44 +020042
43class Config:
44 """Representation of the Mbed TLS configuration.
45
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 Mezei92065ed2024-06-07 13:47:59 +020060 # pylint: disable=unused-argument
Gabor Mezeiee521b62024-06-07 13:50:41 +020061 def __init__(self):
Gilles Peskineb4063892019-07-27 21:36:44 +020062 self.settings = {}
63
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)."""
74 return all(self.__contains__(name) for name in names)
75
76 def any(self, *names):
77 """True if at least one symbol in names are active (i.e. set)."""
78 return any(self.__contains__(name) for name in names)
79
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 """
109 self.settings[name].value = value
110
111 def set(self, name, value=None):
112 """Set name to the given value and make it active.
113
114 If value is None and name is already known, don't change its value.
115 If value is None and name is not known, set its value to the empty
116 string.
117 """
118 if name in self.settings:
119 if value is not None:
120 self.settings[name].value = value
121 self.settings[name].active = True
122 else:
123 self.settings[name] = Setting(True, name, value=value)
124
125 def unset(self, name):
126 """Make name unset (inactive).
127
Gilles Peskine55cc4db2019-08-01 23:13:23 +0200128 name remains known if it was known before.
Gilles Peskineb4063892019-07-27 21:36:44 +0200129 """
Gilles Peskine55cc4db2019-08-01 23:13:23 +0200130 if name not in self.settings:
131 return
Gabor Mezeic5ff33c2024-06-28 17:46:44 +0200132
133 setting = self.settings[name]
134 # Check if modifying the config file
135 if setting.configfile and setting.active:
136 setting.configfile.modified = True
137
138 setting.active = False
Gilles Peskineb4063892019-07-27 21:36:44 +0200139
140 def adapt(self, adapter):
141 """Run adapter on each known symbol and (de)activate it accordingly.
142
143 `adapter` must be a function that returns a boolean. It is called as
Gilles Peskine53d41ae2019-07-27 23:31:53 +0200144 `adapter(name, active, section)` for each setting, where `active` is
145 `True` if `name` is set and `False` if `name` is known but unset,
146 and `section` is the name of the section containing `name`. If
Gilles Peskineb4063892019-07-27 21:36:44 +0200147 `adapter` returns `True`, then set `name` (i.e. make it active),
148 otherwise unset `name` (i.e. make it known but inactive).
149 """
150 for setting in self.settings.values():
Gabor Mezeic5ff33c2024-06-28 17:46:44 +0200151 is_active = setting.active
Gilles Peskine53d41ae2019-07-27 23:31:53 +0200152 setting.active = adapter(setting.name, setting.active,
153 setting.section)
Gabor Mezeic5ff33c2024-06-28 17:46:44 +0200154 # Check if modifying the config file
155 if setting.configfile and setting.active != is_active:
156 setting.configfile.modified = True
Gilles Peskineb4063892019-07-27 21:36:44 +0200157
Gilles Peskine8e90cf42021-05-27 22:12:57 +0200158 def change_matching(self, regexs, enable):
159 """Change all symbols matching one of the regexs to the desired state."""
160 if not regexs:
161 return
162 regex = re.compile('|'.join(regexs))
163 for setting in self.settings.values():
164 if regex.search(setting.name):
Gabor Mezeic5ff33c2024-06-28 17:46:44 +0200165 # Check if modifying the config file
166 if setting.configfile and setting.active != enable:
167 setting.configfile.modified = True
Gilles Peskine8e90cf42021-05-27 22:12:57 +0200168 setting.active = enable
169
Gilles Peskine53d41ae2019-07-27 23:31:53 +0200170def is_full_section(section):
Gabor Mezeide6e1922024-06-28 17:10:50 +0200171 """Is this section affected by "config.py full" and friends?
172
173 In a config file where the sections are not used the whole config file
174 is an empty section (with value None) and the whole file is affected.
175 """
Gabor Mezei3678dee2024-06-04 19:58:43 +0200176 return section is None or section.endswith('support') or section.endswith('modules')
Gilles Peskine53d41ae2019-07-27 23:31:53 +0200177
178def realfull_adapter(_name, active, section):
Gilles Peskineba4162a2022-04-11 17:04:38 +0200179 """Activate all symbols found in the global and boolean feature sections.
180
181 This is intended for building the documentation, including the
182 documentation of settings that are activated by defining an optional
183 preprocessor macro.
184
185 Do not activate definitions in the section containing symbols that are
186 supposed to be defined and documented in their own module.
187 """
188 if section == 'Module configuration options':
Gilles Peskine53d41ae2019-07-27 23:31:53 +0200189 return active
Gilles Peskineb4063892019-07-27 21:36:44 +0200190 return True
191
Gabor Mezei542fd382024-06-10 14:07:42 +0200192PSA_UNSUPPORTED_FEATURE = frozenset([
Gabor Mezei3678dee2024-06-04 19:58:43 +0200193 'PSA_WANT_ALG_CBC_MAC',
194 'PSA_WANT_ALG_XTS',
195 'PSA_WANT_KEY_TYPE_RSA_KEY_PAIR_DERIVE',
196 'PSA_WANT_KEY_TYPE_DH_KEY_PAIR_DERIVE'
197])
198
Gabor Mezei542fd382024-06-10 14:07:42 +0200199PSA_DEPRECATED_FEATURE = frozenset([
Gabor Mezei3678dee2024-06-04 19:58:43 +0200200 'PSA_WANT_KEY_TYPE_ECC_KEY_PAIR',
201 'PSA_WANT_KEY_TYPE_RSA_KEY_PAIR'
202])
203
Gabor Mezei542fd382024-06-10 14:07:42 +0200204PSA_UNSTABLE_FEATURE = frozenset([
Gabor Mezei3678dee2024-06-04 19:58:43 +0200205 'PSA_WANT_ECC_SECP_K1_224'
206])
207
Gabor Mezei9b0f9e72024-06-26 18:08:17 +0200208EXCLUDE_FROM_CRYPTO = PSA_UNSUPPORTED_FEATURE | \
209 PSA_DEPRECATED_FEATURE | \
210 PSA_UNSTABLE_FEATURE
Gabor Mezei542fd382024-06-10 14:07:42 +0200211
Gilles Peskinecfffc282020-04-12 13:55:45 +0200212# The goal of the full configuration is to have everything that can be tested
213# together. This includes deprecated or insecure options. It excludes:
214# * Options that require additional build dependencies or unusual hardware.
215# * Options that make testing less effective.
Gilles Peskinec9d04332020-04-16 20:50:17 +0200216# * Options that are incompatible with other options, or more generally that
217# interact with other parts of the code in such a way that a bulk enabling
218# is not a good way to test them.
Gilles Peskinecfffc282020-04-12 13:55:45 +0200219# * Options that remove features.
Gilles Peskinebbaa2b72020-04-12 13:33:57 +0200220EXCLUDE_FROM_FULL = frozenset([
Gilles Peskinecfffc282020-04-12 13:55:45 +0200221 #pylint: disable=line-too-long
Yanray Wanga8704672023-04-20 17:16:48 +0800222 'MBEDTLS_AES_ONLY_128_BIT_KEY_LENGTH', # interacts with CTR_DRBG_128_BIT_KEY
Gilles Peskinea8861e02023-09-05 20:20:51 +0200223 'MBEDTLS_AES_USE_HARDWARE_ONLY', # hardware dependency
Yanray Wang42be1ba2023-11-23 14:28:47 +0800224 'MBEDTLS_BLOCK_CIPHER_NO_DECRYPT', # incompatible with ECB in PSA, CBC/XTS/NIST_KW/DES
Gilles Peskinec9d04332020-04-16 20:50:17 +0200225 'MBEDTLS_CTR_DRBG_USE_128_BIT_KEY', # interacts with ENTROPY_FORCE_SHA256
Gilles Peskinecfffc282020-04-12 13:55:45 +0200226 'MBEDTLS_DEPRECATED_REMOVED', # conflicts with deprecated options
Gilles Peskine90581ee2020-04-12 14:02:47 +0200227 'MBEDTLS_DEPRECATED_WARNING', # conflicts with deprecated options
Gilles Peskinec9d04332020-04-16 20:50:17 +0200228 'MBEDTLS_ECDH_VARIANT_EVEREST_ENABLED', # influences the use of ECDH in TLS
Janos Follath5b7c38f2023-08-01 08:51:12 +0100229 'MBEDTLS_ECP_WITH_MPI_UINT', # disables the default ECP and is experimental
Gilles Peskinec9d04332020-04-16 20:50:17 +0200230 'MBEDTLS_ENTROPY_FORCE_SHA256', # interacts with CTR_DRBG_128_BIT_KEY
Gilles Peskinecfffc282020-04-12 13:55:45 +0200231 'MBEDTLS_HAVE_SSE2', # hardware dependency
232 'MBEDTLS_MEMORY_BACKTRACE', # depends on MEMORY_BUFFER_ALLOC_C
233 'MBEDTLS_MEMORY_BUFFER_ALLOC_C', # makes sanitizers (e.g. ASan) less effective
234 'MBEDTLS_MEMORY_DEBUG', # depends on MEMORY_BUFFER_ALLOC_C
Gilles Peskinec9d04332020-04-16 20:50:17 +0200235 'MBEDTLS_NO_64BIT_MULTIPLICATION', # influences anything that uses bignum
Gilles Peskinecfffc282020-04-12 13:55:45 +0200236 'MBEDTLS_NO_DEFAULT_ENTROPY_SOURCES', # removes a feature
237 'MBEDTLS_NO_PLATFORM_ENTROPY', # removes a feature
Gilles Peskinec9d04332020-04-16 20:50:17 +0200238 'MBEDTLS_NO_UDBL_DIVISION', # influences anything that uses bignum
Gilles Peskineefaee9a2023-09-20 20:49:47 +0200239 'MBEDTLS_PSA_P256M_DRIVER_ENABLED', # influences SECP256R1 KeyGen/ECDH/ECDSA
Gilles Peskinecfffc282020-04-12 13:55:45 +0200240 'MBEDTLS_PLATFORM_NO_STD_FUNCTIONS', # removes a feature
David Horstmann6f8c95b2024-03-14 14:52:45 +0000241 'MBEDTLS_PSA_ASSUME_EXCLUSIVE_BUFFERS', # removes a feature
Gilles Peskinef08b3f82020-11-13 17:36:48 +0100242 'MBEDTLS_PSA_CRYPTO_EXTERNAL_RNG', # behavior change + build dependency
Ronald Cronc3623db2020-10-29 10:51:32 +0100243 'MBEDTLS_PSA_CRYPTO_KEY_ID_ENCODES_OWNER', # incompatible with USE_PSA_CRYPTO
Gilles Peskinecfffc282020-04-12 13:55:45 +0200244 'MBEDTLS_PSA_CRYPTO_SPM', # platform dependency (PSA SPM)
Gilles Peskinea08def92023-04-28 21:01:49 +0200245 'MBEDTLS_PSA_INJECT_ENTROPY', # conflicts with platform entropy sources
Gilles Peskinec9d04332020-04-16 20:50:17 +0200246 'MBEDTLS_RSA_NO_CRT', # influences the use of RSA in X.509 and TLS
Tom Cosgrove87fbfb52022-03-15 10:51:52 +0000247 'MBEDTLS_SHA256_USE_A64_CRYPTO_ONLY', # interacts with *_USE_A64_CRYPTO_IF_PRESENT
Dave Rodgman9be3cf02023-10-11 14:47:55 +0100248 'MBEDTLS_SHA256_USE_ARMV8_A_CRYPTO_ONLY', # interacts with *_USE_ARMV8_A_CRYPTO_IF_PRESENT
Tom Cosgrove87fbfb52022-03-15 10:51:52 +0000249 'MBEDTLS_SHA512_USE_A64_CRYPTO_ONLY', # interacts with *_USE_A64_CRYPTO_IF_PRESENT
Dave Rodgman7cb635a2023-10-12 16:14:51 +0100250 'MBEDTLS_SHA256_USE_A64_CRYPTO_IF_PRESENT', # setting *_USE_ARMV8_A_CRYPTO is sufficient
Manuel Pégourié-Gonnard6240def2020-07-10 09:35:54 +0200251 'MBEDTLS_TEST_CONSTANT_FLOW_MEMSAN', # build dependency (clang+memsan)
Manuel Pégourié-Gonnard73afa372020-08-19 10:27:38 +0200252 'MBEDTLS_TEST_CONSTANT_FLOW_VALGRIND', # build dependency (valgrind headers)
Hanno Beckere1113562019-06-12 13:59:14 +0100253 'MBEDTLS_X509_REMOVE_INFO', # removes a feature
Gabor Mezei542fd382024-06-10 14:07:42 +0200254 *PSA_UNSUPPORTED_FEATURE,
255 *PSA_DEPRECATED_FEATURE,
256 *PSA_UNSTABLE_FEATURE
Gilles Peskinebbaa2b72020-04-12 13:33:57 +0200257])
258
Gilles Peskine32e889d2020-04-12 23:43:28 +0200259def is_seamless_alt(name):
Gilles Peskinec34faba2020-04-20 15:44:14 +0200260 """Whether the xxx_ALT symbol should be included in the full configuration.
Gilles Peskine32e889d2020-04-12 23:43:28 +0200261
Gilles Peskinec34faba2020-04-20 15:44:14 +0200262 Include alternative implementations of platform functions, which are
Gilles Peskine32e889d2020-04-12 23:43:28 +0200263 configurable function pointers that default to the built-in function.
264 This way we test that the function pointers exist and build correctly
265 without changing the behavior, and tests can verify that the function
266 pointers are used by modifying those pointers.
267
268 Exclude alternative implementations of library functions since they require
269 an implementation of the relevant functions and an xxx_alt.h header.
270 """
Gilles Peskinea8861e02023-09-05 20:20:51 +0200271 if name in (
272 'MBEDTLS_PLATFORM_GMTIME_R_ALT',
273 'MBEDTLS_PLATFORM_SETUP_TEARDOWN_ALT',
274 'MBEDTLS_PLATFORM_MS_TIME_ALT',
275 'MBEDTLS_PLATFORM_ZEROIZE_ALT',
276 ):
Gilles Peskinec34faba2020-04-20 15:44:14 +0200277 # Similar to non-platform xxx_ALT, requires platform_alt.h
278 return False
Gilles Peskine32e889d2020-04-12 23:43:28 +0200279 return name.startswith('MBEDTLS_PLATFORM_')
280
Gilles Peskine53d41ae2019-07-27 23:31:53 +0200281def include_in_full(name):
282 """Rules for symbols in the "full" configuration."""
Gabor Mezei542fd382024-06-10 14:07:42 +0200283 if name in EXCLUDE_FROM_FULL:
Gilles Peskine53d41ae2019-07-27 23:31:53 +0200284 return False
285 if name.endswith('_ALT'):
Gilles Peskine32e889d2020-04-12 23:43:28 +0200286 return is_seamless_alt(name)
Gilles Peskine53d41ae2019-07-27 23:31:53 +0200287 return True
288
289def full_adapter(name, active, section):
290 """Config adapter for "full"."""
291 if not is_full_section(section):
292 return active
293 return include_in_full(name)
294
Gilles Peskinecfffc282020-04-12 13:55:45 +0200295# The baremetal configuration excludes options that require a library or
296# operating system feature that is typically not present on bare metal
297# systems. Features that are excluded from "full" won't be in "baremetal"
298# either (unless explicitly turned on in baremetal_adapter) so they don't
299# need to be repeated here.
Gilles Peskinebbaa2b72020-04-12 13:33:57 +0200300EXCLUDE_FROM_BAREMETAL = frozenset([
Gilles Peskinecfffc282020-04-12 13:55:45 +0200301 #pylint: disable=line-too-long
Gilles Peskine98f8f952020-04-20 15:38:39 +0200302 'MBEDTLS_ENTROPY_NV_SEED', # requires a filesystem and FS_IO or alternate NV seed hooks
Gilles Peskinecfffc282020-04-12 13:55:45 +0200303 'MBEDTLS_FS_IO', # requires a filesystem
Gilles Peskinecfffc282020-04-12 13:55:45 +0200304 'MBEDTLS_HAVE_TIME', # requires a clock
305 'MBEDTLS_HAVE_TIME_DATE', # requires a clock
306 'MBEDTLS_NET_C', # requires POSIX-like networking
307 'MBEDTLS_PLATFORM_FPRINTF_ALT', # requires FILE* from stdio.h
Gilles Peskine98f8f952020-04-20 15:38:39 +0200308 'MBEDTLS_PLATFORM_NV_SEED_ALT', # requires a filesystem and ENTROPY_NV_SEED
309 'MBEDTLS_PLATFORM_TIME_ALT', # requires a clock and HAVE_TIME
310 'MBEDTLS_PSA_CRYPTO_SE_C', # requires a filesystem and PSA_CRYPTO_STORAGE_C
Gilles Peskinecfffc282020-04-12 13:55:45 +0200311 'MBEDTLS_PSA_CRYPTO_STORAGE_C', # requires a filesystem
312 'MBEDTLS_PSA_ITS_FILE_C', # requires a filesystem
313 'MBEDTLS_THREADING_C', # requires a threading interface
314 'MBEDTLS_THREADING_PTHREAD', # requires pthread
315 'MBEDTLS_TIMING_C', # requires a clock
Dave Rodgman9be3cf02023-10-11 14:47:55 +0100316 'MBEDTLS_SHA256_USE_A64_CRYPTO_IF_PRESENT', # requires an OS for runtime-detection
Dave Rodgman5b89c552023-10-10 14:59:02 +0100317 'MBEDTLS_SHA256_USE_ARMV8_A_CRYPTO_IF_PRESENT', # requires an OS for runtime-detection
Dave Rodgmanbe7915a2023-10-11 10:46:38 +0100318 'MBEDTLS_SHA512_USE_A64_CRYPTO_IF_PRESENT', # requires an OS for runtime-detection
Gilles Peskinebbaa2b72020-04-12 13:33:57 +0200319])
320
Gilles Peskine53d41ae2019-07-27 23:31:53 +0200321def keep_in_baremetal(name):
322 """Rules for symbols in the "baremetal" configuration."""
Gilles Peskinebbaa2b72020-04-12 13:33:57 +0200323 if name in EXCLUDE_FROM_BAREMETAL:
Gilles Peskine53d41ae2019-07-27 23:31:53 +0200324 return False
325 return True
326
327def baremetal_adapter(name, active, section):
328 """Config adapter for "baremetal"."""
329 if not is_full_section(section):
330 return active
331 if name == 'MBEDTLS_NO_PLATFORM_ENTROPY':
Gilles Peskinecfffc282020-04-12 13:55:45 +0200332 # No OS-provided entropy source
Gilles Peskine53d41ae2019-07-27 23:31:53 +0200333 return True
334 return include_in_full(name) and keep_in_baremetal(name)
335
Gilles Peskine120f29d2021-09-01 19:51:19 +0200336# This set contains options that are mostly for debugging or test purposes,
337# and therefore should be excluded when doing code size measurements.
338# Options that are their own module (such as MBEDTLS_ERROR_C) are not listed
339# and therefore will be included when doing code size measurements.
340EXCLUDE_FOR_SIZE = frozenset([
341 'MBEDTLS_DEBUG_C', # large code size increase in TLS
342 'MBEDTLS_SELF_TEST', # increases the size of many modules
343 'MBEDTLS_TEST_HOOKS', # only useful with the hosted test framework, increases code size
344])
345
346def baremetal_size_adapter(name, active, section):
347 if name in EXCLUDE_FOR_SIZE:
348 return False
349 return baremetal_adapter(name, active, section)
350
Gilles Peskine31987c62020-01-31 14:23:30 +0100351def include_in_crypto(name):
352 """Rules for symbols in a crypto configuration."""
353 if name.startswith('MBEDTLS_X509_') or \
354 name.startswith('MBEDTLS_SSL_') or \
355 name.startswith('MBEDTLS_KEY_EXCHANGE_'):
356 return False
357 if name in [
Gilles Peskinecfffc282020-04-12 13:55:45 +0200358 'MBEDTLS_DEBUG_C', # part of libmbedtls
359 'MBEDTLS_NET_C', # part of libmbedtls
Nayna Jainc9deb182020-11-16 19:03:12 +0000360 'MBEDTLS_PKCS7_C', # part of libmbedx509
Gilles Peskine31987c62020-01-31 14:23:30 +0100361 ]:
362 return False
Gabor Mezei542fd382024-06-10 14:07:42 +0200363 if name in EXCLUDE_FROM_CRYPTO:
364 return False
Gilles Peskine31987c62020-01-31 14:23:30 +0100365 return True
366
367def crypto_adapter(adapter):
368 """Modify an adapter to disable non-crypto symbols.
369
370 ``crypto_adapter(adapter)(name, active, section)`` is like
371 ``adapter(name, active, section)``, but unsets all X.509 and TLS symbols.
372 """
373 def continuation(name, active, section):
374 if not include_in_crypto(name):
375 return False
376 if adapter is None:
377 return active
378 return adapter(name, active, section)
379 return continuation
380
Gilles Peskineed5c21d2022-06-27 23:02:09 +0200381DEPRECATED = frozenset([
382 'MBEDTLS_PSA_CRYPTO_SE_C',
Gabor Mezei542fd382024-06-10 14:07:42 +0200383 *PSA_DEPRECATED_FEATURE
Gilles Peskineed5c21d2022-06-27 23:02:09 +0200384])
Gilles Peskine30de2e82020-04-20 21:39:22 +0200385def no_deprecated_adapter(adapter):
Gilles Peskinebe1d6092020-04-12 14:17:16 +0200386 """Modify an adapter to disable deprecated symbols.
387
Gilles Peskine30de2e82020-04-20 21:39:22 +0200388 ``no_deprecated_adapter(adapter)(name, active, section)`` is like
Gilles Peskinebe1d6092020-04-12 14:17:16 +0200389 ``adapter(name, active, section)``, but unsets all deprecated symbols
390 and sets ``MBEDTLS_DEPRECATED_REMOVED``.
391 """
392 def continuation(name, active, section):
393 if name == 'MBEDTLS_DEPRECATED_REMOVED':
394 return True
Gilles Peskineed5c21d2022-06-27 23:02:09 +0200395 if name in DEPRECATED:
396 return False
Gilles Peskinebe1d6092020-04-12 14:17:16 +0200397 if adapter is None:
398 return active
399 return adapter(name, active, section)
400 return continuation
401
Paul Elliottfb81f772023-10-18 17:44:59 +0100402def no_platform_adapter(adapter):
403 """Modify an adapter to disable platform symbols.
404
405 ``no_platform_adapter(adapter)(name, active, section)`` is like
406 ``adapter(name, active, section)``, but unsets all platform symbols other
407 ``than MBEDTLS_PLATFORM_C.
408 """
409 def continuation(name, active, section):
410 # Allow MBEDTLS_PLATFORM_C but remove all other platform symbols.
411 if name.startswith('MBEDTLS_PLATFORM_') and name != 'MBEDTLS_PLATFORM_C':
412 return False
413 if adapter is None:
414 return active
415 return adapter(name, active, section)
416 return continuation
417
Gabor Mezei3678dee2024-06-04 19:58:43 +0200418class ConfigFile(metaclass=ABCMeta):
Gabor Mezei62a9bd02024-06-07 13:44:40 +0200419 """Representation of a configuration file."""
420
Gabor Mezei93a6d1f2024-06-26 18:01:09 +0200421 def __init__(self, default_path, name, filename=None):
Gabor Mezei62a9bd02024-06-07 13:44:40 +0200422 """Check if the config file exists."""
Gilles Peskineb4063892019-07-27 21:36:44 +0200423 if filename is None:
Gabor Mezei3678dee2024-06-04 19:58:43 +0200424 for candidate in default_path:
Gilles Peskinece674a92020-03-24 15:37:00 +0100425 if os.path.lexists(candidate):
426 filename = candidate
Gilles Peskine208e4ec2019-07-29 23:43:20 +0200427 break
Gilles Peskinece674a92020-03-24 15:37:00 +0100428 else:
Gabor Mezei8d72ac62024-06-28 17:18:37 +0200429 raise FileNotFoundError(f'{name} configuration file not found: '
430 f'{filename if filename else default_path}')
Gilles Peskineb4063892019-07-27 21:36:44 +0200431
Gabor Mezei3678dee2024-06-04 19:58:43 +0200432 self.filename = filename
433 self.templates = []
434 self.current_section = None
435 self.inclusion_guard = None
Gabor Mezei8a64d8e2024-06-10 15:23:43 +0200436 self.modified = False
Gilles Peskineb4063892019-07-27 21:36:44 +0200437
438 _define_line_regexp = (r'(?P<indentation>\s*)' +
439 r'(?P<commented_out>(//\s*)?)' +
440 r'(?P<define>#\s*define\s+)' +
441 r'(?P<name>\w+)' +
442 r'(?P<arguments>(?:\((?:\w|\s|,)*\))?)' +
443 r'(?P<separator>\s*)' +
444 r'(?P<value>.*)')
Gilles Peskine9ba9c212024-05-23 15:03:43 +0200445 _ifndef_line_regexp = r'#ifndef (?P<inclusion_guard>\w+)'
Gilles Peskine53d41ae2019-07-27 23:31:53 +0200446 _section_line_regexp = (r'\s*/?\*+\s*[\\@]name\s+SECTION:\s*' +
447 r'(?P<section>.*)[ */]*')
448 _config_line_regexp = re.compile(r'|'.join([_define_line_regexp,
Gilles Peskine9ba9c212024-05-23 15:03:43 +0200449 _ifndef_line_regexp,
Gilles Peskine53d41ae2019-07-27 23:31:53 +0200450 _section_line_regexp]))
Gilles Peskineb4063892019-07-27 21:36:44 +0200451 def _parse_line(self, line):
Gabor Mezei62a9bd02024-06-07 13:44:40 +0200452 """Parse a line in the config file, save the templates representing the lines
453 and return the corresponding setting element.
454 """
Gilles Peskineb4063892019-07-27 21:36:44 +0200455 line = line.rstrip('\r\n')
Gilles Peskine53d41ae2019-07-27 23:31:53 +0200456 m = re.match(self._config_line_regexp, line)
457 if m is None:
Gabor Mezei3678dee2024-06-04 19:58:43 +0200458 self.templates.append(line)
459 return None
Gilles Peskine53d41ae2019-07-27 23:31:53 +0200460 elif m.group('section'):
461 self.current_section = m.group('section')
Gabor Mezei3678dee2024-06-04 19:58:43 +0200462 self.templates.append(line)
463 return None
Gilles Peskine9ba9c212024-05-23 15:03:43 +0200464 elif m.group('inclusion_guard') and self.inclusion_guard is None:
465 self.inclusion_guard = m.group('inclusion_guard')
Gabor Mezei3678dee2024-06-04 19:58:43 +0200466 self.templates.append(line)
467 return None
Gilles Peskine53d41ae2019-07-27 23:31:53 +0200468 else:
Gilles Peskineb4063892019-07-27 21:36:44 +0200469 active = not m.group('commented_out')
470 name = m.group('name')
471 value = m.group('value')
Gilles Peskine9ba9c212024-05-23 15:03:43 +0200472 if name == self.inclusion_guard and value == '':
473 # The file double-inclusion guard is not an option.
Gabor Mezei3678dee2024-06-04 19:58:43 +0200474 self.templates.append(line)
475 return None
Gilles Peskineb4063892019-07-27 21:36:44 +0200476 template = (name,
477 m.group('indentation'),
478 m.group('define') + name +
479 m.group('arguments') + m.group('separator'))
Gabor Mezei3678dee2024-06-04 19:58:43 +0200480 self.templates.append(template)
Gilles Peskineb4063892019-07-27 21:36:44 +0200481
Gabor Mezei3678dee2024-06-04 19:58:43 +0200482 return (active, name, value, self.current_section)
483
484 def parse_file(self):
Gabor Mezei62a9bd02024-06-07 13:44:40 +0200485 """Parse the whole file and return the settings."""
Gabor Mezei3678dee2024-06-04 19:58:43 +0200486 with open(self.filename, 'r', encoding='utf-8') as file:
487 for line in file:
488 setting = self._parse_line(line)
489 if setting is not None:
490 yield setting
491 self.current_section = None
492
Gabor Mezeie7742b32024-06-26 18:04:09 +0200493 #pylint: disable=no-self-use
494 def _format_template(self, setting, indent, middle):
495 """Build a line for mbedtls_config.h for the given setting.
496
497 The line has the form "<indent>#define <name> <value>"
498 where <middle> is "#define <name> ".
499 """
500 value = setting.value
501 if value is None:
502 value = ''
503 # Normally the whitespace to separate the symbol name from the
504 # value is part of middle, and there's no whitespace for a symbol
505 # with no value. But if a symbol has been changed from having a
506 # value to not having one, the whitespace is wrong, so fix it.
507 if value:
508 if middle[-1] not in '\t ':
509 middle += ' '
510 else:
511 middle = middle.rstrip()
512 return ''.join([indent,
513 '' if setting.active else '//',
514 middle,
515 value]).rstrip()
Gabor Mezei3678dee2024-06-04 19:58:43 +0200516
517 def write_to_stream(self, settings, output):
518 """Write the whole configuration to output."""
519 for template in self.templates:
520 if isinstance(template, str):
521 line = template
522 else:
Gabor Mezeie7742b32024-06-26 18:04:09 +0200523 name, indent, middle = template
524 line = self._format_template(settings[name], indent, middle)
Gabor Mezei3678dee2024-06-04 19:58:43 +0200525 output.write(line + '\n')
526
527 def write(self, settings, filename=None):
528 """Write the whole configuration to the file it was read from.
529
530 If filename is specified, write to this file instead.
531 """
532 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 Mezei62a9bd02024-06-07 13:44:40 +0200558 """Representation of an Crypto configuration file."""
559
Gabor Mezei3678dee2024-06-04 19:58:43 +0200560 _path_in_tree = 'tf-psa-crypto/include/psa/crypto_config.h'
561 default_path = [_path_in_tree,
562 os.path.join(os.path.dirname(__file__),
563 os.pardir,
564 _path_in_tree),
565 os.path.join(os.path.dirname(os.path.abspath(os.path.dirname(__file__))),
566 _path_in_tree)]
567
568 def __init__(self, filename=None):
Gabor Mezei93a6d1f2024-06-26 18:01:09 +0200569 super().__init__(self.default_path, 'Crypto', filename)
Gabor Mezei3678dee2024-06-04 19:58:43 +0200570
Gabor Mezeif77722d2024-06-28 16:49:33 +0200571class MbedTLSConfig(Config):
Gabor Mezei62a9bd02024-06-07 13:44:40 +0200572 """Representation of the Mbed TLS configuration.
Gabor Mezei3678dee2024-06-04 19:58:43 +0200573
574 See the documentation of the `Config` class for methods to query
575 and modify the configuration.
576 """
Gabor Mezeiee521b62024-06-07 13:50:41 +0200577 def __init__(self, filename=None):
Gabor Mezei3678dee2024-06-04 19:58:43 +0200578 """Read the Mbed TLS configuration file."""
579 super().__init__()
Gabor Mezeif77722d2024-06-28 16:49:33 +0200580 self.configfile = MbedTLSConfigFile(filename)
Gabor Mezeic5ff33c2024-06-28 17:46:44 +0200581 self.settings.update({name: Setting(active, name, value, section, self.configfile)
Gabor Mezei92065ed2024-06-07 13:47:59 +0200582 for (active, name, value, section)
Gabor Mezeiee521b62024-06-07 13:50:41 +0200583 in self.configfile.parse_file()})
Gabor Mezei3678dee2024-06-04 19:58:43 +0200584
585 def set(self, name, value=None):
586 if name not in self.settings:
Gabor Mezeiee521b62024-06-07 13:50:41 +0200587 self.configfile.templates.append((name, '', '#define ' + name + ' '))
588
Gabor Mezei3678dee2024-06-04 19:58:43 +0200589 super().set(name, value)
Gilles Peskineb4063892019-07-27 21:36:44 +0200590
591 def write(self, filename=None):
Gabor Mezei62a9bd02024-06-07 13:44:40 +0200592 """Write the whole configuration to the file it was read from.
593
594 If filename is specified, write to this file instead.
595 """
Gabor Mezeiee521b62024-06-07 13:50:41 +0200596 self.configfile.write(self.settings, filename)
Gilles Peskineb4063892019-07-27 21:36:44 +0200597
Gabor Mezeiee521b62024-06-07 13:50:41 +0200598 def filename(self):
599 return self.configfile.filename
Gabor Mezei3678dee2024-06-04 19:58:43 +0200600
601class CryptoConfig(Config):
Gabor Mezei62a9bd02024-06-07 13:44:40 +0200602 """Representation of the PSA crypto configuration.
Gabor Mezei3678dee2024-06-04 19:58:43 +0200603
604 See the documentation of the `Config` class for methods to query
605 and modify the configuration.
606 """
Gabor Mezeiee521b62024-06-07 13:50:41 +0200607 def __init__(self, filename=None):
Gabor Mezei3678dee2024-06-04 19:58:43 +0200608 """Read the PSA crypto configuration file."""
609 super().__init__()
Gabor Mezeiee521b62024-06-07 13:50:41 +0200610 self.configfile = CryptoConfigFile(filename)
Gabor Mezeic5ff33c2024-06-28 17:46:44 +0200611 self.settings.update({name: Setting(active, name, value, section, self.configfile)
Gabor Mezei92065ed2024-06-07 13:47:59 +0200612 for (active, name, value, section)
Gabor Mezeiee521b62024-06-07 13:50:41 +0200613 in self.configfile.parse_file()})
Gabor Mezei3678dee2024-06-04 19:58:43 +0200614
Gabor Mezeid723b512024-06-07 15:31:52 +0200615 def set(self, name, value='1'):
Gabor Mezei542fd382024-06-10 14:07:42 +0200616 if name in PSA_UNSUPPORTED_FEATURE:
Gabor Mezei92065ed2024-06-07 13:47:59 +0200617 raise ValueError(f'Feature is unsupported: \'{name}\'')
Gabor Mezei542fd382024-06-10 14:07:42 +0200618 if name in PSA_UNSTABLE_FEATURE:
Gabor Mezei92065ed2024-06-07 13:47:59 +0200619 raise ValueError(f'Feature is unstable: \'{name}\'')
Gabor Mezei3678dee2024-06-04 19:58:43 +0200620
Gabor Mezeid723b512024-06-07 15:31:52 +0200621 # The default value in the crypto config is '1'
622 if not value:
623 value = '1'
624
Gabor Mezei3678dee2024-06-04 19:58:43 +0200625 if name not in self.settings:
Gabor Mezeiee521b62024-06-07 13:50:41 +0200626 self.configfile.templates.append((name, '', '#define ' + name + ' '))
627
Gabor Mezei3678dee2024-06-04 19:58:43 +0200628 super().set(name, value)
629
630 def write(self, filename=None):
Gabor Mezei62a9bd02024-06-07 13:44:40 +0200631 """Write the whole configuration to the file it was read from.
632
633 If filename is specified, write to this file instead.
634 """
Gabor Mezeiee521b62024-06-07 13:50:41 +0200635 self.configfile.write(self.settings, filename)
Gabor Mezei3678dee2024-06-04 19:58:43 +0200636
Gabor Mezeiee521b62024-06-07 13:50:41 +0200637 def filename(self):
638 return self.configfile.filename
Gabor Mezei3678dee2024-06-04 19:58:43 +0200639
Gabor Mezei33dd2932024-06-28 17:51:58 +0200640class CombinedConfig(Config):
Gabor Mezei62a9bd02024-06-07 13:44:40 +0200641 """Representation of MbedTLS and PSA crypto configuration
642
643 See the documentation of the `Config` class for methods to query
644 and modify the configuration.
645 """
Gabor Mezei3678dee2024-06-04 19:58:43 +0200646
Gabor Mezei3e2a5502024-06-28 17:27:19 +0200647 def __init__(self, *configs):
Gabor Mezeiee521b62024-06-07 13:50:41 +0200648 super().__init__()
Gabor Mezei3e2a5502024-06-28 17:27:19 +0200649 for config in configs:
650 if isinstance(config, MbedTLSConfigFile):
651 self.mbedtls_configfile = config
652 elif isinstance(config, CryptoConfigFile):
653 self.crypto_configfile = config
654 else:
655 raise ValueError(f'Invalid configfile: {config}')
656
Gabor Mezeiee521b62024-06-07 13:50:41 +0200657 self.settings.update({name: Setting(active, name, value, section, configfile)
658 for configfile in [self.mbedtls_configfile, self.crypto_configfile]
659 for (active, name, value, section) in configfile.parse_file()})
Gabor Mezei3678dee2024-06-04 19:58:43 +0200660
661 _crypto_regexp = re.compile(r'$PSA_.*')
Gabor Mezeiee521b62024-06-07 13:50:41 +0200662 def _get_configfile(self, name):
663 """Find a config type for a setting name
664 """
665 if name in self.settings:
666 return self.settings[name].configfile
667 elif re.match(self._crypto_regexp, name):
668 return self.crypto_configfile
Gabor Mezei3678dee2024-06-04 19:58:43 +0200669 else:
Gabor Mezeiee521b62024-06-07 13:50:41 +0200670 return self.mbedtls_configfile
Gabor Mezei3678dee2024-06-04 19:58:43 +0200671
Gabor Mezei8a64d8e2024-06-10 15:23:43 +0200672 def __setitem__(self, name, value):
673 super().__setitem__(name, value)
674 self.settings[name].configfile.modified = True
675
Gabor Mezei3678dee2024-06-04 19:58:43 +0200676 def set(self, name, value=None):
Gabor Mezeiee521b62024-06-07 13:50:41 +0200677 configfile = self._get_configfile(name)
Gabor Mezei3678dee2024-06-04 19:58:43 +0200678
Gabor Mezeiee521b62024-06-07 13:50:41 +0200679 if configfile == self.crypto_configfile:
Gabor Mezei542fd382024-06-10 14:07:42 +0200680 if name in PSA_UNSUPPORTED_FEATURE:
Gabor Mezeiee521b62024-06-07 13:50:41 +0200681 raise ValueError(f'Feature is unsupported: \'{name}\'')
Gabor Mezei542fd382024-06-10 14:07:42 +0200682 if name in PSA_UNSTABLE_FEATURE:
Gabor Mezeiee521b62024-06-07 13:50:41 +0200683 raise ValueError(f'Feature is unstable: \'{name}\'')
684
Gabor Mezeid723b512024-06-07 15:31:52 +0200685 # The default value in the crypto config is '1'
686 if not value:
687 value = '1'
688
Gabor Mezei8a64d8e2024-06-10 15:23:43 +0200689 if name in self.settings:
690 setting = self.settings[name]
691 if not setting.active or (value is not None and setting.value != value):
692 configfile.modified = True
693 else:
Gabor Mezeiee521b62024-06-07 13:50:41 +0200694 configfile.templates.append((name, '', '#define ' + name + ' '))
Gabor Mezei8a64d8e2024-06-10 15:23:43 +0200695 configfile.modified = True
Gabor Mezeiee521b62024-06-07 13:50:41 +0200696
697 super().set(name, value)
698
Gabor Mezei3678dee2024-06-04 19:58:43 +0200699 def write(self, mbedtls_file=None, crypto_file=None):
Gabor Mezei62a9bd02024-06-07 13:44:40 +0200700 """Write the whole configuration to the file it was read from.
701
702 If mbedtls_file or crypto_file is specified, write the specific configuration
703 to the corresponding file instead.
704 """
Gabor Mezeiee521b62024-06-07 13:50:41 +0200705 self.mbedtls_configfile.write(self.settings, mbedtls_file)
706 self.crypto_configfile.write(self.settings, crypto_file)
Gabor Mezei3678dee2024-06-04 19:58:43 +0200707
Gabor Mezeiee521b62024-06-07 13:50:41 +0200708 def filename(self, name=None):
709 if not name:
710 return [config.filename for config in [self.mbedtls_configfile, self.crypto_configfile]]
711
712 return self._get_configfile(name).filename
Gilles Peskineb4063892019-07-27 21:36:44 +0200713
714if __name__ == '__main__':
Gabor Mezei92065ed2024-06-07 13:47:59 +0200715 #pylint: disable=too-many-statements
Gilles Peskineb4063892019-07-27 21:36:44 +0200716 def main():
Bence Szépkútibb0cfeb2021-05-28 09:42:25 +0200717 """Command line mbedtls_config.h manipulation tool."""
Gilles Peskineb4063892019-07-27 21:36:44 +0200718 parser = argparse.ArgumentParser(description="""
Fredrik Hesse0ec8a902021-10-04 22:13:51 +0200719 Mbed TLS configuration file manipulation tool.
Gilles Peskineb4063892019-07-27 21:36:44 +0200720 """)
721 parser.add_argument('--file', '-f',
722 help="""File to read (and modify if requested).
723 Default: {}.
Gabor Mezeif77722d2024-06-28 16:49:33 +0200724 """.format(MbedTLSConfigFile.default_path))
Gabor Mezei3678dee2024-06-04 19:58:43 +0200725 parser.add_argument('--cryptofile', '-c',
726 help="""Crypto file to read (and modify if requested).
727 Default: {}.
728 """.format(CryptoConfigFile.default_path))
Gilles Peskineb4063892019-07-27 21:36:44 +0200729 parser.add_argument('--force', '-o',
Gilles Peskine435ce222019-08-01 23:13:47 +0200730 action='store_true',
Gilles Peskineb4063892019-07-27 21:36:44 +0200731 help="""For the set command, if SYMBOL is not
732 present, add a definition for it.""")
Gilles Peskinec190c902019-08-01 23:31:05 +0200733 parser.add_argument('--write', '-w', metavar='FILE',
Gilles Peskine40f103c2019-07-27 23:44:01 +0200734 help="""File to write to instead of the input file.""")
Gilles Peskineb4063892019-07-27 21:36:44 +0200735 subparsers = parser.add_subparsers(dest='command',
736 title='Commands')
737 parser_get = subparsers.add_parser('get',
738 help="""Find the value of SYMBOL
739 and print it. Exit with
740 status 0 if a #define for SYMBOL is
741 found, 1 otherwise.
742 """)
743 parser_get.add_argument('symbol', metavar='SYMBOL')
744 parser_set = subparsers.add_parser('set',
745 help="""Set SYMBOL to VALUE.
746 If VALUE is omitted, just uncomment
747 the #define for SYMBOL.
748 Error out of a line defining
749 SYMBOL (commented or not) is not
750 found, unless --force is passed.
751 """)
752 parser_set.add_argument('symbol', metavar='SYMBOL')
Gilles Peskine0c7fcd22019-08-01 23:14:00 +0200753 parser_set.add_argument('value', metavar='VALUE', nargs='?',
754 default='')
Gilles Peskine8e90cf42021-05-27 22:12:57 +0200755 parser_set_all = subparsers.add_parser('set-all',
756 help="""Uncomment all #define
757 whose name contains a match for
758 REGEX.""")
759 parser_set_all.add_argument('regexs', metavar='REGEX', nargs='*')
Gilles Peskineb4063892019-07-27 21:36:44 +0200760 parser_unset = subparsers.add_parser('unset',
761 help="""Comment out the #define
762 for SYMBOL. Do nothing if none
763 is present.""")
764 parser_unset.add_argument('symbol', metavar='SYMBOL')
Gilles Peskine8e90cf42021-05-27 22:12:57 +0200765 parser_unset_all = subparsers.add_parser('unset-all',
766 help="""Comment out all #define
767 whose name contains a match for
768 REGEX.""")
769 parser_unset_all.add_argument('regexs', metavar='REGEX', nargs='*')
Gilles Peskineb4063892019-07-27 21:36:44 +0200770
771 def add_adapter(name, function, description):
772 subparser = subparsers.add_parser(name, help=description)
773 subparser.set_defaults(adapter=function)
Gilles Peskine53d41ae2019-07-27 23:31:53 +0200774 add_adapter('baremetal', baremetal_adapter,
775 """Like full, but exclude features that require platform
776 features such as file input-output.""")
Gilles Peskine120f29d2021-09-01 19:51:19 +0200777 add_adapter('baremetal_size', baremetal_size_adapter,
778 """Like baremetal, but exclude debugging features.
779 Useful for code size measurements.""")
Gilles Peskine53d41ae2019-07-27 23:31:53 +0200780 add_adapter('full', full_adapter,
781 """Uncomment most features.
782 Exclude alternative implementations and platform support
783 options, as well as some options that are awkward to test.
784 """)
Gilles Peskine30de2e82020-04-20 21:39:22 +0200785 add_adapter('full_no_deprecated', no_deprecated_adapter(full_adapter),
Gilles Peskinebe1d6092020-04-12 14:17:16 +0200786 """Uncomment most non-deprecated features.
787 Like "full", but without deprecated features.
788 """)
Paul Elliottfb81f772023-10-18 17:44:59 +0100789 add_adapter('full_no_platform', no_platform_adapter(full_adapter),
790 """Uncomment most non-platform features.
791 Like "full", but without platform features.
792 """)
Gilles Peskineb4063892019-07-27 21:36:44 +0200793 add_adapter('realfull', realfull_adapter,
Gilles Peskine53d41ae2019-07-27 23:31:53 +0200794 """Uncomment all boolean #defines.
795 Suitable for generating documentation, but not for building.""")
Gilles Peskine31987c62020-01-31 14:23:30 +0100796 add_adapter('crypto', crypto_adapter(None),
797 """Only include crypto features. Exclude X.509 and TLS.""")
798 add_adapter('crypto_baremetal', crypto_adapter(baremetal_adapter),
799 """Like baremetal, but with only crypto features,
800 excluding X.509 and TLS.""")
801 add_adapter('crypto_full', crypto_adapter(full_adapter),
802 """Like full, but with only crypto features,
803 excluding X.509 and TLS.""")
Gilles Peskineb4063892019-07-27 21:36:44 +0200804
805 args = parser.parse_args()
Gabor Mezei33dd2932024-06-28 17:51:58 +0200806 config = CombinedConfig(MbedTLSConfigFile(args.file), CryptoConfigFile(args.cryptofile))
Gilles Peskine90b30b62019-07-28 00:36:53 +0200807 if args.command is None:
808 parser.print_help()
809 return 1
810 elif args.command == 'get':
Gilles Peskineb4063892019-07-27 21:36:44 +0200811 if args.symbol in config:
812 value = config[args.symbol]
813 if value:
814 sys.stdout.write(value + '\n')
Gilles Peskinee22a4da2020-03-24 15:43:49 +0100815 return 0 if args.symbol in config else 1
Gilles Peskineb4063892019-07-27 21:36:44 +0200816 elif args.command == 'set':
Gilles Peskine98eb3652019-07-28 16:39:19 +0200817 if not args.force and args.symbol not in config.settings:
Gilles Peskineb4063892019-07-27 21:36:44 +0200818 sys.stderr.write("A #define for the symbol {} "
Gilles Peskine221df1e2019-08-01 23:14:29 +0200819 "was not found in {}\n"
Gabor Mezei3678dee2024-06-04 19:58:43 +0200820 .format(args.symbol, config.filename(args.symbol)))
Gilles Peskineb4063892019-07-27 21:36:44 +0200821 return 1
822 config.set(args.symbol, value=args.value)
Gilles Peskine8e90cf42021-05-27 22:12:57 +0200823 elif args.command == 'set-all':
824 config.change_matching(args.regexs, True)
Gilles Peskineb4063892019-07-27 21:36:44 +0200825 elif args.command == 'unset':
826 config.unset(args.symbol)
Gilles Peskine8e90cf42021-05-27 22:12:57 +0200827 elif args.command == 'unset-all':
828 config.change_matching(args.regexs, False)
Gilles Peskineb4063892019-07-27 21:36:44 +0200829 else:
830 config.adapt(args.adapter)
Gilles Peskine40f103c2019-07-27 23:44:01 +0200831 config.write(args.write)
Gilles Peskinee22a4da2020-03-24 15:43:49 +0100832 return 0
Gilles Peskineb4063892019-07-27 21:36:44 +0200833
834 # Import modules only used by main only if main is defined and called.
835 # pylint: disable=wrong-import-position
836 import argparse
837 import sys
838 sys.exit(main())