1*62c56f98SSadaf Ebrahimi#!/usr/bin/env python3 2*62c56f98SSadaf Ebrahimi 3*62c56f98SSadaf Ebrahimi"""Mbed TLS configuration file manipulation library and tool 4*62c56f98SSadaf Ebrahimi 5*62c56f98SSadaf EbrahimiBasic usage, to read the Mbed TLS configuration: 6*62c56f98SSadaf Ebrahimi config = ConfigFile() 7*62c56f98SSadaf Ebrahimi if 'MBEDTLS_RSA_C' in config: print('RSA is enabled') 8*62c56f98SSadaf Ebrahimi""" 9*62c56f98SSadaf Ebrahimi 10*62c56f98SSadaf Ebrahimi# Note that as long as Mbed TLS 2.28 LTS is maintained, the version of 11*62c56f98SSadaf Ebrahimi# this script in the mbedtls-2.28 branch must remain compatible with 12*62c56f98SSadaf Ebrahimi# Python 3.4. The version in development may only use more recent features 13*62c56f98SSadaf Ebrahimi# in parts that are not backported to 2.28. 14*62c56f98SSadaf Ebrahimi 15*62c56f98SSadaf Ebrahimi## Copyright The Mbed TLS Contributors 16*62c56f98SSadaf Ebrahimi## SPDX-License-Identifier: Apache-2.0 OR GPL-2.0-or-later 17*62c56f98SSadaf Ebrahimi## 18*62c56f98SSadaf Ebrahimi 19*62c56f98SSadaf Ebrahimiimport os 20*62c56f98SSadaf Ebrahimiimport re 21*62c56f98SSadaf Ebrahimi 22*62c56f98SSadaf Ebrahimiclass Setting: 23*62c56f98SSadaf Ebrahimi """Representation of one Mbed TLS mbedtls_config.h setting. 24*62c56f98SSadaf Ebrahimi 25*62c56f98SSadaf Ebrahimi Fields: 26*62c56f98SSadaf Ebrahimi * name: the symbol name ('MBEDTLS_xxx'). 27*62c56f98SSadaf Ebrahimi * value: the value of the macro. The empty string for a plain #define 28*62c56f98SSadaf Ebrahimi with no value. 29*62c56f98SSadaf Ebrahimi * active: True if name is defined, False if a #define for name is 30*62c56f98SSadaf Ebrahimi present in mbedtls_config.h but commented out. 31*62c56f98SSadaf Ebrahimi * section: the name of the section that contains this symbol. 32*62c56f98SSadaf Ebrahimi """ 33*62c56f98SSadaf Ebrahimi # pylint: disable=too-few-public-methods 34*62c56f98SSadaf Ebrahimi def __init__(self, active, name, value='', section=None): 35*62c56f98SSadaf Ebrahimi self.active = active 36*62c56f98SSadaf Ebrahimi self.name = name 37*62c56f98SSadaf Ebrahimi self.value = value 38*62c56f98SSadaf Ebrahimi self.section = section 39*62c56f98SSadaf Ebrahimi 40*62c56f98SSadaf Ebrahimiclass Config: 41*62c56f98SSadaf Ebrahimi """Representation of the Mbed TLS configuration. 42*62c56f98SSadaf Ebrahimi 43*62c56f98SSadaf Ebrahimi In the documentation of this class, a symbol is said to be *active* 44*62c56f98SSadaf Ebrahimi if there is a #define for it that is not commented out, and *known* 45*62c56f98SSadaf Ebrahimi if there is a #define for it whether commented out or not. 46*62c56f98SSadaf Ebrahimi 47*62c56f98SSadaf Ebrahimi This class supports the following protocols: 48*62c56f98SSadaf Ebrahimi * `name in config` is `True` if the symbol `name` is active, `False` 49*62c56f98SSadaf Ebrahimi otherwise (whether `name` is inactive or not known). 50*62c56f98SSadaf Ebrahimi * `config[name]` is the value of the macro `name`. If `name` is inactive, 51*62c56f98SSadaf Ebrahimi raise `KeyError` (even if `name` is known). 52*62c56f98SSadaf Ebrahimi * `config[name] = value` sets the value associated to `name`. `name` 53*62c56f98SSadaf Ebrahimi must be known, but does not need to be set. This does not cause 54*62c56f98SSadaf Ebrahimi name to become set. 55*62c56f98SSadaf Ebrahimi """ 56*62c56f98SSadaf Ebrahimi 57*62c56f98SSadaf Ebrahimi def __init__(self): 58*62c56f98SSadaf Ebrahimi self.settings = {} 59*62c56f98SSadaf Ebrahimi 60*62c56f98SSadaf Ebrahimi def __contains__(self, name): 61*62c56f98SSadaf Ebrahimi """True if the given symbol is active (i.e. set). 62*62c56f98SSadaf Ebrahimi 63*62c56f98SSadaf Ebrahimi False if the given symbol is not set, even if a definition 64*62c56f98SSadaf Ebrahimi is present but commented out. 65*62c56f98SSadaf Ebrahimi """ 66*62c56f98SSadaf Ebrahimi return name in self.settings and self.settings[name].active 67*62c56f98SSadaf Ebrahimi 68*62c56f98SSadaf Ebrahimi def all(self, *names): 69*62c56f98SSadaf Ebrahimi """True if all the elements of names are active (i.e. set).""" 70*62c56f98SSadaf Ebrahimi return all(self.__contains__(name) for name in names) 71*62c56f98SSadaf Ebrahimi 72*62c56f98SSadaf Ebrahimi def any(self, *names): 73*62c56f98SSadaf Ebrahimi """True if at least one symbol in names are active (i.e. set).""" 74*62c56f98SSadaf Ebrahimi return any(self.__contains__(name) for name in names) 75*62c56f98SSadaf Ebrahimi 76*62c56f98SSadaf Ebrahimi def known(self, name): 77*62c56f98SSadaf Ebrahimi """True if a #define for name is present, whether it's commented out or not.""" 78*62c56f98SSadaf Ebrahimi return name in self.settings 79*62c56f98SSadaf Ebrahimi 80*62c56f98SSadaf Ebrahimi def __getitem__(self, name): 81*62c56f98SSadaf Ebrahimi """Get the value of name, i.e. what the preprocessor symbol expands to. 82*62c56f98SSadaf Ebrahimi 83*62c56f98SSadaf Ebrahimi If name is not known, raise KeyError. name does not need to be active. 84*62c56f98SSadaf Ebrahimi """ 85*62c56f98SSadaf Ebrahimi return self.settings[name].value 86*62c56f98SSadaf Ebrahimi 87*62c56f98SSadaf Ebrahimi def get(self, name, default=None): 88*62c56f98SSadaf Ebrahimi """Get the value of name. If name is inactive (not set), return default. 89*62c56f98SSadaf Ebrahimi 90*62c56f98SSadaf Ebrahimi If a #define for name is present and not commented out, return 91*62c56f98SSadaf Ebrahimi its expansion, even if this is the empty string. 92*62c56f98SSadaf Ebrahimi 93*62c56f98SSadaf Ebrahimi If a #define for name is present but commented out, return default. 94*62c56f98SSadaf Ebrahimi """ 95*62c56f98SSadaf Ebrahimi if name in self.settings: 96*62c56f98SSadaf Ebrahimi return self.settings[name].value 97*62c56f98SSadaf Ebrahimi else: 98*62c56f98SSadaf Ebrahimi return default 99*62c56f98SSadaf Ebrahimi 100*62c56f98SSadaf Ebrahimi def __setitem__(self, name, value): 101*62c56f98SSadaf Ebrahimi """If name is known, set its value. 102*62c56f98SSadaf Ebrahimi 103*62c56f98SSadaf Ebrahimi If name is not known, raise KeyError. 104*62c56f98SSadaf Ebrahimi """ 105*62c56f98SSadaf Ebrahimi self.settings[name].value = value 106*62c56f98SSadaf Ebrahimi 107*62c56f98SSadaf Ebrahimi def set(self, name, value=None): 108*62c56f98SSadaf Ebrahimi """Set name to the given value and make it active. 109*62c56f98SSadaf Ebrahimi 110*62c56f98SSadaf Ebrahimi If value is None and name is already known, don't change its value. 111*62c56f98SSadaf Ebrahimi If value is None and name is not known, set its value to the empty 112*62c56f98SSadaf Ebrahimi string. 113*62c56f98SSadaf Ebrahimi """ 114*62c56f98SSadaf Ebrahimi if name in self.settings: 115*62c56f98SSadaf Ebrahimi if value is not None: 116*62c56f98SSadaf Ebrahimi self.settings[name].value = value 117*62c56f98SSadaf Ebrahimi self.settings[name].active = True 118*62c56f98SSadaf Ebrahimi else: 119*62c56f98SSadaf Ebrahimi self.settings[name] = Setting(True, name, value=value) 120*62c56f98SSadaf Ebrahimi 121*62c56f98SSadaf Ebrahimi def unset(self, name): 122*62c56f98SSadaf Ebrahimi """Make name unset (inactive). 123*62c56f98SSadaf Ebrahimi 124*62c56f98SSadaf Ebrahimi name remains known if it was known before. 125*62c56f98SSadaf Ebrahimi """ 126*62c56f98SSadaf Ebrahimi if name not in self.settings: 127*62c56f98SSadaf Ebrahimi return 128*62c56f98SSadaf Ebrahimi self.settings[name].active = False 129*62c56f98SSadaf Ebrahimi 130*62c56f98SSadaf Ebrahimi def adapt(self, adapter): 131*62c56f98SSadaf Ebrahimi """Run adapter on each known symbol and (de)activate it accordingly. 132*62c56f98SSadaf Ebrahimi 133*62c56f98SSadaf Ebrahimi `adapter` must be a function that returns a boolean. It is called as 134*62c56f98SSadaf Ebrahimi `adapter(name, active, section)` for each setting, where `active` is 135*62c56f98SSadaf Ebrahimi `True` if `name` is set and `False` if `name` is known but unset, 136*62c56f98SSadaf Ebrahimi and `section` is the name of the section containing `name`. If 137*62c56f98SSadaf Ebrahimi `adapter` returns `True`, then set `name` (i.e. make it active), 138*62c56f98SSadaf Ebrahimi otherwise unset `name` (i.e. make it known but inactive). 139*62c56f98SSadaf Ebrahimi """ 140*62c56f98SSadaf Ebrahimi for setting in self.settings.values(): 141*62c56f98SSadaf Ebrahimi setting.active = adapter(setting.name, setting.active, 142*62c56f98SSadaf Ebrahimi setting.section) 143*62c56f98SSadaf Ebrahimi 144*62c56f98SSadaf Ebrahimi def change_matching(self, regexs, enable): 145*62c56f98SSadaf Ebrahimi """Change all symbols matching one of the regexs to the desired state.""" 146*62c56f98SSadaf Ebrahimi if not regexs: 147*62c56f98SSadaf Ebrahimi return 148*62c56f98SSadaf Ebrahimi regex = re.compile('|'.join(regexs)) 149*62c56f98SSadaf Ebrahimi for setting in self.settings.values(): 150*62c56f98SSadaf Ebrahimi if regex.search(setting.name): 151*62c56f98SSadaf Ebrahimi setting.active = enable 152*62c56f98SSadaf Ebrahimi 153*62c56f98SSadaf Ebrahimidef is_full_section(section): 154*62c56f98SSadaf Ebrahimi """Is this section affected by "config.py full" and friends?""" 155*62c56f98SSadaf Ebrahimi return section.endswith('support') or section.endswith('modules') 156*62c56f98SSadaf Ebrahimi 157*62c56f98SSadaf Ebrahimidef realfull_adapter(_name, active, section): 158*62c56f98SSadaf Ebrahimi """Activate all symbols found in the global and boolean feature sections. 159*62c56f98SSadaf Ebrahimi 160*62c56f98SSadaf Ebrahimi This is intended for building the documentation, including the 161*62c56f98SSadaf Ebrahimi documentation of settings that are activated by defining an optional 162*62c56f98SSadaf Ebrahimi preprocessor macro. 163*62c56f98SSadaf Ebrahimi 164*62c56f98SSadaf Ebrahimi Do not activate definitions in the section containing symbols that are 165*62c56f98SSadaf Ebrahimi supposed to be defined and documented in their own module. 166*62c56f98SSadaf Ebrahimi """ 167*62c56f98SSadaf Ebrahimi if section == 'Module configuration options': 168*62c56f98SSadaf Ebrahimi return active 169*62c56f98SSadaf Ebrahimi return True 170*62c56f98SSadaf Ebrahimi 171*62c56f98SSadaf Ebrahimi# The goal of the full configuration is to have everything that can be tested 172*62c56f98SSadaf Ebrahimi# together. This includes deprecated or insecure options. It excludes: 173*62c56f98SSadaf Ebrahimi# * Options that require additional build dependencies or unusual hardware. 174*62c56f98SSadaf Ebrahimi# * Options that make testing less effective. 175*62c56f98SSadaf Ebrahimi# * Options that are incompatible with other options, or more generally that 176*62c56f98SSadaf Ebrahimi# interact with other parts of the code in such a way that a bulk enabling 177*62c56f98SSadaf Ebrahimi# is not a good way to test them. 178*62c56f98SSadaf Ebrahimi# * Options that remove features. 179*62c56f98SSadaf EbrahimiEXCLUDE_FROM_FULL = frozenset([ 180*62c56f98SSadaf Ebrahimi #pylint: disable=line-too-long 181*62c56f98SSadaf Ebrahimi 'MBEDTLS_AES_ONLY_128_BIT_KEY_LENGTH', # interacts with CTR_DRBG_128_BIT_KEY 182*62c56f98SSadaf Ebrahimi 'MBEDTLS_AES_USE_HARDWARE_ONLY', # hardware dependency 183*62c56f98SSadaf Ebrahimi 'MBEDTLS_CTR_DRBG_USE_128_BIT_KEY', # interacts with ENTROPY_FORCE_SHA256 184*62c56f98SSadaf Ebrahimi 'MBEDTLS_DEPRECATED_REMOVED', # conflicts with deprecated options 185*62c56f98SSadaf Ebrahimi 'MBEDTLS_DEPRECATED_WARNING', # conflicts with deprecated options 186*62c56f98SSadaf Ebrahimi 'MBEDTLS_ECDH_VARIANT_EVEREST_ENABLED', # influences the use of ECDH in TLS 187*62c56f98SSadaf Ebrahimi 'MBEDTLS_ECP_NO_FALLBACK', # removes internal ECP implementation 188*62c56f98SSadaf Ebrahimi 'MBEDTLS_ECP_WITH_MPI_UINT', # disables the default ECP and is experimental 189*62c56f98SSadaf Ebrahimi 'MBEDTLS_ENTROPY_FORCE_SHA256', # interacts with CTR_DRBG_128_BIT_KEY 190*62c56f98SSadaf Ebrahimi 'MBEDTLS_HAVE_SSE2', # hardware dependency 191*62c56f98SSadaf Ebrahimi 'MBEDTLS_MEMORY_BACKTRACE', # depends on MEMORY_BUFFER_ALLOC_C 192*62c56f98SSadaf Ebrahimi 'MBEDTLS_MEMORY_BUFFER_ALLOC_C', # makes sanitizers (e.g. ASan) less effective 193*62c56f98SSadaf Ebrahimi 'MBEDTLS_MEMORY_DEBUG', # depends on MEMORY_BUFFER_ALLOC_C 194*62c56f98SSadaf Ebrahimi 'MBEDTLS_NO_64BIT_MULTIPLICATION', # influences anything that uses bignum 195*62c56f98SSadaf Ebrahimi 'MBEDTLS_NO_DEFAULT_ENTROPY_SOURCES', # removes a feature 196*62c56f98SSadaf Ebrahimi 'MBEDTLS_NO_PLATFORM_ENTROPY', # removes a feature 197*62c56f98SSadaf Ebrahimi 'MBEDTLS_NO_UDBL_DIVISION', # influences anything that uses bignum 198*62c56f98SSadaf Ebrahimi 'MBEDTLS_PSA_P256M_DRIVER_ENABLED', # influences SECP256R1 KeyGen/ECDH/ECDSA 199*62c56f98SSadaf Ebrahimi 'MBEDTLS_PLATFORM_NO_STD_FUNCTIONS', # removes a feature 200*62c56f98SSadaf Ebrahimi 'MBEDTLS_PSA_CRYPTO_EXTERNAL_RNG', # behavior change + build dependency 201*62c56f98SSadaf Ebrahimi 'MBEDTLS_PSA_CRYPTO_KEY_ID_ENCODES_OWNER', # incompatible with USE_PSA_CRYPTO 202*62c56f98SSadaf Ebrahimi 'MBEDTLS_PSA_CRYPTO_SPM', # platform dependency (PSA SPM) 203*62c56f98SSadaf Ebrahimi 'MBEDTLS_PSA_INJECT_ENTROPY', # conflicts with platform entropy sources 204*62c56f98SSadaf Ebrahimi 'MBEDTLS_RSA_NO_CRT', # influences the use of RSA in X.509 and TLS 205*62c56f98SSadaf Ebrahimi 'MBEDTLS_SHA256_USE_A64_CRYPTO_ONLY', # interacts with *_USE_A64_CRYPTO_IF_PRESENT 206*62c56f98SSadaf Ebrahimi 'MBEDTLS_SHA512_USE_A64_CRYPTO_ONLY', # interacts with *_USE_A64_CRYPTO_IF_PRESENT 207*62c56f98SSadaf Ebrahimi 'MBEDTLS_SSL_RECORD_SIZE_LIMIT', # in development, currently breaks other tests 208*62c56f98SSadaf Ebrahimi 'MBEDTLS_TEST_CONSTANT_FLOW_MEMSAN', # build dependency (clang+memsan) 209*62c56f98SSadaf Ebrahimi 'MBEDTLS_TEST_CONSTANT_FLOW_VALGRIND', # build dependency (valgrind headers) 210*62c56f98SSadaf Ebrahimi 'MBEDTLS_X509_REMOVE_INFO', # removes a feature 211*62c56f98SSadaf Ebrahimi]) 212*62c56f98SSadaf Ebrahimi 213*62c56f98SSadaf Ebrahimidef is_seamless_alt(name): 214*62c56f98SSadaf Ebrahimi """Whether the xxx_ALT symbol should be included in the full configuration. 215*62c56f98SSadaf Ebrahimi 216*62c56f98SSadaf Ebrahimi Include alternative implementations of platform functions, which are 217*62c56f98SSadaf Ebrahimi configurable function pointers that default to the built-in function. 218*62c56f98SSadaf Ebrahimi This way we test that the function pointers exist and build correctly 219*62c56f98SSadaf Ebrahimi without changing the behavior, and tests can verify that the function 220*62c56f98SSadaf Ebrahimi pointers are used by modifying those pointers. 221*62c56f98SSadaf Ebrahimi 222*62c56f98SSadaf Ebrahimi Exclude alternative implementations of library functions since they require 223*62c56f98SSadaf Ebrahimi an implementation of the relevant functions and an xxx_alt.h header. 224*62c56f98SSadaf Ebrahimi """ 225*62c56f98SSadaf Ebrahimi if name in ( 226*62c56f98SSadaf Ebrahimi 'MBEDTLS_PLATFORM_GMTIME_R_ALT', 227*62c56f98SSadaf Ebrahimi 'MBEDTLS_PLATFORM_SETUP_TEARDOWN_ALT', 228*62c56f98SSadaf Ebrahimi 'MBEDTLS_PLATFORM_MS_TIME_ALT', 229*62c56f98SSadaf Ebrahimi 'MBEDTLS_PLATFORM_ZEROIZE_ALT', 230*62c56f98SSadaf Ebrahimi ): 231*62c56f98SSadaf Ebrahimi # Similar to non-platform xxx_ALT, requires platform_alt.h 232*62c56f98SSadaf Ebrahimi return False 233*62c56f98SSadaf Ebrahimi return name.startswith('MBEDTLS_PLATFORM_') 234*62c56f98SSadaf Ebrahimi 235*62c56f98SSadaf Ebrahimidef include_in_full(name): 236*62c56f98SSadaf Ebrahimi """Rules for symbols in the "full" configuration.""" 237*62c56f98SSadaf Ebrahimi if name in EXCLUDE_FROM_FULL: 238*62c56f98SSadaf Ebrahimi return False 239*62c56f98SSadaf Ebrahimi if name.endswith('_ALT'): 240*62c56f98SSadaf Ebrahimi return is_seamless_alt(name) 241*62c56f98SSadaf Ebrahimi return True 242*62c56f98SSadaf Ebrahimi 243*62c56f98SSadaf Ebrahimidef full_adapter(name, active, section): 244*62c56f98SSadaf Ebrahimi """Config adapter for "full".""" 245*62c56f98SSadaf Ebrahimi if not is_full_section(section): 246*62c56f98SSadaf Ebrahimi return active 247*62c56f98SSadaf Ebrahimi return include_in_full(name) 248*62c56f98SSadaf Ebrahimi 249*62c56f98SSadaf Ebrahimi# The baremetal configuration excludes options that require a library or 250*62c56f98SSadaf Ebrahimi# operating system feature that is typically not present on bare metal 251*62c56f98SSadaf Ebrahimi# systems. Features that are excluded from "full" won't be in "baremetal" 252*62c56f98SSadaf Ebrahimi# either (unless explicitly turned on in baremetal_adapter) so they don't 253*62c56f98SSadaf Ebrahimi# need to be repeated here. 254*62c56f98SSadaf EbrahimiEXCLUDE_FROM_BAREMETAL = frozenset([ 255*62c56f98SSadaf Ebrahimi #pylint: disable=line-too-long 256*62c56f98SSadaf Ebrahimi 'MBEDTLS_ENTROPY_NV_SEED', # requires a filesystem and FS_IO or alternate NV seed hooks 257*62c56f98SSadaf Ebrahimi 'MBEDTLS_FS_IO', # requires a filesystem 258*62c56f98SSadaf Ebrahimi 'MBEDTLS_HAVE_TIME', # requires a clock 259*62c56f98SSadaf Ebrahimi 'MBEDTLS_HAVE_TIME_DATE', # requires a clock 260*62c56f98SSadaf Ebrahimi 'MBEDTLS_NET_C', # requires POSIX-like networking 261*62c56f98SSadaf Ebrahimi 'MBEDTLS_PLATFORM_FPRINTF_ALT', # requires FILE* from stdio.h 262*62c56f98SSadaf Ebrahimi 'MBEDTLS_PLATFORM_NV_SEED_ALT', # requires a filesystem and ENTROPY_NV_SEED 263*62c56f98SSadaf Ebrahimi 'MBEDTLS_PLATFORM_TIME_ALT', # requires a clock and HAVE_TIME 264*62c56f98SSadaf Ebrahimi 'MBEDTLS_PSA_CRYPTO_SE_C', # requires a filesystem and PSA_CRYPTO_STORAGE_C 265*62c56f98SSadaf Ebrahimi 'MBEDTLS_PSA_CRYPTO_STORAGE_C', # requires a filesystem 266*62c56f98SSadaf Ebrahimi 'MBEDTLS_PSA_ITS_FILE_C', # requires a filesystem 267*62c56f98SSadaf Ebrahimi 'MBEDTLS_THREADING_C', # requires a threading interface 268*62c56f98SSadaf Ebrahimi 'MBEDTLS_THREADING_PTHREAD', # requires pthread 269*62c56f98SSadaf Ebrahimi 'MBEDTLS_TIMING_C', # requires a clock 270*62c56f98SSadaf Ebrahimi]) 271*62c56f98SSadaf Ebrahimi 272*62c56f98SSadaf Ebrahimidef keep_in_baremetal(name): 273*62c56f98SSadaf Ebrahimi """Rules for symbols in the "baremetal" configuration.""" 274*62c56f98SSadaf Ebrahimi if name in EXCLUDE_FROM_BAREMETAL: 275*62c56f98SSadaf Ebrahimi return False 276*62c56f98SSadaf Ebrahimi return True 277*62c56f98SSadaf Ebrahimi 278*62c56f98SSadaf Ebrahimidef baremetal_adapter(name, active, section): 279*62c56f98SSadaf Ebrahimi """Config adapter for "baremetal".""" 280*62c56f98SSadaf Ebrahimi if not is_full_section(section): 281*62c56f98SSadaf Ebrahimi return active 282*62c56f98SSadaf Ebrahimi if name == 'MBEDTLS_NO_PLATFORM_ENTROPY': 283*62c56f98SSadaf Ebrahimi # No OS-provided entropy source 284*62c56f98SSadaf Ebrahimi return True 285*62c56f98SSadaf Ebrahimi return include_in_full(name) and keep_in_baremetal(name) 286*62c56f98SSadaf Ebrahimi 287*62c56f98SSadaf Ebrahimi# This set contains options that are mostly for debugging or test purposes, 288*62c56f98SSadaf Ebrahimi# and therefore should be excluded when doing code size measurements. 289*62c56f98SSadaf Ebrahimi# Options that are their own module (such as MBEDTLS_ERROR_C) are not listed 290*62c56f98SSadaf Ebrahimi# and therefore will be included when doing code size measurements. 291*62c56f98SSadaf EbrahimiEXCLUDE_FOR_SIZE = frozenset([ 292*62c56f98SSadaf Ebrahimi 'MBEDTLS_DEBUG_C', # large code size increase in TLS 293*62c56f98SSadaf Ebrahimi 'MBEDTLS_SELF_TEST', # increases the size of many modules 294*62c56f98SSadaf Ebrahimi 'MBEDTLS_TEST_HOOKS', # only useful with the hosted test framework, increases code size 295*62c56f98SSadaf Ebrahimi]) 296*62c56f98SSadaf Ebrahimi 297*62c56f98SSadaf Ebrahimidef baremetal_size_adapter(name, active, section): 298*62c56f98SSadaf Ebrahimi if name in EXCLUDE_FOR_SIZE: 299*62c56f98SSadaf Ebrahimi return False 300*62c56f98SSadaf Ebrahimi return baremetal_adapter(name, active, section) 301*62c56f98SSadaf Ebrahimi 302*62c56f98SSadaf Ebrahimidef include_in_crypto(name): 303*62c56f98SSadaf Ebrahimi """Rules for symbols in a crypto configuration.""" 304*62c56f98SSadaf Ebrahimi if name.startswith('MBEDTLS_X509_') or \ 305*62c56f98SSadaf Ebrahimi name.startswith('MBEDTLS_SSL_') or \ 306*62c56f98SSadaf Ebrahimi name.startswith('MBEDTLS_KEY_EXCHANGE_'): 307*62c56f98SSadaf Ebrahimi return False 308*62c56f98SSadaf Ebrahimi if name in [ 309*62c56f98SSadaf Ebrahimi 'MBEDTLS_DEBUG_C', # part of libmbedtls 310*62c56f98SSadaf Ebrahimi 'MBEDTLS_NET_C', # part of libmbedtls 311*62c56f98SSadaf Ebrahimi 'MBEDTLS_PKCS7_C', # part of libmbedx509 312*62c56f98SSadaf Ebrahimi ]: 313*62c56f98SSadaf Ebrahimi return False 314*62c56f98SSadaf Ebrahimi return True 315*62c56f98SSadaf Ebrahimi 316*62c56f98SSadaf Ebrahimidef crypto_adapter(adapter): 317*62c56f98SSadaf Ebrahimi """Modify an adapter to disable non-crypto symbols. 318*62c56f98SSadaf Ebrahimi 319*62c56f98SSadaf Ebrahimi ``crypto_adapter(adapter)(name, active, section)`` is like 320*62c56f98SSadaf Ebrahimi ``adapter(name, active, section)``, but unsets all X.509 and TLS symbols. 321*62c56f98SSadaf Ebrahimi """ 322*62c56f98SSadaf Ebrahimi def continuation(name, active, section): 323*62c56f98SSadaf Ebrahimi if not include_in_crypto(name): 324*62c56f98SSadaf Ebrahimi return False 325*62c56f98SSadaf Ebrahimi if adapter is None: 326*62c56f98SSadaf Ebrahimi return active 327*62c56f98SSadaf Ebrahimi return adapter(name, active, section) 328*62c56f98SSadaf Ebrahimi return continuation 329*62c56f98SSadaf Ebrahimi 330*62c56f98SSadaf EbrahimiDEPRECATED = frozenset([ 331*62c56f98SSadaf Ebrahimi 'MBEDTLS_PSA_CRYPTO_SE_C', 332*62c56f98SSadaf Ebrahimi]) 333*62c56f98SSadaf Ebrahimidef no_deprecated_adapter(adapter): 334*62c56f98SSadaf Ebrahimi """Modify an adapter to disable deprecated symbols. 335*62c56f98SSadaf Ebrahimi 336*62c56f98SSadaf Ebrahimi ``no_deprecated_adapter(adapter)(name, active, section)`` is like 337*62c56f98SSadaf Ebrahimi ``adapter(name, active, section)``, but unsets all deprecated symbols 338*62c56f98SSadaf Ebrahimi and sets ``MBEDTLS_DEPRECATED_REMOVED``. 339*62c56f98SSadaf Ebrahimi """ 340*62c56f98SSadaf Ebrahimi def continuation(name, active, section): 341*62c56f98SSadaf Ebrahimi if name == 'MBEDTLS_DEPRECATED_REMOVED': 342*62c56f98SSadaf Ebrahimi return True 343*62c56f98SSadaf Ebrahimi if name in DEPRECATED: 344*62c56f98SSadaf Ebrahimi return False 345*62c56f98SSadaf Ebrahimi if adapter is None: 346*62c56f98SSadaf Ebrahimi return active 347*62c56f98SSadaf Ebrahimi return adapter(name, active, section) 348*62c56f98SSadaf Ebrahimi return continuation 349*62c56f98SSadaf Ebrahimi 350*62c56f98SSadaf Ebrahimiclass ConfigFile(Config): 351*62c56f98SSadaf Ebrahimi """Representation of the Mbed TLS configuration read for a file. 352*62c56f98SSadaf Ebrahimi 353*62c56f98SSadaf Ebrahimi See the documentation of the `Config` class for methods to query 354*62c56f98SSadaf Ebrahimi and modify the configuration. 355*62c56f98SSadaf Ebrahimi """ 356*62c56f98SSadaf Ebrahimi 357*62c56f98SSadaf Ebrahimi _path_in_tree = 'include/mbedtls/mbedtls_config.h' 358*62c56f98SSadaf Ebrahimi default_path = [_path_in_tree, 359*62c56f98SSadaf Ebrahimi os.path.join(os.path.dirname(__file__), 360*62c56f98SSadaf Ebrahimi os.pardir, 361*62c56f98SSadaf Ebrahimi _path_in_tree), 362*62c56f98SSadaf Ebrahimi os.path.join(os.path.dirname(os.path.abspath(os.path.dirname(__file__))), 363*62c56f98SSadaf Ebrahimi _path_in_tree)] 364*62c56f98SSadaf Ebrahimi 365*62c56f98SSadaf Ebrahimi def __init__(self, filename=None): 366*62c56f98SSadaf Ebrahimi """Read the Mbed TLS configuration file.""" 367*62c56f98SSadaf Ebrahimi if filename is None: 368*62c56f98SSadaf Ebrahimi for candidate in self.default_path: 369*62c56f98SSadaf Ebrahimi if os.path.lexists(candidate): 370*62c56f98SSadaf Ebrahimi filename = candidate 371*62c56f98SSadaf Ebrahimi break 372*62c56f98SSadaf Ebrahimi else: 373*62c56f98SSadaf Ebrahimi raise Exception('Mbed TLS configuration file not found', 374*62c56f98SSadaf Ebrahimi self.default_path) 375*62c56f98SSadaf Ebrahimi super().__init__() 376*62c56f98SSadaf Ebrahimi self.filename = filename 377*62c56f98SSadaf Ebrahimi self.current_section = 'header' 378*62c56f98SSadaf Ebrahimi with open(filename, 'r', encoding='utf-8') as file: 379*62c56f98SSadaf Ebrahimi self.templates = [self._parse_line(line) for line in file] 380*62c56f98SSadaf Ebrahimi self.current_section = None 381*62c56f98SSadaf Ebrahimi 382*62c56f98SSadaf Ebrahimi def set(self, name, value=None): 383*62c56f98SSadaf Ebrahimi if name not in self.settings: 384*62c56f98SSadaf Ebrahimi self.templates.append((name, '', '#define ' + name + ' ')) 385*62c56f98SSadaf Ebrahimi super().set(name, value) 386*62c56f98SSadaf Ebrahimi 387*62c56f98SSadaf Ebrahimi _define_line_regexp = (r'(?P<indentation>\s*)' + 388*62c56f98SSadaf Ebrahimi r'(?P<commented_out>(//\s*)?)' + 389*62c56f98SSadaf Ebrahimi r'(?P<define>#\s*define\s+)' + 390*62c56f98SSadaf Ebrahimi r'(?P<name>\w+)' + 391*62c56f98SSadaf Ebrahimi r'(?P<arguments>(?:\((?:\w|\s|,)*\))?)' + 392*62c56f98SSadaf Ebrahimi r'(?P<separator>\s*)' + 393*62c56f98SSadaf Ebrahimi r'(?P<value>.*)') 394*62c56f98SSadaf Ebrahimi _section_line_regexp = (r'\s*/?\*+\s*[\\@]name\s+SECTION:\s*' + 395*62c56f98SSadaf Ebrahimi r'(?P<section>.*)[ */]*') 396*62c56f98SSadaf Ebrahimi _config_line_regexp = re.compile(r'|'.join([_define_line_regexp, 397*62c56f98SSadaf Ebrahimi _section_line_regexp])) 398*62c56f98SSadaf Ebrahimi def _parse_line(self, line): 399*62c56f98SSadaf Ebrahimi """Parse a line in mbedtls_config.h and return the corresponding template.""" 400*62c56f98SSadaf Ebrahimi line = line.rstrip('\r\n') 401*62c56f98SSadaf Ebrahimi m = re.match(self._config_line_regexp, line) 402*62c56f98SSadaf Ebrahimi if m is None: 403*62c56f98SSadaf Ebrahimi return line 404*62c56f98SSadaf Ebrahimi elif m.group('section'): 405*62c56f98SSadaf Ebrahimi self.current_section = m.group('section') 406*62c56f98SSadaf Ebrahimi return line 407*62c56f98SSadaf Ebrahimi else: 408*62c56f98SSadaf Ebrahimi active = not m.group('commented_out') 409*62c56f98SSadaf Ebrahimi name = m.group('name') 410*62c56f98SSadaf Ebrahimi value = m.group('value') 411*62c56f98SSadaf Ebrahimi template = (name, 412*62c56f98SSadaf Ebrahimi m.group('indentation'), 413*62c56f98SSadaf Ebrahimi m.group('define') + name + 414*62c56f98SSadaf Ebrahimi m.group('arguments') + m.group('separator')) 415*62c56f98SSadaf Ebrahimi self.settings[name] = Setting(active, name, value, 416*62c56f98SSadaf Ebrahimi self.current_section) 417*62c56f98SSadaf Ebrahimi return template 418*62c56f98SSadaf Ebrahimi 419*62c56f98SSadaf Ebrahimi def _format_template(self, name, indent, middle): 420*62c56f98SSadaf Ebrahimi """Build a line for mbedtls_config.h for the given setting. 421*62c56f98SSadaf Ebrahimi 422*62c56f98SSadaf Ebrahimi The line has the form "<indent>#define <name> <value>" 423*62c56f98SSadaf Ebrahimi where <middle> is "#define <name> ". 424*62c56f98SSadaf Ebrahimi """ 425*62c56f98SSadaf Ebrahimi setting = self.settings[name] 426*62c56f98SSadaf Ebrahimi value = setting.value 427*62c56f98SSadaf Ebrahimi if value is None: 428*62c56f98SSadaf Ebrahimi value = '' 429*62c56f98SSadaf Ebrahimi # Normally the whitespace to separate the symbol name from the 430*62c56f98SSadaf Ebrahimi # value is part of middle, and there's no whitespace for a symbol 431*62c56f98SSadaf Ebrahimi # with no value. But if a symbol has been changed from having a 432*62c56f98SSadaf Ebrahimi # value to not having one, the whitespace is wrong, so fix it. 433*62c56f98SSadaf Ebrahimi if value: 434*62c56f98SSadaf Ebrahimi if middle[-1] not in '\t ': 435*62c56f98SSadaf Ebrahimi middle += ' ' 436*62c56f98SSadaf Ebrahimi else: 437*62c56f98SSadaf Ebrahimi middle = middle.rstrip() 438*62c56f98SSadaf Ebrahimi return ''.join([indent, 439*62c56f98SSadaf Ebrahimi '' if setting.active else '//', 440*62c56f98SSadaf Ebrahimi middle, 441*62c56f98SSadaf Ebrahimi value]).rstrip() 442*62c56f98SSadaf Ebrahimi 443*62c56f98SSadaf Ebrahimi def write_to_stream(self, output): 444*62c56f98SSadaf Ebrahimi """Write the whole configuration to output.""" 445*62c56f98SSadaf Ebrahimi for template in self.templates: 446*62c56f98SSadaf Ebrahimi if isinstance(template, str): 447*62c56f98SSadaf Ebrahimi line = template 448*62c56f98SSadaf Ebrahimi else: 449*62c56f98SSadaf Ebrahimi line = self._format_template(*template) 450*62c56f98SSadaf Ebrahimi output.write(line + '\n') 451*62c56f98SSadaf Ebrahimi 452*62c56f98SSadaf Ebrahimi def write(self, filename=None): 453*62c56f98SSadaf Ebrahimi """Write the whole configuration to the file it was read from. 454*62c56f98SSadaf Ebrahimi 455*62c56f98SSadaf Ebrahimi If filename is specified, write to this file instead. 456*62c56f98SSadaf Ebrahimi """ 457*62c56f98SSadaf Ebrahimi if filename is None: 458*62c56f98SSadaf Ebrahimi filename = self.filename 459*62c56f98SSadaf Ebrahimi with open(filename, 'w', encoding='utf-8') as output: 460*62c56f98SSadaf Ebrahimi self.write_to_stream(output) 461*62c56f98SSadaf Ebrahimi 462*62c56f98SSadaf Ebrahimiif __name__ == '__main__': 463*62c56f98SSadaf Ebrahimi def main(): 464*62c56f98SSadaf Ebrahimi """Command line mbedtls_config.h manipulation tool.""" 465*62c56f98SSadaf Ebrahimi parser = argparse.ArgumentParser(description=""" 466*62c56f98SSadaf Ebrahimi Mbed TLS configuration file manipulation tool. 467*62c56f98SSadaf Ebrahimi """) 468*62c56f98SSadaf Ebrahimi parser.add_argument('--file', '-f', 469*62c56f98SSadaf Ebrahimi help="""File to read (and modify if requested). 470*62c56f98SSadaf Ebrahimi Default: {}. 471*62c56f98SSadaf Ebrahimi """.format(ConfigFile.default_path)) 472*62c56f98SSadaf Ebrahimi parser.add_argument('--force', '-o', 473*62c56f98SSadaf Ebrahimi action='store_true', 474*62c56f98SSadaf Ebrahimi help="""For the set command, if SYMBOL is not 475*62c56f98SSadaf Ebrahimi present, add a definition for it.""") 476*62c56f98SSadaf Ebrahimi parser.add_argument('--write', '-w', metavar='FILE', 477*62c56f98SSadaf Ebrahimi help="""File to write to instead of the input file.""") 478*62c56f98SSadaf Ebrahimi subparsers = parser.add_subparsers(dest='command', 479*62c56f98SSadaf Ebrahimi title='Commands') 480*62c56f98SSadaf Ebrahimi parser_get = subparsers.add_parser('get', 481*62c56f98SSadaf Ebrahimi help="""Find the value of SYMBOL 482*62c56f98SSadaf Ebrahimi and print it. Exit with 483*62c56f98SSadaf Ebrahimi status 0 if a #define for SYMBOL is 484*62c56f98SSadaf Ebrahimi found, 1 otherwise. 485*62c56f98SSadaf Ebrahimi """) 486*62c56f98SSadaf Ebrahimi parser_get.add_argument('symbol', metavar='SYMBOL') 487*62c56f98SSadaf Ebrahimi parser_set = subparsers.add_parser('set', 488*62c56f98SSadaf Ebrahimi help="""Set SYMBOL to VALUE. 489*62c56f98SSadaf Ebrahimi If VALUE is omitted, just uncomment 490*62c56f98SSadaf Ebrahimi the #define for SYMBOL. 491*62c56f98SSadaf Ebrahimi Error out of a line defining 492*62c56f98SSadaf Ebrahimi SYMBOL (commented or not) is not 493*62c56f98SSadaf Ebrahimi found, unless --force is passed. 494*62c56f98SSadaf Ebrahimi """) 495*62c56f98SSadaf Ebrahimi parser_set.add_argument('symbol', metavar='SYMBOL') 496*62c56f98SSadaf Ebrahimi parser_set.add_argument('value', metavar='VALUE', nargs='?', 497*62c56f98SSadaf Ebrahimi default='') 498*62c56f98SSadaf Ebrahimi parser_set_all = subparsers.add_parser('set-all', 499*62c56f98SSadaf Ebrahimi help="""Uncomment all #define 500*62c56f98SSadaf Ebrahimi whose name contains a match for 501*62c56f98SSadaf Ebrahimi REGEX.""") 502*62c56f98SSadaf Ebrahimi parser_set_all.add_argument('regexs', metavar='REGEX', nargs='*') 503*62c56f98SSadaf Ebrahimi parser_unset = subparsers.add_parser('unset', 504*62c56f98SSadaf Ebrahimi help="""Comment out the #define 505*62c56f98SSadaf Ebrahimi for SYMBOL. Do nothing if none 506*62c56f98SSadaf Ebrahimi is present.""") 507*62c56f98SSadaf Ebrahimi parser_unset.add_argument('symbol', metavar='SYMBOL') 508*62c56f98SSadaf Ebrahimi parser_unset_all = subparsers.add_parser('unset-all', 509*62c56f98SSadaf Ebrahimi help="""Comment out all #define 510*62c56f98SSadaf Ebrahimi whose name contains a match for 511*62c56f98SSadaf Ebrahimi REGEX.""") 512*62c56f98SSadaf Ebrahimi parser_unset_all.add_argument('regexs', metavar='REGEX', nargs='*') 513*62c56f98SSadaf Ebrahimi 514*62c56f98SSadaf Ebrahimi def add_adapter(name, function, description): 515*62c56f98SSadaf Ebrahimi subparser = subparsers.add_parser(name, help=description) 516*62c56f98SSadaf Ebrahimi subparser.set_defaults(adapter=function) 517*62c56f98SSadaf Ebrahimi add_adapter('baremetal', baremetal_adapter, 518*62c56f98SSadaf Ebrahimi """Like full, but exclude features that require platform 519*62c56f98SSadaf Ebrahimi features such as file input-output.""") 520*62c56f98SSadaf Ebrahimi add_adapter('baremetal_size', baremetal_size_adapter, 521*62c56f98SSadaf Ebrahimi """Like baremetal, but exclude debugging features. 522*62c56f98SSadaf Ebrahimi Useful for code size measurements.""") 523*62c56f98SSadaf Ebrahimi add_adapter('full', full_adapter, 524*62c56f98SSadaf Ebrahimi """Uncomment most features. 525*62c56f98SSadaf Ebrahimi Exclude alternative implementations and platform support 526*62c56f98SSadaf Ebrahimi options, as well as some options that are awkward to test. 527*62c56f98SSadaf Ebrahimi """) 528*62c56f98SSadaf Ebrahimi add_adapter('full_no_deprecated', no_deprecated_adapter(full_adapter), 529*62c56f98SSadaf Ebrahimi """Uncomment most non-deprecated features. 530*62c56f98SSadaf Ebrahimi Like "full", but without deprecated features. 531*62c56f98SSadaf Ebrahimi """) 532*62c56f98SSadaf Ebrahimi add_adapter('realfull', realfull_adapter, 533*62c56f98SSadaf Ebrahimi """Uncomment all boolean #defines. 534*62c56f98SSadaf Ebrahimi Suitable for generating documentation, but not for building.""") 535*62c56f98SSadaf Ebrahimi add_adapter('crypto', crypto_adapter(None), 536*62c56f98SSadaf Ebrahimi """Only include crypto features. Exclude X.509 and TLS.""") 537*62c56f98SSadaf Ebrahimi add_adapter('crypto_baremetal', crypto_adapter(baremetal_adapter), 538*62c56f98SSadaf Ebrahimi """Like baremetal, but with only crypto features, 539*62c56f98SSadaf Ebrahimi excluding X.509 and TLS.""") 540*62c56f98SSadaf Ebrahimi add_adapter('crypto_full', crypto_adapter(full_adapter), 541*62c56f98SSadaf Ebrahimi """Like full, but with only crypto features, 542*62c56f98SSadaf Ebrahimi excluding X.509 and TLS.""") 543*62c56f98SSadaf Ebrahimi 544*62c56f98SSadaf Ebrahimi args = parser.parse_args() 545*62c56f98SSadaf Ebrahimi config = ConfigFile(args.file) 546*62c56f98SSadaf Ebrahimi if args.command is None: 547*62c56f98SSadaf Ebrahimi parser.print_help() 548*62c56f98SSadaf Ebrahimi return 1 549*62c56f98SSadaf Ebrahimi elif args.command == 'get': 550*62c56f98SSadaf Ebrahimi if args.symbol in config: 551*62c56f98SSadaf Ebrahimi value = config[args.symbol] 552*62c56f98SSadaf Ebrahimi if value: 553*62c56f98SSadaf Ebrahimi sys.stdout.write(value + '\n') 554*62c56f98SSadaf Ebrahimi return 0 if args.symbol in config else 1 555*62c56f98SSadaf Ebrahimi elif args.command == 'set': 556*62c56f98SSadaf Ebrahimi if not args.force and args.symbol not in config.settings: 557*62c56f98SSadaf Ebrahimi sys.stderr.write("A #define for the symbol {} " 558*62c56f98SSadaf Ebrahimi "was not found in {}\n" 559*62c56f98SSadaf Ebrahimi .format(args.symbol, config.filename)) 560*62c56f98SSadaf Ebrahimi return 1 561*62c56f98SSadaf Ebrahimi config.set(args.symbol, value=args.value) 562*62c56f98SSadaf Ebrahimi elif args.command == 'set-all': 563*62c56f98SSadaf Ebrahimi config.change_matching(args.regexs, True) 564*62c56f98SSadaf Ebrahimi elif args.command == 'unset': 565*62c56f98SSadaf Ebrahimi config.unset(args.symbol) 566*62c56f98SSadaf Ebrahimi elif args.command == 'unset-all': 567*62c56f98SSadaf Ebrahimi config.change_matching(args.regexs, False) 568*62c56f98SSadaf Ebrahimi else: 569*62c56f98SSadaf Ebrahimi config.adapt(args.adapter) 570*62c56f98SSadaf Ebrahimi config.write(args.write) 571*62c56f98SSadaf Ebrahimi return 0 572*62c56f98SSadaf Ebrahimi 573*62c56f98SSadaf Ebrahimi # Import modules only used by main only if main is defined and called. 574*62c56f98SSadaf Ebrahimi # pylint: disable=wrong-import-position 575*62c56f98SSadaf Ebrahimi import argparse 576*62c56f98SSadaf Ebrahimi import sys 577*62c56f98SSadaf Ebrahimi sys.exit(main()) 578