blob: 62b756031f770de262c35f460c302c15ada286d7 [file] [log] [blame]
Valerio Setti7126ba52024-03-29 16:59:40 +01001#!/usr/bin/env python3
2
3# Copyright The Mbed TLS Contributors
4# SPDX-License-Identifier: Apache-2.0 OR GPL-2.0-or-later
5
6"""Module generating EC and RSA keys to be used in test_suite_pk instead of
7generating the required key at run time. This helps speeding up testing."""
8
Valerio Settia8ccddc2024-05-07 12:10:54 +02009from typing import Iterator, List, Tuple
Valerio Setti7031a4e2024-04-16 10:31:15 +020010import re
Valerio Setti270dcd12024-04-08 13:44:41 +020011import argparse
Valerio Setti8f404602024-04-15 15:09:10 +020012import scripts_path # pylint: disable=unused-import
Valerio Settiee743392024-04-17 15:12:49 +020013from mbedtls_dev.asymmetric_key_data import ASYMMETRIC_KEY_DATA
Valerio Setti84dc3292024-04-29 17:33:48 +020014from mbedtls_dev.build_tree import guess_project_root
Valerio Setti7126ba52024-03-29 16:59:40 +010015
Valerio Setti862d14e2024-04-15 17:58:43 +020016BYTES_PER_LINE = 16
Valerio Setti7126ba52024-03-29 16:59:40 +010017
Valerio Setti862d14e2024-04-15 17:58:43 +020018def c_byte_array_literal_content(array_name: str, key_data: bytes) -> Iterator[str]:
19 yield 'const unsigned char '
20 yield array_name
21 yield '[] = {'
22 for index in range(0, len(key_data), BYTES_PER_LINE):
23 yield '\n '
24 for b in key_data[index:index + BYTES_PER_LINE]:
25 yield ' {:#04x},'.format(b)
26 yield '\n};'
27
Valerio Setti7031a4e2024-04-16 10:31:15 +020028def convert_der_to_c(array_name: str, key_data: bytes) -> str:
Valerio Setti862d14e2024-04-15 17:58:43 +020029 return ''.join(c_byte_array_literal_content(array_name, key_data))
Valerio Setti7126ba52024-03-29 16:59:40 +010030
Valerio Setti7031a4e2024-04-16 10:31:15 +020031def get_key_type(key: str) -> str:
32 if re.match('PSA_KEY_TYPE_RSA_.*', key):
33 return "rsa"
34 elif re.match('PSA_KEY_TYPE_ECC_.*', key):
35 return "ec"
36 else:
37 print("Unhandled key type {}".format(key))
38 return "unknown"
39
40def get_ec_key_family(key: str) -> str:
41 match = re.search(r'.*\((.*)\)', key)
42 if match is None:
43 raise Exception("Unable to get EC family from {}".format(key))
44 return match.group(1)
45
Valerio Setti9aa4fa92024-04-16 10:54:23 +020046# Legacy EC group ID do not support all the key types that PSA does, so the
47# following dictionaries are used for:
48# - getting prefix/suffix for legacy curve names
49# - understand if the curve is supported in legacy symbols (MBEDTLS_ECP_DP_...)
50EC_NAME_CONVERSION = {
51 'PSA_ECC_FAMILY_SECP_K1': {
Valerio Settiee743392024-04-17 15:12:49 +020052 192: ('secp', 'k1'),
53 224: ('secp', 'k1'),
54 256: ('secp', 'k1')
Valerio Setti9aa4fa92024-04-16 10:54:23 +020055 },
56 'PSA_ECC_FAMILY_SECP_R1': {
Valerio Settiee743392024-04-17 15:12:49 +020057 192: ('secp', 'r1'),
58 224: ('secp', 'r1'),
59 256: ('secp', 'r1'),
60 384: ('secp', 'r1'),
61 521: ('secp', 'r1')
Valerio Setti9aa4fa92024-04-16 10:54:23 +020062 },
63 'PSA_ECC_FAMILY_BRAINPOOL_P_R1': {
Valerio Settiee743392024-04-17 15:12:49 +020064 256: ('bp', 'r1'),
65 384: ('bp', 'r1'),
66 512: ('bp', 'r1')
Valerio Setti9aa4fa92024-04-16 10:54:23 +020067 },
68 'PSA_ECC_FAMILY_MONTGOMERY': {
Valerio Settiee743392024-04-17 15:12:49 +020069 255: ('curve', '19'),
70 448: ('curve', '')
Valerio Setti9aa4fa92024-04-16 10:54:23 +020071 }
72}
73
74def get_ec_curve_name(priv_key: str, bits: int) -> str:
75 ec_family = get_ec_key_family(priv_key)
76 try:
77 prefix = EC_NAME_CONVERSION[ec_family][bits][0]
78 suffix = EC_NAME_CONVERSION[ec_family][bits][1]
Valerio Settiee743392024-04-17 15:12:49 +020079 except KeyError:
Valerio Setti9aa4fa92024-04-16 10:54:23 +020080 return ""
81 return prefix + str(bits) + suffix
82
Valerio Setti36188212024-04-17 16:12:12 +020083def get_look_up_table_entry(key_type: str, group_id_or_keybits: str,
Valerio Setti9aa4fa92024-04-16 10:54:23 +020084 priv_array_name: str, pub_array_name: str) -> Iterator[str]:
Valerio Setti36188212024-04-17 16:12:12 +020085 if key_type == "ec":
86 yield " {{ {}, 0,\n".format(group_id_or_keybits)
87 else:
88 yield " {{ 0, {},\n".format(group_id_or_keybits)
Valerio Setti9aa4fa92024-04-16 10:54:23 +020089 yield " {0}, sizeof({0}),\n".format(priv_array_name)
90 yield " {0}, sizeof({0}) }},".format(pub_array_name)
Valerio Setti7031a4e2024-04-16 10:31:15 +020091
Valerio Setticc403cb2024-05-06 12:39:26 +020092
Valerio Settia8ccddc2024-05-07 12:10:54 +020093def write_output_file(output_file_name: str, arrays: str, look_up_table: str):
Valerio Setticc403cb2024-05-06 12:39:26 +020094 with open(output_file_name, 'wt') as output:
Valerio Setti3fcaf6c2024-05-06 14:37:25 +020095 output.write("""\
Valerio Setticc403cb2024-05-06 12:39:26 +020096/*********************************************************************************
97 * This file was automatically generated from tests/scripts/generate_test_keys.py.
98 * Please do not edit it manually.
99 *********************************************************************************/
100""")
Valerio Settia8ccddc2024-05-07 12:10:54 +0200101 output.write(arrays)
Valerio Setticc403cb2024-05-06 12:39:26 +0200102 output.write("""
103struct predefined_key_element {{
104 int group_id; // EC group ID; 0 for RSA keys
105 int keybits; // bits size of RSA key; 0 for EC keys
106 const unsigned char *priv_key;
107 size_t priv_key_len;
108 const unsigned char *pub_key;
109 size_t pub_key_len;
110}};
111
112struct predefined_key_element predefined_keys[] = {{
113{}
114}};
Valerio Setti3fcaf6c2024-05-06 14:37:25 +0200115
116/* End of generated file */
Valerio Settia8ccddc2024-05-07 12:10:54 +0200117""".format(look_up_table))
Valerio Setticc403cb2024-05-06 12:39:26 +0200118
Valerio Settia8ccddc2024-05-07 12:10:54 +0200119def collect_keys() -> Tuple[str, str]:
120 """"
121 This function reads key data from ASYMMETRIC_KEY_DATA and, only for the
122 keys supported in legacy ECP/RSA modules, it returns 2 strings:
123 - the 1st contains C arrays declaration of these keys and
124 - the 2nd contains the final look-up table for all these arrays.
125 """
Valerio Setticc403cb2024-05-06 12:39:26 +0200126 arrays = []
Valerio Settiee743392024-04-17 15:12:49 +0200127 look_up_table = []
Valerio Setti9aa4fa92024-04-16 10:54:23 +0200128
129 # Get a list of private keys only in order to get a single item for every
130 # (key type, key bits) pair. We know that ASYMMETRIC_KEY_DATA
131 # contains also the public counterpart.
Valerio Settiee743392024-04-17 15:12:49 +0200132 priv_keys = [key for key in ASYMMETRIC_KEY_DATA if '_KEY_PAIR' in key]
Valerio Settidc641632024-05-03 18:22:01 +0200133 priv_keys = sorted(priv_keys)
Valerio Setti9aa4fa92024-04-16 10:54:23 +0200134
135 for priv_key in priv_keys:
136 key_type = get_key_type(priv_key)
Valerio Setti7031a4e2024-04-16 10:31:15 +0200137 # Ignore keys which are not EC or RSA
138 if key_type == "unknown":
139 continue
Valerio Setti7031a4e2024-04-16 10:31:15 +0200140
Valerio Setti9aa4fa92024-04-16 10:54:23 +0200141 pub_key = re.sub('_KEY_PAIR', '_PUBLIC_KEY', priv_key)
142
143 for bits in ASYMMETRIC_KEY_DATA[priv_key]:
144 if key_type == "ec":
145 curve = get_ec_curve_name(priv_key, bits)
146 # Ignore EC curves unsupported in legacy symbols
147 if curve == "":
148 continue
Valerio Setti7031a4e2024-04-16 10:31:15 +0200149 # Create output array name
150 if key_type == "rsa":
Valerio Setti9aa4fa92024-04-16 10:54:23 +0200151 array_name_base = "_".join(["test", key_type, str(bits)])
Valerio Setti7031a4e2024-04-16 10:31:15 +0200152 else:
Valerio Setti9aa4fa92024-04-16 10:54:23 +0200153 array_name_base = "_".join(["test", key_type, curve])
154 array_name_priv = array_name_base + "_priv"
155 array_name_pub = array_name_base + "_pub"
Valerio Setti7031a4e2024-04-16 10:31:15 +0200156 # Convert bytearray to C array
Valerio Setti9aa4fa92024-04-16 10:54:23 +0200157 c_array_priv = convert_der_to_c(array_name_priv, ASYMMETRIC_KEY_DATA[priv_key][bits])
158 c_array_pub = convert_der_to_c(array_name_pub, ASYMMETRIC_KEY_DATA[pub_key][bits])
Valerio Setti7031a4e2024-04-16 10:31:15 +0200159 # Write the C array to the output file
Valerio Setticc403cb2024-05-06 12:39:26 +0200160 arrays.append(''.join(["\n", c_array_priv, "\n", c_array_pub, "\n"]))
Valerio Setti9aa4fa92024-04-16 10:54:23 +0200161 # Update the lookup table
162 if key_type == "ec":
Valerio Setti36188212024-04-17 16:12:12 +0200163 group_id_or_keybits = "MBEDTLS_ECP_DP_" + curve.upper()
Valerio Setti9aa4fa92024-04-16 10:54:23 +0200164 else:
Valerio Setti36188212024-04-17 16:12:12 +0200165 group_id_or_keybits = str(bits)
166 look_up_table.append(''.join(get_look_up_table_entry(key_type, group_id_or_keybits,
Valerio Settiee743392024-04-17 15:12:49 +0200167 array_name_priv, array_name_pub)))
Valerio Setti9aa4fa92024-04-16 10:54:23 +0200168
Valerio Settia8ccddc2024-05-07 12:10:54 +0200169 return ''.join(arrays), '\n'.join(look_up_table)
170
171def main() -> None:
172 default_output_path = guess_project_root() + "/tests/src/test_keys.h"
173
174 argparser = argparse.ArgumentParser()
175 argparser.add_argument("--output", help="Output file", default=default_output_path)
176 args = argparser.parse_args()
177
178 output_file = args.output
179
180 arrays, look_up_table = collect_keys()
181
Valerio Setticc403cb2024-05-06 12:39:26 +0200182 write_output_file(output_file, arrays, look_up_table)
Valerio Setti7126ba52024-03-29 16:59:40 +0100183
184if __name__ == '__main__':
Valerio Setti862d14e2024-04-15 17:58:43 +0200185 main()