Integrate p256-m as an example driver alongside Mbed TLS and write documentation for the example.

(Reapplying changes as one commit on top of development post codestyle change instead of rewriting old branch)

Signed-off-by: Aditya Deshpande <aditya.deshpande@arm.com>
This commit is contained in:
Aditya Deshpande 2023-01-12 16:29:02 +00:00
parent 14d6b1124b
commit e41f7e457f
12 changed files with 2284 additions and 0 deletions

View file

@ -1,2 +1,3 @@
THIRDPARTY_DIR = $(dir $(lastword $(MAKEFILE_LIST))) THIRDPARTY_DIR = $(dir $(lastword $(MAKEFILE_LIST)))
include $(THIRDPARTY_DIR)/everest/Makefile.inc include $(THIRDPARTY_DIR)/everest/Makefile.inc
include ../3rdparty/p256-m/Makefile.inc

5
3rdparty/p256-m/Makefile.inc vendored Normal file
View file

@ -0,0 +1,5 @@
THIRDPARTY_INCLUDES+=-I../3rdparty/p256-m/p256-m/include -I../3rdparty/p256-m/p256-m/include/p256-m -I../3rdparty/p256-m/p256-m_driver_interface
THIRDPARTY_CRYPTO_OBJECTS+= \
../3rdparty/p256-m//p256-m_driver_entrypoints.o \
../3rdparty/p256-m//p256-m/p256-m.o

202
3rdparty/p256-m/p256-m/apache-2.0.txt vendored Normal file
View file

