1
0
mirror of https://github.com/Mbed-TLS/mbedtls.git synced 2025-08-07 06:42:56 +03:00

Move driver wrappers generation to tf-psa-crypto

Signed-off-by: Ronald Cron <ronald.cron@arm.com>
This commit is contained in:
Ronald Cron
2024-11-13 09:20:30 +01:00
parent 1fe5277c88
commit 6a2cbe77fa
17 changed files with 18 additions and 13 deletions

View File

@@ -1,71 +0,0 @@
{
"$schema": "http://json-schema.org/draft-04/schema#",
"type": "object",
"properties": {
"_comment": {
"type": "string"
},
"prefix": {
"type": "string",
"pattern": "^[A-Z_a-z][0-9A-Z_a-z]*$"
},
"type": {
"type": "string",
"const": "opaque"
},
"location": {
"type": ["integer","string"],
"pattern": "^(0x|0X)?[a-fA-F0-9]+$"
},
"mbedtls/h_condition": {
"type": "string"
},
"headers": {
"type": "array",
"items": {
"type": "string"
},
"default": []
},
"capabilities": {
"type": "array",
"items": [
{
"type": "object",
"properties": {
"_comment": {
"type": "string"
},
"mbedtls/c_condition": {
"type": "string"
},
"entry_points": {
"type": "array",
"items": {
"type": "string"
}
},
"names": {
"type": "object",
"patternProperties": {
"^[A-Z_a-z][0-9A-Z_a-z]*$": {
"type": "string",
"pattern": "^[A-Z_a-z][0-9A-Z_a-z]*$"
}
}
}
},
"required": [
"entry_points"
]
}
]
}
},
"required": [
"prefix",
"type",
"location",
"capabilities"
]
}

View File

@@ -1,70 +0,0 @@
{
"$schema": "http://json-schema.org/draft-04/schema#",
"type": "object",
"properties": {
"_comment": {
"type": "string"
},
"prefix": {
"type": "string",
"pattern": "^[A-Z_a-z][0-9A-Z_a-z]*$"
},
"type": {
"type": "string",
"const": "transparent"
},
"mbedtls/h_condition": {
"type": "string"
},
"headers": {
"type": "array",
"items": {
"type": "string"
},
"default": []
},
"capabilities": {
"type": "array",
"items": [
{
"type": "object",
"properties": {
"_comment": {
"type": "string"
},
"mbedtls/c_condition": {
"type": "string"
},
"entry_points": {
"type": "array",
"items": {
"type": "string"
}
},
"names": {
"type": "object",
"patternProperties": {
"^[A-Z_a-z][0-9A-Z_a-z]*$": {
"type": "string",
"pattern": "^[A-Z_a-z][0-9A-Z_a-z]*$"
}
}
},
"fallback": {
"type": "boolean",
"default": "false"
}
},
"required": [
"entry_points"
]
}
]
}
},
"required": [
"prefix",
"type",
"capabilities"
]
}

View File

@@ -1 +0,0 @@
["mbedtls_test_opaque_driver.json","mbedtls_test_transparent_driver.json","p256_transparent_driver.json"]

View File

@@ -1,20 +0,0 @@
{
"prefix": "mbedtls_test",
"type": "opaque",
"location": "0x7fffff",
"mbedtls/h_condition": "defined(PSA_CRYPTO_DRIVER_TEST)",
"headers": ["test/drivers/test_driver.h"],
"capabilities": [
{
"_comment": "The Mbed TLS opaque driver supports import key/export key/export_public key",
"mbedtls/c_condition": "defined(PSA_CRYPTO_DRIVER_TEST)",
"entry_points": ["import_key", "export_key", "export_public_key"]
},
{
"_comment": "The Mbed TLS opaque driver supports copy key/ get builtin key",
"mbedtls/c_condition": "defined(PSA_CRYPTO_DRIVER_TEST)",
"entry_points": ["copy_key", "get_builtin_key"],
"names": {"copy_key":"mbedtls_test_opaque_copy_key", "get_builtin_key":"mbedtls_test_opaque_get_builtin_key"}
}
]
}

