blob: 656fcd8881fc1e9fd757d38ccf9a8978f661016b [file] [log] [blame]
Gilles Peskine8519dc92024-01-04 16:38:17 +01001#!/usr/bin/env python3
2"""Generate wrapper functions for PSA function calls.
3"""
4
5# Copyright The Mbed TLS Contributors
6# SPDX-License-Identifier: Apache-2.0 OR GPL-2.0-or-later
7
8import argparse
Gilles Peskinec8b22d02023-12-06 19:32:52 +01009import itertools
Gilles Peskine8519dc92024-01-04 16:38:17 +010010import os
Gilles Peskinec8b22d02023-12-06 19:32:52 +010011from typing import Iterator, List, Optional, Tuple
Gilles Peskine8519dc92024-01-04 16:38:17 +010012
13import scripts_path #pylint: disable=unused-import
14from mbedtls_dev import build_tree
15from mbedtls_dev import c_parsing_helper
16from mbedtls_dev import c_wrapper_generator
17from mbedtls_dev import typing_util
18
19
Gilles Peskinec8b22d02023-12-06 19:32:52 +010020class BufferParameter:
21 """Description of an input or output buffer parameter sequence to a PSA function."""
22 #pylint: disable=too-few-public-methods
23
24 def __init__(self, i: int, is_output: bool,
25 buffer_name: str, size_name: str) -> None:
26 """Initialize the parameter information.
27
28 i is the index of the function argument that is the pointer to the buffer.
29 The size is argument i+1. For a variable-size output, the actual length
30 goes in argument i+2.
31
32 buffer_name and size_names are the names of arguments i and i+1.
33 This class does not yet help with the output length.
34 """
35 self.index = i
36 self.buffer_name = buffer_name
37 self.size_name = size_name
38 self.is_output = is_output
39
40
Gilles Peskine8519dc92024-01-04 16:38:17 +010041class PSAWrapperGenerator(c_wrapper_generator.Base):
42 """Generate a C source file containing wrapper functions for PSA Crypto API calls."""
43
44 _CPP_GUARDS = 'defined(MBEDTLS_PSA_CRYPTO_C) && defined(MBEDTLS_TEST_HOOKS)'
45 _WRAPPER_NAME_PREFIX = 'mbedtls_test_wrap_'
46 _WRAPPER_NAME_SUFFIX = ''
47
48 def gather_data(self) -> None:
49 root_dir = build_tree.guess_mbedtls_root()
50 for header_name in ['crypto.h', 'crypto_extra.h']:
51 header_path = os.path.join(root_dir, 'include', 'psa', header_name)
52 c_parsing_helper.read_function_declarations(self.functions, header_path)
53
54 _SKIP_FUNCTIONS = frozenset([
55 'mbedtls_psa_external_get_random', # not a library function
Gilles Peskine17a14f12024-01-04 16:41:30 +010056 'psa_aead_abort', # not implemented yet
57 'psa_aead_decrypt_setup', # not implemented yet
58 'psa_aead_encrypt_setup', # not implemented yet
59 'psa_aead_finish', # not implemented yet
60 'psa_aead_generate_nonce', # not implemented yet
61 'psa_aead_set_lengths', # not implemented yet
62 'psa_aead_set_nonce', # not implemented yet
63 'psa_aead_update', # not implemented yet
64 'psa_aead_update_ad', # not implemented yet
65 'psa_aead_verify', # not implemented yet
Gilles Peskine8519dc92024-01-04 16:38:17 +010066 'psa_get_key_domain_parameters', # client-side function
67 'psa_get_key_slot_number', # client-side function
Gilles Peskine8519dc92024-01-04 16:38:17 +010068 'psa_set_key_domain_parameters', # client-side function
69 ])
70
71 def _skip_function(self, function: c_wrapper_generator.FunctionInfo) -> bool:
72 if function.return_type != 'psa_status_t':
73 return True
74 if function.name in self._SKIP_FUNCTIONS:
75 return True
76 return False
77
78 # PAKE stuff: not implemented yet
79 _PAKE_STUFF = frozenset([
80 'psa_crypto_driver_pake_inputs_t *',
81 'psa_pake_cipher_suite_t *',
82 ])
83
84 def _return_variable_name(self,
85 function: c_wrapper_generator.FunctionInfo) -> str:
86 """The name of the variable that will contain the return value."""
87 if function.return_type == 'psa_status_t':
88 return 'status'
89 return super()._return_variable_name(function)
90
91 _FUNCTION_GUARDS = c_wrapper_generator.Base._FUNCTION_GUARDS.copy() \
92 #pylint: disable=protected-access
93 _FUNCTION_GUARDS.update({
94 'mbedtls_psa_register_se_key': 'defined(MBEDTLS_PSA_CRYPTO_SE_C)',
95 'mbedtls_psa_inject_entropy': 'defined(MBEDTLS_PSA_INJECT_ENTROPY)',
96 'mbedtls_psa_external_get_random': 'defined(MBEDTLS_PSA_CRYPTO_EXTERNAL_RNG)',
97 'mbedtls_psa_platform_get_builtin_key': 'defined(MBEDTLS_PSA_CRYPTO_BUILTIN_KEYS)',
98 })
99
Gilles Peskinec8b22d02023-12-06 19:32:52 +0100100 @staticmethod
101 def _detect_buffer_parameters(arguments: List[c_parsing_helper.ArgumentInfo],
102 argument_names: List[str]) -> Iterator[BufferParameter]:
103 """Detect function arguments that are buffers (pointer, size [,length])."""
104 types = ['' if arg.suffix else arg.type for arg in arguments]
105 # pairs = list of (type_of_arg_N, type_of_arg_N+1)
106 # where each type_of_arg_X is the empty string if the type is an array
107 # or there is no argument X.
108 pairs = enumerate(itertools.zip_longest(types, types[1:], fillvalue=''))
109 for i, t01 in pairs:
110 if (t01[0] == 'const uint8_t *' or t01[0] == 'uint8_t *') and \
111 t01[1] == 'size_t':
112 yield BufferParameter(i, not t01[0].startswith('const '),
113 argument_names[i], argument_names[i+1])
114
115 @staticmethod
116 def _write_poison_buffer_parameter(out: typing_util.Writable,
117 param: BufferParameter,
118 poison: bool) -> None:
119 """Write poisoning or unpoisoning code for a buffer parameter.
120
121 Write poisoning code if poison is true, unpoisoning code otherwise.
122 """
123 out.write(' MBEDTLS_TEST_MEMORY_{}({}, {});\n'.format(
124 'POISON' if poison else 'UNPOISON',
125 param.buffer_name, param.size_name
126 ))
127
128 @staticmethod
129 def _parameter_should_be_copied(function_name: str,
130 _buffer_name: Optional[str]) -> bool:
131 """Whether the specified buffer argument to a PSA function should be copied.
132 """
133 # Proof-of-concept: just instrument one function for now
134 if function_name == 'psa_cipher_encrypt':
135 return True
136 return False
137
138 def _write_function_call(self, out: typing_util.Writable,
139 function: c_wrapper_generator.FunctionInfo,
140 argument_names: List[str]) -> None:
141 buffer_parameters = list(
142 param
143 for param in self._detect_buffer_parameters(function.arguments,
144 argument_names)
145 if self._parameter_should_be_copied(function.name,
146 function.arguments[param.index].name))
147 for param in buffer_parameters:
148 self._write_poison_buffer_parameter(out, param, True)
149 super()._write_function_call(out, function, argument_names)
150 for param in buffer_parameters:
151 self._write_poison_buffer_parameter(out, param, False)
152
Gilles Peskine8519dc92024-01-04 16:38:17 +0100153 def _write_prologue(self, out: typing_util.Writable, header: bool) -> None:
154 super()._write_prologue(out, header)
155 out.write("""
156#if {}
157
158#include <psa/crypto.h>
159
Gilles Peskinec8b22d02023-12-06 19:32:52 +0100160#include <test/memory.h>
Gilles Peskine8519dc92024-01-04 16:38:17 +0100161#include <test/psa_crypto_helpers.h>
162#include <test/psa_test_wrappers.h>
163"""
164 .format(self._CPP_GUARDS))
165
166 def _write_epilogue(self, out: typing_util.Writable, header: bool) -> None:
167 out.write("""
168#endif /* {} */
169"""
170 .format(self._CPP_GUARDS))
171 super()._write_epilogue(out, header)
172
173
174class PSALoggingWrapperGenerator(PSAWrapperGenerator, c_wrapper_generator.Logging):
175 """Generate a C source file containing wrapper functions that log PSA Crypto API calls."""
176
177 def __init__(self, stream: str) -> None:
178 super().__init__()
179 self.set_stream(stream)
180
181 _PRINTF_TYPE_CAST = c_wrapper_generator.Logging._PRINTF_TYPE_CAST.copy()
182 _PRINTF_TYPE_CAST.update({
183 'mbedtls_svc_key_id_t': 'unsigned',
184 'psa_algorithm_t': 'unsigned',
185 'psa_drv_slot_number_t': 'unsigned long long',
186 'psa_key_derivation_step_t': 'int',
187 'psa_key_id_t': 'unsigned',
188 'psa_key_slot_number_t': 'unsigned long long',
189 'psa_key_lifetime_t': 'unsigned',
190 'psa_key_type_t': 'unsigned',
191 'psa_key_usage_flags_t': 'unsigned',
192 'psa_pake_role_t': 'int',
193 'psa_pake_step_t': 'int',
194 'psa_status_t': 'int',
195 })
196
197 def _printf_parameters(self, typ: str, var: str) -> Tuple[str, List[str]]:
198 if typ.startswith('const '):
199 typ = typ[6:]
200 if typ == 'uint8_t *':
201 # Skip buffers
202 return '', []
203 if typ.endswith('operation_t *'):
204 return '', []
205 if typ in self._PAKE_STUFF:
206 return '', []
207 if typ == 'psa_key_attributes_t *':
208 return (var + '={id=%u, lifetime=0x%08x, type=0x%08x, bits=%u, alg=%08x, usage=%08x}',
209 ['(unsigned) psa_get_key_{}({})'.format(field, var)
210 for field in ['id', 'lifetime', 'type', 'bits', 'algorithm', 'usage_flags']])
211 return super()._printf_parameters(typ, var)
212
213
214DEFAULT_C_OUTPUT_FILE_NAME = 'tests/src/psa_test_wrappers.c'
215DEFAULT_H_OUTPUT_FILE_NAME = 'tests/include/test/psa_test_wrappers.h'
216
217def main() -> None:
218 parser = argparse.ArgumentParser(description=globals()['__doc__'])
219 parser.add_argument('--log',
220 help='Stream to log to (default: no logging code)')
221 parser.add_argument('--output-c',
222 metavar='FILENAME',
223 default=DEFAULT_C_OUTPUT_FILE_NAME,
224 help=('Output .c file path (default: {}; skip .c output if empty)'
225 .format(DEFAULT_C_OUTPUT_FILE_NAME)))
226 parser.add_argument('--output-h',
227 metavar='FILENAME',
228 default=DEFAULT_H_OUTPUT_FILE_NAME,
229 help=('Output .h file path (default: {}; skip .h output if empty)'
230 .format(DEFAULT_H_OUTPUT_FILE_NAME)))
231 options = parser.parse_args()
232 if options.log:
233 generator = PSALoggingWrapperGenerator(options.log) #type: PSAWrapperGenerator
234 else:
235 generator = PSAWrapperGenerator()
236 generator.gather_data()
237 if options.output_h:
238 generator.write_h_file(options.output_h)
239 if options.output_c:
240 generator.write_c_file(options.output_c)
241
242if __name__ == '__main__':
243 main()