blob: 6aac2301ec9422233493bbd144680fa8cb52a350 [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
9import os
Valerio Setti862d14e2024-04-15 17:58:43 +020010from typing import Iterator
Valerio Setti7031a4e2024-04-16 10:31:15 +020011import re
Valerio Setti270dcd12024-04-08 13:44:41 +020012import argparse
Valerio Setti8f404602024-04-15 15:09:10 +020013import scripts_path # pylint: disable=unused-import
Valerio Settiee743392024-04-17 15:12:49 +020014from mbedtls_dev.asymmetric_key_data import ASYMMETRIC_KEY_DATA
Valerio Setti84dc3292024-04-29 17:33:48 +020015from mbedtls_dev.build_tree import guess_project_root
Valerio Setti7126ba52024-03-29 16:59:40 +010016
Valerio Settiee743392024-04-17 15:12:49 +020017OUTPUT_HEADER_FILE = os.path.dirname(os.path.abspath(__file__)) + "/../src/test_keys.h"
Valerio Setti862d14e2024-04-15 17:58:43 +020018BYTES_PER_LINE = 16
Valerio Setti7126ba52024-03-29 16:59:40 +010019
Valerio Setti862d14e2024-04-15 17:58:43 +020020def c_byte_array_literal_content(array_name: str, key_data: bytes) -> Iterator[str]:
21 yield 'const unsigned char '
22 yield array_name
23 yield '[] = {'
24 for index in range(0, len(key_data), BYTES_PER_LINE):
25 yield '\n '
26 for b in key_data[index:index + BYTES_PER_LINE]:
27 yield ' {:#04x},'.format(b)
28 yield '\n};'
29
Valerio Setti7031a4e2024-04-16 10:31:15 +020030def convert_der_to_c(array_name: str, key_data: bytes) -> str:
Valerio Setti862d14e2024-04-15 17:58:43 +020031 return ''.join(c_byte_array_literal_content(array_name, key_data))
Valerio Setti7126ba52024-03-29 16:59:40 +010032
Valerio Setti7031a4e2024-04-16 10:31:15 +020033def get_key_type(key: str) -> str:
34 if re.match('PSA_KEY_TYPE_RSA_.*', key):
35 return "rsa"
36 elif re.match('PSA_KEY_TYPE_ECC_.*', key):
37 return "ec"
38 else:
39 print("Unhandled key type {}".format(key))
40 return "unknown"
41
42def get_ec_key_family(key: str) -> str:
43 match = re.search(r'.*\((.*)\)', key)
44 if match is None:
45 raise Exception("Unable to get EC family from {}".format(key))
46 return match.group(1)
47
Valerio Setti9aa4fa92024-04-16 10:54:23 +020048# Legacy EC group ID do not support all the key types that PSA does, so the
49# following dictionaries are used for:
50# - getting prefix/suffix for legacy curve names
51# - understand if the curve is supported in legacy symbols (MBEDTLS_ECP_DP_...)
52EC_NAME_CONVERSION = {
53 'PSA_ECC_FAMILY_SECP_K1': {
Valerio Settiee743392024-04-17 15:12:49 +020054 192: ('secp', 'k1'),
55 224: ('secp', 'k1'),
56 256: ('secp', 'k1')
Valerio Setti9aa4fa92024-04-16 10:54:23 +020057 },
58 'PSA_ECC_FAMILY_SECP_R1': {
Valerio Settiee743392024-04-17 15:12:49 +020059 192: ('secp', 'r1'),
60 224: ('secp', 'r1'),
61 256: ('secp', 'r1'),
62 384: ('secp', 'r1'),
63 521: ('secp', 'r1')
Valerio Setti9aa4fa92024-04-16 10:54:23 +020064 },
65 'PSA_ECC_FAMILY_BRAINPOOL_P_R1': {
Valerio Settiee743392024-04-17 15:12:49 +020066 256: ('bp', 'r1'),
67 384: ('bp', 'r1'),
68 512: ('bp', 'r1')
Valerio Setti9aa4fa92024-04-16 10:54:23 +020069 },
70 'PSA_ECC_FAMILY_MONTGOMERY': {
Valerio Settiee743392024-04-17 15:12:49 +020071 255: ('curve', '19'),
72 448: ('curve', '')
Valerio Setti9aa4fa92024-04-16 10:54:23 +020073 }
74}
75
76def get_ec_curve_name(priv_key: str, bits: int) -> str:
77 ec_family = get_ec_key_family(priv_key)
78 try:
79 prefix = EC_NAME_CONVERSION[ec_family][bits][0]
80 suffix = EC_NAME_CONVERSION[ec_family][bits][1]
Valerio Settiee743392024-04-17 15:12:49 +020081 except KeyError:
Valerio Setti9aa4fa92024-04-16 10:54:23 +020082 return ""
83 return prefix + str(bits) + suffix
84
Valerio Setti36188212024-04-17 16:12:12 +020085def get_look_up_table_entry(key_type: str, group_id_or_keybits: str,
Valerio Setti9aa4fa92024-04-16 10:54:23 +020086 priv_array_name: str, pub_array_name: str) -> Iterator[str]:
Valerio Setti36188212024-04-17 16:12:12 +020087 if key_type == "ec":
88 yield " {{ {}, 0,\n".format(group_id_or_keybits)
89 else:
90 yield " {{ 0, {},\n".format(group_id_or_keybits)
Valerio Setti9aa4fa92024-04-16 10:54:23 +020091 yield " {0}, sizeof({0}),\n".format(priv_array_name)
92 yield " {0}, sizeof({0}) }},".format(pub_array_name)
Valerio Setti7031a4e2024-04-16 10:31:15 +020093
Valerio Setti0ddab0e2024-04-30 06:49:46 +020094#pylint: disable=too-many-locals
Valerio Setti862d14e2024-04-15 17:58:43 +020095def main() -> None:
Valerio Setti84dc3292024-04-29 17:33:48 +020096 default_output_path = guess_project_root() + "/tests/src/test_keys.h"
Valerio Setti52516a62024-04-11 11:41:24 +020097
Valerio Setti270dcd12024-04-08 13:44:41 +020098 argparser = argparse.ArgumentParser()
Valerio Setti52516a62024-04-11 11:41:24 +020099 argparser.add_argument("--output", help="Output file", default=default_output_path)
Valerio Setti270dcd12024-04-08 13:44:41 +0200100 args = argparser.parse_args()
Valerio Setti7126ba52024-03-29 16:59:40 +0100101
Valerio Setti270dcd12024-04-08 13:44:41 +0200102 output_file = args.output
Valerio Setti96daf672024-04-11 11:50:46 +0200103 # If the output file already exists, then we can quit (successfully)
Valerio Setti270dcd12024-04-08 13:44:41 +0200104 if os.path.exists(output_file):
Valerio Setti96daf672024-04-11 11:50:46 +0200105 return
Valerio Setti270dcd12024-04-08 13:44:41 +0200106
107 output_file = open(output_file, 'at')
Valerio Setti3e22bf22024-04-03 13:42:20 +0200108 output_file.write(
109 "/*********************************************************************************\n" +
110 " * This file was automatically generated from tests/scripts/generate_test_keys.py.\n" +
111 " * Please do not edit it manually.\n" +
Valerio Setti6bda5f52024-04-09 12:28:39 +0200112 " *********************************************************************************/\n"
Valerio Setti3e22bf22024-04-03 13:42:20 +0200113 )
Valerio Setti7126ba52024-03-29 16:59:40 +0100114
Valerio Settiee743392024-04-17 15:12:49 +0200115 look_up_table = []
Valerio Setti9aa4fa92024-04-16 10:54:23 +0200116
117 # Get a list of private keys only in order to get a single item for every
118 # (key type, key bits) pair. We know that ASYMMETRIC_KEY_DATA
119 # contains also the public counterpart.
Valerio Settiee743392024-04-17 15:12:49 +0200120 priv_keys = [key for key in ASYMMETRIC_KEY_DATA if '_KEY_PAIR' in key]
Valerio Setti9aa4fa92024-04-16 10:54:23 +0200121
122 for priv_key in priv_keys:
123 key_type = get_key_type(priv_key)
Valerio Setti7031a4e2024-04-16 10:31:15 +0200124 # Ignore keys which are not EC or RSA
125 if key_type == "unknown":
126 continue
Valerio Setti7031a4e2024-04-16 10:31:15 +0200127
Valerio Setti9aa4fa92024-04-16 10:54:23 +0200128 pub_key = re.sub('_KEY_PAIR', '_PUBLIC_KEY', priv_key)
129
130 for bits in ASYMMETRIC_KEY_DATA[priv_key]:
131 if key_type == "ec":
132 curve = get_ec_curve_name(priv_key, bits)
133 # Ignore EC curves unsupported in legacy symbols
134 if curve == "":
135 continue
Valerio Setti7031a4e2024-04-16 10:31:15 +0200136 # Create output array name
137 if key_type == "rsa":
Valerio Setti9aa4fa92024-04-16 10:54:23 +0200138 array_name_base = "_".join(["test", key_type, str(bits)])
Valerio Setti7031a4e2024-04-16 10:31:15 +0200139 else:
Valerio Setti9aa4fa92024-04-16 10:54:23 +0200140 array_name_base = "_".join(["test", key_type, curve])
141 array_name_priv = array_name_base + "_priv"
142 array_name_pub = array_name_base + "_pub"
Valerio Setti7031a4e2024-04-16 10:31:15 +0200143 # Convert bytearray to C array
Valerio Setti9aa4fa92024-04-16 10:54:23 +0200144 c_array_priv = convert_der_to_c(array_name_priv, ASYMMETRIC_KEY_DATA[priv_key][bits])
145 c_array_pub = convert_der_to_c(array_name_pub, ASYMMETRIC_KEY_DATA[pub_key][bits])
Valerio Setti7031a4e2024-04-16 10:31:15 +0200146 # Write the C array to the output file
Valerio Setti9aa4fa92024-04-16 10:54:23 +0200147 output_file.write(''.join(["\n", c_array_priv, "\n", c_array_pub, "\n"]))
148 # Update the lookup table
149 if key_type == "ec":
Valerio Setti36188212024-04-17 16:12:12 +0200150 group_id_or_keybits = "MBEDTLS_ECP_DP_" + curve.upper()
Valerio Setti9aa4fa92024-04-16 10:54:23 +0200151 else:
Valerio Setti36188212024-04-17 16:12:12 +0200152 group_id_or_keybits = str(bits)
153 look_up_table.append(''.join(get_look_up_table_entry(key_type, group_id_or_keybits,
Valerio Settiee743392024-04-17 15:12:49 +0200154 array_name_priv, array_name_pub)))
Valerio Setti9aa4fa92024-04-16 10:54:23 +0200155 # Write the lookup table: the struct containing pointers to all the arrays we created above.
156 output_file.write("""
157struct predefined_key_element {
Valerio Setti36188212024-04-17 16:12:12 +0200158 int group_id; // EC group ID; 0 for RSA keys
159 int keybits; // bits size of RSA key; 0 for EC keys
Valerio Setti9aa4fa92024-04-16 10:54:23 +0200160 const unsigned char *priv_key;
161 size_t priv_key_len;
162 const unsigned char *pub_key;
163 size_t pub_key_len;
164};
165
Valerio Settiee743392024-04-17 15:12:49 +0200166struct predefined_key_element predefined_keys[] = {
167""")
168 output_file.write("\n".join(look_up_table))
169 output_file.write("\n};\n")
Valerio Setti0ddab0e2024-04-30 06:49:46 +0200170 output_file.flush()
Valerio Setti7126ba52024-03-29 16:59:40 +0100171
172if __name__ == '__main__':
Valerio Setti862d14e2024-04-15 17:58:43 +0200173 main()