blob: 31f0dadc437c60c202a37cbad78f090e6c9bf7a1 [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
Gilles Peskine7c7b7d52024-01-04 17:28:59 +01008### WARNING: the code in this file has not been extensively reviewed yet.
9### We do not think it is harmful, but it may be below our normal standards
10### for robustness and maintainability.
11
Gilles Peskine8519dc92024-01-04 16:38:17 +010012import argparse
Gilles Peskinec8b22d02023-12-06 19:32:52 +010013import itertools
Gilles Peskine8519dc92024-01-04 16:38:17 +010014import os
Gilles Peskinec8b22d02023-12-06 19:32:52 +010015from typing import Iterator, List, Optional, Tuple
Gilles Peskine8519dc92024-01-04 16:38:17 +010016
17import scripts_path #pylint: disable=unused-import
18from mbedtls_dev import build_tree
19from mbedtls_dev import c_parsing_helper
20from mbedtls_dev import c_wrapper_generator
21from mbedtls_dev import typing_util
22
23
Gilles Peskinec8b22d02023-12-06 19:32:52 +010024class BufferParameter:
25 """Description of an input or output buffer parameter sequence to a PSA function."""
26 #pylint: disable=too-few-public-methods
27
28 def __init__(self, i: int, is_output: bool,
29 buffer_name: str, size_name: str) -> None:
30 """Initialize the parameter information.
31
32 i is the index of the function argument that is the pointer to the buffer.
33 The size is argument i+1. For a variable-size output, the actual length
34 goes in argument i+2.
35
36 buffer_name and size_names are the names of arguments i and i+1.
37 This class does not yet help with the output length.
38 """
39 self.index = i
40 self.buffer_name = buffer_name
41 self.size_name = size_name
42 self.is_output = is_output
43
44
Gilles Peskine8519dc92024-01-04 16:38:17 +010045class PSAWrapperGenerator(c_wrapper_generator.Base):
46 """Generate a C source file containing wrapper functions for PSA Crypto API calls."""
47
Gilles Peskinea980aa02024-01-04 20:51:38 +010048 _CPP_GUARDS = ('defined(MBEDTLS_PSA_CRYPTO_C) && ' +
49 'defined(MBEDTLS_TEST_HOOKS) && \\\n ' +
50 '!defined(RECORD_PSA_STATUS_COVERAGE_LOG)')
Gilles Peskine8519dc92024-01-04 16:38:17 +010051 _WRAPPER_NAME_PREFIX = 'mbedtls_test_wrap_'
52 _WRAPPER_NAME_SUFFIX = ''
53
54 def gather_data(self) -> None:
55 root_dir = build_tree.guess_mbedtls_root()
56 for header_name in ['crypto.h', 'crypto_extra.h']:
57 header_path = os.path.join(root_dir, 'include', 'psa', header_name)
58 c_parsing_helper.read_function_declarations(self.functions, header_path)
59
60 _SKIP_FUNCTIONS = frozenset([
61 'mbedtls_psa_external_get_random', # not a library function
Gilles Peskine17a14f12024-01-04 16:41:30 +010062 'psa_aead_abort', # not implemented yet
63 'psa_aead_decrypt_setup', # not implemented yet
64 'psa_aead_encrypt_setup', # not implemented yet
65 'psa_aead_finish', # not implemented yet
66 'psa_aead_generate_nonce', # not implemented yet
67 'psa_aead_set_lengths', # not implemented yet
68 'psa_aead_set_nonce', # not implemented yet
69 'psa_aead_update', # not implemented yet
70 'psa_aead_update_ad', # not implemented yet
71 'psa_aead_verify', # not implemented yet
Gilles Peskine8519dc92024-01-04 16:38:17 +010072 'psa_get_key_domain_parameters', # client-side function
73 'psa_get_key_slot_number', # client-side function
Gilles Peskine8519dc92024-01-04 16:38:17 +010074 'psa_set_key_domain_parameters', # client-side function
75 ])
76
77 def _skip_function(self, function: c_wrapper_generator.FunctionInfo) -> bool:
78 if function.return_type != 'psa_status_t':
79 return True
80 if function.name in self._SKIP_FUNCTIONS:
81 return True
82 return False
83
84 # PAKE stuff: not implemented yet
85 _PAKE_STUFF = frozenset([
86 'psa_crypto_driver_pake_inputs_t *',
87 'psa_pake_cipher_suite_t *',
88 ])
89
90 def _return_variable_name(self,
91 function: c_wrapper_generator.FunctionInfo) -> str:
92 """The name of the variable that will contain the return value."""
93 if function.return_type == 'psa_status_t':
94 return 'status'
95 return super()._return_variable_name(function)
96
97 _FUNCTION_GUARDS = c_wrapper_generator.Base._FUNCTION_GUARDS.copy() \
98 #pylint: disable=protected-access
99 _FUNCTION_GUARDS.update({
100 'mbedtls_psa_register_se_key': 'defined(MBEDTLS_PSA_CRYPTO_SE_C)',
101 'mbedtls_psa_inject_entropy': 'defined(MBEDTLS_PSA_INJECT_ENTROPY)',
102 'mbedtls_psa_external_get_random': 'defined(MBEDTLS_PSA_CRYPTO_EXTERNAL_RNG)',
103 'mbedtls_psa_platform_get_builtin_key': 'defined(MBEDTLS_PSA_CRYPTO_BUILTIN_KEYS)',
104 })
105
Gilles Peskinec8b22d02023-12-06 19:32:52 +0100106 @staticmethod
107 def _detect_buffer_parameters(arguments: List[c_parsing_helper.ArgumentInfo],
108 argument_names: List[str]) -> Iterator[BufferParameter]:
109 """Detect function arguments that are buffers (pointer, size [,length])."""
110 types = ['' if arg.suffix else arg.type for arg in arguments]
111 # pairs = list of (type_of_arg_N, type_of_arg_N+1)
112 # where each type_of_arg_X is the empty string if the type is an array
113 # or there is no argument X.
114 pairs = enumerate(itertools.zip_longest(types, types[1:], fillvalue=''))
115 for i, t01 in pairs:
116 if (t01[0] == 'const uint8_t *' or t01[0] == 'uint8_t *') and \
117 t01[1] == 'size_t':
118 yield BufferParameter(i, not t01[0].startswith('const '),
119 argument_names[i], argument_names[i+1])
120
121 @staticmethod
122 def _write_poison_buffer_parameter(out: typing_util.Writable,
123 param: BufferParameter,
124 poison: bool) -> None:
125 """Write poisoning or unpoisoning code for a buffer parameter.
126
127 Write poisoning code if poison is true, unpoisoning code otherwise.
128 """
129 out.write(' MBEDTLS_TEST_MEMORY_{}({}, {});\n'.format(
130 'POISON' if poison else 'UNPOISON',
131 param.buffer_name, param.size_name
132 ))
133
Gilles Peskineb3d457c2024-01-04 20:33:29 +0100134 def _write_poison_buffer_parameters(self, out: typing_util.Writable,
135 buffer_parameters: List[BufferParameter],
136 poison: bool) -> None:
137 """Write poisoning or unpoisoning code for the buffer parameters.
138
139 Write poisoning code if poison is true, unpoisoning code otherwise.
140 """
141 if not buffer_parameters:
142 return
143 out.write('#if defined(MBEDTLS_PSA_COPY_CALLER_BUFFERS)\n')
144 for param in buffer_parameters:
145 self._write_poison_buffer_parameter(out, param, poison)
146 out.write('#endif /* defined(MBEDTLS_PSA_COPY_CALLER_BUFFERS) */\n')
147
Gilles Peskinec8b22d02023-12-06 19:32:52 +0100148 @staticmethod
149 def _parameter_should_be_copied(function_name: str,
150 _buffer_name: Optional[str]) -> bool:
151 """Whether the specified buffer argument to a PSA function should be copied.
152 """
Thomas Daubneybe060f12024-02-26 13:55:42 +0000153 #pylint: disable=too-many-return-statements
David Horstmann436b2ef2024-01-22 14:36:01 +0000154 if function_name.startswith('psa_aead'):
155 return True
Gabor Mezei143864c2024-01-24 16:58:40 +0100156 if function_name in {'psa_cipher_encrypt', 'psa_cipher_decrypt',
Gabor Mezei50bcca22024-02-01 10:39:56 +0100157 'psa_cipher_update', 'psa_cipher_finish',
158 'psa_cipher_generate_iv', 'psa_cipher_set_iv'}:
Ryan Everett810421c2024-01-25 12:09:09 +0000159 return True
Ryan Everett6c9e69d2024-02-09 16:23:25 +0000160 if function_name in ('psa_key_derivation_output_bytes',
161 'psa_key_derivation_input_bytes'):
162 return True
Ryan Everettc8b6c052024-01-25 15:20:09 +0000163 if function_name in ('psa_import_key',
164 'psa_export_key',
165 'psa_export_public_key'):
Gilles Peskinec8b22d02023-12-06 19:32:52 +0100166 return True
Thomas Daubneyc63e31a2024-01-30 13:33:14 +0000167 if function_name in ('psa_sign_message',
168 'psa_verify_message',
169 'psa_sign_hash',
170 'psa_verify_hash'):
171 return True
Thomas Daubneyebf93292024-01-25 17:09:10 +0000172 if function_name in ('psa_hash_update',
173 'psa_hash_finish',
174 'psa_hash_verify',
175 'psa_hash_compute',
176 'psa_hash_compare'):
177 return True
Thomas Daubneydb5d6072024-02-15 14:18:02 +0000178 if function_name in ('psa_key_derivation_key_agreement',
179 'psa_raw_key_agreement'):
180 return True
David Horstmann4e821502024-02-06 15:44:08 +0000181 if function_name == 'psa_generate_random':
Gilles Peskinec8b22d02023-12-06 19:32:52 +0100182 return True
Thomas Daubney6b915032024-01-30 12:07:38 +0000183 if function_name in ('psa_mac_update',
184 'psa_mac_sign_finish',
185 'psa_mac_verify_finish',
186 'psa_mac_compute',
187 'psa_mac_verify'):
188 return True
Thomas Daubneyd8adccf2024-01-30 14:41:05 +0000189 if function_name in ('psa_asymmetric_encrypt',
Thomas Daubney2b614f92024-01-31 16:57:30 +0000190 'psa_asymmetric_decrypt'):
Thomas Daubneyd8adccf2024-01-30 14:41:05 +0000191 return True
Gilles Peskinec8b22d02023-12-06 19:32:52 +0100192 return False
193
194 def _write_function_call(self, out: typing_util.Writable,
195 function: c_wrapper_generator.FunctionInfo,
196 argument_names: List[str]) -> None:
197 buffer_parameters = list(
198 param
199 for param in self._detect_buffer_parameters(function.arguments,
200 argument_names)
201 if self._parameter_should_be_copied(function.name,
202 function.arguments[param.index].name))
Gilles Peskineb3d457c2024-01-04 20:33:29 +0100203 self._write_poison_buffer_parameters(out, buffer_parameters, True)
Gilles Peskinec8b22d02023-12-06 19:32:52 +0100204 super()._write_function_call(out, function, argument_names)
Gilles Peskineb3d457c2024-01-04 20:33:29 +0100205 self._write_poison_buffer_parameters(out, buffer_parameters, False)
Gilles Peskinec8b22d02023-12-06 19:32:52 +0100206
Gilles Peskine8519dc92024-01-04 16:38:17 +0100207 def _write_prologue(self, out: typing_util.Writable, header: bool) -> None:
208 super()._write_prologue(out, header)
209 out.write("""
210#if {}
211
212#include <psa/crypto.h>
213
Gilles Peskinec8b22d02023-12-06 19:32:52 +0100214#include <test/memory.h>
Gilles Peskine8519dc92024-01-04 16:38:17 +0100215#include <test/psa_crypto_helpers.h>
216#include <test/psa_test_wrappers.h>
217"""
218 .format(self._CPP_GUARDS))
219
220 def _write_epilogue(self, out: typing_util.Writable, header: bool) -> None:
221 out.write("""
222#endif /* {} */
223"""
224 .format(self._CPP_GUARDS))
225 super()._write_epilogue(out, header)
226
227
228class PSALoggingWrapperGenerator(PSAWrapperGenerator, c_wrapper_generator.Logging):
229 """Generate a C source file containing wrapper functions that log PSA Crypto API calls."""
230
231 def __init__(self, stream: str) -> None:
232 super().__init__()
233 self.set_stream(stream)
234
235 _PRINTF_TYPE_CAST = c_wrapper_generator.Logging._PRINTF_TYPE_CAST.copy()
236 _PRINTF_TYPE_CAST.update({
237 'mbedtls_svc_key_id_t': 'unsigned',
238 'psa_algorithm_t': 'unsigned',
239 'psa_drv_slot_number_t': 'unsigned long long',
240 'psa_key_derivation_step_t': 'int',
241 'psa_key_id_t': 'unsigned',
242 'psa_key_slot_number_t': 'unsigned long long',
243 'psa_key_lifetime_t': 'unsigned',
244 'psa_key_type_t': 'unsigned',
245 'psa_key_usage_flags_t': 'unsigned',
246 'psa_pake_role_t': 'int',
247 'psa_pake_step_t': 'int',
248 'psa_status_t': 'int',
249 })
250
251 def _printf_parameters(self, typ: str, var: str) -> Tuple[str, List[str]]:
252 if typ.startswith('const '):
253 typ = typ[6:]
254 if typ == 'uint8_t *':
255 # Skip buffers
256 return '', []
257 if typ.endswith('operation_t *'):
258 return '', []
259 if typ in self._PAKE_STUFF:
260 return '', []
261 if typ == 'psa_key_attributes_t *':
262 return (var + '={id=%u, lifetime=0x%08x, type=0x%08x, bits=%u, alg=%08x, usage=%08x}',
263 ['(unsigned) psa_get_key_{}({})'.format(field, var)
264 for field in ['id', 'lifetime', 'type', 'bits', 'algorithm', 'usage_flags']])
265 return super()._printf_parameters(typ, var)
266
267
268DEFAULT_C_OUTPUT_FILE_NAME = 'tests/src/psa_test_wrappers.c'
269DEFAULT_H_OUTPUT_FILE_NAME = 'tests/include/test/psa_test_wrappers.h'
270
271def main() -> None:
272 parser = argparse.ArgumentParser(description=globals()['__doc__'])
273 parser.add_argument('--log',
274 help='Stream to log to (default: no logging code)')
275 parser.add_argument('--output-c',
276 metavar='FILENAME',
277 default=DEFAULT_C_OUTPUT_FILE_NAME,
278 help=('Output .c file path (default: {}; skip .c output if empty)'
279 .format(DEFAULT_C_OUTPUT_FILE_NAME)))
280 parser.add_argument('--output-h',
281 metavar='FILENAME',
282 default=DEFAULT_H_OUTPUT_FILE_NAME,
283 help=('Output .h file path (default: {}; skip .h output if empty)'
284 .format(DEFAULT_H_OUTPUT_FILE_NAME)))
285 options = parser.parse_args()
286 if options.log:
287 generator = PSALoggingWrapperGenerator(options.log) #type: PSAWrapperGenerator
288 else:
289 generator = PSAWrapperGenerator()
290 generator.gather_data()
291 if options.output_h:
292 generator.write_h_file(options.output_h)
293 if options.output_c:
294 generator.write_c_file(options.output_c)
295
296if __name__ == '__main__':
297 main()