@ -0,0 +1,202 @@
Apache License
Version 2.0, January 2004
http://www.apache.org/licenses/
TERMS AND CONDITIONS FOR USE, REPRODUCTION, AND DISTRIBUTION
1. Definitions.
"License" shall mean the terms and conditions for use, reproduction,
and distribution as defined by Sections 1 through 9 of this document.
"Licensor" shall mean the copyright owner or entity authorized by
the copyright owner that is granting the License.
"Legal Entity" shall mean the union of the acting entity and all
other entities that control, are controlled by, or are under common
control with that entity. For the purposes of this definition,
"control" means (i) the power, direct or indirect, to cause the
direction or management of such entity, whether by contract or
otherwise, or (ii) ownership of fifty percent (50%) or more of the
outstanding shares, or (iii) beneficial ownership of such entity.
"You" (or "Your") shall mean an individual or Legal Entity
exercising permissions granted by this License.
"Source" form shall mean the preferred form for making modifications,
including but not limited to software source code, documentation
source, and configuration files.
"Object" form shall mean any form resulting from mechanical
transformation or translation of a Source form, including but
not limited to compiled object code, generated documentation,
and conversions to other media types.
"Work" shall mean the work of authorship, whether in Source or
Object form, made available under the License, as indicated by a
copyright notice that is included in or attached to the work
(an example is provided in the Appendix below).
"Derivative Works" shall mean any work, whether in Source or Object
form, that is based on (or derived from) the Work and for which the
editorial revisions, annotations, elaborations, or other modifications
represent, as a whole, an original work of authorship. For the purposes
of this License, Derivative Works shall not include works that remain
separable from, or merely link (or bind by name) to the interfaces of,
the Work and Derivative Works thereof.
"Contribution" shall mean any work of authorship, including
the original version of the Work and any modifications or additions
to that Work or Derivative Works thereof, that is intentionally
submitted to Licensor for inclusion in the Work by the copyright owner
or by an individual or Legal Entity authorized to submit on behalf of
the copyright owner. For the purposes of this definition, "submitted"
means any form of electronic, verbal, or written communication sent
to the Licensor or its representatives, including but not limited to
communication on electronic mailing lists, source code control systems,
and issue tracking systems that are managed by, or on behalf of, the
Licensor for the purpose of discussing and improving the Work, but
excluding communication that is conspicuously marked or otherwise
designated in writing by the copyright owner as "Not a Contribution."
"Contributor" shall mean Licensor and any individual or Legal Entity
on behalf of whom a Contribution has been received by Licensor and
subsequently incorporated within the Work.
2. Grant of Copyright License. Subject to the terms and conditions of
this License, each Contributor hereby grants to You a perpetual,
worldwide, non-exclusive, no-charge, royalty-free, irrevocable
copyright license to reproduce, prepare Derivative Works of,
publicly display, publicly perform, sublicense, and distribute the
Work and such Derivative Works in Source or Object form.
3. Grant of Patent License. Subject to the terms and conditions of
this License, each Contributor hereby grants to You a perpetual,
worldwide, non-exclusive, no-charge, royalty-free, irrevocable
(except as stated in this section) patent license to make, have made,
use, offer to sell, sell, import, and otherwise transfer the Work,
where such license applies only to those patent claims licensable
by such Contributor that are necessarily infringed by their
Contribution(s) alone or by combination of their Contribution(s)
with the Work to which such Contribution(s) was submitted. If You
institute patent litigation against any entity (including a
cross-claim or counterclaim in a lawsuit) alleging that the Work
or a Contribution incorporated within the Work constitutes direct
or contributory patent infringement, then any patent licenses
granted to You under this License for that Work shall terminate
as of the date such litigation is filed.
4. Redistribution. You may reproduce and distribute copies of the
Work or Derivative Works thereof in any medium, with or without
modifications, and in Source or Object form, provided that You
meet the following conditions:
(a) You must give any other recipients of the Work or
Derivative Works a copy of this License; and
(b) You must cause any modified files to carry prominent notices
stating that You changed the files; and
(c) You must retain, in the Source form of any Derivative Works
that You distribute, all copyright, patent, trademark, and
attribution notices from the Source form of the Work,
excluding those notices that do not pertain to any part of
the Derivative Works; and
(d) If the Work includes a "NOTICE" text file as part of its
distribution, then any Derivative Works that You distribute must
include a readable copy of the attribution notices contained
within such NOTICE file, excluding those notices that do not
pertain to any part of the Derivative Works, in at least one
of the following places: within a NOTICE text file distributed
as part of the Derivative Works; within the Source form or
documentation, if provided along with the Derivative Works; or,
within a display generated by the Derivative Works, if and
wherever such third-party notices normally appear. The contents
of the NOTICE file are for informational purposes only and
do not modify the License. You may add Your own attribution
notices within Derivative Works that You distribute, alongside
or as an addendum to the NOTICE text from the Work, provided
that such additional attribution notices cannot be construed
as modifying the License.
You may add Your own copyright statement to Your modifications and
may provide additional or different license terms and conditions
for use, reproduction, or distribution of Your modifications, or
for any such Derivative Works as a whole, provided Your use,
reproduction, and distribution of the Work otherwise complies with
the conditions stated in this License.
5. Submission of Contributions. Unless You explicitly state otherwise,
any Contribution intentionally submitted for inclusion in the Work
by You to the Licensor shall be under the terms and conditions of
this License, without any additional terms or conditions.
Notwithstanding the above, nothing herein shall supersede or modify
the terms of any separate license agreement you may have executed
with Licensor regarding such Contributions.
6. Trademarks. This License does not grant permission to use the trade
names, trademarks, service marks, or product names of the Licensor,
except as required for reasonable and customary use in describing the
origin of the Work and reproducing the content of the NOTICE file.
7. Disclaimer of Warranty. Unless required by applicable law or
agreed to in writing, Licensor provides the Work (and each
Contributor provides its Contributions) on an "AS IS" BASIS,
WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or
implied, including, without limitation, any warranties or conditions
of TITLE, NON-INFRINGEMENT, MERCHANTABILITY, or FITNESS FOR A
PARTICULAR PURPOSE. You are solely responsible for determining the
appropriateness of using or redistributing the Work and assume any
risks associated with Your exercise of permissions under this License.
8. Limitation of Liability. In no event and under no legal theory,
whether in tort (including negligence), contract, or otherwise,
unless required by applicable law (such as deliberate and grossly
negligent acts) or agreed to in writing, shall any Contributor be
liable to You for damages, including any direct, indirect, special,
incidental, or consequential damages of any character arising as a
result of this License or out of the use or inability to use the
Work (including but not limited to damages for loss of goodwill,
work stoppage, computer failure or malfunction, or any and all
other commercial damages or losses), even if such Contributor
has been advised of the possibility of such damages.
9. Accepting Warranty or Additional Liability. While redistributing
the Work or Derivative Works thereof, You may choose to offer,
and charge a fee for, acceptance of support, warranty, indemnity,
or other liability obligations and/or rights consistent with this
License. However, in accepting such obligations, You may act only
on Your own behalf and on Your sole responsibility, not on behalf
of any other Contributor, and only if You agree to indemnify,
defend, and hold each Contributor harmless for any liability
incurred by, or claims asserted against, such Contributor by reason
of your accepting any such warranty or additional liability.
END OF TERMS AND CONDITIONS
APPENDIX: How to apply the Apache License to your work.
To apply the Apache License to your work, attach the following
boilerplate notice, with the fields enclosed by brackets "[]"
replaced with your own identifying information. (Don't include
the brackets!) The text should be enclosed in the appropriate
comment syntax for the file format. We also recommend that a
file or class name and description of purpose be included on the
same "printed page" as the copyright notice for easier
identification within third-party archives.
Copyright [yyyy] [name of copyright owner]
Licensed under the Apache License, Version 2.0 (the "License");
you may not use this file except in compliance with the License.
You may obtain a copy of the License at
http://www.apache.org/licenses/LICENSE-2.0
Unless required by applicable law or agreed to in writing, software
distributed under the License is distributed on an "AS IS" BASIS,
WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
See the License for the specific language governing permissions and
limitations under the License.

1459
3rdparty/p256-m/p256-m/p256-m.c vendored Normal file

File diff suppressed because it is too large Load diff

95
3rdparty/p256-m/p256-m/p256-m.h vendored Normal file
View file

