blob: 230bbd8fcae1baf466eb229212f680f9247bcb2f [file] [log] [blame]
Gilles Peskine09940492021-01-26 22:16:30 +01001#!/usr/bin/env python3
2"""Generate test data for PSA cryptographic mechanisms.
3"""
4
5# Copyright The Mbed TLS Contributors
6# SPDX-License-Identifier: Apache-2.0
7#
8# Licensed under the Apache License, Version 2.0 (the "License"); you may
9# not use this file except in compliance with the License.
10# You may obtain a copy of the License at
11#
12# http://www.apache.org/licenses/LICENSE-2.0
13#
14# Unless required by applicable law or agreed to in writing, software
15# distributed under the License is distributed on an "AS IS" BASIS, WITHOUT
16# WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
17# See the License for the specific language governing permissions and
18# limitations under the License.
19
20import argparse
Gilles Peskine14e428f2021-01-26 22:19:21 +010021import os
22import re
Gilles Peskine09940492021-01-26 22:16:30 +010023import sys
Gilles Peskine14e428f2021-01-26 22:19:21 +010024from typing import Iterable, List, TypeVar
Gilles Peskine09940492021-01-26 22:16:30 +010025
26import scripts_path # pylint: disable=unused-import
Gilles Peskine14e428f2021-01-26 22:19:21 +010027from mbedtls_dev import crypto_knowledge
Gilles Peskine09940492021-01-26 22:16:30 +010028from mbedtls_dev import macro_collector
Gilles Peskine14e428f2021-01-26 22:19:21 +010029from mbedtls_dev import test_case
Gilles Peskine09940492021-01-26 22:16:30 +010030
31T = TypeVar('T') #pylint: disable=invalid-name
32
Gilles Peskine14e428f2021-01-26 22:19:21 +010033
34def test_case_for_key_type_not_supported(verb: str, key_type: str, bits: int,
35 dependencies: List[str],
36 *args: str) -> test_case.TestCase:
37 """Return one test case exercising a key creation method
38 for an unsupported key type or size.
39 """
40 tc = test_case.TestCase()
41 adverb = 'not' if dependencies else 'never'
42 tc.set_description('PSA {} {} {}-bit {} supported'
43 .format(verb, key_type, bits, adverb))
44 tc.set_dependencies(dependencies)
45 tc.set_function(verb + '_not_supported')
46 tc.set_arguments([key_type] + list(args))
47 return tc
48
Gilles Peskine09940492021-01-26 22:16:30 +010049class TestGenerator:
50 """Gather information and generate test data."""
51
52 def __init__(self, options):
53 self.test_suite_directory = self.get_option(options, 'directory',
54 'tests/suites')
55 self.constructors = self.read_psa_interface()
56
57 @staticmethod
58 def get_option(options, name: str, default: T) -> T:
59 value = getattr(options, name, None)
60 return default if value is None else value
61
62 @staticmethod
63 def remove_unwanted_macros(
64 constructors: macro_collector.PSAMacroCollector
65 ) -> None:
66 # Mbed TLS doesn't support DSA. Don't attempt to generate any related
67 # test case.
68 constructors.key_types.discard('PSA_KEY_TYPE_DSA_KEY_PAIR')
69 constructors.key_types.discard('PSA_KEY_TYPE_DSA_PUBLIC_KEY')
70 constructors.algorithms_from_hash.pop('PSA_ALG_DSA', None)
71 constructors.algorithms_from_hash.pop('PSA_ALG_DETERMINISTIC_DSA', None)
72
73 def read_psa_interface(self) -> macro_collector.PSAMacroCollector:
74 """Return the list of known key types, algorithms, etc."""
75 constructors = macro_collector.PSAMacroCollector()
76 header_file_names = ['include/psa/crypto_values.h',
77 'include/psa/crypto_extra.h']
78 for header_file_name in header_file_names:
79 with open(header_file_name, 'rb') as header_file:
80 constructors.read_file(header_file)
81 self.remove_unwanted_macros(constructors)
82 return constructors
83
Gilles Peskine14e428f2021-01-26 22:19:21 +010084 def write_test_data_file(self, basename: str,
85 test_cases: Iterable[test_case.TestCase]) -> None:
86 """Write the test cases to a .data file.
87
88 The output file is ``basename + '.data'`` in the test suite directory.
89 """
90 filename = os.path.join(self.test_suite_directory, basename + '.data')
91 test_case.write_data_file(filename, test_cases)
92
93 @staticmethod
94 def test_cases_for_key_type_not_supported(
95 kt: crypto_knowledge.KeyType
96 ) -> List[test_case.TestCase]:
97 """Return test cases exercising key creation when the given type is unsupported."""
98 if kt.name == 'PSA_KEY_TYPE_RAW_DATA':
99 # This key type is always supported.
100 return []
101 want_symbol = re.sub(r'\APSA_', r'PSA_WANT_', kt.name)
102 import_dependencies = ['!' + want_symbol]
103 if kt.name.endswith('_PUBLIC_KEY'):
104 generate_dependencies = []
105 else:
106 generate_dependencies = import_dependencies
107 test_cases = []
108 for bits in kt.sizes_to_test():
109 test_cases.append(test_case_for_key_type_not_supported(
110 'import', kt.name, bits, import_dependencies,
111 test_case.hex_string(kt.key_material(bits))
112 ))
113 test_cases.append(test_case_for_key_type_not_supported(
114 'generate', kt.name, bits, generate_dependencies,
115 str(bits)
116 ))
117 # To be added: derive
118 return test_cases
119
120 def generate_not_supported(self) -> None:
121 """Generate test cases that exercise the creation of keys of unsupported types."""
122 test_cases = []
123 for key_type in sorted(self.constructors.key_types):
124 kt = crypto_knowledge.KeyType(key_type)
125 test_cases += self.test_cases_for_key_type_not_supported(kt)
126 # To be added: parametrized key types (ECC, FFDH)
127 self.write_test_data_file(
128 'test_suite_psa_crypto_not_supported.generated',
129 test_cases)
130
131 def generate_all(self):
132 self.generate_not_supported()
133
Gilles Peskine09940492021-01-26 22:16:30 +0100134def main(args):
135 """Command line entry point."""
136 parser = argparse.ArgumentParser(description=__doc__)
137 options = parser.parse_args(args)
138 generator = TestGenerator(options)
Gilles Peskine14e428f2021-01-26 22:19:21 +0100139 generator.generate_all()
Gilles Peskine09940492021-01-26 22:16:30 +0100140
141if __name__ == '__main__':
142 main(sys.argv[1:])