2021-01-26 22:16:30 +01:00
|
|
|
#!/usr/bin/env python3
|
|
|
|
"""Generate test data for PSA cryptographic mechanisms.
|
2021-03-10 02:34:37 +01:00
|
|
|
|
|
|
|
With no arguments, generate all test data. With non-option arguments,
|
|
|
|
generate only the specified files.
|
2021-01-26 22:16:30 +01:00
|
|
|
"""
|
|
|
|
|
|
|
|
# Copyright The Mbed TLS Contributors
|
|
|
|
# SPDX-License-Identifier: Apache-2.0
|
|
|
|
#
|
|
|
|
# Licensed under the Apache License, Version 2.0 (the "License"); you may
|
|
|
|
# not use this file except in compliance with the License.
|
|
|
|
# You may obtain a copy of the License at
|
|
|
|
#
|
|
|
|
# http://www.apache.org/licenses/LICENSE-2.0
|
|
|
|
#
|
|
|
|
# Unless required by applicable law or agreed to in writing, software
|
|
|
|
# distributed under the License is distributed on an "AS IS" BASIS, WITHOUT
|
|
|
|
# WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
|
|
|
|
# See the License for the specific language governing permissions and
|
|
|
|
# limitations under the License.
|
|
|
|
|
|
|
|
import argparse
|
2021-01-26 22:19:21 +01:00
|
|
|
import os
|
|
|
|
import re
|
2021-01-26 22:16:30 +01:00
|
|
|
import sys
|
2021-02-17 15:11:05 +01:00
|
|
|
from typing import Callable, Dict, FrozenSet, Iterable, Iterator, List, Optional, TypeVar
|
2021-01-26 22:16:30 +01:00
|
|
|
|
|
|
|
import scripts_path # pylint: disable=unused-import
|
2021-01-26 22:19:21 +01:00
|
|
|
from mbedtls_dev import crypto_knowledge
|
2021-01-26 22:16:30 +01:00
|
|
|
from mbedtls_dev import macro_collector
|
2021-03-10 15:03:44 +01:00
|
|
|
from mbedtls_dev import psa_storage
|
2021-01-26 22:19:21 +01:00
|
|
|
from mbedtls_dev import test_case
|
2021-01-26 22:16:30 +01:00
|
|
|
|
|
|
|
T = TypeVar('T') #pylint: disable=invalid-name
|
|
|
|
|
2021-01-26 22:19:21 +01:00
|
|
|
|
2021-02-16 12:13:12 +01:00
|
|
|
def psa_want_symbol(name: str) -> str:
|
2021-01-27 18:24:48 +01:00
|
|
|
"""Return the PSA_WANT_xxx symbol associated with a PSA crypto feature."""
|
|
|
|
if name.startswith('PSA_'):
|
|
|
|
return name[:4] + 'WANT_' + name[4:]
|
|
|
|
else:
|
|
|
|
raise ValueError('Unable to determine the PSA_WANT_ symbol for ' + name)
|
|
|
|
|
2021-02-16 12:13:12 +01:00
|
|
|
def finish_family_dependency(dep: str, bits: int) -> str:
|
|
|
|
"""Finish dep if it's a family dependency symbol prefix.
|
|
|
|
|
|
|
|
A family dependency symbol prefix is a PSA_WANT_ symbol that needs to be
|
|
|
|
qualified by the key size. If dep is such a symbol, finish it by adjusting
|
|
|
|
the prefix and appending the key size. Other symbols are left unchanged.
|
|
|
|
"""
|
|
|
|
return re.sub(r'_FAMILY_(.*)', r'_\1_' + str(bits), dep)
|
|
|
|
|
|
|
|
def finish_family_dependencies(dependencies: List[str], bits: int) -> List[str]:
|
|
|
|
"""Finish any family dependency symbol prefixes.
|
|
|
|
|
|
|
|
Apply `finish_family_dependency` to each element of `dependencies`.
|
|
|
|
"""
|
|
|
|
return [finish_family_dependency(dep, bits) for dep in dependencies]
|
2021-01-27 18:24:48 +01:00
|
|
|
|
2021-04-20 23:23:45 +02:00
|
|
|
SYMBOLS_WITHOUT_DEPENDENCY = frozenset([
|
|
|
|
'PSA_ALG_AEAD_WITH_AT_LEAST_THIS_LENGTH_TAG', # modifier, only in policies
|
|
|
|
'PSA_ALG_AEAD_WITH_SHORTENED_TAG', # modifier
|
|
|
|
'PSA_ALG_ANY_HASH', # only in policies
|
|
|
|
'PSA_ALG_AT_LEAST_THIS_LENGTH_MAC', # modifier, only in policies
|
|
|
|
'PSA_ALG_KEY_AGREEMENT', # chaining
|
|
|
|
'PSA_ALG_TRUNCATED_MAC', # modifier
|
|
|
|
])
|
2021-03-10 15:07:16 +01:00
|
|
|
def automatic_dependencies(*expressions: str) -> List[str]:
|
|
|
|
"""Infer dependencies of a test case by looking for PSA_xxx symbols.
|
|
|
|
|
|
|
|
The arguments are strings which should be C expressions. Do not use
|
|
|
|
string literals or comments as this function is not smart enough to
|
|
|
|
skip them.
|
|
|
|
"""
|
|
|
|
used = set()
|
|
|
|
for expr in expressions:
|
|
|
|
used.update(re.findall(r'PSA_(?:ALG|ECC_FAMILY|KEY_TYPE)_\w+', expr))
|
2021-04-20 23:23:45 +02:00
|
|
|
used.difference_update(SYMBOLS_WITHOUT_DEPENDENCY)
|
2021-03-10 15:07:16 +01:00
|
|
|
return sorted(psa_want_symbol(name) for name in used)
|
|
|
|
|
2021-02-16 14:16:25 +01:00
|
|
|
# A temporary hack: at the time of writing, not all dependency symbols
|
|
|
|
# are implemented yet. Skip test cases for which the dependency symbols are
|
|
|
|
# not available. Once all dependency symbols are available, this hack must
|
|
|
|
# be removed so that a bug in the dependency symbols proprely leads to a test
|
|
|
|
# failure.
|
|
|
|
def read_implemented_dependencies(filename: str) -> FrozenSet[str]:
|
|
|
|
return frozenset(symbol
|
|
|
|
for line in open(filename)
|
|
|
|
for symbol in re.findall(r'\bPSA_WANT_\w+\b', line))
|
|
|
|
IMPLEMENTED_DEPENDENCIES = read_implemented_dependencies('include/psa/crypto_config.h')
|
|
|
|
def hack_dependencies_not_implemented(dependencies: List[str]) -> None:
|
|
|
|
if not all(dep.lstrip('!') in IMPLEMENTED_DEPENDENCIES
|
|
|
|
for dep in dependencies):
|
|
|
|
dependencies.append('DEPENDENCY_NOT_IMPLEMENTED_YET')
|
|
|
|
|
2021-01-26 22:19:21 +01:00
|
|
|
|
2021-03-10 02:12:08 +01:00
|
|
|
class Information:
|
|
|
|
"""Gather information about PSA constructors."""
|
2021-01-26 22:16:30 +01:00
|
|
|
|
2021-03-10 02:12:08 +01:00
|
|
|
def __init__(self) -> None:
|
2021-01-26 22:16:30 +01:00
|
|
|
self.constructors = self.read_psa_interface()
|
|
|
|
|
|
|
|
@staticmethod
|
|
|
|
def remove_unwanted_macros(
|
2021-04-19 13:50:25 +02:00
|
|
|
constructors: macro_collector.PSAMacroEnumerator
|
2021-01-26 22:16:30 +01:00
|
|
|
) -> None:
|
2021-04-19 13:50:25 +02:00
|
|
|
# Mbed TLS doesn't support finite-field DH yet and will not support
|
|
|
|
# finite-field DSA. Don't attempt to generate any related test case.
|
|
|
|
constructors.key_types.discard('PSA_KEY_TYPE_DH_KEY_PAIR')
|
|
|
|
constructors.key_types.discard('PSA_KEY_TYPE_DH_PUBLIC_KEY')
|
2021-01-26 22:16:30 +01:00
|
|
|
constructors.key_types.discard('PSA_KEY_TYPE_DSA_KEY_PAIR')
|
|
|
|
constructors.key_types.discard('PSA_KEY_TYPE_DSA_PUBLIC_KEY')
|
|
|
|
|
2021-04-19 13:50:25 +02:00
|
|
|
def read_psa_interface(self) -> macro_collector.PSAMacroEnumerator:
|
2021-01-26 22:16:30 +01:00
|
|
|
"""Return the list of known key types, algorithms, etc."""
|
2021-03-30 21:46:35 +02:00
|
|
|
constructors = macro_collector.InputsForTest()
|
2021-01-26 22:16:30 +01:00
|
|
|
header_file_names = ['include/psa/crypto_values.h',
|
|
|
|
'include/psa/crypto_extra.h']
|
2021-04-19 13:50:25 +02:00
|
|
|
test_suites = ['tests/suites/test_suite_psa_crypto_metadata.data']
|
2021-01-26 22:16:30 +01:00
|
|
|
for header_file_name in header_file_names:
|
2021-04-19 13:50:25 +02:00
|
|
|
constructors.parse_header(header_file_name)
|
|
|
|
for test_cases in test_suites:
|
|
|
|
constructors.parse_test_cases(test_cases)
|
2021-01-26 22:16:30 +01:00
|
|
|
self.remove_unwanted_macros(constructors)
|
2021-03-30 21:46:35 +02:00
|
|
|
constructors.gather_arguments()
|
2021-01-26 22:16:30 +01:00
|
|
|
return constructors
|
|
|
|
|
2021-01-26 22:19:21 +01:00
|
|
|
|
2021-10-08 12:26:21 +02:00
|
|
|
def test_case_for_key_type_not_supported_invalid_arg(
|
2021-03-10 02:12:08 +01:00
|
|
|
verb: str, key_type: str, bits: int,
|
|
|
|
dependencies: List[str],
|
|
|
|
*args: str,
|
|
|
|
param_descr: str = ''
|
|
|
|
) -> test_case.TestCase:
|
|
|
|
"""Return one test case exercising a key creation method
|
|
|
|
for an unsupported key type or size.
|
|
|
|
"""
|
|
|
|
hack_dependencies_not_implemented(dependencies)
|
|
|
|
tc = test_case.TestCase()
|
|
|
|
short_key_type = re.sub(r'PSA_(KEY_TYPE|ECC_FAMILY)_', r'', key_type)
|
|
|
|
adverb = 'not' if dependencies else 'never'
|
|
|
|
if param_descr:
|
|
|
|
adverb = param_descr + ' ' + adverb
|
2021-10-08 12:26:21 +02:00
|
|
|
if (verb == "generate") and ("PUBLIC" in short_key_type):
|
|
|
|
tc.set_description('PSA {} {} {}-bit invalid argument'
|
|
|
|
.format(verb, short_key_type, bits))
|
|
|
|
tc.set_function(verb + '_invalid_arg')
|
|
|
|
else:
|
|
|
|
tc.set_description('PSA {} {} {}-bit {} supported'
|
|
|
|
.format(verb, short_key_type, bits, adverb))
|
|
|
|
tc.set_function(verb + '_not_supported')
|
2021-03-10 02:12:08 +01:00
|
|
|
tc.set_dependencies(dependencies)
|
|
|
|
tc.set_arguments([key_type] + list(args))
|
|
|
|
return tc
|
|
|
|
|
|
|
|
class NotSupported:
|
|
|
|
"""Generate test cases for when something is not supported."""
|
|
|
|
|
|
|
|
def __init__(self, info: Information) -> None:
|
|
|
|
self.constructors = info.constructors
|
2021-01-26 22:19:21 +01:00
|
|
|
|
2021-02-16 14:06:50 +01:00
|
|
|
ALWAYS_SUPPORTED = frozenset([
|
|
|
|
'PSA_KEY_TYPE_DERIVE',
|
|
|
|
'PSA_KEY_TYPE_RAW_DATA',
|
|
|
|
])
|
2021-01-26 22:19:21 +01:00
|
|
|
def test_cases_for_key_type_not_supported(
|
2021-02-16 14:06:50 +01:00
|
|
|
self,
|
2021-01-27 18:24:48 +01:00
|
|
|
kt: crypto_knowledge.KeyType,
|
|
|
|
param: Optional[int] = None,
|
|
|
|
param_descr: str = '',
|
2021-02-17 15:11:05 +01:00
|
|
|
) -> Iterator[test_case.TestCase]:
|
2021-01-27 18:24:48 +01:00
|
|
|
"""Return test cases exercising key creation when the given type is unsupported.
|
|
|
|
|
|
|
|
If param is present and not None, emit test cases conditioned on this
|
|
|
|
parameter not being supported. If it is absent or None, emit test cases
|
|
|
|
conditioned on the base type not being supported.
|
|
|
|
"""
|
2021-02-16 14:06:50 +01:00
|
|
|
if kt.name in self.ALWAYS_SUPPORTED:
|
|
|
|
# Don't generate test cases for key types that are always supported.
|
|
|
|
# They would be skipped in all configurations, which is noise.
|
2021-02-17 15:11:05 +01:00
|
|
|
return
|
2021-01-27 18:24:48 +01:00
|
|
|
import_dependencies = [('!' if param is None else '') +
|
|
|
|
psa_want_symbol(kt.name)]
|
|
|
|
if kt.params is not None:
|
|
|
|
import_dependencies += [('!' if param == i else '') +
|
|
|
|
psa_want_symbol(sym)
|
|
|
|
for i, sym in enumerate(kt.params)]
|
2021-01-26 22:19:21 +01:00
|
|
|
if kt.name.endswith('_PUBLIC_KEY'):
|
|
|
|
generate_dependencies = []
|
|
|
|
else:
|
|
|
|
generate_dependencies = import_dependencies
|
|
|
|
for bits in kt.sizes_to_test():
|
2021-10-08 12:26:21 +02:00
|
|
|
yield test_case_for_key_type_not_supported_invalid_arg(
|
2021-02-16 12:13:12 +01:00
|
|
|
'import', kt.expression, bits,
|
|
|
|
finish_family_dependencies(import_dependencies, bits),
|
2021-01-27 18:24:48 +01:00
|
|
|
test_case.hex_string(kt.key_material(bits)),
|
|
|
|
param_descr=param_descr,
|
2021-02-17 15:11:05 +01:00
|
|
|
)
|
2021-01-27 18:24:48 +01:00
|
|
|
if not generate_dependencies and param is not None:
|
|
|
|
# If generation is impossible for this key type, rather than
|
|
|
|
# supported or not depending on implementation capabilities,
|
|
|
|
# only generate the test case once.
|
|
|
|
continue
|
2021-10-08 12:26:21 +02:00
|
|
|
yield test_case_for_key_type_not_supported_invalid_arg(
|
2021-02-16 12:13:12 +01:00
|
|
|
'generate', kt.expression, bits,
|
|
|
|
finish_family_dependencies(generate_dependencies, bits),
|
2021-01-27 18:24:48 +01:00
|
|
|
str(bits),
|
|
|
|
param_descr=param_descr,
|
2021-02-17 15:11:05 +01:00
|
|
|
)
|
2021-01-26 22:19:21 +01:00
|
|
|
# To be added: derive
|
|
|
|
|
2021-04-19 13:50:25 +02:00
|
|
|
ECC_KEY_TYPES = ('PSA_KEY_TYPE_ECC_KEY_PAIR',
|
|
|
|
'PSA_KEY_TYPE_ECC_PUBLIC_KEY')
|
|
|
|
|
2021-02-17 15:11:05 +01:00
|
|
|
def test_cases_for_not_supported(self) -> Iterator[test_case.TestCase]:
|
2021-01-26 22:19:21 +01:00
|
|
|
"""Generate test cases that exercise the creation of keys of unsupported types."""
|
|
|
|
for key_type in sorted(self.constructors.key_types):
|
2021-04-19 13:50:25 +02:00
|
|
|
if key_type in self.ECC_KEY_TYPES:
|
|
|
|
continue
|
2021-01-26 22:19:21 +01:00
|
|
|
kt = crypto_knowledge.KeyType(key_type)
|
2021-02-17 15:11:05 +01:00
|
|
|
yield from self.test_cases_for_key_type_not_supported(kt)
|
2021-01-27 18:24:48 +01:00
|
|
|
for curve_family in sorted(self.constructors.ecc_curves):
|
2021-04-19 13:50:25 +02:00
|
|
|
for constr in self.ECC_KEY_TYPES:
|
2021-01-27 18:24:48 +01:00
|
|
|
kt = crypto_knowledge.KeyType(constr, [curve_family])
|
2021-02-17 15:11:05 +01:00
|
|
|
yield from self.test_cases_for_key_type_not_supported(
|
2021-01-27 18:24:48 +01:00
|
|
|
kt, param_descr='type')
|
2021-02-17 15:11:05 +01:00
|
|
|
yield from self.test_cases_for_key_type_not_supported(
|
2021-01-27 18:24:48 +01:00
|
|
|
kt, 0, param_descr='curve')
|
2021-03-10 02:12:08 +01:00
|
|
|
|
|
|
|
|
2021-03-10 15:03:44 +01:00
|
|
|
class StorageKey(psa_storage.Key):
|
|
|
|
"""Representation of a key for storage format testing."""
|
|
|
|
|
2021-06-29 15:29:24 +02:00
|
|
|
IMPLICIT_USAGE_FLAGS = {
|
|
|
|
'PSA_KEY_USAGE_SIGN_HASH': 'PSA_KEY_USAGE_SIGN_MESSAGE',
|
|
|
|
'PSA_KEY_USAGE_VERIFY_HASH': 'PSA_KEY_USAGE_VERIFY_MESSAGE'
|
|
|
|
} #type: Dict[str, str]
|
|
|
|
"""Mapping of usage flags to the flags that they imply."""
|
|
|
|
|
|
|
|
def __init__(
|
|
|
|
self,
|
|
|
|
usage: str,
|
|
|
|
without_implicit_usage: Optional[bool] = False,
|
|
|
|
**kwargs
|
|
|
|
) -> None:
|
|
|
|
"""Prepare to generate a key.
|
|
|
|
|
|
|
|
* `usage` : The usage flags used for the key.
|
|
|
|
* `without_implicit_usage`: Flag to defide to apply the usage extension
|
|
|
|
"""
|
2021-06-29 17:21:21 +02:00
|
|
|
super().__init__(usage=usage, **kwargs)
|
2021-06-29 15:29:24 +02:00
|
|
|
|
|
|
|
if not without_implicit_usage:
|
|
|
|
for flag, implicit in self.IMPLICIT_USAGE_FLAGS.items():
|
|
|
|
if self.usage.value() & psa_storage.Expr(flag).value() and \
|
|
|
|
self.usage.value() & psa_storage.Expr(implicit).value() == 0:
|
|
|
|
self.usage = psa_storage.Expr(self.usage.string + ' | ' + implicit)
|
|
|
|
|
|
|
|
class StorageTestData(StorageKey):
|
|
|
|
"""Representation of test case data for storage format testing."""
|
|
|
|
|
2021-06-24 10:16:44 +02:00
|
|
|
def __init__(
|
|
|
|
self,
|
|
|
|
description: str,
|
|
|
|
expected_usage: Optional[str] = None,
|
|
|
|
**kwargs
|
|
|
|
) -> None:
|
2021-06-29 15:29:24 +02:00
|
|
|
"""Prepare to generate test data
|
2021-06-24 10:16:44 +02:00
|
|
|
|
2021-06-29 15:29:24 +02:00
|
|
|
* `description` : used for the the test case names
|
|
|
|
* `expected_usage`: the usage flags generated as the expected usage flags
|
|
|
|
in the test cases. CAn differ from the usage flags
|
|
|
|
stored in the keys because of the usage flags extension.
|
2021-06-24 10:16:44 +02:00
|
|
|
"""
|
2021-03-10 15:03:44 +01:00
|
|
|
super().__init__(**kwargs)
|
|
|
|
self.description = description #type: str
|
2021-06-29 15:29:24 +02:00
|
|
|
self.expected_usage = expected_usage if expected_usage else self.usage.string #type: str
|
2021-06-24 10:04:38 +02:00
|
|
|
|
2021-03-10 15:03:44 +01:00
|
|
|
class StorageFormat:
|
|
|
|
"""Storage format stability test cases."""
|
|
|
|
|
|
|
|
def __init__(self, info: Information, version: int, forward: bool) -> None:
|
|
|
|
"""Prepare to generate test cases for storage format stability.
|
|
|
|
|
|
|
|
* `info`: information about the API. See the `Information` class.
|
|
|
|
* `version`: the storage format version to generate test cases for.
|
|
|
|
* `forward`: if true, generate forward compatibility test cases which
|
|
|
|
save a key and check that its representation is as intended. Otherwise
|
|
|
|
generate backward compatibility test cases which inject a key
|
|
|
|
representation and check that it can be read and used.
|
|
|
|
"""
|
2021-06-23 17:01:44 +02:00
|
|
|
self.constructors = info.constructors #type: macro_collector.PSAMacroEnumerator
|
|
|
|
self.version = version #type: int
|
|
|
|
self.forward = forward #type: bool
|
2021-03-10 15:03:44 +01:00
|
|
|
|
2021-06-29 15:29:24 +02:00
|
|
|
def make_test_case(self, key: StorageTestData) -> test_case.TestCase:
|
2021-03-10 15:03:44 +01:00
|
|
|
"""Construct a storage format test case for the given key.
|
|
|
|
|
|
|
|
If ``forward`` is true, generate a forward compatibility test case:
|
|
|
|
create a key and validate that it has the expected representation.
|
|
|
|
Otherwise generate a backward compatibility test case: inject the
|
|
|
|
key representation into storage and validate that it can be read
|
|
|
|
correctly.
|
|
|
|
"""
|
|
|
|
verb = 'save' if self.forward else 'read'
|
|
|
|
tc = test_case.TestCase()
|
|
|
|
tc.set_description('PSA storage {}: {}'.format(verb, key.description))
|
2021-03-10 15:07:16 +01:00
|
|
|
dependencies = automatic_dependencies(
|
|
|
|
key.lifetime.string, key.type.string,
|
2021-06-29 15:29:24 +02:00
|
|
|
key.expected_usage, key.alg.string, key.alg2.string,
|
2021-03-10 15:07:16 +01:00
|
|
|
)
|
|
|
|
dependencies = finish_family_dependencies(dependencies, key.bits)
|
|
|
|
tc.set_dependencies(dependencies)
|
2021-03-10 15:03:44 +01:00
|
|
|
tc.set_function('key_storage_' + verb)
|
|
|
|
if self.forward:
|
|
|
|
extra_arguments = []
|
|
|
|
else:
|
2021-04-21 20:11:33 +02:00
|
|
|
flags = []
|
2021-03-10 15:03:44 +01:00
|
|
|
# Some test keys have the RAW_DATA type and attributes that don't
|
|
|
|
# necessarily make sense. We do this to validate numerical
|
|
|
|
# encodings of the attributes.
|
|
|
|
# Raw data keys have no useful exercise anyway so there is no
|
|
|
|
# loss of test coverage.
|
2021-04-21 20:11:33 +02:00
|
|
|
if key.type.string != 'PSA_KEY_TYPE_RAW_DATA':
|
|
|
|
flags.append('TEST_FLAG_EXERCISE')
|
|
|
|
if 'READ_ONLY' in key.lifetime.string:
|
|
|
|
flags.append('TEST_FLAG_READ_ONLY')
|
|
|
|
extra_arguments = [' | '.join(flags) if flags else '0']
|
2021-03-10 15:03:44 +01:00
|
|
|
tc.set_arguments([key.lifetime.string,
|
|
|
|
key.type.string, str(key.bits),
|
2021-06-29 15:29:24 +02:00
|
|
|
key.expected_usage, key.alg.string, key.alg2.string,
|
2021-03-10 15:03:44 +01:00
|
|
|
'"' + key.material.hex() + '"',
|
|
|
|
'"' + key.hex() + '"',
|
|
|
|
*extra_arguments])
|
|
|
|
return tc
|
|
|
|
|
2021-04-21 22:05:34 +02:00
|
|
|
def key_for_lifetime(
|
|
|
|
self,
|
|
|
|
lifetime: str,
|
2021-06-29 15:29:24 +02:00
|
|
|
) -> StorageTestData:
|
2021-04-21 22:05:34 +02:00
|
|
|
"""Construct a test key for the given lifetime."""
|
|
|
|
short = lifetime
|
|
|
|
short = re.sub(r'PSA_KEY_LIFETIME_FROM_PERSISTENCE_AND_LOCATION',
|
|
|
|
r'', short)
|
|
|
|
short = re.sub(r'PSA_KEY_[A-Z]+_', r'', short)
|
|
|
|
description = 'lifetime: ' + short
|
2021-06-29 15:29:24 +02:00
|
|
|
key = StorageTestData(version=self.version,
|
|
|
|
id=1, lifetime=lifetime,
|
|
|
|
type='PSA_KEY_TYPE_RAW_DATA', bits=8,
|
|
|
|
usage='PSA_KEY_USAGE_EXPORT', alg=0, alg2=0,
|
|
|
|
material=b'L',
|
|
|
|
description=description)
|
|
|
|
return key
|
|
|
|
|
|
|
|
def all_keys_for_lifetimes(self) -> Iterator[StorageTestData]:
|
2021-04-21 22:05:34 +02:00
|
|
|
"""Generate test keys covering lifetimes."""
|
|
|
|
lifetimes = sorted(self.constructors.lifetimes)
|
|
|
|
expressions = self.constructors.generate_expressions(lifetimes)
|
|
|
|
for lifetime in expressions:
|
|
|
|
# Don't attempt to create or load a volatile key in storage
|
|
|
|
if 'VOLATILE' in lifetime:
|
|
|
|
continue
|
|
|
|
# Don't attempt to create a read-only key in storage,
|
|
|
|
# but do attempt to load one.
|
|
|
|
if 'READ_ONLY' in lifetime and self.forward:
|
|
|
|
continue
|
2021-06-28 19:26:55 +02:00
|
|
|
yield self.key_for_lifetime(lifetime)
|
2021-04-21 22:05:34 +02:00
|
|
|
|
2021-06-29 15:39:56 +02:00
|
|
|
def keys_for_usage_flags(
|
2021-03-10 15:03:44 +01:00
|
|
|
self,
|
|
|
|
usage_flags: List[str],
|
2021-06-24 09:42:02 +02:00
|
|
|
short: Optional[str] = None,
|
2021-06-28 19:26:55 +02:00
|
|
|
test_implicit_usage: Optional[bool] = False
|
2021-06-29 15:29:24 +02:00
|
|
|
) -> Iterator[StorageTestData]:
|
2021-03-10 15:03:44 +01:00
|
|
|
"""Construct a test key for the given key usage."""
|
|
|
|
usage = ' | '.join(usage_flags) if usage_flags else '0'
|
|
|
|
if short is None:
|
|
|
|
short = re.sub(r'\bPSA_KEY_USAGE_', r'', usage)
|
2021-06-28 19:26:55 +02:00
|
|
|
extra_desc = ' with implication' if test_implicit_usage else ''
|
2021-06-24 09:42:02 +02:00
|
|
|
description = 'usage' + extra_desc + ': ' + short
|
2021-06-29 15:29:24 +02:00
|
|
|
key1 = StorageTestData(version=self.version,
|
|
|
|
id=1, lifetime=0x00000001,
|
|
|
|
type='PSA_KEY_TYPE_RAW_DATA', bits=8,
|
|
|
|
expected_usage=usage,
|
|
|
|
usage=usage, alg=0, alg2=0,
|
|
|
|
material=b'K',
|
|
|
|
description=description)
|
|
|
|
yield key1
|
|
|
|
|
2021-06-28 19:26:55 +02:00
|
|
|
if test_implicit_usage:
|
|
|
|
description = 'usage without implication' + ': ' + short
|
2021-06-29 15:29:24 +02:00
|
|
|
key2 = StorageTestData(version=self.version,
|
|
|
|
id=1, lifetime=0x00000001,
|
|
|
|
type='PSA_KEY_TYPE_RAW_DATA', bits=8,
|
|
|
|
without_implicit_usage=True,
|
|
|
|
usage=usage, alg=0, alg2=0,
|
|
|
|
material=b'K',
|
|
|
|
description=description)
|
|
|
|
yield key2
|
|
|
|
|
|
|
|
def generate_keys_for_usage_flags(self, **kwargs) -> Iterator[StorageTestData]:
|
2021-03-10 15:03:44 +01:00
|
|
|
"""Generate test keys covering usage flags."""
|
|
|
|
known_flags = sorted(self.constructors.key_usage_flags)
|
2021-06-29 15:39:56 +02:00
|
|
|
yield from self.keys_for_usage_flags(['0'], **kwargs)
|
2021-06-28 19:26:55 +02:00
|
|
|
for usage_flag in known_flags:
|
2021-06-29 15:39:56 +02:00
|
|
|
yield from self.keys_for_usage_flags([usage_flag], **kwargs)
|
2021-06-28 19:26:55 +02:00
|
|
|
for flag1, flag2 in zip(known_flags,
|
|
|
|
known_flags[1:] + [known_flags[0]]):
|
2021-06-29 15:39:56 +02:00
|
|
|
yield from self.keys_for_usage_flags([flag1, flag2], **kwargs)
|
2021-06-28 19:26:55 +02:00
|
|
|
|
2021-06-29 15:29:24 +02:00
|
|
|
def generate_key_for_all_usage_flags(self) -> Iterator[StorageTestData]:
|
2021-06-24 14:38:51 +02:00
|
|
|
known_flags = sorted(self.constructors.key_usage_flags)
|
2021-06-29 15:39:56 +02:00
|
|
|
yield from self.keys_for_usage_flags(known_flags, short='all known')
|
2021-06-24 14:38:51 +02:00
|
|
|
|
2021-06-29 15:29:24 +02:00
|
|
|
def all_keys_for_usage_flags(self) -> Iterator[StorageTestData]:
|
2021-06-28 19:26:55 +02:00
|
|
|
yield from self.generate_keys_for_usage_flags()
|
|
|
|
yield from self.generate_key_for_all_usage_flags()
|
2021-03-10 15:03:44 +01:00
|
|
|
|
2021-03-10 15:07:16 +01:00
|
|
|
def keys_for_type(
|
|
|
|
self,
|
|
|
|
key_type: str,
|
|
|
|
params: Optional[Iterable[str]] = None
|
2021-06-29 15:29:24 +02:00
|
|
|
) -> Iterator[StorageTestData]:
|
2021-03-10 15:07:16 +01:00
|
|
|
"""Generate test keys for the given key type.
|
|
|
|
|
|
|
|
For key types that depend on a parameter (e.g. elliptic curve family),
|
|
|
|
`param` is the parameter to pass to the constructor. Only a single
|
|
|
|
parameter is supported.
|
|
|
|
"""
|
|
|
|
kt = crypto_knowledge.KeyType(key_type, params)
|
|
|
|
for bits in kt.sizes_to_test():
|
|
|
|
usage_flags = 'PSA_KEY_USAGE_EXPORT'
|
|
|
|
alg = 0
|
|
|
|
alg2 = 0
|
|
|
|
key_material = kt.key_material(bits)
|
|
|
|
short_expression = re.sub(r'\bPSA_(?:KEY_TYPE|ECC_FAMILY)_',
|
|
|
|
r'',
|
|
|
|
kt.expression)
|
|
|
|
description = 'type: {} {}-bit'.format(short_expression, bits)
|
2021-06-29 15:29:24 +02:00
|
|
|
key = StorageTestData(version=self.version,
|
|
|
|
id=1, lifetime=0x00000001,
|
|
|
|
type=kt.expression, bits=bits,
|
|
|
|
usage=usage_flags, alg=alg, alg2=alg2,
|
|
|
|
material=key_material,
|
|
|
|
description=description)
|
|
|
|
yield key
|
|
|
|
|
|
|
|
def all_keys_for_types(self) -> Iterator[StorageTestData]:
|
2021-03-10 15:07:16 +01:00
|
|
|
"""Generate test keys covering key types and their representations."""
|
2021-04-19 13:50:25 +02:00
|
|
|
key_types = sorted(self.constructors.key_types)
|
2021-06-28 19:26:55 +02:00
|
|
|
for key_type in self.constructors.generate_expressions(key_types):
|
|
|
|
yield from self.keys_for_type(key_type)
|
2021-03-10 15:07:16 +01:00
|
|
|
|
2021-06-29 15:29:24 +02:00
|
|
|
def keys_for_algorithm(self, alg: str) -> Iterator[StorageTestData]:
|
2021-03-10 15:08:57 +01:00
|
|
|
"""Generate test keys for the specified algorithm."""
|
|
|
|
# For now, we don't have information on the compatibility of key
|
|
|
|
# types and algorithms. So we just test the encoding of algorithms,
|
|
|
|
# and not that operations can be performed with them.
|
2021-04-21 10:18:19 +02:00
|
|
|
descr = re.sub(r'PSA_ALG_', r'', alg)
|
|
|
|
descr = re.sub(r',', r', ', re.sub(r' +', r'', descr))
|
2021-03-10 15:08:57 +01:00
|
|
|
usage = 'PSA_KEY_USAGE_EXPORT'
|
2021-06-29 15:29:24 +02:00
|
|
|
key1 = StorageTestData(version=self.version,
|
|
|
|
id=1, lifetime=0x00000001,
|
|
|
|
type='PSA_KEY_TYPE_RAW_DATA', bits=8,
|
|
|
|
usage=usage, alg=alg, alg2=0,
|
|
|
|
material=b'K',
|
|
|
|
description='alg: ' + descr)
|
|
|
|
yield key1
|
|
|
|
key2 = StorageTestData(version=self.version,
|
|
|
|
id=1, lifetime=0x00000001,
|
|
|
|
type='PSA_KEY_TYPE_RAW_DATA', bits=8,
|
|
|
|
usage=usage, alg=0, alg2=alg,
|
|
|
|
material=b'L',
|
|
|
|
description='alg2: ' + descr)
|
|
|
|
yield key2
|
|
|
|
|
|
|
|
def all_keys_for_algorithms(self) -> Iterator[StorageTestData]:
|
2021-03-10 15:08:57 +01:00
|
|
|
"""Generate test keys covering algorithm encodings."""
|
2021-04-19 13:50:25 +02:00
|
|
|
algorithms = sorted(self.constructors.algorithms)
|
2021-06-28 19:26:55 +02:00
|
|
|
for alg in self.constructors.generate_expressions(algorithms):
|
|
|
|
yield from self.keys_for_algorithm(alg)
|
2021-03-10 15:08:57 +01:00
|
|
|
|
2021-06-29 15:42:57 +02:00
|
|
|
def generate_all_keys(self) -> Iterator[StorageTestData]:
|
2021-06-24 09:49:50 +02:00
|
|
|
"""Generate all keys for the test cases."""
|
2021-06-29 15:42:57 +02:00
|
|
|
yield from self.all_keys_for_lifetimes()
|
|
|
|
yield from self.all_keys_for_usage_flags()
|
|
|
|
yield from self.all_keys_for_types()
|
|
|
|
yield from self.all_keys_for_algorithms()
|
2021-06-24 09:49:50 +02:00
|
|
|
|
2021-06-28 19:26:55 +02:00
|
|
|
def all_test_cases(self) -> Iterator[test_case.TestCase]:
|
2021-03-10 15:03:44 +01:00
|
|
|
"""Generate all storage format test cases."""
|
2021-04-12 14:43:05 +02:00
|
|
|
# First build a list of all keys, then construct all the corresponding
|
|
|
|
# test cases. This allows all required information to be obtained in
|
|
|
|
# one go, which is a significant performance gain as the information
|
|
|
|
# includes numerical values obtained by compiling a C program.
|
2021-07-06 21:05:52 +02:00
|
|
|
all_keys = list(self.generate_all_keys())
|
|
|
|
for key in all_keys:
|
2021-06-28 19:26:55 +02:00
|
|
|
if key.location_value() != 0:
|
|
|
|
# Skip keys with a non-default location, because they
|
|
|
|
# require a driver and we currently have no mechanism to
|
|
|
|
# determine whether a driver is available.
|
|
|
|
continue
|
|
|
|
yield self.make_test_case(key)
|
2021-03-10 15:03:44 +01:00
|
|
|
|
2021-06-24 09:53:26 +02:00
|
|
|
class StorageFormatForward(StorageFormat):
|
|
|
|
"""Storage format stability test cases for forward compatibility."""
|
|
|
|
|
|
|
|
def __init__(self, info: Information, version: int) -> None:
|
|
|
|
super().__init__(info, version, True)
|
|
|
|
|
|
|
|
class StorageFormatV0(StorageFormat):
|
|
|
|
"""Storage format stability test cases for version 0 compatibility."""
|
|
|
|
|
|
|
|
def __init__(self, info: Information) -> None:
|
|
|
|
super().__init__(info, 0, False)
|
2021-03-10 15:03:44 +01:00
|
|
|
|
2021-06-29 15:29:24 +02:00
|
|
|
def all_keys_for_usage_flags(self) -> Iterator[StorageTestData]:
|
2021-06-24 10:04:38 +02:00
|
|
|
"""Generate test keys covering usage flags."""
|
2021-06-28 19:26:55 +02:00
|
|
|
yield from self.generate_keys_for_usage_flags(test_implicit_usage=True)
|
|
|
|
yield from self.generate_key_for_all_usage_flags()
|
2021-06-24 10:04:38 +02:00
|
|
|
|
2021-06-28 17:40:32 +02:00
|
|
|
def keys_for_implicit_usage(
|
2021-06-24 10:16:44 +02:00
|
|
|
self,
|
2021-06-28 16:54:11 +02:00
|
|
|
implyer_usage: str,
|
2021-06-24 10:16:44 +02:00
|
|
|
alg: str,
|
2021-06-28 20:02:11 +02:00
|
|
|
key_type: crypto_knowledge.KeyType
|
2021-06-29 15:29:24 +02:00
|
|
|
) -> StorageTestData:
|
2021-06-24 14:38:25 +02:00
|
|
|
# pylint: disable=too-many-locals
|
2021-06-28 16:27:29 +02:00
|
|
|
"""Generate test keys for the specified implicit usage flag,
|
2021-06-24 10:16:44 +02:00
|
|
|
algorithm and key type combination.
|
|
|
|
"""
|
2021-06-28 20:02:11 +02:00
|
|
|
bits = key_type.sizes_to_test()[0]
|
2021-06-28 16:54:11 +02:00
|
|
|
implicit_usage = StorageKey.IMPLICIT_USAGE_FLAGS[implyer_usage]
|
2021-06-28 16:35:48 +02:00
|
|
|
usage_flags = 'PSA_KEY_USAGE_EXPORT'
|
2021-06-28 16:54:11 +02:00
|
|
|
material_usage_flags = usage_flags + ' | ' + implyer_usage
|
|
|
|
expected_usage_flags = material_usage_flags + ' | ' + implicit_usage
|
2021-06-28 16:35:48 +02:00
|
|
|
alg2 = 0
|
2021-06-28 20:02:11 +02:00
|
|
|
key_material = key_type.key_material(bits)
|
2021-06-28 16:54:11 +02:00
|
|
|
usage_expression = re.sub(r'PSA_KEY_USAGE_', r'', implyer_usage)
|
2021-06-28 16:35:48 +02:00
|
|
|
alg_expression = re.sub(r'PSA_ALG_', r'', alg)
|
|
|
|
alg_expression = re.sub(r',', r', ', re.sub(r' +', r'', alg_expression))
|
|
|
|
key_type_expression = re.sub(r'\bPSA_(?:KEY_TYPE|ECC_FAMILY)_',
|
|
|
|
r'',
|
2021-06-28 20:02:11 +02:00
|
|
|
key_type.expression)
|
2021-06-28 17:40:32 +02:00
|
|
|
description = 'implied by {}: {} {} {}-bit'.format(
|
2021-06-28 16:35:48 +02:00
|
|
|
usage_expression, alg_expression, key_type_expression, bits)
|
2021-06-29 15:29:24 +02:00
|
|
|
key = StorageTestData(version=self.version,
|
|
|
|
id=1, lifetime=0x00000001,
|
|
|
|
type=key_type.expression, bits=bits,
|
|
|
|
usage=material_usage_flags,
|
|
|
|
expected_usage=expected_usage_flags,
|
|
|
|
without_implicit_usage=True,
|
|
|
|
alg=alg, alg2=alg2,
|
|
|
|
material=key_material,
|
|
|
|
description=description)
|
|
|
|
return key
|
2021-06-24 10:16:44 +02:00
|
|
|
|
|
|
|
def gather_key_types_for_sign_alg(self) -> Dict[str, List[str]]:
|
2021-06-24 14:38:25 +02:00
|
|
|
# pylint: disable=too-many-locals
|
2021-06-24 10:16:44 +02:00
|
|
|
"""Match possible key types for sign algorithms."""
|
|
|
|
# To create a valid combinaton both the algorithms and key types
|
|
|
|
# must be filtered. Pair them with keywords created from its names.
|
|
|
|
incompatible_alg_keyword = frozenset(['RAW', 'ANY', 'PURE'])
|
|
|
|
incompatible_key_type_keywords = frozenset(['MONTGOMERY'])
|
|
|
|
keyword_translation = {
|
|
|
|
'ECDSA': 'ECC',
|
|
|
|
'ED[0-9]*.*' : 'EDWARDS'
|
|
|
|
}
|
|
|
|
exclusive_keywords = {
|
|
|
|
'EDWARDS': 'ECC'
|
|
|
|
}
|
2021-06-24 14:38:25 +02:00
|
|
|
key_types = set(self.constructors.generate_expressions(self.constructors.key_types))
|
|
|
|
algorithms = set(self.constructors.generate_expressions(self.constructors.sign_algorithms))
|
2021-06-24 10:16:44 +02:00
|
|
|
alg_with_keys = {} #type: Dict[str, List[str]]
|
|
|
|
translation_table = str.maketrans('(', '_', ')')
|
|
|
|
for alg in algorithms:
|
|
|
|
# Generate keywords from the name of the algorithm
|
|
|
|
alg_keywords = set(alg.partition('(')[0].split(sep='_')[2:])
|
|
|
|
# Translate keywords for better matching with the key types
|
|
|
|
for keyword in alg_keywords.copy():
|
|
|
|
for pattern, replace in keyword_translation.items():
|
|
|
|
if re.match(pattern, keyword):
|
|
|
|
alg_keywords.remove(keyword)
|
|
|
|
alg_keywords.add(replace)
|
|
|
|
# Filter out incompatible algortihms
|
|
|
|
if not alg_keywords.isdisjoint(incompatible_alg_keyword):
|
|
|
|
continue
|
|
|
|
|
|
|
|
for key_type in key_types:
|
|
|
|
# Generate keywords from the of the key type
|
|
|
|
key_type_keywords = set(key_type.translate(translation_table).split(sep='_')[3:])
|
|
|
|
|
|
|
|
# Remove ambigious keywords
|
|
|
|
for keyword1, keyword2 in exclusive_keywords.items():
|
|
|
|
if keyword1 in key_type_keywords:
|
|
|
|
key_type_keywords.remove(keyword2)
|
|
|
|
|
|
|
|
if key_type_keywords.isdisjoint(incompatible_key_type_keywords) and\
|
|
|
|
not key_type_keywords.isdisjoint(alg_keywords):
|
|
|
|
if alg in alg_with_keys:
|
|
|
|
alg_with_keys[alg].append(key_type)
|
|
|
|
else:
|
|
|
|
alg_with_keys[alg] = [key_type]
|
|
|
|
return alg_with_keys
|
|
|
|
|
2021-06-29 15:29:24 +02:00
|
|
|
def all_keys_for_implicit_usage(self) -> Iterator[StorageTestData]:
|
2021-06-24 10:16:44 +02:00
|
|
|
"""Generate test keys for usage flag extensions."""
|
|
|
|
# Generate a key type and algorithm pair for each extendable usage
|
|
|
|
# flag to generate a valid key for exercising. The key is generated
|
|
|
|
# without usage extension to check the extension compatiblity.
|
|
|
|
alg_with_keys = self.gather_key_types_for_sign_alg()
|
2021-06-24 16:35:01 +02:00
|
|
|
|
2021-06-28 19:26:55 +02:00
|
|
|
for usage in sorted(StorageKey.IMPLICIT_USAGE_FLAGS, key=str):
|
|
|
|
for alg in sorted(alg_with_keys):
|
|
|
|
for key_type in sorted(alg_with_keys[alg]):
|
|
|
|
# The key types must be filtered to fit the specific usage flag.
|
2021-06-28 20:02:11 +02:00
|
|
|
kt = crypto_knowledge.KeyType(key_type)
|
|
|
|
if kt.is_valid_for_signature(usage):
|
|
|
|
yield self.keys_for_implicit_usage(usage, alg, kt)
|
2021-06-24 10:16:44 +02:00
|
|
|
|
2021-06-29 15:42:57 +02:00
|
|
|
def generate_all_keys(self) -> Iterator[StorageTestData]:
|
|
|
|
yield from super().generate_all_keys()
|
|
|
|
yield from self.all_keys_for_implicit_usage()
|
2021-06-24 10:04:38 +02:00
|
|
|
|
2021-03-10 02:12:08 +01:00
|
|
|
class TestGenerator:
|
|
|
|
"""Generate test data."""
|
|
|
|
|
|
|
|
def __init__(self, options) -> None:
|
|
|
|
self.test_suite_directory = self.get_option(options, 'directory',
|
|
|
|
'tests/suites')
|
|
|
|
self.info = Information()
|
|
|
|
|
|
|
|
@staticmethod
|
|
|
|
def get_option(options, name: str, default: T) -> T:
|
|
|
|
value = getattr(options, name, None)
|
|
|
|
return default if value is None else value
|
|
|
|
|
2021-03-10 02:34:37 +01:00
|
|
|
def filename_for(self, basename: str) -> str:
|
|
|
|
"""The location of the data file with the specified base name."""
|
|
|
|
return os.path.join(self.test_suite_directory, basename + '.data')
|
|
|
|
|
2021-03-10 02:12:08 +01:00
|
|
|
def write_test_data_file(self, basename: str,
|
|
|
|
test_cases: Iterable[test_case.TestCase]) -> None:
|
|
|
|
"""Write the test cases to a .data file.
|
|
|
|
|
|
|
|
The output file is ``basename + '.data'`` in the test suite directory.
|
|
|
|
"""
|
2021-03-10 02:34:37 +01:00
|
|
|
filename = self.filename_for(basename)
|
2021-03-10 02:12:08 +01:00
|
|
|
test_case.write_data_file(filename, test_cases)
|
|
|
|
|
2021-03-10 02:34:37 +01:00
|
|
|
TARGETS = {
|
|
|
|
'test_suite_psa_crypto_not_supported.generated':
|
2021-02-17 15:11:05 +01:00
|
|
|
lambda info: NotSupported(info).test_cases_for_not_supported(),
|
2021-03-10 15:03:44 +01:00
|
|
|
'test_suite_psa_crypto_storage_format.current':
|
2021-06-24 09:53:26 +02:00
|
|
|
lambda info: StorageFormatForward(info, 0).all_test_cases(),
|
2021-03-10 15:03:44 +01:00
|
|
|
'test_suite_psa_crypto_storage_format.v0':
|
2021-06-24 09:53:26 +02:00
|
|
|
lambda info: StorageFormatV0(info).all_test_cases(),
|
2021-03-10 02:34:37 +01:00
|
|
|
} #type: Dict[str, Callable[[Information], Iterable[test_case.TestCase]]]
|
|
|
|
|
|
|
|
def generate_target(self, name: str) -> None:
|
|
|
|
test_cases = self.TARGETS[name](self.info)
|
|
|
|
self.write_test_data_file(name, test_cases)
|
2021-01-26 22:19:21 +01:00
|
|
|
|
2021-01-26 22:16:30 +01:00
|
|
|
def main(args):
|
|
|
|
"""Command line entry point."""
|
|
|
|
parser = argparse.ArgumentParser(description=__doc__)
|
2021-03-10 02:34:37 +01:00
|
|
|
parser.add_argument('--list', action='store_true',
|
|
|
|
help='List available targets and exit')
|
|
|
|
parser.add_argument('targets', nargs='*', metavar='TARGET',
|
|
|
|
help='Target file to generate (default: all; "-": none)')
|
2021-01-26 22:16:30 +01:00
|
|
|
options = parser.parse_args(args)
|
|
|
|
generator = TestGenerator(options)
|
2021-03-10 02:34:37 +01:00
|
|
|
if options.list:
|
|
|
|
for name in sorted(generator.TARGETS):
|
|
|
|
print(generator.filename_for(name))
|
|
|
|
return
|
|
|
|
if options.targets:
|
|
|
|
# Allow "-" as a special case so you can run
|
|
|
|
# ``generate_psa_tests.py - $targets`` and it works uniformly whether
|
|
|
|
# ``$targets`` is empty or not.
|
|
|
|
options.targets = [os.path.basename(re.sub(r'\.data\Z', r'', target))
|
|
|
|
for target in options.targets
|
|
|
|
if target != '-']
|
|
|
|
else:
|
|
|
|
options.targets = sorted(generator.TARGETS)
|
|
|
|
for target in options.targets:
|
|
|
|
generator.generate_target(target)
|
2021-01-26 22:16:30 +01:00
|
|
|
|
|
|
|
if __name__ == '__main__':
|
|
|
|
main(sys.argv[1:])
|