@ -0,0 +1,95 @@
/*
* Interface of curve P-256 (ECDH and ECDSA)
*
* Author: Manuel Pégourié-Gonnard.
* SPDX-License-Identifier: Apache-2.0
*/
#ifndef P256_M_H
#define P256_M_H
#include <stdint.h>
#include <stddef.h>
/* Status codes */
#define P256_SUCCESS 0
#define P256_RANDOM_FAILED -1
#define P256_INVALID_PUBKEY -2
#define P256_INVALID_PRIVKEY -3
#define P256_INVALID_SIGNATURE -4
#ifdef __cplusplus
extern "C" {
#endif
/*
* RNG function - must be provided externally and be cryptographically secure.
*
* in: output - must point to a writable buffer of at least output_size bytes.
* output_size - the number of random bytes to write to output.
* out: output is filled with output_size random bytes.
* return 0 on success, non-zero on errors.
*/
extern int p256_generate_random(uint8_t * output, unsigned output_size);
/*
* ECDH/ECDSA generate key pair
*
* [in] draws from p256_generate_random()
* [out] priv: on success, holds the private key, as a big-endian integer
* [out] pub: on success, holds the public key, as two big-endian integers
*
* return: P256_SUCCESS on success
* P256_RANDOM_FAILED on failure
*/
int p256_gen_keypair(uint8_t priv[32], uint8_t pub[64]);
/*
* ECDH compute shared secret
*
* [out] secret: on success, holds the shared secret, as a big-endian integer
* [in] priv: our private key as a big-endian integer
* [in] pub: the peer's public key, as two big-endian integers
*
* return: P256_SUCCESS on success
* P256_INVALID_PRIVKEY if priv is invalid
* P256_INVALID_PUBKEY if pub is invalid
*/
int p256_ecdh_shared_secret(uint8_t secret[32],
const uint8_t priv[32], const uint8_t pub[64]);
/*
* ECDSA sign
*
* [in] draws from p256_generate_random()
* [out] sig: on success, holds the signature, as two big-endian integers
* [in] priv: our private key as a big-endian integer
* [in] hash: the hash of the message to be signed
* [in] hlen: the size of hash in bytes
*
* return: P256_SUCCESS on success
* P256_RANDOM_FAILED on failure
* P256_INVALID_PRIVKEY if priv is invalid
*/
int p256_ecdsa_sign(uint8_t sig[64], const uint8_t priv[32],
const uint8_t *hash, size_t hlen);
/*
* ECDSA verify
*
* [in] sig: the signature to be verified, as two big-endian integers
* [in] pub: the associated public key, as two big-endian integers
* [in] hash: the hash of the message that was signed
* [in] hlen: the size of hash in bytes
*
* return: P256_SUCCESS on success - the signature was verified as valid
* P256_INVALID_PUBKEY if pub is invalid
* P256_INVALID_SIGNATURE if the signature was found to be invalid
*/
int p256_ecdsa_verify(const uint8_t sig[64], const uint8_t pub[64],
const uint8_t *hash, size_t hlen);
#ifdef __cplusplus
}
#endif
#endif /* P256_M_H */

View file

