config.py 23 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541
  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 mbedtls_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 mbedtls_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 change_matching(self, regexs, enable):
  122. """Change all symbols matching one of the regexs to the desired state."""
  123. if not regexs:
  124. return
  125. regex = re.compile('|'.join(regexs))
  126. for setting in self.settings.values():
  127. if regex.search(setting.name):
  128. setting.active = enable
  129. def is_full_section(section):
  130. """Is this section affected by "config.py full" and friends?"""
  131. return section.endswith('support') or section.endswith('modules')
  132. def realfull_adapter(_name, active, section):
  133. """Activate all symbols found in the system and feature sections."""
  134. if not is_full_section(section):
  135. return active
  136. return True
  137. # The goal of the full configuration is to have everything that can be tested
  138. # together. This includes deprecated or insecure options. It excludes:
  139. # * Options that require additional build dependencies or unusual hardware.
  140. # * Options that make testing less effective.
  141. # * Options that are incompatible with other options, or more generally that
  142. # interact with other parts of the code in such a way that a bulk enabling
  143. # is not a good way to test them.
  144. # * Options that remove features.
  145. EXCLUDE_FROM_FULL = frozenset([
  146. #pylint: disable=line-too-long
  147. 'MBEDTLS_CTR_DRBG_USE_128_BIT_KEY', # interacts with ENTROPY_FORCE_SHA256
  148. 'MBEDTLS_DEPRECATED_REMOVED', # conflicts with deprecated options
  149. 'MBEDTLS_DEPRECATED_WARNING', # conflicts with deprecated options
  150. 'MBEDTLS_ECDH_VARIANT_EVEREST_ENABLED', # influences the use of ECDH in TLS
  151. 'MBEDTLS_ECP_NO_FALLBACK', # removes internal ECP implementation
  152. 'MBEDTLS_ECP_RESTARTABLE', # incompatible with USE_PSA_CRYPTO
  153. 'MBEDTLS_ENTROPY_FORCE_SHA256', # interacts with CTR_DRBG_128_BIT_KEY
  154. 'MBEDTLS_HAVE_SSE2', # hardware dependency
  155. 'MBEDTLS_MEMORY_BACKTRACE', # depends on MEMORY_BUFFER_ALLOC_C
  156. 'MBEDTLS_MEMORY_BUFFER_ALLOC_C', # makes sanitizers (e.g. ASan) less effective
  157. 'MBEDTLS_MEMORY_DEBUG', # depends on MEMORY_BUFFER_ALLOC_C
  158. 'MBEDTLS_NO_64BIT_MULTIPLICATION', # influences anything that uses bignum
  159. 'MBEDTLS_NO_DEFAULT_ENTROPY_SOURCES', # removes a feature
  160. 'MBEDTLS_NO_PLATFORM_ENTROPY', # removes a feature
  161. 'MBEDTLS_NO_UDBL_DIVISION', # influences anything that uses bignum
  162. 'MBEDTLS_PLATFORM_NO_STD_FUNCTIONS', # removes a feature
  163. 'MBEDTLS_PSA_CRYPTO_CONFIG', # toggles old/new style PSA config
  164. 'MBEDTLS_PSA_CRYPTO_EXTERNAL_RNG', # behavior change + build dependency
  165. 'MBEDTLS_PSA_CRYPTO_KEY_ID_ENCODES_OWNER', # incompatible with USE_PSA_CRYPTO
  166. 'MBEDTLS_PSA_CRYPTO_SPM', # platform dependency (PSA SPM)
  167. 'MBEDTLS_PSA_INJECT_ENTROPY', # build dependency (hook functions)
  168. 'MBEDTLS_RSA_NO_CRT', # influences the use of RSA in X.509 and TLS
  169. 'MBEDTLS_TEST_CONSTANT_FLOW_MEMSAN', # build dependency (clang+memsan)
  170. 'MBEDTLS_TEST_CONSTANT_FLOW_VALGRIND', # build dependency (valgrind headers)
  171. 'MBEDTLS_X509_REMOVE_INFO', # removes a feature
  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_HAVE_TIME', # requires a clock
  209. 'MBEDTLS_HAVE_TIME_DATE', # requires a clock
  210. 'MBEDTLS_NET_C', # requires POSIX-like networking
  211. 'MBEDTLS_PLATFORM_FPRINTF_ALT', # requires FILE* from stdio.h
  212. 'MBEDTLS_PLATFORM_NV_SEED_ALT', # requires a filesystem and ENTROPY_NV_SEED
  213. 'MBEDTLS_PLATFORM_TIME_ALT', # requires a clock and HAVE_TIME
  214. 'MBEDTLS_PSA_CRYPTO_SE_C', # requires a filesystem and PSA_CRYPTO_STORAGE_C
  215. 'MBEDTLS_PSA_CRYPTO_STORAGE_C', # requires a filesystem
  216. 'MBEDTLS_PSA_ITS_FILE_C', # requires a filesystem
  217. 'MBEDTLS_THREADING_C', # requires a threading interface
  218. 'MBEDTLS_THREADING_PTHREAD', # requires pthread
  219. 'MBEDTLS_TIMING_C', # requires a clock
  220. ])
  221. def keep_in_baremetal(name):
  222. """Rules for symbols in the "baremetal" configuration."""
  223. if name in EXCLUDE_FROM_BAREMETAL:
  224. return False
  225. return True
  226. def baremetal_adapter(name, active, section):
  227. """Config adapter for "baremetal"."""
  228. if not is_full_section(section):
  229. return active
  230. if name == 'MBEDTLS_NO_PLATFORM_ENTROPY':
  231. # No OS-provided entropy source
  232. return True
  233. return include_in_full(name) and keep_in_baremetal(name)
  234. def include_in_crypto(name):
  235. """Rules for symbols in a crypto configuration."""
  236. if name.startswith('MBEDTLS_X509_') or \
  237. name.startswith('MBEDTLS_SSL_') or \
  238. name.startswith('MBEDTLS_KEY_EXCHANGE_'):
  239. return False
  240. if name in [
  241. 'MBEDTLS_DEBUG_C', # part of libmbedtls
  242. 'MBEDTLS_NET_C', # part of libmbedtls
  243. ]:
  244. return False
  245. return True
  246. def crypto_adapter(adapter):
  247. """Modify an adapter to disable non-crypto symbols.
  248. ``crypto_adapter(adapter)(name, active, section)`` is like
  249. ``adapter(name, active, section)``, but unsets all X.509 and TLS symbols.
  250. """
  251. def continuation(name, active, section):
  252. if not include_in_crypto(name):
  253. return False
  254. if adapter is None:
  255. return active
  256. return adapter(name, active, section)
  257. return continuation
  258. def no_deprecated_adapter(adapter):
  259. """Modify an adapter to disable deprecated symbols.
  260. ``no_deprecated_adapter(adapter)(name, active, section)`` is like
  261. ``adapter(name, active, section)``, but unsets all deprecated symbols
  262. and sets ``MBEDTLS_DEPRECATED_REMOVED``.
  263. """
  264. def continuation(name, active, section):
  265. if name == 'MBEDTLS_DEPRECATED_REMOVED':
  266. return True
  267. if adapter is None:
  268. return active
  269. return adapter(name, active, section)
  270. return continuation
  271. class ConfigFile(Config):
  272. """Representation of the Mbed TLS configuration read for a file.
  273. See the documentation of the `Config` class for methods to query
  274. and modify the configuration.
  275. """
  276. _path_in_tree = 'include/mbedtls/mbedtls_config.h'
  277. default_path = [_path_in_tree,
  278. os.path.join(os.path.dirname(__file__),
  279. os.pardir,
  280. _path_in_tree),
  281. os.path.join(os.path.dirname(os.path.abspath(os.path.dirname(__file__))),
  282. _path_in_tree)]
  283. def __init__(self, filename=None):
  284. """Read the Mbed TLS configuration file."""
  285. if filename is None:
  286. for candidate in self.default_path:
  287. if os.path.lexists(candidate):
  288. filename = candidate
  289. break
  290. else:
  291. raise Exception('Mbed TLS configuration file not found',
  292. self.default_path)
  293. super().__init__()
  294. self.filename = filename
  295. self.current_section = 'header'
  296. with open(filename, 'r', encoding='utf-8') as file:
  297. self.templates = [self._parse_line(line) for line in file]
  298. self.current_section = None
  299. def set(self, name, value=None):
  300. if name not in self.settings:
  301. self.templates.append((name, '', '#define ' + name + ' '))
  302. super().set(name, value)
  303. _define_line_regexp = (r'(?P<indentation>\s*)' +
  304. r'(?P<commented_out>(//\s*)?)' +
  305. r'(?P<define>#\s*define\s+)' +
  306. r'(?P<name>\w+)' +
  307. r'(?P<arguments>(?:\((?:\w|\s|,)*\))?)' +
  308. r'(?P<separator>\s*)' +
  309. r'(?P<value>.*)')
  310. _section_line_regexp = (r'\s*/?\*+\s*[\\@]name\s+SECTION:\s*' +
  311. r'(?P<section>.*)[ */]*')
  312. _config_line_regexp = re.compile(r'|'.join([_define_line_regexp,
  313. _section_line_regexp]))
  314. def _parse_line(self, line):
  315. """Parse a line in mbedtls_config.h and return the corresponding template."""
  316. line = line.rstrip('\r\n')
  317. m = re.match(self._config_line_regexp, line)
  318. if m is None:
  319. return line
  320. elif m.group('section'):
  321. self.current_section = m.group('section')
  322. return line
  323. else:
  324. active = not m.group('commented_out')
  325. name = m.group('name')
  326. value = m.group('value')
  327. template = (name,
  328. m.group('indentation'),
  329. m.group('define') + name +
  330. m.group('arguments') + m.group('separator'))
  331. self.settings[name] = Setting(active, name, value,
  332. self.current_section)
  333. return template
  334. def _format_template(self, name, indent, middle):
  335. """Build a line for mbedtls_config.h for the given setting.
  336. The line has the form "<indent>#define <name> <value>"
  337. where <middle> is "#define <name> ".
  338. """
  339. setting = self.settings[name]
  340. value = setting.value
  341. if value is None:
  342. value = ''
  343. # Normally the whitespace to separte the symbol name from the
  344. # value is part of middle, and there's no whitespace for a symbol
  345. # with no value. But if a symbol has been changed from having a
  346. # value to not having one, the whitespace is wrong, so fix it.
  347. if value:
  348. if middle[-1] not in '\t ':
  349. middle += ' '
  350. else:
  351. middle = middle.rstrip()
  352. return ''.join([indent,
  353. '' if setting.active else '//',
  354. middle,
  355. value]).rstrip()
  356. def write_to_stream(self, output):
  357. """Write the whole configuration to output."""
  358. for template in self.templates:
  359. if isinstance(template, str):
  360. line = template
  361. else:
  362. line = self._format_template(*template)
  363. output.write(line + '\n')
  364. def write(self, filename=None):
  365. """Write the whole configuration to the file it was read from.
  366. If filename is specified, write to this file instead.
  367. """
  368. if filename is None:
  369. filename = self.filename
  370. with open(filename, 'w', encoding='utf-8') as output:
  371. self.write_to_stream(output)
  372. if __name__ == '__main__':
  373. def main():
  374. """Command line mbedtls_config.h manipulation tool."""
  375. parser = argparse.ArgumentParser(description="""
  376. Mbed TLS and Mbed Crypto configuration file manipulation tool.
  377. """)
  378. parser.add_argument('--file', '-f',
  379. help="""File to read (and modify if requested).
  380. Default: {}.
  381. """.format(ConfigFile.default_path))
  382. parser.add_argument('--force', '-o',
  383. action='store_true',
  384. help="""For the set command, if SYMBOL is not
  385. present, add a definition for it.""")
  386. parser.add_argument('--write', '-w', metavar='FILE',
  387. help="""File to write to instead of the input file.""")
  388. subparsers = parser.add_subparsers(dest='command',
  389. title='Commands')
  390. parser_get = subparsers.add_parser('get',
  391. help="""Find the value of SYMBOL
  392. and print it. Exit with
  393. status 0 if a #define for SYMBOL is
  394. found, 1 otherwise.
  395. """)
  396. parser_get.add_argument('symbol', metavar='SYMBOL')
  397. parser_set = subparsers.add_parser('set',
  398. help="""Set SYMBOL to VALUE.
  399. If VALUE is omitted, just uncomment
  400. the #define for SYMBOL.
  401. Error out of a line defining
  402. SYMBOL (commented or not) is not
  403. found, unless --force is passed.
  404. """)
  405. parser_set.add_argument('symbol', metavar='SYMBOL')
  406. parser_set.add_argument('value', metavar='VALUE', nargs='?',
  407. default='')
  408. parser_set_all = subparsers.add_parser('set-all',
  409. help="""Uncomment all #define
  410. whose name contains a match for
  411. REGEX.""")
  412. parser_set_all.add_argument('regexs', metavar='REGEX', nargs='*')
  413. parser_unset = subparsers.add_parser('unset',
  414. help="""Comment out the #define
  415. for SYMBOL. Do nothing if none
  416. is present.""")
  417. parser_unset.add_argument('symbol', metavar='SYMBOL')
  418. parser_unset_all = subparsers.add_parser('unset-all',
  419. help="""Comment out all #define
  420. whose name contains a match for
  421. REGEX.""")
  422. parser_unset_all.add_argument('regexs', metavar='REGEX', nargs='*')
  423. def add_adapter(name, function, description):
  424. subparser = subparsers.add_parser(name, help=description)
  425. subparser.set_defaults(adapter=function)
  426. add_adapter('baremetal', baremetal_adapter,
  427. """Like full, but exclude features that require platform
  428. features such as file input-output.""")
  429. add_adapter('full', full_adapter,
  430. """Uncomment most features.
  431. Exclude alternative implementations and platform support
  432. options, as well as some options that are awkward to test.
  433. """)
  434. add_adapter('full_no_deprecated', no_deprecated_adapter(full_adapter),
  435. """Uncomment most non-deprecated features.
  436. Like "full", but without deprecated features.
  437. """)
  438. add_adapter('realfull', realfull_adapter,
  439. """Uncomment all boolean #defines.
  440. Suitable for generating documentation, but not for building.""")
  441. add_adapter('crypto', crypto_adapter(None),
  442. """Only include crypto features. Exclude X.509 and TLS.""")
  443. add_adapter('crypto_baremetal', crypto_adapter(baremetal_adapter),
  444. """Like baremetal, but with only crypto features,
  445. excluding X.509 and TLS.""")
  446. add_adapter('crypto_full', crypto_adapter(full_adapter),
  447. """Like full, but with only crypto features,
  448. excluding X.509 and TLS.""")
  449. args = parser.parse_args()
  450. config = ConfigFile(args.file)
  451. if args.command is None:
  452. parser.print_help()
  453. return 1
  454. elif args.command == 'get':
  455. if args.symbol in config:
  456. value = config[args.symbol]
  457. if value:
  458. sys.stdout.write(value + '\n')
  459. return 0 if args.symbol in config else 1
  460. elif args.command == 'set':
  461. if not args.force and args.symbol not in config.settings:
  462. sys.stderr.write("A #define for the symbol {} "
  463. "was not found in {}\n"
  464. .format(args.symbol, config.filename))
  465. return 1
  466. config.set(args.symbol, value=args.value)
  467. elif args.command == 'set-all':
  468. config.change_matching(args.regexs, True)
  469. elif args.command == 'unset':
  470. config.unset(args.symbol)
  471. elif args.command == 'unset-all':
  472. config.change_matching(args.regexs, False)
  473. else:
  474. config.adapt(args.adapter)
  475. config.write(args.write)
  476. return 0
  477. # Import modules only used by main only if main is defined and called.
  478. # pylint: disable=wrong-import-position
  479. import argparse
  480. import sys
  481. sys.exit(main())