View File

@@ -1,22 +0,0 @@
{
"prefix": "mbedtls_test",
"type": "transparent",
"mbedtls/h_condition": "defined(PSA_CRYPTO_DRIVER_TEST)",
"headers": ["test/drivers/test_driver.h"],
"capabilities": [
{
"_comment": "The Mbed TLS transparent driver supports import key/export key",
"mbedtls/c_condition": "defined(PSA_CRYPTO_DRIVER_TEST)",
"entry_points": ["import_key"],
"fallback": true
},
{
"_comment": "The Mbed TLS transparent driver supports export_public key",
"mbedtls/c_condition": "defined(PSA_CRYPTO_DRIVER_TEST)",
"entry_points": ["export_public_key"],
"fallback": true,
"names": {"export_public_key":"mbedtls_test_transparent_export_public_key"}
}
]
}

View File

@@ -1,20 +0,0 @@
{
"prefix": "p256",
"type": "transparent",
"mbedtls/h_condition": "defined(MBEDTLS_PSA_P256M_DRIVER_ENABLED)",
"headers": ["../tf-psa-crypto/drivers/p256-m/p256-m_driver_entrypoints.h"],
"capabilities": [
{
"mbedtls/c_condition": "defined(MBEDTLS_PSA_P256M_DRIVER_ENABLED)",
"_comment_entry_points": "This is not the complete list of entry points supported by this driver, only those that are currently supported in JSON. See docs/psa-driver-example-and-guide.md",
"entry_points": ["import_key", "export_public_key"],
"algorithms": ["PSA_ALG_ECDH", "PSA_ALG_ECDSA(PSA_ALG_ANY_HASH)"],
"key_types": [
"PSA_KEY_TYPE_ECC_KEY_PAIR(PSA_ECC_FAMILY_SECP_R1)",
"PSA_KEY_TYPE_ECC_PUBLIC_KEY(PSA_ECC_FAMILY_SECP_R1)"
],
"key_sizes": [256],
"fallback": false
}
]
}

View File