@ -0,0 +1,204 @@
#include "mbedtls/platform.h"
#include "p256-m_driver_entrypoints.h"
#include "p256-m/p256-m.h"
#include "psa/crypto.h"
#include "psa_crypto_driver_wrappers.h"
#if defined(MBEDTLS_P256M_EXAMPLE_DRIVER_ENABLED)
psa_status_t p256m_to_psa_error( int ret )
{
switch( ret )
{
case P256_SUCCESS:
return( PSA_SUCCESS );
case P256_INVALID_PUBKEY:
case P256_INVALID_PRIVKEY:
return( PSA_ERROR_INVALID_ARGUMENT );
case P256_INVALID_SIGNATURE:
return( PSA_ERROR_INVALID_SIGNATURE );
case P256_RANDOM_FAILED:
default:
return( PSA_ERROR_GENERIC_ERROR );
}
}
psa_status_t p256m_transparent_generate_key(
const psa_key_attributes_t *attributes,
uint8_t *key_buffer,
size_t key_buffer_size,
size_t *key_buffer_length )
{
/* We don't use this argument, but the specification mandates the signature
* of driver entry-points. (void) used to avoid compiler warning. */
(void) attributes;
psa_status_t status = PSA_ERROR_NOT_SUPPORTED;
/*
* p256-m generates a 32 byte private key, and expects to write to a buffer
* that is of that size. */
if( key_buffer_size != 32 )
return( status );
/*
* p256-m's keypair generation function outputs both public and private
* keys. Allocate a buffer to which the public key will be written. The
* private key will be written to key_buffer, which is passed to this
* function as an argument. */
uint8_t *public_key_buffer = NULL;
public_key_buffer = mbedtls_calloc( 1, 64);
if( public_key_buffer == NULL)
return( PSA_ERROR_INSUFFICIENT_MEMORY );
status = p256m_to_psa_error(
p256_gen_keypair(key_buffer, public_key_buffer) );
if( status == PSA_SUCCESS )
*key_buffer_length = 32;
/*
* The storage format for a SECP256R1 keypair is just the private key, so
* the public key does not need to be passed back to the caller. Therefore
* the buffer containing it can be freed. */
free( public_key_buffer );
return status;
}
psa_status_t p256m_transparent_key_agreement(
const psa_key_attributes_t *attributes,
const uint8_t *key_buffer,
size_t key_buffer_size,
psa_algorithm_t alg,
const uint8_t *peer_key,
size_t peer_key_length,
uint8_t *shared_secret,
size_t shared_secret_size,
size_t *shared_secret_length )
{
/* We don't use these arguments, but the specification mandates the
* sginature of driver entry-points. (void) used to avoid compiler
* warning. */
(void) attributes;
(void) alg;
/*
* Check that private key = 32 bytes, peer public key = 65 bytes,
* and that the shared secret buffer is big enough. */
psa_status_t status = PSA_ERROR_NOT_SUPPORTED;
if( key_buffer_size != 32 || shared_secret_size < 32 ||
peer_key_length != 65 )
return ( status );
status = p256m_to_psa_error(
p256_ecdh_shared_secret(shared_secret, key_buffer, peer_key+1) );
if( status == PSA_SUCCESS )
*shared_secret_length = 32;
return status;
}
psa_status_t p256m_transparent_sign_hash(
const psa_key_attributes_t *attributes,
const uint8_t *key_buffer,
size_t key_buffer_size,
psa_algorithm_t alg,
const uint8_t *hash,
size_t hash_length,
uint8_t *signature,
size_t signature_size,
size_t *signature_length )
{
/* We don't use these arguments, but the specification mandates the
* sginature of driver entry-points. (void) used to avoid compiler
* warning. */
(void) attributes;
(void) alg;
psa_status_t status = PSA_ERROR_NOT_SUPPORTED;
if( key_buffer_size != 32 || signature_size != 64)
return( status );
status = p256m_to_psa_error(
p256_ecdsa_sign(signature, key_buffer, hash, hash_length) );
if( status == PSA_SUCCESS )
*signature_length = 64;
return status;
}
/* This function expects the key buffer to contain a 65 byte public key,
* as exported by psa_export_public_key() */
static psa_status_t p256m_verify_hash_with_public_key(
const uint8_t *key_buffer,
size_t key_buffer_size,
const uint8_t *hash,
size_t hash_length,
const uint8_t *signature,
size_t signature_length )
{
psa_status_t status = PSA_ERROR_NOT_SUPPORTED;
if( key_buffer_size != 65 || signature_length != 64 || *key_buffer != 0x04 )
return status;
const uint8_t *public_key_buffer = key_buffer + 1;
status = p256m_to_psa_error(
p256_ecdsa_verify( signature, public_key_buffer, hash, hash_length) );
return status;
}
psa_status_t p256m_transparent_verify_hash(
const psa_key_attributes_t *attributes,
const uint8_t *key_buffer,
size_t key_buffer_size,
psa_algorithm_t alg,
const uint8_t *hash,
size_t hash_length,
const uint8_t *signature,
size_t signature_length )
{
/* We don't use this argument, but the specification mandates the signature
* of driver entry-points. (void) used to avoid compiler warning. */
(void) alg;
psa_status_t status;
uint8_t *public_key_buffer = NULL;
size_t public_key_buffer_size = 65;
public_key_buffer = mbedtls_calloc( 1, public_key_buffer_size);
if( public_key_buffer == NULL)
return( PSA_ERROR_INSUFFICIENT_MEMORY );
size_t *public_key_length = NULL;
public_key_length = mbedtls_calloc( 1, sizeof(size_t) );
if( public_key_length == NULL)
return( PSA_ERROR_INSUFFICIENT_MEMORY );
*public_key_length = 65;
/* The contents of key_buffer may either be the 32 byte private key
* (keypair representation), or the 65 byte public key. To ensure the
* latter is obtained, the public key is exported. */
status = psa_driver_wrapper_export_public_key(
attributes,
key_buffer,
key_buffer_size,
public_key_buffer,
public_key_buffer_size,
public_key_length );
if( status != PSA_SUCCESS )
goto exit;
status = p256m_verify_hash_with_public_key(
public_key_buffer,
public_key_buffer_size,
hash,
hash_length,
signature,
signature_length );
exit:
free( public_key_buffer );
free( public_key_length );
return ( status );
}
#endif /* MBEDTLS_P256M_EXAMPLE_DRIVER_ENABLED */

View file

