config.py 22 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537
  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_FALLBACK', # removes internal ECP implementation
  144. 'MBEDTLS_ECP_NO_INTERNAL_RNG', # removes a feature
  145. 'MBEDTLS_ECP_RESTARTABLE', # incompatible with USE_PSA_CRYPTO
  146. 'MBEDTLS_ENTROPY_FORCE_SHA256', # interacts with CTR_DRBG_128_BIT_KEY
  147. 'MBEDTLS_HAVE_SSE2', # hardware dependency
  148. 'MBEDTLS_MEMORY_BACKTRACE', # depends on MEMORY_BUFFER_ALLOC_C
  149. 'MBEDTLS_MEMORY_BUFFER_ALLOC_C', # makes sanitizers (e.g. ASan) less effective
  150. 'MBEDTLS_MEMORY_DEBUG', # depends on MEMORY_BUFFER_ALLOC_C
  151. 'MBEDTLS_NO_64BIT_MULTIPLICATION', # influences anything that uses bignum
  152. 'MBEDTLS_NO_DEFAULT_ENTROPY_SOURCES', # removes a feature
  153. 'MBEDTLS_NO_PLATFORM_ENTROPY', # removes a feature
  154. 'MBEDTLS_NO_UDBL_DIVISION', # influences anything that uses bignum
  155. 'MBEDTLS_PKCS11_C', # build dependency (libpkcs11-helper)
  156. 'MBEDTLS_PLATFORM_NO_STD_FUNCTIONS', # removes a feature
  157. 'MBEDTLS_PSA_CRYPTO_CONFIG', # toggles old/new style PSA config
  158. 'MBEDTLS_PSA_CRYPTO_EXTERNAL_RNG', # behavior change + build dependency
  159. 'MBEDTLS_PSA_CRYPTO_KEY_ID_ENCODES_OWNER', # incompatible with USE_PSA_CRYPTO
  160. 'MBEDTLS_PSA_CRYPTO_SPM', # platform dependency (PSA SPM)
  161. 'MBEDTLS_PSA_INJECT_ENTROPY', # build dependency (hook functions)
  162. 'MBEDTLS_REMOVE_3DES_CIPHERSUITES', # removes a feature
  163. 'MBEDTLS_REMOVE_ARC4_CIPHERSUITES', # removes a feature
  164. 'MBEDTLS_RSA_NO_CRT', # influences the use of RSA in X.509 and TLS
  165. 'MBEDTLS_SHA512_NO_SHA384', # removes a feature
  166. 'MBEDTLS_SSL_HW_RECORD_ACCEL', # build dependency (hook functions)
  167. 'MBEDTLS_TEST_CONSTANT_FLOW_MEMSAN', # build dependency (clang+memsan)
  168. 'MBEDTLS_TEST_CONSTANT_FLOW_VALGRIND', # build dependency (valgrind headers)
  169. 'MBEDTLS_TEST_NULL_ENTROPY', # removes a feature
  170. 'MBEDTLS_X509_ALLOW_UNSUPPORTED_CRITICAL_EXTENSION', # influences the use of X.509 in TLS
  171. 'MBEDTLS_ZLIB_SUPPORT', # build dependency (libz)
  172. ])
  173. def is_seamless_alt(name):
  174. """Whether the xxx_ALT symbol should be included in the full configuration.
  175. Include alternative implementations of platform functions, which are
  176. configurable function pointers that default to the built-in function.
  177. This way we test that the function pointers exist and build correctly
  178. without changing the behavior, and tests can verify that the function
  179. pointers are used by modifying those pointers.
  180. Exclude alternative implementations of library functions since they require
  181. an implementation of the relevant functions and an xxx_alt.h header.
  182. """
  183. if name == 'MBEDTLS_PLATFORM_SETUP_TEARDOWN_ALT':
  184. # Similar to non-platform xxx_ALT, requires platform_alt.h
  185. return False
  186. return name.startswith('MBEDTLS_PLATFORM_')
  187. def include_in_full(name):
  188. """Rules for symbols in the "full" configuration."""
  189. if name in EXCLUDE_FROM_FULL:
  190. return False
  191. if name.endswith('_ALT'):
  192. return is_seamless_alt(name)
  193. return True
  194. def full_adapter(name, active, section):
  195. """Config adapter for "full"."""
  196. if not is_full_section(section):
  197. return active
  198. return include_in_full(name)
  199. # The baremetal configuration excludes options that require a library or
  200. # operating system feature that is typically not present on bare metal
  201. # systems. Features that are excluded from "full" won't be in "baremetal"
  202. # either (unless explicitly turned on in baremetal_adapter) so they don't
  203. # need to be repeated here.
  204. EXCLUDE_FROM_BAREMETAL = frozenset([
  205. #pylint: disable=line-too-long
  206. 'MBEDTLS_ENTROPY_NV_SEED', # requires a filesystem and FS_IO or alternate NV seed hooks
  207. 'MBEDTLS_FS_IO', # requires a filesystem
  208. 'MBEDTLS_HAVEGE_C', # requires a clock
  209. 'MBEDTLS_HAVE_TIME', # requires a clock
  210. 'MBEDTLS_HAVE_TIME_DATE', # requires a clock
  211. 'MBEDTLS_NET_C', # requires POSIX-like networking
  212. 'MBEDTLS_PLATFORM_FPRINTF_ALT', # requires FILE* from stdio.h
  213. 'MBEDTLS_PLATFORM_NV_SEED_ALT', # requires a filesystem and ENTROPY_NV_SEED
  214. 'MBEDTLS_PLATFORM_TIME_ALT', # requires a clock and HAVE_TIME
  215. 'MBEDTLS_PSA_CRYPTO_SE_C', # requires a filesystem and PSA_CRYPTO_STORAGE_C
  216. 'MBEDTLS_PSA_CRYPTO_STORAGE_C', # requires a filesystem
  217. 'MBEDTLS_PSA_ITS_FILE_C', # requires a filesystem
  218. 'MBEDTLS_THREADING_C', # requires a threading interface
  219. 'MBEDTLS_THREADING_PTHREAD', # requires pthread
  220. 'MBEDTLS_TIMING_C', # requires a clock
  221. ])
  222. def keep_in_baremetal(name):
  223. """Rules for symbols in the "baremetal" configuration."""
  224. if name in EXCLUDE_FROM_BAREMETAL:
  225. return False
  226. return True
  227. def baremetal_adapter(name, active, section):
  228. """Config adapter for "baremetal"."""
  229. if not is_full_section(section):
  230. return active
  231. if name == 'MBEDTLS_NO_PLATFORM_ENTROPY':
  232. # No OS-provided entropy source
  233. return True
  234. return include_in_full(name) and keep_in_baremetal(name)
  235. def include_in_crypto(name):
  236. """Rules for symbols in a crypto configuration."""
  237. if name.startswith('MBEDTLS_X509_') or \
  238. name.startswith('MBEDTLS_SSL_') or \
  239. name.startswith('MBEDTLS_KEY_EXCHANGE_'):
  240. return False
  241. if name in [
  242. 'MBEDTLS_CERTS_C', # part of libmbedx509
  243. 'MBEDTLS_DEBUG_C', # part of libmbedtls
  244. 'MBEDTLS_NET_C', # part of libmbedtls
  245. 'MBEDTLS_PKCS11_C', # part of libmbedx509
  246. ]:
  247. return False
  248. return True
  249. def crypto_adapter(adapter):
  250. """Modify an adapter to disable non-crypto symbols.
  251. ``crypto_adapter(adapter)(name, active, section)`` is like
  252. ``adapter(name, active, section)``, but unsets all X.509 and TLS symbols.
  253. """
  254. def continuation(name, active, section):
  255. if not include_in_crypto(name):
  256. return False
  257. if adapter is None:
  258. return active
  259. return adapter(name, active, section)
  260. return continuation
  261. DEPRECATED = frozenset([
  262. 'MBEDTLS_SSL_PROTO_SSL3',
  263. 'MBEDTLS_SSL_SRV_SUPPORT_SSLV2_CLIENT_HELLO',
  264. ])
  265. def no_deprecated_adapter(adapter):
  266. """Modify an adapter to disable deprecated symbols.
  267. ``no_deprecated_adapter(adapter)(name, active, section)`` is like
  268. ``adapter(name, active, section)``, but unsets all deprecated symbols
  269. and sets ``MBEDTLS_DEPRECATED_REMOVED``.
  270. """
  271. def continuation(name, active, section):
  272. if name == 'MBEDTLS_DEPRECATED_REMOVED':
  273. return True
  274. if name in DEPRECATED:
  275. return False
  276. if adapter is None:
  277. return active
  278. return adapter(name, active, section)
  279. return continuation
  280. class ConfigFile(Config):
  281. """Representation of the Mbed TLS configuration read for a file.
  282. See the documentation of the `Config` class for methods to query
  283. and modify the configuration.
  284. """
  285. _path_in_tree = 'include/mbedtls/config.h'
  286. default_path = [_path_in_tree,
  287. os.path.join(os.path.dirname(__file__),
  288. os.pardir,
  289. _path_in_tree),
  290. os.path.join(os.path.dirname(os.path.abspath(os.path.dirname(__file__))),
  291. _path_in_tree)]
  292. def __init__(self, filename=None):
  293. """Read the Mbed TLS configuration file."""
  294. if filename is None:
  295. for candidate in self.default_path:
  296. if os.path.lexists(candidate):
  297. filename = candidate
  298. break
  299. else:
  300. raise Exception('Mbed TLS configuration file not found',
  301. self.default_path)
  302. super().__init__()
  303. self.filename = filename
  304. self.current_section = 'header'
  305. with open(filename, 'r', encoding='utf-8') as file:
  306. self.templates = [self._parse_line(line) for line in file]
  307. self.current_section = None
  308. def set(self, name, value=None):
  309. if name not in self.settings:
  310. self.templates.append((name, '', '#define ' + name + ' '))
  311. super().set(name, value)
  312. _define_line_regexp = (r'(?P<indentation>\s*)' +
  313. r'(?P<commented_out>(//\s*)?)' +
  314. r'(?P<define>#\s*define\s+)' +
  315. r'(?P<name>\w+)' +
  316. r'(?P<arguments>(?:\((?:\w|\s|,)*\))?)' +
  317. r'(?P<separator>\s*)' +
  318. r'(?P<value>.*)')
  319. _section_line_regexp = (r'\s*/?\*+\s*[\\@]name\s+SECTION:\s*' +
  320. r'(?P<section>.*)[ */]*')
  321. _config_line_regexp = re.compile(r'|'.join([_define_line_regexp,
  322. _section_line_regexp]))
  323. def _parse_line(self, line):
  324. """Parse a line in config.h and return the corresponding template."""
  325. line = line.rstrip('\r\n')
  326. m = re.match(self._config_line_regexp, line)
  327. if m is None:
  328. return line
  329. elif m.group('section'):
  330. self.current_section = m.group('section')
  331. return line
  332. else:
  333. active = not m.group('commented_out')
  334. name = m.group('name')
  335. value = m.group('value')
  336. template = (name,
  337. m.group('indentation'),
  338. m.group('define') + name +
  339. m.group('arguments') + m.group('separator'))
  340. self.settings[name] = Setting(active, name, value,
  341. self.current_section)
  342. return template
  343. def _format_template(self, name, indent, middle):
  344. """Build a line for config.h for the given setting.
  345. The line has the form "<indent>#define <name> <value>"
  346. where <middle> is "#define <name> ".
  347. """
  348. setting = self.settings[name]
  349. value = setting.value
  350. if value is None:
  351. value = ''
  352. # Normally the whitespace to separte the symbol name from the
  353. # value is part of middle, and there's no whitespace for a symbol
  354. # with no value. But if a symbol has been changed from having a
  355. # value to not having one, the whitespace is wrong, so fix it.
  356. if value:
  357. if middle[-1] not in '\t ':
  358. middle += ' '
  359. else:
  360. middle = middle.rstrip()
  361. return ''.join([indent,
  362. '' if setting.active else '//',
  363. middle,
  364. value]).rstrip()
  365. def write_to_stream(self, output):
  366. """Write the whole configuration to output."""
  367. for template in self.templates:
  368. if isinstance(template, str):
  369. line = template
  370. else:
  371. line = self._format_template(*template)
  372. output.write(line + '\n')
  373. def write(self, filename=None):
  374. """Write the whole configuration to the file it was read from.
  375. If filename is specified, write to this file instead.
  376. """
  377. if filename is None:
  378. filename = self.filename
  379. with open(filename, 'w', encoding='utf-8') as output:
  380. self.write_to_stream(output)
  381. if __name__ == '__main__':
  382. def main():
  383. """Command line config.h manipulation tool."""
  384. parser = argparse.ArgumentParser(description="""
  385. Mbed TLS and Mbed Crypto configuration file manipulation tool.
  386. """)
  387. parser.add_argument('--file', '-f',
  388. help="""File to read (and modify if requested).
  389. Default: {}.
  390. """.format(ConfigFile.default_path))
  391. parser.add_argument('--force', '-o',
  392. action='store_true',
  393. help="""For the set command, if SYMBOL is not
  394. present, add a definition for it.""")
  395. parser.add_argument('--write', '-w', metavar='FILE',
  396. help="""File to write to instead of the input file.""")
  397. subparsers = parser.add_subparsers(dest='command',
  398. title='Commands')
  399. parser_get = subparsers.add_parser('get',
  400. help="""Find the value of SYMBOL
  401. and print it. Exit with
  402. status 0 if a #define for SYMBOL is
  403. found, 1 otherwise.
  404. """)
  405. parser_get.add_argument('symbol', metavar='SYMBOL')
  406. parser_set = subparsers.add_parser('set',
  407. help="""Set SYMBOL to VALUE.
  408. If VALUE is omitted, just uncomment
  409. the #define for SYMBOL.
  410. Error out of a line defining
  411. SYMBOL (commented or not) is not
  412. found, unless --force is passed.
  413. """)
  414. parser_set.add_argument('symbol', metavar='SYMBOL')
  415. parser_set.add_argument('value', metavar='VALUE', nargs='?',
  416. default='')
  417. parser_unset = subparsers.add_parser('unset',
  418. help="""Comment out the #define
  419. for SYMBOL. Do nothing if none
  420. is present.""")
  421. parser_unset.add_argument('symbol', metavar='SYMBOL')
  422. def add_adapter(name, function, description):
  423. subparser = subparsers.add_parser(name, help=description)
  424. subparser.set_defaults(adapter=function)
  425. add_adapter('baremetal', baremetal_adapter,
  426. """Like full, but exclude features that require platform
  427. features such as file input-output.""")
  428. add_adapter('full', full_adapter,
  429. """Uncomment most features.
  430. Exclude alternative implementations and platform support
  431. options, as well as some options that are awkward to test.
  432. """)
  433. add_adapter('full_no_deprecated', no_deprecated_adapter(full_adapter),
  434. """Uncomment most non-deprecated features.
  435. Like "full", but without deprecated features.
  436. """)
  437. add_adapter('realfull', realfull_adapter,
  438. """Uncomment all boolean #defines.
  439. Suitable for generating documentation, but not for building.""")
  440. add_adapter('crypto', crypto_adapter(None),
  441. """Only include crypto features. Exclude X.509 and TLS.""")
  442. add_adapter('crypto_baremetal', crypto_adapter(baremetal_adapter),
  443. """Like baremetal, but with only crypto features,
  444. excluding X.509 and TLS.""")
  445. add_adapter('crypto_full', crypto_adapter(full_adapter),
  446. """Like full, but with only crypto features,
  447. excluding X.509 and TLS.""")
  448. args = parser.parse_args()
  449. config = ConfigFile(args.file)
  450. if args.command is None:
  451. parser.print_help()
  452. return 1
  453. elif args.command == 'get':
  454. if args.symbol in config:
  455. value = config[args.symbol]
  456. if value:
  457. sys.stdout.write(value + '\n')
  458. return 0 if args.symbol in config else 1
  459. elif args.command == 'set':
  460. if not args.force and args.symbol not in config.settings:
  461. sys.stderr.write("A #define for the symbol {} "
  462. "was not found in {}\n"
  463. .format(args.symbol, config.filename))
  464. return 1
  465. config.set(args.symbol, value=args.value)
  466. elif args.command == 'unset':
  467. config.unset(args.symbol)
  468. else:
  469. config.adapt(args.adapter)
  470. config.write(args.write)
  471. return 0
  472. # Import modules only used by main only if main is defined and called.
  473. # pylint: disable=wrong-import-position
  474. import argparse
  475. import sys
  476. sys.exit(main())