@@ -1,17 +0,0 @@
{# One Shot function's dispatch code for opaque drivers.
Expected inputs:
* drivers: the list of driver descriptions.
* entry_point: the name of the entry point that this function dispatches to.
* entry_point_param(driver): the parameters to pass to the entry point.
* nest_indent: number of extra spaces to indent the code to.
-#}
{% for driver in drivers if driver.type == "opaque" -%}
{% for capability in driver.capabilities if entry_point in capability.entry_points -%}
#if ({% if capability['mbedtls/c_condition'] is defined -%}{{ capability['mbedtls/c_condition'] }} {% else -%} {{ 1 }} {% endif %})
{%- filter indent(width = nest_indent) %}
case {{ driver.location }}:
return( {{ entry_point_name(capability, entry_point, driver) }}({{entry_point_param(driver) | indent(20)}}));
{% endfilter -%}
#endif
{% endfor %}
{% endfor %}

View File

@@ -1,19 +0,0 @@
{# One Shot function's dispatch code for transparent drivers.
Expected inputs:
* drivers: the list of driver descriptions.
* entry_point: the name of the entry point that this function dispatches to.
* entry_point_param(driver): the parameters to pass to the entry point.
* nest_indent: number of extra spaces to indent the code to.
-#}
{% for driver in drivers if driver.type == "transparent" -%}
{% for capability in driver.capabilities if entry_point in capability.entry_points -%}
#if ({% if capability['mbedtls/c_condition'] is defined -%}{{ capability['mbedtls/c_condition'] }} {% else -%} {{ 1 }} {% endif %})
{%- filter indent(width = nest_indent) %}
status = {{ entry_point_name(capability, entry_point, driver) }}({{entry_point_param(driver) | indent(20)}});
if( status != PSA_ERROR_NOT_SUPPORTED )
return( status );
{% endfilter -%}
#endif
{% endfor %}
{% endfor %}

View File

@@ -1,224 +0,0 @@
/*
* Functions to delegate cryptographic operations to an available
* and appropriate accelerator.
* Warning: This file is now auto-generated.
*/
/* Copyright The Mbed TLS Contributors
* SPDX-License-Identifier: Apache-2.0 OR GPL-2.0-or-later
*/
/* BEGIN-common headers */
#include "common.h"
#include "psa_crypto_aead.h"
#include "psa_crypto_cipher.h"
#include "psa_crypto_core.h"
#include "psa_crypto_driver_wrappers_no_static.h"
#include "psa_crypto_hash.h"
#include "psa_crypto_mac.h"
#include "psa_crypto_pake.h"
#include "psa_crypto_rsa.h"
#include "mbedtls/platform.h"
/* END-common headers */
#if defined(MBEDTLS_PSA_CRYPTO_C)
/* BEGIN-driver headers */
{% for driver in drivers -%}
/* Headers for {{driver.prefix}} {{driver.type}} driver */
{% if driver['mbedtls/h_condition'] is defined -%}
#if {{ driver['mbedtls/h_condition'] }}
{% endif -%}
{% for header in driver.headers -%}
#include "{{ header }}"
{% endfor %}
{% if driver['mbedtls/h_condition'] is defined -%}
#endif
{% endif -%}
{% endfor %}
/* END-driver headers */
/* Auto-generated values depending on which drivers are registered.
* ID 0 is reserved for unallocated operations.
* ID 1 is reserved for the Mbed TLS software driver. */
/* BEGIN-driver id definition */
#define PSA_CRYPTO_MBED_TLS_DRIVER_ID (1)
{% for driver in drivers -%}
#define {{(driver.prefix + "_" + driver.type + "_driver_id").upper()}} ({{ loop.index + 1 }})
{% endfor %}
/* END-driver id */
/* BEGIN-Common Macro definitions */
{% macro entry_point_name(capability, entry_point, driver) -%}
{% if capability.name is defined and entry_point in capability.names.keys() -%}
{{ capability.names[entry_point]}}
{% else -%}
{{driver.prefix}}_{{driver.type}}_{{entry_point}}
{% endif -%}
{% endmacro %}
/* END-Common Macro definitions */
/* Support the 'old' SE interface when asked to */
#if defined(MBEDTLS_PSA_CRYPTO_SE_C)
/* PSA_CRYPTO_DRIVER_PRESENT is defined when either a new-style or old-style
* SE driver is present, to avoid unused argument errors at compile time. */
#ifndef PSA_CRYPTO_DRIVER_PRESENT
#define PSA_CRYPTO_DRIVER_PRESENT
#endif
#include "psa_crypto_se.h"
#endif
/** Get the key buffer size required to store the key material of a key
* associated with an opaque driver.
*
* \param[in] attributes The key attributes.
* \param[out] key_buffer_size Minimum buffer size to contain the key material
*
* \retval #PSA_SUCCESS
* The minimum size for a buffer to contain the key material has been
* returned successfully.
* \retval #PSA_ERROR_NOT_SUPPORTED
* The type and/or the size in bits of the key or the combination of
* the two is not supported.
* \retval #PSA_ERROR_INVALID_ARGUMENT
* The key is declared with a lifetime not known to us.
*/
psa_status_t psa_driver_wrapper_get_key_buffer_size(
const psa_key_attributes_t *attributes,
size_t *key_buffer_size )
{
psa_key_location_t location = PSA_KEY_LIFETIME_GET_LOCATION( psa_get_key_lifetime(attributes) );
psa_key_type_t key_type = psa_get_key_type(attributes);
size_t key_bits = psa_get_key_bits(attributes);
*key_buffer_size = 0;
switch( location )
{
#if defined(PSA_CRYPTO_DRIVER_TEST)
case PSA_CRYPTO_TEST_DRIVER_LOCATION:
#if defined(MBEDTLS_PSA_CRYPTO_BUILTIN_KEYS)
/* Emulate property 'builtin_key_size' */
if( psa_key_id_is_builtin(
MBEDTLS_SVC_KEY_ID_GET_KEY_ID(
psa_get_key_id( attributes ) ) ) )
{
*key_buffer_size = sizeof( psa_drv_slot_number_t );
return( PSA_SUCCESS );
}
#endif /* MBEDTLS_PSA_CRYPTO_BUILTIN_KEYS */
*key_buffer_size = mbedtls_test_opaque_size_function( key_type,
key_bits );
return( ( *key_buffer_size != 0 ) ?
PSA_SUCCESS : PSA_ERROR_NOT_SUPPORTED );
#endif /* PSA_CRYPTO_DRIVER_TEST */
default:
(void)key_type;
(void)key_bits;
return( PSA_ERROR_INVALID_ARGUMENT );
}
}
psa_status_t psa_driver_wrapper_export_public_key(
const psa_key_attributes_t *attributes,
const uint8_t *key_buffer, size_t key_buffer_size,
uint8_t *data, size_t data_size, size_t *data_length )
{
{% with entry_point = "export_public_key" -%}
{% macro entry_point_param(driver) -%}
attributes,
key_buffer,
key_buffer_size,
data,
data_size,
data_length
{% endmacro %}
psa_status_t status = PSA_ERROR_INVALID_ARGUMENT;
psa_key_location_t location = PSA_KEY_LIFETIME_GET_LOCATION(
psa_get_key_lifetime( attributes ) );
/* Try dynamically-registered SE interface first */
#if defined(MBEDTLS_PSA_CRYPTO_SE_C)
const psa_drv_se_t *drv;
psa_drv_se_context_t *drv_context;
if( psa_get_se_driver( psa_get_key_lifetime(attributes), &drv, &drv_context ) )
{
if( ( drv->key_management == NULL ) ||
( drv->key_management->p_export_public == NULL ) )
{
return( PSA_ERROR_NOT_SUPPORTED );
}
return( drv->key_management->p_export_public(
drv_context,
*( (psa_key_slot_number_t *)key_buffer ),
data, data_size, data_length ) );
}
#endif /* MBEDTLS_PSA_CRYPTO_SE_C */
switch( location )
{
case PSA_KEY_LOCATION_LOCAL_STORAGE:
/* Key is stored in the slot in export representation, so
* cycle through all known transparent accelerators */
#if defined(PSA_CRYPTO_ACCELERATOR_DRIVER_PRESENT)
{% with nest_indent=12 %}
{% include "OS-template-transparent.jinja" -%}
{% endwith -%}
#endif /* PSA_CRYPTO_ACCELERATOR_DRIVER_PRESENT */
/* Fell through, meaning no accelerator supports this operation */
return( psa_export_public_key_internal( attributes,
key_buffer,
key_buffer_size,
data,
data_size,
data_length ) );
/* Add cases for opaque driver here */
#if defined(PSA_CRYPTO_ACCELERATOR_DRIVER_PRESENT)
{% with nest_indent=8 %}
{% include "OS-template-opaque.jinja" -%}
{% endwith -%}
#endif /* PSA_CRYPTO_ACCELERATOR_DRIVER_PRESENT */
default:
/* Key is declared with a lifetime not known to us */
return( status );
}
{% endwith %}
}
psa_status_t psa_driver_wrapper_get_builtin_key(
psa_drv_slot_number_t slot_number,
psa_key_attributes_t *attributes,
uint8_t *key_buffer, size_t key_buffer_size, size_t *key_buffer_length )
{
{% with entry_point = "get_builtin_key" -%}
{% macro entry_point_param(driver) -%}
slot_number,
attributes,
key_buffer,
key_buffer_size,
key_buffer_length
{% endmacro %}
psa_key_location_t location = PSA_KEY_LIFETIME_GET_LOCATION( psa_get_key_lifetime(attributes) );
switch( location )
{
#if defined(PSA_CRYPTO_ACCELERATOR_DRIVER_PRESENT)
{% with nest_indent=8 %}
{% include "OS-template-opaque.jinja" -%}
{% endwith -%}
#endif /* PSA_CRYPTO_ACCELERATOR_DRIVER_PRESENT */
default:
(void) slot_number;
(void) key_buffer;
(void) key_buffer_size;
(void) key_buffer_length;
return( PSA_ERROR_DOES_NOT_EXIST );
}
{% endwith %}
}
#endif /* MBEDTLS_PSA_CRYPTO_C */

View File

@@ -1,214 +0,0 @@
#!/usr/bin/env python3
"""Generate psa_crypto_driver_wrappers.h
psa_crypto_driver_wrappers_no_static.c
This module is invoked by the build scripts to auto generate the
psa_crypto_driver_wrappers.h and psa_crypto_driver_wrappers_no_static
based on template files in script/data_files/driver_templates/.
"""
# Copyright The Mbed TLS Contributors
# SPDX-License-Identifier: Apache-2.0 OR GPL-2.0-or-later
import sys
import os
import json
from typing import NewType, Dict, Any
from traceback import format_tb
import argparse
import jsonschema
import jinja2
import framework_scripts_path # pylint: disable=unused-import
from mbedtls_framework import build_tree
JSONSchema = NewType('JSONSchema', object)
# The Driver is an Object, but practically it's indexable and can called a dictionary to
# keep MyPy happy till MyPy comes with a more composite type for JsonObjects.
Driver = NewType('Driver', dict)
class JsonValidationException(Exception):
def __init__(self, message="Json Validation Failed"):
self.message = message
super().__init__(self.message)
class DriverReaderException(Exception):
def __init__(self, message="Driver Reader Failed"):
self.message = message
super().__init__(self.message)
def render(template_path: str, driver_jsoncontext: list) -> str:
"""
Render template from the input file and driver JSON.
"""
environment = jinja2.Environment(
loader=jinja2.FileSystemLoader(os.path.dirname(template_path)),
keep_trailing_newline=True)
template = environment.get_template(os.path.basename(template_path))
return template.render(drivers=driver_jsoncontext)
def generate_driver_wrapper_file(template_dir: str,
output_dir: str,
template_file_name: str,
driver_jsoncontext: list) -> None:
"""
Generate the file psa_crypto_driver_wrapper.c.
"""
driver_wrapper_template_filename = \
os.path.join(template_dir, template_file_name)
result = render(driver_wrapper_template_filename, driver_jsoncontext)
with open(file=os.path.join(output_dir, os.path.splitext(template_file_name)[0]),
mode='w',
encoding='UTF-8') as out_file:
out_file.write(result)
def validate_json(driverjson_data: Driver, driverschema_list: dict) -> None:
"""
Validate the Driver JSON against an appropriate schema
the schema passed could be that matching an opaque/ transparent driver.
"""
driver_type = driverjson_data["type"]
driver_prefix = driverjson_data["prefix"]
try:
_schema = driverschema_list[driver_type]
jsonschema.validate(instance=driverjson_data, schema=_schema)
except KeyError as err:
# This could happen if the driverjson_data.type does not exist in the provided schema list
# schemas = {'transparent': transparent_driver_schema, 'opaque': opaque_driver_schema}
# Print onto stdout and stderr.
print("Unknown Driver type " + driver_type +
" for driver " + driver_prefix, str(err))
print("Unknown Driver type " + driver_type +
" for driver " + driver_prefix, str(err), file=sys.stderr)
raise JsonValidationException() from err
except jsonschema.exceptions.ValidationError as err:
# Print onto stdout and stderr.
print("Error: Failed to validate data file: {} using schema: {}."
"\n Exception Message: \"{}\""
" ".format(driverjson_data, _schema, str(err)))
print("Error: Failed to validate data file: {} using schema: {}."
"\n Exception Message: \"{}\""
" ".format(driverjson_data, _schema, str(err)), file=sys.stderr)
raise JsonValidationException() from err
def load_driver(schemas: Dict[str, Any], driver_file: str) -> Any:
"""loads validated json driver"""
with open(file=driver_file, mode='r', encoding='UTF-8') as f:
json_data = json.load(f)
try:
validate_json(json_data, schemas)
except JsonValidationException as e:
raise DriverReaderException from e
return json_data
def load_schemas(project_root: str) -> Dict[str, Any]:
"""
Load schemas map
"""
schema_file_paths = {
'transparent': os.path.join(project_root,
'scripts',
'data_files',
'driver_jsons',
'driver_transparent_schema.json'),
'opaque': os.path.join(project_root,
'scripts',
'data_files',
'driver_jsons',
'driver_opaque_schema.json')
}
driver_schema = {}
for key, file_path in schema_file_paths.items():
with open(file=file_path, mode='r', encoding='UTF-8') as file:
driver_schema[key] = json.load(file)
return driver_schema
def read_driver_descriptions(project_root: str,
json_directory: str,
jsondriver_list: str) -> list:
"""
Merge driver JSON files into a single ordered JSON after validation.
"""
driver_schema = load_schemas(project_root)
with open(file=os.path.join(json_directory, jsondriver_list),
mode='r',
encoding='UTF-8') as driver_list_file:
driver_list = json.load(driver_list_file)
return [load_driver(schemas=driver_schema,
driver_file=os.path.join(json_directory, driver_file_name))
for driver_file_name in driver_list]
def trace_exception(e: Exception, file=sys.stderr) -> None:
"""Prints exception trace to the given TextIO handle"""
print("Exception: type: %s, message: %s, trace: %s" % (
e.__class__, str(e), format_tb(e.__traceback__)
), file)
TEMPLATE_FILENAMES = ["psa_crypto_driver_wrappers.h.jinja",
"psa_crypto_driver_wrappers_no_static.c.jinja"]
def main() -> int:
"""
Main with command line arguments.
"""
def_arg_project_root = build_tree.guess_project_root()
parser = argparse.ArgumentParser()
parser.add_argument('--project-root', default=def_arg_project_root,
help='root directory of repo source code')
parser.add_argument('--template-dir',
help='directory holding the driver templates')
parser.add_argument('--json-dir',
help='directory holding the driver JSONs')
parser.add_argument('output_directory', nargs='?',
help='output file\'s location')
args = parser.parse_args()
project_root = os.path.abspath(args.project_root)
crypto_core_directory = build_tree.crypto_core_directory(project_root)
output_directory = args.output_directory if args.output_directory is not None else \
crypto_core_directory
template_directory = args.template_dir if args.template_dir is not None else \
os.path.join(project_root,
'scripts',
'data_files',
'driver_templates')
json_directory = args.json_dir if args.json_dir is not None else \
os.path.join(project_root,
'scripts',
'data_files',
'driver_jsons')
try:
# Read and validate list of driver jsons from driverlist.json
merged_driver_json = read_driver_descriptions(project_root,
json_directory,
'driverlist.json')
except DriverReaderException as e:
trace_exception(e)
return 1
for template_filename in TEMPLATE_FILENAMES:
generate_driver_wrapper_file(template_directory, output_directory,
template_filename, merged_driver_json)
return 0
if __name__ == '__main__':
sys.exit(main())

View File

@@ -9,7 +9,7 @@
@rem @@@@ library\** @@@@
@rem psa_crypto_driver_wrappers.h needs to be generated prior to
@rem generate_visualc_files.pl being invoked.
python scripts\generate_driver_wrappers.py || exit /b 1
python tf-psa-crypto\scripts\generate_driver_wrappers.py || exit /b 1
perl scripts\generate_errors.pl || exit /b 1
perl scripts\generate_query_config.pl || exit /b 1
perl scripts\generate_features.pl || exit /b 1