@ -0,0 +1,155 @@
#ifndef P256M_DRIVER_ENTRYPOINTS_H
#define P256M_DRIVER_ENTRYPOINTS_H
#if defined(MBEDTLS_P256M_EXAMPLE_DRIVER_ENABLED)
#ifndef PSA_CRYPTO_ACCELERATOR_DRIVER_PRESENT
#define PSA_CRYPTO_ACCELERATOR_DRIVER_PRESENT
#endif /* PSA_CRYPTO_ACCELERATOR_DRIVER_PRESENT */
#endif /* MBEDTLS_P256M_EXAMPLE_DRIVER_ENABLED */
#include "psa/crypto_types.h"
/** Convert an internal p256-m error code to a PSA error code
*
* \param ret An error code thrown by p256-m
*
* \return The corresponding PSA error code
*/
//no-check-names
psa_status_t p256m_to_psa_error( int ret );
/** Generate SECP256R1 ECC Key Pair.
* Interface function which calls the p256-m key generation function and
* places it in the key buffer provided by the caller (mbed TLS) in the
* correct format. For a SECP256R1 curve this is the 32 bit private key.
*
* \param[in] attributes The attributes of the key to use for the
* operation.
* \param[out] key_buffer The buffer to contain the key data in
* output format upon successful return.
* \param[in] key_buffer_size Size of the \p key_buffer buffer in bytes.
* \param[out] key_buffer_length The length of the data written in \p
* key_buffer in bytes.
*
* \retval #PSA_SUCCESS
* Success. Keypair generated and stored in buffer.
* \retval #PSA_ERROR_NOT_SUPPORTED
* \retval #PSA_ERROR_GENERIC_ERROR
* \retval #PSA_ERROR_INSUFFICIENT_MEMORY
*/
//no-check-names
psa_status_t p256m_transparent_generate_key(
const psa_key_attributes_t *attributes,
uint8_t *key_buffer,
size_t key_buffer_size,
size_t *key_buffer_length );
/** Perform raw key agreement using p256-m's ECDH implementation
* \param[in] attributes The attributes of the key to use for the
* operation.
* \param[in] key_buffer The buffer containing the private key
* in the format specified by PSA.
* \param[in] key_buffer_size Size of the \p key_buffer buffer in bytes.
* \param[in] alg A key agreement algorithm that is
* compatible with the type of the key.
* \param[in] peer_key The buffer containing the peer's public
* key in format specified by PSA.
* \param[in] peer_key_length Size of the \p peer_key buffer in
* bytes.
* \param[out] shared_secret The buffer to which the shared secret
* is to be written.
* \param[in] shared_secret_size Size of the \p shared_secret buffer in
* bytes.
* \param[out] shared_secret_length On success, the number of bytes that
* make up the returned shared secret.
* \retval #PSA_SUCCESS
* Success. Shared secret successfully calculated.
* \retval #PSA_ERROR_NOT_SUPPORTED
*/
//no-check-names
psa_status_t p256m_transparent_key_agreement(
const psa_key_attributes_t *attributes,
const uint8_t *key_buffer,
size_t key_buffer_size,
psa_algorithm_t alg,
const uint8_t *peer_key,
size_t peer_key_length,
uint8_t *shared_secret,
size_t shared_secret_size,
size_t *shared_secret_length );
/** Sign an already-calculated hash with a private key using p256-m's ECDSA
* implementation
* \param[in] attributes The attributes of the key to use for the
* operation.
* \param[in] key_buffer The buffer containing the private key
* in the format specified by PSA.
* \param[in] key_buffer_size Size of the \p key_buffer buffer in bytes.
* \param[in] alg A signature algorithm that is compatible
* with the type of the key.
* \param[in] hash The hash to sign.
* \param[in] hash_length Size of the \p hash buffer in bytes.
* \param[out] signature Buffer where signature is to be written.
* \param[in] signature_size Size of the \p signature buffer in bytes.
* \param[out] signature_length On success, the number of bytes
* that make up the returned signature value.
*
* \retval #PSA_SUCCESS
* Success. Hash was signed successfully.
* respectively of the key.
* \retval #PSA_ERROR_NOT_SUPPORTED
*/
//no-check-names
psa_status_t p256m_transparent_sign_hash(
const psa_key_attributes_t *attributes,
const uint8_t *key_buffer,
size_t key_buffer_size,
psa_algorithm_t alg,
const uint8_t *hash,
size_t hash_length,
uint8_t *signature,
size_t signature_size,
size_t *signature_length );
/** Verify the signature of a hash using a SECP256R1 public key using p256-m's
* ECDSA implementation.
*
* \note p256-m expects a 64 byte public key, but the contents of the key
buffer may be the 32 byte keypair representation or the 65 byte
public key representation. As a result, this function calls
psa_driver_wrapper_export_public_key() to ensure the public key
can be passed to p256-m.
*
* \param[in] attributes The attributes of the key to use for the
* operation.
*
* \param[in] key_buffer The buffer containing the key
* in the format specified by PSA.
* \param[in] key_buffer_size Size of the \p key_buffer buffer in bytes.
* \param[in] alg A signature algorithm that is compatible with
* the type of the key.
* \param[in] hash The hash whose signature is to be
* verified.
* \param[in] hash_length Size of the \p hash buffer in bytes.
* \param[in] signature Buffer containing the signature to verify.
* \param[in] signature_length Size of the \p signature buffer in bytes.
*
* \retval #PSA_SUCCESS
* The signature is valid.
* \retval #PSA_ERROR_INVALID_SIGNATURE
* The calculation was performed successfully, but the passed
* signature is not a valid signature.
* \retval #PSA_ERROR_NOT_SUPPORTED
*/
psa_status_t p256m_transparent_verify_hash(
const psa_key_attributes_t *attributes,
const uint8_t *key_buffer,
size_t key_buffer_size,
psa_algorithm_t alg,
const uint8_t *hash,
size_t hash_length,
const uint8_t *signature,
size_t signature_length );
#endif /* P256M_DRIVER_ENTRYPOINTS_H */

View file

