blob: 85b35e5d2a0649e0aacd15995d8df371730580de [file] [log] [blame]
Gilles Peskine09940492021-01-26 22:16:30 +01001#!/usr/bin/env python3
2"""Generate test data for PSA cryptographic mechanisms.
Gilles Peskine0298bda2021-03-10 02:34:37 +01003
4With no arguments, generate all test data. With non-option arguments,
5generate only the specified files.
Gilles Peskine09940492021-01-26 22:16:30 +01006"""
7
8# Copyright The Mbed TLS Contributors
Tomás González5fae5602023-11-13 11:45:12 +00009# SPDX-License-Identifier: Apache-2.0 OR GPL-2.0-or-later
Gilles Peskine09940492021-01-26 22:16:30 +010010
Gilles Peskinef8b6b502022-03-15 17:26:33 +010011import enum
Gilles Peskine14e428f2021-01-26 22:19:21 +010012import re
Gilles Peskine09940492021-01-26 22:16:30 +010013import sys
Werner Lewisdcad1e92022-08-24 11:30:03 +010014from typing import Callable, Dict, FrozenSet, Iterable, Iterator, List, Optional
Gilles Peskine09940492021-01-26 22:16:30 +010015
16import scripts_path # pylint: disable=unused-import
Tomás González2bff1bf2023-10-30 15:29:23 +000017from mbedtls_dev import crypto_data_tests
Gilles Peskine14e428f2021-01-26 22:19:21 +010018from mbedtls_dev import crypto_knowledge
Tomás González734d22c2023-10-30 15:15:45 +000019from mbedtls_dev import macro_collector #pylint: disable=unused-import
20from mbedtls_dev import psa_information
Gilles Peskine897dff92021-03-10 15:03:44 +010021from mbedtls_dev import psa_storage
Gilles Peskine14e428f2021-01-26 22:19:21 +010022from mbedtls_dev import test_case
Gilles Peskine69feebd2022-09-16 21:41:47 +020023from mbedtls_dev import test_data_generation
Gilles Peskine09940492021-01-26 22:16:30 +010024
Gilles Peskine14e428f2021-01-26 22:19:21 +010025
Przemyslaw Stekield6ead7c2021-10-11 10:15:25 +020026def test_case_for_key_type_not_supported(
Gilles Peskineb94ea512021-03-10 02:12:08 +010027 verb: str, key_type: str, bits: int,
Gilles Peskine1ae57ec2024-04-10 17:16:16 +020028 not_supported_mechanism: str,
Gilles Peskineb94ea512021-03-10 02:12:08 +010029 *args: str,
30 param_descr: str = ''
31) -> test_case.TestCase:
32 """Return one test case exercising a key creation method
33 for an unsupported key type or size.
34 """
Gilles Peskine1ae57ec2024-04-10 17:16:16 +020035 tc = psa_information.TestCase()
Gilles Peskined79aef52022-03-17 23:42:25 +010036 short_key_type = crypto_knowledge.short_expression(key_type)
Gilles Peskine1ae57ec2024-04-10 17:16:16 +020037 tc.set_description('PSA {} {} {}-bit{} not supported'
38 .format(verb, short_key_type, bits,
39 ' ' + param_descr if param_descr else ''))
Przemyslaw Stekield6ead7c2021-10-11 10:15:25 +020040 tc.set_function(verb + '_not_supported')
Gilles Peskine1ae57ec2024-04-10 17:16:16 +020041 tc.set_key_bits(bits)
42 tc.assumes_not_supported(not_supported_mechanism)
Przemyslaw Stekield6ead7c2021-10-11 10:15:25 +020043 tc.set_arguments([key_type] + list(args))
44 return tc
45
Gilles Peskine4fa76bd2022-12-15 22:14:28 +010046class KeyTypeNotSupported:
47 """Generate test cases for when a key type is not supported."""
Gilles Peskineb94ea512021-03-10 02:12:08 +010048
Tomás González734d22c2023-10-30 15:15:45 +000049 def __init__(self, info: psa_information.Information) -> None:
Gilles Peskineb94ea512021-03-10 02:12:08 +010050 self.constructors = info.constructors
Gilles Peskine14e428f2021-01-26 22:19:21 +010051
Gilles Peskine60b29fe2021-02-16 14:06:50 +010052 ALWAYS_SUPPORTED = frozenset([
53 'PSA_KEY_TYPE_DERIVE',
54 'PSA_KEY_TYPE_RAW_DATA',
55 ])
Gilles Peskine14e428f2021-01-26 22:19:21 +010056 def test_cases_for_key_type_not_supported(
Gilles Peskine60b29fe2021-02-16 14:06:50 +010057 self,
Gilles Peskineaf172842021-01-27 18:24:48 +010058 kt: crypto_knowledge.KeyType,
59 param: Optional[int] = None,
60 param_descr: str = '',
Gilles Peskine3d778392021-02-17 15:11:05 +010061 ) -> Iterator[test_case.TestCase]:
Przemyslaw Stekiel32a8b842021-10-18 14:58:20 +020062 """Return test cases exercising key creation when the given type is unsupported.
Gilles Peskineaf172842021-01-27 18:24:48 +010063
64 If param is present and not None, emit test cases conditioned on this
65 parameter not being supported. If it is absent or None, emit test cases
Przemyslaw Stekiel32a8b842021-10-18 14:58:20 +020066 conditioned on the base type not being supported.
Gilles Peskineaf172842021-01-27 18:24:48 +010067 """
Gilles Peskine60b29fe2021-02-16 14:06:50 +010068 if kt.name in self.ALWAYS_SUPPORTED:
69 # Don't generate test cases for key types that are always supported.
70 # They would be skipped in all configurations, which is noise.
Gilles Peskine3d778392021-02-17 15:11:05 +010071 return
Gilles Peskine1ae57ec2024-04-10 17:16:16 +020072 if param is None:
73 not_supported_mechanism = kt.name
Gilles Peskine14e428f2021-01-26 22:19:21 +010074 else:
Gilles Peskine1ae57ec2024-04-10 17:16:16 +020075 assert kt.params is not None
76 not_supported_mechanism = kt.params[param]
Gilles Peskine14e428f2021-01-26 22:19:21 +010077 for bits in kt.sizes_to_test():
Przemyslaw Stekield6ead7c2021-10-11 10:15:25 +020078 yield test_case_for_key_type_not_supported(
Gilles Peskine7f756872021-02-16 12:13:12 +010079 'import', kt.expression, bits,
Gilles Peskine1ae57ec2024-04-10 17:16:16 +020080 not_supported_mechanism,
Gilles Peskineaf172842021-01-27 18:24:48 +010081 test_case.hex_string(kt.key_material(bits)),
82 param_descr=param_descr,
Gilles Peskine3d778392021-02-17 15:11:05 +010083 )
Gilles Peskine1ae57ec2024-04-10 17:16:16 +020084 # Don't generate not-supported test cases for key generation of
85 # public keys. Our implementation always returns
86 # PSA_ERROR_INVALID_ARGUMENT when attempting to generate a
87 # public key, so we cover this together with the positive cases
88 # in the KeyGenerate class.
Gilles Peskine989c13d2022-03-17 12:52:24 +010089 if not kt.is_public():
Przemyslaw Stekield6ead7c2021-10-11 10:15:25 +020090 yield test_case_for_key_type_not_supported(
91 'generate', kt.expression, bits,
Gilles Peskine1ae57ec2024-04-10 17:16:16 +020092 not_supported_mechanism,
Przemyslaw Stekield6ead7c2021-10-11 10:15:25 +020093 str(bits),
94 param_descr=param_descr,
95 )
Gilles Peskine14e428f2021-01-26 22:19:21 +010096 # To be added: derive
Gilles Peskine14e428f2021-01-26 22:19:21 +010097
Gilles Peskineb93f8542021-04-19 13:50:25 +020098 ECC_KEY_TYPES = ('PSA_KEY_TYPE_ECC_KEY_PAIR',
99 'PSA_KEY_TYPE_ECC_PUBLIC_KEY')
100
Gilles Peskine3d778392021-02-17 15:11:05 +0100101 def test_cases_for_not_supported(self) -> Iterator[test_case.TestCase]:
Gilles Peskine14e428f2021-01-26 22:19:21 +0100102 """Generate test cases that exercise the creation of keys of unsupported types."""
Gilles Peskine14e428f2021-01-26 22:19:21 +0100103 for key_type in sorted(self.constructors.key_types):
Gilles Peskineb93f8542021-04-19 13:50:25 +0200104 if key_type in self.ECC_KEY_TYPES:
105 continue
Gilles Peskine14e428f2021-01-26 22:19:21 +0100106 kt = crypto_knowledge.KeyType(key_type)
Gilles Peskine3d778392021-02-17 15:11:05 +0100107 yield from self.test_cases_for_key_type_not_supported(kt)
Gilles Peskineaf172842021-01-27 18:24:48 +0100108 for curve_family in sorted(self.constructors.ecc_curves):
Gilles Peskineb93f8542021-04-19 13:50:25 +0200109 for constr in self.ECC_KEY_TYPES:
Gilles Peskineaf172842021-01-27 18:24:48 +0100110 kt = crypto_knowledge.KeyType(constr, [curve_family])
Gilles Peskine3d778392021-02-17 15:11:05 +0100111 yield from self.test_cases_for_key_type_not_supported(
Gilles Peskineaf172842021-01-27 18:24:48 +0100112 kt, param_descr='type')
Gilles Peskine3d778392021-02-17 15:11:05 +0100113 yield from self.test_cases_for_key_type_not_supported(
Gilles Peskineaf172842021-01-27 18:24:48 +0100114 kt, 0, param_descr='curve')
Gilles Peskineb94ea512021-03-10 02:12:08 +0100115
Przemyslaw Stekiel997caf82021-10-15 15:21:51 +0200116def test_case_for_key_generation(
117 key_type: str, bits: int,
Przemyslaw Stekiel997caf82021-10-15 15:21:51 +0200118 *args: str,
Przemyslaw Stekielc03b7c52021-10-20 11:59:50 +0200119 result: str = ''
Przemyslaw Stekiel997caf82021-10-15 15:21:51 +0200120) -> test_case.TestCase:
121 """Return one test case exercising a key generation.
122 """
Gilles Peskine6281cf42024-04-10 16:07:29 +0200123 tc = psa_information.TestCase()
Gilles Peskined79aef52022-03-17 23:42:25 +0100124 short_key_type = crypto_knowledge.short_expression(key_type)
Przemyslaw Stekiel997caf82021-10-15 15:21:51 +0200125 tc.set_description('PSA {} {}-bit'
Przemyslaw Stekielc03b7c52021-10-20 11:59:50 +0200126 .format(short_key_type, bits))
Przemyslaw Stekiel997caf82021-10-15 15:21:51 +0200127 tc.set_function('generate_key')
Gilles Peskine6281cf42024-04-10 16:07:29 +0200128 tc.set_key_bits(bits)
Przemyslaw Stekiel1ab3a5c2021-11-02 10:50:44 +0100129 tc.set_arguments([key_type] + list(args) + [result])
Przemyslaw Stekiel997caf82021-10-15 15:21:51 +0200130 return tc
131
132class KeyGenerate:
133 """Generate positive and negative (invalid argument) test cases for key generation."""
134
Tomás González734d22c2023-10-30 15:15:45 +0000135 def __init__(self, info: psa_information.Information) -> None:
Przemyslaw Stekiel997caf82021-10-15 15:21:51 +0200136 self.constructors = info.constructors
137
Przemyslaw Stekielc03b7c52021-10-20 11:59:50 +0200138 ECC_KEY_TYPES = ('PSA_KEY_TYPE_ECC_KEY_PAIR',
139 'PSA_KEY_TYPE_ECC_PUBLIC_KEY')
140
Przemyslaw Stekiel1ab3a5c2021-11-02 10:50:44 +0100141 @staticmethod
Przemyslaw Stekiel997caf82021-10-15 15:21:51 +0200142 def test_cases_for_key_type_key_generation(
Przemyslaw Stekielc03b7c52021-10-20 11:59:50 +0200143 kt: crypto_knowledge.KeyType
Przemyslaw Stekiel997caf82021-10-15 15:21:51 +0200144 ) -> Iterator[test_case.TestCase]:
145 """Return test cases exercising key generation.
146
147 All key types can be generated except for public keys. For public key
148 PSA_ERROR_INVALID_ARGUMENT status is expected.
149 """
150 result = 'PSA_SUCCESS'
Przemyslaw Stekiel997caf82021-10-15 15:21:51 +0200151 if kt.name.endswith('_PUBLIC_KEY'):
Przemyslaw Stekiel997caf82021-10-15 15:21:51 +0200152 result = 'PSA_ERROR_INVALID_ARGUMENT'
Przemyslaw Stekiel997caf82021-10-15 15:21:51 +0200153 for bits in kt.sizes_to_test():
Gilles Peskine6281cf42024-04-10 16:07:29 +0200154 tc = test_case_for_key_generation(
Przemyslaw Stekiel997caf82021-10-15 15:21:51 +0200155 kt.expression, bits,
Przemyslaw Stekiel997caf82021-10-15 15:21:51 +0200156 str(bits),
Przemyslaw Stekielc03b7c52021-10-20 11:59:50 +0200157 result
Przemyslaw Stekiel997caf82021-10-15 15:21:51 +0200158 )
Gilles Peskine6281cf42024-04-10 16:07:29 +0200159 if result == 'PSA_ERROR_INVALID_ARGUMENT':
160 # The library checks whether the key type is a public key generically,
161 # before it reaches a point where it needs support for the specific key
162 # type, so it returns INVALID_ARGUMENT for unsupported public key types.
163 tc.set_dependencies([])
164 elif kt.name == 'PSA_KEY_TYPE_RSA_KEY_PAIR':
165 # A necessary deviation because PSA_WANT symbols don't
166 # distinguish between key generation and usage, but for
167 # RSA key generation has an extra requirement.
168 tc.dependencies.insert(0, 'MBEDTLS_GENPRIME')
169 yield tc
Przemyslaw Stekiel997caf82021-10-15 15:21:51 +0200170
Przemyslaw Stekiel997caf82021-10-15 15:21:51 +0200171 def test_cases_for_key_generation(self) -> Iterator[test_case.TestCase]:
172 """Generate test cases that exercise the generation of keys."""
173 for key_type in sorted(self.constructors.key_types):
174 if key_type in self.ECC_KEY_TYPES:
175 continue
176 kt = crypto_knowledge.KeyType(key_type)
177 yield from self.test_cases_for_key_type_key_generation(kt)
178 for curve_family in sorted(self.constructors.ecc_curves):
179 for constr in self.ECC_KEY_TYPES:
180 kt = crypto_knowledge.KeyType(constr, [curve_family])
Przemyslaw Stekielc03b7c52021-10-20 11:59:50 +0200181 yield from self.test_cases_for_key_type_key_generation(kt)
Przemyslaw Stekiel997caf82021-10-15 15:21:51 +0200182
Gilles Peskinec05158b2021-04-27 20:40:10 +0200183class OpFail:
184 """Generate test cases for operations that must fail."""
185 #pylint: disable=too-few-public-methods
186
Gilles Peskinef8b6b502022-03-15 17:26:33 +0100187 class Reason(enum.Enum):
188 NOT_SUPPORTED = 0
189 INVALID = 1
190 INCOMPATIBLE = 2
Gilles Peskinec2fc2412021-04-29 21:56:59 +0200191 PUBLIC = 3
Gilles Peskinef8b6b502022-03-15 17:26:33 +0100192
Tomás González734d22c2023-10-30 15:15:45 +0000193 def __init__(self, info: psa_information.Information) -> None:
Gilles Peskinec05158b2021-04-27 20:40:10 +0200194 self.constructors = info.constructors
Gilles Peskinef8b6b502022-03-15 17:26:33 +0100195 key_type_expressions = self.constructors.generate_expressions(
196 sorted(self.constructors.key_types)
197 )
198 self.key_types = [crypto_knowledge.KeyType(kt_expr)
199 for kt_expr in key_type_expressions]
Gilles Peskinec05158b2021-04-27 20:40:10 +0200200
Gilles Peskinef8b6b502022-03-15 17:26:33 +0100201 def make_test_case(
202 self,
203 alg: crypto_knowledge.Algorithm,
204 category: crypto_knowledge.AlgorithmCategory,
205 reason: 'Reason',
206 kt: Optional[crypto_knowledge.KeyType] = None,
207 not_deps: FrozenSet[str] = frozenset(),
208 ) -> test_case.TestCase:
209 """Construct a failure test case for a one-key or keyless operation."""
210 #pylint: disable=too-many-arguments,too-many-locals
Gilles Peskine764c2d32024-04-10 18:12:02 +0200211 tc = psa_information.TestCase()
Gilles Peskined79aef52022-03-17 23:42:25 +0100212 pretty_alg = alg.short_expression()
Gilles Peskined0964452021-04-29 21:35:03 +0200213 if reason == self.Reason.NOT_SUPPORTED:
214 short_deps = [re.sub(r'PSA_WANT_ALG_', r'', dep)
215 for dep in not_deps]
216 pretty_reason = '!' + '&'.join(sorted(short_deps))
217 else:
218 pretty_reason = reason.name.lower()
Gilles Peskinef8b6b502022-03-15 17:26:33 +0100219 if kt:
220 key_type = kt.expression
Gilles Peskined79aef52022-03-17 23:42:25 +0100221 pretty_type = kt.short_expression()
Gilles Peskinea2180472021-04-27 21:03:43 +0200222 else:
Gilles Peskinef8b6b502022-03-15 17:26:33 +0100223 key_type = ''
224 pretty_type = ''
225 tc.set_description('PSA {} {}: {}{}'
226 .format(category.name.lower(),
227 pretty_alg,
228 pretty_reason,
229 ' with ' + pretty_type if pretty_type else ''))
Gilles Peskinef8b6b502022-03-15 17:26:33 +0100230 tc.set_function(category.name.lower() + '_fail')
David Horstmann4fc7e0e2023-01-24 18:53:15 +0000231 arguments = [] # type: List[str]
Gilles Peskinef8b6b502022-03-15 17:26:33 +0100232 if kt:
Gilles Peskine764c2d32024-04-10 18:12:02 +0200233 bits = kt.sizes_to_test()[0]
234 key_material = kt.key_material(bits)
Gilles Peskinef8b6b502022-03-15 17:26:33 +0100235 arguments += [key_type, test_case.hex_string(key_material)]
Gilles Peskine764c2d32024-04-10 18:12:02 +0200236 tc.set_key_bits(bits)
Gilles Peskinef8b6b502022-03-15 17:26:33 +0100237 arguments.append(alg.expression)
Gilles Peskinec2fc2412021-04-29 21:56:59 +0200238 if category.is_asymmetric():
239 arguments.append('1' if reason == self.Reason.PUBLIC else '0')
Gilles Peskinef8b6b502022-03-15 17:26:33 +0100240 error = ('NOT_SUPPORTED' if reason == self.Reason.NOT_SUPPORTED else
241 'INVALID_ARGUMENT')
242 arguments.append('PSA_ERROR_' + error)
Gilles Peskine764c2d32024-04-10 18:12:02 +0200243 for dep in not_deps:
244 tc.assumes_not_supported(dep)
Gilles Peskinef8b6b502022-03-15 17:26:33 +0100245 tc.set_arguments(arguments)
246 return tc
Gilles Peskinea2180472021-04-27 21:03:43 +0200247
Gilles Peskinef8b6b502022-03-15 17:26:33 +0100248 def no_key_test_cases(
249 self,
250 alg: crypto_knowledge.Algorithm,
251 category: crypto_knowledge.AlgorithmCategory,
252 ) -> Iterator[test_case.TestCase]:
253 """Generate failure test cases for keyless operations with the specified algorithm."""
Gilles Peskine23cb12e2021-04-29 20:54:40 +0200254 if alg.can_do(category):
Gilles Peskinef8b6b502022-03-15 17:26:33 +0100255 # Compatible operation, unsupported algorithm
Tomás González734d22c2023-10-30 15:15:45 +0000256 for dep in psa_information.automatic_dependencies(alg.base_expression):
Gilles Peskinef8b6b502022-03-15 17:26:33 +0100257 yield self.make_test_case(alg, category,
258 self.Reason.NOT_SUPPORTED,
259 not_deps=frozenset([dep]))
260 else:
261 # Incompatible operation, supported algorithm
262 yield self.make_test_case(alg, category, self.Reason.INVALID)
263
264 def one_key_test_cases(
265 self,
266 alg: crypto_knowledge.Algorithm,
267 category: crypto_knowledge.AlgorithmCategory,
268 ) -> Iterator[test_case.TestCase]:
269 """Generate failure test cases for one-key operations with the specified algorithm."""
270 for kt in self.key_types:
271 key_is_compatible = kt.can_do(alg)
Gilles Peskine23cb12e2021-04-29 20:54:40 +0200272 if key_is_compatible and alg.can_do(category):
Gilles Peskinef8b6b502022-03-15 17:26:33 +0100273 # Compatible key and operation, unsupported algorithm
Tomás González734d22c2023-10-30 15:15:45 +0000274 for dep in psa_information.automatic_dependencies(alg.base_expression):
Gilles Peskinef8b6b502022-03-15 17:26:33 +0100275 yield self.make_test_case(alg, category,
276 self.Reason.NOT_SUPPORTED,
277 kt=kt, not_deps=frozenset([dep]))
Gilles Peskinec2fc2412021-04-29 21:56:59 +0200278 # Public key for a private-key operation
279 if category.is_asymmetric() and kt.is_public():
280 yield self.make_test_case(alg, category,
281 self.Reason.PUBLIC,
282 kt=kt)
Gilles Peskinef8b6b502022-03-15 17:26:33 +0100283 elif key_is_compatible:
284 # Compatible key, incompatible operation, supported algorithm
285 yield self.make_test_case(alg, category,
286 self.Reason.INVALID,
287 kt=kt)
Gilles Peskine23cb12e2021-04-29 20:54:40 +0200288 elif alg.can_do(category):
Gilles Peskinef8b6b502022-03-15 17:26:33 +0100289 # Incompatible key, compatible operation, supported algorithm
290 yield self.make_test_case(alg, category,
291 self.Reason.INCOMPATIBLE,
292 kt=kt)
293 else:
294 # Incompatible key and operation. Don't test cases where
295 # multiple things are wrong, to keep the number of test
296 # cases reasonable.
297 pass
298
299 def test_cases_for_algorithm(
300 self,
301 alg: crypto_knowledge.Algorithm,
302 ) -> Iterator[test_case.TestCase]:
Gilles Peskinea2180472021-04-27 21:03:43 +0200303 """Generate operation failure test cases for the specified algorithm."""
Gilles Peskinef8b6b502022-03-15 17:26:33 +0100304 for category in crypto_knowledge.AlgorithmCategory:
305 if category == crypto_knowledge.AlgorithmCategory.PAKE:
306 # PAKE operations are not implemented yet
307 pass
308 elif category.requires_key():
309 yield from self.one_key_test_cases(alg, category)
310 else:
311 yield from self.no_key_test_cases(alg, category)
Gilles Peskinea2180472021-04-27 21:03:43 +0200312
Gilles Peskinec05158b2021-04-27 20:40:10 +0200313 def all_test_cases(self) -> Iterator[test_case.TestCase]:
314 """Generate all test cases for operations that must fail."""
Gilles Peskinea2180472021-04-27 21:03:43 +0200315 algorithms = sorted(self.constructors.algorithms)
Gilles Peskinef8b6b502022-03-15 17:26:33 +0100316 for expr in self.constructors.generate_expressions(algorithms):
317 alg = crypto_knowledge.Algorithm(expr)
Gilles Peskinea2180472021-04-27 21:03:43 +0200318 yield from self.test_cases_for_algorithm(alg)
Gilles Peskinec05158b2021-04-27 20:40:10 +0200319
320
Gilles Peskine897dff92021-03-10 15:03:44 +0100321class StorageKey(psa_storage.Key):
322 """Representation of a key for storage format testing."""
323
gabor-mezei-arme4b74992021-06-29 15:29:24 +0200324 IMPLICIT_USAGE_FLAGS = {
325 'PSA_KEY_USAGE_SIGN_HASH': 'PSA_KEY_USAGE_SIGN_MESSAGE',
326 'PSA_KEY_USAGE_VERIFY_HASH': 'PSA_KEY_USAGE_VERIFY_MESSAGE'
327 } #type: Dict[str, str]
328 """Mapping of usage flags to the flags that they imply."""
329
330 def __init__(
331 self,
Gilles Peskined9af9782022-03-17 22:32:59 +0100332 usage: Iterable[str],
gabor-mezei-arme4b74992021-06-29 15:29:24 +0200333 without_implicit_usage: Optional[bool] = False,
334 **kwargs
335 ) -> None:
336 """Prepare to generate a key.
337
338 * `usage` : The usage flags used for the key.
Tom Cosgrove49f99bc2022-12-04 16:44:21 +0000339 * `without_implicit_usage`: Flag to define to apply the usage extension
gabor-mezei-arme4b74992021-06-29 15:29:24 +0200340 """
Gilles Peskined9af9782022-03-17 22:32:59 +0100341 usage_flags = set(usage)
gabor-mezei-arme4b74992021-06-29 15:29:24 +0200342 if not without_implicit_usage:
Gilles Peskined9af9782022-03-17 22:32:59 +0100343 for flag in sorted(usage_flags):
344 if flag in self.IMPLICIT_USAGE_FLAGS:
345 usage_flags.add(self.IMPLICIT_USAGE_FLAGS[flag])
346 if usage_flags:
347 usage_expression = ' | '.join(sorted(usage_flags))
348 else:
349 usage_expression = '0'
350 super().__init__(usage=usage_expression, **kwargs)
gabor-mezei-arme4b74992021-06-29 15:29:24 +0200351
352class StorageTestData(StorageKey):
353 """Representation of test case data for storage format testing."""
354
gabor-mezei-arm044fefc2021-06-24 10:16:44 +0200355 def __init__(
356 self,
357 description: str,
Gilles Peskined9af9782022-03-17 22:32:59 +0100358 expected_usage: Optional[List[str]] = None,
gabor-mezei-arm044fefc2021-06-24 10:16:44 +0200359 **kwargs
360 ) -> None:
gabor-mezei-arme4b74992021-06-29 15:29:24 +0200361 """Prepare to generate test data
gabor-mezei-arm044fefc2021-06-24 10:16:44 +0200362
gabor-mezei-arme4b74992021-06-29 15:29:24 +0200363 * `description` : used for the the test case names
364 * `expected_usage`: the usage flags generated as the expected usage flags
365 in the test cases. CAn differ from the usage flags
366 stored in the keys because of the usage flags extension.
gabor-mezei-arm044fefc2021-06-24 10:16:44 +0200367 """
Gilles Peskine897dff92021-03-10 15:03:44 +0100368 super().__init__(**kwargs)
369 self.description = description #type: str
Gilles Peskined9af9782022-03-17 22:32:59 +0100370 if expected_usage is None:
371 self.expected_usage = self.usage #type: psa_storage.Expr
372 elif expected_usage:
373 self.expected_usage = psa_storage.Expr(' | '.join(expected_usage))
374 else:
375 self.expected_usage = psa_storage.Expr(0)
gabor-mezei-arm15c1f032021-06-24 10:04:38 +0200376
Gilles Peskine897dff92021-03-10 15:03:44 +0100377class StorageFormat:
378 """Storage format stability test cases."""
379
Tomás González734d22c2023-10-30 15:15:45 +0000380 def __init__(self, info: psa_information.Information, version: int, forward: bool) -> None:
Gilles Peskine897dff92021-03-10 15:03:44 +0100381 """Prepare to generate test cases for storage format stability.
382
Tomás González734d22c2023-10-30 15:15:45 +0000383 * `info`: information about the API. See the `psa_information.Information` class.
Gilles Peskine897dff92021-03-10 15:03:44 +0100384 * `version`: the storage format version to generate test cases for.
385 * `forward`: if true, generate forward compatibility test cases which
386 save a key and check that its representation is as intended. Otherwise
387 generate backward compatibility test cases which inject a key
388 representation and check that it can be read and used.
389 """
gabor-mezei-arm0bdb84e2021-06-23 17:01:44 +0200390 self.constructors = info.constructors #type: macro_collector.PSAMacroEnumerator
391 self.version = version #type: int
392 self.forward = forward #type: bool
Gilles Peskine897dff92021-03-10 15:03:44 +0100393
Gilles Peskine32611242022-03-19 12:09:13 +0100394 RSA_OAEP_RE = re.compile(r'PSA_ALG_RSA_OAEP\((.*)\)\Z')
Gilles Peskine8ddced52022-03-19 15:36:09 +0100395 BRAINPOOL_RE = re.compile(r'PSA_KEY_TYPE_\w+\(PSA_ECC_FAMILY_BRAINPOOL_\w+\)\Z')
Gilles Peskine32611242022-03-19 12:09:13 +0100396 @classmethod
Gilles Peskine8ddced52022-03-19 15:36:09 +0100397 def exercise_key_with_algorithm(
Gilles Peskine32611242022-03-19 12:09:13 +0100398 cls,
399 key_type: psa_storage.Expr, bits: int,
400 alg: psa_storage.Expr
401 ) -> bool:
Gilles Peskine1efe7fd2022-12-15 23:03:19 +0100402 """Whether to exercise the given key with the given algorithm.
Gilles Peskine32611242022-03-19 12:09:13 +0100403
404 Normally only the type and algorithm matter for compatibility, and
405 this is handled in crypto_knowledge.KeyType.can_do(). This function
406 exists to detect exceptional cases. Exceptional cases detected here
407 are not tested in OpFail and should therefore have manually written
408 test cases.
409 """
Gilles Peskine8ddced52022-03-19 15:36:09 +0100410 # Some test keys have the RAW_DATA type and attributes that don't
411 # necessarily make sense. We do this to validate numerical
412 # encodings of the attributes.
413 # Raw data keys have no useful exercise anyway so there is no
414 # loss of test coverage.
415 if key_type.string == 'PSA_KEY_TYPE_RAW_DATA':
416 return False
Gilles Peskinec7686002022-04-20 16:31:37 +0200417 # Mbed TLS only supports 128-bit keys for RC4.
418 if key_type.string == 'PSA_KEY_TYPE_ARC4' and bits != 128:
419 return False
Gilles Peskine32611242022-03-19 12:09:13 +0100420 # OAEP requires room for two hashes plus wrapping
421 m = cls.RSA_OAEP_RE.match(alg.string)
422 if m:
423 hash_alg = m.group(1)
424 hash_length = crypto_knowledge.Algorithm.hash_length(hash_alg)
425 key_length = (bits + 7) // 8
426 # Leave enough room for at least one byte of plaintext
427 return key_length > 2 * hash_length + 2
Gilles Peskine8ddced52022-03-19 15:36:09 +0100428 # There's nothing wrong with ECC keys on Brainpool curves,
429 # but operations with them are very slow. So we only exercise them
430 # with a single algorithm, not with all possible hashes. We do
431 # exercise other curves with all algorithms so test coverage is
432 # perfectly adequate like this.
433 m = cls.BRAINPOOL_RE.match(key_type.string)
434 if m and alg.string != 'PSA_ALG_ECDSA_ANY':
435 return False
Gilles Peskine32611242022-03-19 12:09:13 +0100436 return True
437
gabor-mezei-arme4b74992021-06-29 15:29:24 +0200438 def make_test_case(self, key: StorageTestData) -> test_case.TestCase:
Gilles Peskine897dff92021-03-10 15:03:44 +0100439 """Construct a storage format test case for the given key.
440
441 If ``forward`` is true, generate a forward compatibility test case:
442 create a key and validate that it has the expected representation.
443 Otherwise generate a backward compatibility test case: inject the
444 key representation into storage and validate that it can be read
445 correctly.
446 """
447 verb = 'save' if self.forward else 'read'
Gilles Peskinec7b58d52024-04-10 15:55:39 +0200448 tc = psa_information.TestCase()
Gilles Peskine930ccef2022-03-18 00:02:15 +0100449 tc.set_description(verb + ' ' + key.description)
Gilles Peskinec7b58d52024-04-10 15:55:39 +0200450 tc.set_key_bits(key.bits)
Gilles Peskine897dff92021-03-10 15:03:44 +0100451 tc.set_function('key_storage_' + verb)
452 if self.forward:
453 extra_arguments = []
454 else:
Gilles Peskine643eb832021-04-21 20:11:33 +0200455 flags = []
Gilles Peskine8ddced52022-03-19 15:36:09 +0100456 if self.exercise_key_with_algorithm(key.type, key.bits, key.alg):
Gilles Peskine643eb832021-04-21 20:11:33 +0200457 flags.append('TEST_FLAG_EXERCISE')
458 if 'READ_ONLY' in key.lifetime.string:
459 flags.append('TEST_FLAG_READ_ONLY')
460 extra_arguments = [' | '.join(flags) if flags else '0']
Gilles Peskine897dff92021-03-10 15:03:44 +0100461 tc.set_arguments([key.lifetime.string,
462 key.type.string, str(key.bits),
Gilles Peskined9af9782022-03-17 22:32:59 +0100463 key.expected_usage.string,
464 key.alg.string, key.alg2.string,
Gilles Peskine897dff92021-03-10 15:03:44 +0100465 '"' + key.material.hex() + '"',
466 '"' + key.hex() + '"',
467 *extra_arguments])
468 return tc
469
Gilles Peskineefb584d2021-04-21 22:05:34 +0200470 def key_for_lifetime(
471 self,
472 lifetime: str,
gabor-mezei-arme4b74992021-06-29 15:29:24 +0200473 ) -> StorageTestData:
Gilles Peskineefb584d2021-04-21 22:05:34 +0200474 """Construct a test key for the given lifetime."""
475 short = lifetime
476 short = re.sub(r'PSA_KEY_LIFETIME_FROM_PERSISTENCE_AND_LOCATION',
477 r'', short)
Gilles Peskined79aef52022-03-17 23:42:25 +0100478 short = crypto_knowledge.short_expression(short)
Gilles Peskineefb584d2021-04-21 22:05:34 +0200479 description = 'lifetime: ' + short
gabor-mezei-arme4b74992021-06-29 15:29:24 +0200480 key = StorageTestData(version=self.version,
481 id=1, lifetime=lifetime,
482 type='PSA_KEY_TYPE_RAW_DATA', bits=8,
Gilles Peskined9af9782022-03-17 22:32:59 +0100483 usage=['PSA_KEY_USAGE_EXPORT'], alg=0, alg2=0,
gabor-mezei-arme4b74992021-06-29 15:29:24 +0200484 material=b'L',
485 description=description)
486 return key
Gilles Peskineefb584d2021-04-21 22:05:34 +0200487
gabor-mezei-arme4b74992021-06-29 15:29:24 +0200488 def all_keys_for_lifetimes(self) -> Iterator[StorageTestData]:
Gilles Peskineefb584d2021-04-21 22:05:34 +0200489 """Generate test keys covering lifetimes."""
490 lifetimes = sorted(self.constructors.lifetimes)
491 expressions = self.constructors.generate_expressions(lifetimes)
492 for lifetime in expressions:
493 # Don't attempt to create or load a volatile key in storage
494 if 'VOLATILE' in lifetime:
495 continue
496 # Don't attempt to create a read-only key in storage,
497 # but do attempt to load one.
498 if 'READ_ONLY' in lifetime and self.forward:
499 continue
gabor-mezei-arm5ea30372021-06-28 19:26:55 +0200500 yield self.key_for_lifetime(lifetime)
Gilles Peskineefb584d2021-04-21 22:05:34 +0200501
Gilles Peskinea296e482022-02-24 18:58:08 +0100502 def key_for_usage_flags(
Gilles Peskine897dff92021-03-10 15:03:44 +0100503 self,
504 usage_flags: List[str],
gabor-mezei-armd71659f2021-06-24 09:42:02 +0200505 short: Optional[str] = None,
Gilles Peskinea296e482022-02-24 18:58:08 +0100506 test_implicit_usage: Optional[bool] = True
507 ) -> StorageTestData:
Gilles Peskine897dff92021-03-10 15:03:44 +0100508 """Construct a test key for the given key usage."""
Gilles Peskinea296e482022-02-24 18:58:08 +0100509 extra_desc = ' without implication' if test_implicit_usage else ''
Gilles Peskined9af9782022-03-17 22:32:59 +0100510 description = 'usage' + extra_desc + ': '
gabor-mezei-arme4b74992021-06-29 15:29:24 +0200511 key1 = StorageTestData(version=self.version,
512 id=1, lifetime=0x00000001,
513 type='PSA_KEY_TYPE_RAW_DATA', bits=8,
Gilles Peskined9af9782022-03-17 22:32:59 +0100514 expected_usage=usage_flags,
Gilles Peskinea296e482022-02-24 18:58:08 +0100515 without_implicit_usage=not test_implicit_usage,
Gilles Peskined9af9782022-03-17 22:32:59 +0100516 usage=usage_flags, alg=0, alg2=0,
gabor-mezei-arme4b74992021-06-29 15:29:24 +0200517 material=b'K',
518 description=description)
Gilles Peskined9af9782022-03-17 22:32:59 +0100519 if short is None:
Gilles Peskined79aef52022-03-17 23:42:25 +0100520 usage_expr = key1.expected_usage.string
521 key1.description += crypto_knowledge.short_expression(usage_expr)
Gilles Peskined9af9782022-03-17 22:32:59 +0100522 else:
523 key1.description += short
Gilles Peskinea296e482022-02-24 18:58:08 +0100524 return key1
Gilles Peskine897dff92021-03-10 15:03:44 +0100525
gabor-mezei-arme4b74992021-06-29 15:29:24 +0200526 def generate_keys_for_usage_flags(self, **kwargs) -> Iterator[StorageTestData]:
Gilles Peskine897dff92021-03-10 15:03:44 +0100527 """Generate test keys covering usage flags."""
528 known_flags = sorted(self.constructors.key_usage_flags)
Gilles Peskinea296e482022-02-24 18:58:08 +0100529 yield self.key_for_usage_flags(['0'], **kwargs)
gabor-mezei-arm5ea30372021-06-28 19:26:55 +0200530 for usage_flag in known_flags:
Gilles Peskinea296e482022-02-24 18:58:08 +0100531 yield self.key_for_usage_flags([usage_flag], **kwargs)
gabor-mezei-arm5ea30372021-06-28 19:26:55 +0200532 for flag1, flag2 in zip(known_flags,
533 known_flags[1:] + [known_flags[0]]):
Gilles Peskinea296e482022-02-24 18:58:08 +0100534 yield self.key_for_usage_flags([flag1, flag2], **kwargs)
gabor-mezei-armbce85272021-06-24 14:38:51 +0200535
gabor-mezei-arme4b74992021-06-29 15:29:24 +0200536 def generate_key_for_all_usage_flags(self) -> Iterator[StorageTestData]:
gabor-mezei-armbce85272021-06-24 14:38:51 +0200537 known_flags = sorted(self.constructors.key_usage_flags)
Gilles Peskinea296e482022-02-24 18:58:08 +0100538 yield self.key_for_usage_flags(known_flags, short='all known')
gabor-mezei-armbce85272021-06-24 14:38:51 +0200539
gabor-mezei-arme4b74992021-06-29 15:29:24 +0200540 def all_keys_for_usage_flags(self) -> Iterator[StorageTestData]:
gabor-mezei-arm5ea30372021-06-28 19:26:55 +0200541 yield from self.generate_keys_for_usage_flags()
542 yield from self.generate_key_for_all_usage_flags()
Gilles Peskine897dff92021-03-10 15:03:44 +0100543
Gilles Peskine6213a002021-04-29 22:28:07 +0200544 def key_for_type_and_alg(
545 self,
546 kt: crypto_knowledge.KeyType,
547 bits: int,
548 alg: Optional[crypto_knowledge.Algorithm] = None,
549 ) -> StorageTestData:
550 """Construct a test key of the given type.
551
552 If alg is not None, this key allows it.
553 """
Gilles Peskined9af9782022-03-17 22:32:59 +0100554 usage_flags = ['PSA_KEY_USAGE_EXPORT']
Gilles Peskine0de11432022-03-18 09:58:09 +0100555 alg1 = 0 #type: psa_storage.Exprable
Gilles Peskine6213a002021-04-29 22:28:07 +0200556 alg2 = 0
Gilles Peskine0de11432022-03-18 09:58:09 +0100557 if alg is not None:
558 alg1 = alg.expression
559 usage_flags += alg.usage_flags(public=kt.is_public())
Gilles Peskine6213a002021-04-29 22:28:07 +0200560 key_material = kt.key_material(bits)
Gilles Peskine930ccef2022-03-18 00:02:15 +0100561 description = 'type: {} {}-bit'.format(kt.short_expression(1), bits)
Gilles Peskine6213a002021-04-29 22:28:07 +0200562 if alg is not None:
Gilles Peskine930ccef2022-03-18 00:02:15 +0100563 description += ', ' + alg.short_expression(1)
Gilles Peskine6213a002021-04-29 22:28:07 +0200564 key = StorageTestData(version=self.version,
565 id=1, lifetime=0x00000001,
566 type=kt.expression, bits=bits,
567 usage=usage_flags, alg=alg1, alg2=alg2,
568 material=key_material,
569 description=description)
570 return key
571
Gilles Peskinef8223ab2021-03-10 15:07:16 +0100572 def keys_for_type(
573 self,
574 key_type: str,
Gilles Peskine6213a002021-04-29 22:28:07 +0200575 all_algorithms: List[crypto_knowledge.Algorithm],
gabor-mezei-arme4b74992021-06-29 15:29:24 +0200576 ) -> Iterator[StorageTestData]:
Gilles Peskine6213a002021-04-29 22:28:07 +0200577 """Generate test keys for the given key type."""
578 kt = crypto_knowledge.KeyType(key_type)
Gilles Peskinef8223ab2021-03-10 15:07:16 +0100579 for bits in kt.sizes_to_test():
Gilles Peskine6213a002021-04-29 22:28:07 +0200580 # Test a non-exercisable key, as well as exercisable keys for
581 # each compatible algorithm.
582 # To do: test reading a key from storage with an incompatible
583 # or unsupported algorithm.
584 yield self.key_for_type_and_alg(kt, bits)
585 compatible_algorithms = [alg for alg in all_algorithms
586 if kt.can_do(alg)]
587 for alg in compatible_algorithms:
588 yield self.key_for_type_and_alg(kt, bits, alg)
Gilles Peskinef8223ab2021-03-10 15:07:16 +0100589
gabor-mezei-arme4b74992021-06-29 15:29:24 +0200590 def all_keys_for_types(self) -> Iterator[StorageTestData]:
Gilles Peskinef8223ab2021-03-10 15:07:16 +0100591 """Generate test keys covering key types and their representations."""
Gilles Peskineb93f8542021-04-19 13:50:25 +0200592 key_types = sorted(self.constructors.key_types)
Gilles Peskine6213a002021-04-29 22:28:07 +0200593 all_algorithms = [crypto_knowledge.Algorithm(alg)
594 for alg in self.constructors.generate_expressions(
595 sorted(self.constructors.algorithms)
596 )]
gabor-mezei-arm5ea30372021-06-28 19:26:55 +0200597 for key_type in self.constructors.generate_expressions(key_types):
Gilles Peskine6213a002021-04-29 22:28:07 +0200598 yield from self.keys_for_type(key_type, all_algorithms)
Gilles Peskinef8223ab2021-03-10 15:07:16 +0100599
gabor-mezei-arme4b74992021-06-29 15:29:24 +0200600 def keys_for_algorithm(self, alg: str) -> Iterator[StorageTestData]:
Gilles Peskine6213a002021-04-29 22:28:07 +0200601 """Generate test keys for the encoding of the specified algorithm."""
602 # These test cases only validate the encoding of algorithms, not
603 # whether the key read from storage is suitable for an operation.
604 # `keys_for_types` generate read tests with an algorithm and a
605 # compatible key.
Gilles Peskine930ccef2022-03-18 00:02:15 +0100606 descr = crypto_knowledge.short_expression(alg, 1)
Gilles Peskined9af9782022-03-17 22:32:59 +0100607 usage = ['PSA_KEY_USAGE_EXPORT']
gabor-mezei-arme4b74992021-06-29 15:29:24 +0200608 key1 = StorageTestData(version=self.version,
609 id=1, lifetime=0x00000001,
610 type='PSA_KEY_TYPE_RAW_DATA', bits=8,
611 usage=usage, alg=alg, alg2=0,
612 material=b'K',
613 description='alg: ' + descr)
614 yield key1
615 key2 = StorageTestData(version=self.version,
616 id=1, lifetime=0x00000001,
617 type='PSA_KEY_TYPE_RAW_DATA', bits=8,
618 usage=usage, alg=0, alg2=alg,
619 material=b'L',
620 description='alg2: ' + descr)
621 yield key2
Gilles Peskined86bc522021-03-10 15:08:57 +0100622
gabor-mezei-arme4b74992021-06-29 15:29:24 +0200623 def all_keys_for_algorithms(self) -> Iterator[StorageTestData]:
Gilles Peskined86bc522021-03-10 15:08:57 +0100624 """Generate test keys covering algorithm encodings."""
Gilles Peskineb93f8542021-04-19 13:50:25 +0200625 algorithms = sorted(self.constructors.algorithms)
gabor-mezei-arm5ea30372021-06-28 19:26:55 +0200626 for alg in self.constructors.generate_expressions(algorithms):
627 yield from self.keys_for_algorithm(alg)
Gilles Peskined86bc522021-03-10 15:08:57 +0100628
gabor-mezei-armea840de2021-06-29 15:42:57 +0200629 def generate_all_keys(self) -> Iterator[StorageTestData]:
gabor-mezei-arm8b0c91c2021-06-24 09:49:50 +0200630 """Generate all keys for the test cases."""
gabor-mezei-armea840de2021-06-29 15:42:57 +0200631 yield from self.all_keys_for_lifetimes()
632 yield from self.all_keys_for_usage_flags()
633 yield from self.all_keys_for_types()
634 yield from self.all_keys_for_algorithms()
gabor-mezei-arm8b0c91c2021-06-24 09:49:50 +0200635
gabor-mezei-arm5ea30372021-06-28 19:26:55 +0200636 def all_test_cases(self) -> Iterator[test_case.TestCase]:
Gilles Peskine897dff92021-03-10 15:03:44 +0100637 """Generate all storage format test cases."""
Gilles Peskineae9f14b2021-04-12 14:43:05 +0200638 # First build a list of all keys, then construct all the corresponding
639 # test cases. This allows all required information to be obtained in
640 # one go, which is a significant performance gain as the information
641 # includes numerical values obtained by compiling a C program.
Gilles Peskine3008c582021-07-06 21:05:52 +0200642 all_keys = list(self.generate_all_keys())
643 for key in all_keys:
gabor-mezei-arm5ea30372021-06-28 19:26:55 +0200644 if key.location_value() != 0:
645 # Skip keys with a non-default location, because they
646 # require a driver and we currently have no mechanism to
647 # determine whether a driver is available.
648 continue
649 yield self.make_test_case(key)
Gilles Peskine897dff92021-03-10 15:03:44 +0100650
gabor-mezei-arm4d9fb732021-06-24 09:53:26 +0200651class StorageFormatForward(StorageFormat):
652 """Storage format stability test cases for forward compatibility."""
653
Tomás González734d22c2023-10-30 15:15:45 +0000654 def __init__(self, info: psa_information.Information, version: int) -> None:
gabor-mezei-arm4d9fb732021-06-24 09:53:26 +0200655 super().__init__(info, version, True)
656
657class StorageFormatV0(StorageFormat):
658 """Storage format stability test cases for version 0 compatibility."""
659
Tomás González734d22c2023-10-30 15:15:45 +0000660 def __init__(self, info: psa_information.Information) -> None:
gabor-mezei-arm4d9fb732021-06-24 09:53:26 +0200661 super().__init__(info, 0, False)
Gilles Peskine897dff92021-03-10 15:03:44 +0100662
gabor-mezei-arme4b74992021-06-29 15:29:24 +0200663 def all_keys_for_usage_flags(self) -> Iterator[StorageTestData]:
gabor-mezei-arm15c1f032021-06-24 10:04:38 +0200664 """Generate test keys covering usage flags."""
Gilles Peskinea296e482022-02-24 18:58:08 +0100665 yield from super().all_keys_for_usage_flags()
666 yield from self.generate_keys_for_usage_flags(test_implicit_usage=False)
gabor-mezei-arm15c1f032021-06-24 10:04:38 +0200667
gabor-mezei-armacfcc182021-06-28 17:40:32 +0200668 def keys_for_implicit_usage(
gabor-mezei-arm044fefc2021-06-24 10:16:44 +0200669 self,
gabor-mezei-arme84d3212021-06-28 16:54:11 +0200670 implyer_usage: str,
gabor-mezei-arm044fefc2021-06-24 10:16:44 +0200671 alg: str,
gabor-mezei-arm805c7352021-06-28 20:02:11 +0200672 key_type: crypto_knowledge.KeyType
gabor-mezei-arme4b74992021-06-29 15:29:24 +0200673 ) -> StorageTestData:
gabor-mezei-armb92d61b2021-06-24 14:38:25 +0200674 # pylint: disable=too-many-locals
gabor-mezei-arm927742e2021-06-28 16:27:29 +0200675 """Generate test keys for the specified implicit usage flag,
gabor-mezei-arm044fefc2021-06-24 10:16:44 +0200676 algorithm and key type combination.
677 """
gabor-mezei-arm805c7352021-06-28 20:02:11 +0200678 bits = key_type.sizes_to_test()[0]
gabor-mezei-arme84d3212021-06-28 16:54:11 +0200679 implicit_usage = StorageKey.IMPLICIT_USAGE_FLAGS[implyer_usage]
Gilles Peskined9af9782022-03-17 22:32:59 +0100680 usage_flags = ['PSA_KEY_USAGE_EXPORT']
681 material_usage_flags = usage_flags + [implyer_usage]
682 expected_usage_flags = material_usage_flags + [implicit_usage]
gabor-mezei-arm47812632021-06-28 16:35:48 +0200683 alg2 = 0
gabor-mezei-arm805c7352021-06-28 20:02:11 +0200684 key_material = key_type.key_material(bits)
Gilles Peskine930ccef2022-03-18 00:02:15 +0100685 usage_expression = crypto_knowledge.short_expression(implyer_usage, 1)
686 alg_expression = crypto_knowledge.short_expression(alg, 1)
687 key_type_expression = key_type.short_expression(1)
gabor-mezei-armacfcc182021-06-28 17:40:32 +0200688 description = 'implied by {}: {} {} {}-bit'.format(
gabor-mezei-arm47812632021-06-28 16:35:48 +0200689 usage_expression, alg_expression, key_type_expression, bits)
gabor-mezei-arme4b74992021-06-29 15:29:24 +0200690 key = StorageTestData(version=self.version,
691 id=1, lifetime=0x00000001,
692 type=key_type.expression, bits=bits,
693 usage=material_usage_flags,
694 expected_usage=expected_usage_flags,
695 without_implicit_usage=True,
696 alg=alg, alg2=alg2,
697 material=key_material,
698 description=description)
699 return key
gabor-mezei-arm044fefc2021-06-24 10:16:44 +0200700
701 def gather_key_types_for_sign_alg(self) -> Dict[str, List[str]]:
gabor-mezei-armb92d61b2021-06-24 14:38:25 +0200702 # pylint: disable=too-many-locals
gabor-mezei-arm044fefc2021-06-24 10:16:44 +0200703 """Match possible key types for sign algorithms."""
Shaun Case0e7791f2021-12-20 21:14:10 -0800704 # To create a valid combination both the algorithms and key types
gabor-mezei-arm044fefc2021-06-24 10:16:44 +0200705 # must be filtered. Pair them with keywords created from its names.
706 incompatible_alg_keyword = frozenset(['RAW', 'ANY', 'PURE'])
707 incompatible_key_type_keywords = frozenset(['MONTGOMERY'])
708 keyword_translation = {
709 'ECDSA': 'ECC',
710 'ED[0-9]*.*' : 'EDWARDS'
711 }
712 exclusive_keywords = {
713 'EDWARDS': 'ECC'
714 }
gabor-mezei-armb92d61b2021-06-24 14:38:25 +0200715 key_types = set(self.constructors.generate_expressions(self.constructors.key_types))
716 algorithms = set(self.constructors.generate_expressions(self.constructors.sign_algorithms))
gabor-mezei-arm044fefc2021-06-24 10:16:44 +0200717 alg_with_keys = {} #type: Dict[str, List[str]]
718 translation_table = str.maketrans('(', '_', ')')
719 for alg in algorithms:
720 # Generate keywords from the name of the algorithm
721 alg_keywords = set(alg.partition('(')[0].split(sep='_')[2:])
722 # Translate keywords for better matching with the key types
723 for keyword in alg_keywords.copy():
724 for pattern, replace in keyword_translation.items():
725 if re.match(pattern, keyword):
726 alg_keywords.remove(keyword)
727 alg_keywords.add(replace)
Shaun Case0e7791f2021-12-20 21:14:10 -0800728 # Filter out incompatible algorithms
gabor-mezei-arm044fefc2021-06-24 10:16:44 +0200729 if not alg_keywords.isdisjoint(incompatible_alg_keyword):
730 continue
731
732 for key_type in key_types:
733 # Generate keywords from the of the key type
734 key_type_keywords = set(key_type.translate(translation_table).split(sep='_')[3:])
735
Shaun Case0e7791f2021-12-20 21:14:10 -0800736 # Remove ambiguous keywords
gabor-mezei-arm044fefc2021-06-24 10:16:44 +0200737 for keyword1, keyword2 in exclusive_keywords.items():
738 if keyword1 in key_type_keywords:
739 key_type_keywords.remove(keyword2)
740
741 if key_type_keywords.isdisjoint(incompatible_key_type_keywords) and\
742 not key_type_keywords.isdisjoint(alg_keywords):
743 if alg in alg_with_keys:
744 alg_with_keys[alg].append(key_type)
745 else:
746 alg_with_keys[alg] = [key_type]
747 return alg_with_keys
748
gabor-mezei-arme4b74992021-06-29 15:29:24 +0200749 def all_keys_for_implicit_usage(self) -> Iterator[StorageTestData]:
gabor-mezei-arm044fefc2021-06-24 10:16:44 +0200750 """Generate test keys for usage flag extensions."""
751 # Generate a key type and algorithm pair for each extendable usage
752 # flag to generate a valid key for exercising. The key is generated
Shaun Case0e7791f2021-12-20 21:14:10 -0800753 # without usage extension to check the extension compatibility.
gabor-mezei-arm044fefc2021-06-24 10:16:44 +0200754 alg_with_keys = self.gather_key_types_for_sign_alg()
gabor-mezei-arm7d2ec9a2021-06-24 16:35:01 +0200755
gabor-mezei-arm5ea30372021-06-28 19:26:55 +0200756 for usage in sorted(StorageKey.IMPLICIT_USAGE_FLAGS, key=str):
757 for alg in sorted(alg_with_keys):
758 for key_type in sorted(alg_with_keys[alg]):
759 # The key types must be filtered to fit the specific usage flag.
gabor-mezei-arm805c7352021-06-28 20:02:11 +0200760 kt = crypto_knowledge.KeyType(key_type)
Gilles Peskine989c13d2022-03-17 12:52:24 +0100761 if kt.is_public() and '_SIGN_' in usage:
762 # Can't sign with a public key
763 continue
764 yield self.keys_for_implicit_usage(usage, alg, kt)
gabor-mezei-arm044fefc2021-06-24 10:16:44 +0200765
gabor-mezei-armea840de2021-06-29 15:42:57 +0200766 def generate_all_keys(self) -> Iterator[StorageTestData]:
767 yield from super().generate_all_keys()
768 yield from self.all_keys_for_implicit_usage()
gabor-mezei-arm15c1f032021-06-24 10:04:38 +0200769
Tomás González734d22c2023-10-30 15:15:45 +0000770
Gilles Peskine69feebd2022-09-16 21:41:47 +0200771class PSATestGenerator(test_data_generation.TestGenerator):
Werner Lewisdcad1e92022-08-24 11:30:03 +0100772 """Test generator subclass including PSA targets and info."""
Dave Rodgmanbeb5ad72022-04-22 14:52:41 +0100773 # Note that targets whose names contain 'test_format' have their content
Gilles Peskinecfd4fae2021-04-23 16:37:12 +0200774 # validated by `abi_check.py`.
Werner Lewis0d07e862022-09-02 11:56:34 +0100775 targets = {
Przemyslaw Stekiel997caf82021-10-15 15:21:51 +0200776 'test_suite_psa_crypto_generate_key.generated':
777 lambda info: KeyGenerate(info).test_cases_for_key_generation(),
Gilles Peskine0298bda2021-03-10 02:34:37 +0100778 'test_suite_psa_crypto_not_supported.generated':
Gilles Peskine4fa76bd2022-12-15 22:14:28 +0100779 lambda info: KeyTypeNotSupported(info).test_cases_for_not_supported(),
Tomás González2bff1bf2023-10-30 15:29:23 +0000780 'test_suite_psa_crypto_low_hash.generated':
781 lambda info: crypto_data_tests.HashPSALowLevel(info).all_test_cases(),
Gilles Peskinec05158b2021-04-27 20:40:10 +0200782 'test_suite_psa_crypto_op_fail.generated':
783 lambda info: OpFail(info).all_test_cases(),
Gilles Peskine897dff92021-03-10 15:03:44 +0100784 'test_suite_psa_crypto_storage_format.current':
gabor-mezei-arm4d9fb732021-06-24 09:53:26 +0200785 lambda info: StorageFormatForward(info, 0).all_test_cases(),
Gilles Peskine897dff92021-03-10 15:03:44 +0100786 'test_suite_psa_crypto_storage_format.v0':
gabor-mezei-arm4d9fb732021-06-24 09:53:26 +0200787 lambda info: StorageFormatV0(info).all_test_cases(),
Tomás González734d22c2023-10-30 15:15:45 +0000788 } #type: Dict[str, Callable[[psa_information.Information], Iterable[test_case.TestCase]]]
Gilles Peskine0298bda2021-03-10 02:34:37 +0100789
Werner Lewisdcad1e92022-08-24 11:30:03 +0100790 def __init__(self, options):
791 super().__init__(options)
Tomás González734d22c2023-10-30 15:15:45 +0000792 self.info = psa_information.Information()
Gilles Peskine14e428f2021-01-26 22:19:21 +0100793
Werner Lewisdcad1e92022-08-24 11:30:03 +0100794 def generate_target(self, name: str, *target_args) -> None:
795 super().generate_target(name, self.info)
Gilles Peskine09940492021-01-26 22:16:30 +0100796
Tomás González734d22c2023-10-30 15:15:45 +0000797
Gilles Peskine09940492021-01-26 22:16:30 +0100798if __name__ == '__main__':
Gilles Peskine69feebd2022-09-16 21:41:47 +0200799 test_data_generation.main(sys.argv[1:], __doc__, PSATestGenerator)