blob: 3ee21d1464678fc905d874505e0cad4cf56c0b17 [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
Gilles Peskineb4063892019-07-27 21:36:44 +0200132 self.settings[name].active = False
133
134 def adapt(self, adapter):
135 """Run adapter on each known symbol and (de)activate it accordingly.
136
137 `adapter` must be a function that returns a boolean. It is called as
Gilles Peskine53d41ae2019-07-27 23:31:53 +0200138 `adapter(name, active, section)` for each setting, where `active` is
139 `True` if `name` is set and `False` if `name` is known but unset,
140 and `section` is the name of the section containing `name`. If
Gilles Peskineb4063892019-07-27 21:36:44 +0200141 `adapter` returns `True`, then set `name` (i.e. make it active),
142 otherwise unset `name` (i.e. make it known but inactive).
143 """
144 for setting in self.settings.values():
Gilles Peskine53d41ae2019-07-27 23:31:53 +0200145 setting.active = adapter(setting.name, setting.active,
146 setting.section)
Gilles Peskineb4063892019-07-27 21:36:44 +0200147
Gilles Peskine8e90cf42021-05-27 22:12:57 +0200148 def change_matching(self, regexs, enable):
149 """Change all symbols matching one of the regexs to the desired state."""
150 if not regexs:
151 return
152 regex = re.compile('|'.join(regexs))
153 for setting in self.settings.values():
154 if regex.search(setting.name):
155 setting.active = enable
156
Gilles Peskine53d41ae2019-07-27 23:31:53 +0200157def is_full_section(section):
Gabor Mezeide6e1922024-06-28 17:10:50 +0200158 """Is this section affected by "config.py full" and friends?
159
160 In a config file where the sections are not used the whole config file
161 is an empty section (with value None) and the whole file is affected.
162 """
Gabor Mezei3678dee2024-06-04 19:58:43 +0200163 return section is None or section.endswith('support') or section.endswith('modules')
Gilles Peskine53d41ae2019-07-27 23:31:53 +0200164
165def realfull_adapter(_name, active, section):
Gilles Peskineba4162a2022-04-11 17:04:38 +0200166 """Activate all symbols found in the global and boolean feature sections.
167
168 This is intended for building the documentation, including the
169 documentation of settings that are activated by defining an optional
170 preprocessor macro.
171
172 Do not activate definitions in the section containing symbols that are
173 supposed to be defined and documented in their own module.
174 """
175 if section == 'Module configuration options':
Gilles Peskine53d41ae2019-07-27 23:31:53 +0200176 return active
Gilles Peskineb4063892019-07-27 21:36:44 +0200177 return True
178
Gabor Mezei542fd382024-06-10 14:07:42 +0200179PSA_UNSUPPORTED_FEATURE = frozenset([
Gabor Mezei3678dee2024-06-04 19:58:43 +0200180 'PSA_WANT_ALG_CBC_MAC',
181 'PSA_WANT_ALG_XTS',
182 'PSA_WANT_KEY_TYPE_RSA_KEY_PAIR_DERIVE',
183 'PSA_WANT_KEY_TYPE_DH_KEY_PAIR_DERIVE'
184])
185
Gabor Mezei542fd382024-06-10 14:07:42 +0200186PSA_DEPRECATED_FEATURE = frozenset([
Gabor Mezei3678dee2024-06-04 19:58:43 +0200187 'PSA_WANT_KEY_TYPE_ECC_KEY_PAIR',
188 'PSA_WANT_KEY_TYPE_RSA_KEY_PAIR'
189])
190
Gabor Mezei542fd382024-06-10 14:07:42 +0200191PSA_UNSTABLE_FEATURE = frozenset([
Gabor Mezei3678dee2024-06-04 19:58:43 +0200192 'PSA_WANT_ECC_SECP_K1_224'
193])
194
Gabor Mezei9b0f9e72024-06-26 18:08:17 +0200195EXCLUDE_FROM_CRYPTO = PSA_UNSUPPORTED_FEATURE | \
196 PSA_DEPRECATED_FEATURE | \
197 PSA_UNSTABLE_FEATURE
Gabor Mezei542fd382024-06-10 14:07:42 +0200198
Gilles Peskinecfffc282020-04-12 13:55:45 +0200199# The goal of the full configuration is to have everything that can be tested
200# together. This includes deprecated or insecure options. It excludes:
201# * Options that require additional build dependencies or unusual hardware.
202# * Options that make testing less effective.
Gilles Peskinec9d04332020-04-16 20:50:17 +0200203# * Options that are incompatible with other options, or more generally that
204# interact with other parts of the code in such a way that a bulk enabling
205# is not a good way to test them.
Gilles Peskinecfffc282020-04-12 13:55:45 +0200206# * Options that remove features.
Gilles Peskinebbaa2b72020-04-12 13:33:57 +0200207EXCLUDE_FROM_FULL = frozenset([
Gilles Peskinecfffc282020-04-12 13:55:45 +0200208 #pylint: disable=line-too-long
Yanray Wanga8704672023-04-20 17:16:48 +0800209 'MBEDTLS_AES_ONLY_128_BIT_KEY_LENGTH', # interacts with CTR_DRBG_128_BIT_KEY
Gilles Peskinea8861e02023-09-05 20:20:51 +0200210 'MBEDTLS_AES_USE_HARDWARE_ONLY', # hardware dependency
Yanray Wang42be1ba2023-11-23 14:28:47 +0800211 'MBEDTLS_BLOCK_CIPHER_NO_DECRYPT', # incompatible with ECB in PSA, CBC/XTS/NIST_KW/DES
Gilles Peskinec9d04332020-04-16 20:50:17 +0200212 'MBEDTLS_CTR_DRBG_USE_128_BIT_KEY', # interacts with ENTROPY_FORCE_SHA256
Gilles Peskinecfffc282020-04-12 13:55:45 +0200213 'MBEDTLS_DEPRECATED_REMOVED', # conflicts with deprecated options
Gilles Peskine90581ee2020-04-12 14:02:47 +0200214 'MBEDTLS_DEPRECATED_WARNING', # conflicts with deprecated options
Gilles Peskinec9d04332020-04-16 20:50:17 +0200215 'MBEDTLS_ECDH_VARIANT_EVEREST_ENABLED', # influences the use of ECDH in TLS
Janos Follath5b7c38f2023-08-01 08:51:12 +0100216 'MBEDTLS_ECP_WITH_MPI_UINT', # disables the default ECP and is experimental
Gilles Peskinec9d04332020-04-16 20:50:17 +0200217 'MBEDTLS_ENTROPY_FORCE_SHA256', # interacts with CTR_DRBG_128_BIT_KEY
Gilles Peskinecfffc282020-04-12 13:55:45 +0200218 'MBEDTLS_HAVE_SSE2', # hardware dependency
219 'MBEDTLS_MEMORY_BACKTRACE', # depends on MEMORY_BUFFER_ALLOC_C
220 'MBEDTLS_MEMORY_BUFFER_ALLOC_C', # makes sanitizers (e.g. ASan) less effective
221 'MBEDTLS_MEMORY_DEBUG', # depends on MEMORY_BUFFER_ALLOC_C
Gilles Peskinec9d04332020-04-16 20:50:17 +0200222 'MBEDTLS_NO_64BIT_MULTIPLICATION', # influences anything that uses bignum
Gilles Peskinecfffc282020-04-12 13:55:45 +0200223 'MBEDTLS_NO_DEFAULT_ENTROPY_SOURCES', # removes a feature
224 'MBEDTLS_NO_PLATFORM_ENTROPY', # removes a feature
Gilles Peskinec9d04332020-04-16 20:50:17 +0200225 'MBEDTLS_NO_UDBL_DIVISION', # influences anything that uses bignum
Gilles Peskineefaee9a2023-09-20 20:49:47 +0200226 'MBEDTLS_PSA_P256M_DRIVER_ENABLED', # influences SECP256R1 KeyGen/ECDH/ECDSA
Gilles Peskinecfffc282020-04-12 13:55:45 +0200227 'MBEDTLS_PLATFORM_NO_STD_FUNCTIONS', # removes a feature
David Horstmann6f8c95b2024-03-14 14:52:45 +0000228 'MBEDTLS_PSA_ASSUME_EXCLUSIVE_BUFFERS', # removes a feature
Gilles Peskinef08b3f82020-11-13 17:36:48 +0100229 'MBEDTLS_PSA_CRYPTO_EXTERNAL_RNG', # behavior change + build dependency
Ronald Cronc3623db2020-10-29 10:51:32 +0100230 'MBEDTLS_PSA_CRYPTO_KEY_ID_ENCODES_OWNER', # incompatible with USE_PSA_CRYPTO
Gilles Peskinecfffc282020-04-12 13:55:45 +0200231 'MBEDTLS_PSA_CRYPTO_SPM', # platform dependency (PSA SPM)
Gilles Peskinea08def92023-04-28 21:01:49 +0200232 'MBEDTLS_PSA_INJECT_ENTROPY', # conflicts with platform entropy sources
Gilles Peskinec9d04332020-04-16 20:50:17 +0200233 'MBEDTLS_RSA_NO_CRT', # influences the use of RSA in X.509 and TLS
Tom Cosgrove87fbfb52022-03-15 10:51:52 +0000234 'MBEDTLS_SHA256_USE_A64_CRYPTO_ONLY', # interacts with *_USE_A64_CRYPTO_IF_PRESENT
Dave Rodgman9be3cf02023-10-11 14:47:55 +0100235 'MBEDTLS_SHA256_USE_ARMV8_A_CRYPTO_ONLY', # interacts with *_USE_ARMV8_A_CRYPTO_IF_PRESENT
Tom Cosgrove87fbfb52022-03-15 10:51:52 +0000236 'MBEDTLS_SHA512_USE_A64_CRYPTO_ONLY', # interacts with *_USE_A64_CRYPTO_IF_PRESENT
Dave Rodgman7cb635a2023-10-12 16:14:51 +0100237 'MBEDTLS_SHA256_USE_A64_CRYPTO_IF_PRESENT', # setting *_USE_ARMV8_A_CRYPTO is sufficient
Manuel Pégourié-Gonnard6240def2020-07-10 09:35:54 +0200238 'MBEDTLS_TEST_CONSTANT_FLOW_MEMSAN', # build dependency (clang+memsan)
Manuel Pégourié-Gonnard73afa372020-08-19 10:27:38 +0200239 'MBEDTLS_TEST_CONSTANT_FLOW_VALGRIND', # build dependency (valgrind headers)
Hanno Beckere1113562019-06-12 13:59:14 +0100240 'MBEDTLS_X509_REMOVE_INFO', # removes a feature
Gabor Mezei542fd382024-06-10 14:07:42 +0200241 *PSA_UNSUPPORTED_FEATURE,
242 *PSA_DEPRECATED_FEATURE,
243 *PSA_UNSTABLE_FEATURE
Gilles Peskinebbaa2b72020-04-12 13:33:57 +0200244])
245
Gilles Peskine32e889d2020-04-12 23:43:28 +0200246def is_seamless_alt(name):
Gilles Peskinec34faba2020-04-20 15:44:14 +0200247 """Whether the xxx_ALT symbol should be included in the full configuration.
Gilles Peskine32e889d2020-04-12 23:43:28 +0200248
Gilles Peskinec34faba2020-04-20 15:44:14 +0200249 Include alternative implementations of platform functions, which are
Gilles Peskine32e889d2020-04-12 23:43:28 +0200250 configurable function pointers that default to the built-in function.
251 This way we test that the function pointers exist and build correctly
252 without changing the behavior, and tests can verify that the function
253 pointers are used by modifying those pointers.
254
255 Exclude alternative implementations of library functions since they require
256 an implementation of the relevant functions and an xxx_alt.h header.
257 """
Gilles Peskinea8861e02023-09-05 20:20:51 +0200258 if name in (
259 'MBEDTLS_PLATFORM_GMTIME_R_ALT',
260 'MBEDTLS_PLATFORM_SETUP_TEARDOWN_ALT',
261 'MBEDTLS_PLATFORM_MS_TIME_ALT',
262 'MBEDTLS_PLATFORM_ZEROIZE_ALT',
263 ):
Gilles Peskinec34faba2020-04-20 15:44:14 +0200264 # Similar to non-platform xxx_ALT, requires platform_alt.h
265 return False
Gilles Peskine32e889d2020-04-12 23:43:28 +0200266 return name.startswith('MBEDTLS_PLATFORM_')
267
Gilles Peskine53d41ae2019-07-27 23:31:53 +0200268def include_in_full(name):
269 """Rules for symbols in the "full" configuration."""
Gabor Mezei542fd382024-06-10 14:07:42 +0200270 if name in EXCLUDE_FROM_FULL:
Gilles Peskine53d41ae2019-07-27 23:31:53 +0200271 return False
272 if name.endswith('_ALT'):
Gilles Peskine32e889d2020-04-12 23:43:28 +0200273 return is_seamless_alt(name)
Gilles Peskine53d41ae2019-07-27 23:31:53 +0200274 return True
275
276def full_adapter(name, active, section):
277 """Config adapter for "full"."""
278 if not is_full_section(section):
279 return active
280 return include_in_full(name)
281
Gilles Peskinecfffc282020-04-12 13:55:45 +0200282# The baremetal configuration excludes options that require a library or
283# operating system feature that is typically not present on bare metal
284# systems. Features that are excluded from "full" won't be in "baremetal"
285# either (unless explicitly turned on in baremetal_adapter) so they don't
286# need to be repeated here.
Gilles Peskinebbaa2b72020-04-12 13:33:57 +0200287EXCLUDE_FROM_BAREMETAL = frozenset([
Gilles Peskinecfffc282020-04-12 13:55:45 +0200288 #pylint: disable=line-too-long
Gilles Peskine98f8f952020-04-20 15:38:39 +0200289 'MBEDTLS_ENTROPY_NV_SEED', # requires a filesystem and FS_IO or alternate NV seed hooks
Gilles Peskinecfffc282020-04-12 13:55:45 +0200290 'MBEDTLS_FS_IO', # requires a filesystem
Gilles Peskinecfffc282020-04-12 13:55:45 +0200291 'MBEDTLS_HAVE_TIME', # requires a clock
292 'MBEDTLS_HAVE_TIME_DATE', # requires a clock
293 'MBEDTLS_NET_C', # requires POSIX-like networking
294 'MBEDTLS_PLATFORM_FPRINTF_ALT', # requires FILE* from stdio.h
Gilles Peskine98f8f952020-04-20 15:38:39 +0200295 'MBEDTLS_PLATFORM_NV_SEED_ALT', # requires a filesystem and ENTROPY_NV_SEED
296 'MBEDTLS_PLATFORM_TIME_ALT', # requires a clock and HAVE_TIME
297 'MBEDTLS_PSA_CRYPTO_SE_C', # requires a filesystem and PSA_CRYPTO_STORAGE_C
Gilles Peskinecfffc282020-04-12 13:55:45 +0200298 'MBEDTLS_PSA_CRYPTO_STORAGE_C', # requires a filesystem
299 'MBEDTLS_PSA_ITS_FILE_C', # requires a filesystem
300 'MBEDTLS_THREADING_C', # requires a threading interface
301 'MBEDTLS_THREADING_PTHREAD', # requires pthread
302 'MBEDTLS_TIMING_C', # requires a clock
Dave Rodgman9be3cf02023-10-11 14:47:55 +0100303 'MBEDTLS_SHA256_USE_A64_CRYPTO_IF_PRESENT', # requires an OS for runtime-detection
Dave Rodgman5b89c552023-10-10 14:59:02 +0100304 'MBEDTLS_SHA256_USE_ARMV8_A_CRYPTO_IF_PRESENT', # requires an OS for runtime-detection
Dave Rodgmanbe7915a2023-10-11 10:46:38 +0100305 'MBEDTLS_SHA512_USE_A64_CRYPTO_IF_PRESENT', # requires an OS for runtime-detection
Gilles Peskinebbaa2b72020-04-12 13:33:57 +0200306])
307
Gilles Peskine53d41ae2019-07-27 23:31:53 +0200308def keep_in_baremetal(name):
309 """Rules for symbols in the "baremetal" configuration."""
Gilles Peskinebbaa2b72020-04-12 13:33:57 +0200310 if name in EXCLUDE_FROM_BAREMETAL:
Gilles Peskine53d41ae2019-07-27 23:31:53 +0200311 return False
312 return True
313
314def baremetal_adapter(name, active, section):
315 """Config adapter for "baremetal"."""
316 if not is_full_section(section):
317 return active
318 if name == 'MBEDTLS_NO_PLATFORM_ENTROPY':
Gilles Peskinecfffc282020-04-12 13:55:45 +0200319 # No OS-provided entropy source
Gilles Peskine53d41ae2019-07-27 23:31:53 +0200320 return True
321 return include_in_full(name) and keep_in_baremetal(name)
322
Gilles Peskine120f29d2021-09-01 19:51:19 +0200323# This set contains options that are mostly for debugging or test purposes,
324# and therefore should be excluded when doing code size measurements.
325# Options that are their own module (such as MBEDTLS_ERROR_C) are not listed
326# and therefore will be included when doing code size measurements.
327EXCLUDE_FOR_SIZE = frozenset([
328 'MBEDTLS_DEBUG_C', # large code size increase in TLS
329 'MBEDTLS_SELF_TEST', # increases the size of many modules
330 'MBEDTLS_TEST_HOOKS', # only useful with the hosted test framework, increases code size
331])
332
333def baremetal_size_adapter(name, active, section):
334 if name in EXCLUDE_FOR_SIZE:
335 return False
336 return baremetal_adapter(name, active, section)
337
Gilles Peskine31987c62020-01-31 14:23:30 +0100338def include_in_crypto(name):
339 """Rules for symbols in a crypto configuration."""
340 if name.startswith('MBEDTLS_X509_') or \
341 name.startswith('MBEDTLS_SSL_') or \
342 name.startswith('MBEDTLS_KEY_EXCHANGE_'):
343 return False
344 if name in [
Gilles Peskinecfffc282020-04-12 13:55:45 +0200345 'MBEDTLS_DEBUG_C', # part of libmbedtls
346 'MBEDTLS_NET_C', # part of libmbedtls
Nayna Jainc9deb182020-11-16 19:03:12 +0000347 'MBEDTLS_PKCS7_C', # part of libmbedx509
Gilles Peskine31987c62020-01-31 14:23:30 +0100348 ]:
349 return False
Gabor Mezei542fd382024-06-10 14:07:42 +0200350 if name in EXCLUDE_FROM_CRYPTO:
351 return False
Gilles Peskine31987c62020-01-31 14:23:30 +0100352 return True
353
354def crypto_adapter(adapter):
355 """Modify an adapter to disable non-crypto symbols.
356
357 ``crypto_adapter(adapter)(name, active, section)`` is like
358 ``adapter(name, active, section)``, but unsets all X.509 and TLS symbols.
359 """
360 def continuation(name, active, section):
361 if not include_in_crypto(name):
362 return False
363 if adapter is None:
364 return active
365 return adapter(name, active, section)
366 return continuation
367
Gilles Peskineed5c21d2022-06-27 23:02:09 +0200368DEPRECATED = frozenset([
369 'MBEDTLS_PSA_CRYPTO_SE_C',
Gabor Mezei542fd382024-06-10 14:07:42 +0200370 *PSA_DEPRECATED_FEATURE
Gilles Peskineed5c21d2022-06-27 23:02:09 +0200371])
Gilles Peskine30de2e82020-04-20 21:39:22 +0200372def no_deprecated_adapter(adapter):
Gilles Peskinebe1d6092020-04-12 14:17:16 +0200373 """Modify an adapter to disable deprecated symbols.
374
Gilles Peskine30de2e82020-04-20 21:39:22 +0200375 ``no_deprecated_adapter(adapter)(name, active, section)`` is like
Gilles Peskinebe1d6092020-04-12 14:17:16 +0200376 ``adapter(name, active, section)``, but unsets all deprecated symbols
377 and sets ``MBEDTLS_DEPRECATED_REMOVED``.
378 """
379 def continuation(name, active, section):
380 if name == 'MBEDTLS_DEPRECATED_REMOVED':
381 return True
Gilles Peskineed5c21d2022-06-27 23:02:09 +0200382 if name in DEPRECATED:
383 return False
Gilles Peskinebe1d6092020-04-12 14:17:16 +0200384 if adapter is None:
385 return active
386 return adapter(name, active, section)
387 return continuation
388
Paul Elliottfb81f772023-10-18 17:44:59 +0100389def no_platform_adapter(adapter):
390 """Modify an adapter to disable platform symbols.
391
392 ``no_platform_adapter(adapter)(name, active, section)`` is like
393 ``adapter(name, active, section)``, but unsets all platform symbols other
394 ``than MBEDTLS_PLATFORM_C.
395 """
396 def continuation(name, active, section):
397 # Allow MBEDTLS_PLATFORM_C but remove all other platform symbols.
398 if name.startswith('MBEDTLS_PLATFORM_') and name != 'MBEDTLS_PLATFORM_C':
399 return False
400 if adapter is None:
401 return active
402 return adapter(name, active, section)
403 return continuation
404
Gabor Mezei3678dee2024-06-04 19:58:43 +0200405class ConfigFile(metaclass=ABCMeta):
Gabor Mezei62a9bd02024-06-07 13:44:40 +0200406 """Representation of a configuration file."""
407
Gabor Mezei93a6d1f2024-06-26 18:01:09 +0200408 def __init__(self, default_path, name, filename=None):
Gabor Mezei62a9bd02024-06-07 13:44:40 +0200409 """Check if the config file exists."""
Gilles Peskineb4063892019-07-27 21:36:44 +0200410 if filename is None:
Gabor Mezei3678dee2024-06-04 19:58:43 +0200411 for candidate in default_path:
Gilles Peskinece674a92020-03-24 15:37:00 +0100412 if os.path.lexists(candidate):
413 filename = candidate
Gilles Peskine208e4ec2019-07-29 23:43:20 +0200414 break
Gilles Peskinece674a92020-03-24 15:37:00 +0100415 else:
Gabor Mezei92065ed2024-06-07 13:47:59 +0200416 raise ValueError(f'{name} configuration file not found: '
417 f'{filename if filename else default_path}')
Gilles Peskineb4063892019-07-27 21:36:44 +0200418
Gabor Mezei3678dee2024-06-04 19:58:43 +0200419 self.filename = filename
420 self.templates = []
421 self.current_section = None
422 self.inclusion_guard = None
Gabor Mezei8a64d8e2024-06-10 15:23:43 +0200423 self.modified = False
Gilles Peskineb4063892019-07-27 21:36:44 +0200424
425 _define_line_regexp = (r'(?P<indentation>\s*)' +
426 r'(?P<commented_out>(//\s*)?)' +
427 r'(?P<define>#\s*define\s+)' +
428 r'(?P<name>\w+)' +
429 r'(?P<arguments>(?:\((?:\w|\s|,)*\))?)' +
430 r'(?P<separator>\s*)' +
431 r'(?P<value>.*)')
Gilles Peskine9ba9c212024-05-23 15:03:43 +0200432 _ifndef_line_regexp = r'#ifndef (?P<inclusion_guard>\w+)'
Gilles Peskine53d41ae2019-07-27 23:31:53 +0200433 _section_line_regexp = (r'\s*/?\*+\s*[\\@]name\s+SECTION:\s*' +
434 r'(?P<section>.*)[ */]*')
435 _config_line_regexp = re.compile(r'|'.join([_define_line_regexp,
Gilles Peskine9ba9c212024-05-23 15:03:43 +0200436 _ifndef_line_regexp,
Gilles Peskine53d41ae2019-07-27 23:31:53 +0200437 _section_line_regexp]))
Gilles Peskineb4063892019-07-27 21:36:44 +0200438 def _parse_line(self, line):
Gabor Mezei62a9bd02024-06-07 13:44:40 +0200439 """Parse a line in the config file, save the templates representing the lines
440 and return the corresponding setting element.
441 """
Gilles Peskineb4063892019-07-27 21:36:44 +0200442 line = line.rstrip('\r\n')
Gilles Peskine53d41ae2019-07-27 23:31:53 +0200443 m = re.match(self._config_line_regexp, line)
444 if m is None:
Gabor Mezei3678dee2024-06-04 19:58:43 +0200445 self.templates.append(line)
446 return None
Gilles Peskine53d41ae2019-07-27 23:31:53 +0200447 elif m.group('section'):
448 self.current_section = m.group('section')
Gabor Mezei3678dee2024-06-04 19:58:43 +0200449 self.templates.append(line)
450 return None
Gilles Peskine9ba9c212024-05-23 15:03:43 +0200451 elif m.group('inclusion_guard') and self.inclusion_guard is None:
452 self.inclusion_guard = m.group('inclusion_guard')
Gabor Mezei3678dee2024-06-04 19:58:43 +0200453 self.templates.append(line)
454 return None
Gilles Peskine53d41ae2019-07-27 23:31:53 +0200455 else:
Gilles Peskineb4063892019-07-27 21:36:44 +0200456 active = not m.group('commented_out')
457 name = m.group('name')
458 value = m.group('value')
Gilles Peskine9ba9c212024-05-23 15:03:43 +0200459 if name == self.inclusion_guard and value == '':
460 # The file double-inclusion guard is not an option.
Gabor Mezei3678dee2024-06-04 19:58:43 +0200461 self.templates.append(line)
462 return None
Gilles Peskineb4063892019-07-27 21:36:44 +0200463 template = (name,
464 m.group('indentation'),
465 m.group('define') + name +
466 m.group('arguments') + m.group('separator'))
Gabor Mezei3678dee2024-06-04 19:58:43 +0200467 self.templates.append(template)
Gilles Peskineb4063892019-07-27 21:36:44 +0200468
Gabor Mezei3678dee2024-06-04 19:58:43 +0200469 return (active, name, value, self.current_section)
470
471 def parse_file(self):
Gabor Mezei62a9bd02024-06-07 13:44:40 +0200472 """Parse the whole file and return the settings."""
Gabor Mezei3678dee2024-06-04 19:58:43 +0200473 with open(self.filename, 'r', encoding='utf-8') as file:
474 for line in file:
475 setting = self._parse_line(line)
476 if setting is not None:
477 yield setting
478 self.current_section = None
479
Gabor Mezeie7742b32024-06-26 18:04:09 +0200480 #pylint: disable=no-self-use
481 def _format_template(self, setting, indent, middle):
482 """Build a line for mbedtls_config.h for the given setting.
483
484 The line has the form "<indent>#define <name> <value>"
485 where <middle> is "#define <name> ".
486 """
487 value = setting.value
488 if value is None:
489 value = ''
490 # Normally the whitespace to separate the symbol name from the
491 # value is part of middle, and there's no whitespace for a symbol
492 # with no value. But if a symbol has been changed from having a
493 # value to not having one, the whitespace is wrong, so fix it.
494 if value:
495 if middle[-1] not in '\t ':
496 middle += ' '
497 else:
498 middle = middle.rstrip()
499 return ''.join([indent,
500 '' if setting.active else '//',
501 middle,
502 value]).rstrip()
Gabor Mezei3678dee2024-06-04 19:58:43 +0200503
504 def write_to_stream(self, settings, output):
505 """Write the whole configuration to output."""
506 for template in self.templates:
507 if isinstance(template, str):
508 line = template
509 else:
Gabor Mezeie7742b32024-06-26 18:04:09 +0200510 name, indent, middle = template
511 line = self._format_template(settings[name], indent, middle)
Gabor Mezei3678dee2024-06-04 19:58:43 +0200512 output.write(line + '\n')
513
514 def write(self, settings, filename=None):
515 """Write the whole configuration to the file it was read from.
516
517 If filename is specified, write to this file instead.
518 """
519 if filename is None:
520 filename = self.filename
Gabor Mezei8a64d8e2024-06-10 15:23:43 +0200521
522 # Not modified so no need to write to the file
523 if not self.modified and filename == self.filename:
524 return
525
Gabor Mezei3678dee2024-06-04 19:58:43 +0200526 with open(filename, 'w', encoding='utf-8') as output:
527 self.write_to_stream(settings, output)
528
Gabor Mezeif77722d2024-06-28 16:49:33 +0200529class MbedTLSConfigFile(ConfigFile):
Gabor Mezei62a9bd02024-06-07 13:44:40 +0200530 """Representation of an MbedTLS configuration file."""
531
Gabor Mezei3678dee2024-06-04 19:58:43 +0200532 _path_in_tree = 'include/mbedtls/mbedtls_config.h'
533 default_path = [_path_in_tree,
534 os.path.join(os.path.dirname(__file__),
535 os.pardir,
536 _path_in_tree),
537 os.path.join(os.path.dirname(os.path.abspath(os.path.dirname(__file__))),
538 _path_in_tree)]
539
540 def __init__(self, filename=None):
Gabor Mezei93a6d1f2024-06-26 18:01:09 +0200541 super().__init__(self.default_path, 'Mbed TLS', filename)
Gabor Mezei3678dee2024-06-04 19:58:43 +0200542 self.current_section = 'header'
543
Gabor Mezei3678dee2024-06-04 19:58:43 +0200544class CryptoConfigFile(ConfigFile):
Gabor Mezei62a9bd02024-06-07 13:44:40 +0200545 """Representation of an Crypto configuration file."""
546
Gabor Mezei3678dee2024-06-04 19:58:43 +0200547 _path_in_tree = 'tf-psa-crypto/include/psa/crypto_config.h'
548 default_path = [_path_in_tree,
549 os.path.join(os.path.dirname(__file__),
550 os.pardir,
551 _path_in_tree),
552 os.path.join(os.path.dirname(os.path.abspath(os.path.dirname(__file__))),
553 _path_in_tree)]
554
555 def __init__(self, filename=None):
Gabor Mezei93a6d1f2024-06-26 18:01:09 +0200556 super().__init__(self.default_path, 'Crypto', filename)
Gabor Mezei3678dee2024-06-04 19:58:43 +0200557
Gabor Mezeif77722d2024-06-28 16:49:33 +0200558class MbedTLSConfig(Config):
Gabor Mezei62a9bd02024-06-07 13:44:40 +0200559 """Representation of the Mbed TLS configuration.
Gabor Mezei3678dee2024-06-04 19:58:43 +0200560
561 See the documentation of the `Config` class for methods to query
562 and modify the configuration.
563 """
Gabor Mezeiee521b62024-06-07 13:50:41 +0200564 def __init__(self, filename=None):
Gabor Mezei3678dee2024-06-04 19:58:43 +0200565 """Read the Mbed TLS configuration file."""
566 super().__init__()
Gabor Mezeif77722d2024-06-28 16:49:33 +0200567 self.configfile = MbedTLSConfigFile(filename)
Gabor Mezeiee521b62024-06-07 13:50:41 +0200568 self.settings.update({name: Setting(active, name, value, section)
Gabor Mezei92065ed2024-06-07 13:47:59 +0200569 for (active, name, value, section)
Gabor Mezeiee521b62024-06-07 13:50:41 +0200570 in self.configfile.parse_file()})
Gabor Mezei3678dee2024-06-04 19:58:43 +0200571
572 def set(self, name, value=None):
573 if name not in self.settings:
Gabor Mezeiee521b62024-06-07 13:50:41 +0200574 self.configfile.templates.append((name, '', '#define ' + name + ' '))
575
Gabor Mezei3678dee2024-06-04 19:58:43 +0200576 super().set(name, value)
Gilles Peskineb4063892019-07-27 21:36:44 +0200577
578 def write(self, filename=None):
Gabor Mezei62a9bd02024-06-07 13:44:40 +0200579 """Write the whole configuration to the file it was read from.
580
581 If filename is specified, write to this file instead.
582 """
Gabor Mezeiee521b62024-06-07 13:50:41 +0200583 self.configfile.write(self.settings, filename)
Gilles Peskineb4063892019-07-27 21:36:44 +0200584
Gabor Mezeiee521b62024-06-07 13:50:41 +0200585 def filename(self):
586 return self.configfile.filename
Gabor Mezei3678dee2024-06-04 19:58:43 +0200587
588class CryptoConfig(Config):
Gabor Mezei62a9bd02024-06-07 13:44:40 +0200589 """Representation of the PSA crypto configuration.
Gabor Mezei3678dee2024-06-04 19:58:43 +0200590
591 See the documentation of the `Config` class for methods to query
592 and modify the configuration.
593 """
Gabor Mezeiee521b62024-06-07 13:50:41 +0200594 def __init__(self, filename=None):
Gabor Mezei3678dee2024-06-04 19:58:43 +0200595 """Read the PSA crypto configuration file."""
596 super().__init__()
Gabor Mezeiee521b62024-06-07 13:50:41 +0200597 self.configfile = CryptoConfigFile(filename)
598 self.settings.update({name: Setting(active, name, value, section)
Gabor Mezei92065ed2024-06-07 13:47:59 +0200599 for (active, name, value, section)
Gabor Mezeiee521b62024-06-07 13:50:41 +0200600 in self.configfile.parse_file()})
Gabor Mezei3678dee2024-06-04 19:58:43 +0200601
Gabor Mezeid723b512024-06-07 15:31:52 +0200602 def set(self, name, value='1'):
Gabor Mezei542fd382024-06-10 14:07:42 +0200603 if name in PSA_UNSUPPORTED_FEATURE:
Gabor Mezei92065ed2024-06-07 13:47:59 +0200604 raise ValueError(f'Feature is unsupported: \'{name}\'')
Gabor Mezei542fd382024-06-10 14:07:42 +0200605 if name in PSA_UNSTABLE_FEATURE:
Gabor Mezei92065ed2024-06-07 13:47:59 +0200606 raise ValueError(f'Feature is unstable: \'{name}\'')
Gabor Mezei3678dee2024-06-04 19:58:43 +0200607
Gabor Mezeid723b512024-06-07 15:31:52 +0200608 # The default value in the crypto config is '1'
609 if not value:
610 value = '1'
611
Gabor Mezei3678dee2024-06-04 19:58:43 +0200612 if name not in self.settings:
Gabor Mezeiee521b62024-06-07 13:50:41 +0200613 self.configfile.templates.append((name, '', '#define ' + name + ' '))
614
Gabor Mezei3678dee2024-06-04 19:58:43 +0200615 super().set(name, value)
616
617 def write(self, filename=None):
Gabor Mezei62a9bd02024-06-07 13:44:40 +0200618 """Write the whole configuration to the file it was read from.
619
620 If filename is specified, write to this file instead.
621 """
Gabor Mezeiee521b62024-06-07 13:50:41 +0200622 self.configfile.write(self.settings, filename)
Gabor Mezei3678dee2024-06-04 19:58:43 +0200623
Gabor Mezeiee521b62024-06-07 13:50:41 +0200624 def filename(self):
625 return self.configfile.filename
Gabor Mezei3678dee2024-06-04 19:58:43 +0200626
Gabor Mezeiee521b62024-06-07 13:50:41 +0200627class MultiConfig(Config):
Gabor Mezei62a9bd02024-06-07 13:44:40 +0200628 """Representation of MbedTLS and PSA crypto configuration
629
630 See the documentation of the `Config` class for methods to query
631 and modify the configuration.
632 """
Gabor Mezei3678dee2024-06-04 19:58:43 +0200633
Gabor Mezeiee521b62024-06-07 13:50:41 +0200634 def __init__(self, mbedtls_filename=None, crypto__filename=None):
635 super().__init__()
Gabor Mezeif77722d2024-06-28 16:49:33 +0200636 self.mbedtls_configfile = MbedTLSConfigFile(mbedtls_filename)
Gabor Mezeiee521b62024-06-07 13:50:41 +0200637 self.crypto_configfile = CryptoConfigFile(crypto__filename)
638 self.settings.update({name: Setting(active, name, value, section, configfile)
639 for configfile in [self.mbedtls_configfile, self.crypto_configfile]
640 for (active, name, value, section) in configfile.parse_file()})
Gabor Mezei3678dee2024-06-04 19:58:43 +0200641
642 _crypto_regexp = re.compile(r'$PSA_.*')
Gabor Mezeiee521b62024-06-07 13:50:41 +0200643 def _get_configfile(self, name):
644 """Find a config type for a setting name
645 """
646 if name in self.settings:
647 return self.settings[name].configfile
648 elif re.match(self._crypto_regexp, name):
649 return self.crypto_configfile
Gabor Mezei3678dee2024-06-04 19:58:43 +0200650 else:
Gabor Mezeiee521b62024-06-07 13:50:41 +0200651 return self.mbedtls_configfile
Gabor Mezei3678dee2024-06-04 19:58:43 +0200652
Gabor Mezei8a64d8e2024-06-10 15:23:43 +0200653 def __setitem__(self, name, value):
654 super().__setitem__(name, value)
655 self.settings[name].configfile.modified = True
656
Gabor Mezei3678dee2024-06-04 19:58:43 +0200657 def set(self, name, value=None):
Gabor Mezeiee521b62024-06-07 13:50:41 +0200658 configfile = self._get_configfile(name)
Gabor Mezei3678dee2024-06-04 19:58:43 +0200659
Gabor Mezeiee521b62024-06-07 13:50:41 +0200660 if configfile == self.crypto_configfile:
Gabor Mezei542fd382024-06-10 14:07:42 +0200661 if name in PSA_UNSUPPORTED_FEATURE:
Gabor Mezeiee521b62024-06-07 13:50:41 +0200662 raise ValueError(f'Feature is unsupported: \'{name}\'')
Gabor Mezei542fd382024-06-10 14:07:42 +0200663 if name in PSA_UNSTABLE_FEATURE:
Gabor Mezeiee521b62024-06-07 13:50:41 +0200664 raise ValueError(f'Feature is unstable: \'{name}\'')
665
Gabor Mezeid723b512024-06-07 15:31:52 +0200666 # The default value in the crypto config is '1'
667 if not value:
668 value = '1'
669
Gabor Mezei8a64d8e2024-06-10 15:23:43 +0200670 if name in self.settings:
671 setting = self.settings[name]
672 if not setting.active or (value is not None and setting.value != value):
673 configfile.modified = True
674 else:
Gabor Mezeiee521b62024-06-07 13:50:41 +0200675 configfile.templates.append((name, '', '#define ' + name + ' '))
Gabor Mezei8a64d8e2024-06-10 15:23:43 +0200676 configfile.modified = True
Gabor Mezeiee521b62024-06-07 13:50:41 +0200677
678 super().set(name, value)
679
Gabor Mezei8a64d8e2024-06-10 15:23:43 +0200680 def unset(self, name):
681 if name in self.settings and self.settings[name].active:
682 self.settings[name].configfile.modified = True
683
684 super().unset(name)
685
686 def adapt(self, adapter):
687 # Determine if the config files will be modified
688 unmodified = {config for config in [self.mbedtls_configfile, self.crypto_configfile]
689 if not config.modified}
690 if unmodified:
691 for setting in self.settings.values():
692 if not setting.configfile.modified and \
693 setting.active != adapter(setting.name, setting.active, setting.section):
694 setting.configfile.modified = True
695 unmodified.remove(setting.configfile)
696 if not unmodified:
697 break
698
699 super().adapt(adapter)
700
701 def change_matching(self, regexs, enable):
702 # Determine if the config files will be modified
703 if regexs:
704 regex = re.compile('|'.join(regexs))
705 unmodified = {config for config in [self.mbedtls_configfile, self.crypto_configfile]
706 if not config.modified}
707 if unmodified:
708 for setting in self.settings.values():
709 if not setting.configfile.modified and \
710 setting.active != enable and \
711 regex.search(setting.name):
712 setting.configfile.modified = True
713 unmodified.remove(setting.configfile)
714 if not unmodified:
715 break
716
717 super().change_matching(regexs, enable)
718
Gabor Mezei3678dee2024-06-04 19:58:43 +0200719 def write(self, mbedtls_file=None, crypto_file=None):
Gabor Mezei62a9bd02024-06-07 13:44:40 +0200720 """Write the whole configuration to the file it was read from.
721
722 If mbedtls_file or crypto_file is specified, write the specific configuration
723 to the corresponding file instead.
724 """
Gabor Mezeiee521b62024-06-07 13:50:41 +0200725 self.mbedtls_configfile.write(self.settings, mbedtls_file)
726 self.crypto_configfile.write(self.settings, crypto_file)
Gabor Mezei3678dee2024-06-04 19:58:43 +0200727
Gabor Mezeiee521b62024-06-07 13:50:41 +0200728 def filename(self, name=None):
729 if not name:
730 return [config.filename for config in [self.mbedtls_configfile, self.crypto_configfile]]
731
732 return self._get_configfile(name).filename
Gilles Peskineb4063892019-07-27 21:36:44 +0200733
734if __name__ == '__main__':
Gabor Mezei92065ed2024-06-07 13:47:59 +0200735 #pylint: disable=too-many-statements
Gilles Peskineb4063892019-07-27 21:36:44 +0200736 def main():
Bence Szépkútibb0cfeb2021-05-28 09:42:25 +0200737 """Command line mbedtls_config.h manipulation tool."""
Gilles Peskineb4063892019-07-27 21:36:44 +0200738 parser = argparse.ArgumentParser(description="""
Fredrik Hesse0ec8a902021-10-04 22:13:51 +0200739 Mbed TLS configuration file manipulation tool.
Gilles Peskineb4063892019-07-27 21:36:44 +0200740 """)
741 parser.add_argument('--file', '-f',
742 help="""File to read (and modify if requested).
743 Default: {}.
Gabor Mezeif77722d2024-06-28 16:49:33 +0200744 """.format(MbedTLSConfigFile.default_path))
Gabor Mezei3678dee2024-06-04 19:58:43 +0200745 parser.add_argument('--cryptofile', '-c',
746 help="""Crypto file to read (and modify if requested).
747 Default: {}.
748 """.format(CryptoConfigFile.default_path))
Gilles Peskineb4063892019-07-27 21:36:44 +0200749 parser.add_argument('--force', '-o',
Gilles Peskine435ce222019-08-01 23:13:47 +0200750 action='store_true',
Gilles Peskineb4063892019-07-27 21:36:44 +0200751 help="""For the set command, if SYMBOL is not
752 present, add a definition for it.""")
Gilles Peskinec190c902019-08-01 23:31:05 +0200753 parser.add_argument('--write', '-w', metavar='FILE',
Gilles Peskine40f103c2019-07-27 23:44:01 +0200754 help="""File to write to instead of the input file.""")
Gilles Peskineb4063892019-07-27 21:36:44 +0200755 subparsers = parser.add_subparsers(dest='command',
756 title='Commands')
757 parser_get = subparsers.add_parser('get',
758 help="""Find the value of SYMBOL
759 and print it. Exit with
760 status 0 if a #define for SYMBOL is
761 found, 1 otherwise.
762 """)
763 parser_get.add_argument('symbol', metavar='SYMBOL')
764 parser_set = subparsers.add_parser('set',
765 help="""Set SYMBOL to VALUE.
766 If VALUE is omitted, just uncomment
767 the #define for SYMBOL.
768 Error out of a line defining
769 SYMBOL (commented or not) is not
770 found, unless --force is passed.
771 """)
772 parser_set.add_argument('symbol', metavar='SYMBOL')
Gilles Peskine0c7fcd22019-08-01 23:14:00 +0200773 parser_set.add_argument('value', metavar='VALUE', nargs='?',
774 default='')
Gilles Peskine8e90cf42021-05-27 22:12:57 +0200775 parser_set_all = subparsers.add_parser('set-all',
776 help="""Uncomment all #define
777 whose name contains a match for
778 REGEX.""")
779 parser_set_all.add_argument('regexs', metavar='REGEX', nargs='*')
Gilles Peskineb4063892019-07-27 21:36:44 +0200780 parser_unset = subparsers.add_parser('unset',
781 help="""Comment out the #define
782 for SYMBOL. Do nothing if none
783 is present.""")
784 parser_unset.add_argument('symbol', metavar='SYMBOL')
Gilles Peskine8e90cf42021-05-27 22:12:57 +0200785 parser_unset_all = subparsers.add_parser('unset-all',
786 help="""Comment out all #define
787 whose name contains a match for
788 REGEX.""")
789 parser_unset_all.add_argument('regexs', metavar='REGEX', nargs='*')
Gilles Peskineb4063892019-07-27 21:36:44 +0200790
791 def add_adapter(name, function, description):
792 subparser = subparsers.add_parser(name, help=description)
793 subparser.set_defaults(adapter=function)
Gilles Peskine53d41ae2019-07-27 23:31:53 +0200794 add_adapter('baremetal', baremetal_adapter,
795 """Like full, but exclude features that require platform
796 features such as file input-output.""")
Gilles Peskine120f29d2021-09-01 19:51:19 +0200797 add_adapter('baremetal_size', baremetal_size_adapter,
798 """Like baremetal, but exclude debugging features.
799 Useful for code size measurements.""")
Gilles Peskine53d41ae2019-07-27 23:31:53 +0200800 add_adapter('full', full_adapter,
801 """Uncomment most features.
802 Exclude alternative implementations and platform support
803 options, as well as some options that are awkward to test.
804 """)
Gilles Peskine30de2e82020-04-20 21:39:22 +0200805 add_adapter('full_no_deprecated', no_deprecated_adapter(full_adapter),
Gilles Peskinebe1d6092020-04-12 14:17:16 +0200806 """Uncomment most non-deprecated features.
807 Like "full", but without deprecated features.
808 """)
Paul Elliottfb81f772023-10-18 17:44:59 +0100809 add_adapter('full_no_platform', no_platform_adapter(full_adapter),
810 """Uncomment most non-platform features.
811 Like "full", but without platform features.
812 """)
Gilles Peskineb4063892019-07-27 21:36:44 +0200813 add_adapter('realfull', realfull_adapter,
Gilles Peskine53d41ae2019-07-27 23:31:53 +0200814 """Uncomment all boolean #defines.
815 Suitable for generating documentation, but not for building.""")
Gilles Peskine31987c62020-01-31 14:23:30 +0100816 add_adapter('crypto', crypto_adapter(None),
817 """Only include crypto features. Exclude X.509 and TLS.""")
818 add_adapter('crypto_baremetal', crypto_adapter(baremetal_adapter),
819 """Like baremetal, but with only crypto features,
820 excluding X.509 and TLS.""")
821 add_adapter('crypto_full', crypto_adapter(full_adapter),
822 """Like full, but with only crypto features,
823 excluding X.509 and TLS.""")
Gilles Peskineb4063892019-07-27 21:36:44 +0200824
825 args = parser.parse_args()
Gabor Mezei3678dee2024-06-04 19:58:43 +0200826 config = MultiConfig(args.file, args.cryptofile)
Gilles Peskine90b30b62019-07-28 00:36:53 +0200827 if args.command is None:
828 parser.print_help()
829 return 1
830 elif args.command == 'get':
Gilles Peskineb4063892019-07-27 21:36:44 +0200831 if args.symbol in config:
832 value = config[args.symbol]
833 if value:
834 sys.stdout.write(value + '\n')
Gilles Peskinee22a4da2020-03-24 15:43:49 +0100835 return 0 if args.symbol in config else 1
Gilles Peskineb4063892019-07-27 21:36:44 +0200836 elif args.command == 'set':
Gilles Peskine98eb3652019-07-28 16:39:19 +0200837 if not args.force and args.symbol not in config.settings:
Gilles Peskineb4063892019-07-27 21:36:44 +0200838 sys.stderr.write("A #define for the symbol {} "
Gilles Peskine221df1e2019-08-01 23:14:29 +0200839 "was not found in {}\n"
Gabor Mezei3678dee2024-06-04 19:58:43 +0200840 .format(args.symbol, config.filename(args.symbol)))
Gilles Peskineb4063892019-07-27 21:36:44 +0200841 return 1
842 config.set(args.symbol, value=args.value)
Gilles Peskine8e90cf42021-05-27 22:12:57 +0200843 elif args.command == 'set-all':
844 config.change_matching(args.regexs, True)
Gilles Peskineb4063892019-07-27 21:36:44 +0200845 elif args.command == 'unset':
846 config.unset(args.symbol)
Gilles Peskine8e90cf42021-05-27 22:12:57 +0200847 elif args.command == 'unset-all':
848 config.change_matching(args.regexs, False)
Gilles Peskineb4063892019-07-27 21:36:44 +0200849 else:
850 config.adapt(args.adapter)
Gilles Peskine40f103c2019-07-27 23:44:01 +0200851 config.write(args.write)
Gilles Peskinee22a4da2020-03-24 15:43:49 +0100852 return 0
Gilles Peskineb4063892019-07-27 21:36:44 +0200853
854 # Import modules only used by main only if main is defined and called.
855 # pylint: disable=wrong-import-position
856 import argparse
857 import sys
858 sys.exit(main())