@ -0,0 +1,74 @@
# PSA Cryptoprocessor driver development examples
As of Mbed TLS 3.3.0, the PSA Driver Interface has only been partially implemented. As a result, the deliverables for writing a driver and the method for integrating a driver with Mbed TLS will vary depending on the operation being accelerated. This document describes how to write and integrate cryptoprocessor drivers depending on which operation or driver type is being implemented.
The `docs/proposed/` directory contains three documents which pertain to the proposed, work-in-progress driver system. The [PSA Driver Interface](https://github.com/Mbed-TLS/mbedtls/blob/development/docs/proposed/psa-driver-interface.md) describes how drivers will interface with Mbed TLS in the future, as well as driver types, operation types, and entry points. As many key terms and concepts used in the examples in this document are defined in the PSA Driver Interface, it is recommended that developers read it prior to starting work on implementing drivers.
The PSA Driver [Developer](https://github.com/Mbed-TLS/mbedtls/blob/development/docs/proposed/psa-driver-developer-guide.md) Guide describes the deliverables for writing a driver that can be used with Mbed TLS, and the PSA Driver [Integration](https://github.com/Mbed-TLS/mbedtls/blob/development/docs/proposed/psa-driver-integration-guide.md) Guide describes how a driver can be built alongside Mbed TLS.
## Background on how Mbed TLS calls drivers
The PSA Driver Interface specification specifies which cryptographic operations can be accelerated by third-party drivers. Operations that are completed within one step (one function call), such as verifying a signature, are called *Single-Part Operations*. On the other hand, operations that consist of multiple steps implemented by different functions called sequentially are called *Multi-Part Operations*. Single-part operations implemented by a driver will have one entry point, while multi-part operations will have multiple: one for each step.
There are two types of drivers: *transparent* or *opaque*. See below an excerpt from the PSA Driver Interface specification defining them:
* **Transparent** drivers implement cryptographic operations on keys that are provided in cleartext at the beginning of each operation. They are typically used for hardware **accelerators**. When a transparent driver is available for a particular combination of parameters (cryptographic algorithm, key type and size, etc.), it is used instead of the default software implementation. Transparent drivers can also be pure software implementations that are distributed as plug-ins to a PSA Cryptography implementation (for example, an alternative implementation with different performance characteristics, or a certified implementation).
* **Opaque** drivers implement cryptographic operations on keys that can only be used inside a protected environment such as a **secure element**, a hardware security module, a smartcard, a secure enclave, etc. An opaque driver is invoked for the specific [key location](https://github.com/Mbed-TLS/mbedtls/blob/development/docs/proposed/psa-driver-interface.md#lifetimes-and-locations) that the driver is registered for: the dispatch is based on the key's lifetime.
Mbed TLS contains a **driver dispatch layer** (also called a driver wrapper layer). For each cryptographic operation that supports driver acceleration (or sub-part of a multi-part operation), the library calls the corresponding function in the driver wrapper. Using flags set at compile time, the driver wrapper ascertains whether any present drivers support the operation. When no such driver is present, the built-in library implementation is called as a fallback (if allowed). When a compatible driver is present, the driver wrapper calls the driver entry point function provided by the driver author.
The long-term goal is for the driver dispatch layer to be auto-generated using a JSON driver description file provided by the driver author.
For some cryptographic operations, this auto-generation logic has already been implemented. When accelerating these operations, the instructions in the above documents can be followed. For the remaining operations which do not yet support auto-generation of the driver wrapper, developers will have to manually edit the driver dispatch layer and call their driver's entry point functions from there.
Auto-generation of the driver wrapper is supported for the operation entry points specified in the table below. Certain operations are only permitted for opaque drivers. All other operation entry points do not support auto-generation of the driver wrapper.
| Transparent Driver | Opaque Driver |
|---------------------|---------------------|
| `import_key` | `import_key` |
| `export_key` | `export_key` |
| `export_public_key` | `export_public_key` |
| | `copy_key` |
| | `get_builtin_key` |
### Process for Entry Points where auto-generation is implemented
If the driver is accelerating operations whose entry points are in the above table, the instructions in the driver [developer](https://github.com/Mbed-TLS/mbedtls/blob/development/docs/proposed/psa-driver-developer-guide.md) and [integration](https://github.com/Mbed-TLS/mbedtls/blob/development/docs/proposed/psa-driver-integration-guide.md) guides should be followed.
**TODO: Provide brief summary of the method using the Mbed TLS test driver as an example**
### Process for Entry Points where auto-generation is not implemented
If the driver is accelerating operations whose entry points are not present in the table, a different process is followed where the developer manually edits the driver dispatch layer. In general, the following steps must be taken **for each single-part operation** or **for each sub-part of a multi-part operation**:
**1. Choose a driver prefix and a macro name that indicates whether the driver is enabled** \
A driver prefix is simply a word (often the name of the driver) that all functions/macros associated with the driver should begin with. This is similar to how most functions/macros in Mbed TLS begin with `PSA_XXX/psa_xx` or `MBEDTLS_XXX/mbedtls_xxx`. The macro name can follow the form `DRIVER_PREFIX_ENABLED` or something similar; it will be used to indicate the driver is available to be called. When building with the driver present, define this macro at compile time. For example, when using `make`, this is done using the `-D` flag.
**2. Locate the function in the driver dispatch layer that corresponds to the entry point of the operation being accelerated.** \
The file `psa_crypto_driver_wrappers.c.jinja` contains the driver wrapper functions. For the entry points that have driver wrapper auto-generation implemented, the functions have been replaced with `jinja` templating logic. While the file has a `.jinja` extension, the driver wrapper functions for the remaining entry points are simple C functions. The names of these functions are of the form `psa_driver_wrapper` followed by the entry point name. So, for example, the function `psa_driver_wrapper_sign_hash()` corresponds to the `sign_hash` entry point.
**3. If a driver entry point function has been provided then ensure it has the same signature as the driver wrapper function.** \
If one has not been provided then write one. Its name should begin with the driver prefix, followed by transparent/opaque (depending on driver type), and end with the entry point name. It should have the same signature as the driver wrapper function. The purpose of the entry point function is to take arguments in PSA format for the implemented operation and return outputs/status codes in PSA format.
**4. Include the following in one of the driver header files:**
```
#if defined(DRIVER_PREFIX_ENABLED)
#ifndef PSA_CRYPTO_ACCELERATOR_DRIVER_PRESENT
#define PSA_CRYPTO_ACCELERATOR_DRIVER_PRESENT
#endif
```
**5. Conditionally include header files required by the driver**
Include any header files required by the driver in `psa_crypto_driver_wrappers.h`, placing the `#include` statements within an `#if defined` block which checks if the driver is available:
```
#if defined(DRIVER_PREFIX_ENABLED)
#include ...
#endif
```
**6. Modify the driver wrapper function** \
Each driver wrapper function contains a `switch` statement which checks the location of the key. If the key is stored in local storage, then operations are performed by a transparent driver. If it is stored elsewhere, then operations are performed by an opaque driver.
* **Transparent drivers:** Calls to drivers go under `case PSA_KEY_LOCATION_LOCAL_STORAGE`
<!-- the developer must manually edit the driver dispatch layer such that it first checks for the presence of the driver, and its compatibility with operation parameters (such as key type, algorithm type etc.). If the checks are passed, the driver's entry point function for that operation is called. The specification for the signature of entry point functions can be found [here](https://github.com/Mbed-TLS/mbedtls/blob/development/docs/proposed/psa-driver-interface.md#overview-of-driver-entry-points), but as a rule of thumb the signature for the driver entry point for an operation will be the same as the signature of its driver wrapper function. -->

View file

@ -3919,4 +3919,16 @@
*/ */
//#define MBEDTLS_ECDH_VARIANT_EVEREST_ENABLED //#define MBEDTLS_ECDH_VARIANT_EVEREST_ENABLED
/**
* Uncomment to enable p256-m, which implements ECC key generation, ECDH,
* and ECDSA for SECP256R1 curves. This driver is used as an example to
* document how a third-party driver or software accelerator can be integrated
* to work alongside Mbed TLS.
*
* \warning As of now, the built-in RNG for p256-m depends on rand(). This is
* fine for examples, but not in production.
* DO NOT ENABLE/USE THIS MACRO IN PRODUCTION BUILDS!
*/
//#define MBEDTLS_P256M_EXAMPLE_DRIVER_ENABLED
/** \} name SECTION: Module configuration options */ /** \} name SECTION: Module configuration options */

View file

@ -24,6 +24,10 @@
#include "psa/crypto.h" #include "psa/crypto.h"
#include "psa/crypto_driver_common.h" #include "psa/crypto_driver_common.h"
#if defined(MBEDTLS_P256M_EXAMPLE_DRIVER_ENABLED)
#include "../3rdparty/p256-m/p256-m_driver_entrypoints.h"
#endif /* MBEDTLS_P256M_EXAMPLE_DRIVER_ENABLED */
/* /*
* Initialization and termination functions * Initialization and termination functions
*/ */

View file

@ -216,6 +216,7 @@ EXCLUDE_FROM_FULL = frozenset([
'MBEDTLS_TEST_CONSTANT_FLOW_VALGRIND', # build dependency (valgrind headers) 'MBEDTLS_TEST_CONSTANT_FLOW_VALGRIND', # build dependency (valgrind headers)
'MBEDTLS_X509_REMOVE_INFO', # removes a feature 'MBEDTLS_X509_REMOVE_INFO', # removes a feature
'MBEDTLS_SSL_RECORD_SIZE_LIMIT', # in development, currently breaks other tests 'MBEDTLS_SSL_RECORD_SIZE_LIMIT', # in development, currently breaks other tests
'MBEDTLS_P256M_EXAMPLE_DRIVER_ENABLED' # influences SECP256R1 KeyGen/ECDH/ECDSA
]) ])
def is_seamless_alt(name): def is_seamless_alt(name):

View file

@ -316,6 +316,26 @@ psa_status_t psa_driver_wrapper_sign_hash(
if( status != PSA_ERROR_NOT_SUPPORTED ) if( status != PSA_ERROR_NOT_SUPPORTED )
return( status ); return( status );
#endif /* PSA_CRYPTO_DRIVER_TEST */ #endif /* PSA_CRYPTO_DRIVER_TEST */
#if defined (MBEDTLS_P256M_EXAMPLE_DRIVER_ENABLED)
if( PSA_KEY_TYPE_IS_ECC( attributes->core.type ) &&
PSA_ALG_IS_ECDSA(alg) &&
!PSA_ALG_ECDSA_IS_DETERMINISTIC( alg ) &&
PSA_KEY_TYPE_ECC_GET_FAMILY(attributes->core.type) == PSA_ECC_FAMILY_SECP_R1 &&
attributes->core.bits == 256 )
{
status = p256m_transparent_sign_hash( attributes,
key_buffer,
key_buffer_size,
alg,
hash,
hash_length,
signature,
signature_size,
signature_length );
if( status != PSA_ERROR_NOT_SUPPORTED )
return( status );
}
#endif /* MBEDTLS_P256M_EXAMPLE_DRIVER_ENABLED */
#endif /* PSA_CRYPTO_ACCELERATOR_DRIVER_PRESENT */ #endif /* PSA_CRYPTO_ACCELERATOR_DRIVER_PRESENT */
/* Fell through, meaning no accelerator supports this operation */ /* Fell through, meaning no accelerator supports this operation */
return( psa_sign_hash_builtin( attributes, return( psa_sign_hash_builtin( attributes,
@ -400,6 +420,25 @@ psa_status_t psa_driver_wrapper_verify_hash(
if( status != PSA_ERROR_NOT_SUPPORTED ) if( status != PSA_ERROR_NOT_SUPPORTED )
return( status ); return( status );
#endif /* PSA_CRYPTO_DRIVER_TEST */ #endif /* PSA_CRYPTO_DRIVER_TEST */
#if defined (MBEDTLS_P256M_EXAMPLE_DRIVER_ENABLED)
if( PSA_KEY_TYPE_IS_ECC( attributes->core.type ) &&
PSA_ALG_IS_ECDSA(alg) &&
!PSA_ALG_ECDSA_IS_DETERMINISTIC( alg ) &&
PSA_KEY_TYPE_ECC_GET_FAMILY(attributes->core.type) == PSA_ECC_FAMILY_SECP_R1 &&
attributes->core.bits == 256 )
{
status = p256m_transparent_verify_hash( attributes,
key_buffer,
key_buffer_size,
alg,
hash,
hash_length,
signature,
signature_length );
if( status != PSA_ERROR_NOT_SUPPORTED )
return( status );
}
#endif /* MBEDTLS_P256M_EXAMPLE_DRIVER_ENABLED */
#endif /* PSA_CRYPTO_ACCELERATOR_DRIVER_PRESENT */ #endif /* PSA_CRYPTO_ACCELERATOR_DRIVER_PRESENT */
return( psa_verify_hash_builtin( attributes, return( psa_verify_hash_builtin( attributes,
@ -814,6 +853,20 @@ psa_status_t psa_driver_wrapper_generate_key(
if( status != PSA_ERROR_NOT_SUPPORTED ) if( status != PSA_ERROR_NOT_SUPPORTED )
break; break;
#endif /* PSA_CRYPTO_DRIVER_TEST */ #endif /* PSA_CRYPTO_DRIVER_TEST */
#if defined(MBEDTLS_P256M_EXAMPLE_DRIVER_ENABLED)
if( PSA_KEY_TYPE_IS_ECC( attributes->core.type ) &&
attributes->core.type == PSA_KEY_TYPE_ECC_KEY_PAIR(PSA_ECC_FAMILY_SECP_R1) &&
attributes->core.bits == 256 )
{
status = p256m_transparent_generate_key( attributes,
key_buffer,
key_buffer_size,
key_buffer_length );
if( status != PSA_ERROR_NOT_SUPPORTED )
break;
}
#endif /* MBEDTLS_P256M_EXAMPLE_DRIVER_ENABLED */
} }
#endif /* PSA_CRYPTO_ACCELERATOR_DRIVER_PRESENT */ #endif /* PSA_CRYPTO_ACCELERATOR_DRIVER_PRESENT */
@ -2752,6 +2805,25 @@ psa_status_t psa_driver_wrapper_key_agreement(
if( status != PSA_ERROR_NOT_SUPPORTED ) if( status != PSA_ERROR_NOT_SUPPORTED )
return( status ); return( status );
#endif /* PSA_CRYPTO_DRIVER_TEST */ #endif /* PSA_CRYPTO_DRIVER_TEST */
#if defined(MBEDTLS_P256M_EXAMPLE_DRIVER_ENABLED)
if( PSA_KEY_TYPE_IS_ECC( attributes->core.type ) &&
PSA_ALG_IS_ECDH(alg) &&
PSA_KEY_TYPE_ECC_GET_FAMILY(attributes->core.type) == PSA_ECC_FAMILY_SECP_R1 &&
attributes->core.bits == 256 )
{
status = p256m_transparent_key_agreement( attributes,
key_buffer,
key_buffer_size,
alg,
peer_key,
peer_key_length,
shared_secret,
shared_secret_size,
shared_secret_length );
if( status != PSA_ERROR_NOT_SUPPORTED)
return( status );
}
#endif /* MBEDTLS_P256M_EXAMPLE_DRIVER_ENABLED */
#endif /* PSA_CRYPTO_ACCELERATOR_DRIVER_PRESENT */ #endif /* PSA_CRYPTO_ACCELERATOR_DRIVER_PRESENT */
/* Software Fallback */ /* Software Fallback */