generate_psa_tests.py 41 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622623624625626627628629630631632633634635636637638639640641642643644645646647648649650651652653654655656657658659660661662663664665666667668669670671672673674675676677678679680681682683684685686687688689690691692693694695696697698699700701702703704705706707708709710711712713714715716717718719720721722723724725726727728729730731732733734735736737738739740741742743744745746747748749750751752753754755756757758759760761762763764765766767768769770771772773774775776777778779780781782783784785786787788789790791792793794795796797798799800801802803804805806807808809810811812813814815816817818819820821822823824825826827828829830831832833834835836837838839840841842843844845846847848849850851852853854855856857858859860861862863864865866867868869870871872873874875876877878879880881882883884885886887888889890891892893894895896897898899900901902903904905906907908909910911912913914915916917918919920921922
  1. #!/usr/bin/env python3
  2. """Generate test data for PSA cryptographic mechanisms.
  3. With no arguments, generate all test data. With non-option arguments,
  4. generate only the specified files.
  5. """
  6. # Copyright The Mbed TLS Contributors
  7. # SPDX-License-Identifier: Apache-2.0
  8. #
  9. # Licensed under the Apache License, Version 2.0 (the "License"); you may
  10. # not use this file except in compliance with the License.
  11. # You may obtain a copy of the License at
  12. #
  13. # http://www.apache.org/licenses/LICENSE-2.0
  14. #
  15. # Unless required by applicable law or agreed to in writing, software
  16. # distributed under the License is distributed on an "AS IS" BASIS, WITHOUT
  17. # WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
  18. # See the License for the specific language governing permissions and
  19. # limitations under the License.
  20. import enum
  21. import re
  22. import sys
  23. from typing import Callable, Dict, FrozenSet, Iterable, Iterator, List, Optional
  24. import scripts_path # pylint: disable=unused-import
  25. from mbedtls_dev import crypto_knowledge
  26. from mbedtls_dev import macro_collector
  27. from mbedtls_dev import psa_storage
  28. from mbedtls_dev import test_case
  29. from mbedtls_dev import test_data_generation
  30. def psa_want_symbol(name: str) -> str:
  31. """Return the PSA_WANT_xxx symbol associated with a PSA crypto feature."""
  32. if name.startswith('PSA_'):
  33. return name[:4] + 'WANT_' + name[4:]
  34. else:
  35. raise ValueError('Unable to determine the PSA_WANT_ symbol for ' + name)
  36. def finish_family_dependency(dep: str, bits: int) -> str:
  37. """Finish dep if it's a family dependency symbol prefix.
  38. A family dependency symbol prefix is a PSA_WANT_ symbol that needs to be
  39. qualified by the key size. If dep is such a symbol, finish it by adjusting
  40. the prefix and appending the key size. Other symbols are left unchanged.
  41. """
  42. return re.sub(r'_FAMILY_(.*)', r'_\1_' + str(bits), dep)
  43. def finish_family_dependencies(dependencies: List[str], bits: int) -> List[str]:
  44. """Finish any family dependency symbol prefixes.
  45. Apply `finish_family_dependency` to each element of `dependencies`.
  46. """
  47. return [finish_family_dependency(dep, bits) for dep in dependencies]
  48. SYMBOLS_WITHOUT_DEPENDENCY = frozenset([
  49. 'PSA_ALG_AEAD_WITH_AT_LEAST_THIS_LENGTH_TAG', # modifier, only in policies
  50. 'PSA_ALG_AEAD_WITH_SHORTENED_TAG', # modifier
  51. 'PSA_ALG_ANY_HASH', # only in policies
  52. 'PSA_ALG_AT_LEAST_THIS_LENGTH_MAC', # modifier, only in policies
  53. 'PSA_ALG_KEY_AGREEMENT', # chaining
  54. 'PSA_ALG_TRUNCATED_MAC', # modifier
  55. ])
  56. def automatic_dependencies(*expressions: str) -> List[str]:
  57. """Infer dependencies of a test case by looking for PSA_xxx symbols.
  58. The arguments are strings which should be C expressions. Do not use
  59. string literals or comments as this function is not smart enough to
  60. skip them.
  61. """
  62. used = set()
  63. for expr in expressions:
  64. used.update(re.findall(r'PSA_(?:ALG|ECC_FAMILY|KEY_TYPE)_\w+', expr))
  65. used.difference_update(SYMBOLS_WITHOUT_DEPENDENCY)
  66. return sorted(psa_want_symbol(name) for name in used)
  67. # A temporary hack: at the time of writing, not all dependency symbols
  68. # are implemented yet. Skip test cases for which the dependency symbols are
  69. # not available. Once all dependency symbols are available, this hack must
  70. # be removed so that a bug in the dependency symbols properly leads to a test
  71. # failure.
  72. def read_implemented_dependencies(filename: str) -> FrozenSet[str]:
  73. return frozenset(symbol
  74. for line in open(filename)
  75. for symbol in re.findall(r'\bPSA_WANT_\w+\b', line))
  76. _implemented_dependencies = None #type: Optional[FrozenSet[str]] #pylint: disable=invalid-name
  77. def hack_dependencies_not_implemented(dependencies: List[str]) -> None:
  78. global _implemented_dependencies #pylint: disable=global-statement,invalid-name
  79. if _implemented_dependencies is None:
  80. _implemented_dependencies = \
  81. read_implemented_dependencies('include/psa/crypto_config.h')
  82. if not all((dep.lstrip('!') in _implemented_dependencies or 'PSA_WANT' not in dep)
  83. for dep in dependencies):
  84. dependencies.append('DEPENDENCY_NOT_IMPLEMENTED_YET')
  85. class Information:
  86. """Gather information about PSA constructors."""
  87. def __init__(self) -> None:
  88. self.constructors = self.read_psa_interface()
  89. @staticmethod
  90. def remove_unwanted_macros(
  91. constructors: macro_collector.PSAMacroEnumerator
  92. ) -> None:
  93. # Mbed TLS doesn't support finite-field DH yet and will not support
  94. # finite-field DSA. Don't attempt to generate any related test case.
  95. constructors.key_types.discard('PSA_KEY_TYPE_DH_KEY_PAIR')
  96. constructors.key_types.discard('PSA_KEY_TYPE_DH_PUBLIC_KEY')
  97. constructors.key_types.discard('PSA_KEY_TYPE_DSA_KEY_PAIR')
  98. constructors.key_types.discard('PSA_KEY_TYPE_DSA_PUBLIC_KEY')
  99. def read_psa_interface(self) -> macro_collector.PSAMacroEnumerator:
  100. """Return the list of known key types, algorithms, etc."""
  101. constructors = macro_collector.InputsForTest()
  102. header_file_names = ['include/psa/crypto_values.h',
  103. 'include/psa/crypto_extra.h']
  104. test_suites = ['tests/suites/test_suite_psa_crypto_metadata.data']
  105. for header_file_name in header_file_names:
  106. constructors.parse_header(header_file_name)
  107. for test_cases in test_suites:
  108. constructors.parse_test_cases(test_cases)
  109. self.remove_unwanted_macros(constructors)
  110. constructors.gather_arguments()
  111. return constructors
  112. def test_case_for_key_type_not_supported(
  113. verb: str, key_type: str, bits: int,
  114. dependencies: List[str],
  115. *args: str,
  116. param_descr: str = ''
  117. ) -> test_case.TestCase:
  118. """Return one test case exercising a key creation method
  119. for an unsupported key type or size.
  120. """
  121. hack_dependencies_not_implemented(dependencies)
  122. tc = test_case.TestCase()
  123. short_key_type = crypto_knowledge.short_expression(key_type)
  124. adverb = 'not' if dependencies else 'never'
  125. if param_descr:
  126. adverb = param_descr + ' ' + adverb
  127. tc.set_description('PSA {} {} {}-bit {} supported'
  128. .format(verb, short_key_type, bits, adverb))
  129. tc.set_dependencies(dependencies)
  130. tc.set_function(verb + '_not_supported')
  131. tc.set_arguments([key_type] + list(args))
  132. return tc
  133. class KeyTypeNotSupported:
  134. """Generate test cases for when a key type is not supported."""
  135. def __init__(self, info: Information) -> None:
  136. self.constructors = info.constructors
  137. ALWAYS_SUPPORTED = frozenset([
  138. 'PSA_KEY_TYPE_DERIVE',
  139. 'PSA_KEY_TYPE_PASSWORD',
  140. 'PSA_KEY_TYPE_PASSWORD_HASH',
  141. 'PSA_KEY_TYPE_RAW_DATA',
  142. 'PSA_KEY_TYPE_HMAC'
  143. ])
  144. def test_cases_for_key_type_not_supported(
  145. self,
  146. kt: crypto_knowledge.KeyType,
  147. param: Optional[int] = None,
  148. param_descr: str = '',
  149. ) -> Iterator[test_case.TestCase]:
  150. """Return test cases exercising key creation when the given type is unsupported.
  151. If param is present and not None, emit test cases conditioned on this
  152. parameter not being supported. If it is absent or None, emit test cases
  153. conditioned on the base type not being supported.
  154. """
  155. if kt.name in self.ALWAYS_SUPPORTED:
  156. # Don't generate test cases for key types that are always supported.
  157. # They would be skipped in all configurations, which is noise.
  158. return
  159. import_dependencies = [('!' if param is None else '') +
  160. psa_want_symbol(kt.name)]
  161. if kt.params is not None:
  162. import_dependencies += [('!' if param == i else '') +
  163. psa_want_symbol(sym)
  164. for i, sym in enumerate(kt.params)]
  165. if kt.name.endswith('_PUBLIC_KEY'):
  166. generate_dependencies = []
  167. else:
  168. generate_dependencies = import_dependencies
  169. for bits in kt.sizes_to_test():
  170. yield test_case_for_key_type_not_supported(
  171. 'import', kt.expression, bits,
  172. finish_family_dependencies(import_dependencies, bits),
  173. test_case.hex_string(kt.key_material(bits)),
  174. param_descr=param_descr,
  175. )
  176. if not generate_dependencies and param is not None:
  177. # If generation is impossible for this key type, rather than
  178. # supported or not depending on implementation capabilities,
  179. # only generate the test case once.
  180. continue
  181. # For public key we expect that key generation fails with
  182. # INVALID_ARGUMENT. It is handled by KeyGenerate class.
  183. if not kt.is_public():
  184. yield test_case_for_key_type_not_supported(
  185. 'generate', kt.expression, bits,
  186. finish_family_dependencies(generate_dependencies, bits),
  187. str(bits),
  188. param_descr=param_descr,
  189. )
  190. # To be added: derive
  191. ECC_KEY_TYPES = ('PSA_KEY_TYPE_ECC_KEY_PAIR',
  192. 'PSA_KEY_TYPE_ECC_PUBLIC_KEY')
  193. def test_cases_for_not_supported(self) -> Iterator[test_case.TestCase]:
  194. """Generate test cases that exercise the creation of keys of unsupported types."""
  195. for key_type in sorted(self.constructors.key_types):
  196. if key_type in self.ECC_KEY_TYPES:
  197. continue
  198. kt = crypto_knowledge.KeyType(key_type)
  199. yield from self.test_cases_for_key_type_not_supported(kt)
  200. for curve_family in sorted(self.constructors.ecc_curves):
  201. for constr in self.ECC_KEY_TYPES:
  202. kt = crypto_knowledge.KeyType(constr, [curve_family])
  203. yield from self.test_cases_for_key_type_not_supported(
  204. kt, param_descr='type')
  205. yield from self.test_cases_for_key_type_not_supported(
  206. kt, 0, param_descr='curve')
  207. def test_case_for_key_generation(
  208. key_type: str, bits: int,
  209. dependencies: List[str],
  210. *args: str,
  211. result: str = ''
  212. ) -> test_case.TestCase:
  213. """Return one test case exercising a key generation.
  214. """
  215. hack_dependencies_not_implemented(dependencies)
  216. tc = test_case.TestCase()
  217. short_key_type = crypto_knowledge.short_expression(key_type)
  218. tc.set_description('PSA {} {}-bit'
  219. .format(short_key_type, bits))
  220. tc.set_dependencies(dependencies)
  221. tc.set_function('generate_key')
  222. tc.set_arguments([key_type] + list(args) + [result])
  223. return tc
  224. class KeyGenerate:
  225. """Generate positive and negative (invalid argument) test cases for key generation."""
  226. def __init__(self, info: Information) -> None:
  227. self.constructors = info.constructors
  228. ECC_KEY_TYPES = ('PSA_KEY_TYPE_ECC_KEY_PAIR',
  229. 'PSA_KEY_TYPE_ECC_PUBLIC_KEY')
  230. @staticmethod
  231. def test_cases_for_key_type_key_generation(
  232. kt: crypto_knowledge.KeyType
  233. ) -> Iterator[test_case.TestCase]:
  234. """Return test cases exercising key generation.
  235. All key types can be generated except for public keys. For public key
  236. PSA_ERROR_INVALID_ARGUMENT status is expected.
  237. """
  238. result = 'PSA_SUCCESS'
  239. import_dependencies = [psa_want_symbol(kt.name)]
  240. if kt.params is not None:
  241. import_dependencies += [psa_want_symbol(sym)
  242. for i, sym in enumerate(kt.params)]
  243. if kt.name.endswith('_PUBLIC_KEY'):
  244. # The library checks whether the key type is a public key generically,
  245. # before it reaches a point where it needs support for the specific key
  246. # type, so it returns INVALID_ARGUMENT for unsupported public key types.
  247. generate_dependencies = []
  248. result = 'PSA_ERROR_INVALID_ARGUMENT'
  249. else:
  250. generate_dependencies = import_dependencies
  251. if kt.name == 'PSA_KEY_TYPE_RSA_KEY_PAIR':
  252. generate_dependencies.append("MBEDTLS_GENPRIME")
  253. for bits in kt.sizes_to_test():
  254. yield test_case_for_key_generation(
  255. kt.expression, bits,
  256. finish_family_dependencies(generate_dependencies, bits),
  257. str(bits),
  258. result
  259. )
  260. def test_cases_for_key_generation(self) -> Iterator[test_case.TestCase]:
  261. """Generate test cases that exercise the generation of keys."""
  262. for key_type in sorted(self.constructors.key_types):
  263. if key_type in self.ECC_KEY_TYPES:
  264. continue
  265. kt = crypto_knowledge.KeyType(key_type)
  266. yield from self.test_cases_for_key_type_key_generation(kt)
  267. for curve_family in sorted(self.constructors.ecc_curves):
  268. for constr in self.ECC_KEY_TYPES:
  269. kt = crypto_knowledge.KeyType(constr, [curve_family])
  270. yield from self.test_cases_for_key_type_key_generation(kt)
  271. class OpFail:
  272. """Generate test cases for operations that must fail."""
  273. #pylint: disable=too-few-public-methods
  274. class Reason(enum.Enum):
  275. NOT_SUPPORTED = 0
  276. INVALID = 1
  277. INCOMPATIBLE = 2
  278. PUBLIC = 3
  279. def __init__(self, info: Information) -> None:
  280. self.constructors = info.constructors
  281. key_type_expressions = self.constructors.generate_expressions(
  282. sorted(self.constructors.key_types)
  283. )
  284. self.key_types = [crypto_knowledge.KeyType(kt_expr)
  285. for kt_expr in key_type_expressions]
  286. def make_test_case(
  287. self,
  288. alg: crypto_knowledge.Algorithm,
  289. category: crypto_knowledge.AlgorithmCategory,
  290. reason: 'Reason',
  291. kt: Optional[crypto_knowledge.KeyType] = None,
  292. not_deps: FrozenSet[str] = frozenset(),
  293. ) -> test_case.TestCase:
  294. """Construct a failure test case for a one-key or keyless operation."""
  295. #pylint: disable=too-many-arguments,too-many-locals
  296. tc = test_case.TestCase()
  297. pretty_alg = alg.short_expression()
  298. if reason == self.Reason.NOT_SUPPORTED:
  299. short_deps = [re.sub(r'PSA_WANT_ALG_', r'', dep)
  300. for dep in not_deps]
  301. pretty_reason = '!' + '&'.join(sorted(short_deps))
  302. else:
  303. pretty_reason = reason.name.lower()
  304. if kt:
  305. key_type = kt.expression
  306. pretty_type = kt.short_expression()
  307. else:
  308. key_type = ''
  309. pretty_type = ''
  310. tc.set_description('PSA {} {}: {}{}'
  311. .format(category.name.lower(),
  312. pretty_alg,
  313. pretty_reason,
  314. ' with ' + pretty_type if pretty_type else ''))
  315. dependencies = automatic_dependencies(alg.base_expression, key_type)
  316. for i, dep in enumerate(dependencies):
  317. if dep in not_deps:
  318. dependencies[i] = '!' + dep
  319. tc.set_dependencies(dependencies)
  320. tc.set_function(category.name.lower() + '_fail')
  321. arguments = [] # type: List[str]
  322. if kt:
  323. key_material = kt.key_material(kt.sizes_to_test()[0])
  324. arguments += [key_type, test_case.hex_string(key_material)]
  325. arguments.append(alg.expression)
  326. if category.is_asymmetric():
  327. arguments.append('1' if reason == self.Reason.PUBLIC else '0')
  328. error = ('NOT_SUPPORTED' if reason == self.Reason.NOT_SUPPORTED else
  329. 'INVALID_ARGUMENT')
  330. arguments.append('PSA_ERROR_' + error)
  331. tc.set_arguments(arguments)
  332. return tc
  333. def no_key_test_cases(
  334. self,
  335. alg: crypto_knowledge.Algorithm,
  336. category: crypto_knowledge.AlgorithmCategory,
  337. ) -> Iterator[test_case.TestCase]:
  338. """Generate failure test cases for keyless operations with the specified algorithm."""
  339. if alg.can_do(category):
  340. # Compatible operation, unsupported algorithm
  341. for dep in automatic_dependencies(alg.base_expression):
  342. yield self.make_test_case(alg, category,
  343. self.Reason.NOT_SUPPORTED,
  344. not_deps=frozenset([dep]))
  345. else:
  346. # Incompatible operation, supported algorithm
  347. yield self.make_test_case(alg, category, self.Reason.INVALID)
  348. def one_key_test_cases(
  349. self,
  350. alg: crypto_knowledge.Algorithm,
  351. category: crypto_knowledge.AlgorithmCategory,
  352. ) -> Iterator[test_case.TestCase]:
  353. """Generate failure test cases for one-key operations with the specified algorithm."""
  354. for kt in self.key_types:
  355. key_is_compatible = kt.can_do(alg)
  356. if key_is_compatible and alg.can_do(category):
  357. # Compatible key and operation, unsupported algorithm
  358. for dep in automatic_dependencies(alg.base_expression):
  359. yield self.make_test_case(alg, category,
  360. self.Reason.NOT_SUPPORTED,
  361. kt=kt, not_deps=frozenset([dep]))
  362. # Public key for a private-key operation
  363. if category.is_asymmetric() and kt.is_public():
  364. yield self.make_test_case(alg, category,
  365. self.Reason.PUBLIC,
  366. kt=kt)
  367. elif key_is_compatible:
  368. # Compatible key, incompatible operation, supported algorithm
  369. yield self.make_test_case(alg, category,
  370. self.Reason.INVALID,
  371. kt=kt)
  372. elif alg.can_do(category):
  373. # Incompatible key, compatible operation, supported algorithm
  374. yield self.make_test_case(alg, category,
  375. self.Reason.INCOMPATIBLE,
  376. kt=kt)
  377. else:
  378. # Incompatible key and operation. Don't test cases where
  379. # multiple things are wrong, to keep the number of test
  380. # cases reasonable.
  381. pass
  382. def test_cases_for_algorithm(
  383. self,
  384. alg: crypto_knowledge.Algorithm,
  385. ) -> Iterator[test_case.TestCase]:
  386. """Generate operation failure test cases for the specified algorithm."""
  387. for category in crypto_knowledge.AlgorithmCategory:
  388. if category == crypto_knowledge.AlgorithmCategory.PAKE:
  389. # PAKE operations are not implemented yet
  390. pass
  391. elif category.requires_key():
  392. yield from self.one_key_test_cases(alg, category)
  393. else:
  394. yield from self.no_key_test_cases(alg, category)
  395. def all_test_cases(self) -> Iterator[test_case.TestCase]:
  396. """Generate all test cases for operations that must fail."""
  397. algorithms = sorted(self.constructors.algorithms)
  398. for expr in self.constructors.generate_expressions(algorithms):
  399. alg = crypto_knowledge.Algorithm(expr)
  400. yield from self.test_cases_for_algorithm(alg)
  401. class StorageKey(psa_storage.Key):
  402. """Representation of a key for storage format testing."""
  403. IMPLICIT_USAGE_FLAGS = {
  404. 'PSA_KEY_USAGE_SIGN_HASH': 'PSA_KEY_USAGE_SIGN_MESSAGE',
  405. 'PSA_KEY_USAGE_VERIFY_HASH': 'PSA_KEY_USAGE_VERIFY_MESSAGE'
  406. } #type: Dict[str, str]
  407. """Mapping of usage flags to the flags that they imply."""
  408. def __init__(
  409. self,
  410. usage: Iterable[str],
  411. without_implicit_usage: Optional[bool] = False,
  412. **kwargs
  413. ) -> None:
  414. """Prepare to generate a key.
  415. * `usage` : The usage flags used for the key.
  416. * `without_implicit_usage`: Flag to define to apply the usage extension
  417. """
  418. usage_flags = set(usage)
  419. if not without_implicit_usage:
  420. for flag in sorted(usage_flags):
  421. if flag in self.IMPLICIT_USAGE_FLAGS:
  422. usage_flags.add(self.IMPLICIT_USAGE_FLAGS[flag])
  423. if usage_flags:
  424. usage_expression = ' | '.join(sorted(usage_flags))
  425. else:
  426. usage_expression = '0'
  427. super().__init__(usage=usage_expression, **kwargs)
  428. class StorageTestData(StorageKey):
  429. """Representation of test case data for storage format testing."""
  430. def __init__(
  431. self,
  432. description: str,
  433. expected_usage: Optional[List[str]] = None,
  434. **kwargs
  435. ) -> None:
  436. """Prepare to generate test data
  437. * `description` : used for the test case names
  438. * `expected_usage`: the usage flags generated as the expected usage flags
  439. in the test cases. CAn differ from the usage flags
  440. stored in the keys because of the usage flags extension.
  441. """
  442. super().__init__(**kwargs)
  443. self.description = description #type: str
  444. if expected_usage is None:
  445. self.expected_usage = self.usage #type: psa_storage.Expr
  446. elif expected_usage:
  447. self.expected_usage = psa_storage.Expr(' | '.join(expected_usage))
  448. else:
  449. self.expected_usage = psa_storage.Expr(0)
  450. class StorageFormat:
  451. """Storage format stability test cases."""
  452. def __init__(self, info: Information, version: int, forward: bool) -> None:
  453. """Prepare to generate test cases for storage format stability.
  454. * `info`: information about the API. See the `Information` class.
  455. * `version`: the storage format version to generate test cases for.
  456. * `forward`: if true, generate forward compatibility test cases which
  457. save a key and check that its representation is as intended. Otherwise
  458. generate backward compatibility test cases which inject a key
  459. representation and check that it can be read and used.
  460. """
  461. self.constructors = info.constructors #type: macro_collector.PSAMacroEnumerator
  462. self.version = version #type: int
  463. self.forward = forward #type: bool
  464. RSA_OAEP_RE = re.compile(r'PSA_ALG_RSA_OAEP\((.*)\)\Z')
  465. BRAINPOOL_RE = re.compile(r'PSA_KEY_TYPE_\w+\(PSA_ECC_FAMILY_BRAINPOOL_\w+\)\Z')
  466. @classmethod
  467. def exercise_key_with_algorithm(
  468. cls,
  469. key_type: psa_storage.Expr, bits: int,
  470. alg: psa_storage.Expr
  471. ) -> bool:
  472. """Whether to exercise the given key with the given algorithm.
  473. Normally only the type and algorithm matter for compatibility, and
  474. this is handled in crypto_knowledge.KeyType.can_do(). This function
  475. exists to detect exceptional cases. Exceptional cases detected here
  476. are not tested in OpFail and should therefore have manually written
  477. test cases.
  478. """
  479. # Some test keys have the RAW_DATA type and attributes that don't
  480. # necessarily make sense. We do this to validate numerical
  481. # encodings of the attributes.
  482. # Raw data keys have no useful exercise anyway so there is no
  483. # loss of test coverage.
  484. if key_type.string == 'PSA_KEY_TYPE_RAW_DATA':
  485. return False
  486. # OAEP requires room for two hashes plus wrapping
  487. m = cls.RSA_OAEP_RE.match(alg.string)
  488. if m:
  489. hash_alg = m.group(1)
  490. hash_length = crypto_knowledge.Algorithm.hash_length(hash_alg)
  491. key_length = (bits + 7) // 8
  492. # Leave enough room for at least one byte of plaintext
  493. return key_length > 2 * hash_length + 2
  494. # There's nothing wrong with ECC keys on Brainpool curves,
  495. # but operations with them are very slow. So we only exercise them
  496. # with a single algorithm, not with all possible hashes. We do
  497. # exercise other curves with all algorithms so test coverage is
  498. # perfectly adequate like this.
  499. m = cls.BRAINPOOL_RE.match(key_type.string)
  500. if m and alg.string != 'PSA_ALG_ECDSA_ANY':
  501. return False
  502. return True
  503. def make_test_case(self, key: StorageTestData) -> test_case.TestCase:
  504. """Construct a storage format test case for the given key.
  505. If ``forward`` is true, generate a forward compatibility test case:
  506. create a key and validate that it has the expected representation.
  507. Otherwise generate a backward compatibility test case: inject the
  508. key representation into storage and validate that it can be read
  509. correctly.
  510. """
  511. verb = 'save' if self.forward else 'read'
  512. tc = test_case.TestCase()
  513. tc.set_description(verb + ' ' + key.description)
  514. dependencies = automatic_dependencies(
  515. key.lifetime.string, key.type.string,
  516. key.alg.string, key.alg2.string,
  517. )
  518. dependencies = finish_family_dependencies(dependencies, key.bits)
  519. tc.set_dependencies(dependencies)
  520. tc.set_function('key_storage_' + verb)
  521. if self.forward:
  522. extra_arguments = []
  523. else:
  524. flags = []
  525. if self.exercise_key_with_algorithm(key.type, key.bits, key.alg):
  526. flags.append('TEST_FLAG_EXERCISE')
  527. if 'READ_ONLY' in key.lifetime.string:
  528. flags.append('TEST_FLAG_READ_ONLY')
  529. extra_arguments = [' | '.join(flags) if flags else '0']
  530. tc.set_arguments([key.lifetime.string,
  531. key.type.string, str(key.bits),
  532. key.expected_usage.string,
  533. key.alg.string, key.alg2.string,
  534. '"' + key.material.hex() + '"',
  535. '"' + key.hex() + '"',
  536. *extra_arguments])
  537. return tc
  538. def key_for_lifetime(
  539. self,
  540. lifetime: str,
  541. ) -> StorageTestData:
  542. """Construct a test key for the given lifetime."""
  543. short = lifetime
  544. short = re.sub(r'PSA_KEY_LIFETIME_FROM_PERSISTENCE_AND_LOCATION',
  545. r'', short)
  546. short = crypto_knowledge.short_expression(short)
  547. description = 'lifetime: ' + short
  548. key = StorageTestData(version=self.version,
  549. id=1, lifetime=lifetime,
  550. type='PSA_KEY_TYPE_RAW_DATA', bits=8,
  551. usage=['PSA_KEY_USAGE_EXPORT'], alg=0, alg2=0,
  552. material=b'L',
  553. description=description)
  554. return key
  555. def all_keys_for_lifetimes(self) -> Iterator[StorageTestData]:
  556. """Generate test keys covering lifetimes."""
  557. lifetimes = sorted(self.constructors.lifetimes)
  558. expressions = self.constructors.generate_expressions(lifetimes)
  559. for lifetime in expressions:
  560. # Don't attempt to create or load a volatile key in storage
  561. if 'VOLATILE' in lifetime:
  562. continue
  563. # Don't attempt to create a read-only key in storage,
  564. # but do attempt to load one.
  565. if 'READ_ONLY' in lifetime and self.forward:
  566. continue
  567. yield self.key_for_lifetime(lifetime)
  568. def key_for_usage_flags(
  569. self,
  570. usage_flags: List[str],
  571. short: Optional[str] = None,
  572. test_implicit_usage: Optional[bool] = True
  573. ) -> StorageTestData:
  574. """Construct a test key for the given key usage."""
  575. extra_desc = ' without implication' if test_implicit_usage else ''
  576. description = 'usage' + extra_desc + ': '
  577. key1 = StorageTestData(version=self.version,
  578. id=1, lifetime=0x00000001,
  579. type='PSA_KEY_TYPE_RAW_DATA', bits=8,
  580. expected_usage=usage_flags,
  581. without_implicit_usage=not test_implicit_usage,
  582. usage=usage_flags, alg=0, alg2=0,
  583. material=b'K',
  584. description=description)
  585. if short is None:
  586. usage_expr = key1.expected_usage.string
  587. key1.description += crypto_knowledge.short_expression(usage_expr)
  588. else:
  589. key1.description += short
  590. return key1
  591. def generate_keys_for_usage_flags(self, **kwargs) -> Iterator[StorageTestData]:
  592. """Generate test keys covering usage flags."""
  593. known_flags = sorted(self.constructors.key_usage_flags)
  594. yield self.key_for_usage_flags(['0'], **kwargs)
  595. for usage_flag in known_flags:
  596. yield self.key_for_usage_flags([usage_flag], **kwargs)
  597. for flag1, flag2 in zip(known_flags,
  598. known_flags[1:] + [known_flags[0]]):
  599. yield self.key_for_usage_flags([flag1, flag2], **kwargs)
  600. def generate_key_for_all_usage_flags(self) -> Iterator[StorageTestData]:
  601. known_flags = sorted(self.constructors.key_usage_flags)
  602. yield self.key_for_usage_flags(known_flags, short='all known')
  603. def all_keys_for_usage_flags(self) -> Iterator[StorageTestData]:
  604. yield from self.generate_keys_for_usage_flags()
  605. yield from self.generate_key_for_all_usage_flags()
  606. def key_for_type_and_alg(
  607. self,
  608. kt: crypto_knowledge.KeyType,
  609. bits: int,
  610. alg: Optional[crypto_knowledge.Algorithm] = None,
  611. ) -> StorageTestData:
  612. """Construct a test key of the given type.
  613. If alg is not None, this key allows it.
  614. """
  615. usage_flags = ['PSA_KEY_USAGE_EXPORT']
  616. alg1 = 0 #type: psa_storage.Exprable
  617. alg2 = 0
  618. if alg is not None:
  619. alg1 = alg.expression
  620. usage_flags += alg.usage_flags(public=kt.is_public())
  621. key_material = kt.key_material(bits)
  622. description = 'type: {} {}-bit'.format(kt.short_expression(1), bits)
  623. if alg is not None:
  624. description += ', ' + alg.short_expression(1)
  625. key = StorageTestData(version=self.version,
  626. id=1, lifetime=0x00000001,
  627. type=kt.expression, bits=bits,
  628. usage=usage_flags, alg=alg1, alg2=alg2,
  629. material=key_material,
  630. description=description)
  631. return key
  632. def keys_for_type(
  633. self,
  634. key_type: str,
  635. all_algorithms: List[crypto_knowledge.Algorithm],
  636. ) -> Iterator[StorageTestData]:
  637. """Generate test keys for the given key type."""
  638. kt = crypto_knowledge.KeyType(key_type)
  639. for bits in kt.sizes_to_test():
  640. # Test a non-exercisable key, as well as exercisable keys for
  641. # each compatible algorithm.
  642. # To do: test reading a key from storage with an incompatible
  643. # or unsupported algorithm.
  644. yield self.key_for_type_and_alg(kt, bits)
  645. compatible_algorithms = [alg for alg in all_algorithms
  646. if kt.can_do(alg)]
  647. for alg in compatible_algorithms:
  648. yield self.key_for_type_and_alg(kt, bits, alg)
  649. def all_keys_for_types(self) -> Iterator[StorageTestData]:
  650. """Generate test keys covering key types and their representations."""
  651. key_types = sorted(self.constructors.key_types)
  652. all_algorithms = [crypto_knowledge.Algorithm(alg)
  653. for alg in self.constructors.generate_expressions(
  654. sorted(self.constructors.algorithms)
  655. )]
  656. for key_type in self.constructors.generate_expressions(key_types):
  657. yield from self.keys_for_type(key_type, all_algorithms)
  658. def keys_for_algorithm(self, alg: str) -> Iterator[StorageTestData]:
  659. """Generate test keys for the encoding of the specified algorithm."""
  660. # These test cases only validate the encoding of algorithms, not
  661. # whether the key read from storage is suitable for an operation.
  662. # `keys_for_types` generate read tests with an algorithm and a
  663. # compatible key.
  664. descr = crypto_knowledge.short_expression(alg, 1)
  665. usage = ['PSA_KEY_USAGE_EXPORT']
  666. key1 = StorageTestData(version=self.version,
  667. id=1, lifetime=0x00000001,
  668. type='PSA_KEY_TYPE_RAW_DATA', bits=8,
  669. usage=usage, alg=alg, alg2=0,
  670. material=b'K',
  671. description='alg: ' + descr)
  672. yield key1
  673. key2 = StorageTestData(version=self.version,
  674. id=1, lifetime=0x00000001,
  675. type='PSA_KEY_TYPE_RAW_DATA', bits=8,
  676. usage=usage, alg=0, alg2=alg,
  677. material=b'L',
  678. description='alg2: ' + descr)
  679. yield key2
  680. def all_keys_for_algorithms(self) -> Iterator[StorageTestData]:
  681. """Generate test keys covering algorithm encodings."""
  682. algorithms = sorted(self.constructors.algorithms)
  683. for alg in self.constructors.generate_expressions(algorithms):
  684. yield from self.keys_for_algorithm(alg)
  685. def generate_all_keys(self) -> Iterator[StorageTestData]:
  686. """Generate all keys for the test cases."""
  687. yield from self.all_keys_for_lifetimes()
  688. yield from self.all_keys_for_usage_flags()
  689. yield from self.all_keys_for_types()
  690. yield from self.all_keys_for_algorithms()
  691. def all_test_cases(self) -> Iterator[test_case.TestCase]:
  692. """Generate all storage format test cases."""
  693. # First build a list of all keys, then construct all the corresponding
  694. # test cases. This allows all required information to be obtained in
  695. # one go, which is a significant performance gain as the information
  696. # includes numerical values obtained by compiling a C program.
  697. all_keys = list(self.generate_all_keys())
  698. for key in all_keys:
  699. if key.location_value() != 0:
  700. # Skip keys with a non-default location, because they
  701. # require a driver and we currently have no mechanism to
  702. # determine whether a driver is available.
  703. continue
  704. yield self.make_test_case(key)
  705. class StorageFormatForward(StorageFormat):
  706. """Storage format stability test cases for forward compatibility."""
  707. def __init__(self, info: Information, version: int) -> None:
  708. super().__init__(info, version, True)
  709. class StorageFormatV0(StorageFormat):
  710. """Storage format stability test cases for version 0 compatibility."""
  711. def __init__(self, info: Information) -> None:
  712. super().__init__(info, 0, False)
  713. def all_keys_for_usage_flags(self) -> Iterator[StorageTestData]:
  714. """Generate test keys covering usage flags."""
  715. yield from super().all_keys_for_usage_flags()
  716. yield from self.generate_keys_for_usage_flags(test_implicit_usage=False)
  717. def keys_for_implicit_usage(
  718. self,
  719. implyer_usage: str,
  720. alg: str,
  721. key_type: crypto_knowledge.KeyType
  722. ) -> StorageTestData:
  723. # pylint: disable=too-many-locals
  724. """Generate test keys for the specified implicit usage flag,
  725. algorithm and key type combination.
  726. """
  727. bits = key_type.sizes_to_test()[0]
  728. implicit_usage = StorageKey.IMPLICIT_USAGE_FLAGS[implyer_usage]
  729. usage_flags = ['PSA_KEY_USAGE_EXPORT']
  730. material_usage_flags = usage_flags + [implyer_usage]
  731. expected_usage_flags = material_usage_flags + [implicit_usage]
  732. alg2 = 0
  733. key_material = key_type.key_material(bits)
  734. usage_expression = crypto_knowledge.short_expression(implyer_usage, 1)
  735. alg_expression = crypto_knowledge.short_expression(alg, 1)
  736. key_type_expression = key_type.short_expression(1)
  737. description = 'implied by {}: {} {} {}-bit'.format(
  738. usage_expression, alg_expression, key_type_expression, bits)
  739. key = StorageTestData(version=self.version,
  740. id=1, lifetime=0x00000001,
  741. type=key_type.expression, bits=bits,
  742. usage=material_usage_flags,
  743. expected_usage=expected_usage_flags,
  744. without_implicit_usage=True,
  745. alg=alg, alg2=alg2,
  746. material=key_material,
  747. description=description)
  748. return key
  749. def gather_key_types_for_sign_alg(self) -> Dict[str, List[str]]:
  750. # pylint: disable=too-many-locals
  751. """Match possible key types for sign algorithms."""
  752. # To create a valid combination both the algorithms and key types
  753. # must be filtered. Pair them with keywords created from its names.
  754. incompatible_alg_keyword = frozenset(['RAW', 'ANY', 'PURE'])
  755. incompatible_key_type_keywords = frozenset(['MONTGOMERY'])
  756. keyword_translation = {
  757. 'ECDSA': 'ECC',
  758. 'ED[0-9]*.*' : 'EDWARDS'
  759. }
  760. exclusive_keywords = {
  761. 'EDWARDS': 'ECC'
  762. }
  763. key_types = set(self.constructors.generate_expressions(self.constructors.key_types))
  764. algorithms = set(self.constructors.generate_expressions(self.constructors.sign_algorithms))
  765. alg_with_keys = {} #type: Dict[str, List[str]]
  766. translation_table = str.maketrans('(', '_', ')')
  767. for alg in algorithms:
  768. # Generate keywords from the name of the algorithm
  769. alg_keywords = set(alg.partition('(')[0].split(sep='_')[2:])
  770. # Translate keywords for better matching with the key types
  771. for keyword in alg_keywords.copy():
  772. for pattern, replace in keyword_translation.items():
  773. if re.match(pattern, keyword):
  774. alg_keywords.remove(keyword)
  775. alg_keywords.add(replace)
  776. # Filter out incompatible algorithms
  777. if not alg_keywords.isdisjoint(incompatible_alg_keyword):
  778. continue
  779. for key_type in key_types:
  780. # Generate keywords from the of the key type
  781. key_type_keywords = set(key_type.translate(translation_table).split(sep='_')[3:])
  782. # Remove ambiguous keywords
  783. for keyword1, keyword2 in exclusive_keywords.items():
  784. if keyword1 in key_type_keywords:
  785. key_type_keywords.remove(keyword2)
  786. if key_type_keywords.isdisjoint(incompatible_key_type_keywords) and\
  787. not key_type_keywords.isdisjoint(alg_keywords):
  788. if alg in alg_with_keys:
  789. alg_with_keys[alg].append(key_type)
  790. else:
  791. alg_with_keys[alg] = [key_type]
  792. return alg_with_keys
  793. def all_keys_for_implicit_usage(self) -> Iterator[StorageTestData]:
  794. """Generate test keys for usage flag extensions."""
  795. # Generate a key type and algorithm pair for each extendable usage
  796. # flag to generate a valid key for exercising. The key is generated
  797. # without usage extension to check the extension compatibility.
  798. alg_with_keys = self.gather_key_types_for_sign_alg()
  799. for usage in sorted(StorageKey.IMPLICIT_USAGE_FLAGS, key=str):
  800. for alg in sorted(alg_with_keys):
  801. for key_type in sorted(alg_with_keys[alg]):
  802. # The key types must be filtered to fit the specific usage flag.
  803. kt = crypto_knowledge.KeyType(key_type)
  804. if kt.is_public() and '_SIGN_' in usage:
  805. # Can't sign with a public key
  806. continue
  807. yield self.keys_for_implicit_usage(usage, alg, kt)
  808. def generate_all_keys(self) -> Iterator[StorageTestData]:
  809. yield from super().generate_all_keys()
  810. yield from self.all_keys_for_implicit_usage()
  811. class PSATestGenerator(test_data_generation.TestGenerator):
  812. """Test generator subclass including PSA targets and info."""
  813. # Note that targets whose names contain 'test_format' have their content
  814. # validated by `abi_check.py`.
  815. targets = {
  816. 'test_suite_psa_crypto_generate_key.generated':
  817. lambda info: KeyGenerate(info).test_cases_for_key_generation(),
  818. 'test_suite_psa_crypto_not_supported.generated':
  819. lambda info: KeyTypeNotSupported(info).test_cases_for_not_supported(),
  820. 'test_suite_psa_crypto_op_fail.generated':
  821. lambda info: OpFail(info).all_test_cases(),
  822. 'test_suite_psa_crypto_storage_format.current':
  823. lambda info: StorageFormatForward(info, 0).all_test_cases(),
  824. 'test_suite_psa_crypto_storage_format.v0':
  825. lambda info: StorageFormatV0(info).all_test_cases(),
  826. } #type: Dict[str, Callable[[Information], Iterable[test_case.TestCase]]]
  827. def __init__(self, options):
  828. super().__init__(options)
  829. self.info = Information()
  830. def generate_target(self, name: str, *target_args) -> None:
  831. super().generate_target(name, self.info)
  832. if __name__ == '__main__':
  833. test_data_generation.main(sys.argv[1:], __doc__, PSATestGenerator)