config.py 22 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534
  1. #!/usr/bin/env python3
  2. """Mbed TLS configuration file manipulation library and tool
  3. Basic usage, to read the Mbed TLS or Mbed Crypto configuration:
  4. config = ConfigFile()
  5. if 'MBEDTLS_RSA_C' in config: print('RSA is enabled')
  6. """
  7. ## Copyright The Mbed TLS Contributors
  8. ## SPDX-License-Identifier: Apache-2.0
  9. ##
  10. ## Licensed under the Apache License, Version 2.0 (the "License"); you may
  11. ## not use this file except in compliance with the License.
  12. ## You may obtain a copy of the License at
  13. ##
  14. ## http://www.apache.org/licenses/LICENSE-2.0
  15. ##
  16. ## Unless required by applicable law or agreed to in writing, software
  17. ## distributed under the License is distributed on an "AS IS" BASIS, WITHOUT
  18. ## WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
  19. ## See the License for the specific language governing permissions and
  20. ## limitations under the License.
  21. import os
  22. import re
  23. class Setting:
  24. """Representation of one Mbed TLS config.h setting.
  25. Fields:
  26. * name: the symbol name ('MBEDTLS_xxx').
  27. * value: the value of the macro. The empty string for a plain #define
  28. with no value.
  29. * active: True if name is defined, False if a #define for name is
  30. present in config.h but commented out.
  31. * section: the name of the section that contains this symbol.
  32. """
  33. # pylint: disable=too-few-public-methods
  34. def __init__(self, active, name, value='', section=None):
  35. self.active = active
  36. self.name = name
  37. self.value = value
  38. self.section = section
  39. class Config:
  40. """Representation of the Mbed TLS configuration.
  41. In the documentation of this class, a symbol is said to be *active*
  42. if there is a #define for it that is not commented out, and *known*
  43. if there is a #define for it whether commented out or not.
  44. This class supports the following protocols:
  45. * `name in config` is `True` if the symbol `name` is active, `False`
  46. otherwise (whether `name` is inactive or not known).
  47. * `config[name]` is the value of the macro `name`. If `name` is inactive,
  48. raise `KeyError` (even if `name` is known).
  49. * `config[name] = value` sets the value associated to `name`. `name`
  50. must be known, but does not need to be set. This does not cause
  51. name to become set.
  52. """
  53. def __init__(self):
  54. self.settings = {}
  55. def __contains__(self, name):
  56. """True if the given symbol is active (i.e. set).
  57. False if the given symbol is not set, even if a definition
  58. is present but commented out.
  59. """
  60. return name in self.settings and self.settings[name].active
  61. def all(self, *names):
  62. """True if all the elements of names are active (i.e. set)."""
  63. return all(self.__contains__(name) for name in names)
  64. def any(self, *names):
  65. """True if at least one symbol in names are active (i.e. set)."""
  66. return any(self.__contains__(name) for name in names)
  67. def known(self, name):
  68. """True if a #define for name is present, whether it's commented out or not."""
  69. return name in self.settings
  70. def __getitem__(self, name):
  71. """Get the value of name, i.e. what the preprocessor symbol expands to.
  72. If name is not known, raise KeyError. name does not need to be active.
  73. """
  74. return self.settings[name].value
  75. def get(self, name, default=None):
  76. """Get the value of name. If name is inactive (not set), return default.
  77. If a #define for name is present and not commented out, return
  78. its expansion, even if this is the empty string.
  79. If a #define for name is present but commented out, return default.
  80. """
  81. if name in self.settings:
  82. return self.settings[name].value
  83. else:
  84. return default
  85. def __setitem__(self, name, value):
  86. """If name is known, set its value.
  87. If name is not known, raise KeyError.
  88. """
  89. self.settings[name].value = value
  90. def set(self, name, value=None):
  91. """Set name to the given value and make it active.
  92. If value is None and name is already known, don't change its value.
  93. If value is None and name is not known, set its value to the empty
  94. string.
  95. """
  96. if name in self.settings:
  97. if value is not None:
  98. self.settings[name].value = value
  99. self.settings[name].active = True
  100. else:
  101. self.settings[name] = Setting(True, name, value=value)
  102. def unset(self, name):
  103. """Make name unset (inactive).
  104. name remains known if it was known before.
  105. """
  106. if name not in self.settings:
  107. return
  108. self.settings[name].active = False
  109. def adapt(self, adapter):
  110. """Run adapter on each known symbol and (de)activate it accordingly.
  111. `adapter` must be a function that returns a boolean. It is called as
  112. `adapter(name, active, section)` for each setting, where `active` is
  113. `True` if `name` is set and `False` if `name` is known but unset,
  114. and `section` is the name of the section containing `name`. If
  115. `adapter` returns `True`, then set `name` (i.e. make it active),
  116. otherwise unset `name` (i.e. make it known but inactive).
  117. """
  118. for setting in self.settings.values():
  119. setting.active = adapter(setting.name, setting.active,
  120. setting.section)
  121. def is_full_section(section):
  122. """Is this section affected by "config.py full" and friends?"""
  123. return section.endswith('support') or section.endswith('modules')
  124. def realfull_adapter(_name, active, section):
  125. """Activate all symbols found in the system and feature sections."""
  126. if not is_full_section(section):
  127. return active
  128. return True
  129. # The goal of the full configuration is to have everything that can be tested
  130. # together. This includes deprecated or insecure options. It excludes:
  131. # * Options that require additional build dependencies or unusual hardware.
  132. # * Options that make testing less effective.
  133. # * Options that are incompatible with other options, or more generally that
  134. # interact with other parts of the code in such a way that a bulk enabling
  135. # is not a good way to test them.
  136. # * Options that remove features.
  137. EXCLUDE_FROM_FULL = frozenset([
  138. #pylint: disable=line-too-long
  139. 'MBEDTLS_CTR_DRBG_USE_128_BIT_KEY', # interacts with ENTROPY_FORCE_SHA256
  140. 'MBEDTLS_DEPRECATED_REMOVED', # conflicts with deprecated options
  141. 'MBEDTLS_DEPRECATED_WARNING', # conflicts with deprecated options
  142. 'MBEDTLS_ECDH_VARIANT_EVEREST_ENABLED', # influences the use of ECDH in TLS
  143. 'MBEDTLS_ECP_NO_INTERNAL_RNG', # removes a feature
  144. 'MBEDTLS_ECP_RESTARTABLE', # incompatible with USE_PSA_CRYPTO
  145. 'MBEDTLS_ENTROPY_FORCE_SHA256', # interacts with CTR_DRBG_128_BIT_KEY
  146. 'MBEDTLS_HAVE_SSE2', # hardware dependency
  147. 'MBEDTLS_MEMORY_BACKTRACE', # depends on MEMORY_BUFFER_ALLOC_C
  148. 'MBEDTLS_MEMORY_BUFFER_ALLOC_C', # makes sanitizers (e.g. ASan) less effective
  149. 'MBEDTLS_MEMORY_DEBUG', # depends on MEMORY_BUFFER_ALLOC_C
  150. 'MBEDTLS_NO_64BIT_MULTIPLICATION', # influences anything that uses bignum
  151. 'MBEDTLS_NO_DEFAULT_ENTROPY_SOURCES', # removes a feature
  152. 'MBEDTLS_NO_PLATFORM_ENTROPY', # removes a feature
  153. 'MBEDTLS_NO_UDBL_DIVISION', # influences anything that uses bignum
  154. 'MBEDTLS_PKCS11_C', # build dependency (libpkcs11-helper)
  155. 'MBEDTLS_PLATFORM_NO_STD_FUNCTIONS', # removes a feature
  156. 'MBEDTLS_PSA_CRYPTO_CONFIG', # toggles old/new style PSA config
  157. 'MBEDTLS_PSA_CRYPTO_KEY_ID_ENCODES_OWNER', # incompatible with USE_PSA_CRYPTO
  158. 'MBEDTLS_PSA_CRYPTO_SPM', # platform dependency (PSA SPM)
  159. 'MBEDTLS_PSA_INJECT_ENTROPY', # build dependency (hook functions)
  160. 'MBEDTLS_REMOVE_3DES_CIPHERSUITES', # removes a feature
  161. 'MBEDTLS_REMOVE_ARC4_CIPHERSUITES', # removes a feature
  162. 'MBEDTLS_RSA_NO_CRT', # influences the use of RSA in X.509 and TLS
  163. 'MBEDTLS_SHA512_NO_SHA384', # removes a feature
  164. 'MBEDTLS_SSL_HW_RECORD_ACCEL', # build dependency (hook functions)
  165. 'MBEDTLS_TEST_CONSTANT_FLOW_MEMSAN', # build dependency (clang+memsan)
  166. 'MBEDTLS_TEST_CONSTANT_FLOW_VALGRIND', # build dependency (valgrind headers)
  167. 'MBEDTLS_TEST_NULL_ENTROPY', # removes a feature
  168. 'MBEDTLS_X509_ALLOW_UNSUPPORTED_CRITICAL_EXTENSION', # influences the use of X.509 in TLS
  169. 'MBEDTLS_ZLIB_SUPPORT', # build dependency (libz)
  170. ])
  171. def is_seamless_alt(name):
  172. """Whether the xxx_ALT symbol should be included in the full configuration.
  173. Include alternative implementations of platform functions, which are
  174. configurable function pointers that default to the built-in function.
  175. This way we test that the function pointers exist and build correctly
  176. without changing the behavior, and tests can verify that the function
  177. pointers are used by modifying those pointers.
  178. Exclude alternative implementations of library functions since they require
  179. an implementation of the relevant functions and an xxx_alt.h header.
  180. """
  181. if name == 'MBEDTLS_PLATFORM_SETUP_TEARDOWN_ALT':
  182. # Similar to non-platform xxx_ALT, requires platform_alt.h
  183. return False
  184. return name.startswith('MBEDTLS_PLATFORM_')
  185. def include_in_full(name):
  186. """Rules for symbols in the "full" configuration."""
  187. if name in EXCLUDE_FROM_FULL:
  188. return False
  189. if name.endswith('_ALT'):
  190. return is_seamless_alt(name)
  191. return True
  192. def full_adapter(name, active, section):
  193. """Config adapter for "full"."""
  194. if not is_full_section(section):
  195. return active
  196. return include_in_full(name)
  197. # The baremetal configuration excludes options that require a library or
  198. # operating system feature that is typically not present on bare metal
  199. # systems. Features that are excluded from "full" won't be in "baremetal"
  200. # either (unless explicitly turned on in baremetal_adapter) so they don't
  201. # need to be repeated here.
  202. EXCLUDE_FROM_BAREMETAL = frozenset([
  203. #pylint: disable=line-too-long
  204. 'MBEDTLS_ENTROPY_NV_SEED', # requires a filesystem and FS_IO or alternate NV seed hooks
  205. 'MBEDTLS_FS_IO', # requires a filesystem
  206. 'MBEDTLS_HAVEGE_C', # requires a clock
  207. 'MBEDTLS_HAVE_TIME', # requires a clock
  208. 'MBEDTLS_HAVE_TIME_DATE', # requires a clock
  209. 'MBEDTLS_NET_C', # requires POSIX-like networking
  210. 'MBEDTLS_PLATFORM_FPRINTF_ALT', # requires FILE* from stdio.h
  211. 'MBEDTLS_PLATFORM_NV_SEED_ALT', # requires a filesystem and ENTROPY_NV_SEED
  212. 'MBEDTLS_PLATFORM_TIME_ALT', # requires a clock and HAVE_TIME
  213. 'MBEDTLS_PSA_CRYPTO_SE_C', # requires a filesystem and PSA_CRYPTO_STORAGE_C
  214. 'MBEDTLS_PSA_CRYPTO_STORAGE_C', # requires a filesystem
  215. 'MBEDTLS_PSA_ITS_FILE_C', # requires a filesystem
  216. 'MBEDTLS_THREADING_C', # requires a threading interface
  217. 'MBEDTLS_THREADING_PTHREAD', # requires pthread
  218. 'MBEDTLS_TIMING_C', # requires a clock
  219. ])
  220. def keep_in_baremetal(name):
  221. """Rules for symbols in the "baremetal" configuration."""
  222. if name in EXCLUDE_FROM_BAREMETAL:
  223. return False
  224. return True
  225. def baremetal_adapter(name, active, section):
  226. """Config adapter for "baremetal"."""
  227. if not is_full_section(section):
  228. return active
  229. if name == 'MBEDTLS_NO_PLATFORM_ENTROPY':
  230. # No OS-provided entropy source
  231. return True
  232. return include_in_full(name) and keep_in_baremetal(name)
  233. def include_in_crypto(name):
  234. """Rules for symbols in a crypto configuration."""
  235. if name.startswith('MBEDTLS_X509_') or \
  236. name.startswith('MBEDTLS_SSL_') or \
  237. name.startswith('MBEDTLS_KEY_EXCHANGE_'):
  238. return False
  239. if name in [
  240. 'MBEDTLS_CERTS_C', # part of libmbedx509
  241. 'MBEDTLS_DEBUG_C', # part of libmbedtls
  242. 'MBEDTLS_NET_C', # part of libmbedtls
  243. 'MBEDTLS_PKCS11_C', # part of libmbedx509
  244. ]:
  245. return False
  246. return True
  247. def crypto_adapter(adapter):
  248. """Modify an adapter to disable non-crypto symbols.
  249. ``crypto_adapter(adapter)(name, active, section)`` is like
  250. ``adapter(name, active, section)``, but unsets all X.509 and TLS symbols.
  251. """
  252. def continuation(name, active, section):
  253. if not include_in_crypto(name):
  254. return False
  255. if adapter is None:
  256. return active
  257. return adapter(name, active, section)
  258. return continuation
  259. DEPRECATED = frozenset([
  260. 'MBEDTLS_SSL_PROTO_SSL3',
  261. 'MBEDTLS_SSL_SRV_SUPPORT_SSLV2_CLIENT_HELLO',
  262. ])
  263. def no_deprecated_adapter(adapter):
  264. """Modify an adapter to disable deprecated symbols.
  265. ``no_deprecated_adapter(adapter)(name, active, section)`` is like
  266. ``adapter(name, active, section)``, but unsets all deprecated symbols
  267. and sets ``MBEDTLS_DEPRECATED_REMOVED``.
  268. """
  269. def continuation(name, active, section):
  270. if name == 'MBEDTLS_DEPRECATED_REMOVED':
  271. return True
  272. if name in DEPRECATED:
  273. return False
  274. if adapter is None:
  275. return active
  276. return adapter(name, active, section)
  277. return continuation
  278. class ConfigFile(Config):
  279. """Representation of the Mbed TLS configuration read for a file.
  280. See the documentation of the `Config` class for methods to query
  281. and modify the configuration.
  282. """
  283. _path_in_tree = 'include/mbedtls/config.h'
  284. default_path = [_path_in_tree,
  285. os.path.join(os.path.dirname(__file__),
  286. os.pardir,
  287. _path_in_tree),
  288. os.path.join(os.path.dirname(os.path.abspath(os.path.dirname(__file__))),
  289. _path_in_tree)]
  290. def __init__(self, filename=None):
  291. """Read the Mbed TLS configuration file."""
  292. if filename is None:
  293. for candidate in self.default_path:
  294. if os.path.lexists(candidate):
  295. filename = candidate
  296. break
  297. else:
  298. raise Exception('Mbed TLS configuration file not found',
  299. self.default_path)
  300. super().__init__()
  301. self.filename = filename
  302. self.current_section = 'header'
  303. with open(filename, 'r', encoding='utf-8') as file:
  304. self.templates = [self._parse_line(line) for line in file]
  305. self.current_section = None
  306. def set(self, name, value=None):
  307. if name not in self.settings:
  308. self.templates.append((name, '', '#define ' + name + ' '))
  309. super().set(name, value)
  310. _define_line_regexp = (r'(?P<indentation>\s*)' +
  311. r'(?P<commented_out>(//\s*)?)' +
  312. r'(?P<define>#\s*define\s+)' +
  313. r'(?P<name>\w+)' +
  314. r'(?P<arguments>(?:\((?:\w|\s|,)*\))?)' +
  315. r'(?P<separator>\s*)' +
  316. r'(?P<value>.*)')
  317. _section_line_regexp = (r'\s*/?\*+\s*[\\@]name\s+SECTION:\s*' +
  318. r'(?P<section>.*)[ */]*')
  319. _config_line_regexp = re.compile(r'|'.join([_define_line_regexp,
  320. _section_line_regexp]))
  321. def _parse_line(self, line):
  322. """Parse a line in config.h and return the corresponding template."""
  323. line = line.rstrip('\r\n')
  324. m = re.match(self._config_line_regexp, line)
  325. if m is None:
  326. return line
  327. elif m.group('section'):
  328. self.current_section = m.group('section')
  329. return line
  330. else:
  331. active = not m.group('commented_out')
  332. name = m.group('name')
  333. value = m.group('value')
  334. template = (name,
  335. m.group('indentation'),
  336. m.group('define') + name +
  337. m.group('arguments') + m.group('separator'))
  338. self.settings[name] = Setting(active, name, value,
  339. self.current_section)
  340. return template
  341. def _format_template(self, name, indent, middle):
  342. """Build a line for config.h for the given setting.
  343. The line has the form "<indent>#define <name> <value>"
  344. where <middle> is "#define <name> ".
  345. """
  346. setting = self.settings[name]
  347. value = setting.value
  348. if value is None:
  349. value = ''
  350. # Normally the whitespace to separte the symbol name from the
  351. # value is part of middle, and there's no whitespace for a symbol
  352. # with no value. But if a symbol has been changed from having a
  353. # value to not having one, the whitespace is wrong, so fix it.
  354. if value:
  355. if middle[-1] not in '\t ':
  356. middle += ' '
  357. else:
  358. middle = middle.rstrip()
  359. return ''.join([indent,
  360. '' if setting.active else '//',
  361. middle,
  362. value]).rstrip()
  363. def write_to_stream(self, output):
  364. """Write the whole configuration to output."""
  365. for template in self.templates:
  366. if isinstance(template, str):
  367. line = template
  368. else:
  369. line = self._format_template(*template)
  370. output.write(line + '\n')
  371. def write(self, filename=None):
  372. """Write the whole configuration to the file it was read from.
  373. If filename is specified, write to this file instead.
  374. """
  375. if filename is None:
  376. filename = self.filename
  377. with open(filename, 'w', encoding='utf-8') as output:
  378. self.write_to_stream(output)
  379. if __name__ == '__main__':
  380. def main():
  381. """Command line config.h manipulation tool."""
  382. parser = argparse.ArgumentParser(description="""
  383. Mbed TLS and Mbed Crypto configuration file manipulation tool.
  384. """)
  385. parser.add_argument('--file', '-f',
  386. help="""File to read (and modify if requested).
  387. Default: {}.
  388. """.format(ConfigFile.default_path))
  389. parser.add_argument('--force', '-o',
  390. action='store_true',
  391. help="""For the set command, if SYMBOL is not
  392. present, add a definition for it.""")
  393. parser.add_argument('--write', '-w', metavar='FILE',
  394. help="""File to write to instead of the input file.""")
  395. subparsers = parser.add_subparsers(dest='command',
  396. title='Commands')
  397. parser_get = subparsers.add_parser('get',
  398. help="""Find the value of SYMBOL
  399. and print it. Exit with
  400. status 0 if a #define for SYMBOL is
  401. found, 1 otherwise.
  402. """)
  403. parser_get.add_argument('symbol', metavar='SYMBOL')
  404. parser_set = subparsers.add_parser('set',
  405. help="""Set SYMBOL to VALUE.
  406. If VALUE is omitted, just uncomment
  407. the #define for SYMBOL.
  408. Error out of a line defining
  409. SYMBOL (commented or not) is not
  410. found, unless --force is passed.
  411. """)
  412. parser_set.add_argument('symbol', metavar='SYMBOL')
  413. parser_set.add_argument('value', metavar='VALUE', nargs='?',
  414. default='')
  415. parser_unset = subparsers.add_parser('unset',
  416. help="""Comment out the #define
  417. for SYMBOL. Do nothing if none
  418. is present.""")
  419. parser_unset.add_argument('symbol', metavar='SYMBOL')
  420. def add_adapter(name, function, description):
  421. subparser = subparsers.add_parser(name, help=description)
  422. subparser.set_defaults(adapter=function)
  423. add_adapter('baremetal', baremetal_adapter,
  424. """Like full, but exclude features that require platform
  425. features such as file input-output.""")
  426. add_adapter('full', full_adapter,
  427. """Uncomment most features.
  428. Exclude alternative implementations and platform support
  429. options, as well as some options that are awkward to test.
  430. """)
  431. add_adapter('full_no_deprecated', no_deprecated_adapter(full_adapter),
  432. """Uncomment most non-deprecated features.
  433. Like "full", but without deprecated features.
  434. """)
  435. add_adapter('realfull', realfull_adapter,
  436. """Uncomment all boolean #defines.
  437. Suitable for generating documentation, but not for building.""")
  438. add_adapter('crypto', crypto_adapter(None),
  439. """Only include crypto features. Exclude X.509 and TLS.""")
  440. add_adapter('crypto_baremetal', crypto_adapter(baremetal_adapter),
  441. """Like baremetal, but with only crypto features,
  442. excluding X.509 and TLS.""")
  443. add_adapter('crypto_full', crypto_adapter(full_adapter),
  444. """Like full, but with only crypto features,
  445. excluding X.509 and TLS.""")
  446. args = parser.parse_args()
  447. config = ConfigFile(args.file)
  448. if args.command is None:
  449. parser.print_help()
  450. return 1
  451. elif args.command == 'get':
  452. if args.symbol in config:
  453. value = config[args.symbol]
  454. if value:
  455. sys.stdout.write(value + '\n')
  456. return 0 if args.symbol in config else 1
  457. elif args.command == 'set':
  458. if not args.force and args.symbol not in config.settings:
  459. sys.stderr.write("A #define for the symbol {} "
  460. "was not found in {}\n"
  461. .format(args.symbol, config.filename))
  462. return 1
  463. config.set(args.symbol, value=args.value)
  464. elif args.command == 'unset':
  465. config.unset(args.symbol)
  466. else:
  467. config.adapt(args.adapter)
  468. config.write(args.write)
  469. return 0
  470. # Import modules only used by main only if main is defined and called.
  471. # pylint: disable=wrong-import-position
  472. import argparse
  473. import sys
  474. sys.exit(main())