Unnamed: 0
int64 0
0
| repo_id
stringlengths 5
186
| file_path
stringlengths 15
223
| content
stringlengths 1
32.8M
⌀ |
---|---|---|---|
0 | repos/gpt4all.zig/src/zig-libcurl/zig-mbedtls/mbedtls | repos/gpt4all.zig/src/zig-libcurl/zig-mbedtls/mbedtls/library/pkparse.c | /*
* Public Key layer for parsing key files and structures
*
* Copyright The Mbed TLS Contributors
* SPDX-License-Identifier: Apache-2.0
*
* 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.
*/
#include "common.h"
#if defined(MBEDTLS_PK_PARSE_C)
#include "mbedtls/pk.h"
#include "mbedtls/asn1.h"
#include "mbedtls/oid.h"
#include "mbedtls/platform_util.h"
#include "mbedtls/error.h"
#include <string.h>
#if defined(MBEDTLS_RSA_C)
#include "mbedtls/rsa.h"
#endif
#if defined(MBEDTLS_ECP_C)
#include "mbedtls/ecp.h"
#endif
#if defined(MBEDTLS_ECDSA_C)
#include "mbedtls/ecdsa.h"
#endif
#if defined(MBEDTLS_PEM_PARSE_C)
#include "mbedtls/pem.h"
#endif
#if defined(MBEDTLS_PKCS5_C)
#include "mbedtls/pkcs5.h"
#endif
#if defined(MBEDTLS_PKCS12_C)
#include "mbedtls/pkcs12.h"
#endif
#if defined(MBEDTLS_PLATFORM_C)
#include "mbedtls/platform.h"
#else
#include <stdlib.h>
#define mbedtls_calloc calloc
#define mbedtls_free free
#endif
/* Parameter validation macros based on platform_util.h */
#define PK_VALIDATE_RET( cond ) \
MBEDTLS_INTERNAL_VALIDATE_RET( cond, MBEDTLS_ERR_PK_BAD_INPUT_DATA )
#define PK_VALIDATE( cond ) \
MBEDTLS_INTERNAL_VALIDATE( cond )
#if defined(MBEDTLS_FS_IO)
/*
* Load all data from a file into a given buffer.
*
* The file is expected to contain either PEM or DER encoded data.
* A terminating null byte is always appended. It is included in the announced
* length only if the data looks like it is PEM encoded.
*/
int mbedtls_pk_load_file( const char *path, unsigned char **buf, size_t *n )
{
FILE *f;
long size;
PK_VALIDATE_RET( path != NULL );
PK_VALIDATE_RET( buf != NULL );
PK_VALIDATE_RET( n != NULL );
if( ( f = fopen( path, "rb" ) ) == NULL )
return( MBEDTLS_ERR_PK_FILE_IO_ERROR );
fseek( f, 0, SEEK_END );
if( ( size = ftell( f ) ) == -1 )
{
fclose( f );
return( MBEDTLS_ERR_PK_FILE_IO_ERROR );
}
fseek( f, 0, SEEK_SET );
*n = (size_t) size;
if( *n + 1 == 0 ||
( *buf = mbedtls_calloc( 1, *n + 1 ) ) == NULL )
{
fclose( f );
return( MBEDTLS_ERR_PK_ALLOC_FAILED );
}
if( fread( *buf, 1, *n, f ) != *n )
{
fclose( f );
mbedtls_platform_zeroize( *buf, *n );
mbedtls_free( *buf );
return( MBEDTLS_ERR_PK_FILE_IO_ERROR );
}
fclose( f );
(*buf)[*n] = '\0';
if( strstr( (const char *) *buf, "-----BEGIN " ) != NULL )
++*n;
return( 0 );
}
/*
* Load and parse a private key
*/
int mbedtls_pk_parse_keyfile( mbedtls_pk_context *ctx,
const char *path, const char *pwd )
{
int ret = MBEDTLS_ERR_ERROR_CORRUPTION_DETECTED;
size_t n;
unsigned char *buf;
PK_VALIDATE_RET( ctx != NULL );
PK_VALIDATE_RET( path != NULL );
if( ( ret = mbedtls_pk_load_file( path, &buf, &n ) ) != 0 )
return( ret );
if( pwd == NULL )
ret = mbedtls_pk_parse_key( ctx, buf, n, NULL, 0 );
else
ret = mbedtls_pk_parse_key( ctx, buf, n,
(const unsigned char *) pwd, strlen( pwd ) );
mbedtls_platform_zeroize( buf, n );
mbedtls_free( buf );
return( ret );
}
/*
* Load and parse a public key
*/
int mbedtls_pk_parse_public_keyfile( mbedtls_pk_context *ctx, const char *path )
{
int ret = MBEDTLS_ERR_ERROR_CORRUPTION_DETECTED;
size_t n;
unsigned char *buf;
PK_VALIDATE_RET( ctx != NULL );
PK_VALIDATE_RET( path != NULL );
if( ( ret = mbedtls_pk_load_file( path, &buf, &n ) ) != 0 )
return( ret );
ret = mbedtls_pk_parse_public_key( ctx, buf, n );
mbedtls_platform_zeroize( buf, n );
mbedtls_free( buf );
return( ret );
}
#endif /* MBEDTLS_FS_IO */
#if defined(MBEDTLS_ECP_C)
/* Minimally parse an ECParameters buffer to and mbedtls_asn1_buf
*
* ECParameters ::= CHOICE {
* namedCurve OBJECT IDENTIFIER
* specifiedCurve SpecifiedECDomain -- = SEQUENCE { ... }
* -- implicitCurve NULL
* }
*/
static int pk_get_ecparams( unsigned char **p, const unsigned char *end,
mbedtls_asn1_buf *params )
{
int ret = MBEDTLS_ERR_ERROR_CORRUPTION_DETECTED;
if ( end - *p < 1 )
return( MBEDTLS_ERROR_ADD( MBEDTLS_ERR_PK_KEY_INVALID_FORMAT,
MBEDTLS_ERR_ASN1_OUT_OF_DATA ) );
/* Tag may be either OID or SEQUENCE */
params->tag = **p;
if( params->tag != MBEDTLS_ASN1_OID
#if defined(MBEDTLS_PK_PARSE_EC_EXTENDED)
&& params->tag != ( MBEDTLS_ASN1_CONSTRUCTED | MBEDTLS_ASN1_SEQUENCE )
#endif
)
{
return( MBEDTLS_ERROR_ADD( MBEDTLS_ERR_PK_KEY_INVALID_FORMAT,
MBEDTLS_ERR_ASN1_UNEXPECTED_TAG ) );
}
if( ( ret = mbedtls_asn1_get_tag( p, end, ¶ms->len, params->tag ) ) != 0 )
{
return( MBEDTLS_ERROR_ADD( MBEDTLS_ERR_PK_KEY_INVALID_FORMAT, ret ) );
}
params->p = *p;
*p += params->len;
if( *p != end )
return( MBEDTLS_ERROR_ADD( MBEDTLS_ERR_PK_KEY_INVALID_FORMAT,
MBEDTLS_ERR_ASN1_LENGTH_MISMATCH ) );
return( 0 );
}
#if defined(MBEDTLS_PK_PARSE_EC_EXTENDED)
/*
* Parse a SpecifiedECDomain (SEC 1 C.2) and (mostly) fill the group with it.
* WARNING: the resulting group should only be used with
* pk_group_id_from_specified(), since its base point may not be set correctly
* if it was encoded compressed.
*
* SpecifiedECDomain ::= SEQUENCE {
* version SpecifiedECDomainVersion(ecdpVer1 | ecdpVer2 | ecdpVer3, ...),
* fieldID FieldID {{FieldTypes}},
* curve Curve,
* base ECPoint,
* order INTEGER,
* cofactor INTEGER OPTIONAL,
* hash HashAlgorithm OPTIONAL,
* ...
* }
*
* We only support prime-field as field type, and ignore hash and cofactor.
*/
static int pk_group_from_specified( const mbedtls_asn1_buf *params, mbedtls_ecp_group *grp )
{
int ret = MBEDTLS_ERR_ERROR_CORRUPTION_DETECTED;
unsigned char *p = params->p;
const unsigned char * const end = params->p + params->len;
const unsigned char *end_field, *end_curve;
size_t len;
int ver;
/* SpecifiedECDomainVersion ::= INTEGER { 1, 2, 3 } */
if( ( ret = mbedtls_asn1_get_int( &p, end, &ver ) ) != 0 )
return( MBEDTLS_ERROR_ADD( MBEDTLS_ERR_PK_KEY_INVALID_FORMAT, ret ) );
if( ver < 1 || ver > 3 )
return( MBEDTLS_ERR_PK_KEY_INVALID_FORMAT );
/*
* FieldID { FIELD-ID:IOSet } ::= SEQUENCE { -- Finite field
* fieldType FIELD-ID.&id({IOSet}),
* parameters FIELD-ID.&Type({IOSet}{@fieldType})
* }
*/
if( ( ret = mbedtls_asn1_get_tag( &p, end, &len,
MBEDTLS_ASN1_CONSTRUCTED | MBEDTLS_ASN1_SEQUENCE ) ) != 0 )
return( ret );
end_field = p + len;
/*
* FIELD-ID ::= TYPE-IDENTIFIER
* FieldTypes FIELD-ID ::= {
* { Prime-p IDENTIFIED BY prime-field } |
* { Characteristic-two IDENTIFIED BY characteristic-two-field }
* }
* prime-field OBJECT IDENTIFIER ::= { id-fieldType 1 }
*/
if( ( ret = mbedtls_asn1_get_tag( &p, end_field, &len, MBEDTLS_ASN1_OID ) ) != 0 )
return( ret );
if( len != MBEDTLS_OID_SIZE( MBEDTLS_OID_ANSI_X9_62_PRIME_FIELD ) ||
memcmp( p, MBEDTLS_OID_ANSI_X9_62_PRIME_FIELD, len ) != 0 )
{
return( MBEDTLS_ERR_PK_FEATURE_UNAVAILABLE );
}
p += len;
/* Prime-p ::= INTEGER -- Field of size p. */
if( ( ret = mbedtls_asn1_get_mpi( &p, end_field, &grp->P ) ) != 0 )
return( MBEDTLS_ERROR_ADD( MBEDTLS_ERR_PK_KEY_INVALID_FORMAT, ret ) );
grp->pbits = mbedtls_mpi_bitlen( &grp->P );
if( p != end_field )
return( MBEDTLS_ERROR_ADD( MBEDTLS_ERR_PK_KEY_INVALID_FORMAT,
MBEDTLS_ERR_ASN1_LENGTH_MISMATCH ) );
/*
* Curve ::= SEQUENCE {
* a FieldElement,
* b FieldElement,
* seed BIT STRING OPTIONAL
* -- Shall be present if used in SpecifiedECDomain
* -- with version equal to ecdpVer2 or ecdpVer3
* }
*/
if( ( ret = mbedtls_asn1_get_tag( &p, end, &len,
MBEDTLS_ASN1_CONSTRUCTED | MBEDTLS_ASN1_SEQUENCE ) ) != 0 )
return( ret );
end_curve = p + len;
/*
* FieldElement ::= OCTET STRING
* containing an integer in the case of a prime field
*/
if( ( ret = mbedtls_asn1_get_tag( &p, end_curve, &len, MBEDTLS_ASN1_OCTET_STRING ) ) != 0 ||
( ret = mbedtls_mpi_read_binary( &grp->A, p, len ) ) != 0 )
{
return( MBEDTLS_ERROR_ADD( MBEDTLS_ERR_PK_KEY_INVALID_FORMAT, ret ) );
}
p += len;
if( ( ret = mbedtls_asn1_get_tag( &p, end_curve, &len, MBEDTLS_ASN1_OCTET_STRING ) ) != 0 ||
( ret = mbedtls_mpi_read_binary( &grp->B, p, len ) ) != 0 )
{
return( MBEDTLS_ERROR_ADD( MBEDTLS_ERR_PK_KEY_INVALID_FORMAT, ret ) );
}
p += len;
/* Ignore seed BIT STRING OPTIONAL */
if( ( ret = mbedtls_asn1_get_tag( &p, end_curve, &len, MBEDTLS_ASN1_BIT_STRING ) ) == 0 )
p += len;
if( p != end_curve )
return( MBEDTLS_ERROR_ADD( MBEDTLS_ERR_PK_KEY_INVALID_FORMAT,
MBEDTLS_ERR_ASN1_LENGTH_MISMATCH ) );
/*
* ECPoint ::= OCTET STRING
*/
if( ( ret = mbedtls_asn1_get_tag( &p, end, &len, MBEDTLS_ASN1_OCTET_STRING ) ) != 0 )
return( MBEDTLS_ERROR_ADD( MBEDTLS_ERR_PK_KEY_INVALID_FORMAT, ret ) );
if( ( ret = mbedtls_ecp_point_read_binary( grp, &grp->G,
( const unsigned char *) p, len ) ) != 0 )
{
/*
* If we can't read the point because it's compressed, cheat by
* reading only the X coordinate and the parity bit of Y.
*/
if( ret != MBEDTLS_ERR_ECP_FEATURE_UNAVAILABLE ||
( p[0] != 0x02 && p[0] != 0x03 ) ||
len != mbedtls_mpi_size( &grp->P ) + 1 ||
mbedtls_mpi_read_binary( &grp->G.X, p + 1, len - 1 ) != 0 ||
mbedtls_mpi_lset( &grp->G.Y, p[0] - 2 ) != 0 ||
mbedtls_mpi_lset( &grp->G.Z, 1 ) != 0 )
{
return( MBEDTLS_ERR_PK_KEY_INVALID_FORMAT );
}
}
p += len;
/*
* order INTEGER
*/
if( ( ret = mbedtls_asn1_get_mpi( &p, end, &grp->N ) ) != 0 )
return( MBEDTLS_ERROR_ADD( MBEDTLS_ERR_PK_KEY_INVALID_FORMAT, ret ) );
grp->nbits = mbedtls_mpi_bitlen( &grp->N );
/*
* Allow optional elements by purposefully not enforcing p == end here.
*/
return( 0 );
}
/*
* Find the group id associated with an (almost filled) group as generated by
* pk_group_from_specified(), or return an error if unknown.
*/
static int pk_group_id_from_group( const mbedtls_ecp_group *grp, mbedtls_ecp_group_id *grp_id )
{
int ret = 0;
mbedtls_ecp_group ref;
const mbedtls_ecp_group_id *id;
mbedtls_ecp_group_init( &ref );
for( id = mbedtls_ecp_grp_id_list(); *id != MBEDTLS_ECP_DP_NONE; id++ )
{
/* Load the group associated to that id */
mbedtls_ecp_group_free( &ref );
MBEDTLS_MPI_CHK( mbedtls_ecp_group_load( &ref, *id ) );
/* Compare to the group we were given, starting with easy tests */
if( grp->pbits == ref.pbits && grp->nbits == ref.nbits &&
mbedtls_mpi_cmp_mpi( &grp->P, &ref.P ) == 0 &&
mbedtls_mpi_cmp_mpi( &grp->A, &ref.A ) == 0 &&
mbedtls_mpi_cmp_mpi( &grp->B, &ref.B ) == 0 &&
mbedtls_mpi_cmp_mpi( &grp->N, &ref.N ) == 0 &&
mbedtls_mpi_cmp_mpi( &grp->G.X, &ref.G.X ) == 0 &&
mbedtls_mpi_cmp_mpi( &grp->G.Z, &ref.G.Z ) == 0 &&
/* For Y we may only know the parity bit, so compare only that */
mbedtls_mpi_get_bit( &grp->G.Y, 0 ) == mbedtls_mpi_get_bit( &ref.G.Y, 0 ) )
{
break;
}
}
cleanup:
mbedtls_ecp_group_free( &ref );
*grp_id = *id;
if( ret == 0 && *id == MBEDTLS_ECP_DP_NONE )
ret = MBEDTLS_ERR_ECP_FEATURE_UNAVAILABLE;
return( ret );
}
/*
* Parse a SpecifiedECDomain (SEC 1 C.2) and find the associated group ID
*/
static int pk_group_id_from_specified( const mbedtls_asn1_buf *params,
mbedtls_ecp_group_id *grp_id )
{
int ret = MBEDTLS_ERR_ERROR_CORRUPTION_DETECTED;
mbedtls_ecp_group grp;
mbedtls_ecp_group_init( &grp );
if( ( ret = pk_group_from_specified( params, &grp ) ) != 0 )
goto cleanup;
ret = pk_group_id_from_group( &grp, grp_id );
cleanup:
mbedtls_ecp_group_free( &grp );
return( ret );
}
#endif /* MBEDTLS_PK_PARSE_EC_EXTENDED */
/*
* Use EC parameters to initialise an EC group
*
* ECParameters ::= CHOICE {
* namedCurve OBJECT IDENTIFIER
* specifiedCurve SpecifiedECDomain -- = SEQUENCE { ... }
* -- implicitCurve NULL
*/
static int pk_use_ecparams( const mbedtls_asn1_buf *params, mbedtls_ecp_group *grp )
{
int ret = MBEDTLS_ERR_ERROR_CORRUPTION_DETECTED;
mbedtls_ecp_group_id grp_id;
if( params->tag == MBEDTLS_ASN1_OID )
{
if( mbedtls_oid_get_ec_grp( params, &grp_id ) != 0 )
return( MBEDTLS_ERR_PK_UNKNOWN_NAMED_CURVE );
}
else
{
#if defined(MBEDTLS_PK_PARSE_EC_EXTENDED)
if( ( ret = pk_group_id_from_specified( params, &grp_id ) ) != 0 )
return( ret );
#else
return( MBEDTLS_ERR_PK_KEY_INVALID_FORMAT );
#endif
}
/*
* grp may already be initilialized; if so, make sure IDs match
*/
if( grp->id != MBEDTLS_ECP_DP_NONE && grp->id != grp_id )
return( MBEDTLS_ERR_PK_KEY_INVALID_FORMAT );
if( ( ret = mbedtls_ecp_group_load( grp, grp_id ) ) != 0 )
return( ret );
return( 0 );
}
/*
* EC public key is an EC point
*
* The caller is responsible for clearing the structure upon failure if
* desired. Take care to pass along the possible ECP_FEATURE_UNAVAILABLE
* return code of mbedtls_ecp_point_read_binary() and leave p in a usable state.
*/
static int pk_get_ecpubkey( unsigned char **p, const unsigned char *end,
mbedtls_ecp_keypair *key )
{
int ret = MBEDTLS_ERR_ERROR_CORRUPTION_DETECTED;
if( ( ret = mbedtls_ecp_point_read_binary( &key->grp, &key->Q,
(const unsigned char *) *p, end - *p ) ) == 0 )
{
ret = mbedtls_ecp_check_pubkey( &key->grp, &key->Q );
}
/*
* We know mbedtls_ecp_point_read_binary consumed all bytes or failed
*/
*p = (unsigned char *) end;
return( ret );
}
#endif /* MBEDTLS_ECP_C */
#if defined(MBEDTLS_RSA_C)
/*
* RSAPublicKey ::= SEQUENCE {
* modulus INTEGER, -- n
* publicExponent INTEGER -- e
* }
*/
static int pk_get_rsapubkey( unsigned char **p,
const unsigned char *end,
mbedtls_rsa_context *rsa )
{
int ret = MBEDTLS_ERR_ERROR_CORRUPTION_DETECTED;
size_t len;
if( ( ret = mbedtls_asn1_get_tag( p, end, &len,
MBEDTLS_ASN1_CONSTRUCTED | MBEDTLS_ASN1_SEQUENCE ) ) != 0 )
return( MBEDTLS_ERROR_ADD( MBEDTLS_ERR_PK_INVALID_PUBKEY, ret ) );
if( *p + len != end )
return( MBEDTLS_ERROR_ADD( MBEDTLS_ERR_PK_INVALID_PUBKEY,
MBEDTLS_ERR_ASN1_LENGTH_MISMATCH ) );
/* Import N */
if( ( ret = mbedtls_asn1_get_tag( p, end, &len, MBEDTLS_ASN1_INTEGER ) ) != 0 )
return( MBEDTLS_ERROR_ADD( MBEDTLS_ERR_PK_INVALID_PUBKEY, ret ) );
if( ( ret = mbedtls_rsa_import_raw( rsa, *p, len, NULL, 0, NULL, 0,
NULL, 0, NULL, 0 ) ) != 0 )
return( MBEDTLS_ERR_PK_INVALID_PUBKEY );
*p += len;
/* Import E */
if( ( ret = mbedtls_asn1_get_tag( p, end, &len, MBEDTLS_ASN1_INTEGER ) ) != 0 )
return( MBEDTLS_ERROR_ADD( MBEDTLS_ERR_PK_INVALID_PUBKEY, ret ) );
if( ( ret = mbedtls_rsa_import_raw( rsa, NULL, 0, NULL, 0, NULL, 0,
NULL, 0, *p, len ) ) != 0 )
return( MBEDTLS_ERR_PK_INVALID_PUBKEY );
*p += len;
if( mbedtls_rsa_complete( rsa ) != 0 ||
mbedtls_rsa_check_pubkey( rsa ) != 0 )
{
return( MBEDTLS_ERR_PK_INVALID_PUBKEY );
}
if( *p != end )
return( MBEDTLS_ERROR_ADD( MBEDTLS_ERR_PK_INVALID_PUBKEY,
MBEDTLS_ERR_ASN1_LENGTH_MISMATCH ) );
return( 0 );
}
#endif /* MBEDTLS_RSA_C */
/* Get a PK algorithm identifier
*
* AlgorithmIdentifier ::= SEQUENCE {
* algorithm OBJECT IDENTIFIER,
* parameters ANY DEFINED BY algorithm OPTIONAL }
*/
static int pk_get_pk_alg( unsigned char **p,
const unsigned char *end,
mbedtls_pk_type_t *pk_alg, mbedtls_asn1_buf *params )
{
int ret = MBEDTLS_ERR_ERROR_CORRUPTION_DETECTED;
mbedtls_asn1_buf alg_oid;
memset( params, 0, sizeof(mbedtls_asn1_buf) );
if( ( ret = mbedtls_asn1_get_alg( p, end, &alg_oid, params ) ) != 0 )
return( MBEDTLS_ERROR_ADD( MBEDTLS_ERR_PK_INVALID_ALG, ret ) );
if( mbedtls_oid_get_pk_alg( &alg_oid, pk_alg ) != 0 )
return( MBEDTLS_ERR_PK_UNKNOWN_PK_ALG );
/*
* No parameters with RSA (only for EC)
*/
if( *pk_alg == MBEDTLS_PK_RSA &&
( ( params->tag != MBEDTLS_ASN1_NULL && params->tag != 0 ) ||
params->len != 0 ) )
{
return( MBEDTLS_ERR_PK_INVALID_ALG );
}
return( 0 );
}
/*
* SubjectPublicKeyInfo ::= SEQUENCE {
* algorithm AlgorithmIdentifier,
* subjectPublicKey BIT STRING }
*/
int mbedtls_pk_parse_subpubkey( unsigned char **p, const unsigned char *end,
mbedtls_pk_context *pk )
{
int ret = MBEDTLS_ERR_ERROR_CORRUPTION_DETECTED;
size_t len;
mbedtls_asn1_buf alg_params;
mbedtls_pk_type_t pk_alg = MBEDTLS_PK_NONE;
const mbedtls_pk_info_t *pk_info;
PK_VALIDATE_RET( p != NULL );
PK_VALIDATE_RET( *p != NULL );
PK_VALIDATE_RET( end != NULL );
PK_VALIDATE_RET( pk != NULL );
if( ( ret = mbedtls_asn1_get_tag( p, end, &len,
MBEDTLS_ASN1_CONSTRUCTED | MBEDTLS_ASN1_SEQUENCE ) ) != 0 )
{
return( MBEDTLS_ERROR_ADD( MBEDTLS_ERR_PK_KEY_INVALID_FORMAT, ret ) );
}
end = *p + len;
if( ( ret = pk_get_pk_alg( p, end, &pk_alg, &alg_params ) ) != 0 )
return( ret );
if( ( ret = mbedtls_asn1_get_bitstring_null( p, end, &len ) ) != 0 )
return( MBEDTLS_ERROR_ADD( MBEDTLS_ERR_PK_INVALID_PUBKEY, ret ) );
if( *p + len != end )
return( MBEDTLS_ERROR_ADD( MBEDTLS_ERR_PK_INVALID_PUBKEY,
MBEDTLS_ERR_ASN1_LENGTH_MISMATCH ) );
if( ( pk_info = mbedtls_pk_info_from_type( pk_alg ) ) == NULL )
return( MBEDTLS_ERR_PK_UNKNOWN_PK_ALG );
if( ( ret = mbedtls_pk_setup( pk, pk_info ) ) != 0 )
return( ret );
#if defined(MBEDTLS_RSA_C)
if( pk_alg == MBEDTLS_PK_RSA )
{
ret = pk_get_rsapubkey( p, end, mbedtls_pk_rsa( *pk ) );
} else
#endif /* MBEDTLS_RSA_C */
#if defined(MBEDTLS_ECP_C)
if( pk_alg == MBEDTLS_PK_ECKEY_DH || pk_alg == MBEDTLS_PK_ECKEY )
{
ret = pk_use_ecparams( &alg_params, &mbedtls_pk_ec( *pk )->grp );
if( ret == 0 )
ret = pk_get_ecpubkey( p, end, mbedtls_pk_ec( *pk ) );
} else
#endif /* MBEDTLS_ECP_C */
ret = MBEDTLS_ERR_PK_UNKNOWN_PK_ALG;
if( ret == 0 && *p != end )
ret = MBEDTLS_ERROR_ADD( MBEDTLS_ERR_PK_INVALID_PUBKEY,
MBEDTLS_ERR_ASN1_LENGTH_MISMATCH );
if( ret != 0 )
mbedtls_pk_free( pk );
return( ret );
}
#if defined(MBEDTLS_RSA_C)
/*
* Wrapper around mbedtls_asn1_get_mpi() that rejects zero.
*
* The value zero is:
* - never a valid value for an RSA parameter
* - interpreted as "omitted, please reconstruct" by mbedtls_rsa_complete().
*
* Since values can't be omitted in PKCS#1, passing a zero value to
* rsa_complete() would be incorrect, so reject zero values early.
*/
static int asn1_get_nonzero_mpi( unsigned char **p,
const unsigned char *end,
mbedtls_mpi *X )
{
int ret;
ret = mbedtls_asn1_get_mpi( p, end, X );
if( ret != 0 )
return( ret );
if( mbedtls_mpi_cmp_int( X, 0 ) == 0 )
return( MBEDTLS_ERR_PK_KEY_INVALID_FORMAT );
return( 0 );
}
/*
* Parse a PKCS#1 encoded private RSA key
*/
static int pk_parse_key_pkcs1_der( mbedtls_rsa_context *rsa,
const unsigned char *key,
size_t keylen )
{
int ret, version;
size_t len;
unsigned char *p, *end;
mbedtls_mpi T;
mbedtls_mpi_init( &T );
p = (unsigned char *) key;
end = p + keylen;
/*
* This function parses the RSAPrivateKey (PKCS#1)
*
* RSAPrivateKey ::= SEQUENCE {
* version Version,
* modulus INTEGER, -- n
* publicExponent INTEGER, -- e
* privateExponent INTEGER, -- d
* prime1 INTEGER, -- p
* prime2 INTEGER, -- q
* exponent1 INTEGER, -- d mod (p-1)
* exponent2 INTEGER, -- d mod (q-1)
* coefficient INTEGER, -- (inverse of q) mod p
* otherPrimeInfos OtherPrimeInfos OPTIONAL
* }
*/
if( ( ret = mbedtls_asn1_get_tag( &p, end, &len,
MBEDTLS_ASN1_CONSTRUCTED | MBEDTLS_ASN1_SEQUENCE ) ) != 0 )
{
return( MBEDTLS_ERROR_ADD( MBEDTLS_ERR_PK_KEY_INVALID_FORMAT, ret ) );
}
end = p + len;
if( ( ret = mbedtls_asn1_get_int( &p, end, &version ) ) != 0 )
{
return( MBEDTLS_ERROR_ADD( MBEDTLS_ERR_PK_KEY_INVALID_FORMAT, ret ) );
}
if( version != 0 )
{
return( MBEDTLS_ERR_PK_KEY_INVALID_VERSION );
}
/* Import N */
if( ( ret = asn1_get_nonzero_mpi( &p, end, &T ) ) != 0 ||
( ret = mbedtls_rsa_import( rsa, &T, NULL, NULL,
NULL, NULL ) ) != 0 )
goto cleanup;
/* Import E */
if( ( ret = asn1_get_nonzero_mpi( &p, end, &T ) ) != 0 ||
( ret = mbedtls_rsa_import( rsa, NULL, NULL, NULL,
NULL, &T ) ) != 0 )
goto cleanup;
/* Import D */
if( ( ret = asn1_get_nonzero_mpi( &p, end, &T ) ) != 0 ||
( ret = mbedtls_rsa_import( rsa, NULL, NULL, NULL,
&T, NULL ) ) != 0 )
goto cleanup;
/* Import P */
if( ( ret = asn1_get_nonzero_mpi( &p, end, &T ) ) != 0 ||
( ret = mbedtls_rsa_import( rsa, NULL, &T, NULL,
NULL, NULL ) ) != 0 )
goto cleanup;
/* Import Q */
if( ( ret = asn1_get_nonzero_mpi( &p, end, &T ) ) != 0 ||
( ret = mbedtls_rsa_import( rsa, NULL, NULL, &T,
NULL, NULL ) ) != 0 )
goto cleanup;
#if !defined(MBEDTLS_RSA_NO_CRT) && !defined(MBEDTLS_RSA_ALT)
/*
* The RSA CRT parameters DP, DQ and QP are nominally redundant, in
* that they can be easily recomputed from D, P and Q. However by
* parsing them from the PKCS1 structure it is possible to avoid
* recalculating them which both reduces the overhead of loading
* RSA private keys into memory and also avoids side channels which
* can arise when computing those values, since all of D, P, and Q
* are secret. See https://eprint.iacr.org/2020/055 for a
* description of one such attack.
*/
/* Import DP */
if( ( ret = asn1_get_nonzero_mpi( &p, end, &T ) ) != 0 ||
( ret = mbedtls_mpi_copy( &rsa->DP, &T ) ) != 0 )
goto cleanup;
/* Import DQ */
if( ( ret = asn1_get_nonzero_mpi( &p, end, &T ) ) != 0 ||
( ret = mbedtls_mpi_copy( &rsa->DQ, &T ) ) != 0 )
goto cleanup;
/* Import QP */
if( ( ret = asn1_get_nonzero_mpi( &p, end, &T ) ) != 0 ||
( ret = mbedtls_mpi_copy( &rsa->QP, &T ) ) != 0 )
goto cleanup;
#else
/* Verify existance of the CRT params */
if( ( ret = asn1_get_nonzero_mpi( &p, end, &T ) ) != 0 ||
( ret = asn1_get_nonzero_mpi( &p, end, &T ) ) != 0 ||
( ret = asn1_get_nonzero_mpi( &p, end, &T ) ) != 0 )
goto cleanup;
#endif
/* rsa_complete() doesn't complete anything with the default
* implementation but is still called:
* - for the benefit of alternative implementation that may want to
* pre-compute stuff beyond what's provided (eg Montgomery factors)
* - as is also sanity-checks the key
*
* Furthermore, we also check the public part for consistency with
* mbedtls_pk_parse_pubkey(), as it includes size minima for example.
*/
if( ( ret = mbedtls_rsa_complete( rsa ) ) != 0 ||
( ret = mbedtls_rsa_check_pubkey( rsa ) ) != 0 )
{
goto cleanup;
}
if( p != end )
{
ret = MBEDTLS_ERROR_ADD( MBEDTLS_ERR_PK_KEY_INVALID_FORMAT,
MBEDTLS_ERR_ASN1_LENGTH_MISMATCH );
}
cleanup:
mbedtls_mpi_free( &T );
if( ret != 0 )
{
/* Wrap error code if it's coming from a lower level */
if( ( ret & 0xff80 ) == 0 )
ret = MBEDTLS_ERROR_ADD( MBEDTLS_ERR_PK_KEY_INVALID_FORMAT, ret );
else
ret = MBEDTLS_ERR_PK_KEY_INVALID_FORMAT;
mbedtls_rsa_free( rsa );
}
return( ret );
}
#endif /* MBEDTLS_RSA_C */
#if defined(MBEDTLS_ECP_C)
/*
* Parse a SEC1 encoded private EC key
*/
static int pk_parse_key_sec1_der( mbedtls_ecp_keypair *eck,
const unsigned char *key,
size_t keylen )
{
int ret = MBEDTLS_ERR_ERROR_CORRUPTION_DETECTED;
int version, pubkey_done;
size_t len;
mbedtls_asn1_buf params;
unsigned char *p = (unsigned char *) key;
unsigned char *end = p + keylen;
unsigned char *end2;
/*
* RFC 5915, or SEC1 Appendix C.4
*
* ECPrivateKey ::= SEQUENCE {
* version INTEGER { ecPrivkeyVer1(1) } (ecPrivkeyVer1),
* privateKey OCTET STRING,
* parameters [0] ECParameters {{ NamedCurve }} OPTIONAL,
* publicKey [1] BIT STRING OPTIONAL
* }
*/
if( ( ret = mbedtls_asn1_get_tag( &p, end, &len,
MBEDTLS_ASN1_CONSTRUCTED | MBEDTLS_ASN1_SEQUENCE ) ) != 0 )
{
return( MBEDTLS_ERROR_ADD( MBEDTLS_ERR_PK_KEY_INVALID_FORMAT, ret ) );
}
end = p + len;
if( ( ret = mbedtls_asn1_get_int( &p, end, &version ) ) != 0 )
return( MBEDTLS_ERROR_ADD( MBEDTLS_ERR_PK_KEY_INVALID_FORMAT, ret ) );
if( version != 1 )
return( MBEDTLS_ERR_PK_KEY_INVALID_VERSION );
if( ( ret = mbedtls_asn1_get_tag( &p, end, &len, MBEDTLS_ASN1_OCTET_STRING ) ) != 0 )
return( MBEDTLS_ERROR_ADD( MBEDTLS_ERR_PK_KEY_INVALID_FORMAT, ret ) );
if( ( ret = mbedtls_mpi_read_binary( &eck->d, p, len ) ) != 0 )
{
mbedtls_ecp_keypair_free( eck );
return( MBEDTLS_ERROR_ADD( MBEDTLS_ERR_PK_KEY_INVALID_FORMAT, ret ) );
}
p += len;
pubkey_done = 0;
if( p != end )
{
/*
* Is 'parameters' present?
*/
if( ( ret = mbedtls_asn1_get_tag( &p, end, &len,
MBEDTLS_ASN1_CONTEXT_SPECIFIC | MBEDTLS_ASN1_CONSTRUCTED | 0 ) ) == 0 )
{
if( ( ret = pk_get_ecparams( &p, p + len, ¶ms) ) != 0 ||
( ret = pk_use_ecparams( ¶ms, &eck->grp ) ) != 0 )
{
mbedtls_ecp_keypair_free( eck );
return( ret );
}
}
else if( ret != MBEDTLS_ERR_ASN1_UNEXPECTED_TAG )
{
mbedtls_ecp_keypair_free( eck );
return( MBEDTLS_ERROR_ADD( MBEDTLS_ERR_PK_KEY_INVALID_FORMAT, ret ) );
}
}
if( p != end )
{
/*
* Is 'publickey' present? If not, or if we can't read it (eg because it
* is compressed), create it from the private key.
*/
if( ( ret = mbedtls_asn1_get_tag( &p, end, &len,
MBEDTLS_ASN1_CONTEXT_SPECIFIC | MBEDTLS_ASN1_CONSTRUCTED | 1 ) ) == 0 )
{
end2 = p + len;
if( ( ret = mbedtls_asn1_get_bitstring_null( &p, end2, &len ) ) != 0 )
return( MBEDTLS_ERROR_ADD( MBEDTLS_ERR_PK_KEY_INVALID_FORMAT, ret ) );
if( p + len != end2 )
return( MBEDTLS_ERROR_ADD( MBEDTLS_ERR_PK_KEY_INVALID_FORMAT,
MBEDTLS_ERR_ASN1_LENGTH_MISMATCH ) );
if( ( ret = pk_get_ecpubkey( &p, end2, eck ) ) == 0 )
pubkey_done = 1;
else
{
/*
* The only acceptable failure mode of pk_get_ecpubkey() above
* is if the point format is not recognized.
*/
if( ret != MBEDTLS_ERR_ECP_FEATURE_UNAVAILABLE )
return( MBEDTLS_ERR_PK_KEY_INVALID_FORMAT );
}
}
else if( ret != MBEDTLS_ERR_ASN1_UNEXPECTED_TAG )
{
mbedtls_ecp_keypair_free( eck );
return( MBEDTLS_ERROR_ADD( MBEDTLS_ERR_PK_KEY_INVALID_FORMAT, ret ) );
}
}
if( ! pubkey_done &&
( ret = mbedtls_ecp_mul( &eck->grp, &eck->Q, &eck->d, &eck->grp.G,
NULL, NULL ) ) != 0 )
{
mbedtls_ecp_keypair_free( eck );
return( MBEDTLS_ERROR_ADD( MBEDTLS_ERR_PK_KEY_INVALID_FORMAT, ret ) );
}
if( ( ret = mbedtls_ecp_check_privkey( &eck->grp, &eck->d ) ) != 0 )
{
mbedtls_ecp_keypair_free( eck );
return( ret );
}
return( 0 );
}
#endif /* MBEDTLS_ECP_C */
/*
* Parse an unencrypted PKCS#8 encoded private key
*
* Notes:
*
* - This function does not own the key buffer. It is the
* responsibility of the caller to take care of zeroizing
* and freeing it after use.
*
* - The function is responsible for freeing the provided
* PK context on failure.
*
*/
static int pk_parse_key_pkcs8_unencrypted_der(
mbedtls_pk_context *pk,
const unsigned char* key,
size_t keylen )
{
int ret, version;
size_t len;
mbedtls_asn1_buf params;
unsigned char *p = (unsigned char *) key;
unsigned char *end = p + keylen;
mbedtls_pk_type_t pk_alg = MBEDTLS_PK_NONE;
const mbedtls_pk_info_t *pk_info;
/*
* This function parses the PrivateKeyInfo object (PKCS#8 v1.2 = RFC 5208)
*
* PrivateKeyInfo ::= SEQUENCE {
* version Version,
* privateKeyAlgorithm PrivateKeyAlgorithmIdentifier,
* privateKey PrivateKey,
* attributes [0] IMPLICIT Attributes OPTIONAL }
*
* Version ::= INTEGER
* PrivateKeyAlgorithmIdentifier ::= AlgorithmIdentifier
* PrivateKey ::= OCTET STRING
*
* The PrivateKey OCTET STRING is a SEC1 ECPrivateKey
*/
if( ( ret = mbedtls_asn1_get_tag( &p, end, &len,
MBEDTLS_ASN1_CONSTRUCTED | MBEDTLS_ASN1_SEQUENCE ) ) != 0 )
{
return( MBEDTLS_ERROR_ADD( MBEDTLS_ERR_PK_KEY_INVALID_FORMAT, ret ) );
}
end = p + len;
if( ( ret = mbedtls_asn1_get_int( &p, end, &version ) ) != 0 )
return( MBEDTLS_ERROR_ADD( MBEDTLS_ERR_PK_KEY_INVALID_FORMAT, ret ) );
if( version != 0 )
return( MBEDTLS_ERROR_ADD( MBEDTLS_ERR_PK_KEY_INVALID_VERSION, ret ) );
if( ( ret = pk_get_pk_alg( &p, end, &pk_alg, ¶ms ) ) != 0 )
{
return( ret );
}
if( ( ret = mbedtls_asn1_get_tag( &p, end, &len, MBEDTLS_ASN1_OCTET_STRING ) ) != 0 )
return( MBEDTLS_ERROR_ADD( MBEDTLS_ERR_PK_KEY_INVALID_FORMAT, ret ) );
if( len < 1 )
return( MBEDTLS_ERROR_ADD( MBEDTLS_ERR_PK_KEY_INVALID_FORMAT,
MBEDTLS_ERR_ASN1_OUT_OF_DATA ) );
if( ( pk_info = mbedtls_pk_info_from_type( pk_alg ) ) == NULL )
return( MBEDTLS_ERR_PK_UNKNOWN_PK_ALG );
if( ( ret = mbedtls_pk_setup( pk, pk_info ) ) != 0 )
return( ret );
#if defined(MBEDTLS_RSA_C)
if( pk_alg == MBEDTLS_PK_RSA )
{
if( ( ret = pk_parse_key_pkcs1_der( mbedtls_pk_rsa( *pk ), p, len ) ) != 0 )
{
mbedtls_pk_free( pk );
return( ret );
}
} else
#endif /* MBEDTLS_RSA_C */
#if defined(MBEDTLS_ECP_C)
if( pk_alg == MBEDTLS_PK_ECKEY || pk_alg == MBEDTLS_PK_ECKEY_DH )
{
if( ( ret = pk_use_ecparams( ¶ms, &mbedtls_pk_ec( *pk )->grp ) ) != 0 ||
( ret = pk_parse_key_sec1_der( mbedtls_pk_ec( *pk ), p, len ) ) != 0 )
{
mbedtls_pk_free( pk );
return( ret );
}
} else
#endif /* MBEDTLS_ECP_C */
return( MBEDTLS_ERR_PK_UNKNOWN_PK_ALG );
return( 0 );
}
/*
* Parse an encrypted PKCS#8 encoded private key
*
* To save space, the decryption happens in-place on the given key buffer.
* Also, while this function may modify the keybuffer, it doesn't own it,
* and instead it is the responsibility of the caller to zeroize and properly
* free it after use.
*
*/
#if defined(MBEDTLS_PKCS12_C) || defined(MBEDTLS_PKCS5_C)
static int pk_parse_key_pkcs8_encrypted_der(
mbedtls_pk_context *pk,
unsigned char *key, size_t keylen,
const unsigned char *pwd, size_t pwdlen )
{
int ret, decrypted = 0;
size_t len;
unsigned char *buf;
unsigned char *p, *end;
mbedtls_asn1_buf pbe_alg_oid, pbe_params;
#if defined(MBEDTLS_PKCS12_C)
mbedtls_cipher_type_t cipher_alg;
mbedtls_md_type_t md_alg;
#endif
p = key;
end = p + keylen;
if( pwdlen == 0 )
return( MBEDTLS_ERR_PK_PASSWORD_REQUIRED );
/*
* This function parses the EncryptedPrivateKeyInfo object (PKCS#8)
*
* EncryptedPrivateKeyInfo ::= SEQUENCE {
* encryptionAlgorithm EncryptionAlgorithmIdentifier,
* encryptedData EncryptedData
* }
*
* EncryptionAlgorithmIdentifier ::= AlgorithmIdentifier
*
* EncryptedData ::= OCTET STRING
*
* The EncryptedData OCTET STRING is a PKCS#8 PrivateKeyInfo
*
*/
if( ( ret = mbedtls_asn1_get_tag( &p, end, &len,
MBEDTLS_ASN1_CONSTRUCTED | MBEDTLS_ASN1_SEQUENCE ) ) != 0 )
{
return( MBEDTLS_ERROR_ADD( MBEDTLS_ERR_PK_KEY_INVALID_FORMAT, ret ) );
}
end = p + len;
if( ( ret = mbedtls_asn1_get_alg( &p, end, &pbe_alg_oid, &pbe_params ) ) != 0 )
return( MBEDTLS_ERROR_ADD( MBEDTLS_ERR_PK_KEY_INVALID_FORMAT, ret ) );
if( ( ret = mbedtls_asn1_get_tag( &p, end, &len, MBEDTLS_ASN1_OCTET_STRING ) ) != 0 )
return( MBEDTLS_ERROR_ADD( MBEDTLS_ERR_PK_KEY_INVALID_FORMAT, ret ) );
buf = p;
/*
* Decrypt EncryptedData with appropriate PBE
*/
#if defined(MBEDTLS_PKCS12_C)
if( mbedtls_oid_get_pkcs12_pbe_alg( &pbe_alg_oid, &md_alg, &cipher_alg ) == 0 )
{
if( ( ret = mbedtls_pkcs12_pbe( &pbe_params, MBEDTLS_PKCS12_PBE_DECRYPT,
cipher_alg, md_alg,
pwd, pwdlen, p, len, buf ) ) != 0 )
{
if( ret == MBEDTLS_ERR_PKCS12_PASSWORD_MISMATCH )
return( MBEDTLS_ERR_PK_PASSWORD_MISMATCH );
return( ret );
}
decrypted = 1;
}
else if( MBEDTLS_OID_CMP( MBEDTLS_OID_PKCS12_PBE_SHA1_RC4_128, &pbe_alg_oid ) == 0 )
{
if( ( ret = mbedtls_pkcs12_pbe_sha1_rc4_128( &pbe_params,
MBEDTLS_PKCS12_PBE_DECRYPT,
pwd, pwdlen,
p, len, buf ) ) != 0 )
{
return( ret );
}
// Best guess for password mismatch when using RC4. If first tag is
// not MBEDTLS_ASN1_CONSTRUCTED | MBEDTLS_ASN1_SEQUENCE
//
if( *buf != ( MBEDTLS_ASN1_CONSTRUCTED | MBEDTLS_ASN1_SEQUENCE ) )
return( MBEDTLS_ERR_PK_PASSWORD_MISMATCH );
decrypted = 1;
}
else
#endif /* MBEDTLS_PKCS12_C */
#if defined(MBEDTLS_PKCS5_C)
if( MBEDTLS_OID_CMP( MBEDTLS_OID_PKCS5_PBES2, &pbe_alg_oid ) == 0 )
{
if( ( ret = mbedtls_pkcs5_pbes2( &pbe_params, MBEDTLS_PKCS5_DECRYPT, pwd, pwdlen,
p, len, buf ) ) != 0 )
{
if( ret == MBEDTLS_ERR_PKCS5_PASSWORD_MISMATCH )
return( MBEDTLS_ERR_PK_PASSWORD_MISMATCH );
return( ret );
}
decrypted = 1;
}
else
#endif /* MBEDTLS_PKCS5_C */
{
((void) pwd);
}
if( decrypted == 0 )
return( MBEDTLS_ERR_PK_FEATURE_UNAVAILABLE );
return( pk_parse_key_pkcs8_unencrypted_der( pk, buf, len ) );
}
#endif /* MBEDTLS_PKCS12_C || MBEDTLS_PKCS5_C */
/*
* Parse a private key
*/
int mbedtls_pk_parse_key( mbedtls_pk_context *pk,
const unsigned char *key, size_t keylen,
const unsigned char *pwd, size_t pwdlen )
{
int ret = MBEDTLS_ERR_ERROR_CORRUPTION_DETECTED;
const mbedtls_pk_info_t *pk_info;
#if defined(MBEDTLS_PEM_PARSE_C)
size_t len;
mbedtls_pem_context pem;
#endif
PK_VALIDATE_RET( pk != NULL );
if( keylen == 0 )
return( MBEDTLS_ERR_PK_KEY_INVALID_FORMAT );
PK_VALIDATE_RET( key != NULL );
#if defined(MBEDTLS_PEM_PARSE_C)
mbedtls_pem_init( &pem );
#if defined(MBEDTLS_RSA_C)
/* Avoid calling mbedtls_pem_read_buffer() on non-null-terminated string */
if( key[keylen - 1] != '\0' )
ret = MBEDTLS_ERR_PEM_NO_HEADER_FOOTER_PRESENT;
else
ret = mbedtls_pem_read_buffer( &pem,
"-----BEGIN RSA PRIVATE KEY-----",
"-----END RSA PRIVATE KEY-----",
key, pwd, pwdlen, &len );
if( ret == 0 )
{
pk_info = mbedtls_pk_info_from_type( MBEDTLS_PK_RSA );
if( ( ret = mbedtls_pk_setup( pk, pk_info ) ) != 0 ||
( ret = pk_parse_key_pkcs1_der( mbedtls_pk_rsa( *pk ),
pem.buf, pem.buflen ) ) != 0 )
{
mbedtls_pk_free( pk );
}
mbedtls_pem_free( &pem );
return( ret );
}
else if( ret == MBEDTLS_ERR_PEM_PASSWORD_MISMATCH )
return( MBEDTLS_ERR_PK_PASSWORD_MISMATCH );
else if( ret == MBEDTLS_ERR_PEM_PASSWORD_REQUIRED )
return( MBEDTLS_ERR_PK_PASSWORD_REQUIRED );
else if( ret != MBEDTLS_ERR_PEM_NO_HEADER_FOOTER_PRESENT )
return( ret );
#endif /* MBEDTLS_RSA_C */
#if defined(MBEDTLS_ECP_C)
/* Avoid calling mbedtls_pem_read_buffer() on non-null-terminated string */
if( key[keylen - 1] != '\0' )
ret = MBEDTLS_ERR_PEM_NO_HEADER_FOOTER_PRESENT;
else
ret = mbedtls_pem_read_buffer( &pem,
"-----BEGIN EC PRIVATE KEY-----",
"-----END EC PRIVATE KEY-----",
key, pwd, pwdlen, &len );
if( ret == 0 )
{
pk_info = mbedtls_pk_info_from_type( MBEDTLS_PK_ECKEY );
if( ( ret = mbedtls_pk_setup( pk, pk_info ) ) != 0 ||
( ret = pk_parse_key_sec1_der( mbedtls_pk_ec( *pk ),
pem.buf, pem.buflen ) ) != 0 )
{
mbedtls_pk_free( pk );
}
mbedtls_pem_free( &pem );
return( ret );
}
else if( ret == MBEDTLS_ERR_PEM_PASSWORD_MISMATCH )
return( MBEDTLS_ERR_PK_PASSWORD_MISMATCH );
else if( ret == MBEDTLS_ERR_PEM_PASSWORD_REQUIRED )
return( MBEDTLS_ERR_PK_PASSWORD_REQUIRED );
else if( ret != MBEDTLS_ERR_PEM_NO_HEADER_FOOTER_PRESENT )
return( ret );
#endif /* MBEDTLS_ECP_C */
/* Avoid calling mbedtls_pem_read_buffer() on non-null-terminated string */
if( key[keylen - 1] != '\0' )
ret = MBEDTLS_ERR_PEM_NO_HEADER_FOOTER_PRESENT;
else
ret = mbedtls_pem_read_buffer( &pem,
"-----BEGIN PRIVATE KEY-----",
"-----END PRIVATE KEY-----",
key, NULL, 0, &len );
if( ret == 0 )
{
if( ( ret = pk_parse_key_pkcs8_unencrypted_der( pk,
pem.buf, pem.buflen ) ) != 0 )
{
mbedtls_pk_free( pk );
}
mbedtls_pem_free( &pem );
return( ret );
}
else if( ret != MBEDTLS_ERR_PEM_NO_HEADER_FOOTER_PRESENT )
return( ret );
#if defined(MBEDTLS_PKCS12_C) || defined(MBEDTLS_PKCS5_C)
/* Avoid calling mbedtls_pem_read_buffer() on non-null-terminated string */
if( key[keylen - 1] != '\0' )
ret = MBEDTLS_ERR_PEM_NO_HEADER_FOOTER_PRESENT;
else
ret = mbedtls_pem_read_buffer( &pem,
"-----BEGIN ENCRYPTED PRIVATE KEY-----",
"-----END ENCRYPTED PRIVATE KEY-----",
key, NULL, 0, &len );
if( ret == 0 )
{
if( ( ret = pk_parse_key_pkcs8_encrypted_der( pk,
pem.buf, pem.buflen,
pwd, pwdlen ) ) != 0 )
{
mbedtls_pk_free( pk );
}
mbedtls_pem_free( &pem );
return( ret );
}
else if( ret != MBEDTLS_ERR_PEM_NO_HEADER_FOOTER_PRESENT )
return( ret );
#endif /* MBEDTLS_PKCS12_C || MBEDTLS_PKCS5_C */
#else
((void) pwd);
((void) pwdlen);
#endif /* MBEDTLS_PEM_PARSE_C */
/*
* At this point we only know it's not a PEM formatted key. Could be any
* of the known DER encoded private key formats
*
* We try the different DER format parsers to see if one passes without
* error
*/
#if defined(MBEDTLS_PKCS12_C) || defined(MBEDTLS_PKCS5_C)
{
unsigned char *key_copy;
if( ( key_copy = mbedtls_calloc( 1, keylen ) ) == NULL )
return( MBEDTLS_ERR_PK_ALLOC_FAILED );
memcpy( key_copy, key, keylen );
ret = pk_parse_key_pkcs8_encrypted_der( pk, key_copy, keylen,
pwd, pwdlen );
mbedtls_platform_zeroize( key_copy, keylen );
mbedtls_free( key_copy );
}
if( ret == 0 )
return( 0 );
mbedtls_pk_free( pk );
mbedtls_pk_init( pk );
if( ret == MBEDTLS_ERR_PK_PASSWORD_MISMATCH )
{
return( ret );
}
#endif /* MBEDTLS_PKCS12_C || MBEDTLS_PKCS5_C */
if( ( ret = pk_parse_key_pkcs8_unencrypted_der( pk, key, keylen ) ) == 0 )
return( 0 );
mbedtls_pk_free( pk );
mbedtls_pk_init( pk );
#if defined(MBEDTLS_RSA_C)
pk_info = mbedtls_pk_info_from_type( MBEDTLS_PK_RSA );
if( mbedtls_pk_setup( pk, pk_info ) == 0 &&
pk_parse_key_pkcs1_der( mbedtls_pk_rsa( *pk ), key, keylen ) == 0 )
{
return( 0 );
}
mbedtls_pk_free( pk );
mbedtls_pk_init( pk );
#endif /* MBEDTLS_RSA_C */
#if defined(MBEDTLS_ECP_C)
pk_info = mbedtls_pk_info_from_type( MBEDTLS_PK_ECKEY );
if( mbedtls_pk_setup( pk, pk_info ) == 0 &&
pk_parse_key_sec1_der( mbedtls_pk_ec( *pk ),
key, keylen ) == 0 )
{
return( 0 );
}
mbedtls_pk_free( pk );
#endif /* MBEDTLS_ECP_C */
/* If MBEDTLS_RSA_C is defined but MBEDTLS_ECP_C isn't,
* it is ok to leave the PK context initialized but not
* freed: It is the caller's responsibility to call pk_init()
* before calling this function, and to call pk_free()
* when it fails. If MBEDTLS_ECP_C is defined but MBEDTLS_RSA_C
* isn't, this leads to mbedtls_pk_free() being called
* twice, once here and once by the caller, but this is
* also ok and in line with the mbedtls_pk_free() calls
* on failed PEM parsing attempts. */
return( MBEDTLS_ERR_PK_KEY_INVALID_FORMAT );
}
/*
* Parse a public key
*/
int mbedtls_pk_parse_public_key( mbedtls_pk_context *ctx,
const unsigned char *key, size_t keylen )
{
int ret = MBEDTLS_ERR_ERROR_CORRUPTION_DETECTED;
unsigned char *p;
#if defined(MBEDTLS_RSA_C)
const mbedtls_pk_info_t *pk_info;
#endif
#if defined(MBEDTLS_PEM_PARSE_C)
size_t len;
mbedtls_pem_context pem;
#endif
PK_VALIDATE_RET( ctx != NULL );
if( keylen == 0 )
return( MBEDTLS_ERR_PK_KEY_INVALID_FORMAT );
PK_VALIDATE_RET( key != NULL || keylen == 0 );
#if defined(MBEDTLS_PEM_PARSE_C)
mbedtls_pem_init( &pem );
#if defined(MBEDTLS_RSA_C)
/* Avoid calling mbedtls_pem_read_buffer() on non-null-terminated string */
if( key[keylen - 1] != '\0' )
ret = MBEDTLS_ERR_PEM_NO_HEADER_FOOTER_PRESENT;
else
ret = mbedtls_pem_read_buffer( &pem,
"-----BEGIN RSA PUBLIC KEY-----",
"-----END RSA PUBLIC KEY-----",
key, NULL, 0, &len );
if( ret == 0 )
{
p = pem.buf;
if( ( pk_info = mbedtls_pk_info_from_type( MBEDTLS_PK_RSA ) ) == NULL )
return( MBEDTLS_ERR_PK_UNKNOWN_PK_ALG );
if( ( ret = mbedtls_pk_setup( ctx, pk_info ) ) != 0 )
return( ret );
if ( ( ret = pk_get_rsapubkey( &p, p + pem.buflen, mbedtls_pk_rsa( *ctx ) ) ) != 0 )
mbedtls_pk_free( ctx );
mbedtls_pem_free( &pem );
return( ret );
}
else if( ret != MBEDTLS_ERR_PEM_NO_HEADER_FOOTER_PRESENT )
{
mbedtls_pem_free( &pem );
return( ret );
}
#endif /* MBEDTLS_RSA_C */
/* Avoid calling mbedtls_pem_read_buffer() on non-null-terminated string */
if( key[keylen - 1] != '\0' )
ret = MBEDTLS_ERR_PEM_NO_HEADER_FOOTER_PRESENT;
else
ret = mbedtls_pem_read_buffer( &pem,
"-----BEGIN PUBLIC KEY-----",
"-----END PUBLIC KEY-----",
key, NULL, 0, &len );
if( ret == 0 )
{
/*
* Was PEM encoded
*/
p = pem.buf;
ret = mbedtls_pk_parse_subpubkey( &p, p + pem.buflen, ctx );
mbedtls_pem_free( &pem );
return( ret );
}
else if( ret != MBEDTLS_ERR_PEM_NO_HEADER_FOOTER_PRESENT )
{
mbedtls_pem_free( &pem );
return( ret );
}
mbedtls_pem_free( &pem );
#endif /* MBEDTLS_PEM_PARSE_C */
#if defined(MBEDTLS_RSA_C)
if( ( pk_info = mbedtls_pk_info_from_type( MBEDTLS_PK_RSA ) ) == NULL )
return( MBEDTLS_ERR_PK_UNKNOWN_PK_ALG );
if( ( ret = mbedtls_pk_setup( ctx, pk_info ) ) != 0 )
return( ret );
p = (unsigned char *)key;
ret = pk_get_rsapubkey( &p, p + keylen, mbedtls_pk_rsa( *ctx ) );
if( ret == 0 )
{
return( ret );
}
mbedtls_pk_free( ctx );
if( ret != ( MBEDTLS_ERROR_ADD( MBEDTLS_ERR_PK_INVALID_PUBKEY,
MBEDTLS_ERR_ASN1_UNEXPECTED_TAG ) ) )
{
return( ret );
}
#endif /* MBEDTLS_RSA_C */
p = (unsigned char *) key;
ret = mbedtls_pk_parse_subpubkey( &p, p + keylen, ctx );
return( ret );
}
#endif /* MBEDTLS_PK_PARSE_C */
|
0 | repos/gpt4all.zig/src/zig-libcurl/zig-mbedtls/mbedtls | repos/gpt4all.zig/src/zig-libcurl/zig-mbedtls/mbedtls/library/mps_error.h | /*
* Copyright The Mbed TLS Contributors
* SPDX-License-Identifier: Apache-2.0
*
* 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.
*
* This file is part of mbed TLS (https://tls.mbed.org)
*/
/**
* \file mps_error.h
*
* \brief Error codes used by MPS
*/
#ifndef MBEDTLS_MPS_ERROR_H
#define MBEDTLS_MPS_ERROR_H
/* TODO: The error code allocation needs to be revisited:
*
* - Should we make (some of) the MPS Reader error codes public?
* If so, we need to adjust MBEDTLS_MPS_READER_MAKE_ERROR() to hit
* a gap in the Mbed TLS public error space.
* If not, we have to make sure we don't forward those errors
* at the level of the public API -- no risk at the moment as
* long as MPS is an experimental component not accessible from
* public API.
*/
/**
* \name SECTION: MPS general error codes
*
* \{
*/
#ifndef MBEDTLS_MPS_ERR_BASE
#define MBEDTLS_MPS_ERR_BASE ( 0 )
#endif
#define MBEDTLS_MPS_MAKE_ERROR(code) \
( -( MBEDTLS_MPS_ERR_BASE | (code) ) )
#define MBEDTLS_ERR_MPS_OPERATION_UNEXPECTED MBEDTLS_MPS_MAKE_ERROR( 0x1 )
#define MBEDTLS_ERR_MPS_INTERNAL_ERROR MBEDTLS_MPS_MAKE_ERROR( 0x2 )
/* \} name SECTION: MPS general error codes */
/**
* \name SECTION: MPS Reader error codes
*
* \{
*/
#ifndef MBEDTLS_MPS_READER_ERR_BASE
#define MBEDTLS_MPS_READER_ERR_BASE ( 1 << 8 )
#endif
#define MBEDTLS_MPS_READER_MAKE_ERROR(code) \
( -( MBEDTLS_MPS_READER_ERR_BASE | (code) ) )
/*! An attempt to reclaim the data buffer from a reader failed because
* the user hasn't yet read and committed all of it. */
#define MBEDTLS_ERR_MPS_READER_DATA_LEFT MBEDTLS_MPS_READER_MAKE_ERROR( 0x1 )
/*! An invalid argument was passed to the reader. */
#define MBEDTLS_ERR_MPS_READER_INVALID_ARG MBEDTLS_MPS_READER_MAKE_ERROR( 0x2 )
/*! An attempt to move a reader to consuming mode through mbedtls_mps_reader_feed()
* after pausing failed because the provided data is not sufficient to serve the
* read requests that led to the pausing. */
#define MBEDTLS_ERR_MPS_READER_NEED_MORE MBEDTLS_MPS_READER_MAKE_ERROR( 0x3 )
/*! A get request failed because not enough data is available in the reader. */
#define MBEDTLS_ERR_MPS_READER_OUT_OF_DATA MBEDTLS_MPS_READER_MAKE_ERROR( 0x4 )
/*!< A get request after pausing and reactivating the reader failed because
* the request is not in line with the request made prior to pausing. The user
* must not change it's 'strategy' after pausing and reactivating a reader. */
#define MBEDTLS_ERR_MPS_READER_INCONSISTENT_REQUESTS MBEDTLS_MPS_READER_MAKE_ERROR( 0x5 )
/*! An attempt to reclaim the data buffer from a reader failed because the reader
* has no accumulator it can use to backup the data that hasn't been processed. */
#define MBEDTLS_ERR_MPS_READER_NEED_ACCUMULATOR MBEDTLS_MPS_READER_MAKE_ERROR( 0x6 )
/*! An attempt to reclaim the data buffer from a reader failed because the
* accumulator passed to the reader is not large enough to hold both the
* data that hasn't been processed and the excess of the last read-request. */
#define MBEDTLS_ERR_MPS_READER_ACCUMULATOR_TOO_SMALL MBEDTLS_MPS_READER_MAKE_ERROR( 0x7 )
/* \} name SECTION: MPS Reader error codes */
#endif /* MBEDTLS_MPS_ERROR_H */
|
0 | repos/gpt4all.zig/src/zig-libcurl/zig-mbedtls/mbedtls | repos/gpt4all.zig/src/zig-libcurl/zig-mbedtls/mbedtls/library/psa_crypto_slot_management.c | /*
* PSA crypto layer on top of Mbed TLS crypto
*/
/*
* Copyright The Mbed TLS Contributors
* SPDX-License-Identifier: Apache-2.0
*
* 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.
*/
#include "common.h"
#if defined(MBEDTLS_PSA_CRYPTO_C)
#include "psa/crypto.h"
#include "psa_crypto_core.h"
#include "psa_crypto_driver_wrappers.h"
#include "psa_crypto_slot_management.h"
#include "psa_crypto_storage.h"
#if defined(MBEDTLS_PSA_CRYPTO_SE_C)
#include "psa_crypto_se.h"
#endif
#include <stdlib.h>
#include <string.h>
#if defined(MBEDTLS_PLATFORM_C)
#include "mbedtls/platform.h"
#else
#define mbedtls_calloc calloc
#define mbedtls_free free
#endif
#define ARRAY_LENGTH( array ) ( sizeof( array ) / sizeof( *( array ) ) )
typedef struct
{
psa_key_slot_t key_slots[MBEDTLS_PSA_KEY_SLOT_COUNT];
unsigned key_slots_initialized : 1;
} psa_global_data_t;
static psa_global_data_t global_data;
int psa_is_valid_key_id( mbedtls_svc_key_id_t key, int vendor_ok )
{
psa_key_id_t key_id = MBEDTLS_SVC_KEY_ID_GET_KEY_ID( key );
if( ( PSA_KEY_ID_USER_MIN <= key_id ) &&
( key_id <= PSA_KEY_ID_USER_MAX ) )
return( 1 );
if( vendor_ok &&
( PSA_KEY_ID_VENDOR_MIN <= key_id ) &&
( key_id <= PSA_KEY_ID_VENDOR_MAX ) )
return( 1 );
return( 0 );
}
/** Get the description in memory of a key given its identifier and lock it.
*
* The descriptions of volatile keys and loaded persistent keys are
* stored in key slots. This function returns a pointer to the key slot
* containing the description of a key given its identifier.
*
* The function searches the key slots containing the description of the key
* with \p key identifier. The function does only read accesses to the key
* slots. The function does not load any persistent key thus does not access
* any storage.
*
* For volatile key identifiers, only one key slot is queried as a volatile
* key with identifier key_id can only be stored in slot of index
* ( key_id - #PSA_KEY_ID_VOLATILE_MIN ).
*
* On success, the function locks the key slot. It is the responsibility of
* the caller to unlock the key slot when it does not access it anymore.
*
* \param key Key identifier to query.
* \param[out] p_slot On success, `*p_slot` contains a pointer to the
* key slot containing the description of the key
* identified by \p key.
*
* \retval #PSA_SUCCESS
* The pointer to the key slot containing the description of the key
* identified by \p key was returned.
* \retval #PSA_ERROR_INVALID_HANDLE
* \p key is not a valid key identifier.
* \retval #PSA_ERROR_DOES_NOT_EXIST
* There is no key with key identifier \p key in the key slots.
*/
static psa_status_t psa_get_and_lock_key_slot_in_memory(
mbedtls_svc_key_id_t key, psa_key_slot_t **p_slot )
{
psa_status_t status = PSA_ERROR_CORRUPTION_DETECTED;
psa_key_id_t key_id = MBEDTLS_SVC_KEY_ID_GET_KEY_ID( key );
size_t slot_idx;
psa_key_slot_t *slot = NULL;
if( psa_key_id_is_volatile( key_id ) )
{
slot = &global_data.key_slots[ key_id - PSA_KEY_ID_VOLATILE_MIN ];
/*
* Check if both the PSA key identifier key_id and the owner
* identifier of key match those of the key slot.
*
* Note that, if the key slot is not occupied, its PSA key identifier
* is equal to zero. This is an invalid value for a PSA key identifier
* and thus cannot be equal to the valid PSA key identifier key_id.
*/
status = mbedtls_svc_key_id_equal( key, slot->attr.id ) ?
PSA_SUCCESS : PSA_ERROR_DOES_NOT_EXIST;
}
else
{
if ( !psa_is_valid_key_id( key, 1 ) )
return( PSA_ERROR_INVALID_HANDLE );
for( slot_idx = 0; slot_idx < MBEDTLS_PSA_KEY_SLOT_COUNT; slot_idx++ )
{
slot = &global_data.key_slots[ slot_idx ];
if( mbedtls_svc_key_id_equal( key, slot->attr.id ) )
break;
}
status = ( slot_idx < MBEDTLS_PSA_KEY_SLOT_COUNT ) ?
PSA_SUCCESS : PSA_ERROR_DOES_NOT_EXIST;
}
if( status == PSA_SUCCESS )
{
status = psa_lock_key_slot( slot );
if( status == PSA_SUCCESS )
*p_slot = slot;
}
return( status );
}
psa_status_t psa_initialize_key_slots( void )
{
/* Nothing to do: program startup and psa_wipe_all_key_slots() both
* guarantee that the key slots are initialized to all-zero, which
* means that all the key slots are in a valid, empty state. */
global_data.key_slots_initialized = 1;
return( PSA_SUCCESS );
}
void psa_wipe_all_key_slots( void )
{
size_t slot_idx;
for( slot_idx = 0; slot_idx < MBEDTLS_PSA_KEY_SLOT_COUNT; slot_idx++ )
{
psa_key_slot_t *slot = &global_data.key_slots[ slot_idx ];
slot->lock_count = 1;
(void) psa_wipe_key_slot( slot );
}
global_data.key_slots_initialized = 0;
}
psa_status_t psa_get_empty_key_slot( psa_key_id_t *volatile_key_id,
psa_key_slot_t **p_slot )
{
psa_status_t status = PSA_ERROR_CORRUPTION_DETECTED;
size_t slot_idx;
psa_key_slot_t *selected_slot, *unlocked_persistent_key_slot;
if( ! global_data.key_slots_initialized )
{
status = PSA_ERROR_BAD_STATE;
goto error;
}
selected_slot = unlocked_persistent_key_slot = NULL;
for( slot_idx = 0; slot_idx < MBEDTLS_PSA_KEY_SLOT_COUNT; slot_idx++ )
{
psa_key_slot_t *slot = &global_data.key_slots[ slot_idx ];
if( ! psa_is_key_slot_occupied( slot ) )
{
selected_slot = slot;
break;
}
if( ( unlocked_persistent_key_slot == NULL ) &&
( ! PSA_KEY_LIFETIME_IS_VOLATILE( slot->attr.lifetime ) ) &&
( ! psa_is_key_slot_locked( slot ) ) )
unlocked_persistent_key_slot = slot;
}
/*
* If there is no unused key slot and there is at least one unlocked key
* slot containing the description of a persistent key, recycle the first
* such key slot we encountered. If we later need to operate on the
* persistent key we are evicting now, we will reload its description from
* storage.
*/
if( ( selected_slot == NULL ) &&
( unlocked_persistent_key_slot != NULL ) )
{
selected_slot = unlocked_persistent_key_slot;
selected_slot->lock_count = 1;
psa_wipe_key_slot( selected_slot );
}
if( selected_slot != NULL )
{
status = psa_lock_key_slot( selected_slot );
if( status != PSA_SUCCESS )
goto error;
*volatile_key_id = PSA_KEY_ID_VOLATILE_MIN +
( (psa_key_id_t)( selected_slot - global_data.key_slots ) );
*p_slot = selected_slot;
return( PSA_SUCCESS );
}
status = PSA_ERROR_INSUFFICIENT_MEMORY;
error:
*p_slot = NULL;
*volatile_key_id = 0;
return( status );
}
#if defined(MBEDTLS_PSA_CRYPTO_STORAGE_C)
static psa_status_t psa_load_persistent_key_into_slot( psa_key_slot_t *slot )
{
psa_status_t status = PSA_SUCCESS;
uint8_t *key_data = NULL;
size_t key_data_length = 0;
status = psa_load_persistent_key( &slot->attr,
&key_data, &key_data_length );
if( status != PSA_SUCCESS )
goto exit;
#if defined(MBEDTLS_PSA_CRYPTO_SE_C)
/* Special handling is required for loading keys associated with a
* dynamically registered SE interface. */
const psa_drv_se_t *drv;
psa_drv_se_context_t *drv_context;
if( psa_get_se_driver( slot->attr.lifetime, &drv, &drv_context ) )
{
psa_se_key_data_storage_t *data;
if( key_data_length != sizeof( *data ) )
{
status = PSA_ERROR_DATA_INVALID;
goto exit;
}
data = (psa_se_key_data_storage_t *) key_data;
status = psa_copy_key_material_into_slot(
slot, data->slot_number, sizeof( data->slot_number ) );
goto exit;
}
#endif /* MBEDTLS_PSA_CRYPTO_SE_C */
status = psa_copy_key_material_into_slot( slot, key_data, key_data_length );
exit:
psa_free_persistent_key_data( key_data, key_data_length );
return( status );
}
#endif /* MBEDTLS_PSA_CRYPTO_STORAGE_C */
#if defined(MBEDTLS_PSA_CRYPTO_BUILTIN_KEYS)
static psa_status_t psa_load_builtin_key_into_slot( psa_key_slot_t *slot )
{
psa_status_t status = PSA_ERROR_CORRUPTION_DETECTED;
psa_key_attributes_t attributes = PSA_KEY_ATTRIBUTES_INIT;
psa_key_lifetime_t lifetime = PSA_KEY_LIFETIME_VOLATILE;
psa_drv_slot_number_t slot_number = 0;
size_t key_buffer_size = 0;
size_t key_buffer_length = 0;
if( ! psa_key_id_is_builtin(
MBEDTLS_SVC_KEY_ID_GET_KEY_ID( slot->attr.id ) ) )
{
return( PSA_ERROR_DOES_NOT_EXIST );
}
/* Check the platform function to see whether this key actually exists */
status = mbedtls_psa_platform_get_builtin_key(
slot->attr.id, &lifetime, &slot_number );
if( status != PSA_SUCCESS )
return( status );
/* Set required key attributes to ensure get_builtin_key can retrieve the
* full attributes. */
psa_set_key_id( &attributes, slot->attr.id );
psa_set_key_lifetime( &attributes, lifetime );
/* Get the full key attributes from the driver in order to be able to
* calculate the required buffer size. */
status = psa_driver_wrapper_get_builtin_key(
slot_number, &attributes,
NULL, 0, NULL );
if( status != PSA_ERROR_BUFFER_TOO_SMALL )
{
/* Builtin keys cannot be defined by the attributes alone */
if( status == PSA_SUCCESS )
status = PSA_ERROR_CORRUPTION_DETECTED;
return( status );
}
/* If the key should exist according to the platform, then ask the driver
* what its expected size is. */
status = psa_driver_wrapper_get_key_buffer_size( &attributes,
&key_buffer_size );
if( status != PSA_SUCCESS )
return( status );
/* Allocate a buffer of the required size and load the builtin key directly
* into the (now properly sized) slot buffer. */
status = psa_allocate_buffer_to_slot( slot, key_buffer_size );
if( status != PSA_SUCCESS )
return( status );
status = psa_driver_wrapper_get_builtin_key(
slot_number, &attributes,
slot->key.data, slot->key.bytes, &key_buffer_length );
if( status != PSA_SUCCESS )
goto exit;
/* Copy actual key length and core attributes into the slot on success */
slot->key.bytes = key_buffer_length;
slot->attr = attributes.core;
exit:
if( status != PSA_SUCCESS )
psa_remove_key_data_from_memory( slot );
return( status );
}
#endif /* MBEDTLS_PSA_CRYPTO_BUILTIN_KEYS */
psa_status_t psa_get_and_lock_key_slot( mbedtls_svc_key_id_t key,
psa_key_slot_t **p_slot )
{
psa_status_t status = PSA_ERROR_CORRUPTION_DETECTED;
*p_slot = NULL;
if( ! global_data.key_slots_initialized )
return( PSA_ERROR_BAD_STATE );
/*
* On success, the pointer to the slot is passed directly to the caller
* thus no need to unlock the key slot here.
*/
status = psa_get_and_lock_key_slot_in_memory( key, p_slot );
if( status != PSA_ERROR_DOES_NOT_EXIST )
return( status );
/* Loading keys from storage requires support for such a mechanism */
#if defined(MBEDTLS_PSA_CRYPTO_STORAGE_C) || \
defined(MBEDTLS_PSA_CRYPTO_BUILTIN_KEYS)
psa_key_id_t volatile_key_id;
status = psa_get_empty_key_slot( &volatile_key_id, p_slot );
if( status != PSA_SUCCESS )
return( status );
(*p_slot)->attr.id = key;
(*p_slot)->attr.lifetime = PSA_KEY_LIFETIME_PERSISTENT;
status = PSA_ERROR_DOES_NOT_EXIST;
#if defined(MBEDTLS_PSA_CRYPTO_BUILTIN_KEYS)
/* Load keys in the 'builtin' range through their own interface */
status = psa_load_builtin_key_into_slot( *p_slot );
#endif /* MBEDTLS_PSA_CRYPTO_BUILTIN_KEYS */
#if defined(MBEDTLS_PSA_CRYPTO_STORAGE_C)
if( status == PSA_ERROR_DOES_NOT_EXIST )
status = psa_load_persistent_key_into_slot( *p_slot );
#endif /* defined(MBEDTLS_PSA_CRYPTO_STORAGE_C) */
if( status != PSA_SUCCESS )
{
psa_wipe_key_slot( *p_slot );
if( status == PSA_ERROR_DOES_NOT_EXIST )
status = PSA_ERROR_INVALID_HANDLE;
}
else
/* Add implicit usage flags. */
psa_extend_key_usage_flags( &(*p_slot)->attr.policy.usage );
return( status );
#else /* MBEDTLS_PSA_CRYPTO_STORAGE_C || MBEDTLS_PSA_CRYPTO_BUILTIN_KEYS */
return( PSA_ERROR_INVALID_HANDLE );
#endif /* MBEDTLS_PSA_CRYPTO_STORAGE_C || MBEDTLS_PSA_CRYPTO_BUILTIN_KEYS */
}
psa_status_t psa_unlock_key_slot( psa_key_slot_t *slot )
{
if( slot == NULL )
return( PSA_SUCCESS );
if( slot->lock_count > 0 )
{
slot->lock_count--;
return( PSA_SUCCESS );
}
/*
* As the return error code may not be handled in case of multiple errors,
* do our best to report if the lock counter is equal to zero: if
* available call MBEDTLS_PARAM_FAILED that may terminate execution (if
* called as part of the execution of a unit test suite this will stop the
* test suite execution).
*/
#ifdef MBEDTLS_CHECK_PARAMS
MBEDTLS_PARAM_FAILED( slot->lock_count > 0 );
#endif
return( PSA_ERROR_CORRUPTION_DETECTED );
}
psa_status_t psa_validate_key_location( psa_key_lifetime_t lifetime,
psa_se_drv_table_entry_t **p_drv )
{
if ( psa_key_lifetime_is_external( lifetime ) )
{
#if defined(MBEDTLS_PSA_CRYPTO_SE_C)
/* Check whether a driver is registered against this lifetime */
psa_se_drv_table_entry_t *driver = psa_get_se_driver_entry( lifetime );
if( driver != NULL )
{
if (p_drv != NULL)
*p_drv = driver;
return( PSA_SUCCESS );
}
#else /* MBEDTLS_PSA_CRYPTO_SE_C */
(void) p_drv;
#endif /* MBEDTLS_PSA_CRYPTO_SE_C */
#if defined(MBEDTLS_PSA_CRYPTO_DRIVERS)
/* Key location for external keys gets checked by the wrapper */
return( PSA_SUCCESS );
#else /* MBEDTLS_PSA_CRYPTO_DRIVERS */
/* No support for external lifetimes at all, or dynamic interface
* did not find driver for requested lifetime. */
return( PSA_ERROR_INVALID_ARGUMENT );
#endif /* MBEDTLS_PSA_CRYPTO_DRIVERS */
}
else
/* Local/internal keys are always valid */
return( PSA_SUCCESS );
}
psa_status_t psa_validate_key_persistence( psa_key_lifetime_t lifetime )
{
if ( PSA_KEY_LIFETIME_IS_VOLATILE( lifetime ) )
{
/* Volatile keys are always supported */
return( PSA_SUCCESS );
}
else
{
/* Persistent keys require storage support */
#if defined(MBEDTLS_PSA_CRYPTO_STORAGE_C)
if( PSA_KEY_LIFETIME_IS_READ_ONLY( lifetime ) )
return( PSA_ERROR_INVALID_ARGUMENT );
else
return( PSA_SUCCESS );
#else /* MBEDTLS_PSA_CRYPTO_STORAGE_C */
return( PSA_ERROR_NOT_SUPPORTED );
#endif /* !MBEDTLS_PSA_CRYPTO_STORAGE_C */
}
}
psa_status_t psa_open_key( mbedtls_svc_key_id_t key, psa_key_handle_t *handle )
{
#if defined(MBEDTLS_PSA_CRYPTO_STORAGE_C)
psa_status_t status;
psa_key_slot_t *slot;
status = psa_get_and_lock_key_slot( key, &slot );
if( status != PSA_SUCCESS )
{
*handle = PSA_KEY_HANDLE_INIT;
if( status == PSA_ERROR_INVALID_HANDLE )
status = PSA_ERROR_DOES_NOT_EXIST;
return( status );
}
*handle = key;
return( psa_unlock_key_slot( slot ) );
#else /* defined(MBEDTLS_PSA_CRYPTO_STORAGE_C) */
(void) key;
*handle = PSA_KEY_HANDLE_INIT;
return( PSA_ERROR_NOT_SUPPORTED );
#endif /* !defined(MBEDTLS_PSA_CRYPTO_STORAGE_C) */
}
psa_status_t psa_close_key( psa_key_handle_t handle )
{
psa_status_t status;
psa_key_slot_t *slot;
if( psa_key_handle_is_null( handle ) )
return( PSA_SUCCESS );
status = psa_get_and_lock_key_slot_in_memory( handle, &slot );
if( status != PSA_SUCCESS )
{
if( status == PSA_ERROR_DOES_NOT_EXIST )
status = PSA_ERROR_INVALID_HANDLE;
return( status );
}
if( slot->lock_count <= 1 )
return( psa_wipe_key_slot( slot ) );
else
return( psa_unlock_key_slot( slot ) );
}
psa_status_t psa_purge_key( mbedtls_svc_key_id_t key )
{
psa_status_t status;
psa_key_slot_t *slot;
status = psa_get_and_lock_key_slot_in_memory( key, &slot );
if( status != PSA_SUCCESS )
return( status );
if( ( ! PSA_KEY_LIFETIME_IS_VOLATILE( slot->attr.lifetime ) ) &&
( slot->lock_count <= 1 ) )
return( psa_wipe_key_slot( slot ) );
else
return( psa_unlock_key_slot( slot ) );
}
void mbedtls_psa_get_stats( mbedtls_psa_stats_t *stats )
{
size_t slot_idx;
memset( stats, 0, sizeof( *stats ) );
for( slot_idx = 0; slot_idx < MBEDTLS_PSA_KEY_SLOT_COUNT; slot_idx++ )
{
const psa_key_slot_t *slot = &global_data.key_slots[ slot_idx ];
if( psa_is_key_slot_locked( slot ) )
{
++stats->locked_slots;
}
if( ! psa_is_key_slot_occupied( slot ) )
{
++stats->empty_slots;
continue;
}
if( PSA_KEY_LIFETIME_IS_VOLATILE( slot->attr.lifetime ) )
++stats->volatile_slots;
else
{
psa_key_id_t id = MBEDTLS_SVC_KEY_ID_GET_KEY_ID( slot->attr.id );
++stats->persistent_slots;
if( id > stats->max_open_internal_key_id )
stats->max_open_internal_key_id = id;
}
if( PSA_KEY_LIFETIME_GET_LOCATION( slot->attr.lifetime ) !=
PSA_KEY_LOCATION_LOCAL_STORAGE )
{
psa_key_id_t id = MBEDTLS_SVC_KEY_ID_GET_KEY_ID( slot->attr.id );
++stats->external_slots;
if( id > stats->max_open_external_key_id )
stats->max_open_external_key_id = id;
}
}
}
#endif /* MBEDTLS_PSA_CRYPTO_C */
|
0 | repos/gpt4all.zig/src/zig-libcurl/zig-mbedtls/mbedtls | repos/gpt4all.zig/src/zig-libcurl/zig-mbedtls/mbedtls/library/havege.c | /**
* \brief HAVEGE: HArdware Volatile Entropy Gathering and Expansion
*
* Copyright The Mbed TLS Contributors
* SPDX-License-Identifier: Apache-2.0
*
* 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.
*/
/*
* The HAVEGE RNG was designed by Andre Seznec in 2002.
*
* http://www.irisa.fr/caps/projects/hipsor/publi.php
*
* Contact: seznec(at)irisa_dot_fr - orocheco(at)irisa_dot_fr
*/
#include "common.h"
#if defined(MBEDTLS_HAVEGE_C)
#include "mbedtls/havege.h"
#include "mbedtls/timing.h"
#include "mbedtls/platform_util.h"
#include <stdint.h>
#include <string.h>
/* ------------------------------------------------------------------------
* On average, one iteration accesses two 8-word blocks in the havege WALK
* table, and generates 16 words in the RES array.
*
* The data read in the WALK table is updated and permuted after each use.
* The result of the hardware clock counter read is used for this update.
*
* 25 conditional tests are present. The conditional tests are grouped in
* two nested groups of 12 conditional tests and 1 test that controls the
* permutation; on average, there should be 6 tests executed and 3 of them
* should be mispredicted.
* ------------------------------------------------------------------------
*/
#define SWAP(X,Y) { uint32_t *T = (X); (X) = (Y); (Y) = T; }
#define TST1_ENTER if( PTEST & 1 ) { PTEST ^= 3; PTEST >>= 1;
#define TST2_ENTER if( PTEST & 1 ) { PTEST ^= 3; PTEST >>= 1;
#define TST1_LEAVE U1++; }
#define TST2_LEAVE U2++; }
#define ONE_ITERATION \
\
PTEST = PT1 >> 20; \
\
TST1_ENTER TST1_ENTER TST1_ENTER TST1_ENTER \
TST1_ENTER TST1_ENTER TST1_ENTER TST1_ENTER \
TST1_ENTER TST1_ENTER TST1_ENTER TST1_ENTER \
\
TST1_LEAVE TST1_LEAVE TST1_LEAVE TST1_LEAVE \
TST1_LEAVE TST1_LEAVE TST1_LEAVE TST1_LEAVE \
TST1_LEAVE TST1_LEAVE TST1_LEAVE TST1_LEAVE \
\
PTX = (PT1 >> 18) & 7; \
PT1 &= 0x1FFF; \
PT2 &= 0x1FFF; \
CLK = (uint32_t) mbedtls_timing_hardclock(); \
\
i = 0; \
A = &WALK[PT1 ]; RES[i++] ^= *A; \
B = &WALK[PT2 ]; RES[i++] ^= *B; \
C = &WALK[PT1 ^ 1]; RES[i++] ^= *C; \
D = &WALK[PT2 ^ 4]; RES[i++] ^= *D; \
\
IN = (*A >> (1)) ^ (*A << (31)) ^ CLK; \
*A = (*B >> (2)) ^ (*B << (30)) ^ CLK; \
*B = IN ^ U1; \
*C = (*C >> (3)) ^ (*C << (29)) ^ CLK; \
*D = (*D >> (4)) ^ (*D << (28)) ^ CLK; \
\
A = &WALK[PT1 ^ 2]; RES[i++] ^= *A; \
B = &WALK[PT2 ^ 2]; RES[i++] ^= *B; \
C = &WALK[PT1 ^ 3]; RES[i++] ^= *C; \
D = &WALK[PT2 ^ 6]; RES[i++] ^= *D; \
\
if( PTEST & 1 ) SWAP( A, C ); \
\
IN = (*A >> (5)) ^ (*A << (27)) ^ CLK; \
*A = (*B >> (6)) ^ (*B << (26)) ^ CLK; \
*B = IN; CLK = (uint32_t) mbedtls_timing_hardclock(); \
*C = (*C >> (7)) ^ (*C << (25)) ^ CLK; \
*D = (*D >> (8)) ^ (*D << (24)) ^ CLK; \
\
A = &WALK[PT1 ^ 4]; \
B = &WALK[PT2 ^ 1]; \
\
PTEST = PT2 >> 1; \
\
PT2 = (RES[(i - 8) ^ PTY] ^ WALK[PT2 ^ PTY ^ 7]); \
PT2 = ((PT2 & 0x1FFF) & (~8)) ^ ((PT1 ^ 8) & 0x8); \
PTY = (PT2 >> 10) & 7; \
\
TST2_ENTER TST2_ENTER TST2_ENTER TST2_ENTER \
TST2_ENTER TST2_ENTER TST2_ENTER TST2_ENTER \
TST2_ENTER TST2_ENTER TST2_ENTER TST2_ENTER \
\
TST2_LEAVE TST2_LEAVE TST2_LEAVE TST2_LEAVE \
TST2_LEAVE TST2_LEAVE TST2_LEAVE TST2_LEAVE \
TST2_LEAVE TST2_LEAVE TST2_LEAVE TST2_LEAVE \
\
C = &WALK[PT1 ^ 5]; \
D = &WALK[PT2 ^ 5]; \
\
RES[i++] ^= *A; \
RES[i++] ^= *B; \
RES[i++] ^= *C; \
RES[i++] ^= *D; \
\
IN = (*A >> ( 9)) ^ (*A << (23)) ^ CLK; \
*A = (*B >> (10)) ^ (*B << (22)) ^ CLK; \
*B = IN ^ U2; \
*C = (*C >> (11)) ^ (*C << (21)) ^ CLK; \
*D = (*D >> (12)) ^ (*D << (20)) ^ CLK; \
\
A = &WALK[PT1 ^ 6]; RES[i++] ^= *A; \
B = &WALK[PT2 ^ 3]; RES[i++] ^= *B; \
C = &WALK[PT1 ^ 7]; RES[i++] ^= *C; \
D = &WALK[PT2 ^ 7]; RES[i++] ^= *D; \
\
IN = (*A >> (13)) ^ (*A << (19)) ^ CLK; \
*A = (*B >> (14)) ^ (*B << (18)) ^ CLK; \
*B = IN; \
*C = (*C >> (15)) ^ (*C << (17)) ^ CLK; \
*D = (*D >> (16)) ^ (*D << (16)) ^ CLK; \
\
PT1 = ( RES[( i - 8 ) ^ PTX] ^ \
WALK[PT1 ^ PTX ^ 7] ) & (~1); \
PT1 ^= (PT2 ^ 0x10) & 0x10; \
\
for( n++, i = 0; i < 16; i++ ) \
hs->pool[n % MBEDTLS_HAVEGE_COLLECT_SIZE] ^= RES[i];
/*
* Entropy gathering function
*/
static void havege_fill( mbedtls_havege_state *hs )
{
size_t n = 0;
size_t i;
uint32_t U1, U2, *A, *B, *C, *D;
uint32_t PT1, PT2, *WALK, RES[16];
uint32_t PTX, PTY, CLK, PTEST, IN;
WALK = hs->WALK;
PT1 = hs->PT1;
PT2 = hs->PT2;
PTX = U1 = 0;
PTY = U2 = 0;
(void)PTX;
memset( RES, 0, sizeof( RES ) );
while( n < MBEDTLS_HAVEGE_COLLECT_SIZE * 4 )
{
ONE_ITERATION
ONE_ITERATION
ONE_ITERATION
ONE_ITERATION
}
hs->PT1 = PT1;
hs->PT2 = PT2;
hs->offset[0] = 0;
hs->offset[1] = MBEDTLS_HAVEGE_COLLECT_SIZE / 2;
}
/*
* HAVEGE initialization
*/
void mbedtls_havege_init( mbedtls_havege_state *hs )
{
memset( hs, 0, sizeof( mbedtls_havege_state ) );
havege_fill( hs );
}
void mbedtls_havege_free( mbedtls_havege_state *hs )
{
if( hs == NULL )
return;
mbedtls_platform_zeroize( hs, sizeof( mbedtls_havege_state ) );
}
/*
* HAVEGE rand function
*/
int mbedtls_havege_random( void *p_rng, unsigned char *buf, size_t len )
{
uint32_t val;
size_t use_len;
mbedtls_havege_state *hs = (mbedtls_havege_state *) p_rng;
unsigned char *p = buf;
while( len > 0 )
{
use_len = len;
if( use_len > sizeof( val ) )
use_len = sizeof( val );
if( hs->offset[1] >= MBEDTLS_HAVEGE_COLLECT_SIZE )
havege_fill( hs );
val = hs->pool[hs->offset[0]++];
val ^= hs->pool[hs->offset[1]++];
memcpy( p, &val, use_len );
len -= use_len;
p += use_len;
}
return( 0 );
}
#endif /* MBEDTLS_HAVEGE_C */
|
0 | repos/gpt4all.zig/src/zig-libcurl/zig-mbedtls/mbedtls | repos/gpt4all.zig/src/zig-libcurl/zig-mbedtls/mbedtls/library/sha512.c | /*
* FIPS-180-2 compliant SHA-384/512 implementation
*
* Copyright The Mbed TLS Contributors
* SPDX-License-Identifier: Apache-2.0
*
* 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.
*/
/*
* The SHA-512 Secure Hash Standard was published by NIST in 2002.
*
* http://csrc.nist.gov/publications/fips/fips180-2/fips180-2.pdf
*/
#include "common.h"
#if defined(MBEDTLS_SHA512_C)
#include "mbedtls/sha512.h"
#include "mbedtls/platform_util.h"
#include "mbedtls/error.h"
#if defined(_MSC_VER) || defined(__WATCOMC__)
#define UL64(x) x##ui64
#else
#define UL64(x) x##ULL
#endif
#include <string.h>
#if defined(MBEDTLS_SELF_TEST)
#if defined(MBEDTLS_PLATFORM_C)
#include "mbedtls/platform.h"
#else
#include <stdio.h>
#include <stdlib.h>
#define mbedtls_printf printf
#define mbedtls_calloc calloc
#define mbedtls_free free
#endif /* MBEDTLS_PLATFORM_C */
#endif /* MBEDTLS_SELF_TEST */
#define SHA512_VALIDATE_RET(cond) \
MBEDTLS_INTERNAL_VALIDATE_RET( cond, MBEDTLS_ERR_SHA512_BAD_INPUT_DATA )
#define SHA512_VALIDATE(cond) MBEDTLS_INTERNAL_VALIDATE( cond )
#if !defined(MBEDTLS_SHA512_ALT)
/*
* 64-bit integer manipulation macros (big endian)
*/
#ifndef GET_UINT64_BE
#define GET_UINT64_BE(n,b,i) \
{ \
(n) = ( (uint64_t) (b)[(i) ] << 56 ) \
| ( (uint64_t) (b)[(i) + 1] << 48 ) \
| ( (uint64_t) (b)[(i) + 2] << 40 ) \
| ( (uint64_t) (b)[(i) + 3] << 32 ) \
| ( (uint64_t) (b)[(i) + 4] << 24 ) \
| ( (uint64_t) (b)[(i) + 5] << 16 ) \
| ( (uint64_t) (b)[(i) + 6] << 8 ) \
| ( (uint64_t) (b)[(i) + 7] ); \
}
#endif /* GET_UINT64_BE */
#ifndef PUT_UINT64_BE
#define PUT_UINT64_BE(n,b,i) \
{ \
(b)[(i) ] = (unsigned char) ( (n) >> 56 ); \
(b)[(i) + 1] = (unsigned char) ( (n) >> 48 ); \
(b)[(i) + 2] = (unsigned char) ( (n) >> 40 ); \
(b)[(i) + 3] = (unsigned char) ( (n) >> 32 ); \
(b)[(i) + 4] = (unsigned char) ( (n) >> 24 ); \
(b)[(i) + 5] = (unsigned char) ( (n) >> 16 ); \
(b)[(i) + 6] = (unsigned char) ( (n) >> 8 ); \
(b)[(i) + 7] = (unsigned char) ( (n) ); \
}
#endif /* PUT_UINT64_BE */
#if defined(MBEDTLS_SHA512_SMALLER)
static void sha512_put_uint64_be( uint64_t n, unsigned char *b, uint8_t i )
{
PUT_UINT64_BE(n, b, i);
}
#else
#define sha512_put_uint64_be PUT_UINT64_BE
#endif /* MBEDTLS_SHA512_SMALLER */
void mbedtls_sha512_init( mbedtls_sha512_context *ctx )
{
SHA512_VALIDATE( ctx != NULL );
memset( ctx, 0, sizeof( mbedtls_sha512_context ) );
}
void mbedtls_sha512_free( mbedtls_sha512_context *ctx )
{
if( ctx == NULL )
return;
mbedtls_platform_zeroize( ctx, sizeof( mbedtls_sha512_context ) );
}
void mbedtls_sha512_clone( mbedtls_sha512_context *dst,
const mbedtls_sha512_context *src )
{
SHA512_VALIDATE( dst != NULL );
SHA512_VALIDATE( src != NULL );
*dst = *src;
}
/*
* SHA-512 context setup
*/
int mbedtls_sha512_starts_ret( mbedtls_sha512_context *ctx, int is384 )
{
SHA512_VALIDATE_RET( ctx != NULL );
#if !defined(MBEDTLS_SHA512_NO_SHA384)
SHA512_VALIDATE_RET( is384 == 0 || is384 == 1 );
#else
SHA512_VALIDATE_RET( is384 == 0 );
#endif
ctx->total[0] = 0;
ctx->total[1] = 0;
if( is384 == 0 )
{
/* SHA-512 */
ctx->state[0] = UL64(0x6A09E667F3BCC908);
ctx->state[1] = UL64(0xBB67AE8584CAA73B);
ctx->state[2] = UL64(0x3C6EF372FE94F82B);
ctx->state[3] = UL64(0xA54FF53A5F1D36F1);
ctx->state[4] = UL64(0x510E527FADE682D1);
ctx->state[5] = UL64(0x9B05688C2B3E6C1F);
ctx->state[6] = UL64(0x1F83D9ABFB41BD6B);
ctx->state[7] = UL64(0x5BE0CD19137E2179);
}
else
{
#if defined(MBEDTLS_SHA512_NO_SHA384)
return( MBEDTLS_ERR_SHA512_BAD_INPUT_DATA );
#else
/* SHA-384 */
ctx->state[0] = UL64(0xCBBB9D5DC1059ED8);
ctx->state[1] = UL64(0x629A292A367CD507);
ctx->state[2] = UL64(0x9159015A3070DD17);
ctx->state[3] = UL64(0x152FECD8F70E5939);
ctx->state[4] = UL64(0x67332667FFC00B31);
ctx->state[5] = UL64(0x8EB44A8768581511);
ctx->state[6] = UL64(0xDB0C2E0D64F98FA7);
ctx->state[7] = UL64(0x47B5481DBEFA4FA4);
#endif /* MBEDTLS_SHA512_NO_SHA384 */
}
#if !defined(MBEDTLS_SHA512_NO_SHA384)
ctx->is384 = is384;
#endif
return( 0 );
}
#if !defined(MBEDTLS_DEPRECATED_REMOVED)
void mbedtls_sha512_starts( mbedtls_sha512_context *ctx,
int is384 )
{
mbedtls_sha512_starts_ret( ctx, is384 );
}
#endif
#if !defined(MBEDTLS_SHA512_PROCESS_ALT)
/*
* Round constants
*/
static const uint64_t K[80] =
{
UL64(0x428A2F98D728AE22), UL64(0x7137449123EF65CD),
UL64(0xB5C0FBCFEC4D3B2F), UL64(0xE9B5DBA58189DBBC),
UL64(0x3956C25BF348B538), UL64(0x59F111F1B605D019),
UL64(0x923F82A4AF194F9B), UL64(0xAB1C5ED5DA6D8118),
UL64(0xD807AA98A3030242), UL64(0x12835B0145706FBE),
UL64(0x243185BE4EE4B28C), UL64(0x550C7DC3D5FFB4E2),
UL64(0x72BE5D74F27B896F), UL64(0x80DEB1FE3B1696B1),
UL64(0x9BDC06A725C71235), UL64(0xC19BF174CF692694),
UL64(0xE49B69C19EF14AD2), UL64(0xEFBE4786384F25E3),
UL64(0x0FC19DC68B8CD5B5), UL64(0x240CA1CC77AC9C65),
UL64(0x2DE92C6F592B0275), UL64(0x4A7484AA6EA6E483),
UL64(0x5CB0A9DCBD41FBD4), UL64(0x76F988DA831153B5),
UL64(0x983E5152EE66DFAB), UL64(0xA831C66D2DB43210),
UL64(0xB00327C898FB213F), UL64(0xBF597FC7BEEF0EE4),
UL64(0xC6E00BF33DA88FC2), UL64(0xD5A79147930AA725),
UL64(0x06CA6351E003826F), UL64(0x142929670A0E6E70),
UL64(0x27B70A8546D22FFC), UL64(0x2E1B21385C26C926),
UL64(0x4D2C6DFC5AC42AED), UL64(0x53380D139D95B3DF),
UL64(0x650A73548BAF63DE), UL64(0x766A0ABB3C77B2A8),
UL64(0x81C2C92E47EDAEE6), UL64(0x92722C851482353B),
UL64(0xA2BFE8A14CF10364), UL64(0xA81A664BBC423001),
UL64(0xC24B8B70D0F89791), UL64(0xC76C51A30654BE30),
UL64(0xD192E819D6EF5218), UL64(0xD69906245565A910),
UL64(0xF40E35855771202A), UL64(0x106AA07032BBD1B8),
UL64(0x19A4C116B8D2D0C8), UL64(0x1E376C085141AB53),
UL64(0x2748774CDF8EEB99), UL64(0x34B0BCB5E19B48A8),
UL64(0x391C0CB3C5C95A63), UL64(0x4ED8AA4AE3418ACB),
UL64(0x5B9CCA4F7763E373), UL64(0x682E6FF3D6B2B8A3),
UL64(0x748F82EE5DEFB2FC), UL64(0x78A5636F43172F60),
UL64(0x84C87814A1F0AB72), UL64(0x8CC702081A6439EC),
UL64(0x90BEFFFA23631E28), UL64(0xA4506CEBDE82BDE9),
UL64(0xBEF9A3F7B2C67915), UL64(0xC67178F2E372532B),
UL64(0xCA273ECEEA26619C), UL64(0xD186B8C721C0C207),
UL64(0xEADA7DD6CDE0EB1E), UL64(0xF57D4F7FEE6ED178),
UL64(0x06F067AA72176FBA), UL64(0x0A637DC5A2C898A6),
UL64(0x113F9804BEF90DAE), UL64(0x1B710B35131C471B),
UL64(0x28DB77F523047D84), UL64(0x32CAAB7B40C72493),
UL64(0x3C9EBE0A15C9BEBC), UL64(0x431D67C49C100D4C),
UL64(0x4CC5D4BECB3E42B6), UL64(0x597F299CFC657E2A),
UL64(0x5FCB6FAB3AD6FAEC), UL64(0x6C44198C4A475817)
};
int mbedtls_internal_sha512_process( mbedtls_sha512_context *ctx,
const unsigned char data[128] )
{
int i;
struct
{
uint64_t temp1, temp2, W[80];
uint64_t A[8];
} local;
SHA512_VALIDATE_RET( ctx != NULL );
SHA512_VALIDATE_RET( (const unsigned char *)data != NULL );
#define SHR(x,n) ((x) >> (n))
#define ROTR(x,n) (SHR((x),(n)) | ((x) << (64 - (n))))
#define S0(x) (ROTR(x, 1) ^ ROTR(x, 8) ^ SHR(x, 7))
#define S1(x) (ROTR(x,19) ^ ROTR(x,61) ^ SHR(x, 6))
#define S2(x) (ROTR(x,28) ^ ROTR(x,34) ^ ROTR(x,39))
#define S3(x) (ROTR(x,14) ^ ROTR(x,18) ^ ROTR(x,41))
#define F0(x,y,z) (((x) & (y)) | ((z) & ((x) | (y))))
#define F1(x,y,z) ((z) ^ ((x) & ((y) ^ (z))))
#define P(a,b,c,d,e,f,g,h,x,K) \
do \
{ \
local.temp1 = (h) + S3(e) + F1((e),(f),(g)) + (K) + (x); \
local.temp2 = S2(a) + F0((a),(b),(c)); \
(d) += local.temp1; (h) = local.temp1 + local.temp2; \
} while( 0 )
for( i = 0; i < 8; i++ )
local.A[i] = ctx->state[i];
#if defined(MBEDTLS_SHA512_SMALLER)
for( i = 0; i < 80; i++ )
{
if( i < 16 )
{
GET_UINT64_BE( local.W[i], data, i << 3 );
}
else
{
local.W[i] = S1(local.W[i - 2]) + local.W[i - 7] +
S0(local.W[i - 15]) + local.W[i - 16];
}
P( local.A[0], local.A[1], local.A[2], local.A[3], local.A[4],
local.A[5], local.A[6], local.A[7], local.W[i], K[i] );
local.temp1 = local.A[7]; local.A[7] = local.A[6];
local.A[6] = local.A[5]; local.A[5] = local.A[4];
local.A[4] = local.A[3]; local.A[3] = local.A[2];
local.A[2] = local.A[1]; local.A[1] = local.A[0];
local.A[0] = local.temp1;
}
#else /* MBEDTLS_SHA512_SMALLER */
for( i = 0; i < 16; i++ )
{
GET_UINT64_BE( local.W[i], data, i << 3 );
}
for( ; i < 80; i++ )
{
local.W[i] = S1(local.W[i - 2]) + local.W[i - 7] +
S0(local.W[i - 15]) + local.W[i - 16];
}
i = 0;
do
{
P( local.A[0], local.A[1], local.A[2], local.A[3], local.A[4],
local.A[5], local.A[6], local.A[7], local.W[i], K[i] ); i++;
P( local.A[7], local.A[0], local.A[1], local.A[2], local.A[3],
local.A[4], local.A[5], local.A[6], local.W[i], K[i] ); i++;
P( local.A[6], local.A[7], local.A[0], local.A[1], local.A[2],
local.A[3], local.A[4], local.A[5], local.W[i], K[i] ); i++;
P( local.A[5], local.A[6], local.A[7], local.A[0], local.A[1],
local.A[2], local.A[3], local.A[4], local.W[i], K[i] ); i++;
P( local.A[4], local.A[5], local.A[6], local.A[7], local.A[0],
local.A[1], local.A[2], local.A[3], local.W[i], K[i] ); i++;
P( local.A[3], local.A[4], local.A[5], local.A[6], local.A[7],
local.A[0], local.A[1], local.A[2], local.W[i], K[i] ); i++;
P( local.A[2], local.A[3], local.A[4], local.A[5], local.A[6],
local.A[7], local.A[0], local.A[1], local.W[i], K[i] ); i++;
P( local.A[1], local.A[2], local.A[3], local.A[4], local.A[5],
local.A[6], local.A[7], local.A[0], local.W[i], K[i] ); i++;
}
while( i < 80 );
#endif /* MBEDTLS_SHA512_SMALLER */
for( i = 0; i < 8; i++ )
ctx->state[i] += local.A[i];
/* Zeroise buffers and variables to clear sensitive data from memory. */
mbedtls_platform_zeroize( &local, sizeof( local ) );
return( 0 );
}
#if !defined(MBEDTLS_DEPRECATED_REMOVED)
void mbedtls_sha512_process( mbedtls_sha512_context *ctx,
const unsigned char data[128] )
{
mbedtls_internal_sha512_process( ctx, data );
}
#endif
#endif /* !MBEDTLS_SHA512_PROCESS_ALT */
/*
* SHA-512 process buffer
*/
int mbedtls_sha512_update_ret( mbedtls_sha512_context *ctx,
const unsigned char *input,
size_t ilen )
{
int ret = MBEDTLS_ERR_ERROR_CORRUPTION_DETECTED;
size_t fill;
unsigned int left;
SHA512_VALIDATE_RET( ctx != NULL );
SHA512_VALIDATE_RET( ilen == 0 || input != NULL );
if( ilen == 0 )
return( 0 );
left = (unsigned int) (ctx->total[0] & 0x7F);
fill = 128 - left;
ctx->total[0] += (uint64_t) ilen;
if( ctx->total[0] < (uint64_t) ilen )
ctx->total[1]++;
if( left && ilen >= fill )
{
memcpy( (void *) (ctx->buffer + left), input, fill );
if( ( ret = mbedtls_internal_sha512_process( ctx, ctx->buffer ) ) != 0 )
return( ret );
input += fill;
ilen -= fill;
left = 0;
}
while( ilen >= 128 )
{
if( ( ret = mbedtls_internal_sha512_process( ctx, input ) ) != 0 )
return( ret );
input += 128;
ilen -= 128;
}
if( ilen > 0 )
memcpy( (void *) (ctx->buffer + left), input, ilen );
return( 0 );
}
#if !defined(MBEDTLS_DEPRECATED_REMOVED)
void mbedtls_sha512_update( mbedtls_sha512_context *ctx,
const unsigned char *input,
size_t ilen )
{
mbedtls_sha512_update_ret( ctx, input, ilen );
}
#endif
/*
* SHA-512 final digest
*/
int mbedtls_sha512_finish_ret( mbedtls_sha512_context *ctx,
unsigned char output[64] )
{
int ret = MBEDTLS_ERR_ERROR_CORRUPTION_DETECTED;
unsigned used;
uint64_t high, low;
SHA512_VALIDATE_RET( ctx != NULL );
SHA512_VALIDATE_RET( (unsigned char *)output != NULL );
/*
* Add padding: 0x80 then 0x00 until 16 bytes remain for the length
*/
used = ctx->total[0] & 0x7F;
ctx->buffer[used++] = 0x80;
if( used <= 112 )
{
/* Enough room for padding + length in current block */
memset( ctx->buffer + used, 0, 112 - used );
}
else
{
/* We'll need an extra block */
memset( ctx->buffer + used, 0, 128 - used );
if( ( ret = mbedtls_internal_sha512_process( ctx, ctx->buffer ) ) != 0 )
return( ret );
memset( ctx->buffer, 0, 112 );
}
/*
* Add message length
*/
high = ( ctx->total[0] >> 61 )
| ( ctx->total[1] << 3 );
low = ( ctx->total[0] << 3 );
sha512_put_uint64_be( high, ctx->buffer, 112 );
sha512_put_uint64_be( low, ctx->buffer, 120 );
if( ( ret = mbedtls_internal_sha512_process( ctx, ctx->buffer ) ) != 0 )
return( ret );
/*
* Output final state
*/
sha512_put_uint64_be( ctx->state[0], output, 0 );
sha512_put_uint64_be( ctx->state[1], output, 8 );
sha512_put_uint64_be( ctx->state[2], output, 16 );
sha512_put_uint64_be( ctx->state[3], output, 24 );
sha512_put_uint64_be( ctx->state[4], output, 32 );
sha512_put_uint64_be( ctx->state[5], output, 40 );
#if !defined(MBEDTLS_SHA512_NO_SHA384)
if( ctx->is384 == 0 )
#endif
{
sha512_put_uint64_be( ctx->state[6], output, 48 );
sha512_put_uint64_be( ctx->state[7], output, 56 );
}
return( 0 );
}
#if !defined(MBEDTLS_DEPRECATED_REMOVED)
void mbedtls_sha512_finish( mbedtls_sha512_context *ctx,
unsigned char output[64] )
{
mbedtls_sha512_finish_ret( ctx, output );
}
#endif
#endif /* !MBEDTLS_SHA512_ALT */
/*
* output = SHA-512( input buffer )
*/
int mbedtls_sha512_ret( const unsigned char *input,
size_t ilen,
unsigned char output[64],
int is384 )
{
int ret = MBEDTLS_ERR_ERROR_CORRUPTION_DETECTED;
mbedtls_sha512_context ctx;
#if !defined(MBEDTLS_SHA512_NO_SHA384)
SHA512_VALIDATE_RET( is384 == 0 || is384 == 1 );
#else
SHA512_VALIDATE_RET( is384 == 0 );
#endif
SHA512_VALIDATE_RET( ilen == 0 || input != NULL );
SHA512_VALIDATE_RET( (unsigned char *)output != NULL );
mbedtls_sha512_init( &ctx );
if( ( ret = mbedtls_sha512_starts_ret( &ctx, is384 ) ) != 0 )
goto exit;
if( ( ret = mbedtls_sha512_update_ret( &ctx, input, ilen ) ) != 0 )
goto exit;
if( ( ret = mbedtls_sha512_finish_ret( &ctx, output ) ) != 0 )
goto exit;
exit:
mbedtls_sha512_free( &ctx );
return( ret );
}
#if !defined(MBEDTLS_DEPRECATED_REMOVED)
void mbedtls_sha512( const unsigned char *input,
size_t ilen,
unsigned char output[64],
int is384 )
{
mbedtls_sha512_ret( input, ilen, output, is384 );
}
#endif
#if defined(MBEDTLS_SELF_TEST)
/*
* FIPS-180-2 test vectors
*/
static const unsigned char sha512_test_buf[3][113] =
{
{ "abc" },
{ "abcdefghbcdefghicdefghijdefghijkefghijklfghijklmghijklmnhijklmnoijklmnopjklmnopqklmnopqrlmnopqrsmnopqrstnopqrstu" },
{ "" }
};
static const size_t sha512_test_buflen[3] =
{
3, 112, 1000
};
static const unsigned char sha512_test_sum[][64] =
{
#if !defined(MBEDTLS_SHA512_NO_SHA384)
/*
* SHA-384 test vectors
*/
{ 0xCB, 0x00, 0x75, 0x3F, 0x45, 0xA3, 0x5E, 0x8B,
0xB5, 0xA0, 0x3D, 0x69, 0x9A, 0xC6, 0x50, 0x07,
0x27, 0x2C, 0x32, 0xAB, 0x0E, 0xDE, 0xD1, 0x63,
0x1A, 0x8B, 0x60, 0x5A, 0x43, 0xFF, 0x5B, 0xED,
0x80, 0x86, 0x07, 0x2B, 0xA1, 0xE7, 0xCC, 0x23,
0x58, 0xBA, 0xEC, 0xA1, 0x34, 0xC8, 0x25, 0xA7 },
{ 0x09, 0x33, 0x0C, 0x33, 0xF7, 0x11, 0x47, 0xE8,
0x3D, 0x19, 0x2F, 0xC7, 0x82, 0xCD, 0x1B, 0x47,
0x53, 0x11, 0x1B, 0x17, 0x3B, 0x3B, 0x05, 0xD2,
0x2F, 0xA0, 0x80, 0x86, 0xE3, 0xB0, 0xF7, 0x12,
0xFC, 0xC7, 0xC7, 0x1A, 0x55, 0x7E, 0x2D, 0xB9,
0x66, 0xC3, 0xE9, 0xFA, 0x91, 0x74, 0x60, 0x39 },
{ 0x9D, 0x0E, 0x18, 0x09, 0x71, 0x64, 0x74, 0xCB,
0x08, 0x6E, 0x83, 0x4E, 0x31, 0x0A, 0x4A, 0x1C,
0xED, 0x14, 0x9E, 0x9C, 0x00, 0xF2, 0x48, 0x52,
0x79, 0x72, 0xCE, 0xC5, 0x70, 0x4C, 0x2A, 0x5B,
0x07, 0xB8, 0xB3, 0xDC, 0x38, 0xEC, 0xC4, 0xEB,
0xAE, 0x97, 0xDD, 0xD8, 0x7F, 0x3D, 0x89, 0x85 },
#endif /* !MBEDTLS_SHA512_NO_SHA384 */
/*
* SHA-512 test vectors
*/
{ 0xDD, 0xAF, 0x35, 0xA1, 0x93, 0x61, 0x7A, 0xBA,
0xCC, 0x41, 0x73, 0x49, 0xAE, 0x20, 0x41, 0x31,
0x12, 0xE6, 0xFA, 0x4E, 0x89, 0xA9, 0x7E, 0xA2,
0x0A, 0x9E, 0xEE, 0xE6, 0x4B, 0x55, 0xD3, 0x9A,
0x21, 0x92, 0x99, 0x2A, 0x27, 0x4F, 0xC1, 0xA8,
0x36, 0xBA, 0x3C, 0x23, 0xA3, 0xFE, 0xEB, 0xBD,
0x45, 0x4D, 0x44, 0x23, 0x64, 0x3C, 0xE8, 0x0E,
0x2A, 0x9A, 0xC9, 0x4F, 0xA5, 0x4C, 0xA4, 0x9F },
{ 0x8E, 0x95, 0x9B, 0x75, 0xDA, 0xE3, 0x13, 0xDA,
0x8C, 0xF4, 0xF7, 0x28, 0x14, 0xFC, 0x14, 0x3F,
0x8F, 0x77, 0x79, 0xC6, 0xEB, 0x9F, 0x7F, 0xA1,
0x72, 0x99, 0xAE, 0xAD, 0xB6, 0x88, 0x90, 0x18,
0x50, 0x1D, 0x28, 0x9E, 0x49, 0x00, 0xF7, 0xE4,
0x33, 0x1B, 0x99, 0xDE, 0xC4, 0xB5, 0x43, 0x3A,
0xC7, 0xD3, 0x29, 0xEE, 0xB6, 0xDD, 0x26, 0x54,
0x5E, 0x96, 0xE5, 0x5B, 0x87, 0x4B, 0xE9, 0x09 },
{ 0xE7, 0x18, 0x48, 0x3D, 0x0C, 0xE7, 0x69, 0x64,
0x4E, 0x2E, 0x42, 0xC7, 0xBC, 0x15, 0xB4, 0x63,
0x8E, 0x1F, 0x98, 0xB1, 0x3B, 0x20, 0x44, 0x28,
0x56, 0x32, 0xA8, 0x03, 0xAF, 0xA9, 0x73, 0xEB,
0xDE, 0x0F, 0xF2, 0x44, 0x87, 0x7E, 0xA6, 0x0A,
0x4C, 0xB0, 0x43, 0x2C, 0xE5, 0x77, 0xC3, 0x1B,
0xEB, 0x00, 0x9C, 0x5C, 0x2C, 0x49, 0xAA, 0x2E,
0x4E, 0xAD, 0xB2, 0x17, 0xAD, 0x8C, 0xC0, 0x9B }
};
#define ARRAY_LENGTH( a ) ( sizeof( a ) / sizeof( ( a )[0] ) )
/*
* Checkup routine
*/
int mbedtls_sha512_self_test( int verbose )
{
int i, j, k, buflen, ret = 0;
unsigned char *buf;
unsigned char sha512sum[64];
mbedtls_sha512_context ctx;
buf = mbedtls_calloc( 1024, sizeof(unsigned char) );
if( NULL == buf )
{
if( verbose != 0 )
mbedtls_printf( "Buffer allocation failed\n" );
return( 1 );
}
mbedtls_sha512_init( &ctx );
for( i = 0; i < (int) ARRAY_LENGTH(sha512_test_sum); i++ )
{
j = i % 3;
#if !defined(MBEDTLS_SHA512_NO_SHA384)
k = i < 3;
#else
k = 0;
#endif
if( verbose != 0 )
mbedtls_printf( " SHA-%d test #%d: ", 512 - k * 128, j + 1 );
if( ( ret = mbedtls_sha512_starts_ret( &ctx, k ) ) != 0 )
goto fail;
if( j == 2 )
{
memset( buf, 'a', buflen = 1000 );
for( j = 0; j < 1000; j++ )
{
ret = mbedtls_sha512_update_ret( &ctx, buf, buflen );
if( ret != 0 )
goto fail;
}
}
else
{
ret = mbedtls_sha512_update_ret( &ctx, sha512_test_buf[j],
sha512_test_buflen[j] );
if( ret != 0 )
goto fail;
}
if( ( ret = mbedtls_sha512_finish_ret( &ctx, sha512sum ) ) != 0 )
goto fail;
if( memcmp( sha512sum, sha512_test_sum[i], 64 - k * 16 ) != 0 )
{
ret = 1;
goto fail;
}
if( verbose != 0 )
mbedtls_printf( "passed\n" );
}
if( verbose != 0 )
mbedtls_printf( "\n" );
goto exit;
fail:
if( verbose != 0 )
mbedtls_printf( "failed\n" );
exit:
mbedtls_sha512_free( &ctx );
mbedtls_free( buf );
return( ret );
}
#undef ARRAY_LENGTH
#endif /* MBEDTLS_SELF_TEST */
#endif /* MBEDTLS_SHA512_C */
|
0 | repos/gpt4all.zig/src/zig-libcurl/zig-mbedtls/mbedtls | repos/gpt4all.zig/src/zig-libcurl/zig-mbedtls/mbedtls/library/memory_buffer_alloc.c | /*
* Buffer-based memory allocator
*
* Copyright The Mbed TLS Contributors
* SPDX-License-Identifier: Apache-2.0
*
* 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.
*/
#include "common.h"
#if defined(MBEDTLS_MEMORY_BUFFER_ALLOC_C)
#include "mbedtls/memory_buffer_alloc.h"
/* No need for the header guard as MBEDTLS_MEMORY_BUFFER_ALLOC_C
is dependent upon MBEDTLS_PLATFORM_C */
#include "mbedtls/platform.h"
#include "mbedtls/platform_util.h"
#include <string.h>
#if defined(MBEDTLS_MEMORY_BACKTRACE)
#include <execinfo.h>
#endif
#if defined(MBEDTLS_THREADING_C)
#include "mbedtls/threading.h"
#endif
#define MAGIC1 0xFF00AA55
#define MAGIC2 0xEE119966
#define MAX_BT 20
typedef struct _memory_header memory_header;
struct _memory_header
{
size_t magic1;
size_t size;
size_t alloc;
memory_header *prev;
memory_header *next;
memory_header *prev_free;
memory_header *next_free;
#if defined(MBEDTLS_MEMORY_BACKTRACE)
char **trace;
size_t trace_count;
#endif
size_t magic2;
};
typedef struct
{
unsigned char *buf;
size_t len;
memory_header *first;
memory_header *first_free;
int verify;
#if defined(MBEDTLS_MEMORY_DEBUG)
size_t alloc_count;
size_t free_count;
size_t total_used;
size_t maximum_used;
size_t header_count;
size_t maximum_header_count;
#endif
#if defined(MBEDTLS_THREADING_C)
mbedtls_threading_mutex_t mutex;
#endif
}
buffer_alloc_ctx;
static buffer_alloc_ctx heap;
#if defined(MBEDTLS_MEMORY_DEBUG)
static void debug_header( memory_header *hdr )
{
#if defined(MBEDTLS_MEMORY_BACKTRACE)
size_t i;
#endif
mbedtls_fprintf( stderr, "HDR: PTR(%10zu), PREV(%10zu), NEXT(%10zu), "
"ALLOC(%zu), SIZE(%10zu)\n",
(size_t) hdr, (size_t) hdr->prev, (size_t) hdr->next,
hdr->alloc, hdr->size );
mbedtls_fprintf( stderr, " FPREV(%10zu), FNEXT(%10zu)\n",
(size_t) hdr->prev_free, (size_t) hdr->next_free );
#if defined(MBEDTLS_MEMORY_BACKTRACE)
mbedtls_fprintf( stderr, "TRACE: \n" );
for( i = 0; i < hdr->trace_count; i++ )
mbedtls_fprintf( stderr, "%s\n", hdr->trace[i] );
mbedtls_fprintf( stderr, "\n" );
#endif
}
static void debug_chain( void )
{
memory_header *cur = heap.first;
mbedtls_fprintf( stderr, "\nBlock list\n" );
while( cur != NULL )
{
debug_header( cur );
cur = cur->next;
}
mbedtls_fprintf( stderr, "Free list\n" );
cur = heap.first_free;
while( cur != NULL )
{
debug_header( cur );
cur = cur->next_free;
}
}
#endif /* MBEDTLS_MEMORY_DEBUG */
static int verify_header( memory_header *hdr )
{
if( hdr->magic1 != MAGIC1 )
{
#if defined(MBEDTLS_MEMORY_DEBUG)
mbedtls_fprintf( stderr, "FATAL: MAGIC1 mismatch\n" );
#endif
return( 1 );
}
if( hdr->magic2 != MAGIC2 )
{
#if defined(MBEDTLS_MEMORY_DEBUG)
mbedtls_fprintf( stderr, "FATAL: MAGIC2 mismatch\n" );
#endif
return( 1 );
}
if( hdr->alloc > 1 )
{
#if defined(MBEDTLS_MEMORY_DEBUG)
mbedtls_fprintf( stderr, "FATAL: alloc has illegal value\n" );
#endif
return( 1 );
}
if( hdr->prev != NULL && hdr->prev == hdr->next )
{
#if defined(MBEDTLS_MEMORY_DEBUG)
mbedtls_fprintf( stderr, "FATAL: prev == next\n" );
#endif
return( 1 );
}
if( hdr->prev_free != NULL && hdr->prev_free == hdr->next_free )
{
#if defined(MBEDTLS_MEMORY_DEBUG)
mbedtls_fprintf( stderr, "FATAL: prev_free == next_free\n" );
#endif
return( 1 );
}
return( 0 );
}
static int verify_chain( void )
{
memory_header *prv = heap.first, *cur;
if( prv == NULL || verify_header( prv ) != 0 )
{
#if defined(MBEDTLS_MEMORY_DEBUG)
mbedtls_fprintf( stderr, "FATAL: verification of first header "
"failed\n" );
#endif
return( 1 );
}
if( heap.first->prev != NULL )
{
#if defined(MBEDTLS_MEMORY_DEBUG)
mbedtls_fprintf( stderr, "FATAL: verification failed: "
"first->prev != NULL\n" );
#endif
return( 1 );
}
cur = heap.first->next;
while( cur != NULL )
{
if( verify_header( cur ) != 0 )
{
#if defined(MBEDTLS_MEMORY_DEBUG)
mbedtls_fprintf( stderr, "FATAL: verification of header "
"failed\n" );
#endif
return( 1 );
}
if( cur->prev != prv )
{
#if defined(MBEDTLS_MEMORY_DEBUG)
mbedtls_fprintf( stderr, "FATAL: verification failed: "
"cur->prev != prv\n" );
#endif
return( 1 );
}
prv = cur;
cur = cur->next;
}
return( 0 );
}
static void *buffer_alloc_calloc( size_t n, size_t size )
{
memory_header *new, *cur = heap.first_free;
unsigned char *p;
void *ret;
size_t original_len, len;
#if defined(MBEDTLS_MEMORY_BACKTRACE)
void *trace_buffer[MAX_BT];
size_t trace_cnt;
#endif
if( heap.buf == NULL || heap.first == NULL )
return( NULL );
original_len = len = n * size;
if( n == 0 || size == 0 || len / n != size )
return( NULL );
else if( len > (size_t)-MBEDTLS_MEMORY_ALIGN_MULTIPLE )
return( NULL );
if( len % MBEDTLS_MEMORY_ALIGN_MULTIPLE )
{
len -= len % MBEDTLS_MEMORY_ALIGN_MULTIPLE;
len += MBEDTLS_MEMORY_ALIGN_MULTIPLE;
}
// Find block that fits
//
while( cur != NULL )
{
if( cur->size >= len )
break;
cur = cur->next_free;
}
if( cur == NULL )
return( NULL );
if( cur->alloc != 0 )
{
#if defined(MBEDTLS_MEMORY_DEBUG)
mbedtls_fprintf( stderr, "FATAL: block in free_list but allocated "
"data\n" );
#endif
mbedtls_exit( 1 );
}
#if defined(MBEDTLS_MEMORY_DEBUG)
heap.alloc_count++;
#endif
// Found location, split block if > memory_header + 4 room left
//
if( cur->size - len < sizeof(memory_header) +
MBEDTLS_MEMORY_ALIGN_MULTIPLE )
{
cur->alloc = 1;
// Remove from free_list
//
if( cur->prev_free != NULL )
cur->prev_free->next_free = cur->next_free;
else
heap.first_free = cur->next_free;
if( cur->next_free != NULL )
cur->next_free->prev_free = cur->prev_free;
cur->prev_free = NULL;
cur->next_free = NULL;
#if defined(MBEDTLS_MEMORY_DEBUG)
heap.total_used += cur->size;
if( heap.total_used > heap.maximum_used )
heap.maximum_used = heap.total_used;
#endif
#if defined(MBEDTLS_MEMORY_BACKTRACE)
trace_cnt = backtrace( trace_buffer, MAX_BT );
cur->trace = backtrace_symbols( trace_buffer, trace_cnt );
cur->trace_count = trace_cnt;
#endif
if( ( heap.verify & MBEDTLS_MEMORY_VERIFY_ALLOC ) && verify_chain() != 0 )
mbedtls_exit( 1 );
ret = (unsigned char *) cur + sizeof( memory_header );
memset( ret, 0, original_len );
return( ret );
}
p = ( (unsigned char *) cur ) + sizeof(memory_header) + len;
new = (memory_header *) p;
new->size = cur->size - len - sizeof(memory_header);
new->alloc = 0;
new->prev = cur;
new->next = cur->next;
#if defined(MBEDTLS_MEMORY_BACKTRACE)
new->trace = NULL;
new->trace_count = 0;
#endif
new->magic1 = MAGIC1;
new->magic2 = MAGIC2;
if( new->next != NULL )
new->next->prev = new;
// Replace cur with new in free_list
//
new->prev_free = cur->prev_free;
new->next_free = cur->next_free;
if( new->prev_free != NULL )
new->prev_free->next_free = new;
else
heap.first_free = new;
if( new->next_free != NULL )
new->next_free->prev_free = new;
cur->alloc = 1;
cur->size = len;
cur->next = new;
cur->prev_free = NULL;
cur->next_free = NULL;
#if defined(MBEDTLS_MEMORY_DEBUG)
heap.header_count++;
if( heap.header_count > heap.maximum_header_count )
heap.maximum_header_count = heap.header_count;
heap.total_used += cur->size;
if( heap.total_used > heap.maximum_used )
heap.maximum_used = heap.total_used;
#endif
#if defined(MBEDTLS_MEMORY_BACKTRACE)
trace_cnt = backtrace( trace_buffer, MAX_BT );
cur->trace = backtrace_symbols( trace_buffer, trace_cnt );
cur->trace_count = trace_cnt;
#endif
if( ( heap.verify & MBEDTLS_MEMORY_VERIFY_ALLOC ) && verify_chain() != 0 )
mbedtls_exit( 1 );
ret = (unsigned char *) cur + sizeof( memory_header );
memset( ret, 0, original_len );
return( ret );
}
static void buffer_alloc_free( void *ptr )
{
memory_header *hdr, *old = NULL;
unsigned char *p = (unsigned char *) ptr;
if( ptr == NULL || heap.buf == NULL || heap.first == NULL )
return;
if( p < heap.buf || p >= heap.buf + heap.len )
{
#if defined(MBEDTLS_MEMORY_DEBUG)
mbedtls_fprintf( stderr, "FATAL: mbedtls_free() outside of managed "
"space\n" );
#endif
mbedtls_exit( 1 );
}
p -= sizeof(memory_header);
hdr = (memory_header *) p;
if( verify_header( hdr ) != 0 )
mbedtls_exit( 1 );
if( hdr->alloc != 1 )
{
#if defined(MBEDTLS_MEMORY_DEBUG)
mbedtls_fprintf( stderr, "FATAL: mbedtls_free() on unallocated "
"data\n" );
#endif
mbedtls_exit( 1 );
}
hdr->alloc = 0;
#if defined(MBEDTLS_MEMORY_DEBUG)
heap.free_count++;
heap.total_used -= hdr->size;
#endif
#if defined(MBEDTLS_MEMORY_BACKTRACE)
free( hdr->trace );
hdr->trace = NULL;
hdr->trace_count = 0;
#endif
// Regroup with block before
//
if( hdr->prev != NULL && hdr->prev->alloc == 0 )
{
#if defined(MBEDTLS_MEMORY_DEBUG)
heap.header_count--;
#endif
hdr->prev->size += sizeof(memory_header) + hdr->size;
hdr->prev->next = hdr->next;
old = hdr;
hdr = hdr->prev;
if( hdr->next != NULL )
hdr->next->prev = hdr;
memset( old, 0, sizeof(memory_header) );
}
// Regroup with block after
//
if( hdr->next != NULL && hdr->next->alloc == 0 )
{
#if defined(MBEDTLS_MEMORY_DEBUG)
heap.header_count--;
#endif
hdr->size += sizeof(memory_header) + hdr->next->size;
old = hdr->next;
hdr->next = hdr->next->next;
if( hdr->prev_free != NULL || hdr->next_free != NULL )
{
if( hdr->prev_free != NULL )
hdr->prev_free->next_free = hdr->next_free;
else
heap.first_free = hdr->next_free;
if( hdr->next_free != NULL )
hdr->next_free->prev_free = hdr->prev_free;
}
hdr->prev_free = old->prev_free;
hdr->next_free = old->next_free;
if( hdr->prev_free != NULL )
hdr->prev_free->next_free = hdr;
else
heap.first_free = hdr;
if( hdr->next_free != NULL )
hdr->next_free->prev_free = hdr;
if( hdr->next != NULL )
hdr->next->prev = hdr;
memset( old, 0, sizeof(memory_header) );
}
// Prepend to free_list if we have not merged
// (Does not have to stay in same order as prev / next list)
//
if( old == NULL )
{
hdr->next_free = heap.first_free;
if( heap.first_free != NULL )
heap.first_free->prev_free = hdr;
heap.first_free = hdr;
}
if( ( heap.verify & MBEDTLS_MEMORY_VERIFY_FREE ) && verify_chain() != 0 )
mbedtls_exit( 1 );
}
void mbedtls_memory_buffer_set_verify( int verify )
{
heap.verify = verify;
}
int mbedtls_memory_buffer_alloc_verify( void )
{
return verify_chain();
}
#if defined(MBEDTLS_MEMORY_DEBUG)
void mbedtls_memory_buffer_alloc_status( void )
{
mbedtls_fprintf( stderr,
"Current use: %zu blocks / %zu bytes, max: %zu blocks / "
"%zu bytes (total %zu bytes), alloc / free: %zu / %zu\n",
heap.header_count, heap.total_used,
heap.maximum_header_count, heap.maximum_used,
heap.maximum_header_count * sizeof( memory_header )
+ heap.maximum_used,
heap.alloc_count, heap.free_count );
if( heap.first->next == NULL )
{
mbedtls_fprintf( stderr, "All memory de-allocated in stack buffer\n" );
}
else
{
mbedtls_fprintf( stderr, "Memory currently allocated:\n" );
debug_chain();
}
}
void mbedtls_memory_buffer_alloc_max_get( size_t *max_used, size_t *max_blocks )
{
*max_used = heap.maximum_used;
*max_blocks = heap.maximum_header_count;
}
void mbedtls_memory_buffer_alloc_max_reset( void )
{
heap.maximum_used = 0;
heap.maximum_header_count = 0;
}
void mbedtls_memory_buffer_alloc_cur_get( size_t *cur_used, size_t *cur_blocks )
{
*cur_used = heap.total_used;
*cur_blocks = heap.header_count;
}
#endif /* MBEDTLS_MEMORY_DEBUG */
#if defined(MBEDTLS_THREADING_C)
static void *buffer_alloc_calloc_mutexed( size_t n, size_t size )
{
void *buf;
if( mbedtls_mutex_lock( &heap.mutex ) != 0 )
return( NULL );
buf = buffer_alloc_calloc( n, size );
if( mbedtls_mutex_unlock( &heap.mutex ) )
return( NULL );
return( buf );
}
static void buffer_alloc_free_mutexed( void *ptr )
{
/* We have to good option here, but corrupting the heap seems
* worse than loosing memory. */
if( mbedtls_mutex_lock( &heap.mutex ) )
return;
buffer_alloc_free( ptr );
(void) mbedtls_mutex_unlock( &heap.mutex );
}
#endif /* MBEDTLS_THREADING_C */
void mbedtls_memory_buffer_alloc_init( unsigned char *buf, size_t len )
{
memset( &heap, 0, sizeof( buffer_alloc_ctx ) );
#if defined(MBEDTLS_THREADING_C)
mbedtls_mutex_init( &heap.mutex );
mbedtls_platform_set_calloc_free( buffer_alloc_calloc_mutexed,
buffer_alloc_free_mutexed );
#else
mbedtls_platform_set_calloc_free( buffer_alloc_calloc, buffer_alloc_free );
#endif
if( len < sizeof( memory_header ) + MBEDTLS_MEMORY_ALIGN_MULTIPLE )
return;
else if( (size_t)buf % MBEDTLS_MEMORY_ALIGN_MULTIPLE )
{
/* Adjust len first since buf is used in the computation */
len -= MBEDTLS_MEMORY_ALIGN_MULTIPLE
- (size_t)buf % MBEDTLS_MEMORY_ALIGN_MULTIPLE;
buf += MBEDTLS_MEMORY_ALIGN_MULTIPLE
- (size_t)buf % MBEDTLS_MEMORY_ALIGN_MULTIPLE;
}
memset( buf, 0, len );
heap.buf = buf;
heap.len = len;
heap.first = (memory_header *)buf;
heap.first->size = len - sizeof( memory_header );
heap.first->magic1 = MAGIC1;
heap.first->magic2 = MAGIC2;
heap.first_free = heap.first;
}
void mbedtls_memory_buffer_alloc_free( void )
{
#if defined(MBEDTLS_THREADING_C)
mbedtls_mutex_free( &heap.mutex );
#endif
mbedtls_platform_zeroize( &heap, sizeof(buffer_alloc_ctx) );
}
#if defined(MBEDTLS_SELF_TEST)
static int check_pointer( void *p )
{
if( p == NULL )
return( -1 );
if( (size_t) p % MBEDTLS_MEMORY_ALIGN_MULTIPLE != 0 )
return( -1 );
return( 0 );
}
static int check_all_free( void )
{
if(
#if defined(MBEDTLS_MEMORY_DEBUG)
heap.total_used != 0 ||
#endif
heap.first != heap.first_free ||
(void *) heap.first != (void *) heap.buf )
{
return( -1 );
}
return( 0 );
}
#define TEST_ASSERT( condition ) \
if( ! (condition) ) \
{ \
if( verbose != 0 ) \
mbedtls_printf( "failed\n" ); \
\
ret = 1; \
goto cleanup; \
}
int mbedtls_memory_buffer_alloc_self_test( int verbose )
{
unsigned char buf[1024];
unsigned char *p, *q, *r, *end;
int ret = 0;
if( verbose != 0 )
mbedtls_printf( " MBA test #1 (basic alloc-free cycle): " );
mbedtls_memory_buffer_alloc_init( buf, sizeof( buf ) );
p = mbedtls_calloc( 1, 1 );
q = mbedtls_calloc( 1, 128 );
r = mbedtls_calloc( 1, 16 );
TEST_ASSERT( check_pointer( p ) == 0 &&
check_pointer( q ) == 0 &&
check_pointer( r ) == 0 );
mbedtls_free( r );
mbedtls_free( q );
mbedtls_free( p );
TEST_ASSERT( check_all_free( ) == 0 );
/* Memorize end to compare with the next test */
end = heap.buf + heap.len;
mbedtls_memory_buffer_alloc_free( );
if( verbose != 0 )
mbedtls_printf( "passed\n" );
if( verbose != 0 )
mbedtls_printf( " MBA test #2 (buf not aligned): " );
mbedtls_memory_buffer_alloc_init( buf + 1, sizeof( buf ) - 1 );
TEST_ASSERT( heap.buf + heap.len == end );
p = mbedtls_calloc( 1, 1 );
q = mbedtls_calloc( 1, 128 );
r = mbedtls_calloc( 1, 16 );
TEST_ASSERT( check_pointer( p ) == 0 &&
check_pointer( q ) == 0 &&
check_pointer( r ) == 0 );
mbedtls_free( r );
mbedtls_free( q );
mbedtls_free( p );
TEST_ASSERT( check_all_free( ) == 0 );
mbedtls_memory_buffer_alloc_free( );
if( verbose != 0 )
mbedtls_printf( "passed\n" );
if( verbose != 0 )
mbedtls_printf( " MBA test #3 (full): " );
mbedtls_memory_buffer_alloc_init( buf, sizeof( buf ) );
p = mbedtls_calloc( 1, sizeof( buf ) - sizeof( memory_header ) );
TEST_ASSERT( check_pointer( p ) == 0 );
TEST_ASSERT( mbedtls_calloc( 1, 1 ) == NULL );
mbedtls_free( p );
p = mbedtls_calloc( 1, sizeof( buf ) - 2 * sizeof( memory_header ) - 16 );
q = mbedtls_calloc( 1, 16 );
TEST_ASSERT( check_pointer( p ) == 0 && check_pointer( q ) == 0 );
TEST_ASSERT( mbedtls_calloc( 1, 1 ) == NULL );
mbedtls_free( q );
TEST_ASSERT( mbedtls_calloc( 1, 17 ) == NULL );
mbedtls_free( p );
TEST_ASSERT( check_all_free( ) == 0 );
mbedtls_memory_buffer_alloc_free( );
if( verbose != 0 )
mbedtls_printf( "passed\n" );
cleanup:
mbedtls_memory_buffer_alloc_free( );
return( ret );
}
#endif /* MBEDTLS_SELF_TEST */
#endif /* MBEDTLS_MEMORY_BUFFER_ALLOC_C */
|
0 | repos/gpt4all.zig/src/zig-libcurl/zig-mbedtls/mbedtls | repos/gpt4all.zig/src/zig-libcurl/zig-mbedtls/mbedtls/library/ccm.c | /*
* NIST SP800-38C compliant CCM implementation
*
* Copyright The Mbed TLS Contributors
* SPDX-License-Identifier: Apache-2.0
*
* 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.
*/
/*
* Definition of CCM:
* http://csrc.nist.gov/publications/nistpubs/800-38C/SP800-38C_updated-July20_2007.pdf
* RFC 3610 "Counter with CBC-MAC (CCM)"
*
* Related:
* RFC 5116 "An Interface and Algorithms for Authenticated Encryption"
*/
#include "common.h"
#if defined(MBEDTLS_CCM_C)
#include "mbedtls/ccm.h"
#include "mbedtls/platform_util.h"
#include "mbedtls/error.h"
#include <string.h>
#if defined(MBEDTLS_SELF_TEST) && defined(MBEDTLS_AES_C)
#if defined(MBEDTLS_PLATFORM_C)
#include "mbedtls/platform.h"
#else
#include <stdio.h>
#define mbedtls_printf printf
#endif /* MBEDTLS_PLATFORM_C */
#endif /* MBEDTLS_SELF_TEST && MBEDTLS_AES_C */
#if !defined(MBEDTLS_CCM_ALT)
#define CCM_VALIDATE_RET( cond ) \
MBEDTLS_INTERNAL_VALIDATE_RET( cond, MBEDTLS_ERR_CCM_BAD_INPUT )
#define CCM_VALIDATE( cond ) \
MBEDTLS_INTERNAL_VALIDATE( cond )
#define CCM_ENCRYPT 0
#define CCM_DECRYPT 1
/*
* Initialize context
*/
void mbedtls_ccm_init( mbedtls_ccm_context *ctx )
{
CCM_VALIDATE( ctx != NULL );
memset( ctx, 0, sizeof( mbedtls_ccm_context ) );
}
int mbedtls_ccm_setkey( mbedtls_ccm_context *ctx,
mbedtls_cipher_id_t cipher,
const unsigned char *key,
unsigned int keybits )
{
int ret = MBEDTLS_ERR_ERROR_CORRUPTION_DETECTED;
const mbedtls_cipher_info_t *cipher_info;
CCM_VALIDATE_RET( ctx != NULL );
CCM_VALIDATE_RET( key != NULL );
cipher_info = mbedtls_cipher_info_from_values( cipher, keybits,
MBEDTLS_MODE_ECB );
if( cipher_info == NULL )
return( MBEDTLS_ERR_CCM_BAD_INPUT );
if( cipher_info->block_size != 16 )
return( MBEDTLS_ERR_CCM_BAD_INPUT );
mbedtls_cipher_free( &ctx->cipher_ctx );
if( ( ret = mbedtls_cipher_setup( &ctx->cipher_ctx, cipher_info ) ) != 0 )
return( ret );
if( ( ret = mbedtls_cipher_setkey( &ctx->cipher_ctx, key, keybits,
MBEDTLS_ENCRYPT ) ) != 0 )
{
return( ret );
}
return( 0 );
}
/*
* Free context
*/
void mbedtls_ccm_free( mbedtls_ccm_context *ctx )
{
if( ctx == NULL )
return;
mbedtls_cipher_free( &ctx->cipher_ctx );
mbedtls_platform_zeroize( ctx, sizeof( mbedtls_ccm_context ) );
}
/*
* Macros for common operations.
* Results in smaller compiled code than static inline functions.
*/
/*
* Update the CBC-MAC state in y using a block in b
* (Always using b as the source helps the compiler optimise a bit better.)
*/
#define UPDATE_CBC_MAC \
for( i = 0; i < 16; i++ ) \
y[i] ^= b[i]; \
\
if( ( ret = mbedtls_cipher_update( &ctx->cipher_ctx, y, 16, y, &olen ) ) != 0 ) \
return( ret );
/*
* Encrypt or decrypt a partial block with CTR
* Warning: using b for temporary storage! src and dst must not be b!
* This avoids allocating one more 16 bytes buffer while allowing src == dst.
*/
#define CTR_CRYPT( dst, src, len ) \
do \
{ \
if( ( ret = mbedtls_cipher_update( &ctx->cipher_ctx, ctr, \
16, b, &olen ) ) != 0 ) \
{ \
return( ret ); \
} \
\
for( i = 0; i < (len); i++ ) \
(dst)[i] = (src)[i] ^ b[i]; \
} while( 0 )
/*
* Authenticated encryption or decryption
*/
static int ccm_auth_crypt( mbedtls_ccm_context *ctx, int mode, size_t length,
const unsigned char *iv, size_t iv_len,
const unsigned char *add, size_t add_len,
const unsigned char *input, unsigned char *output,
unsigned char *tag, size_t tag_len )
{
int ret = MBEDTLS_ERR_ERROR_CORRUPTION_DETECTED;
unsigned char i;
unsigned char q;
size_t len_left, olen;
unsigned char b[16];
unsigned char y[16];
unsigned char ctr[16];
const unsigned char *src;
unsigned char *dst;
/*
* Check length requirements: SP800-38C A.1
* Additional requirement: a < 2^16 - 2^8 to simplify the code.
* 'length' checked later (when writing it to the first block)
*
* Also, loosen the requirements to enable support for CCM* (IEEE 802.15.4).
*/
if( tag_len == 2 || tag_len > 16 || tag_len % 2 != 0 )
return( MBEDTLS_ERR_CCM_BAD_INPUT );
/* Also implies q is within bounds */
if( iv_len < 7 || iv_len > 13 )
return( MBEDTLS_ERR_CCM_BAD_INPUT );
if( add_len >= 0xFF00 )
return( MBEDTLS_ERR_CCM_BAD_INPUT );
q = 16 - 1 - (unsigned char) iv_len;
/*
* First block B_0:
* 0 .. 0 flags
* 1 .. iv_len nonce (aka iv)
* iv_len+1 .. 15 length
*
* With flags as (bits):
* 7 0
* 6 add present?
* 5 .. 3 (t - 2) / 2
* 2 .. 0 q - 1
*/
b[0] = 0;
b[0] |= ( add_len > 0 ) << 6;
b[0] |= ( ( tag_len - 2 ) / 2 ) << 3;
b[0] |= q - 1;
memcpy( b + 1, iv, iv_len );
for( i = 0, len_left = length; i < q; i++, len_left >>= 8 )
b[15-i] = (unsigned char)( len_left & 0xFF );
if( len_left > 0 )
return( MBEDTLS_ERR_CCM_BAD_INPUT );
/* Start CBC-MAC with first block */
memset( y, 0, 16 );
UPDATE_CBC_MAC;
/*
* If there is additional data, update CBC-MAC with
* add_len, add, 0 (padding to a block boundary)
*/
if( add_len > 0 )
{
size_t use_len;
len_left = add_len;
src = add;
memset( b, 0, 16 );
b[0] = (unsigned char)( ( add_len >> 8 ) & 0xFF );
b[1] = (unsigned char)( ( add_len ) & 0xFF );
use_len = len_left < 16 - 2 ? len_left : 16 - 2;
memcpy( b + 2, src, use_len );
len_left -= use_len;
src += use_len;
UPDATE_CBC_MAC;
while( len_left > 0 )
{
use_len = len_left > 16 ? 16 : len_left;
memset( b, 0, 16 );
memcpy( b, src, use_len );
UPDATE_CBC_MAC;
len_left -= use_len;
src += use_len;
}
}
/*
* Prepare counter block for encryption:
* 0 .. 0 flags
* 1 .. iv_len nonce (aka iv)
* iv_len+1 .. 15 counter (initially 1)
*
* With flags as (bits):
* 7 .. 3 0
* 2 .. 0 q - 1
*/
ctr[0] = q - 1;
memcpy( ctr + 1, iv, iv_len );
memset( ctr + 1 + iv_len, 0, q );
ctr[15] = 1;
/*
* Authenticate and {en,de}crypt the message.
*
* The only difference between encryption and decryption is
* the respective order of authentication and {en,de}cryption.
*/
len_left = length;
src = input;
dst = output;
while( len_left > 0 )
{
size_t use_len = len_left > 16 ? 16 : len_left;
if( mode == CCM_ENCRYPT )
{
memset( b, 0, 16 );
memcpy( b, src, use_len );
UPDATE_CBC_MAC;
}
CTR_CRYPT( dst, src, use_len );
if( mode == CCM_DECRYPT )
{
memset( b, 0, 16 );
memcpy( b, dst, use_len );
UPDATE_CBC_MAC;
}
dst += use_len;
src += use_len;
len_left -= use_len;
/*
* Increment counter.
* No need to check for overflow thanks to the length check above.
*/
for( i = 0; i < q; i++ )
if( ++ctr[15-i] != 0 )
break;
}
/*
* Authentication: reset counter and crypt/mask internal tag
*/
for( i = 0; i < q; i++ )
ctr[15-i] = 0;
CTR_CRYPT( y, y, 16 );
memcpy( tag, y, tag_len );
return( 0 );
}
/*
* Authenticated encryption
*/
int mbedtls_ccm_star_encrypt_and_tag( mbedtls_ccm_context *ctx, size_t length,
const unsigned char *iv, size_t iv_len,
const unsigned char *add, size_t add_len,
const unsigned char *input, unsigned char *output,
unsigned char *tag, size_t tag_len )
{
CCM_VALIDATE_RET( ctx != NULL );
CCM_VALIDATE_RET( iv != NULL );
CCM_VALIDATE_RET( add_len == 0 || add != NULL );
CCM_VALIDATE_RET( length == 0 || input != NULL );
CCM_VALIDATE_RET( length == 0 || output != NULL );
CCM_VALIDATE_RET( tag_len == 0 || tag != NULL );
return( ccm_auth_crypt( ctx, CCM_ENCRYPT, length, iv, iv_len,
add, add_len, input, output, tag, tag_len ) );
}
int mbedtls_ccm_encrypt_and_tag( mbedtls_ccm_context *ctx, size_t length,
const unsigned char *iv, size_t iv_len,
const unsigned char *add, size_t add_len,
const unsigned char *input, unsigned char *output,
unsigned char *tag, size_t tag_len )
{
CCM_VALIDATE_RET( ctx != NULL );
CCM_VALIDATE_RET( iv != NULL );
CCM_VALIDATE_RET( add_len == 0 || add != NULL );
CCM_VALIDATE_RET( length == 0 || input != NULL );
CCM_VALIDATE_RET( length == 0 || output != NULL );
CCM_VALIDATE_RET( tag_len == 0 || tag != NULL );
if( tag_len == 0 )
return( MBEDTLS_ERR_CCM_BAD_INPUT );
return( mbedtls_ccm_star_encrypt_and_tag( ctx, length, iv, iv_len, add,
add_len, input, output, tag, tag_len ) );
}
/*
* Authenticated decryption
*/
int mbedtls_ccm_star_auth_decrypt( mbedtls_ccm_context *ctx, size_t length,
const unsigned char *iv, size_t iv_len,
const unsigned char *add, size_t add_len,
const unsigned char *input, unsigned char *output,
const unsigned char *tag, size_t tag_len )
{
int ret = MBEDTLS_ERR_ERROR_CORRUPTION_DETECTED;
unsigned char check_tag[16];
unsigned char i;
int diff;
CCM_VALIDATE_RET( ctx != NULL );
CCM_VALIDATE_RET( iv != NULL );
CCM_VALIDATE_RET( add_len == 0 || add != NULL );
CCM_VALIDATE_RET( length == 0 || input != NULL );
CCM_VALIDATE_RET( length == 0 || output != NULL );
CCM_VALIDATE_RET( tag_len == 0 || tag != NULL );
if( ( ret = ccm_auth_crypt( ctx, CCM_DECRYPT, length,
iv, iv_len, add, add_len,
input, output, check_tag, tag_len ) ) != 0 )
{
return( ret );
}
/* Check tag in "constant-time" */
for( diff = 0, i = 0; i < tag_len; i++ )
diff |= tag[i] ^ check_tag[i];
if( diff != 0 )
{
mbedtls_platform_zeroize( output, length );
return( MBEDTLS_ERR_CCM_AUTH_FAILED );
}
return( 0 );
}
int mbedtls_ccm_auth_decrypt( mbedtls_ccm_context *ctx, size_t length,
const unsigned char *iv, size_t iv_len,
const unsigned char *add, size_t add_len,
const unsigned char *input, unsigned char *output,
const unsigned char *tag, size_t tag_len )
{
CCM_VALIDATE_RET( ctx != NULL );
CCM_VALIDATE_RET( iv != NULL );
CCM_VALIDATE_RET( add_len == 0 || add != NULL );
CCM_VALIDATE_RET( length == 0 || input != NULL );
CCM_VALIDATE_RET( length == 0 || output != NULL );
CCM_VALIDATE_RET( tag_len == 0 || tag != NULL );
if( tag_len == 0 )
return( MBEDTLS_ERR_CCM_BAD_INPUT );
return( mbedtls_ccm_star_auth_decrypt( ctx, length, iv, iv_len, add,
add_len, input, output, tag, tag_len ) );
}
#endif /* !MBEDTLS_CCM_ALT */
#if defined(MBEDTLS_SELF_TEST) && defined(MBEDTLS_AES_C)
/*
* Examples 1 to 3 from SP800-38C Appendix C
*/
#define NB_TESTS 3
#define CCM_SELFTEST_PT_MAX_LEN 24
#define CCM_SELFTEST_CT_MAX_LEN 32
/*
* The data is the same for all tests, only the used length changes
*/
static const unsigned char key_test_data[] = {
0x40, 0x41, 0x42, 0x43, 0x44, 0x45, 0x46, 0x47,
0x48, 0x49, 0x4a, 0x4b, 0x4c, 0x4d, 0x4e, 0x4f
};
static const unsigned char iv_test_data[] = {
0x10, 0x11, 0x12, 0x13, 0x14, 0x15, 0x16, 0x17,
0x18, 0x19, 0x1a, 0x1b
};
static const unsigned char ad_test_data[] = {
0x00, 0x01, 0x02, 0x03, 0x04, 0x05, 0x06, 0x07,
0x08, 0x09, 0x0a, 0x0b, 0x0c, 0x0d, 0x0e, 0x0f,
0x10, 0x11, 0x12, 0x13
};
static const unsigned char msg_test_data[CCM_SELFTEST_PT_MAX_LEN] = {
0x20, 0x21, 0x22, 0x23, 0x24, 0x25, 0x26, 0x27,
0x28, 0x29, 0x2a, 0x2b, 0x2c, 0x2d, 0x2e, 0x2f,
0x30, 0x31, 0x32, 0x33, 0x34, 0x35, 0x36, 0x37,
};
static const size_t iv_len_test_data [NB_TESTS] = { 7, 8, 12 };
static const size_t add_len_test_data[NB_TESTS] = { 8, 16, 20 };
static const size_t msg_len_test_data[NB_TESTS] = { 4, 16, 24 };
static const size_t tag_len_test_data[NB_TESTS] = { 4, 6, 8 };
static const unsigned char res_test_data[NB_TESTS][CCM_SELFTEST_CT_MAX_LEN] = {
{ 0x71, 0x62, 0x01, 0x5b, 0x4d, 0xac, 0x25, 0x5d },
{ 0xd2, 0xa1, 0xf0, 0xe0, 0x51, 0xea, 0x5f, 0x62,
0x08, 0x1a, 0x77, 0x92, 0x07, 0x3d, 0x59, 0x3d,
0x1f, 0xc6, 0x4f, 0xbf, 0xac, 0xcd },
{ 0xe3, 0xb2, 0x01, 0xa9, 0xf5, 0xb7, 0x1a, 0x7a,
0x9b, 0x1c, 0xea, 0xec, 0xcd, 0x97, 0xe7, 0x0b,
0x61, 0x76, 0xaa, 0xd9, 0xa4, 0x42, 0x8a, 0xa5,
0x48, 0x43, 0x92, 0xfb, 0xc1, 0xb0, 0x99, 0x51 }
};
int mbedtls_ccm_self_test( int verbose )
{
mbedtls_ccm_context ctx;
/*
* Some hardware accelerators require the input and output buffers
* would be in RAM, because the flash is not accessible.
* Use buffers on the stack to hold the test vectors data.
*/
unsigned char plaintext[CCM_SELFTEST_PT_MAX_LEN];
unsigned char ciphertext[CCM_SELFTEST_CT_MAX_LEN];
size_t i;
int ret = MBEDTLS_ERR_ERROR_CORRUPTION_DETECTED;
mbedtls_ccm_init( &ctx );
if( mbedtls_ccm_setkey( &ctx, MBEDTLS_CIPHER_ID_AES, key_test_data,
8 * sizeof key_test_data ) != 0 )
{
if( verbose != 0 )
mbedtls_printf( " CCM: setup failed" );
return( 1 );
}
for( i = 0; i < NB_TESTS; i++ )
{
if( verbose != 0 )
mbedtls_printf( " CCM-AES #%u: ", (unsigned int) i + 1 );
memset( plaintext, 0, CCM_SELFTEST_PT_MAX_LEN );
memset( ciphertext, 0, CCM_SELFTEST_CT_MAX_LEN );
memcpy( plaintext, msg_test_data, msg_len_test_data[i] );
ret = mbedtls_ccm_encrypt_and_tag( &ctx, msg_len_test_data[i],
iv_test_data, iv_len_test_data[i],
ad_test_data, add_len_test_data[i],
plaintext, ciphertext,
ciphertext + msg_len_test_data[i],
tag_len_test_data[i] );
if( ret != 0 ||
memcmp( ciphertext, res_test_data[i],
msg_len_test_data[i] + tag_len_test_data[i] ) != 0 )
{
if( verbose != 0 )
mbedtls_printf( "failed\n" );
return( 1 );
}
memset( plaintext, 0, CCM_SELFTEST_PT_MAX_LEN );
ret = mbedtls_ccm_auth_decrypt( &ctx, msg_len_test_data[i],
iv_test_data, iv_len_test_data[i],
ad_test_data, add_len_test_data[i],
ciphertext, plaintext,
ciphertext + msg_len_test_data[i],
tag_len_test_data[i] );
if( ret != 0 ||
memcmp( plaintext, msg_test_data, msg_len_test_data[i] ) != 0 )
{
if( verbose != 0 )
mbedtls_printf( "failed\n" );
return( 1 );
}
if( verbose != 0 )
mbedtls_printf( "passed\n" );
}
mbedtls_ccm_free( &ctx );
if( verbose != 0 )
mbedtls_printf( "\n" );
return( 0 );
}
#endif /* MBEDTLS_SELF_TEST && MBEDTLS_AES_C */
#endif /* MBEDTLS_CCM_C */
|
0 | repos/gpt4all.zig/src/zig-libcurl/zig-mbedtls/mbedtls | repos/gpt4all.zig/src/zig-libcurl/zig-mbedtls/mbedtls/library/md4.c | /*
* RFC 1186/1320 compliant MD4 implementation
*
* Copyright The Mbed TLS Contributors
* SPDX-License-Identifier: Apache-2.0
*
* 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.
*/
/*
* The MD4 algorithm was designed by Ron Rivest in 1990.
*
* http://www.ietf.org/rfc/rfc1186.txt
* http://www.ietf.org/rfc/rfc1320.txt
*/
#include "common.h"
#if defined(MBEDTLS_MD4_C)
#include "mbedtls/md4.h"
#include "mbedtls/platform_util.h"
#include "mbedtls/error.h"
#include <string.h>
#if defined(MBEDTLS_SELF_TEST)
#if defined(MBEDTLS_PLATFORM_C)
#include "mbedtls/platform.h"
#else
#include <stdio.h>
#define mbedtls_printf printf
#endif /* MBEDTLS_PLATFORM_C */
#endif /* MBEDTLS_SELF_TEST */
#if !defined(MBEDTLS_MD4_ALT)
/*
* 32-bit integer manipulation macros (little endian)
*/
#ifndef GET_UINT32_LE
#define GET_UINT32_LE(n,b,i) \
{ \
(n) = ( (uint32_t) (b)[(i) ] ) \
| ( (uint32_t) (b)[(i) + 1] << 8 ) \
| ( (uint32_t) (b)[(i) + 2] << 16 ) \
| ( (uint32_t) (b)[(i) + 3] << 24 ); \
}
#endif
#ifndef PUT_UINT32_LE
#define PUT_UINT32_LE(n,b,i) \
{ \
(b)[(i) ] = (unsigned char) ( ( (n) ) & 0xFF ); \
(b)[(i) + 1] = (unsigned char) ( ( (n) >> 8 ) & 0xFF ); \
(b)[(i) + 2] = (unsigned char) ( ( (n) >> 16 ) & 0xFF ); \
(b)[(i) + 3] = (unsigned char) ( ( (n) >> 24 ) & 0xFF ); \
}
#endif
void mbedtls_md4_init( mbedtls_md4_context *ctx )
{
memset( ctx, 0, sizeof( mbedtls_md4_context ) );
}
void mbedtls_md4_free( mbedtls_md4_context *ctx )
{
if( ctx == NULL )
return;
mbedtls_platform_zeroize( ctx, sizeof( mbedtls_md4_context ) );
}
void mbedtls_md4_clone( mbedtls_md4_context *dst,
const mbedtls_md4_context *src )
{
*dst = *src;
}
/*
* MD4 context setup
*/
int mbedtls_md4_starts_ret( mbedtls_md4_context *ctx )
{
ctx->total[0] = 0;
ctx->total[1] = 0;
ctx->state[0] = 0x67452301;
ctx->state[1] = 0xEFCDAB89;
ctx->state[2] = 0x98BADCFE;
ctx->state[3] = 0x10325476;
return( 0 );
}
#if !defined(MBEDTLS_DEPRECATED_REMOVED)
void mbedtls_md4_starts( mbedtls_md4_context *ctx )
{
mbedtls_md4_starts_ret( ctx );
}
#endif
#if !defined(MBEDTLS_MD4_PROCESS_ALT)
int mbedtls_internal_md4_process( mbedtls_md4_context *ctx,
const unsigned char data[64] )
{
struct
{
uint32_t X[16], A, B, C, D;
} local;
GET_UINT32_LE( local.X[ 0], data, 0 );
GET_UINT32_LE( local.X[ 1], data, 4 );
GET_UINT32_LE( local.X[ 2], data, 8 );
GET_UINT32_LE( local.X[ 3], data, 12 );
GET_UINT32_LE( local.X[ 4], data, 16 );
GET_UINT32_LE( local.X[ 5], data, 20 );
GET_UINT32_LE( local.X[ 6], data, 24 );
GET_UINT32_LE( local.X[ 7], data, 28 );
GET_UINT32_LE( local.X[ 8], data, 32 );
GET_UINT32_LE( local.X[ 9], data, 36 );
GET_UINT32_LE( local.X[10], data, 40 );
GET_UINT32_LE( local.X[11], data, 44 );
GET_UINT32_LE( local.X[12], data, 48 );
GET_UINT32_LE( local.X[13], data, 52 );
GET_UINT32_LE( local.X[14], data, 56 );
GET_UINT32_LE( local.X[15], data, 60 );
#define S(x,n) (((x) << (n)) | (((x) & 0xFFFFFFFF) >> (32 - (n))))
local.A = ctx->state[0];
local.B = ctx->state[1];
local.C = ctx->state[2];
local.D = ctx->state[3];
#define F(x, y, z) (((x) & (y)) | ((~(x)) & (z)))
#define P(a,b,c,d,x,s) \
do \
{ \
(a) += F((b),(c),(d)) + (x); \
(a) = S((a),(s)); \
} while( 0 )
P( local.A, local.B, local.C, local.D, local.X[ 0], 3 );
P( local.D, local.A, local.B, local.C, local.X[ 1], 7 );
P( local.C, local.D, local.A, local.B, local.X[ 2], 11 );
P( local.B, local.C, local.D, local.A, local.X[ 3], 19 );
P( local.A, local.B, local.C, local.D, local.X[ 4], 3 );
P( local.D, local.A, local.B, local.C, local.X[ 5], 7 );
P( local.C, local.D, local.A, local.B, local.X[ 6], 11 );
P( local.B, local.C, local.D, local.A, local.X[ 7], 19 );
P( local.A, local.B, local.C, local.D, local.X[ 8], 3 );
P( local.D, local.A, local.B, local.C, local.X[ 9], 7 );
P( local.C, local.D, local.A, local.B, local.X[10], 11 );
P( local.B, local.C, local.D, local.A, local.X[11], 19 );
P( local.A, local.B, local.C, local.D, local.X[12], 3 );
P( local.D, local.A, local.B, local.C, local.X[13], 7 );
P( local.C, local.D, local.A, local.B, local.X[14], 11 );
P( local.B, local.C, local.D, local.A, local.X[15], 19 );
#undef P
#undef F
#define F(x,y,z) (((x) & (y)) | ((x) & (z)) | ((y) & (z)))
#define P(a,b,c,d,x,s) \
do \
{ \
(a) += F((b),(c),(d)) + (x) + 0x5A827999; \
(a) = S((a),(s)); \
} while( 0 )
P( local.A, local.B, local.C, local.D, local.X[ 0], 3 );
P( local.D, local.A, local.B, local.C, local.X[ 4], 5 );
P( local.C, local.D, local.A, local.B, local.X[ 8], 9 );
P( local.B, local.C, local.D, local.A, local.X[12], 13 );
P( local.A, local.B, local.C, local.D, local.X[ 1], 3 );
P( local.D, local.A, local.B, local.C, local.X[ 5], 5 );
P( local.C, local.D, local.A, local.B, local.X[ 9], 9 );
P( local.B, local.C, local.D, local.A, local.X[13], 13 );
P( local.A, local.B, local.C, local.D, local.X[ 2], 3 );
P( local.D, local.A, local.B, local.C, local.X[ 6], 5 );
P( local.C, local.D, local.A, local.B, local.X[10], 9 );
P( local.B, local.C, local.D, local.A, local.X[14], 13 );
P( local.A, local.B, local.C, local.D, local.X[ 3], 3 );
P( local.D, local.A, local.B, local.C, local.X[ 7], 5 );
P( local.C, local.D, local.A, local.B, local.X[11], 9 );
P( local.B, local.C, local.D, local.A, local.X[15], 13 );
#undef P
#undef F
#define F(x,y,z) ((x) ^ (y) ^ (z))
#define P(a,b,c,d,x,s) \
do \
{ \
(a) += F((b),(c),(d)) + (x) + 0x6ED9EBA1; \
(a) = S((a),(s)); \
} while( 0 )
P( local.A, local.B, local.C, local.D, local.X[ 0], 3 );
P( local.D, local.A, local.B, local.C, local.X[ 8], 9 );
P( local.C, local.D, local.A, local.B, local.X[ 4], 11 );
P( local.B, local.C, local.D, local.A, local.X[12], 15 );
P( local.A, local.B, local.C, local.D, local.X[ 2], 3 );
P( local.D, local.A, local.B, local.C, local.X[10], 9 );
P( local.C, local.D, local.A, local.B, local.X[ 6], 11 );
P( local.B, local.C, local.D, local.A, local.X[14], 15 );
P( local.A, local.B, local.C, local.D, local.X[ 1], 3 );
P( local.D, local.A, local.B, local.C, local.X[ 9], 9 );
P( local.C, local.D, local.A, local.B, local.X[ 5], 11 );
P( local.B, local.C, local.D, local.A, local.X[13], 15 );
P( local.A, local.B, local.C, local.D, local.X[ 3], 3 );
P( local.D, local.A, local.B, local.C, local.X[11], 9 );
P( local.C, local.D, local.A, local.B, local.X[ 7], 11 );
P( local.B, local.C, local.D, local.A, local.X[15], 15 );
#undef F
#undef P
ctx->state[0] += local.A;
ctx->state[1] += local.B;
ctx->state[2] += local.C;
ctx->state[3] += local.D;
/* Zeroise variables to clear sensitive data from memory. */
mbedtls_platform_zeroize( &local, sizeof( local ) );
return( 0 );
}
#if !defined(MBEDTLS_DEPRECATED_REMOVED)
void mbedtls_md4_process( mbedtls_md4_context *ctx,
const unsigned char data[64] )
{
mbedtls_internal_md4_process( ctx, data );
}
#endif
#endif /* !MBEDTLS_MD4_PROCESS_ALT */
/*
* MD4 process buffer
*/
int mbedtls_md4_update_ret( mbedtls_md4_context *ctx,
const unsigned char *input,
size_t ilen )
{
int ret = MBEDTLS_ERR_ERROR_CORRUPTION_DETECTED;
size_t fill;
uint32_t left;
if( ilen == 0 )
return( 0 );
left = ctx->total[0] & 0x3F;
fill = 64 - left;
ctx->total[0] += (uint32_t) ilen;
ctx->total[0] &= 0xFFFFFFFF;
if( ctx->total[0] < (uint32_t) ilen )
ctx->total[1]++;
if( left && ilen >= fill )
{
memcpy( (void *) (ctx->buffer + left),
(void *) input, fill );
if( ( ret = mbedtls_internal_md4_process( ctx, ctx->buffer ) ) != 0 )
return( ret );
input += fill;
ilen -= fill;
left = 0;
}
while( ilen >= 64 )
{
if( ( ret = mbedtls_internal_md4_process( ctx, input ) ) != 0 )
return( ret );
input += 64;
ilen -= 64;
}
if( ilen > 0 )
{
memcpy( (void *) (ctx->buffer + left),
(void *) input, ilen );
}
return( 0 );
}
#if !defined(MBEDTLS_DEPRECATED_REMOVED)
void mbedtls_md4_update( mbedtls_md4_context *ctx,
const unsigned char *input,
size_t ilen )
{
mbedtls_md4_update_ret( ctx, input, ilen );
}
#endif
static const unsigned char md4_padding[64] =
{
0x80, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0
};
/*
* MD4 final digest
*/
int mbedtls_md4_finish_ret( mbedtls_md4_context *ctx,
unsigned char output[16] )
{
int ret = MBEDTLS_ERR_ERROR_CORRUPTION_DETECTED;
uint32_t last, padn;
uint32_t high, low;
unsigned char msglen[8];
high = ( ctx->total[0] >> 29 )
| ( ctx->total[1] << 3 );
low = ( ctx->total[0] << 3 );
PUT_UINT32_LE( low, msglen, 0 );
PUT_UINT32_LE( high, msglen, 4 );
last = ctx->total[0] & 0x3F;
padn = ( last < 56 ) ? ( 56 - last ) : ( 120 - last );
ret = mbedtls_md4_update_ret( ctx, (unsigned char *)md4_padding, padn );
if( ret != 0 )
return( ret );
if( ( ret = mbedtls_md4_update_ret( ctx, msglen, 8 ) ) != 0 )
return( ret );
PUT_UINT32_LE( ctx->state[0], output, 0 );
PUT_UINT32_LE( ctx->state[1], output, 4 );
PUT_UINT32_LE( ctx->state[2], output, 8 );
PUT_UINT32_LE( ctx->state[3], output, 12 );
return( 0 );
}
#if !defined(MBEDTLS_DEPRECATED_REMOVED)
void mbedtls_md4_finish( mbedtls_md4_context *ctx,
unsigned char output[16] )
{
mbedtls_md4_finish_ret( ctx, output );
}
#endif
#endif /* !MBEDTLS_MD4_ALT */
/*
* output = MD4( input buffer )
*/
int mbedtls_md4_ret( const unsigned char *input,
size_t ilen,
unsigned char output[16] )
{
int ret = MBEDTLS_ERR_ERROR_CORRUPTION_DETECTED;
mbedtls_md4_context ctx;
mbedtls_md4_init( &ctx );
if( ( ret = mbedtls_md4_starts_ret( &ctx ) ) != 0 )
goto exit;
if( ( ret = mbedtls_md4_update_ret( &ctx, input, ilen ) ) != 0 )
goto exit;
if( ( ret = mbedtls_md4_finish_ret( &ctx, output ) ) != 0 )
goto exit;
exit:
mbedtls_md4_free( &ctx );
return( ret );
}
#if !defined(MBEDTLS_DEPRECATED_REMOVED)
void mbedtls_md4( const unsigned char *input,
size_t ilen,
unsigned char output[16] )
{
mbedtls_md4_ret( input, ilen, output );
}
#endif
#if defined(MBEDTLS_SELF_TEST)
/*
* RFC 1320 test vectors
*/
static const unsigned char md4_test_str[7][81] =
{
{ "" },
{ "a" },
{ "abc" },
{ "message digest" },
{ "abcdefghijklmnopqrstuvwxyz" },
{ "ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789" },
{ "12345678901234567890123456789012345678901234567890123456789012345678901234567890" }
};
static const size_t md4_test_strlen[7] =
{
0, 1, 3, 14, 26, 62, 80
};
static const unsigned char md4_test_sum[7][16] =
{
{ 0x31, 0xD6, 0xCF, 0xE0, 0xD1, 0x6A, 0xE9, 0x31,
0xB7, 0x3C, 0x59, 0xD7, 0xE0, 0xC0, 0x89, 0xC0 },
{ 0xBD, 0xE5, 0x2C, 0xB3, 0x1D, 0xE3, 0x3E, 0x46,
0x24, 0x5E, 0x05, 0xFB, 0xDB, 0xD6, 0xFB, 0x24 },
{ 0xA4, 0x48, 0x01, 0x7A, 0xAF, 0x21, 0xD8, 0x52,
0x5F, 0xC1, 0x0A, 0xE8, 0x7A, 0xA6, 0x72, 0x9D },
{ 0xD9, 0x13, 0x0A, 0x81, 0x64, 0x54, 0x9F, 0xE8,
0x18, 0x87, 0x48, 0x06, 0xE1, 0xC7, 0x01, 0x4B },
{ 0xD7, 0x9E, 0x1C, 0x30, 0x8A, 0xA5, 0xBB, 0xCD,
0xEE, 0xA8, 0xED, 0x63, 0xDF, 0x41, 0x2D, 0xA9 },
{ 0x04, 0x3F, 0x85, 0x82, 0xF2, 0x41, 0xDB, 0x35,
0x1C, 0xE6, 0x27, 0xE1, 0x53, 0xE7, 0xF0, 0xE4 },
{ 0xE3, 0x3B, 0x4D, 0xDC, 0x9C, 0x38, 0xF2, 0x19,
0x9C, 0x3E, 0x7B, 0x16, 0x4F, 0xCC, 0x05, 0x36 }
};
/*
* Checkup routine
*/
int mbedtls_md4_self_test( int verbose )
{
int i, ret = 0;
unsigned char md4sum[16];
for( i = 0; i < 7; i++ )
{
if( verbose != 0 )
mbedtls_printf( " MD4 test #%d: ", i + 1 );
ret = mbedtls_md4_ret( md4_test_str[i], md4_test_strlen[i], md4sum );
if( ret != 0 )
goto fail;
if( memcmp( md4sum, md4_test_sum[i], 16 ) != 0 )
{
ret = 1;
goto fail;
}
if( verbose != 0 )
mbedtls_printf( "passed\n" );
}
if( verbose != 0 )
mbedtls_printf( "\n" );
return( 0 );
fail:
if( verbose != 0 )
mbedtls_printf( "failed\n" );
return( ret );
}
#endif /* MBEDTLS_SELF_TEST */
#endif /* MBEDTLS_MD4_C */
|
0 | repos/gpt4all.zig/src/zig-libcurl/zig-mbedtls/mbedtls | repos/gpt4all.zig/src/zig-libcurl/zig-mbedtls/mbedtls/library/ssl_srv.c | /*
* SSLv3/TLSv1 server-side functions
*
* Copyright The Mbed TLS Contributors
* SPDX-License-Identifier: Apache-2.0
*
* 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.
*/
#include "common.h"
#if defined(MBEDTLS_SSL_SRV_C)
#if defined(MBEDTLS_PLATFORM_C)
#include "mbedtls/platform.h"
#else
#include <stdlib.h>
#define mbedtls_calloc calloc
#define mbedtls_free free
#endif
#include "mbedtls/ssl.h"
#include "mbedtls/ssl_internal.h"
#include "mbedtls/debug.h"
#include "mbedtls/error.h"
#include "mbedtls/platform_util.h"
#include <string.h>
#if defined(MBEDTLS_ECP_C)
#include "mbedtls/ecp.h"
#endif
#if defined(MBEDTLS_HAVE_TIME)
#include "mbedtls/platform_time.h"
#endif
#if defined(MBEDTLS_SSL_DTLS_HELLO_VERIFY)
int mbedtls_ssl_set_client_transport_id( mbedtls_ssl_context *ssl,
const unsigned char *info,
size_t ilen )
{
if( ssl->conf->endpoint != MBEDTLS_SSL_IS_SERVER )
return( MBEDTLS_ERR_SSL_BAD_INPUT_DATA );
mbedtls_free( ssl->cli_id );
if( ( ssl->cli_id = mbedtls_calloc( 1, ilen ) ) == NULL )
return( MBEDTLS_ERR_SSL_ALLOC_FAILED );
memcpy( ssl->cli_id, info, ilen );
ssl->cli_id_len = ilen;
return( 0 );
}
void mbedtls_ssl_conf_dtls_cookies( mbedtls_ssl_config *conf,
mbedtls_ssl_cookie_write_t *f_cookie_write,
mbedtls_ssl_cookie_check_t *f_cookie_check,
void *p_cookie )
{
conf->f_cookie_write = f_cookie_write;
conf->f_cookie_check = f_cookie_check;
conf->p_cookie = p_cookie;
}
#endif /* MBEDTLS_SSL_DTLS_HELLO_VERIFY */
#if defined(MBEDTLS_SSL_SERVER_NAME_INDICATION)
static int ssl_parse_servername_ext( mbedtls_ssl_context *ssl,
const unsigned char *buf,
size_t len )
{
int ret = MBEDTLS_ERR_ERROR_CORRUPTION_DETECTED;
size_t servername_list_size, hostname_len;
const unsigned char *p;
MBEDTLS_SSL_DEBUG_MSG( 3, ( "parse ServerName extension" ) );
if( len < 2 )
{
MBEDTLS_SSL_DEBUG_MSG( 1, ( "bad client hello message" ) );
mbedtls_ssl_send_alert_message( ssl, MBEDTLS_SSL_ALERT_LEVEL_FATAL,
MBEDTLS_SSL_ALERT_MSG_DECODE_ERROR );
return( MBEDTLS_ERR_SSL_BAD_HS_CLIENT_HELLO );
}
servername_list_size = ( ( buf[0] << 8 ) | ( buf[1] ) );
if( servername_list_size + 2 != len )
{
MBEDTLS_SSL_DEBUG_MSG( 1, ( "bad client hello message" ) );
mbedtls_ssl_send_alert_message( ssl, MBEDTLS_SSL_ALERT_LEVEL_FATAL,
MBEDTLS_SSL_ALERT_MSG_DECODE_ERROR );
return( MBEDTLS_ERR_SSL_BAD_HS_CLIENT_HELLO );
}
p = buf + 2;
while( servername_list_size > 2 )
{
hostname_len = ( ( p[1] << 8 ) | p[2] );
if( hostname_len + 3 > servername_list_size )
{
MBEDTLS_SSL_DEBUG_MSG( 1, ( "bad client hello message" ) );
mbedtls_ssl_send_alert_message( ssl, MBEDTLS_SSL_ALERT_LEVEL_FATAL,
MBEDTLS_SSL_ALERT_MSG_DECODE_ERROR );
return( MBEDTLS_ERR_SSL_BAD_HS_CLIENT_HELLO );
}
if( p[0] == MBEDTLS_TLS_EXT_SERVERNAME_HOSTNAME )
{
ret = ssl->conf->f_sni( ssl->conf->p_sni,
ssl, p + 3, hostname_len );
if( ret != 0 )
{
MBEDTLS_SSL_DEBUG_RET( 1, "ssl_sni_wrapper", ret );
mbedtls_ssl_send_alert_message( ssl, MBEDTLS_SSL_ALERT_LEVEL_FATAL,
MBEDTLS_SSL_ALERT_MSG_UNRECOGNIZED_NAME );
return( MBEDTLS_ERR_SSL_BAD_HS_CLIENT_HELLO );
}
return( 0 );
}
servername_list_size -= hostname_len + 3;
p += hostname_len + 3;
}
if( servername_list_size != 0 )
{
MBEDTLS_SSL_DEBUG_MSG( 1, ( "bad client hello message" ) );
mbedtls_ssl_send_alert_message( ssl, MBEDTLS_SSL_ALERT_LEVEL_FATAL,
MBEDTLS_SSL_ALERT_MSG_ILLEGAL_PARAMETER );
return( MBEDTLS_ERR_SSL_BAD_HS_CLIENT_HELLO );
}
return( 0 );
}
#endif /* MBEDTLS_SSL_SERVER_NAME_INDICATION */
#if defined(MBEDTLS_KEY_EXCHANGE_SOME_PSK_ENABLED)
static int ssl_conf_has_psk_or_cb( mbedtls_ssl_config const *conf )
{
if( conf->f_psk != NULL )
return( 1 );
if( conf->psk_identity_len == 0 || conf->psk_identity == NULL )
return( 0 );
if( conf->psk != NULL && conf->psk_len != 0 )
return( 1 );
#if defined(MBEDTLS_USE_PSA_CRYPTO)
if( ! mbedtls_svc_key_id_is_null( conf->psk_opaque ) )
return( 1 );
#endif /* MBEDTLS_USE_PSA_CRYPTO */
return( 0 );
}
#if defined(MBEDTLS_USE_PSA_CRYPTO)
static int ssl_use_opaque_psk( mbedtls_ssl_context const *ssl )
{
if( ssl->conf->f_psk != NULL )
{
/* If we've used a callback to select the PSK,
* the static configuration is irrelevant. */
if( ! mbedtls_svc_key_id_is_null( ssl->handshake->psk_opaque ) )
return( 1 );
return( 0 );
}
if( ! mbedtls_svc_key_id_is_null( ssl->conf->psk_opaque ) )
return( 1 );
return( 0 );
}
#endif /* MBEDTLS_USE_PSA_CRYPTO */
#endif /* MBEDTLS_KEY_EXCHANGE_SOME_PSK_ENABLED */
static int ssl_parse_renegotiation_info( mbedtls_ssl_context *ssl,
const unsigned char *buf,
size_t len )
{
#if defined(MBEDTLS_SSL_RENEGOTIATION)
if( ssl->renego_status != MBEDTLS_SSL_INITIAL_HANDSHAKE )
{
/* Check verify-data in constant-time. The length OTOH is no secret */
if( len != 1 + ssl->verify_data_len ||
buf[0] != ssl->verify_data_len ||
mbedtls_ssl_safer_memcmp( buf + 1, ssl->peer_verify_data,
ssl->verify_data_len ) != 0 )
{
MBEDTLS_SSL_DEBUG_MSG( 1, ( "non-matching renegotiation info" ) );
mbedtls_ssl_send_alert_message( ssl, MBEDTLS_SSL_ALERT_LEVEL_FATAL,
MBEDTLS_SSL_ALERT_MSG_HANDSHAKE_FAILURE );
return( MBEDTLS_ERR_SSL_BAD_HS_CLIENT_HELLO );
}
}
else
#endif /* MBEDTLS_SSL_RENEGOTIATION */
{
if( len != 1 || buf[0] != 0x0 )
{
MBEDTLS_SSL_DEBUG_MSG( 1, ( "non-zero length renegotiation info" ) );
mbedtls_ssl_send_alert_message( ssl, MBEDTLS_SSL_ALERT_LEVEL_FATAL,
MBEDTLS_SSL_ALERT_MSG_HANDSHAKE_FAILURE );
return( MBEDTLS_ERR_SSL_BAD_HS_CLIENT_HELLO );
}
ssl->secure_renegotiation = MBEDTLS_SSL_SECURE_RENEGOTIATION;
}
return( 0 );
}
#if defined(MBEDTLS_SSL_PROTO_TLS1_2) && \
defined(MBEDTLS_KEY_EXCHANGE_WITH_CERT_ENABLED)
/*
* Status of the implementation of signature-algorithms extension:
*
* Currently, we are only considering the signature-algorithm extension
* to pick a ciphersuite which allows us to send the ServerKeyExchange
* message with a signature-hash combination that the user allows.
*
* We do *not* check whether all certificates in our certificate
* chain are signed with an allowed signature-hash pair.
* This needs to be done at a later stage.
*
*/
static int ssl_parse_signature_algorithms_ext( mbedtls_ssl_context *ssl,
const unsigned char *buf,
size_t len )
{
size_t sig_alg_list_size;
const unsigned char *p;
const unsigned char *end = buf + len;
mbedtls_md_type_t md_cur;
mbedtls_pk_type_t sig_cur;
if ( len < 2 ) {
MBEDTLS_SSL_DEBUG_MSG( 1, ( "bad client hello message" ) );
mbedtls_ssl_send_alert_message( ssl, MBEDTLS_SSL_ALERT_LEVEL_FATAL,
MBEDTLS_SSL_ALERT_MSG_DECODE_ERROR );
return( MBEDTLS_ERR_SSL_BAD_HS_CLIENT_HELLO );
}
sig_alg_list_size = ( ( buf[0] << 8 ) | ( buf[1] ) );
if( sig_alg_list_size + 2 != len ||
sig_alg_list_size % 2 != 0 )
{
MBEDTLS_SSL_DEBUG_MSG( 1, ( "bad client hello message" ) );
mbedtls_ssl_send_alert_message( ssl, MBEDTLS_SSL_ALERT_LEVEL_FATAL,
MBEDTLS_SSL_ALERT_MSG_DECODE_ERROR );
return( MBEDTLS_ERR_SSL_BAD_HS_CLIENT_HELLO );
}
/* Currently we only guarantee signing the ServerKeyExchange message according
* to the constraints specified in this extension (see above), so it suffices
* to remember only one suitable hash for each possible signature algorithm.
*
* This will change when we also consider certificate signatures,
* in which case we will need to remember the whole signature-hash
* pair list from the extension.
*/
for( p = buf + 2; p < end; p += 2 )
{
/* Silently ignore unknown signature or hash algorithms. */
if( ( sig_cur = mbedtls_ssl_pk_alg_from_sig( p[1] ) ) == MBEDTLS_PK_NONE )
{
MBEDTLS_SSL_DEBUG_MSG( 3, ( "client hello v3, signature_algorithm ext"
" unknown sig alg encoding %d", p[1] ) );
continue;
}
/* Check if we support the hash the user proposes */
md_cur = mbedtls_ssl_md_alg_from_hash( p[0] );
if( md_cur == MBEDTLS_MD_NONE )
{
MBEDTLS_SSL_DEBUG_MSG( 3, ( "client hello v3, signature_algorithm ext:"
" unknown hash alg encoding %d", p[0] ) );
continue;
}
if( mbedtls_ssl_check_sig_hash( ssl, md_cur ) == 0 )
{
mbedtls_ssl_sig_hash_set_add( &ssl->handshake->hash_algs, sig_cur, md_cur );
MBEDTLS_SSL_DEBUG_MSG( 3, ( "client hello v3, signature_algorithm ext:"
" match sig %u and hash %u",
(unsigned) sig_cur, (unsigned) md_cur ) );
}
else
{
MBEDTLS_SSL_DEBUG_MSG( 3, ( "client hello v3, signature_algorithm ext: "
"hash alg %u not supported", (unsigned) md_cur ) );
}
}
return( 0 );
}
#endif /* MBEDTLS_SSL_PROTO_TLS1_2 &&
MBEDTLS_KEY_EXCHANGE_WITH_CERT_ENABLED */
#if defined(MBEDTLS_ECDH_C) || defined(MBEDTLS_ECDSA_C) || \
defined(MBEDTLS_KEY_EXCHANGE_ECJPAKE_ENABLED)
static int ssl_parse_supported_elliptic_curves( mbedtls_ssl_context *ssl,
const unsigned char *buf,
size_t len )
{
size_t list_size, our_size;
const unsigned char *p;
const mbedtls_ecp_curve_info *curve_info, **curves;
if ( len < 2 ) {
MBEDTLS_SSL_DEBUG_MSG( 1, ( "bad client hello message" ) );
mbedtls_ssl_send_alert_message( ssl, MBEDTLS_SSL_ALERT_LEVEL_FATAL,
MBEDTLS_SSL_ALERT_MSG_DECODE_ERROR );
return( MBEDTLS_ERR_SSL_BAD_HS_CLIENT_HELLO );
}
list_size = ( ( buf[0] << 8 ) | ( buf[1] ) );
if( list_size + 2 != len ||
list_size % 2 != 0 )
{
MBEDTLS_SSL_DEBUG_MSG( 1, ( "bad client hello message" ) );
mbedtls_ssl_send_alert_message( ssl, MBEDTLS_SSL_ALERT_LEVEL_FATAL,
MBEDTLS_SSL_ALERT_MSG_DECODE_ERROR );
return( MBEDTLS_ERR_SSL_BAD_HS_CLIENT_HELLO );
}
/* Should never happen unless client duplicates the extension */
if( ssl->handshake->curves != NULL )
{
MBEDTLS_SSL_DEBUG_MSG( 1, ( "bad client hello message" ) );
mbedtls_ssl_send_alert_message( ssl, MBEDTLS_SSL_ALERT_LEVEL_FATAL,
MBEDTLS_SSL_ALERT_MSG_DECODE_ERROR );
return( MBEDTLS_ERR_SSL_BAD_HS_CLIENT_HELLO );
}
/* Don't allow our peer to make us allocate too much memory,
* and leave room for a final 0 */
our_size = list_size / 2 + 1;
if( our_size > MBEDTLS_ECP_DP_MAX )
our_size = MBEDTLS_ECP_DP_MAX;
if( ( curves = mbedtls_calloc( our_size, sizeof( *curves ) ) ) == NULL )
{
mbedtls_ssl_send_alert_message( ssl, MBEDTLS_SSL_ALERT_LEVEL_FATAL,
MBEDTLS_SSL_ALERT_MSG_INTERNAL_ERROR );
return( MBEDTLS_ERR_SSL_ALLOC_FAILED );
}
ssl->handshake->curves = curves;
p = buf + 2;
while( list_size > 0 && our_size > 1 )
{
curve_info = mbedtls_ecp_curve_info_from_tls_id( ( p[0] << 8 ) | p[1] );
if( curve_info != NULL )
{
*curves++ = curve_info;
our_size--;
}
list_size -= 2;
p += 2;
}
return( 0 );
}
static int ssl_parse_supported_point_formats( mbedtls_ssl_context *ssl,
const unsigned char *buf,
size_t len )
{
size_t list_size;
const unsigned char *p;
if( len == 0 || (size_t)( buf[0] + 1 ) != len )
{
MBEDTLS_SSL_DEBUG_MSG( 1, ( "bad client hello message" ) );
mbedtls_ssl_send_alert_message( ssl, MBEDTLS_SSL_ALERT_LEVEL_FATAL,
MBEDTLS_SSL_ALERT_MSG_DECODE_ERROR );
return( MBEDTLS_ERR_SSL_BAD_HS_CLIENT_HELLO );
}
list_size = buf[0];
p = buf + 1;
while( list_size > 0 )
{
if( p[0] == MBEDTLS_ECP_PF_UNCOMPRESSED ||
p[0] == MBEDTLS_ECP_PF_COMPRESSED )
{
#if defined(MBEDTLS_ECDH_C) || defined(MBEDTLS_ECDSA_C)
ssl->handshake->ecdh_ctx.point_format = p[0];
#endif
#if defined(MBEDTLS_KEY_EXCHANGE_ECJPAKE_ENABLED)
ssl->handshake->ecjpake_ctx.point_format = p[0];
#endif
MBEDTLS_SSL_DEBUG_MSG( 4, ( "point format selected: %d", p[0] ) );
return( 0 );
}
list_size--;
p++;
}
return( 0 );
}
#endif /* MBEDTLS_ECDH_C || MBEDTLS_ECDSA_C ||
MBEDTLS_KEY_EXCHANGE_ECJPAKE_ENABLED */
#if defined(MBEDTLS_KEY_EXCHANGE_ECJPAKE_ENABLED)
static int ssl_parse_ecjpake_kkpp( mbedtls_ssl_context *ssl,
const unsigned char *buf,
size_t len )
{
int ret = MBEDTLS_ERR_ERROR_CORRUPTION_DETECTED;
if( mbedtls_ecjpake_check( &ssl->handshake->ecjpake_ctx ) != 0 )
{
MBEDTLS_SSL_DEBUG_MSG( 3, ( "skip ecjpake kkpp extension" ) );
return( 0 );
}
if( ( ret = mbedtls_ecjpake_read_round_one( &ssl->handshake->ecjpake_ctx,
buf, len ) ) != 0 )
{
MBEDTLS_SSL_DEBUG_RET( 1, "mbedtls_ecjpake_read_round_one", ret );
mbedtls_ssl_send_alert_message( ssl, MBEDTLS_SSL_ALERT_LEVEL_FATAL,
MBEDTLS_SSL_ALERT_MSG_ILLEGAL_PARAMETER );
return( ret );
}
/* Only mark the extension as OK when we're sure it is */
ssl->handshake->cli_exts |= MBEDTLS_TLS_EXT_ECJPAKE_KKPP_OK;
return( 0 );
}
#endif /* MBEDTLS_KEY_EXCHANGE_ECJPAKE_ENABLED */
#if defined(MBEDTLS_SSL_MAX_FRAGMENT_LENGTH)
static int ssl_parse_max_fragment_length_ext( mbedtls_ssl_context *ssl,
const unsigned char *buf,
size_t len )
{
if( len != 1 || buf[0] >= MBEDTLS_SSL_MAX_FRAG_LEN_INVALID )
{
MBEDTLS_SSL_DEBUG_MSG( 1, ( "bad client hello message" ) );
mbedtls_ssl_send_alert_message( ssl, MBEDTLS_SSL_ALERT_LEVEL_FATAL,
MBEDTLS_SSL_ALERT_MSG_ILLEGAL_PARAMETER );
return( MBEDTLS_ERR_SSL_BAD_HS_CLIENT_HELLO );
}
ssl->session_negotiate->mfl_code = buf[0];
return( 0 );
}
#endif /* MBEDTLS_SSL_MAX_FRAGMENT_LENGTH */
#if defined(MBEDTLS_SSL_DTLS_CONNECTION_ID)
static int ssl_parse_cid_ext( mbedtls_ssl_context *ssl,
const unsigned char *buf,
size_t len )
{
size_t peer_cid_len;
/* CID extension only makes sense in DTLS */
if( ssl->conf->transport != MBEDTLS_SSL_TRANSPORT_DATAGRAM )
{
MBEDTLS_SSL_DEBUG_MSG( 1, ( "bad client hello message" ) );
mbedtls_ssl_send_alert_message( ssl, MBEDTLS_SSL_ALERT_LEVEL_FATAL,
MBEDTLS_SSL_ALERT_MSG_ILLEGAL_PARAMETER );
return( MBEDTLS_ERR_SSL_BAD_HS_CLIENT_HELLO );
}
/*
* Quoting draft-ietf-tls-dtls-connection-id-05
* https://tools.ietf.org/html/draft-ietf-tls-dtls-connection-id-05
*
* struct {
* opaque cid<0..2^8-1>;
* } ConnectionId;
*/
if( len < 1 )
{
MBEDTLS_SSL_DEBUG_MSG( 1, ( "bad client hello message" ) );
mbedtls_ssl_send_alert_message( ssl, MBEDTLS_SSL_ALERT_LEVEL_FATAL,
MBEDTLS_SSL_ALERT_MSG_ILLEGAL_PARAMETER );
return( MBEDTLS_ERR_SSL_BAD_HS_CLIENT_HELLO );
}
peer_cid_len = *buf++;
len--;
if( len != peer_cid_len )
{
MBEDTLS_SSL_DEBUG_MSG( 1, ( "bad client hello message" ) );
mbedtls_ssl_send_alert_message( ssl, MBEDTLS_SSL_ALERT_LEVEL_FATAL,
MBEDTLS_SSL_ALERT_MSG_ILLEGAL_PARAMETER );
return( MBEDTLS_ERR_SSL_BAD_HS_CLIENT_HELLO );
}
/* Ignore CID if the user has disabled its use. */
if( ssl->negotiate_cid == MBEDTLS_SSL_CID_DISABLED )
{
/* Leave ssl->handshake->cid_in_use in its default
* value of MBEDTLS_SSL_CID_DISABLED. */
MBEDTLS_SSL_DEBUG_MSG( 3, ( "Client sent CID extension, but CID disabled" ) );
return( 0 );
}
if( peer_cid_len > MBEDTLS_SSL_CID_OUT_LEN_MAX )
{
MBEDTLS_SSL_DEBUG_MSG( 1, ( "bad client hello message" ) );
mbedtls_ssl_send_alert_message( ssl, MBEDTLS_SSL_ALERT_LEVEL_FATAL,
MBEDTLS_SSL_ALERT_MSG_ILLEGAL_PARAMETER );
return( MBEDTLS_ERR_SSL_BAD_HS_CLIENT_HELLO );
}
ssl->handshake->cid_in_use = MBEDTLS_SSL_CID_ENABLED;
ssl->handshake->peer_cid_len = (uint8_t) peer_cid_len;
memcpy( ssl->handshake->peer_cid, buf, peer_cid_len );
MBEDTLS_SSL_DEBUG_MSG( 3, ( "Use of CID extension negotiated" ) );
MBEDTLS_SSL_DEBUG_BUF( 3, "Client CID", buf, peer_cid_len );
return( 0 );
}
#endif /* MBEDTLS_SSL_DTLS_CONNECTION_ID */
#if defined(MBEDTLS_SSL_TRUNCATED_HMAC)
static int ssl_parse_truncated_hmac_ext( mbedtls_ssl_context *ssl,
const unsigned char *buf,
size_t len )
{
if( len != 0 )
{
MBEDTLS_SSL_DEBUG_MSG( 1, ( "bad client hello message" ) );
mbedtls_ssl_send_alert_message( ssl, MBEDTLS_SSL_ALERT_LEVEL_FATAL,
MBEDTLS_SSL_ALERT_MSG_DECODE_ERROR );
return( MBEDTLS_ERR_SSL_BAD_HS_CLIENT_HELLO );
}
((void) buf);
if( ssl->conf->trunc_hmac == MBEDTLS_SSL_TRUNC_HMAC_ENABLED )
ssl->session_negotiate->trunc_hmac = MBEDTLS_SSL_TRUNC_HMAC_ENABLED;
return( 0 );
}
#endif /* MBEDTLS_SSL_TRUNCATED_HMAC */
#if defined(MBEDTLS_SSL_ENCRYPT_THEN_MAC)
static int ssl_parse_encrypt_then_mac_ext( mbedtls_ssl_context *ssl,
const unsigned char *buf,
size_t len )
{
if( len != 0 )
{
MBEDTLS_SSL_DEBUG_MSG( 1, ( "bad client hello message" ) );
mbedtls_ssl_send_alert_message( ssl, MBEDTLS_SSL_ALERT_LEVEL_FATAL,
MBEDTLS_SSL_ALERT_MSG_DECODE_ERROR );
return( MBEDTLS_ERR_SSL_BAD_HS_CLIENT_HELLO );
}
((void) buf);
if( ssl->conf->encrypt_then_mac == MBEDTLS_SSL_ETM_ENABLED &&
ssl->minor_ver != MBEDTLS_SSL_MINOR_VERSION_0 )
{
ssl->session_negotiate->encrypt_then_mac = MBEDTLS_SSL_ETM_ENABLED;
}
return( 0 );
}
#endif /* MBEDTLS_SSL_ENCRYPT_THEN_MAC */
#if defined(MBEDTLS_SSL_EXTENDED_MASTER_SECRET)
static int ssl_parse_extended_ms_ext( mbedtls_ssl_context *ssl,
const unsigned char *buf,
size_t len )
{
if( len != 0 )
{
MBEDTLS_SSL_DEBUG_MSG( 1, ( "bad client hello message" ) );
mbedtls_ssl_send_alert_message( ssl, MBEDTLS_SSL_ALERT_LEVEL_FATAL,
MBEDTLS_SSL_ALERT_MSG_DECODE_ERROR );
return( MBEDTLS_ERR_SSL_BAD_HS_CLIENT_HELLO );
}
((void) buf);
if( ssl->conf->extended_ms == MBEDTLS_SSL_EXTENDED_MS_ENABLED &&
ssl->minor_ver != MBEDTLS_SSL_MINOR_VERSION_0 )
{
ssl->handshake->extended_ms = MBEDTLS_SSL_EXTENDED_MS_ENABLED;
}
return( 0 );
}
#endif /* MBEDTLS_SSL_EXTENDED_MASTER_SECRET */
#if defined(MBEDTLS_SSL_SESSION_TICKETS)
static int ssl_parse_session_ticket_ext( mbedtls_ssl_context *ssl,
unsigned char *buf,
size_t len )
{
int ret = MBEDTLS_ERR_ERROR_CORRUPTION_DETECTED;
mbedtls_ssl_session session;
mbedtls_ssl_session_init( &session );
if( ssl->conf->f_ticket_parse == NULL ||
ssl->conf->f_ticket_write == NULL )
{
return( 0 );
}
/* Remember the client asked us to send a new ticket */
ssl->handshake->new_session_ticket = 1;
MBEDTLS_SSL_DEBUG_MSG( 3, ( "ticket length: %" MBEDTLS_PRINTF_SIZET, len ) );
if( len == 0 )
return( 0 );
#if defined(MBEDTLS_SSL_RENEGOTIATION)
if( ssl->renego_status != MBEDTLS_SSL_INITIAL_HANDSHAKE )
{
MBEDTLS_SSL_DEBUG_MSG( 3, ( "ticket rejected: renegotiating" ) );
return( 0 );
}
#endif /* MBEDTLS_SSL_RENEGOTIATION */
/*
* Failures are ok: just ignore the ticket and proceed.
*/
if( ( ret = ssl->conf->f_ticket_parse( ssl->conf->p_ticket, &session,
buf, len ) ) != 0 )
{
mbedtls_ssl_session_free( &session );
if( ret == MBEDTLS_ERR_SSL_INVALID_MAC )
MBEDTLS_SSL_DEBUG_MSG( 3, ( "ticket is not authentic" ) );
else if( ret == MBEDTLS_ERR_SSL_SESSION_TICKET_EXPIRED )
MBEDTLS_SSL_DEBUG_MSG( 3, ( "ticket is expired" ) );
else
MBEDTLS_SSL_DEBUG_RET( 1, "mbedtls_ssl_ticket_parse", ret );
return( 0 );
}
/*
* Keep the session ID sent by the client, since we MUST send it back to
* inform them we're accepting the ticket (RFC 5077 section 3.4)
*/
session.id_len = ssl->session_negotiate->id_len;
memcpy( &session.id, ssl->session_negotiate->id, session.id_len );
mbedtls_ssl_session_free( ssl->session_negotiate );
memcpy( ssl->session_negotiate, &session, sizeof( mbedtls_ssl_session ) );
/* Zeroize instead of free as we copied the content */
mbedtls_platform_zeroize( &session, sizeof( mbedtls_ssl_session ) );
MBEDTLS_SSL_DEBUG_MSG( 3, ( "session successfully restored from ticket" ) );
ssl->handshake->resume = 1;
/* Don't send a new ticket after all, this one is OK */
ssl->handshake->new_session_ticket = 0;
return( 0 );
}
#endif /* MBEDTLS_SSL_SESSION_TICKETS */
#if defined(MBEDTLS_SSL_ALPN)
static int ssl_parse_alpn_ext( mbedtls_ssl_context *ssl,
const unsigned char *buf, size_t len )
{
size_t list_len, cur_len, ours_len;
const unsigned char *theirs, *start, *end;
const char **ours;
/* If ALPN not configured, just ignore the extension */
if( ssl->conf->alpn_list == NULL )
return( 0 );
/*
* opaque ProtocolName<1..2^8-1>;
*
* struct {
* ProtocolName protocol_name_list<2..2^16-1>
* } ProtocolNameList;
*/
/* Min length is 2 (list_len) + 1 (name_len) + 1 (name) */
if( len < 4 )
{
mbedtls_ssl_send_alert_message( ssl, MBEDTLS_SSL_ALERT_LEVEL_FATAL,
MBEDTLS_SSL_ALERT_MSG_DECODE_ERROR );
return( MBEDTLS_ERR_SSL_BAD_HS_CLIENT_HELLO );
}
list_len = ( buf[0] << 8 ) | buf[1];
if( list_len != len - 2 )
{
mbedtls_ssl_send_alert_message( ssl, MBEDTLS_SSL_ALERT_LEVEL_FATAL,
MBEDTLS_SSL_ALERT_MSG_DECODE_ERROR );
return( MBEDTLS_ERR_SSL_BAD_HS_CLIENT_HELLO );
}
/*
* Validate peer's list (lengths)
*/
start = buf + 2;
end = buf + len;
for( theirs = start; theirs != end; theirs += cur_len )
{
cur_len = *theirs++;
/* Current identifier must fit in list */
if( cur_len > (size_t)( end - theirs ) )
{
mbedtls_ssl_send_alert_message( ssl, MBEDTLS_SSL_ALERT_LEVEL_FATAL,
MBEDTLS_SSL_ALERT_MSG_DECODE_ERROR );
return( MBEDTLS_ERR_SSL_BAD_HS_CLIENT_HELLO );
}
/* Empty strings MUST NOT be included */
if( cur_len == 0 )
{
mbedtls_ssl_send_alert_message( ssl, MBEDTLS_SSL_ALERT_LEVEL_FATAL,
MBEDTLS_SSL_ALERT_MSG_ILLEGAL_PARAMETER );
return( MBEDTLS_ERR_SSL_BAD_HS_CLIENT_HELLO );
}
}
/*
* Use our order of preference
*/
for( ours = ssl->conf->alpn_list; *ours != NULL; ours++ )
{
ours_len = strlen( *ours );
for( theirs = start; theirs != end; theirs += cur_len )
{
cur_len = *theirs++;
if( cur_len == ours_len &&
memcmp( theirs, *ours, cur_len ) == 0 )
{
ssl->alpn_chosen = *ours;
return( 0 );
}
}
}
/* If we get there, no match was found */
mbedtls_ssl_send_alert_message( ssl, MBEDTLS_SSL_ALERT_LEVEL_FATAL,
MBEDTLS_SSL_ALERT_MSG_NO_APPLICATION_PROTOCOL );
return( MBEDTLS_ERR_SSL_BAD_HS_CLIENT_HELLO );
}
#endif /* MBEDTLS_SSL_ALPN */
#if defined(MBEDTLS_SSL_DTLS_SRTP)
static int ssl_parse_use_srtp_ext( mbedtls_ssl_context *ssl,
const unsigned char *buf,
size_t len )
{
mbedtls_ssl_srtp_profile client_protection = MBEDTLS_TLS_SRTP_UNSET;
size_t i,j;
size_t profile_length;
uint16_t mki_length;
/*! 2 bytes for profile length and 1 byte for mki len */
const size_t size_of_lengths = 3;
/* If use_srtp is not configured, just ignore the extension */
if( ( ssl->conf->transport != MBEDTLS_SSL_TRANSPORT_DATAGRAM ) ||
( ssl->conf->dtls_srtp_profile_list == NULL ) ||
( ssl->conf->dtls_srtp_profile_list_len == 0 ) )
{
return( 0 );
}
/* RFC5764 section 4.1.1
* uint8 SRTPProtectionProfile[2];
*
* struct {
* SRTPProtectionProfiles SRTPProtectionProfiles;
* opaque srtp_mki<0..255>;
* } UseSRTPData;
* SRTPProtectionProfile SRTPProtectionProfiles<2..2^16-1>;
*/
/*
* Min length is 5: at least one protection profile(2 bytes)
* and length(2 bytes) + srtp_mki length(1 byte)
* Check here that we have at least 2 bytes of protection profiles length
* and one of srtp_mki length
*/
if( len < size_of_lengths )
{
mbedtls_ssl_send_alert_message( ssl, MBEDTLS_SSL_ALERT_LEVEL_FATAL,
MBEDTLS_SSL_ALERT_MSG_HANDSHAKE_FAILURE );
return( MBEDTLS_ERR_SSL_BAD_HS_CLIENT_HELLO );
}
ssl->dtls_srtp_info.chosen_dtls_srtp_profile = MBEDTLS_TLS_SRTP_UNSET;
/* first 2 bytes are protection profile length(in bytes) */
profile_length = ( buf[0] << 8 ) | buf[1];
buf += 2;
/* The profile length cannot be bigger than input buffer size - lengths fields */
if( profile_length > len - size_of_lengths ||
profile_length % 2 != 0 ) /* profiles are 2 bytes long, so the length must be even */
{
mbedtls_ssl_send_alert_message( ssl, MBEDTLS_SSL_ALERT_LEVEL_FATAL,
MBEDTLS_SSL_ALERT_MSG_HANDSHAKE_FAILURE );
return( MBEDTLS_ERR_SSL_BAD_HS_CLIENT_HELLO );
}
/*
* parse the extension list values are defined in
* http://www.iana.org/assignments/srtp-protection/srtp-protection.xhtml
*/
for( j = 0; j < profile_length; j += 2 )
{
uint16_t protection_profile_value = buf[j] << 8 | buf[j + 1];
client_protection = mbedtls_ssl_check_srtp_profile_value( protection_profile_value );
if( client_protection != MBEDTLS_TLS_SRTP_UNSET )
{
MBEDTLS_SSL_DEBUG_MSG( 3, ( "found srtp profile: %s",
mbedtls_ssl_get_srtp_profile_as_string(
client_protection ) ) );
}
else
{
continue;
}
/* check if suggested profile is in our list */
for( i = 0; i < ssl->conf->dtls_srtp_profile_list_len; i++)
{
if( client_protection == ssl->conf->dtls_srtp_profile_list[i] )
{
ssl->dtls_srtp_info.chosen_dtls_srtp_profile = ssl->conf->dtls_srtp_profile_list[i];
MBEDTLS_SSL_DEBUG_MSG( 3, ( "selected srtp profile: %s",
mbedtls_ssl_get_srtp_profile_as_string(
client_protection ) ) );
break;
}
}
if( ssl->dtls_srtp_info.chosen_dtls_srtp_profile != MBEDTLS_TLS_SRTP_UNSET )
break;
}
buf += profile_length; /* buf points to the mki length */
mki_length = *buf;
buf++;
if( mki_length > MBEDTLS_TLS_SRTP_MAX_MKI_LENGTH ||
mki_length + profile_length + size_of_lengths != len )
{
mbedtls_ssl_send_alert_message( ssl, MBEDTLS_SSL_ALERT_LEVEL_FATAL,
MBEDTLS_SSL_ALERT_MSG_HANDSHAKE_FAILURE );
return( MBEDTLS_ERR_SSL_BAD_HS_CLIENT_HELLO );
}
/* Parse the mki only if present and mki is supported locally */
if( ssl->conf->dtls_srtp_mki_support == MBEDTLS_SSL_DTLS_SRTP_MKI_SUPPORTED &&
mki_length > 0 )
{
ssl->dtls_srtp_info.mki_len = mki_length;
memcpy( ssl->dtls_srtp_info.mki_value, buf, mki_length );
MBEDTLS_SSL_DEBUG_BUF( 3, "using mki", ssl->dtls_srtp_info.mki_value,
ssl->dtls_srtp_info.mki_len );
}
return( 0 );
}
#endif /* MBEDTLS_SSL_DTLS_SRTP */
/*
* Auxiliary functions for ServerHello parsing and related actions
*/
#if defined(MBEDTLS_X509_CRT_PARSE_C)
/*
* Return 0 if the given key uses one of the acceptable curves, -1 otherwise
*/
#if defined(MBEDTLS_ECDSA_C)
static int ssl_check_key_curve( mbedtls_pk_context *pk,
const mbedtls_ecp_curve_info **curves )
{
const mbedtls_ecp_curve_info **crv = curves;
mbedtls_ecp_group_id grp_id = mbedtls_pk_ec( *pk )->grp.id;
while( *crv != NULL )
{
if( (*crv)->grp_id == grp_id )
return( 0 );
crv++;
}
return( -1 );
}
#endif /* MBEDTLS_ECDSA_C */
/*
* Try picking a certificate for this ciphersuite,
* return 0 on success and -1 on failure.
*/
static int ssl_pick_cert( mbedtls_ssl_context *ssl,
const mbedtls_ssl_ciphersuite_t * ciphersuite_info )
{
mbedtls_ssl_key_cert *cur, *list, *fallback = NULL;
mbedtls_pk_type_t pk_alg =
mbedtls_ssl_get_ciphersuite_sig_pk_alg( ciphersuite_info );
uint32_t flags;
#if defined(MBEDTLS_SSL_SERVER_NAME_INDICATION)
if( ssl->handshake->sni_key_cert != NULL )
list = ssl->handshake->sni_key_cert;
else
#endif
list = ssl->conf->key_cert;
if( pk_alg == MBEDTLS_PK_NONE )
return( 0 );
MBEDTLS_SSL_DEBUG_MSG( 3, ( "ciphersuite requires certificate" ) );
if( list == NULL )
{
MBEDTLS_SSL_DEBUG_MSG( 3, ( "server has no certificate" ) );
return( -1 );
}
for( cur = list; cur != NULL; cur = cur->next )
{
flags = 0;
MBEDTLS_SSL_DEBUG_CRT( 3, "candidate certificate chain, certificate",
cur->cert );
if( ! mbedtls_pk_can_do( &cur->cert->pk, pk_alg ) )
{
MBEDTLS_SSL_DEBUG_MSG( 3, ( "certificate mismatch: key type" ) );
continue;
}
/*
* This avoids sending the client a cert it'll reject based on
* keyUsage or other extensions.
*
* It also allows the user to provision different certificates for
* different uses based on keyUsage, eg if they want to avoid signing
* and decrypting with the same RSA key.
*/
if( mbedtls_ssl_check_cert_usage( cur->cert, ciphersuite_info,
MBEDTLS_SSL_IS_SERVER, &flags ) != 0 )
{
MBEDTLS_SSL_DEBUG_MSG( 3, ( "certificate mismatch: "
"(extended) key usage extension" ) );
continue;
}
#if defined(MBEDTLS_ECDSA_C)
if( pk_alg == MBEDTLS_PK_ECDSA &&
ssl_check_key_curve( &cur->cert->pk, ssl->handshake->curves ) != 0 )
{
MBEDTLS_SSL_DEBUG_MSG( 3, ( "certificate mismatch: elliptic curve" ) );
continue;
}
#endif
/*
* Try to select a SHA-1 certificate for pre-1.2 clients, but still
* present them a SHA-higher cert rather than failing if it's the only
* one we got that satisfies the other conditions.
*/
if( ssl->minor_ver < MBEDTLS_SSL_MINOR_VERSION_3 &&
cur->cert->sig_md != MBEDTLS_MD_SHA1 )
{
if( fallback == NULL )
fallback = cur;
{
MBEDTLS_SSL_DEBUG_MSG( 3, ( "certificate not preferred: "
"sha-2 with pre-TLS 1.2 client" ) );
continue;
}
}
/* If we get there, we got a winner */
break;
}
if( cur == NULL )
cur = fallback;
/* Do not update ssl->handshake->key_cert unless there is a match */
if( cur != NULL )
{
ssl->handshake->key_cert = cur;
MBEDTLS_SSL_DEBUG_CRT( 3, "selected certificate chain, certificate",
ssl->handshake->key_cert->cert );
return( 0 );
}
return( -1 );
}
#endif /* MBEDTLS_X509_CRT_PARSE_C */
/*
* Check if a given ciphersuite is suitable for use with our config/keys/etc
* Sets ciphersuite_info only if the suite matches.
*/
static int ssl_ciphersuite_match( mbedtls_ssl_context *ssl, int suite_id,
const mbedtls_ssl_ciphersuite_t **ciphersuite_info )
{
const mbedtls_ssl_ciphersuite_t *suite_info;
#if defined(MBEDTLS_SSL_PROTO_TLS1_2) && \
defined(MBEDTLS_KEY_EXCHANGE_WITH_CERT_ENABLED)
mbedtls_pk_type_t sig_type;
#endif
suite_info = mbedtls_ssl_ciphersuite_from_id( suite_id );
if( suite_info == NULL )
{
MBEDTLS_SSL_DEBUG_MSG( 1, ( "should never happen" ) );
return( MBEDTLS_ERR_SSL_INTERNAL_ERROR );
}
MBEDTLS_SSL_DEBUG_MSG( 3, ( "trying ciphersuite: %#04x (%s)",
(unsigned int) suite_id, suite_info->name ) );
if( suite_info->min_minor_ver > ssl->minor_ver ||
suite_info->max_minor_ver < ssl->minor_ver )
{
MBEDTLS_SSL_DEBUG_MSG( 3, ( "ciphersuite mismatch: version" ) );
return( 0 );
}
#if defined(MBEDTLS_SSL_PROTO_DTLS)
if( ssl->conf->transport == MBEDTLS_SSL_TRANSPORT_DATAGRAM &&
( suite_info->flags & MBEDTLS_CIPHERSUITE_NODTLS ) )
return( 0 );
#endif
#if defined(MBEDTLS_ARC4_C)
if( ssl->conf->arc4_disabled == MBEDTLS_SSL_ARC4_DISABLED &&
suite_info->cipher == MBEDTLS_CIPHER_ARC4_128 )
{
MBEDTLS_SSL_DEBUG_MSG( 3, ( "ciphersuite mismatch: rc4" ) );
return( 0 );
}
#endif
#if defined(MBEDTLS_KEY_EXCHANGE_ECJPAKE_ENABLED)
if( suite_info->key_exchange == MBEDTLS_KEY_EXCHANGE_ECJPAKE &&
( ssl->handshake->cli_exts & MBEDTLS_TLS_EXT_ECJPAKE_KKPP_OK ) == 0 )
{
MBEDTLS_SSL_DEBUG_MSG( 3, ( "ciphersuite mismatch: ecjpake "
"not configured or ext missing" ) );
return( 0 );
}
#endif
#if defined(MBEDTLS_ECDH_C) || defined(MBEDTLS_ECDSA_C)
if( mbedtls_ssl_ciphersuite_uses_ec( suite_info ) &&
( ssl->handshake->curves == NULL ||
ssl->handshake->curves[0] == NULL ) )
{
MBEDTLS_SSL_DEBUG_MSG( 3, ( "ciphersuite mismatch: "
"no common elliptic curve" ) );
return( 0 );
}
#endif
#if defined(MBEDTLS_KEY_EXCHANGE_SOME_PSK_ENABLED)
/* If the ciphersuite requires a pre-shared key and we don't
* have one, skip it now rather than failing later */
if( mbedtls_ssl_ciphersuite_uses_psk( suite_info ) &&
ssl_conf_has_psk_or_cb( ssl->conf ) == 0 )
{
MBEDTLS_SSL_DEBUG_MSG( 3, ( "ciphersuite mismatch: no pre-shared key" ) );
return( 0 );
}
#endif
#if defined(MBEDTLS_SSL_PROTO_TLS1_2) && \
defined(MBEDTLS_KEY_EXCHANGE_WITH_CERT_ENABLED)
/* If the ciphersuite requires signing, check whether
* a suitable hash algorithm is present. */
if( ssl->minor_ver == MBEDTLS_SSL_MINOR_VERSION_3 )
{
sig_type = mbedtls_ssl_get_ciphersuite_sig_alg( suite_info );
if( sig_type != MBEDTLS_PK_NONE &&
mbedtls_ssl_sig_hash_set_find( &ssl->handshake->hash_algs, sig_type ) == MBEDTLS_MD_NONE )
{
MBEDTLS_SSL_DEBUG_MSG( 3, ( "ciphersuite mismatch: no suitable hash algorithm "
"for signature algorithm %u", (unsigned) sig_type ) );
return( 0 );
}
}
#endif /* MBEDTLS_SSL_PROTO_TLS1_2 &&
MBEDTLS_KEY_EXCHANGE_WITH_CERT_ENABLED */
#if defined(MBEDTLS_X509_CRT_PARSE_C)
/*
* Final check: if ciphersuite requires us to have a
* certificate/key of a particular type:
* - select the appropriate certificate if we have one, or
* - try the next ciphersuite if we don't
* This must be done last since we modify the key_cert list.
*/
if( ssl_pick_cert( ssl, suite_info ) != 0 )
{
MBEDTLS_SSL_DEBUG_MSG( 3, ( "ciphersuite mismatch: "
"no suitable certificate" ) );
return( 0 );
}
#endif
*ciphersuite_info = suite_info;
return( 0 );
}
#if defined(MBEDTLS_SSL_SRV_SUPPORT_SSLV2_CLIENT_HELLO)
static int ssl_parse_client_hello_v2( mbedtls_ssl_context *ssl )
{
int ret, got_common_suite;
unsigned int i, j;
size_t n;
unsigned int ciph_len, sess_len, chal_len;
unsigned char *buf, *p;
const int *ciphersuites;
const mbedtls_ssl_ciphersuite_t *ciphersuite_info;
MBEDTLS_SSL_DEBUG_MSG( 2, ( "=> parse client hello v2" ) );
#if defined(MBEDTLS_SSL_RENEGOTIATION)
if( ssl->renego_status != MBEDTLS_SSL_INITIAL_HANDSHAKE )
{
MBEDTLS_SSL_DEBUG_MSG( 1, ( "client hello v2 illegal for renegotiation" ) );
mbedtls_ssl_send_alert_message( ssl, MBEDTLS_SSL_ALERT_LEVEL_FATAL,
MBEDTLS_SSL_ALERT_MSG_HANDSHAKE_FAILURE );
return( MBEDTLS_ERR_SSL_BAD_HS_CLIENT_HELLO );
}
#endif /* MBEDTLS_SSL_RENEGOTIATION */
buf = ssl->in_hdr;
MBEDTLS_SSL_DEBUG_BUF( 4, "record header", buf, 5 );
MBEDTLS_SSL_DEBUG_MSG( 3, ( "client hello v2, message type: %d",
buf[2] ) );
MBEDTLS_SSL_DEBUG_MSG( 3, ( "client hello v2, message len.: %d",
( ( buf[0] & 0x7F ) << 8 ) | buf[1] ) );
MBEDTLS_SSL_DEBUG_MSG( 3, ( "client hello v2, max. version: [%d:%d]",
buf[3], buf[4] ) );
/*
* SSLv2 Client Hello
*
* Record layer:
* 0 . 1 message length
*
* SSL layer:
* 2 . 2 message type
* 3 . 4 protocol version
*/
if( buf[2] != MBEDTLS_SSL_HS_CLIENT_HELLO ||
buf[3] != MBEDTLS_SSL_MAJOR_VERSION_3 )
{
MBEDTLS_SSL_DEBUG_MSG( 1, ( "bad client hello message" ) );
return( MBEDTLS_ERR_SSL_BAD_HS_CLIENT_HELLO );
}
n = ( ( buf[0] << 8 ) | buf[1] ) & 0x7FFF;
if( n < 17 || n > 512 )
{
MBEDTLS_SSL_DEBUG_MSG( 1, ( "bad client hello message" ) );
return( MBEDTLS_ERR_SSL_BAD_HS_CLIENT_HELLO );
}
ssl->major_ver = MBEDTLS_SSL_MAJOR_VERSION_3;
ssl->minor_ver = ( buf[4] <= ssl->conf->max_minor_ver )
? buf[4] : ssl->conf->max_minor_ver;
if( ssl->minor_ver < ssl->conf->min_minor_ver )
{
MBEDTLS_SSL_DEBUG_MSG( 1, ( "client only supports ssl smaller than minimum"
" [%d:%d] < [%d:%d]",
ssl->major_ver, ssl->minor_ver,
ssl->conf->min_major_ver, ssl->conf->min_minor_ver ) );
mbedtls_ssl_send_alert_message( ssl, MBEDTLS_SSL_ALERT_LEVEL_FATAL,
MBEDTLS_SSL_ALERT_MSG_PROTOCOL_VERSION );
return( MBEDTLS_ERR_SSL_BAD_HS_PROTOCOL_VERSION );
}
ssl->handshake->max_major_ver = buf[3];
ssl->handshake->max_minor_ver = buf[4];
if( ( ret = mbedtls_ssl_fetch_input( ssl, 2 + n ) ) != 0 )
{
MBEDTLS_SSL_DEBUG_RET( 1, "mbedtls_ssl_fetch_input", ret );
return( ret );
}
ssl->handshake->update_checksum( ssl, buf + 2, n );
buf = ssl->in_msg;
n = ssl->in_left - 5;
/*
* 0 . 1 ciphersuitelist length
* 2 . 3 session id length
* 4 . 5 challenge length
* 6 . .. ciphersuitelist
* .. . .. session id
* .. . .. challenge
*/
MBEDTLS_SSL_DEBUG_BUF( 4, "record contents", buf, n );
ciph_len = ( buf[0] << 8 ) | buf[1];
sess_len = ( buf[2] << 8 ) | buf[3];
chal_len = ( buf[4] << 8 ) | buf[5];
MBEDTLS_SSL_DEBUG_MSG( 3, ( "ciph_len: %u, sess_len: %u, chal_len: %u",
ciph_len, sess_len, chal_len ) );
/*
* Make sure each parameter length is valid
*/
if( ciph_len < 3 || ( ciph_len % 3 ) != 0 )
{
MBEDTLS_SSL_DEBUG_MSG( 1, ( "bad client hello message" ) );
return( MBEDTLS_ERR_SSL_BAD_HS_CLIENT_HELLO );
}
if( sess_len > 32 )
{
MBEDTLS_SSL_DEBUG_MSG( 1, ( "bad client hello message" ) );
return( MBEDTLS_ERR_SSL_BAD_HS_CLIENT_HELLO );
}
if( chal_len < 8 || chal_len > 32 )
{
MBEDTLS_SSL_DEBUG_MSG( 1, ( "bad client hello message" ) );
return( MBEDTLS_ERR_SSL_BAD_HS_CLIENT_HELLO );
}
if( n != 6 + ciph_len + sess_len + chal_len )
{
MBEDTLS_SSL_DEBUG_MSG( 1, ( "bad client hello message" ) );
return( MBEDTLS_ERR_SSL_BAD_HS_CLIENT_HELLO );
}
MBEDTLS_SSL_DEBUG_BUF( 3, "client hello, ciphersuitelist",
buf + 6, ciph_len );
MBEDTLS_SSL_DEBUG_BUF( 3, "client hello, session id",
buf + 6 + ciph_len, sess_len );
MBEDTLS_SSL_DEBUG_BUF( 3, "client hello, challenge",
buf + 6 + ciph_len + sess_len, chal_len );
p = buf + 6 + ciph_len;
ssl->session_negotiate->id_len = sess_len;
memset( ssl->session_negotiate->id, 0,
sizeof( ssl->session_negotiate->id ) );
memcpy( ssl->session_negotiate->id, p, ssl->session_negotiate->id_len );
p += sess_len;
memset( ssl->handshake->randbytes, 0, 64 );
memcpy( ssl->handshake->randbytes + 32 - chal_len, p, chal_len );
/*
* Check for TLS_EMPTY_RENEGOTIATION_INFO_SCSV
*/
for( i = 0, p = buf + 6; i < ciph_len; i += 3, p += 3 )
{
if( p[0] == 0 && p[1] == 0 && p[2] == MBEDTLS_SSL_EMPTY_RENEGOTIATION_INFO )
{
MBEDTLS_SSL_DEBUG_MSG( 3, ( "received TLS_EMPTY_RENEGOTIATION_INFO " ) );
#if defined(MBEDTLS_SSL_RENEGOTIATION)
if( ssl->renego_status == MBEDTLS_SSL_RENEGOTIATION_IN_PROGRESS )
{
MBEDTLS_SSL_DEBUG_MSG( 1, ( "received RENEGOTIATION SCSV "
"during renegotiation" ) );
mbedtls_ssl_send_alert_message( ssl, MBEDTLS_SSL_ALERT_LEVEL_FATAL,
MBEDTLS_SSL_ALERT_MSG_HANDSHAKE_FAILURE );
return( MBEDTLS_ERR_SSL_BAD_HS_CLIENT_HELLO );
}
#endif /* MBEDTLS_SSL_RENEGOTIATION */
ssl->secure_renegotiation = MBEDTLS_SSL_SECURE_RENEGOTIATION;
break;
}
}
#if defined(MBEDTLS_SSL_FALLBACK_SCSV)
for( i = 0, p = buf + 6; i < ciph_len; i += 3, p += 3 )
{
if( p[0] == 0 &&
p[1] == (unsigned char)( ( MBEDTLS_SSL_FALLBACK_SCSV_VALUE >> 8 ) & 0xff ) &&
p[2] == (unsigned char)( ( MBEDTLS_SSL_FALLBACK_SCSV_VALUE ) & 0xff ) )
{
MBEDTLS_SSL_DEBUG_MSG( 3, ( "received FALLBACK_SCSV" ) );
if( ssl->minor_ver < ssl->conf->max_minor_ver )
{
MBEDTLS_SSL_DEBUG_MSG( 1, ( "inapropriate fallback" ) );
mbedtls_ssl_send_alert_message( ssl, MBEDTLS_SSL_ALERT_LEVEL_FATAL,
MBEDTLS_SSL_ALERT_MSG_INAPROPRIATE_FALLBACK );
return( MBEDTLS_ERR_SSL_BAD_HS_CLIENT_HELLO );
}
break;
}
}
#endif /* MBEDTLS_SSL_FALLBACK_SCSV */
got_common_suite = 0;
ciphersuites = ssl->conf->ciphersuite_list[ssl->minor_ver];
ciphersuite_info = NULL;
#if defined(MBEDTLS_SSL_SRV_RESPECT_CLIENT_PREFERENCE)
for( j = 0, p = buf + 6; j < ciph_len; j += 3, p += 3 )
for( i = 0; ciphersuites[i] != 0; i++ )
#else
for( i = 0; ciphersuites[i] != 0; i++ )
for( j = 0, p = buf + 6; j < ciph_len; j += 3, p += 3 )
#endif
{
if( p[0] != 0 ||
p[1] != ( ( ciphersuites[i] >> 8 ) & 0xFF ) ||
p[2] != ( ( ciphersuites[i] ) & 0xFF ) )
continue;
got_common_suite = 1;
if( ( ret = ssl_ciphersuite_match( ssl, ciphersuites[i],
&ciphersuite_info ) ) != 0 )
return( ret );
if( ciphersuite_info != NULL )
goto have_ciphersuite_v2;
}
if( got_common_suite )
{
MBEDTLS_SSL_DEBUG_MSG( 1, ( "got ciphersuites in common, "
"but none of them usable" ) );
return( MBEDTLS_ERR_SSL_NO_USABLE_CIPHERSUITE );
}
else
{
MBEDTLS_SSL_DEBUG_MSG( 1, ( "got no ciphersuites in common" ) );
return( MBEDTLS_ERR_SSL_NO_CIPHER_CHOSEN );
}
have_ciphersuite_v2:
MBEDTLS_SSL_DEBUG_MSG( 2, ( "selected ciphersuite: %s", ciphersuite_info->name ) );
ssl->session_negotiate->ciphersuite = ciphersuites[i];
ssl->handshake->ciphersuite_info = ciphersuite_info;
/*
* SSLv2 Client Hello relevant renegotiation security checks
*/
if( ssl->secure_renegotiation == MBEDTLS_SSL_LEGACY_RENEGOTIATION &&
ssl->conf->allow_legacy_renegotiation == MBEDTLS_SSL_LEGACY_BREAK_HANDSHAKE )
{
MBEDTLS_SSL_DEBUG_MSG( 1, ( "legacy renegotiation, breaking off handshake" ) );
mbedtls_ssl_send_alert_message( ssl, MBEDTLS_SSL_ALERT_LEVEL_FATAL,
MBEDTLS_SSL_ALERT_MSG_HANDSHAKE_FAILURE );
return( MBEDTLS_ERR_SSL_BAD_HS_CLIENT_HELLO );
}
ssl->in_left = 0;
ssl->state++;
MBEDTLS_SSL_DEBUG_MSG( 2, ( "<= parse client hello v2" ) );
return( 0 );
}
#endif /* MBEDTLS_SSL_SRV_SUPPORT_SSLV2_CLIENT_HELLO */
/* This function doesn't alert on errors that happen early during
ClientHello parsing because they might indicate that the client is
not talking SSL/TLS at all and would not understand our alert. */
static int ssl_parse_client_hello( mbedtls_ssl_context *ssl )
{
int ret, got_common_suite;
size_t i, j;
size_t ciph_offset, comp_offset, ext_offset;
size_t msg_len, ciph_len, sess_len, comp_len, ext_len;
#if defined(MBEDTLS_SSL_PROTO_DTLS)
size_t cookie_offset, cookie_len;
#endif
unsigned char *buf, *p, *ext;
#if defined(MBEDTLS_SSL_RENEGOTIATION)
int renegotiation_info_seen = 0;
#endif
int handshake_failure = 0;
const int *ciphersuites;
const mbedtls_ssl_ciphersuite_t *ciphersuite_info;
int major, minor;
/* If there is no signature-algorithm extension present,
* we need to fall back to the default values for allowed
* signature-hash pairs. */
#if defined(MBEDTLS_SSL_PROTO_TLS1_2) && \
defined(MBEDTLS_KEY_EXCHANGE_WITH_CERT_ENABLED)
int sig_hash_alg_ext_present = 0;
#endif /* MBEDTLS_SSL_PROTO_TLS1_2 &&
MBEDTLS_KEY_EXCHANGE_WITH_CERT_ENABLED */
MBEDTLS_SSL_DEBUG_MSG( 2, ( "=> parse client hello" ) );
#if defined(MBEDTLS_SSL_DTLS_ANTI_REPLAY)
read_record_header:
#endif
/*
* If renegotiating, then the input was read with mbedtls_ssl_read_record(),
* otherwise read it ourselves manually in order to support SSLv2
* ClientHello, which doesn't use the same record layer format.
*/
#if defined(MBEDTLS_SSL_RENEGOTIATION)
if( ssl->renego_status == MBEDTLS_SSL_INITIAL_HANDSHAKE )
#endif
{
if( ( ret = mbedtls_ssl_fetch_input( ssl, 5 ) ) != 0 )
{
/* No alert on a read error. */
MBEDTLS_SSL_DEBUG_RET( 1, "mbedtls_ssl_fetch_input", ret );
return( ret );
}
}
buf = ssl->in_hdr;
#if defined(MBEDTLS_SSL_SRV_SUPPORT_SSLV2_CLIENT_HELLO)
#if defined(MBEDTLS_SSL_PROTO_DTLS)
if( ssl->conf->transport == MBEDTLS_SSL_TRANSPORT_STREAM )
#endif
if( ( buf[0] & 0x80 ) != 0 )
return( ssl_parse_client_hello_v2( ssl ) );
#endif
MBEDTLS_SSL_DEBUG_BUF( 4, "record header", buf, mbedtls_ssl_in_hdr_len( ssl ) );
/*
* SSLv3/TLS Client Hello
*
* Record layer:
* 0 . 0 message type
* 1 . 2 protocol version
* 3 . 11 DTLS: epoch + record sequence number
* 3 . 4 message length
*/
MBEDTLS_SSL_DEBUG_MSG( 3, ( "client hello v3, message type: %d",
buf[0] ) );
if( buf[0] != MBEDTLS_SSL_MSG_HANDSHAKE )
{
MBEDTLS_SSL_DEBUG_MSG( 1, ( "bad client hello message" ) );
return( MBEDTLS_ERR_SSL_BAD_HS_CLIENT_HELLO );
}
MBEDTLS_SSL_DEBUG_MSG( 3, ( "client hello v3, message len.: %d",
( ssl->in_len[0] << 8 ) | ssl->in_len[1] ) );
MBEDTLS_SSL_DEBUG_MSG( 3, ( "client hello v3, protocol version: [%d:%d]",
buf[1], buf[2] ) );
mbedtls_ssl_read_version( &major, &minor, ssl->conf->transport, buf + 1 );
/* According to RFC 5246 Appendix E.1, the version here is typically
* "{03,00}, the lowest version number supported by the client, [or] the
* value of ClientHello.client_version", so the only meaningful check here
* is the major version shouldn't be less than 3 */
if( major < MBEDTLS_SSL_MAJOR_VERSION_3 )
{
MBEDTLS_SSL_DEBUG_MSG( 1, ( "bad client hello message" ) );
return( MBEDTLS_ERR_SSL_BAD_HS_CLIENT_HELLO );
}
/* For DTLS if this is the initial handshake, remember the client sequence
* number to use it in our next message (RFC 6347 4.2.1) */
#if defined(MBEDTLS_SSL_PROTO_DTLS)
if( ssl->conf->transport == MBEDTLS_SSL_TRANSPORT_DATAGRAM
#if defined(MBEDTLS_SSL_RENEGOTIATION)
&& ssl->renego_status == MBEDTLS_SSL_INITIAL_HANDSHAKE
#endif
)
{
/* Epoch should be 0 for initial handshakes */
if( ssl->in_ctr[0] != 0 || ssl->in_ctr[1] != 0 )
{
MBEDTLS_SSL_DEBUG_MSG( 1, ( "bad client hello message" ) );
return( MBEDTLS_ERR_SSL_BAD_HS_CLIENT_HELLO );
}
memcpy( ssl->cur_out_ctr + 2, ssl->in_ctr + 2, 6 );
#if defined(MBEDTLS_SSL_DTLS_ANTI_REPLAY)
if( mbedtls_ssl_dtls_replay_check( ssl ) != 0 )
{
MBEDTLS_SSL_DEBUG_MSG( 1, ( "replayed record, discarding" ) );
ssl->next_record_offset = 0;
ssl->in_left = 0;
goto read_record_header;
}
/* No MAC to check yet, so we can update right now */
mbedtls_ssl_dtls_replay_update( ssl );
#endif
}
#endif /* MBEDTLS_SSL_PROTO_DTLS */
msg_len = ( ssl->in_len[0] << 8 ) | ssl->in_len[1];
#if defined(MBEDTLS_SSL_RENEGOTIATION)
if( ssl->renego_status != MBEDTLS_SSL_INITIAL_HANDSHAKE )
{
/* Set by mbedtls_ssl_read_record() */
msg_len = ssl->in_hslen;
}
else
#endif
{
if( msg_len > MBEDTLS_SSL_IN_CONTENT_LEN )
{
MBEDTLS_SSL_DEBUG_MSG( 1, ( "bad client hello message" ) );
return( MBEDTLS_ERR_SSL_BAD_HS_CLIENT_HELLO );
}
if( ( ret = mbedtls_ssl_fetch_input( ssl,
mbedtls_ssl_in_hdr_len( ssl ) + msg_len ) ) != 0 )
{
MBEDTLS_SSL_DEBUG_RET( 1, "mbedtls_ssl_fetch_input", ret );
return( ret );
}
/* Done reading this record, get ready for the next one */
#if defined(MBEDTLS_SSL_PROTO_DTLS)
if( ssl->conf->transport == MBEDTLS_SSL_TRANSPORT_DATAGRAM )
ssl->next_record_offset = msg_len + mbedtls_ssl_in_hdr_len( ssl );
else
#endif
ssl->in_left = 0;
}
buf = ssl->in_msg;
MBEDTLS_SSL_DEBUG_BUF( 4, "record contents", buf, msg_len );
ssl->handshake->update_checksum( ssl, buf, msg_len );
/*
* Handshake layer:
* 0 . 0 handshake type
* 1 . 3 handshake length
* 4 . 5 DTLS only: message seqence number
* 6 . 8 DTLS only: fragment offset
* 9 . 11 DTLS only: fragment length
*/
if( msg_len < mbedtls_ssl_hs_hdr_len( ssl ) )
{
MBEDTLS_SSL_DEBUG_MSG( 1, ( "bad client hello message" ) );
return( MBEDTLS_ERR_SSL_BAD_HS_CLIENT_HELLO );
}
MBEDTLS_SSL_DEBUG_MSG( 3, ( "client hello v3, handshake type: %d", buf[0] ) );
if( buf[0] != MBEDTLS_SSL_HS_CLIENT_HELLO )
{
MBEDTLS_SSL_DEBUG_MSG( 1, ( "bad client hello message" ) );
return( MBEDTLS_ERR_SSL_BAD_HS_CLIENT_HELLO );
}
MBEDTLS_SSL_DEBUG_MSG( 3, ( "client hello v3, handshake len.: %d",
( buf[1] << 16 ) | ( buf[2] << 8 ) | buf[3] ) );
/* We don't support fragmentation of ClientHello (yet?) */
if( buf[1] != 0 ||
msg_len != mbedtls_ssl_hs_hdr_len( ssl ) + ( ( buf[2] << 8 ) | buf[3] ) )
{
MBEDTLS_SSL_DEBUG_MSG( 1, ( "bad client hello message" ) );
return( MBEDTLS_ERR_SSL_BAD_HS_CLIENT_HELLO );
}
#if defined(MBEDTLS_SSL_PROTO_DTLS)
if( ssl->conf->transport == MBEDTLS_SSL_TRANSPORT_DATAGRAM )
{
/*
* Copy the client's handshake message_seq on initial handshakes,
* check sequence number on renego.
*/
#if defined(MBEDTLS_SSL_RENEGOTIATION)
if( ssl->renego_status == MBEDTLS_SSL_RENEGOTIATION_IN_PROGRESS )
{
/* This couldn't be done in ssl_prepare_handshake_record() */
unsigned int cli_msg_seq = ( ssl->in_msg[4] << 8 ) |
ssl->in_msg[5];
if( cli_msg_seq != ssl->handshake->in_msg_seq )
{
MBEDTLS_SSL_DEBUG_MSG( 1, ( "bad client hello message_seq: "
"%u (expected %u)", cli_msg_seq,
ssl->handshake->in_msg_seq ) );
return( MBEDTLS_ERR_SSL_BAD_HS_CLIENT_HELLO );
}
ssl->handshake->in_msg_seq++;
}
else
#endif
{
unsigned int cli_msg_seq = ( ssl->in_msg[4] << 8 ) |
ssl->in_msg[5];
ssl->handshake->out_msg_seq = cli_msg_seq;
ssl->handshake->in_msg_seq = cli_msg_seq + 1;
}
/*
* For now we don't support fragmentation, so make sure
* fragment_offset == 0 and fragment_length == length
*/
if( ssl->in_msg[6] != 0 || ssl->in_msg[7] != 0 || ssl->in_msg[8] != 0 ||
memcmp( ssl->in_msg + 1, ssl->in_msg + 9, 3 ) != 0 )
{
MBEDTLS_SSL_DEBUG_MSG( 1, ( "ClientHello fragmentation not supported" ) );
return( MBEDTLS_ERR_SSL_FEATURE_UNAVAILABLE );
}
}
#endif /* MBEDTLS_SSL_PROTO_DTLS */
buf += mbedtls_ssl_hs_hdr_len( ssl );
msg_len -= mbedtls_ssl_hs_hdr_len( ssl );
/*
* ClientHello layer:
* 0 . 1 protocol version
* 2 . 33 random bytes (starting with 4 bytes of Unix time)
* 34 . 35 session id length (1 byte)
* 35 . 34+x session id
* 35+x . 35+x DTLS only: cookie length (1 byte)
* 36+x . .. DTLS only: cookie
* .. . .. ciphersuite list length (2 bytes)
* .. . .. ciphersuite list
* .. . .. compression alg. list length (1 byte)
* .. . .. compression alg. list
* .. . .. extensions length (2 bytes, optional)
* .. . .. extensions (optional)
*/
/*
* Minimal length (with everything empty and extensions omitted) is
* 2 + 32 + 1 + 2 + 1 = 38 bytes. Check that first, so that we can
* read at least up to session id length without worrying.
*/
if( msg_len < 38 )
{
MBEDTLS_SSL_DEBUG_MSG( 1, ( "bad client hello message" ) );
return( MBEDTLS_ERR_SSL_BAD_HS_CLIENT_HELLO );
}
/*
* Check and save the protocol version
*/
MBEDTLS_SSL_DEBUG_BUF( 3, "client hello, version", buf, 2 );
mbedtls_ssl_read_version( &ssl->major_ver, &ssl->minor_ver,
ssl->conf->transport, buf );
ssl->handshake->max_major_ver = ssl->major_ver;
ssl->handshake->max_minor_ver = ssl->minor_ver;
if( ssl->major_ver < ssl->conf->min_major_ver ||
ssl->minor_ver < ssl->conf->min_minor_ver )
{
MBEDTLS_SSL_DEBUG_MSG( 1, ( "client only supports ssl smaller than minimum"
" [%d:%d] < [%d:%d]",
ssl->major_ver, ssl->minor_ver,
ssl->conf->min_major_ver, ssl->conf->min_minor_ver ) );
mbedtls_ssl_send_alert_message( ssl, MBEDTLS_SSL_ALERT_LEVEL_FATAL,
MBEDTLS_SSL_ALERT_MSG_PROTOCOL_VERSION );
return( MBEDTLS_ERR_SSL_BAD_HS_PROTOCOL_VERSION );
}
if( ssl->major_ver > ssl->conf->max_major_ver )
{
ssl->major_ver = ssl->conf->max_major_ver;
ssl->minor_ver = ssl->conf->max_minor_ver;
}
else if( ssl->minor_ver > ssl->conf->max_minor_ver )
ssl->minor_ver = ssl->conf->max_minor_ver;
/*
* Save client random (inc. Unix time)
*/
MBEDTLS_SSL_DEBUG_BUF( 3, "client hello, random bytes", buf + 2, 32 );
memcpy( ssl->handshake->randbytes, buf + 2, 32 );
/*
* Check the session ID length and save session ID
*/
sess_len = buf[34];
if( sess_len > sizeof( ssl->session_negotiate->id ) ||
sess_len + 34 + 2 > msg_len ) /* 2 for cipherlist length field */
{
MBEDTLS_SSL_DEBUG_MSG( 1, ( "bad client hello message" ) );
mbedtls_ssl_send_alert_message( ssl, MBEDTLS_SSL_ALERT_LEVEL_FATAL,
MBEDTLS_SSL_ALERT_MSG_DECODE_ERROR );
return( MBEDTLS_ERR_SSL_BAD_HS_CLIENT_HELLO );
}
MBEDTLS_SSL_DEBUG_BUF( 3, "client hello, session id", buf + 35, sess_len );
ssl->session_negotiate->id_len = sess_len;
memset( ssl->session_negotiate->id, 0,
sizeof( ssl->session_negotiate->id ) );
memcpy( ssl->session_negotiate->id, buf + 35,
ssl->session_negotiate->id_len );
/*
* Check the cookie length and content
*/
#if defined(MBEDTLS_SSL_PROTO_DTLS)
if( ssl->conf->transport == MBEDTLS_SSL_TRANSPORT_DATAGRAM )
{
cookie_offset = 35 + sess_len;
cookie_len = buf[cookie_offset];
if( cookie_offset + 1 + cookie_len + 2 > msg_len )
{
MBEDTLS_SSL_DEBUG_MSG( 1, ( "bad client hello message" ) );
mbedtls_ssl_send_alert_message( ssl, MBEDTLS_SSL_ALERT_LEVEL_FATAL,
MBEDTLS_SSL_ALERT_MSG_PROTOCOL_VERSION );
return( MBEDTLS_ERR_SSL_BAD_HS_CLIENT_HELLO );
}
MBEDTLS_SSL_DEBUG_BUF( 3, "client hello, cookie",
buf + cookie_offset + 1, cookie_len );
#if defined(MBEDTLS_SSL_DTLS_HELLO_VERIFY)
if( ssl->conf->f_cookie_check != NULL
#if defined(MBEDTLS_SSL_RENEGOTIATION)
&& ssl->renego_status == MBEDTLS_SSL_INITIAL_HANDSHAKE
#endif
)
{
if( ssl->conf->f_cookie_check( ssl->conf->p_cookie,
buf + cookie_offset + 1, cookie_len,
ssl->cli_id, ssl->cli_id_len ) != 0 )
{
MBEDTLS_SSL_DEBUG_MSG( 2, ( "cookie verification failed" ) );
ssl->handshake->verify_cookie_len = 1;
}
else
{
MBEDTLS_SSL_DEBUG_MSG( 2, ( "cookie verification passed" ) );
ssl->handshake->verify_cookie_len = 0;
}
}
else
#endif /* MBEDTLS_SSL_DTLS_HELLO_VERIFY */
{
/* We know we didn't send a cookie, so it should be empty */
if( cookie_len != 0 )
{
/* This may be an attacker's probe, so don't send an alert */
MBEDTLS_SSL_DEBUG_MSG( 1, ( "bad client hello message" ) );
return( MBEDTLS_ERR_SSL_BAD_HS_CLIENT_HELLO );
}
MBEDTLS_SSL_DEBUG_MSG( 2, ( "cookie verification skipped" ) );
}
/*
* Check the ciphersuitelist length (will be parsed later)
*/
ciph_offset = cookie_offset + 1 + cookie_len;
}
else
#endif /* MBEDTLS_SSL_PROTO_DTLS */
ciph_offset = 35 + sess_len;
ciph_len = ( buf[ciph_offset + 0] << 8 )
| ( buf[ciph_offset + 1] );
if( ciph_len < 2 ||
ciph_len + 2 + ciph_offset + 1 > msg_len || /* 1 for comp. alg. len */
( ciph_len % 2 ) != 0 )
{
MBEDTLS_SSL_DEBUG_MSG( 1, ( "bad client hello message" ) );
mbedtls_ssl_send_alert_message( ssl, MBEDTLS_SSL_ALERT_LEVEL_FATAL,
MBEDTLS_SSL_ALERT_MSG_DECODE_ERROR );
return( MBEDTLS_ERR_SSL_BAD_HS_CLIENT_HELLO );
}
MBEDTLS_SSL_DEBUG_BUF( 3, "client hello, ciphersuitelist",
buf + ciph_offset + 2, ciph_len );
/*
* Check the compression algorithms length and pick one
*/
comp_offset = ciph_offset + 2 + ciph_len;
comp_len = buf[comp_offset];
if( comp_len < 1 ||
comp_len > 16 ||
comp_len + comp_offset + 1 > msg_len )
{
MBEDTLS_SSL_DEBUG_MSG( 1, ( "bad client hello message" ) );
mbedtls_ssl_send_alert_message( ssl, MBEDTLS_SSL_ALERT_LEVEL_FATAL,
MBEDTLS_SSL_ALERT_MSG_DECODE_ERROR );
return( MBEDTLS_ERR_SSL_BAD_HS_CLIENT_HELLO );
}
MBEDTLS_SSL_DEBUG_BUF( 3, "client hello, compression",
buf + comp_offset + 1, comp_len );
ssl->session_negotiate->compression = MBEDTLS_SSL_COMPRESS_NULL;
#if defined(MBEDTLS_ZLIB_SUPPORT)
for( i = 0; i < comp_len; ++i )
{
if( buf[comp_offset + 1 + i] == MBEDTLS_SSL_COMPRESS_DEFLATE )
{
ssl->session_negotiate->compression = MBEDTLS_SSL_COMPRESS_DEFLATE;
break;
}
}
#endif
/* See comments in ssl_write_client_hello() */
#if defined(MBEDTLS_SSL_PROTO_DTLS)
if( ssl->conf->transport == MBEDTLS_SSL_TRANSPORT_DATAGRAM )
ssl->session_negotiate->compression = MBEDTLS_SSL_COMPRESS_NULL;
#endif
/* Do not parse the extensions if the protocol is SSLv3 */
#if defined(MBEDTLS_SSL_PROTO_SSL3)
if( ( ssl->major_ver != 3 ) || ( ssl->minor_ver != 0 ) )
{
#endif
/*
* Check the extension length
*/
ext_offset = comp_offset + 1 + comp_len;
if( msg_len > ext_offset )
{
if( msg_len < ext_offset + 2 )
{
MBEDTLS_SSL_DEBUG_MSG( 1, ( "bad client hello message" ) );
mbedtls_ssl_send_alert_message( ssl, MBEDTLS_SSL_ALERT_LEVEL_FATAL,
MBEDTLS_SSL_ALERT_MSG_DECODE_ERROR );
return( MBEDTLS_ERR_SSL_BAD_HS_CLIENT_HELLO );
}
ext_len = ( buf[ext_offset + 0] << 8 )
| ( buf[ext_offset + 1] );
if( msg_len != ext_offset + 2 + ext_len )
{
MBEDTLS_SSL_DEBUG_MSG( 1, ( "bad client hello message" ) );
mbedtls_ssl_send_alert_message( ssl, MBEDTLS_SSL_ALERT_LEVEL_FATAL,
MBEDTLS_SSL_ALERT_MSG_DECODE_ERROR );
return( MBEDTLS_ERR_SSL_BAD_HS_CLIENT_HELLO );
}
}
else
ext_len = 0;
ext = buf + ext_offset + 2;
MBEDTLS_SSL_DEBUG_BUF( 3, "client hello extensions", ext, ext_len );
while( ext_len != 0 )
{
unsigned int ext_id;
unsigned int ext_size;
if ( ext_len < 4 ) {
MBEDTLS_SSL_DEBUG_MSG( 1, ( "bad client hello message" ) );
mbedtls_ssl_send_alert_message( ssl, MBEDTLS_SSL_ALERT_LEVEL_FATAL,
MBEDTLS_SSL_ALERT_MSG_DECODE_ERROR );
return( MBEDTLS_ERR_SSL_BAD_HS_CLIENT_HELLO );
}
ext_id = ( ( ext[0] << 8 ) | ( ext[1] ) );
ext_size = ( ( ext[2] << 8 ) | ( ext[3] ) );
if( ext_size + 4 > ext_len )
{
MBEDTLS_SSL_DEBUG_MSG( 1, ( "bad client hello message" ) );
mbedtls_ssl_send_alert_message( ssl, MBEDTLS_SSL_ALERT_LEVEL_FATAL,
MBEDTLS_SSL_ALERT_MSG_DECODE_ERROR );
return( MBEDTLS_ERR_SSL_BAD_HS_CLIENT_HELLO );
}
switch( ext_id )
{
#if defined(MBEDTLS_SSL_SERVER_NAME_INDICATION)
case MBEDTLS_TLS_EXT_SERVERNAME:
MBEDTLS_SSL_DEBUG_MSG( 3, ( "found ServerName extension" ) );
if( ssl->conf->f_sni == NULL )
break;
ret = ssl_parse_servername_ext( ssl, ext + 4, ext_size );
if( ret != 0 )
return( ret );
break;
#endif /* MBEDTLS_SSL_SERVER_NAME_INDICATION */
case MBEDTLS_TLS_EXT_RENEGOTIATION_INFO:
MBEDTLS_SSL_DEBUG_MSG( 3, ( "found renegotiation extension" ) );
#if defined(MBEDTLS_SSL_RENEGOTIATION)
renegotiation_info_seen = 1;
#endif
ret = ssl_parse_renegotiation_info( ssl, ext + 4, ext_size );
if( ret != 0 )
return( ret );
break;
#if defined(MBEDTLS_SSL_PROTO_TLS1_2) && \
defined(MBEDTLS_KEY_EXCHANGE_WITH_CERT_ENABLED)
case MBEDTLS_TLS_EXT_SIG_ALG:
MBEDTLS_SSL_DEBUG_MSG( 3, ( "found signature_algorithms extension" ) );
ret = ssl_parse_signature_algorithms_ext( ssl, ext + 4, ext_size );
if( ret != 0 )
return( ret );
sig_hash_alg_ext_present = 1;
break;
#endif /* MBEDTLS_SSL_PROTO_TLS1_2 &&
MBEDTLS_KEY_EXCHANGE_WITH_CERT_ENABLED */
#if defined(MBEDTLS_ECDH_C) || defined(MBEDTLS_ECDSA_C) || \
defined(MBEDTLS_KEY_EXCHANGE_ECJPAKE_ENABLED)
case MBEDTLS_TLS_EXT_SUPPORTED_ELLIPTIC_CURVES:
MBEDTLS_SSL_DEBUG_MSG( 3, ( "found supported elliptic curves extension" ) );
ret = ssl_parse_supported_elliptic_curves( ssl, ext + 4, ext_size );
if( ret != 0 )
return( ret );
break;
case MBEDTLS_TLS_EXT_SUPPORTED_POINT_FORMATS:
MBEDTLS_SSL_DEBUG_MSG( 3, ( "found supported point formats extension" ) );
ssl->handshake->cli_exts |= MBEDTLS_TLS_EXT_SUPPORTED_POINT_FORMATS_PRESENT;
ret = ssl_parse_supported_point_formats( ssl, ext + 4, ext_size );
if( ret != 0 )
return( ret );
break;
#endif /* MBEDTLS_ECDH_C || MBEDTLS_ECDSA_C ||
MBEDTLS_KEY_EXCHANGE_ECJPAKE_ENABLED */
#if defined(MBEDTLS_KEY_EXCHANGE_ECJPAKE_ENABLED)
case MBEDTLS_TLS_EXT_ECJPAKE_KKPP:
MBEDTLS_SSL_DEBUG_MSG( 3, ( "found ecjpake kkpp extension" ) );
ret = ssl_parse_ecjpake_kkpp( ssl, ext + 4, ext_size );
if( ret != 0 )
return( ret );
break;
#endif /* MBEDTLS_KEY_EXCHANGE_ECJPAKE_ENABLED */
#if defined(MBEDTLS_SSL_MAX_FRAGMENT_LENGTH)
case MBEDTLS_TLS_EXT_MAX_FRAGMENT_LENGTH:
MBEDTLS_SSL_DEBUG_MSG( 3, ( "found max fragment length extension" ) );
ret = ssl_parse_max_fragment_length_ext( ssl, ext + 4, ext_size );
if( ret != 0 )
return( ret );
break;
#endif /* MBEDTLS_SSL_MAX_FRAGMENT_LENGTH */
#if defined(MBEDTLS_SSL_TRUNCATED_HMAC)
case MBEDTLS_TLS_EXT_TRUNCATED_HMAC:
MBEDTLS_SSL_DEBUG_MSG( 3, ( "found truncated hmac extension" ) );
ret = ssl_parse_truncated_hmac_ext( ssl, ext + 4, ext_size );
if( ret != 0 )
return( ret );
break;
#endif /* MBEDTLS_SSL_TRUNCATED_HMAC */
#if defined(MBEDTLS_SSL_DTLS_CONNECTION_ID)
case MBEDTLS_TLS_EXT_CID:
MBEDTLS_SSL_DEBUG_MSG( 3, ( "found CID extension" ) );
ret = ssl_parse_cid_ext( ssl, ext + 4, ext_size );
if( ret != 0 )
return( ret );
break;
#endif /* MBEDTLS_SSL_TRUNCATED_HMAC */
#if defined(MBEDTLS_SSL_ENCRYPT_THEN_MAC)
case MBEDTLS_TLS_EXT_ENCRYPT_THEN_MAC:
MBEDTLS_SSL_DEBUG_MSG( 3, ( "found encrypt then mac extension" ) );
ret = ssl_parse_encrypt_then_mac_ext( ssl, ext + 4, ext_size );
if( ret != 0 )
return( ret );
break;
#endif /* MBEDTLS_SSL_ENCRYPT_THEN_MAC */
#if defined(MBEDTLS_SSL_EXTENDED_MASTER_SECRET)
case MBEDTLS_TLS_EXT_EXTENDED_MASTER_SECRET:
MBEDTLS_SSL_DEBUG_MSG( 3, ( "found extended master secret extension" ) );
ret = ssl_parse_extended_ms_ext( ssl, ext + 4, ext_size );
if( ret != 0 )
return( ret );
break;
#endif /* MBEDTLS_SSL_EXTENDED_MASTER_SECRET */
#if defined(MBEDTLS_SSL_SESSION_TICKETS)
case MBEDTLS_TLS_EXT_SESSION_TICKET:
MBEDTLS_SSL_DEBUG_MSG( 3, ( "found session ticket extension" ) );
ret = ssl_parse_session_ticket_ext( ssl, ext + 4, ext_size );
if( ret != 0 )
return( ret );
break;
#endif /* MBEDTLS_SSL_SESSION_TICKETS */
#if defined(MBEDTLS_SSL_ALPN)
case MBEDTLS_TLS_EXT_ALPN:
MBEDTLS_SSL_DEBUG_MSG( 3, ( "found alpn extension" ) );
ret = ssl_parse_alpn_ext( ssl, ext + 4, ext_size );
if( ret != 0 )
return( ret );
break;
#endif /* MBEDTLS_SSL_SESSION_TICKETS */
#if defined(MBEDTLS_SSL_DTLS_SRTP)
case MBEDTLS_TLS_EXT_USE_SRTP:
MBEDTLS_SSL_DEBUG_MSG( 3, ( "found use_srtp extension" ) );
ret = ssl_parse_use_srtp_ext( ssl, ext + 4, ext_size );
if( ret != 0 )
return( ret );
break;
#endif /* MBEDTLS_SSL_DTLS_SRTP */
default:
MBEDTLS_SSL_DEBUG_MSG( 3, ( "unknown extension found: %u (ignoring)",
ext_id ) );
}
ext_len -= 4 + ext_size;
ext += 4 + ext_size;
}
#if defined(MBEDTLS_SSL_PROTO_SSL3)
}
#endif
#if defined(MBEDTLS_SSL_FALLBACK_SCSV)
for( i = 0, p = buf + ciph_offset + 2; i < ciph_len; i += 2, p += 2 )
{
if( p[0] == (unsigned char)( ( MBEDTLS_SSL_FALLBACK_SCSV_VALUE >> 8 ) & 0xff ) &&
p[1] == (unsigned char)( ( MBEDTLS_SSL_FALLBACK_SCSV_VALUE ) & 0xff ) )
{
MBEDTLS_SSL_DEBUG_MSG( 2, ( "received FALLBACK_SCSV" ) );
if( ssl->minor_ver < ssl->conf->max_minor_ver )
{
MBEDTLS_SSL_DEBUG_MSG( 1, ( "inapropriate fallback" ) );
mbedtls_ssl_send_alert_message( ssl, MBEDTLS_SSL_ALERT_LEVEL_FATAL,
MBEDTLS_SSL_ALERT_MSG_INAPROPRIATE_FALLBACK );
return( MBEDTLS_ERR_SSL_BAD_HS_CLIENT_HELLO );
}
break;
}
}
#endif /* MBEDTLS_SSL_FALLBACK_SCSV */
#if defined(MBEDTLS_SSL_PROTO_TLS1_2) && \
defined(MBEDTLS_KEY_EXCHANGE_WITH_CERT_ENABLED)
/*
* Try to fall back to default hash SHA1 if the client
* hasn't provided any preferred signature-hash combinations.
*/
if( sig_hash_alg_ext_present == 0 )
{
mbedtls_md_type_t md_default = MBEDTLS_MD_SHA1;
if( mbedtls_ssl_check_sig_hash( ssl, md_default ) != 0 )
md_default = MBEDTLS_MD_NONE;
mbedtls_ssl_sig_hash_set_const_hash( &ssl->handshake->hash_algs, md_default );
}
#endif /* MBEDTLS_SSL_PROTO_TLS1_2 &&
MBEDTLS_KEY_EXCHANGE_WITH_CERT_ENABLED */
/*
* Check for TLS_EMPTY_RENEGOTIATION_INFO_SCSV
*/
for( i = 0, p = buf + ciph_offset + 2; i < ciph_len; i += 2, p += 2 )
{
if( p[0] == 0 && p[1] == MBEDTLS_SSL_EMPTY_RENEGOTIATION_INFO )
{
MBEDTLS_SSL_DEBUG_MSG( 3, ( "received TLS_EMPTY_RENEGOTIATION_INFO " ) );
#if defined(MBEDTLS_SSL_RENEGOTIATION)
if( ssl->renego_status == MBEDTLS_SSL_RENEGOTIATION_IN_PROGRESS )
{
MBEDTLS_SSL_DEBUG_MSG( 1, ( "received RENEGOTIATION SCSV "
"during renegotiation" ) );
mbedtls_ssl_send_alert_message( ssl, MBEDTLS_SSL_ALERT_LEVEL_FATAL,
MBEDTLS_SSL_ALERT_MSG_HANDSHAKE_FAILURE );
return( MBEDTLS_ERR_SSL_BAD_HS_CLIENT_HELLO );
}
#endif
ssl->secure_renegotiation = MBEDTLS_SSL_SECURE_RENEGOTIATION;
break;
}
}
/*
* Renegotiation security checks
*/
if( ssl->secure_renegotiation != MBEDTLS_SSL_SECURE_RENEGOTIATION &&
ssl->conf->allow_legacy_renegotiation == MBEDTLS_SSL_LEGACY_BREAK_HANDSHAKE )
{
MBEDTLS_SSL_DEBUG_MSG( 1, ( "legacy renegotiation, breaking off handshake" ) );
handshake_failure = 1;
}
#if defined(MBEDTLS_SSL_RENEGOTIATION)
else if( ssl->renego_status == MBEDTLS_SSL_RENEGOTIATION_IN_PROGRESS &&
ssl->secure_renegotiation == MBEDTLS_SSL_SECURE_RENEGOTIATION &&
renegotiation_info_seen == 0 )
{
MBEDTLS_SSL_DEBUG_MSG( 1, ( "renegotiation_info extension missing (secure)" ) );
handshake_failure = 1;
}
else if( ssl->renego_status == MBEDTLS_SSL_RENEGOTIATION_IN_PROGRESS &&
ssl->secure_renegotiation == MBEDTLS_SSL_LEGACY_RENEGOTIATION &&
ssl->conf->allow_legacy_renegotiation == MBEDTLS_SSL_LEGACY_NO_RENEGOTIATION )
{
MBEDTLS_SSL_DEBUG_MSG( 1, ( "legacy renegotiation not allowed" ) );
handshake_failure = 1;
}
else if( ssl->renego_status == MBEDTLS_SSL_RENEGOTIATION_IN_PROGRESS &&
ssl->secure_renegotiation == MBEDTLS_SSL_LEGACY_RENEGOTIATION &&
renegotiation_info_seen == 1 )
{
MBEDTLS_SSL_DEBUG_MSG( 1, ( "renegotiation_info extension present (legacy)" ) );
handshake_failure = 1;
}
#endif /* MBEDTLS_SSL_RENEGOTIATION */
if( handshake_failure == 1 )
{
mbedtls_ssl_send_alert_message( ssl, MBEDTLS_SSL_ALERT_LEVEL_FATAL,
MBEDTLS_SSL_ALERT_MSG_HANDSHAKE_FAILURE );
return( MBEDTLS_ERR_SSL_BAD_HS_CLIENT_HELLO );
}
/*
* Search for a matching ciphersuite
* (At the end because we need information from the EC-based extensions
* and certificate from the SNI callback triggered by the SNI extension.)
*/
got_common_suite = 0;
ciphersuites = ssl->conf->ciphersuite_list[ssl->minor_ver];
ciphersuite_info = NULL;
#if defined(MBEDTLS_SSL_SRV_RESPECT_CLIENT_PREFERENCE)
for( j = 0, p = buf + ciph_offset + 2; j < ciph_len; j += 2, p += 2 )
for( i = 0; ciphersuites[i] != 0; i++ )
#else
for( i = 0; ciphersuites[i] != 0; i++ )
for( j = 0, p = buf + ciph_offset + 2; j < ciph_len; j += 2, p += 2 )
#endif
{
if( p[0] != ( ( ciphersuites[i] >> 8 ) & 0xFF ) ||
p[1] != ( ( ciphersuites[i] ) & 0xFF ) )
continue;
got_common_suite = 1;
if( ( ret = ssl_ciphersuite_match( ssl, ciphersuites[i],
&ciphersuite_info ) ) != 0 )
return( ret );
if( ciphersuite_info != NULL )
goto have_ciphersuite;
}
if( got_common_suite )
{
MBEDTLS_SSL_DEBUG_MSG( 1, ( "got ciphersuites in common, "
"but none of them usable" ) );
mbedtls_ssl_send_alert_message( ssl, MBEDTLS_SSL_ALERT_LEVEL_FATAL,
MBEDTLS_SSL_ALERT_MSG_HANDSHAKE_FAILURE );
return( MBEDTLS_ERR_SSL_NO_USABLE_CIPHERSUITE );
}
else
{
MBEDTLS_SSL_DEBUG_MSG( 1, ( "got no ciphersuites in common" ) );
mbedtls_ssl_send_alert_message( ssl, MBEDTLS_SSL_ALERT_LEVEL_FATAL,
MBEDTLS_SSL_ALERT_MSG_HANDSHAKE_FAILURE );
return( MBEDTLS_ERR_SSL_NO_CIPHER_CHOSEN );
}
have_ciphersuite:
MBEDTLS_SSL_DEBUG_MSG( 2, ( "selected ciphersuite: %s", ciphersuite_info->name ) );
ssl->session_negotiate->ciphersuite = ciphersuites[i];
ssl->handshake->ciphersuite_info = ciphersuite_info;
ssl->state++;
#if defined(MBEDTLS_SSL_PROTO_DTLS)
if( ssl->conf->transport == MBEDTLS_SSL_TRANSPORT_DATAGRAM )
mbedtls_ssl_recv_flight_completed( ssl );
#endif
/* Debugging-only output for testsuite */
#if defined(MBEDTLS_DEBUG_C) && \
defined(MBEDTLS_SSL_PROTO_TLS1_2) && \
defined(MBEDTLS_KEY_EXCHANGE_WITH_CERT_ENABLED)
if( ssl->minor_ver == MBEDTLS_SSL_MINOR_VERSION_3 )
{
mbedtls_pk_type_t sig_alg = mbedtls_ssl_get_ciphersuite_sig_alg( ciphersuite_info );
if( sig_alg != MBEDTLS_PK_NONE )
{
mbedtls_md_type_t md_alg = mbedtls_ssl_sig_hash_set_find( &ssl->handshake->hash_algs,
sig_alg );
MBEDTLS_SSL_DEBUG_MSG( 3, ( "client hello v3, signature_algorithm ext: %d",
mbedtls_ssl_hash_from_md_alg( md_alg ) ) );
}
else
{
MBEDTLS_SSL_DEBUG_MSG( 3, ( "no hash algorithm for signature algorithm "
"%u - should not happen", (unsigned) sig_alg ) );
}
}
#endif
MBEDTLS_SSL_DEBUG_MSG( 2, ( "<= parse client hello" ) );
return( 0 );
}
#if defined(MBEDTLS_SSL_TRUNCATED_HMAC)
static void ssl_write_truncated_hmac_ext( mbedtls_ssl_context *ssl,
unsigned char *buf,
size_t *olen )
{
unsigned char *p = buf;
if( ssl->session_negotiate->trunc_hmac == MBEDTLS_SSL_TRUNC_HMAC_DISABLED )
{
*olen = 0;
return;
}
MBEDTLS_SSL_DEBUG_MSG( 3, ( "server hello, adding truncated hmac extension" ) );
*p++ = (unsigned char)( ( MBEDTLS_TLS_EXT_TRUNCATED_HMAC >> 8 ) & 0xFF );
*p++ = (unsigned char)( ( MBEDTLS_TLS_EXT_TRUNCATED_HMAC ) & 0xFF );
*p++ = 0x00;
*p++ = 0x00;
*olen = 4;
}
#endif /* MBEDTLS_SSL_TRUNCATED_HMAC */
#if defined(MBEDTLS_SSL_DTLS_CONNECTION_ID)
static void ssl_write_cid_ext( mbedtls_ssl_context *ssl,
unsigned char *buf,
size_t *olen )
{
unsigned char *p = buf;
size_t ext_len;
const unsigned char *end = ssl->out_msg + MBEDTLS_SSL_OUT_CONTENT_LEN;
*olen = 0;
/* Skip writing the extension if we don't want to use it or if
* the client hasn't offered it. */
if( ssl->handshake->cid_in_use == MBEDTLS_SSL_CID_DISABLED )
return;
/* ssl->own_cid_len is at most MBEDTLS_SSL_CID_IN_LEN_MAX
* which is at most 255, so the increment cannot overflow. */
if( end < p || (size_t)( end - p ) < (unsigned)( ssl->own_cid_len + 5 ) )
{
MBEDTLS_SSL_DEBUG_MSG( 1, ( "buffer too small" ) );
return;
}
MBEDTLS_SSL_DEBUG_MSG( 3, ( "server hello, adding CID extension" ) );
/*
* Quoting draft-ietf-tls-dtls-connection-id-05
* https://tools.ietf.org/html/draft-ietf-tls-dtls-connection-id-05
*
* struct {
* opaque cid<0..2^8-1>;
* } ConnectionId;
*/
*p++ = (unsigned char)( ( MBEDTLS_TLS_EXT_CID >> 8 ) & 0xFF );
*p++ = (unsigned char)( ( MBEDTLS_TLS_EXT_CID ) & 0xFF );
ext_len = (size_t) ssl->own_cid_len + 1;
*p++ = (unsigned char)( ( ext_len >> 8 ) & 0xFF );
*p++ = (unsigned char)( ( ext_len ) & 0xFF );
*p++ = (uint8_t) ssl->own_cid_len;
memcpy( p, ssl->own_cid, ssl->own_cid_len );
*olen = ssl->own_cid_len + 5;
}
#endif /* MBEDTLS_SSL_DTLS_CONNECTION_ID */
#if defined(MBEDTLS_SSL_ENCRYPT_THEN_MAC)
static void ssl_write_encrypt_then_mac_ext( mbedtls_ssl_context *ssl,
unsigned char *buf,
size_t *olen )
{
unsigned char *p = buf;
const mbedtls_ssl_ciphersuite_t *suite = NULL;
const mbedtls_cipher_info_t *cipher = NULL;
if( ssl->session_negotiate->encrypt_then_mac == MBEDTLS_SSL_ETM_DISABLED ||
ssl->minor_ver == MBEDTLS_SSL_MINOR_VERSION_0 )
{
*olen = 0;
return;
}
/*
* RFC 7366: "If a server receives an encrypt-then-MAC request extension
* from a client and then selects a stream or Authenticated Encryption
* with Associated Data (AEAD) ciphersuite, it MUST NOT send an
* encrypt-then-MAC response extension back to the client."
*/
if( ( suite = mbedtls_ssl_ciphersuite_from_id(
ssl->session_negotiate->ciphersuite ) ) == NULL ||
( cipher = mbedtls_cipher_info_from_type( suite->cipher ) ) == NULL ||
cipher->mode != MBEDTLS_MODE_CBC )
{
*olen = 0;
return;
}
MBEDTLS_SSL_DEBUG_MSG( 3, ( "server hello, adding encrypt then mac extension" ) );
*p++ = (unsigned char)( ( MBEDTLS_TLS_EXT_ENCRYPT_THEN_MAC >> 8 ) & 0xFF );
*p++ = (unsigned char)( ( MBEDTLS_TLS_EXT_ENCRYPT_THEN_MAC ) & 0xFF );
*p++ = 0x00;
*p++ = 0x00;
*olen = 4;
}
#endif /* MBEDTLS_SSL_ENCRYPT_THEN_MAC */
#if defined(MBEDTLS_SSL_EXTENDED_MASTER_SECRET)
static void ssl_write_extended_ms_ext( mbedtls_ssl_context *ssl,
unsigned char *buf,
size_t *olen )
{
unsigned char *p = buf;
if( ssl->handshake->extended_ms == MBEDTLS_SSL_EXTENDED_MS_DISABLED ||
ssl->minor_ver == MBEDTLS_SSL_MINOR_VERSION_0 )
{
*olen = 0;
return;
}
MBEDTLS_SSL_DEBUG_MSG( 3, ( "server hello, adding extended master secret "
"extension" ) );
*p++ = (unsigned char)( ( MBEDTLS_TLS_EXT_EXTENDED_MASTER_SECRET >> 8 ) & 0xFF );
*p++ = (unsigned char)( ( MBEDTLS_TLS_EXT_EXTENDED_MASTER_SECRET ) & 0xFF );
*p++ = 0x00;
*p++ = 0x00;
*olen = 4;
}
#endif /* MBEDTLS_SSL_EXTENDED_MASTER_SECRET */
#if defined(MBEDTLS_SSL_SESSION_TICKETS)
static void ssl_write_session_ticket_ext( mbedtls_ssl_context *ssl,
unsigned char *buf,
size_t *olen )
{
unsigned char *p = buf;
if( ssl->handshake->new_session_ticket == 0 )
{
*olen = 0;
return;
}
MBEDTLS_SSL_DEBUG_MSG( 3, ( "server hello, adding session ticket extension" ) );
*p++ = (unsigned char)( ( MBEDTLS_TLS_EXT_SESSION_TICKET >> 8 ) & 0xFF );
*p++ = (unsigned char)( ( MBEDTLS_TLS_EXT_SESSION_TICKET ) & 0xFF );
*p++ = 0x00;
*p++ = 0x00;
*olen = 4;
}
#endif /* MBEDTLS_SSL_SESSION_TICKETS */
static void ssl_write_renegotiation_ext( mbedtls_ssl_context *ssl,
unsigned char *buf,
size_t *olen )
{
unsigned char *p = buf;
if( ssl->secure_renegotiation != MBEDTLS_SSL_SECURE_RENEGOTIATION )
{
*olen = 0;
return;
}
MBEDTLS_SSL_DEBUG_MSG( 3, ( "server hello, secure renegotiation extension" ) );
*p++ = (unsigned char)( ( MBEDTLS_TLS_EXT_RENEGOTIATION_INFO >> 8 ) & 0xFF );
*p++ = (unsigned char)( ( MBEDTLS_TLS_EXT_RENEGOTIATION_INFO ) & 0xFF );
#if defined(MBEDTLS_SSL_RENEGOTIATION)
if( ssl->renego_status != MBEDTLS_SSL_INITIAL_HANDSHAKE )
{
*p++ = 0x00;
*p++ = ( ssl->verify_data_len * 2 + 1 ) & 0xFF;
*p++ = ssl->verify_data_len * 2 & 0xFF;
memcpy( p, ssl->peer_verify_data, ssl->verify_data_len );
p += ssl->verify_data_len;
memcpy( p, ssl->own_verify_data, ssl->verify_data_len );
p += ssl->verify_data_len;
}
else
#endif /* MBEDTLS_SSL_RENEGOTIATION */
{
*p++ = 0x00;
*p++ = 0x01;
*p++ = 0x00;
}
*olen = p - buf;
}
#if defined(MBEDTLS_SSL_MAX_FRAGMENT_LENGTH)
static void ssl_write_max_fragment_length_ext( mbedtls_ssl_context *ssl,
unsigned char *buf,
size_t *olen )
{
unsigned char *p = buf;
if( ssl->session_negotiate->mfl_code == MBEDTLS_SSL_MAX_FRAG_LEN_NONE )
{
*olen = 0;
return;
}
MBEDTLS_SSL_DEBUG_MSG( 3, ( "server hello, max_fragment_length extension" ) );
*p++ = (unsigned char)( ( MBEDTLS_TLS_EXT_MAX_FRAGMENT_LENGTH >> 8 ) & 0xFF );
*p++ = (unsigned char)( ( MBEDTLS_TLS_EXT_MAX_FRAGMENT_LENGTH ) & 0xFF );
*p++ = 0x00;
*p++ = 1;
*p++ = ssl->session_negotiate->mfl_code;
*olen = 5;
}
#endif /* MBEDTLS_SSL_MAX_FRAGMENT_LENGTH */
#if defined(MBEDTLS_ECDH_C) || defined(MBEDTLS_ECDSA_C) || \
defined(MBEDTLS_KEY_EXCHANGE_ECJPAKE_ENABLED)
static void ssl_write_supported_point_formats_ext( mbedtls_ssl_context *ssl,
unsigned char *buf,
size_t *olen )
{
unsigned char *p = buf;
((void) ssl);
if( ( ssl->handshake->cli_exts &
MBEDTLS_TLS_EXT_SUPPORTED_POINT_FORMATS_PRESENT ) == 0 )
{
*olen = 0;
return;
}
MBEDTLS_SSL_DEBUG_MSG( 3, ( "server hello, supported_point_formats extension" ) );
*p++ = (unsigned char)( ( MBEDTLS_TLS_EXT_SUPPORTED_POINT_FORMATS >> 8 ) & 0xFF );
*p++ = (unsigned char)( ( MBEDTLS_TLS_EXT_SUPPORTED_POINT_FORMATS ) & 0xFF );
*p++ = 0x00;
*p++ = 2;
*p++ = 1;
*p++ = MBEDTLS_ECP_PF_UNCOMPRESSED;
*olen = 6;
}
#endif /* MBEDTLS_ECDH_C || MBEDTLS_ECDSA_C || MBEDTLS_KEY_EXCHANGE_ECJPAKE_ENABLED */
#if defined(MBEDTLS_KEY_EXCHANGE_ECJPAKE_ENABLED)
static void ssl_write_ecjpake_kkpp_ext( mbedtls_ssl_context *ssl,
unsigned char *buf,
size_t *olen )
{
int ret = MBEDTLS_ERR_ERROR_CORRUPTION_DETECTED;
unsigned char *p = buf;
const unsigned char *end = ssl->out_msg + MBEDTLS_SSL_OUT_CONTENT_LEN;
size_t kkpp_len;
*olen = 0;
/* Skip costly computation if not needed */
if( ssl->handshake->ciphersuite_info->key_exchange !=
MBEDTLS_KEY_EXCHANGE_ECJPAKE )
return;
MBEDTLS_SSL_DEBUG_MSG( 3, ( "server hello, ecjpake kkpp extension" ) );
if( end - p < 4 )
{
MBEDTLS_SSL_DEBUG_MSG( 1, ( "buffer too small" ) );
return;
}
*p++ = (unsigned char)( ( MBEDTLS_TLS_EXT_ECJPAKE_KKPP >> 8 ) & 0xFF );
*p++ = (unsigned char)( ( MBEDTLS_TLS_EXT_ECJPAKE_KKPP ) & 0xFF );
ret = mbedtls_ecjpake_write_round_one( &ssl->handshake->ecjpake_ctx,
p + 2, end - p - 2, &kkpp_len,
ssl->conf->f_rng, ssl->conf->p_rng );
if( ret != 0 )
{
MBEDTLS_SSL_DEBUG_RET( 1 , "mbedtls_ecjpake_write_round_one", ret );
return;
}
*p++ = (unsigned char)( ( kkpp_len >> 8 ) & 0xFF );
*p++ = (unsigned char)( ( kkpp_len ) & 0xFF );
*olen = kkpp_len + 4;
}
#endif /* MBEDTLS_KEY_EXCHANGE_ECJPAKE_ENABLED */
#if defined(MBEDTLS_SSL_ALPN )
static void ssl_write_alpn_ext( mbedtls_ssl_context *ssl,
unsigned char *buf, size_t *olen )
{
if( ssl->alpn_chosen == NULL )
{
*olen = 0;
return;
}
MBEDTLS_SSL_DEBUG_MSG( 3, ( "server hello, adding alpn extension" ) );
/*
* 0 . 1 ext identifier
* 2 . 3 ext length
* 4 . 5 protocol list length
* 6 . 6 protocol name length
* 7 . 7+n protocol name
*/
buf[0] = (unsigned char)( ( MBEDTLS_TLS_EXT_ALPN >> 8 ) & 0xFF );
buf[1] = (unsigned char)( ( MBEDTLS_TLS_EXT_ALPN ) & 0xFF );
*olen = 7 + strlen( ssl->alpn_chosen );
buf[2] = (unsigned char)( ( ( *olen - 4 ) >> 8 ) & 0xFF );
buf[3] = (unsigned char)( ( ( *olen - 4 ) ) & 0xFF );
buf[4] = (unsigned char)( ( ( *olen - 6 ) >> 8 ) & 0xFF );
buf[5] = (unsigned char)( ( ( *olen - 6 ) ) & 0xFF );
buf[6] = (unsigned char)( ( ( *olen - 7 ) ) & 0xFF );
memcpy( buf + 7, ssl->alpn_chosen, *olen - 7 );
}
#endif /* MBEDTLS_ECDH_C || MBEDTLS_ECDSA_C */
#if defined(MBEDTLS_SSL_DTLS_SRTP ) && defined(MBEDTLS_SSL_PROTO_DTLS)
static void ssl_write_use_srtp_ext( mbedtls_ssl_context *ssl,
unsigned char *buf,
size_t *olen )
{
size_t mki_len = 0, ext_len = 0;
uint16_t profile_value = 0;
const unsigned char *end = ssl->out_msg + MBEDTLS_SSL_OUT_CONTENT_LEN;
*olen = 0;
if( ( ssl->conf->transport != MBEDTLS_SSL_TRANSPORT_DATAGRAM ) ||
( ssl->dtls_srtp_info.chosen_dtls_srtp_profile == MBEDTLS_TLS_SRTP_UNSET ) )
{
return;
}
MBEDTLS_SSL_DEBUG_MSG( 3, ( "server hello, adding use_srtp extension" ) );
if( ssl->conf->dtls_srtp_mki_support == MBEDTLS_SSL_DTLS_SRTP_MKI_SUPPORTED )
{
mki_len = ssl->dtls_srtp_info.mki_len;
}
/* The extension total size is 9 bytes :
* - 2 bytes for the extension tag
* - 2 bytes for the total size
* - 2 bytes for the protection profile length
* - 2 bytes for the protection profile
* - 1 byte for the mki length
* + the actual mki length
* Check we have enough room in the output buffer */
if( (size_t)( end - buf ) < mki_len + 9 )
{
MBEDTLS_SSL_DEBUG_MSG( 1, ( "buffer too small" ) );
return;
}
/* extension */
buf[0] = (unsigned char)( ( MBEDTLS_TLS_EXT_USE_SRTP >> 8 ) & 0xFF );
buf[1] = (unsigned char)( ( MBEDTLS_TLS_EXT_USE_SRTP ) & 0xFF );
/*
* total length 5 and mki value: only one profile(2 bytes)
* and length(2 bytes) and srtp_mki )
*/
ext_len = 5 + mki_len;
buf[2] = (unsigned char)( ( ext_len >> 8 ) & 0xFF );
buf[3] = (unsigned char)( ext_len & 0xFF );
/* protection profile length: 2 */
buf[4] = 0x00;
buf[5] = 0x02;
profile_value = mbedtls_ssl_check_srtp_profile_value(
ssl->dtls_srtp_info.chosen_dtls_srtp_profile );
if( profile_value != MBEDTLS_TLS_SRTP_UNSET )
{
buf[6] = (unsigned char)( ( profile_value >> 8 ) & 0xFF );
buf[7] = (unsigned char)( profile_value & 0xFF );
}
else
{
MBEDTLS_SSL_DEBUG_MSG( 1, ( "use_srtp extension invalid profile" ) );
return;
}
buf[8] = mki_len & 0xFF;
memcpy( &buf[9], ssl->dtls_srtp_info.mki_value, mki_len );
*olen = 9 + mki_len;
}
#endif /* MBEDTLS_SSL_DTLS_SRTP */
#if defined(MBEDTLS_SSL_DTLS_HELLO_VERIFY)
static int ssl_write_hello_verify_request( mbedtls_ssl_context *ssl )
{
int ret = MBEDTLS_ERR_ERROR_CORRUPTION_DETECTED;
unsigned char *p = ssl->out_msg + 4;
unsigned char *cookie_len_byte;
MBEDTLS_SSL_DEBUG_MSG( 2, ( "=> write hello verify request" ) );
/*
* struct {
* ProtocolVersion server_version;
* opaque cookie<0..2^8-1>;
* } HelloVerifyRequest;
*/
/* The RFC is not clear on this point, but sending the actual negotiated
* version looks like the most interoperable thing to do. */
mbedtls_ssl_write_version( ssl->major_ver, ssl->minor_ver,
ssl->conf->transport, p );
MBEDTLS_SSL_DEBUG_BUF( 3, "server version", p, 2 );
p += 2;
/* If we get here, f_cookie_check is not null */
if( ssl->conf->f_cookie_write == NULL )
{
MBEDTLS_SSL_DEBUG_MSG( 1, ( "inconsistent cookie callbacks" ) );
return( MBEDTLS_ERR_SSL_INTERNAL_ERROR );
}
/* Skip length byte until we know the length */
cookie_len_byte = p++;
if( ( ret = ssl->conf->f_cookie_write( ssl->conf->p_cookie,
&p, ssl->out_buf + MBEDTLS_SSL_OUT_BUFFER_LEN,
ssl->cli_id, ssl->cli_id_len ) ) != 0 )
{
MBEDTLS_SSL_DEBUG_RET( 1, "f_cookie_write", ret );
return( ret );
}
*cookie_len_byte = (unsigned char)( p - ( cookie_len_byte + 1 ) );
MBEDTLS_SSL_DEBUG_BUF( 3, "cookie sent", cookie_len_byte + 1, *cookie_len_byte );
ssl->out_msglen = p - ssl->out_msg;
ssl->out_msgtype = MBEDTLS_SSL_MSG_HANDSHAKE;
ssl->out_msg[0] = MBEDTLS_SSL_HS_HELLO_VERIFY_REQUEST;
ssl->state = MBEDTLS_SSL_SERVER_HELLO_VERIFY_REQUEST_SENT;
if( ( ret = mbedtls_ssl_write_handshake_msg( ssl ) ) != 0 )
{
MBEDTLS_SSL_DEBUG_RET( 1, "mbedtls_ssl_write_handshake_msg", ret );
return( ret );
}
#if defined(MBEDTLS_SSL_PROTO_DTLS)
if( ssl->conf->transport == MBEDTLS_SSL_TRANSPORT_DATAGRAM &&
( ret = mbedtls_ssl_flight_transmit( ssl ) ) != 0 )
{
MBEDTLS_SSL_DEBUG_RET( 1, "mbedtls_ssl_flight_transmit", ret );
return( ret );
}
#endif /* MBEDTLS_SSL_PROTO_DTLS */
MBEDTLS_SSL_DEBUG_MSG( 2, ( "<= write hello verify request" ) );
return( 0 );
}
#endif /* MBEDTLS_SSL_DTLS_HELLO_VERIFY */
static void ssl_handle_id_based_session_resumption( mbedtls_ssl_context *ssl )
{
int ret;
mbedtls_ssl_session session_tmp;
mbedtls_ssl_session * const session = ssl->session_negotiate;
/* Resume is 0 by default, see ssl_handshake_init().
* It may be already set to 1 by ssl_parse_session_ticket_ext(). */
if( ssl->handshake->resume == 1 )
return;
if( session->id_len == 0 )
return;
if( ssl->conf->f_get_cache == NULL )
return;
#if defined(MBEDTLS_SSL_RENEGOTIATION)
if( ssl->renego_status != MBEDTLS_SSL_INITIAL_HANDSHAKE )
return;
#endif
mbedtls_ssl_session_init( &session_tmp );
session_tmp.id_len = session->id_len;
memcpy( session_tmp.id, session->id, session->id_len );
ret = ssl->conf->f_get_cache( ssl->conf->p_cache,
&session_tmp );
if( ret != 0 )
goto exit;
if( session->ciphersuite != session_tmp.ciphersuite ||
session->compression != session_tmp.compression )
{
/* Mismatch between cached and negotiated session */
goto exit;
}
/* Move semantics */
mbedtls_ssl_session_free( session );
*session = session_tmp;
memset( &session_tmp, 0, sizeof( session_tmp ) );
MBEDTLS_SSL_DEBUG_MSG( 3, ( "session successfully restored from cache" ) );
ssl->handshake->resume = 1;
exit:
mbedtls_ssl_session_free( &session_tmp );
}
static int ssl_write_server_hello( mbedtls_ssl_context *ssl )
{
#if defined(MBEDTLS_HAVE_TIME)
mbedtls_time_t t;
#endif
int ret = MBEDTLS_ERR_ERROR_CORRUPTION_DETECTED;
size_t olen, ext_len = 0, n;
unsigned char *buf, *p;
MBEDTLS_SSL_DEBUG_MSG( 2, ( "=> write server hello" ) );
#if defined(MBEDTLS_SSL_DTLS_HELLO_VERIFY)
if( ssl->conf->transport == MBEDTLS_SSL_TRANSPORT_DATAGRAM &&
ssl->handshake->verify_cookie_len != 0 )
{
MBEDTLS_SSL_DEBUG_MSG( 2, ( "client hello was not authenticated" ) );
MBEDTLS_SSL_DEBUG_MSG( 2, ( "<= write server hello" ) );
return( ssl_write_hello_verify_request( ssl ) );
}
#endif /* MBEDTLS_SSL_DTLS_HELLO_VERIFY */
if( ssl->conf->f_rng == NULL )
{
MBEDTLS_SSL_DEBUG_MSG( 1, ( "no RNG provided") );
return( MBEDTLS_ERR_SSL_NO_RNG );
}
/*
* 0 . 0 handshake type
* 1 . 3 handshake length
* 4 . 5 protocol version
* 6 . 9 UNIX time()
* 10 . 37 random bytes
*/
buf = ssl->out_msg;
p = buf + 4;
mbedtls_ssl_write_version( ssl->major_ver, ssl->minor_ver,
ssl->conf->transport, p );
p += 2;
MBEDTLS_SSL_DEBUG_MSG( 3, ( "server hello, chosen version: [%d:%d]",
buf[4], buf[5] ) );
#if defined(MBEDTLS_HAVE_TIME)
t = mbedtls_time( NULL );
*p++ = (unsigned char)( t >> 24 );
*p++ = (unsigned char)( t >> 16 );
*p++ = (unsigned char)( t >> 8 );
*p++ = (unsigned char)( t );
MBEDTLS_SSL_DEBUG_MSG( 3, ( "server hello, current time: %" MBEDTLS_PRINTF_LONGLONG,
(long long) t ) );
#else
if( ( ret = ssl->conf->f_rng( ssl->conf->p_rng, p, 4 ) ) != 0 )
return( ret );
p += 4;
#endif /* MBEDTLS_HAVE_TIME */
if( ( ret = ssl->conf->f_rng( ssl->conf->p_rng, p, 28 ) ) != 0 )
return( ret );
p += 28;
memcpy( ssl->handshake->randbytes + 32, buf + 6, 32 );
MBEDTLS_SSL_DEBUG_BUF( 3, "server hello, random bytes", buf + 6, 32 );
ssl_handle_id_based_session_resumption( ssl );
if( ssl->handshake->resume == 0 )
{
/*
* New session, create a new session id,
* unless we're about to issue a session ticket
*/
ssl->state++;
#if defined(MBEDTLS_HAVE_TIME)
ssl->session_negotiate->start = mbedtls_time( NULL );
#endif
#if defined(MBEDTLS_SSL_SESSION_TICKETS)
if( ssl->handshake->new_session_ticket != 0 )
{
ssl->session_negotiate->id_len = n = 0;
memset( ssl->session_negotiate->id, 0, 32 );
}
else
#endif /* MBEDTLS_SSL_SESSION_TICKETS */
{
ssl->session_negotiate->id_len = n = 32;
if( ( ret = ssl->conf->f_rng( ssl->conf->p_rng, ssl->session_negotiate->id,
n ) ) != 0 )
return( ret );
}
}
else
{
/*
* Resuming a session
*/
n = ssl->session_negotiate->id_len;
ssl->state = MBEDTLS_SSL_SERVER_CHANGE_CIPHER_SPEC;
if( ( ret = mbedtls_ssl_derive_keys( ssl ) ) != 0 )
{
MBEDTLS_SSL_DEBUG_RET( 1, "mbedtls_ssl_derive_keys", ret );
return( ret );
}
}
/*
* 38 . 38 session id length
* 39 . 38+n session id
* 39+n . 40+n chosen ciphersuite
* 41+n . 41+n chosen compression alg.
* 42+n . 43+n extensions length
* 44+n . 43+n+m extensions
*/
*p++ = (unsigned char) ssl->session_negotiate->id_len;
memcpy( p, ssl->session_negotiate->id, ssl->session_negotiate->id_len );
p += ssl->session_negotiate->id_len;
MBEDTLS_SSL_DEBUG_MSG( 3, ( "server hello, session id len.: %" MBEDTLS_PRINTF_SIZET, n ) );
MBEDTLS_SSL_DEBUG_BUF( 3, "server hello, session id", buf + 39, n );
MBEDTLS_SSL_DEBUG_MSG( 3, ( "%s session has been resumed",
ssl->handshake->resume ? "a" : "no" ) );
*p++ = (unsigned char)( ssl->session_negotiate->ciphersuite >> 8 );
*p++ = (unsigned char)( ssl->session_negotiate->ciphersuite );
*p++ = (unsigned char)( ssl->session_negotiate->compression );
MBEDTLS_SSL_DEBUG_MSG( 3, ( "server hello, chosen ciphersuite: %s",
mbedtls_ssl_get_ciphersuite_name( ssl->session_negotiate->ciphersuite ) ) );
MBEDTLS_SSL_DEBUG_MSG( 3, ( "server hello, compress alg.: 0x%02X",
(unsigned int) ssl->session_negotiate->compression ) );
/* Do not write the extensions if the protocol is SSLv3 */
#if defined(MBEDTLS_SSL_PROTO_SSL3)
if( ( ssl->major_ver != 3 ) || ( ssl->minor_ver != 0 ) )
{
#endif
/*
* First write extensions, then the total length
*/
ssl_write_renegotiation_ext( ssl, p + 2 + ext_len, &olen );
ext_len += olen;
#if defined(MBEDTLS_SSL_MAX_FRAGMENT_LENGTH)
ssl_write_max_fragment_length_ext( ssl, p + 2 + ext_len, &olen );
ext_len += olen;
#endif
#if defined(MBEDTLS_SSL_TRUNCATED_HMAC)
ssl_write_truncated_hmac_ext( ssl, p + 2 + ext_len, &olen );
ext_len += olen;
#endif
#if defined(MBEDTLS_SSL_DTLS_CONNECTION_ID)
ssl_write_cid_ext( ssl, p + 2 + ext_len, &olen );
ext_len += olen;
#endif
#if defined(MBEDTLS_SSL_ENCRYPT_THEN_MAC)
ssl_write_encrypt_then_mac_ext( ssl, p + 2 + ext_len, &olen );
ext_len += olen;
#endif
#if defined(MBEDTLS_SSL_EXTENDED_MASTER_SECRET)
ssl_write_extended_ms_ext( ssl, p + 2 + ext_len, &olen );
ext_len += olen;
#endif
#if defined(MBEDTLS_SSL_SESSION_TICKETS)
ssl_write_session_ticket_ext( ssl, p + 2 + ext_len, &olen );
ext_len += olen;
#endif
#if defined(MBEDTLS_ECDH_C) || defined(MBEDTLS_ECDSA_C) || \
defined(MBEDTLS_KEY_EXCHANGE_ECJPAKE_ENABLED)
if ( mbedtls_ssl_ciphersuite_uses_ec(
mbedtls_ssl_ciphersuite_from_id( ssl->session_negotiate->ciphersuite ) ) )
{
ssl_write_supported_point_formats_ext( ssl, p + 2 + ext_len, &olen );
ext_len += olen;
}
#endif
#if defined(MBEDTLS_KEY_EXCHANGE_ECJPAKE_ENABLED)
ssl_write_ecjpake_kkpp_ext( ssl, p + 2 + ext_len, &olen );
ext_len += olen;
#endif
#if defined(MBEDTLS_SSL_ALPN)
ssl_write_alpn_ext( ssl, p + 2 + ext_len, &olen );
ext_len += olen;
#endif
#if defined(MBEDTLS_SSL_DTLS_SRTP)
ssl_write_use_srtp_ext( ssl, p + 2 + ext_len, &olen );
ext_len += olen;
#endif
MBEDTLS_SSL_DEBUG_MSG( 3, ( "server hello, total extension length: %" MBEDTLS_PRINTF_SIZET,
ext_len ) );
if( ext_len > 0 )
{
*p++ = (unsigned char)( ( ext_len >> 8 ) & 0xFF );
*p++ = (unsigned char)( ( ext_len ) & 0xFF );
p += ext_len;
}
#if defined(MBEDTLS_SSL_PROTO_SSL3)
}
#endif
ssl->out_msglen = p - buf;
ssl->out_msgtype = MBEDTLS_SSL_MSG_HANDSHAKE;
ssl->out_msg[0] = MBEDTLS_SSL_HS_SERVER_HELLO;
ret = mbedtls_ssl_write_handshake_msg( ssl );
MBEDTLS_SSL_DEBUG_MSG( 2, ( "<= write server hello" ) );
return( ret );
}
#if !defined(MBEDTLS_KEY_EXCHANGE_CERT_REQ_ALLOWED_ENABLED)
static int ssl_write_certificate_request( mbedtls_ssl_context *ssl )
{
const mbedtls_ssl_ciphersuite_t *ciphersuite_info =
ssl->handshake->ciphersuite_info;
MBEDTLS_SSL_DEBUG_MSG( 2, ( "=> write certificate request" ) );
if( !mbedtls_ssl_ciphersuite_cert_req_allowed( ciphersuite_info ) )
{
MBEDTLS_SSL_DEBUG_MSG( 2, ( "<= skip write certificate request" ) );
ssl->state++;
return( 0 );
}
MBEDTLS_SSL_DEBUG_MSG( 1, ( "should never happen" ) );
return( MBEDTLS_ERR_SSL_INTERNAL_ERROR );
}
#else /* !MBEDTLS_KEY_EXCHANGE_CERT_REQ_ALLOWED_ENABLED */
static int ssl_write_certificate_request( mbedtls_ssl_context *ssl )
{
int ret = MBEDTLS_ERR_SSL_FEATURE_UNAVAILABLE;
const mbedtls_ssl_ciphersuite_t *ciphersuite_info =
ssl->handshake->ciphersuite_info;
uint16_t dn_size, total_dn_size; /* excluding length bytes */
size_t ct_len, sa_len; /* including length bytes */
unsigned char *buf, *p;
const unsigned char * const end = ssl->out_msg + MBEDTLS_SSL_OUT_CONTENT_LEN;
const mbedtls_x509_crt *crt;
int authmode;
MBEDTLS_SSL_DEBUG_MSG( 2, ( "=> write certificate request" ) );
ssl->state++;
#if defined(MBEDTLS_SSL_SERVER_NAME_INDICATION)
if( ssl->handshake->sni_authmode != MBEDTLS_SSL_VERIFY_UNSET )
authmode = ssl->handshake->sni_authmode;
else
#endif
authmode = ssl->conf->authmode;
if( !mbedtls_ssl_ciphersuite_cert_req_allowed( ciphersuite_info ) ||
authmode == MBEDTLS_SSL_VERIFY_NONE )
{
MBEDTLS_SSL_DEBUG_MSG( 2, ( "<= skip write certificate request" ) );
return( 0 );
}
/*
* 0 . 0 handshake type
* 1 . 3 handshake length
* 4 . 4 cert type count
* 5 .. m-1 cert types
* m .. m+1 sig alg length (TLS 1.2 only)
* m+1 .. n-1 SignatureAndHashAlgorithms (TLS 1.2 only)
* n .. n+1 length of all DNs
* n+2 .. n+3 length of DN 1
* n+4 .. ... Distinguished Name #1
* ... .. ... length of DN 2, etc.
*/
buf = ssl->out_msg;
p = buf + 4;
/*
* Supported certificate types
*
* ClientCertificateType certificate_types<1..2^8-1>;
* enum { (255) } ClientCertificateType;
*/
ct_len = 0;
#if defined(MBEDTLS_RSA_C)
p[1 + ct_len++] = MBEDTLS_SSL_CERT_TYPE_RSA_SIGN;
#endif
#if defined(MBEDTLS_ECDSA_C)
p[1 + ct_len++] = MBEDTLS_SSL_CERT_TYPE_ECDSA_SIGN;
#endif
p[0] = (unsigned char) ct_len++;
p += ct_len;
sa_len = 0;
#if defined(MBEDTLS_SSL_PROTO_TLS1_2)
/*
* Add signature_algorithms for verify (TLS 1.2)
*
* SignatureAndHashAlgorithm supported_signature_algorithms<2..2^16-2>;
*
* struct {
* HashAlgorithm hash;
* SignatureAlgorithm signature;
* } SignatureAndHashAlgorithm;
*
* enum { (255) } HashAlgorithm;
* enum { (255) } SignatureAlgorithm;
*/
if( ssl->minor_ver == MBEDTLS_SSL_MINOR_VERSION_3 )
{
const int *cur;
/*
* Supported signature algorithms
*/
for( cur = ssl->conf->sig_hashes; *cur != MBEDTLS_MD_NONE; cur++ )
{
unsigned char hash = mbedtls_ssl_hash_from_md_alg( *cur );
if( MBEDTLS_SSL_HASH_NONE == hash || mbedtls_ssl_set_calc_verify_md( ssl, hash ) )
continue;
#if defined(MBEDTLS_RSA_C)
p[2 + sa_len++] = hash;
p[2 + sa_len++] = MBEDTLS_SSL_SIG_RSA;
#endif
#if defined(MBEDTLS_ECDSA_C)
p[2 + sa_len++] = hash;
p[2 + sa_len++] = MBEDTLS_SSL_SIG_ECDSA;
#endif
}
p[0] = (unsigned char)( sa_len >> 8 );
p[1] = (unsigned char)( sa_len );
sa_len += 2;
p += sa_len;
}
#endif /* MBEDTLS_SSL_PROTO_TLS1_2 */
/*
* DistinguishedName certificate_authorities<0..2^16-1>;
* opaque DistinguishedName<1..2^16-1>;
*/
p += 2;
total_dn_size = 0;
if( ssl->conf->cert_req_ca_list == MBEDTLS_SSL_CERT_REQ_CA_LIST_ENABLED )
{
/* NOTE: If trusted certificates are provisioned
* via a CA callback (configured through
* `mbedtls_ssl_conf_ca_cb()`, then the
* CertificateRequest is currently left empty. */
#if defined(MBEDTLS_SSL_SERVER_NAME_INDICATION)
if( ssl->handshake->sni_ca_chain != NULL )
crt = ssl->handshake->sni_ca_chain;
else
#endif
crt = ssl->conf->ca_chain;
while( crt != NULL && crt->version != 0 )
{
/* It follows from RFC 5280 A.1 that this length
* can be represented in at most 11 bits. */
dn_size = (uint16_t) crt->subject_raw.len;
if( end < p || (size_t)( end - p ) < 2 + (size_t) dn_size )
{
MBEDTLS_SSL_DEBUG_MSG( 1, ( "skipping CAs: buffer too short" ) );
break;
}
*p++ = (unsigned char)( dn_size >> 8 );
*p++ = (unsigned char)( dn_size );
memcpy( p, crt->subject_raw.p, dn_size );
p += dn_size;
MBEDTLS_SSL_DEBUG_BUF( 3, "requested DN", p - dn_size, dn_size );
total_dn_size += 2 + dn_size;
crt = crt->next;
}
}
ssl->out_msglen = p - buf;
ssl->out_msgtype = MBEDTLS_SSL_MSG_HANDSHAKE;
ssl->out_msg[0] = MBEDTLS_SSL_HS_CERTIFICATE_REQUEST;
ssl->out_msg[4 + ct_len + sa_len] = (unsigned char)( total_dn_size >> 8 );
ssl->out_msg[5 + ct_len + sa_len] = (unsigned char)( total_dn_size );
ret = mbedtls_ssl_write_handshake_msg( ssl );
MBEDTLS_SSL_DEBUG_MSG( 2, ( "<= write certificate request" ) );
return( ret );
}
#endif /* MBEDTLS_KEY_EXCHANGE_CERT_REQ_ALLOWED_ENABLED */
#if defined(MBEDTLS_KEY_EXCHANGE_ECDH_RSA_ENABLED) || \
defined(MBEDTLS_KEY_EXCHANGE_ECDH_ECDSA_ENABLED)
static int ssl_get_ecdh_params_from_cert( mbedtls_ssl_context *ssl )
{
int ret = MBEDTLS_ERR_ERROR_CORRUPTION_DETECTED;
if( ! mbedtls_pk_can_do( mbedtls_ssl_own_key( ssl ), MBEDTLS_PK_ECKEY ) )
{
MBEDTLS_SSL_DEBUG_MSG( 1, ( "server key not ECDH capable" ) );
return( MBEDTLS_ERR_SSL_PK_TYPE_MISMATCH );
}
if( ( ret = mbedtls_ecdh_get_params( &ssl->handshake->ecdh_ctx,
mbedtls_pk_ec( *mbedtls_ssl_own_key( ssl ) ),
MBEDTLS_ECDH_OURS ) ) != 0 )
{
MBEDTLS_SSL_DEBUG_RET( 1, ( "mbedtls_ecdh_get_params" ), ret );
return( ret );
}
return( 0 );
}
#endif /* MBEDTLS_KEY_EXCHANGE_ECDH_RSA_ENABLED) ||
MBEDTLS_KEY_EXCHANGE_ECDH_ECDSA_ENABLED */
#if defined(MBEDTLS_KEY_EXCHANGE_WITH_SERVER_SIGNATURE_ENABLED) && \
defined(MBEDTLS_SSL_ASYNC_PRIVATE)
static int ssl_resume_server_key_exchange( mbedtls_ssl_context *ssl,
size_t *signature_len )
{
/* Append the signature to ssl->out_msg, leaving 2 bytes for the
* signature length which will be added in ssl_write_server_key_exchange
* after the call to ssl_prepare_server_key_exchange.
* ssl_write_server_key_exchange also takes care of incrementing
* ssl->out_msglen. */
unsigned char *sig_start = ssl->out_msg + ssl->out_msglen + 2;
size_t sig_max_len = ( ssl->out_buf + MBEDTLS_SSL_OUT_CONTENT_LEN
- sig_start );
int ret = ssl->conf->f_async_resume( ssl,
sig_start, signature_len, sig_max_len );
if( ret != MBEDTLS_ERR_SSL_ASYNC_IN_PROGRESS )
{
ssl->handshake->async_in_progress = 0;
mbedtls_ssl_set_async_operation_data( ssl, NULL );
}
MBEDTLS_SSL_DEBUG_RET( 2, "ssl_resume_server_key_exchange", ret );
return( ret );
}
#endif /* defined(MBEDTLS_KEY_EXCHANGE_WITH_SERVER_SIGNATURE_ENABLED) &&
defined(MBEDTLS_SSL_ASYNC_PRIVATE) */
/* Prepare the ServerKeyExchange message, up to and including
* calculating the signature if any, but excluding formatting the
* signature and sending the message. */
static int ssl_prepare_server_key_exchange( mbedtls_ssl_context *ssl,
size_t *signature_len )
{
const mbedtls_ssl_ciphersuite_t *ciphersuite_info =
ssl->handshake->ciphersuite_info;
#if defined(MBEDTLS_KEY_EXCHANGE_SOME_PFS_ENABLED)
#if defined(MBEDTLS_KEY_EXCHANGE_WITH_SERVER_SIGNATURE_ENABLED)
unsigned char *dig_signed = NULL;
#endif /* MBEDTLS_KEY_EXCHANGE_WITH_SERVER_SIGNATURE_ENABLED */
#endif /* MBEDTLS_KEY_EXCHANGE_SOME_PFS_ENABLED */
(void) ciphersuite_info; /* unused in some configurations */
#if !defined(MBEDTLS_KEY_EXCHANGE_WITH_SERVER_SIGNATURE_ENABLED)
(void) signature_len;
#endif /* MBEDTLS_KEY_EXCHANGE_WITH_SERVER_SIGNATURE_ENABLED */
ssl->out_msglen = 4; /* header (type:1, length:3) to be written later */
/*
*
* Part 1: Provide key exchange parameters for chosen ciphersuite.
*
*/
/*
* - ECJPAKE key exchanges
*/
#if defined(MBEDTLS_KEY_EXCHANGE_ECJPAKE_ENABLED)
if( ciphersuite_info->key_exchange == MBEDTLS_KEY_EXCHANGE_ECJPAKE )
{
int ret = MBEDTLS_ERR_ERROR_CORRUPTION_DETECTED;
size_t len = 0;
ret = mbedtls_ecjpake_write_round_two(
&ssl->handshake->ecjpake_ctx,
ssl->out_msg + ssl->out_msglen,
MBEDTLS_SSL_OUT_CONTENT_LEN - ssl->out_msglen, &len,
ssl->conf->f_rng, ssl->conf->p_rng );
if( ret != 0 )
{
MBEDTLS_SSL_DEBUG_RET( 1, "mbedtls_ecjpake_write_round_two", ret );
return( ret );
}
ssl->out_msglen += len;
}
#endif /* MBEDTLS_KEY_EXCHANGE_ECJPAKE_ENABLED */
/*
* For (EC)DHE key exchanges with PSK, parameters are prefixed by support
* identity hint (RFC 4279, Sec. 3). Until someone needs this feature,
* we use empty support identity hints here.
**/
#if defined(MBEDTLS_KEY_EXCHANGE_DHE_PSK_ENABLED) || \
defined(MBEDTLS_KEY_EXCHANGE_ECDHE_PSK_ENABLED)
if( ciphersuite_info->key_exchange == MBEDTLS_KEY_EXCHANGE_DHE_PSK ||
ciphersuite_info->key_exchange == MBEDTLS_KEY_EXCHANGE_ECDHE_PSK )
{
ssl->out_msg[ssl->out_msglen++] = 0x00;
ssl->out_msg[ssl->out_msglen++] = 0x00;
}
#endif /* MBEDTLS_KEY_EXCHANGE_DHE_PSK_ENABLED ||
MBEDTLS_KEY_EXCHANGE_ECDHE_PSK_ENABLED */
/*
* - DHE key exchanges
*/
#if defined(MBEDTLS_KEY_EXCHANGE_SOME_DHE_ENABLED)
if( mbedtls_ssl_ciphersuite_uses_dhe( ciphersuite_info ) )
{
int ret = MBEDTLS_ERR_ERROR_CORRUPTION_DETECTED;
size_t len = 0;
if( ssl->conf->dhm_P.p == NULL || ssl->conf->dhm_G.p == NULL )
{
MBEDTLS_SSL_DEBUG_MSG( 1, ( "no DH parameters set" ) );
return( MBEDTLS_ERR_SSL_BAD_INPUT_DATA );
}
/*
* Ephemeral DH parameters:
*
* struct {
* opaque dh_p<1..2^16-1>;
* opaque dh_g<1..2^16-1>;
* opaque dh_Ys<1..2^16-1>;
* } ServerDHParams;
*/
if( ( ret = mbedtls_dhm_set_group( &ssl->handshake->dhm_ctx,
&ssl->conf->dhm_P,
&ssl->conf->dhm_G ) ) != 0 )
{
MBEDTLS_SSL_DEBUG_RET( 1, "mbedtls_dhm_set_group", ret );
return( ret );
}
if( ( ret = mbedtls_dhm_make_params(
&ssl->handshake->dhm_ctx,
(int) mbedtls_mpi_size( &ssl->handshake->dhm_ctx.P ),
ssl->out_msg + ssl->out_msglen, &len,
ssl->conf->f_rng, ssl->conf->p_rng ) ) != 0 )
{
MBEDTLS_SSL_DEBUG_RET( 1, "mbedtls_dhm_make_params", ret );
return( ret );
}
#if defined(MBEDTLS_KEY_EXCHANGE_WITH_SERVER_SIGNATURE_ENABLED)
dig_signed = ssl->out_msg + ssl->out_msglen;
#endif
ssl->out_msglen += len;
MBEDTLS_SSL_DEBUG_MPI( 3, "DHM: X ", &ssl->handshake->dhm_ctx.X );
MBEDTLS_SSL_DEBUG_MPI( 3, "DHM: P ", &ssl->handshake->dhm_ctx.P );
MBEDTLS_SSL_DEBUG_MPI( 3, "DHM: G ", &ssl->handshake->dhm_ctx.G );
MBEDTLS_SSL_DEBUG_MPI( 3, "DHM: GX", &ssl->handshake->dhm_ctx.GX );
}
#endif /* MBEDTLS_KEY_EXCHANGE_SOME_DHE_ENABLED */
/*
* - ECDHE key exchanges
*/
#if defined(MBEDTLS_KEY_EXCHANGE_SOME_ECDHE_ENABLED)
if( mbedtls_ssl_ciphersuite_uses_ecdhe( ciphersuite_info ) )
{
/*
* Ephemeral ECDH parameters:
*
* struct {
* ECParameters curve_params;
* ECPoint public;
* } ServerECDHParams;
*/
const mbedtls_ecp_curve_info **curve = NULL;
const mbedtls_ecp_group_id *gid;
int ret = MBEDTLS_ERR_ERROR_CORRUPTION_DETECTED;
size_t len = 0;
/* Match our preference list against the offered curves */
for( gid = ssl->conf->curve_list; *gid != MBEDTLS_ECP_DP_NONE; gid++ )
for( curve = ssl->handshake->curves; *curve != NULL; curve++ )
if( (*curve)->grp_id == *gid )
goto curve_matching_done;
curve_matching_done:
if( curve == NULL || *curve == NULL )
{
MBEDTLS_SSL_DEBUG_MSG( 1, ( "no matching curve for ECDHE" ) );
return( MBEDTLS_ERR_SSL_NO_CIPHER_CHOSEN );
}
MBEDTLS_SSL_DEBUG_MSG( 2, ( "ECDHE curve: %s", (*curve)->name ) );
if( ( ret = mbedtls_ecdh_setup( &ssl->handshake->ecdh_ctx,
(*curve)->grp_id ) ) != 0 )
{
MBEDTLS_SSL_DEBUG_RET( 1, "mbedtls_ecp_group_load", ret );
return( ret );
}
if( ( ret = mbedtls_ecdh_make_params(
&ssl->handshake->ecdh_ctx, &len,
ssl->out_msg + ssl->out_msglen,
MBEDTLS_SSL_OUT_CONTENT_LEN - ssl->out_msglen,
ssl->conf->f_rng, ssl->conf->p_rng ) ) != 0 )
{
MBEDTLS_SSL_DEBUG_RET( 1, "mbedtls_ecdh_make_params", ret );
return( ret );
}
#if defined(MBEDTLS_KEY_EXCHANGE_WITH_SERVER_SIGNATURE_ENABLED)
dig_signed = ssl->out_msg + ssl->out_msglen;
#endif
ssl->out_msglen += len;
MBEDTLS_SSL_DEBUG_ECDH( 3, &ssl->handshake->ecdh_ctx,
MBEDTLS_DEBUG_ECDH_Q );
}
#endif /* MBEDTLS_KEY_EXCHANGE_SOME_ECDHE_ENABLED */
/*
*
* Part 2: For key exchanges involving the server signing the
* exchange parameters, compute and add the signature here.
*
*/
#if defined(MBEDTLS_KEY_EXCHANGE_WITH_SERVER_SIGNATURE_ENABLED)
if( mbedtls_ssl_ciphersuite_uses_server_signature( ciphersuite_info ) )
{
size_t dig_signed_len = ssl->out_msg + ssl->out_msglen - dig_signed;
size_t hashlen = 0;
unsigned char hash[MBEDTLS_MD_MAX_SIZE];
int ret = MBEDTLS_ERR_ERROR_CORRUPTION_DETECTED;
/*
* 2.1: Choose hash algorithm:
* A: For TLS 1.2, obey signature-hash-algorithm extension
* to choose appropriate hash.
* B: For SSL3, TLS1.0, TLS1.1 and ECDHE_ECDSA, use SHA1
* (RFC 4492, Sec. 5.4)
* C: Otherwise, use MD5 + SHA1 (RFC 4346, Sec. 7.4.3)
*/
mbedtls_md_type_t md_alg;
#if defined(MBEDTLS_SSL_PROTO_TLS1_2)
mbedtls_pk_type_t sig_alg =
mbedtls_ssl_get_ciphersuite_sig_pk_alg( ciphersuite_info );
if( ssl->minor_ver == MBEDTLS_SSL_MINOR_VERSION_3 )
{
/* A: For TLS 1.2, obey signature-hash-algorithm extension
* (RFC 5246, Sec. 7.4.1.4.1). */
if( sig_alg == MBEDTLS_PK_NONE ||
( md_alg = mbedtls_ssl_sig_hash_set_find( &ssl->handshake->hash_algs,
sig_alg ) ) == MBEDTLS_MD_NONE )
{
MBEDTLS_SSL_DEBUG_MSG( 1, ( "should never happen" ) );
/* (... because we choose a cipher suite
* only if there is a matching hash.) */
return( MBEDTLS_ERR_SSL_INTERNAL_ERROR );
}
}
else
#endif /* MBEDTLS_SSL_PROTO_TLS1_2 */
#if defined(MBEDTLS_SSL_PROTO_SSL3) || defined(MBEDTLS_SSL_PROTO_TLS1) || \
defined(MBEDTLS_SSL_PROTO_TLS1_1)
if( ciphersuite_info->key_exchange == MBEDTLS_KEY_EXCHANGE_ECDHE_ECDSA )
{
/* B: Default hash SHA1 */
md_alg = MBEDTLS_MD_SHA1;
}
else
#endif /* MBEDTLS_SSL_PROTO_SSL3 || MBEDTLS_SSL_PROTO_TLS1 || \
MBEDTLS_SSL_PROTO_TLS1_1 */
{
/* C: MD5 + SHA1 */
md_alg = MBEDTLS_MD_NONE;
}
MBEDTLS_SSL_DEBUG_MSG( 3, ( "pick hash algorithm %u for signing", (unsigned) md_alg ) );
/*
* 2.2: Compute the hash to be signed
*/
#if defined(MBEDTLS_SSL_PROTO_SSL3) || defined(MBEDTLS_SSL_PROTO_TLS1) || \
defined(MBEDTLS_SSL_PROTO_TLS1_1)
if( md_alg == MBEDTLS_MD_NONE )
{
hashlen = 36;
ret = mbedtls_ssl_get_key_exchange_md_ssl_tls( ssl, hash,
dig_signed,
dig_signed_len );
if( ret != 0 )
return( ret );
}
else
#endif /* MBEDTLS_SSL_PROTO_SSL3 || MBEDTLS_SSL_PROTO_TLS1 || \
MBEDTLS_SSL_PROTO_TLS1_1 */
#if defined(MBEDTLS_SSL_PROTO_TLS1) || defined(MBEDTLS_SSL_PROTO_TLS1_1) || \
defined(MBEDTLS_SSL_PROTO_TLS1_2)
if( md_alg != MBEDTLS_MD_NONE )
{
ret = mbedtls_ssl_get_key_exchange_md_tls1_2( ssl, hash, &hashlen,
dig_signed,
dig_signed_len,
md_alg );
if( ret != 0 )
return( ret );
}
else
#endif /* MBEDTLS_SSL_PROTO_TLS1 || MBEDTLS_SSL_PROTO_TLS1_1 || \
MBEDTLS_SSL_PROTO_TLS1_2 */
{
MBEDTLS_SSL_DEBUG_MSG( 1, ( "should never happen" ) );
return( MBEDTLS_ERR_SSL_INTERNAL_ERROR );
}
MBEDTLS_SSL_DEBUG_BUF( 3, "parameters hash", hash, hashlen );
/*
* 2.3: Compute and add the signature
*/
#if defined(MBEDTLS_SSL_PROTO_TLS1_2)
if( ssl->minor_ver == MBEDTLS_SSL_MINOR_VERSION_3 )
{
/*
* For TLS 1.2, we need to specify signature and hash algorithm
* explicitly through a prefix to the signature.
*
* struct {
* HashAlgorithm hash;
* SignatureAlgorithm signature;
* } SignatureAndHashAlgorithm;
*
* struct {
* SignatureAndHashAlgorithm algorithm;
* opaque signature<0..2^16-1>;
* } DigitallySigned;
*
*/
ssl->out_msg[ssl->out_msglen++] =
mbedtls_ssl_hash_from_md_alg( md_alg );
ssl->out_msg[ssl->out_msglen++] =
mbedtls_ssl_sig_from_pk_alg( sig_alg );
}
#endif /* MBEDTLS_SSL_PROTO_TLS1_2 */
#if defined(MBEDTLS_SSL_ASYNC_PRIVATE)
if( ssl->conf->f_async_sign_start != NULL )
{
ret = ssl->conf->f_async_sign_start( ssl,
mbedtls_ssl_own_cert( ssl ),
md_alg, hash, hashlen );
switch( ret )
{
case MBEDTLS_ERR_SSL_HW_ACCEL_FALLTHROUGH:
/* act as if f_async_sign was null */
break;
case 0:
ssl->handshake->async_in_progress = 1;
return( ssl_resume_server_key_exchange( ssl, signature_len ) );
case MBEDTLS_ERR_SSL_ASYNC_IN_PROGRESS:
ssl->handshake->async_in_progress = 1;
return( MBEDTLS_ERR_SSL_ASYNC_IN_PROGRESS );
default:
MBEDTLS_SSL_DEBUG_RET( 1, "f_async_sign_start", ret );
return( ret );
}
}
#endif /* MBEDTLS_SSL_ASYNC_PRIVATE */
if( mbedtls_ssl_own_key( ssl ) == NULL )
{
MBEDTLS_SSL_DEBUG_MSG( 1, ( "got no private key" ) );
return( MBEDTLS_ERR_SSL_PRIVATE_KEY_REQUIRED );
}
/* Append the signature to ssl->out_msg, leaving 2 bytes for the
* signature length which will be added in ssl_write_server_key_exchange
* after the call to ssl_prepare_server_key_exchange.
* ssl_write_server_key_exchange also takes care of incrementing
* ssl->out_msglen. */
if( ( ret = mbedtls_pk_sign( mbedtls_ssl_own_key( ssl ),
md_alg, hash, hashlen,
ssl->out_msg + ssl->out_msglen + 2,
signature_len,
ssl->conf->f_rng,
ssl->conf->p_rng ) ) != 0 )
{
MBEDTLS_SSL_DEBUG_RET( 1, "mbedtls_pk_sign", ret );
return( ret );
}
}
#endif /* MBEDTLS_KEY_EXCHANGE_WITH_SERVER_SIGNATURE_ENABLED */
return( 0 );
}
/* Prepare the ServerKeyExchange message and send it. For ciphersuites
* that do not include a ServerKeyExchange message, do nothing. Either
* way, if successful, move on to the next step in the SSL state
* machine. */
static int ssl_write_server_key_exchange( mbedtls_ssl_context *ssl )
{
int ret = MBEDTLS_ERR_ERROR_CORRUPTION_DETECTED;
size_t signature_len = 0;
#if defined(MBEDTLS_KEY_EXCHANGE_SOME_NON_PFS_ENABLED)
const mbedtls_ssl_ciphersuite_t *ciphersuite_info =
ssl->handshake->ciphersuite_info;
#endif /* MBEDTLS_KEY_EXCHANGE_SOME_NON_PFS_ENABLED */
MBEDTLS_SSL_DEBUG_MSG( 2, ( "=> write server key exchange" ) );
#if defined(MBEDTLS_KEY_EXCHANGE_SOME_NON_PFS_ENABLED)
/* Extract static ECDH parameters and abort if ServerKeyExchange
* is not needed. */
if( mbedtls_ssl_ciphersuite_no_pfs( ciphersuite_info ) )
{
/* For suites involving ECDH, extract DH parameters
* from certificate at this point. */
#if defined(MBEDTLS_KEY_EXCHANGE_SOME_ECDH_ENABLED)
if( mbedtls_ssl_ciphersuite_uses_ecdh( ciphersuite_info ) )
{
ssl_get_ecdh_params_from_cert( ssl );
}
#endif /* MBEDTLS_KEY_EXCHANGE_SOME_ECDH_ENABLED */
/* Key exchanges not involving ephemeral keys don't use
* ServerKeyExchange, so end here. */
MBEDTLS_SSL_DEBUG_MSG( 2, ( "<= skip write server key exchange" ) );
ssl->state++;
return( 0 );
}
#endif /* MBEDTLS_KEY_EXCHANGE_SOME_NON_PFS_ENABLED */
#if defined(MBEDTLS_KEY_EXCHANGE_WITH_SERVER_SIGNATURE_ENABLED) && \
defined(MBEDTLS_SSL_ASYNC_PRIVATE)
/* If we have already prepared the message and there is an ongoing
* signature operation, resume signing. */
if( ssl->handshake->async_in_progress != 0 )
{
MBEDTLS_SSL_DEBUG_MSG( 2, ( "resuming signature operation" ) );
ret = ssl_resume_server_key_exchange( ssl, &signature_len );
}
else
#endif /* defined(MBEDTLS_KEY_EXCHANGE_WITH_SERVER_SIGNATURE_ENABLED) &&
defined(MBEDTLS_SSL_ASYNC_PRIVATE) */
{
/* ServerKeyExchange is needed. Prepare the message. */
ret = ssl_prepare_server_key_exchange( ssl, &signature_len );
}
if( ret != 0 )
{
/* If we're starting to write a new message, set ssl->out_msglen
* to 0. But if we're resuming after an asynchronous message,
* out_msglen is the amount of data written so far and mst be
* preserved. */
if( ret == MBEDTLS_ERR_SSL_ASYNC_IN_PROGRESS )
MBEDTLS_SSL_DEBUG_MSG( 2, ( "<= write server key exchange (pending)" ) );
else
ssl->out_msglen = 0;
return( ret );
}
/* If there is a signature, write its length.
* ssl_prepare_server_key_exchange already wrote the signature
* itself at its proper place in the output buffer. */
#if defined(MBEDTLS_KEY_EXCHANGE_WITH_SERVER_SIGNATURE_ENABLED)
if( signature_len != 0 )
{
ssl->out_msg[ssl->out_msglen++] = (unsigned char)( signature_len >> 8 );
ssl->out_msg[ssl->out_msglen++] = (unsigned char)( signature_len );
MBEDTLS_SSL_DEBUG_BUF( 3, "my signature",
ssl->out_msg + ssl->out_msglen,
signature_len );
/* Skip over the already-written signature */
ssl->out_msglen += signature_len;
}
#endif /* MBEDTLS_KEY_EXCHANGE_WITH_SERVER_SIGNATURE_ENABLED */
/* Add header and send. */
ssl->out_msgtype = MBEDTLS_SSL_MSG_HANDSHAKE;
ssl->out_msg[0] = MBEDTLS_SSL_HS_SERVER_KEY_EXCHANGE;
ssl->state++;
if( ( ret = mbedtls_ssl_write_handshake_msg( ssl ) ) != 0 )
{
MBEDTLS_SSL_DEBUG_RET( 1, "mbedtls_ssl_write_handshake_msg", ret );
return( ret );
}
MBEDTLS_SSL_DEBUG_MSG( 2, ( "<= write server key exchange" ) );
return( 0 );
}
static int ssl_write_server_hello_done( mbedtls_ssl_context *ssl )
{
int ret = MBEDTLS_ERR_ERROR_CORRUPTION_DETECTED;
MBEDTLS_SSL_DEBUG_MSG( 2, ( "=> write server hello done" ) );
ssl->out_msglen = 4;
ssl->out_msgtype = MBEDTLS_SSL_MSG_HANDSHAKE;
ssl->out_msg[0] = MBEDTLS_SSL_HS_SERVER_HELLO_DONE;
ssl->state++;
#if defined(MBEDTLS_SSL_PROTO_DTLS)
if( ssl->conf->transport == MBEDTLS_SSL_TRANSPORT_DATAGRAM )
mbedtls_ssl_send_flight_completed( ssl );
#endif
if( ( ret = mbedtls_ssl_write_handshake_msg( ssl ) ) != 0 )
{
MBEDTLS_SSL_DEBUG_RET( 1, "mbedtls_ssl_write_handshake_msg", ret );
return( ret );
}
#if defined(MBEDTLS_SSL_PROTO_DTLS)
if( ssl->conf->transport == MBEDTLS_SSL_TRANSPORT_DATAGRAM &&
( ret = mbedtls_ssl_flight_transmit( ssl ) ) != 0 )
{
MBEDTLS_SSL_DEBUG_RET( 1, "mbedtls_ssl_flight_transmit", ret );
return( ret );
}
#endif /* MBEDTLS_SSL_PROTO_DTLS */
MBEDTLS_SSL_DEBUG_MSG( 2, ( "<= write server hello done" ) );
return( 0 );
}
#if defined(MBEDTLS_KEY_EXCHANGE_DHE_RSA_ENABLED) || \
defined(MBEDTLS_KEY_EXCHANGE_DHE_PSK_ENABLED)
static int ssl_parse_client_dh_public( mbedtls_ssl_context *ssl, unsigned char **p,
const unsigned char *end )
{
int ret = MBEDTLS_ERR_SSL_FEATURE_UNAVAILABLE;
size_t n;
/*
* Receive G^Y mod P, premaster = (G^Y)^X mod P
*/
if( *p + 2 > end )
{
MBEDTLS_SSL_DEBUG_MSG( 1, ( "bad client key exchange message" ) );
return( MBEDTLS_ERR_SSL_BAD_HS_CLIENT_KEY_EXCHANGE );
}
n = ( (*p)[0] << 8 ) | (*p)[1];
*p += 2;
if( *p + n > end )
{
MBEDTLS_SSL_DEBUG_MSG( 1, ( "bad client key exchange message" ) );
return( MBEDTLS_ERR_SSL_BAD_HS_CLIENT_KEY_EXCHANGE );
}
if( ( ret = mbedtls_dhm_read_public( &ssl->handshake->dhm_ctx, *p, n ) ) != 0 )
{
MBEDTLS_SSL_DEBUG_RET( 1, "mbedtls_dhm_read_public", ret );
return( MBEDTLS_ERR_SSL_BAD_HS_CLIENT_KEY_EXCHANGE_RP );
}
*p += n;
MBEDTLS_SSL_DEBUG_MPI( 3, "DHM: GY", &ssl->handshake->dhm_ctx.GY );
return( ret );
}
#endif /* MBEDTLS_KEY_EXCHANGE_DHE_RSA_ENABLED ||
MBEDTLS_KEY_EXCHANGE_DHE_PSK_ENABLED */
#if defined(MBEDTLS_KEY_EXCHANGE_RSA_ENABLED) || \
defined(MBEDTLS_KEY_EXCHANGE_RSA_PSK_ENABLED)
#if defined(MBEDTLS_SSL_ASYNC_PRIVATE)
static int ssl_resume_decrypt_pms( mbedtls_ssl_context *ssl,
unsigned char *peer_pms,
size_t *peer_pmslen,
size_t peer_pmssize )
{
int ret = ssl->conf->f_async_resume( ssl,
peer_pms, peer_pmslen, peer_pmssize );
if( ret != MBEDTLS_ERR_SSL_ASYNC_IN_PROGRESS )
{
ssl->handshake->async_in_progress = 0;
mbedtls_ssl_set_async_operation_data( ssl, NULL );
}
MBEDTLS_SSL_DEBUG_RET( 2, "ssl_decrypt_encrypted_pms", ret );
return( ret );
}
#endif /* MBEDTLS_SSL_ASYNC_PRIVATE */
static int ssl_decrypt_encrypted_pms( mbedtls_ssl_context *ssl,
const unsigned char *p,
const unsigned char *end,
unsigned char *peer_pms,
size_t *peer_pmslen,
size_t peer_pmssize )
{
int ret = MBEDTLS_ERR_ERROR_CORRUPTION_DETECTED;
mbedtls_pk_context *private_key = mbedtls_ssl_own_key( ssl );
mbedtls_pk_context *public_key = &mbedtls_ssl_own_cert( ssl )->pk;
size_t len = mbedtls_pk_get_len( public_key );
#if defined(MBEDTLS_SSL_ASYNC_PRIVATE)
/* If we have already started decoding the message and there is an ongoing
* decryption operation, resume signing. */
if( ssl->handshake->async_in_progress != 0 )
{
MBEDTLS_SSL_DEBUG_MSG( 2, ( "resuming decryption operation" ) );
return( ssl_resume_decrypt_pms( ssl,
peer_pms, peer_pmslen, peer_pmssize ) );
}
#endif /* MBEDTLS_SSL_ASYNC_PRIVATE */
/*
* Prepare to decrypt the premaster using own private RSA key
*/
#if defined(MBEDTLS_SSL_PROTO_TLS1) || defined(MBEDTLS_SSL_PROTO_TLS1_1) || \
defined(MBEDTLS_SSL_PROTO_TLS1_2)
if( ssl->minor_ver != MBEDTLS_SSL_MINOR_VERSION_0 )
{
if ( p + 2 > end ) {
MBEDTLS_SSL_DEBUG_MSG( 1, ( "bad client key exchange message" ) );
return( MBEDTLS_ERR_SSL_BAD_HS_CLIENT_KEY_EXCHANGE );
}
if( *p++ != ( ( len >> 8 ) & 0xFF ) ||
*p++ != ( ( len ) & 0xFF ) )
{
MBEDTLS_SSL_DEBUG_MSG( 1, ( "bad client key exchange message" ) );
return( MBEDTLS_ERR_SSL_BAD_HS_CLIENT_KEY_EXCHANGE );
}
}
#endif
if( p + len != end )
{
MBEDTLS_SSL_DEBUG_MSG( 1, ( "bad client key exchange message" ) );
return( MBEDTLS_ERR_SSL_BAD_HS_CLIENT_KEY_EXCHANGE );
}
/*
* Decrypt the premaster secret
*/
#if defined(MBEDTLS_SSL_ASYNC_PRIVATE)
if( ssl->conf->f_async_decrypt_start != NULL )
{
ret = ssl->conf->f_async_decrypt_start( ssl,
mbedtls_ssl_own_cert( ssl ),
p, len );
switch( ret )
{
case MBEDTLS_ERR_SSL_HW_ACCEL_FALLTHROUGH:
/* act as if f_async_decrypt_start was null */
break;
case 0:
ssl->handshake->async_in_progress = 1;
return( ssl_resume_decrypt_pms( ssl,
peer_pms,
peer_pmslen,
peer_pmssize ) );
case MBEDTLS_ERR_SSL_ASYNC_IN_PROGRESS:
ssl->handshake->async_in_progress = 1;
return( MBEDTLS_ERR_SSL_ASYNC_IN_PROGRESS );
default:
MBEDTLS_SSL_DEBUG_RET( 1, "f_async_decrypt_start", ret );
return( ret );
}
}
#endif /* MBEDTLS_SSL_ASYNC_PRIVATE */
if( ! mbedtls_pk_can_do( private_key, MBEDTLS_PK_RSA ) )
{
MBEDTLS_SSL_DEBUG_MSG( 1, ( "got no RSA private key" ) );
return( MBEDTLS_ERR_SSL_PRIVATE_KEY_REQUIRED );
}
ret = mbedtls_pk_decrypt( private_key, p, len,
peer_pms, peer_pmslen, peer_pmssize,
ssl->conf->f_rng, ssl->conf->p_rng );
return( ret );
}
static int ssl_parse_encrypted_pms( mbedtls_ssl_context *ssl,
const unsigned char *p,
const unsigned char *end,
size_t pms_offset )
{
int ret = MBEDTLS_ERR_ERROR_CORRUPTION_DETECTED;
unsigned char *pms = ssl->handshake->premaster + pms_offset;
unsigned char ver[2];
unsigned char fake_pms[48], peer_pms[48];
unsigned char mask;
size_t i, peer_pmslen;
unsigned int diff;
/* In case of a failure in decryption, the decryption may write less than
* 2 bytes of output, but we always read the first two bytes. It doesn't
* matter in the end because diff will be nonzero in that case due to
* ret being nonzero, and we only care whether diff is 0.
* But do initialize peer_pms and peer_pmslen for robustness anyway. This
* also makes memory analyzers happy (don't access uninitialized memory,
* even if it's an unsigned char). */
peer_pms[0] = peer_pms[1] = ~0;
peer_pmslen = 0;
ret = ssl_decrypt_encrypted_pms( ssl, p, end,
peer_pms,
&peer_pmslen,
sizeof( peer_pms ) );
#if defined(MBEDTLS_SSL_ASYNC_PRIVATE)
if ( ret == MBEDTLS_ERR_SSL_ASYNC_IN_PROGRESS )
return( ret );
#endif /* MBEDTLS_SSL_ASYNC_PRIVATE */
mbedtls_ssl_write_version( ssl->handshake->max_major_ver,
ssl->handshake->max_minor_ver,
ssl->conf->transport, ver );
/* Avoid data-dependent branches while checking for invalid
* padding, to protect against timing-based Bleichenbacher-type
* attacks. */
diff = (unsigned int) ret;
diff |= peer_pmslen ^ 48;
diff |= peer_pms[0] ^ ver[0];
diff |= peer_pms[1] ^ ver[1];
/* mask = diff ? 0xff : 0x00 using bit operations to avoid branches */
/* MSVC has a warning about unary minus on unsigned, but this is
* well-defined and precisely what we want to do here */
#if defined(_MSC_VER)
#pragma warning( push )
#pragma warning( disable : 4146 )
#endif
mask = - ( ( diff | - diff ) >> ( sizeof( unsigned int ) * 8 - 1 ) );
#if defined(_MSC_VER)
#pragma warning( pop )
#endif
/*
* Protection against Bleichenbacher's attack: invalid PKCS#1 v1.5 padding
* must not cause the connection to end immediately; instead, send a
* bad_record_mac later in the handshake.
* To protect against timing-based variants of the attack, we must
* not have any branch that depends on whether the decryption was
* successful. In particular, always generate the fake premaster secret,
* regardless of whether it will ultimately influence the output or not.
*/
ret = ssl->conf->f_rng( ssl->conf->p_rng, fake_pms, sizeof( fake_pms ) );
if( ret != 0 )
{
/* It's ok to abort on an RNG failure, since this does not reveal
* anything about the RSA decryption. */
return( ret );
}
#if defined(MBEDTLS_SSL_DEBUG_ALL)
if( diff != 0 )
MBEDTLS_SSL_DEBUG_MSG( 1, ( "bad client key exchange message" ) );
#endif
if( sizeof( ssl->handshake->premaster ) < pms_offset ||
sizeof( ssl->handshake->premaster ) - pms_offset < 48 )
{
MBEDTLS_SSL_DEBUG_MSG( 1, ( "should never happen" ) );
return( MBEDTLS_ERR_SSL_INTERNAL_ERROR );
}
ssl->handshake->pmslen = 48;
/* Set pms to either the true or the fake PMS, without
* data-dependent branches. */
for( i = 0; i < ssl->handshake->pmslen; i++ )
pms[i] = ( mask & fake_pms[i] ) | ( (~mask) & peer_pms[i] );
return( 0 );
}
#endif /* MBEDTLS_KEY_EXCHANGE_RSA_ENABLED ||
MBEDTLS_KEY_EXCHANGE_RSA_PSK_ENABLED */
#if defined(MBEDTLS_KEY_EXCHANGE_SOME_PSK_ENABLED)
static int ssl_parse_client_psk_identity( mbedtls_ssl_context *ssl, unsigned char **p,
const unsigned char *end )
{
int ret = 0;
uint16_t n;
if( ssl_conf_has_psk_or_cb( ssl->conf ) == 0 )
{
MBEDTLS_SSL_DEBUG_MSG( 1, ( "got no pre-shared key" ) );
return( MBEDTLS_ERR_SSL_PRIVATE_KEY_REQUIRED );
}
/*
* Receive client pre-shared key identity name
*/
if( end - *p < 2 )
{
MBEDTLS_SSL_DEBUG_MSG( 1, ( "bad client key exchange message" ) );
return( MBEDTLS_ERR_SSL_BAD_HS_CLIENT_KEY_EXCHANGE );
}
n = ( (*p)[0] << 8 ) | (*p)[1];
*p += 2;
if( n == 0 || n > end - *p )
{
MBEDTLS_SSL_DEBUG_MSG( 1, ( "bad client key exchange message" ) );
return( MBEDTLS_ERR_SSL_BAD_HS_CLIENT_KEY_EXCHANGE );
}
if( ssl->conf->f_psk != NULL )
{
if( ssl->conf->f_psk( ssl->conf->p_psk, ssl, *p, n ) != 0 )
ret = MBEDTLS_ERR_SSL_UNKNOWN_IDENTITY;
}
else
{
/* Identity is not a big secret since clients send it in the clear,
* but treat it carefully anyway, just in case */
if( n != ssl->conf->psk_identity_len ||
mbedtls_ssl_safer_memcmp( ssl->conf->psk_identity, *p, n ) != 0 )
{
ret = MBEDTLS_ERR_SSL_UNKNOWN_IDENTITY;
}
}
if( ret == MBEDTLS_ERR_SSL_UNKNOWN_IDENTITY )
{
MBEDTLS_SSL_DEBUG_BUF( 3, "Unknown PSK identity", *p, n );
mbedtls_ssl_send_alert_message( ssl, MBEDTLS_SSL_ALERT_LEVEL_FATAL,
MBEDTLS_SSL_ALERT_MSG_UNKNOWN_PSK_IDENTITY );
return( MBEDTLS_ERR_SSL_UNKNOWN_IDENTITY );
}
*p += n;
return( 0 );
}
#endif /* MBEDTLS_KEY_EXCHANGE_SOME_PSK_ENABLED */
static int ssl_parse_client_key_exchange( mbedtls_ssl_context *ssl )
{
int ret = MBEDTLS_ERR_ERROR_CORRUPTION_DETECTED;
const mbedtls_ssl_ciphersuite_t *ciphersuite_info;
unsigned char *p, *end;
ciphersuite_info = ssl->handshake->ciphersuite_info;
MBEDTLS_SSL_DEBUG_MSG( 2, ( "=> parse client key exchange" ) );
#if defined(MBEDTLS_SSL_ASYNC_PRIVATE) && \
( defined(MBEDTLS_KEY_EXCHANGE_RSA_ENABLED) || \
defined(MBEDTLS_KEY_EXCHANGE_RSA_PSK_ENABLED) )
if( ( ciphersuite_info->key_exchange == MBEDTLS_KEY_EXCHANGE_RSA_PSK ||
ciphersuite_info->key_exchange == MBEDTLS_KEY_EXCHANGE_RSA ) &&
( ssl->handshake->async_in_progress != 0 ) )
{
/* We've already read a record and there is an asynchronous
* operation in progress to decrypt it. So skip reading the
* record. */
MBEDTLS_SSL_DEBUG_MSG( 3, ( "will resume decryption of previously-read record" ) );
}
else
#endif
if( ( ret = mbedtls_ssl_read_record( ssl, 1 ) ) != 0 )
{
MBEDTLS_SSL_DEBUG_RET( 1, "mbedtls_ssl_read_record", ret );
return( ret );
}
p = ssl->in_msg + mbedtls_ssl_hs_hdr_len( ssl );
end = ssl->in_msg + ssl->in_hslen;
if( ssl->in_msgtype != MBEDTLS_SSL_MSG_HANDSHAKE )
{
MBEDTLS_SSL_DEBUG_MSG( 1, ( "bad client key exchange message" ) );
return( MBEDTLS_ERR_SSL_BAD_HS_CLIENT_KEY_EXCHANGE );
}
if( ssl->in_msg[0] != MBEDTLS_SSL_HS_CLIENT_KEY_EXCHANGE )
{
MBEDTLS_SSL_DEBUG_MSG( 1, ( "bad client key exchange message" ) );
return( MBEDTLS_ERR_SSL_BAD_HS_CLIENT_KEY_EXCHANGE );
}
#if defined(MBEDTLS_KEY_EXCHANGE_DHE_RSA_ENABLED)
if( ciphersuite_info->key_exchange == MBEDTLS_KEY_EXCHANGE_DHE_RSA )
{
if( ( ret = ssl_parse_client_dh_public( ssl, &p, end ) ) != 0 )
{
MBEDTLS_SSL_DEBUG_RET( 1, ( "ssl_parse_client_dh_public" ), ret );
return( ret );
}
if( p != end )
{
MBEDTLS_SSL_DEBUG_MSG( 1, ( "bad client key exchange" ) );
return( MBEDTLS_ERR_SSL_BAD_HS_CLIENT_KEY_EXCHANGE );
}
if( ( ret = mbedtls_dhm_calc_secret( &ssl->handshake->dhm_ctx,
ssl->handshake->premaster,
MBEDTLS_PREMASTER_SIZE,
&ssl->handshake->pmslen,
ssl->conf->f_rng, ssl->conf->p_rng ) ) != 0 )
{
MBEDTLS_SSL_DEBUG_RET( 1, "mbedtls_dhm_calc_secret", ret );
return( MBEDTLS_ERR_SSL_BAD_HS_CLIENT_KEY_EXCHANGE_CS );
}
MBEDTLS_SSL_DEBUG_MPI( 3, "DHM: K ", &ssl->handshake->dhm_ctx.K );
}
else
#endif /* MBEDTLS_KEY_EXCHANGE_DHE_RSA_ENABLED */
#if defined(MBEDTLS_KEY_EXCHANGE_ECDHE_RSA_ENABLED) || \
defined(MBEDTLS_KEY_EXCHANGE_ECDHE_ECDSA_ENABLED) || \
defined(MBEDTLS_KEY_EXCHANGE_ECDH_RSA_ENABLED) || \
defined(MBEDTLS_KEY_EXCHANGE_ECDH_ECDSA_ENABLED)
if( ciphersuite_info->key_exchange == MBEDTLS_KEY_EXCHANGE_ECDHE_RSA ||
ciphersuite_info->key_exchange == MBEDTLS_KEY_EXCHANGE_ECDHE_ECDSA ||
ciphersuite_info->key_exchange == MBEDTLS_KEY_EXCHANGE_ECDH_RSA ||
ciphersuite_info->key_exchange == MBEDTLS_KEY_EXCHANGE_ECDH_ECDSA )
{
if( ( ret = mbedtls_ecdh_read_public( &ssl->handshake->ecdh_ctx,
p, end - p) ) != 0 )
{
MBEDTLS_SSL_DEBUG_RET( 1, "mbedtls_ecdh_read_public", ret );
return( MBEDTLS_ERR_SSL_BAD_HS_CLIENT_KEY_EXCHANGE_RP );
}
MBEDTLS_SSL_DEBUG_ECDH( 3, &ssl->handshake->ecdh_ctx,
MBEDTLS_DEBUG_ECDH_QP );
if( ( ret = mbedtls_ecdh_calc_secret( &ssl->handshake->ecdh_ctx,
&ssl->handshake->pmslen,
ssl->handshake->premaster,
MBEDTLS_MPI_MAX_SIZE,
ssl->conf->f_rng, ssl->conf->p_rng ) ) != 0 )
{
MBEDTLS_SSL_DEBUG_RET( 1, "mbedtls_ecdh_calc_secret", ret );
return( MBEDTLS_ERR_SSL_BAD_HS_CLIENT_KEY_EXCHANGE_CS );
}
MBEDTLS_SSL_DEBUG_ECDH( 3, &ssl->handshake->ecdh_ctx,
MBEDTLS_DEBUG_ECDH_Z );
}
else
#endif /* MBEDTLS_KEY_EXCHANGE_ECDHE_RSA_ENABLED ||
MBEDTLS_KEY_EXCHANGE_ECDHE_ECDSA_ENABLED ||
MBEDTLS_KEY_EXCHANGE_ECDH_RSA_ENABLED ||
MBEDTLS_KEY_EXCHANGE_ECDH_ECDSA_ENABLED */
#if defined(MBEDTLS_KEY_EXCHANGE_PSK_ENABLED)
if( ciphersuite_info->key_exchange == MBEDTLS_KEY_EXCHANGE_PSK )
{
if( ( ret = ssl_parse_client_psk_identity( ssl, &p, end ) ) != 0 )
{
MBEDTLS_SSL_DEBUG_RET( 1, ( "ssl_parse_client_psk_identity" ), ret );
return( ret );
}
if( p != end )
{
MBEDTLS_SSL_DEBUG_MSG( 1, ( "bad client key exchange" ) );
return( MBEDTLS_ERR_SSL_BAD_HS_CLIENT_KEY_EXCHANGE );
}
#if defined(MBEDTLS_USE_PSA_CRYPTO)
/* For opaque PSKs, we perform the PSK-to-MS derivation atomatically
* and skip the intermediate PMS. */
if( ssl_use_opaque_psk( ssl ) == 1 )
MBEDTLS_SSL_DEBUG_MSG( 1, ( "skip PMS generation for opaque PSK" ) );
else
#endif /* MBEDTLS_USE_PSA_CRYPTO */
if( ( ret = mbedtls_ssl_psk_derive_premaster( ssl,
ciphersuite_info->key_exchange ) ) != 0 )
{
MBEDTLS_SSL_DEBUG_RET( 1, "mbedtls_ssl_psk_derive_premaster", ret );
return( ret );
}
}
else
#endif /* MBEDTLS_KEY_EXCHANGE_PSK_ENABLED */
#if defined(MBEDTLS_KEY_EXCHANGE_RSA_PSK_ENABLED)
if( ciphersuite_info->key_exchange == MBEDTLS_KEY_EXCHANGE_RSA_PSK )
{
#if defined(MBEDTLS_SSL_ASYNC_PRIVATE)
if ( ssl->handshake->async_in_progress != 0 )
{
/* There is an asynchronous operation in progress to
* decrypt the encrypted premaster secret, so skip
* directly to resuming this operation. */
MBEDTLS_SSL_DEBUG_MSG( 3, ( "PSK identity already parsed" ) );
/* Update p to skip the PSK identity. ssl_parse_encrypted_pms
* won't actually use it, but maintain p anyway for robustness. */
p += ssl->conf->psk_identity_len + 2;
}
else
#endif /* MBEDTLS_SSL_ASYNC_PRIVATE */
if( ( ret = ssl_parse_client_psk_identity( ssl, &p, end ) ) != 0 )
{
MBEDTLS_SSL_DEBUG_RET( 1, ( "ssl_parse_client_psk_identity" ), ret );
return( ret );
}
#if defined(MBEDTLS_USE_PSA_CRYPTO)
/* Opaque PSKs are currently only supported for PSK-only. */
if( ssl_use_opaque_psk( ssl ) == 1 )
return( MBEDTLS_ERR_SSL_FEATURE_UNAVAILABLE );
#endif
if( ( ret = ssl_parse_encrypted_pms( ssl, p, end, 2 ) ) != 0 )
{
MBEDTLS_SSL_DEBUG_RET( 1, ( "ssl_parse_encrypted_pms" ), ret );
return( ret );
}
if( ( ret = mbedtls_ssl_psk_derive_premaster( ssl,
ciphersuite_info->key_exchange ) ) != 0 )
{
MBEDTLS_SSL_DEBUG_RET( 1, "mbedtls_ssl_psk_derive_premaster", ret );
return( ret );
}
}
else
#endif /* MBEDTLS_KEY_EXCHANGE_RSA_PSK_ENABLED */
#if defined(MBEDTLS_KEY_EXCHANGE_DHE_PSK_ENABLED)
if( ciphersuite_info->key_exchange == MBEDTLS_KEY_EXCHANGE_DHE_PSK )
{
if( ( ret = ssl_parse_client_psk_identity( ssl, &p, end ) ) != 0 )
{
MBEDTLS_SSL_DEBUG_RET( 1, ( "ssl_parse_client_psk_identity" ), ret );
return( ret );
}
if( ( ret = ssl_parse_client_dh_public( ssl, &p, end ) ) != 0 )
{
MBEDTLS_SSL_DEBUG_RET( 1, ( "ssl_parse_client_dh_public" ), ret );
return( ret );
}
#if defined(MBEDTLS_USE_PSA_CRYPTO)
/* Opaque PSKs are currently only supported for PSK-only. */
if( ssl_use_opaque_psk( ssl ) == 1 )
return( MBEDTLS_ERR_SSL_FEATURE_UNAVAILABLE );
#endif
if( p != end )
{
MBEDTLS_SSL_DEBUG_MSG( 1, ( "bad client key exchange" ) );
return( MBEDTLS_ERR_SSL_BAD_HS_CLIENT_KEY_EXCHANGE );
}
if( ( ret = mbedtls_ssl_psk_derive_premaster( ssl,
ciphersuite_info->key_exchange ) ) != 0 )
{
MBEDTLS_SSL_DEBUG_RET( 1, "mbedtls_ssl_psk_derive_premaster", ret );
return( ret );
}
}
else
#endif /* MBEDTLS_KEY_EXCHANGE_DHE_PSK_ENABLED */
#if defined(MBEDTLS_KEY_EXCHANGE_ECDHE_PSK_ENABLED)
if( ciphersuite_info->key_exchange == MBEDTLS_KEY_EXCHANGE_ECDHE_PSK )
{
if( ( ret = ssl_parse_client_psk_identity( ssl, &p, end ) ) != 0 )
{
MBEDTLS_SSL_DEBUG_RET( 1, ( "ssl_parse_client_psk_identity" ), ret );
return( ret );
}
if( ( ret = mbedtls_ecdh_read_public( &ssl->handshake->ecdh_ctx,
p, end - p ) ) != 0 )
{
MBEDTLS_SSL_DEBUG_RET( 1, "mbedtls_ecdh_read_public", ret );
return( MBEDTLS_ERR_SSL_BAD_HS_CLIENT_KEY_EXCHANGE_RP );
}
#if defined(MBEDTLS_USE_PSA_CRYPTO)
/* Opaque PSKs are currently only supported for PSK-only. */
if( ssl_use_opaque_psk( ssl ) == 1 )
return( MBEDTLS_ERR_SSL_FEATURE_UNAVAILABLE );
#endif
MBEDTLS_SSL_DEBUG_ECDH( 3, &ssl->handshake->ecdh_ctx,
MBEDTLS_DEBUG_ECDH_QP );
if( ( ret = mbedtls_ssl_psk_derive_premaster( ssl,
ciphersuite_info->key_exchange ) ) != 0 )
{
MBEDTLS_SSL_DEBUG_RET( 1, "mbedtls_ssl_psk_derive_premaster", ret );
return( ret );
}
}
else
#endif /* MBEDTLS_KEY_EXCHANGE_ECDHE_PSK_ENABLED */
#if defined(MBEDTLS_KEY_EXCHANGE_RSA_ENABLED)
if( ciphersuite_info->key_exchange == MBEDTLS_KEY_EXCHANGE_RSA )
{
if( ( ret = ssl_parse_encrypted_pms( ssl, p, end, 0 ) ) != 0 )
{
MBEDTLS_SSL_DEBUG_RET( 1, ( "ssl_parse_parse_encrypted_pms_secret" ), ret );
return( ret );
}
}
else
#endif /* MBEDTLS_KEY_EXCHANGE_RSA_ENABLED */
#if defined(MBEDTLS_KEY_EXCHANGE_ECJPAKE_ENABLED)
if( ciphersuite_info->key_exchange == MBEDTLS_KEY_EXCHANGE_ECJPAKE )
{
ret = mbedtls_ecjpake_read_round_two( &ssl->handshake->ecjpake_ctx,
p, end - p );
if( ret != 0 )
{
MBEDTLS_SSL_DEBUG_RET( 1, "mbedtls_ecjpake_read_round_two", ret );
return( MBEDTLS_ERR_SSL_BAD_HS_SERVER_KEY_EXCHANGE );
}
ret = mbedtls_ecjpake_derive_secret( &ssl->handshake->ecjpake_ctx,
ssl->handshake->premaster, 32, &ssl->handshake->pmslen,
ssl->conf->f_rng, ssl->conf->p_rng );
if( ret != 0 )
{
MBEDTLS_SSL_DEBUG_RET( 1, "mbedtls_ecjpake_derive_secret", ret );
return( ret );
}
}
else
#endif /* MBEDTLS_KEY_EXCHANGE_ECJPAKE_ENABLED */
{
MBEDTLS_SSL_DEBUG_MSG( 1, ( "should never happen" ) );
return( MBEDTLS_ERR_SSL_INTERNAL_ERROR );
}
if( ( ret = mbedtls_ssl_derive_keys( ssl ) ) != 0 )
{
MBEDTLS_SSL_DEBUG_RET( 1, "mbedtls_ssl_derive_keys", ret );
return( ret );
}
ssl->state++;
MBEDTLS_SSL_DEBUG_MSG( 2, ( "<= parse client key exchange" ) );
return( 0 );
}
#if !defined(MBEDTLS_KEY_EXCHANGE_CERT_REQ_ALLOWED_ENABLED)
static int ssl_parse_certificate_verify( mbedtls_ssl_context *ssl )
{
const mbedtls_ssl_ciphersuite_t *ciphersuite_info =
ssl->handshake->ciphersuite_info;
MBEDTLS_SSL_DEBUG_MSG( 2, ( "=> parse certificate verify" ) );
if( !mbedtls_ssl_ciphersuite_cert_req_allowed( ciphersuite_info ) )
{
MBEDTLS_SSL_DEBUG_MSG( 2, ( "<= skip parse certificate verify" ) );
ssl->state++;
return( 0 );
}
MBEDTLS_SSL_DEBUG_MSG( 1, ( "should never happen" ) );
return( MBEDTLS_ERR_SSL_INTERNAL_ERROR );
}
#else /* !MBEDTLS_KEY_EXCHANGE_CERT_REQ_ALLOWED_ENABLED */
static int ssl_parse_certificate_verify( mbedtls_ssl_context *ssl )
{
int ret = MBEDTLS_ERR_SSL_FEATURE_UNAVAILABLE;
size_t i, sig_len;
unsigned char hash[48];
unsigned char *hash_start = hash;
size_t hashlen;
#if defined(MBEDTLS_SSL_PROTO_TLS1_2)
mbedtls_pk_type_t pk_alg;
#endif
mbedtls_md_type_t md_alg;
const mbedtls_ssl_ciphersuite_t *ciphersuite_info =
ssl->handshake->ciphersuite_info;
mbedtls_pk_context * peer_pk;
MBEDTLS_SSL_DEBUG_MSG( 2, ( "=> parse certificate verify" ) );
if( !mbedtls_ssl_ciphersuite_cert_req_allowed( ciphersuite_info ) )
{
MBEDTLS_SSL_DEBUG_MSG( 2, ( "<= skip parse certificate verify" ) );
ssl->state++;
return( 0 );
}
#if defined(MBEDTLS_SSL_KEEP_PEER_CERTIFICATE)
if( ssl->session_negotiate->peer_cert == NULL )
{
MBEDTLS_SSL_DEBUG_MSG( 2, ( "<= skip parse certificate verify" ) );
ssl->state++;
return( 0 );
}
#else /* MBEDTLS_SSL_KEEP_PEER_CERTIFICATE */
if( ssl->session_negotiate->peer_cert_digest == NULL )
{
MBEDTLS_SSL_DEBUG_MSG( 2, ( "<= skip parse certificate verify" ) );
ssl->state++;
return( 0 );
}
#endif /* !MBEDTLS_SSL_KEEP_PEER_CERTIFICATE */
/* Read the message without adding it to the checksum */
ret = mbedtls_ssl_read_record( ssl, 0 /* no checksum update */ );
if( 0 != ret )
{
MBEDTLS_SSL_DEBUG_RET( 1, ( "mbedtls_ssl_read_record" ), ret );
return( ret );
}
ssl->state++;
/* Process the message contents */
if( ssl->in_msgtype != MBEDTLS_SSL_MSG_HANDSHAKE ||
ssl->in_msg[0] != MBEDTLS_SSL_HS_CERTIFICATE_VERIFY )
{
MBEDTLS_SSL_DEBUG_MSG( 1, ( "bad certificate verify message" ) );
return( MBEDTLS_ERR_SSL_BAD_HS_CERTIFICATE_VERIFY );
}
i = mbedtls_ssl_hs_hdr_len( ssl );
#if !defined(MBEDTLS_SSL_KEEP_PEER_CERTIFICATE)
peer_pk = &ssl->handshake->peer_pubkey;
#else /* !MBEDTLS_SSL_KEEP_PEER_CERTIFICATE */
if( ssl->session_negotiate->peer_cert == NULL )
{
/* Should never happen */
return( MBEDTLS_ERR_SSL_INTERNAL_ERROR );
}
peer_pk = &ssl->session_negotiate->peer_cert->pk;
#endif /* MBEDTLS_SSL_KEEP_PEER_CERTIFICATE */
/*
* struct {
* SignatureAndHashAlgorithm algorithm; -- TLS 1.2 only
* opaque signature<0..2^16-1>;
* } DigitallySigned;
*/
#if defined(MBEDTLS_SSL_PROTO_SSL3) || defined(MBEDTLS_SSL_PROTO_TLS1) || \
defined(MBEDTLS_SSL_PROTO_TLS1_1)
if( ssl->minor_ver != MBEDTLS_SSL_MINOR_VERSION_3 )
{
md_alg = MBEDTLS_MD_NONE;
hashlen = 36;
/* For ECDSA, use SHA-1, not MD-5 + SHA-1 */
if( mbedtls_pk_can_do( peer_pk, MBEDTLS_PK_ECDSA ) )
{
hash_start += 16;
hashlen -= 16;
md_alg = MBEDTLS_MD_SHA1;
}
}
else
#endif /* MBEDTLS_SSL_PROTO_SSL3 || MBEDTLS_SSL_PROTO_TLS1 ||
MBEDTLS_SSL_PROTO_TLS1_1 */
#if defined(MBEDTLS_SSL_PROTO_TLS1_2)
if( ssl->minor_ver == MBEDTLS_SSL_MINOR_VERSION_3 )
{
if( i + 2 > ssl->in_hslen )
{
MBEDTLS_SSL_DEBUG_MSG( 1, ( "bad certificate verify message" ) );
return( MBEDTLS_ERR_SSL_BAD_HS_CERTIFICATE_VERIFY );
}
/*
* Hash
*/
md_alg = mbedtls_ssl_md_alg_from_hash( ssl->in_msg[i] );
if( md_alg == MBEDTLS_MD_NONE || mbedtls_ssl_set_calc_verify_md( ssl, ssl->in_msg[i] ) )
{
MBEDTLS_SSL_DEBUG_MSG( 1, ( "peer not adhering to requested sig_alg"
" for verify message" ) );
return( MBEDTLS_ERR_SSL_BAD_HS_CERTIFICATE_VERIFY );
}
#if !defined(MBEDTLS_MD_SHA1)
if( MBEDTLS_MD_SHA1 == md_alg )
hash_start += 16;
#endif
/* Info from md_alg will be used instead */
hashlen = 0;
i++;
/*
* Signature
*/
if( ( pk_alg = mbedtls_ssl_pk_alg_from_sig( ssl->in_msg[i] ) )
== MBEDTLS_PK_NONE )
{
MBEDTLS_SSL_DEBUG_MSG( 1, ( "peer not adhering to requested sig_alg"
" for verify message" ) );
return( MBEDTLS_ERR_SSL_BAD_HS_CERTIFICATE_VERIFY );
}
/*
* Check the certificate's key type matches the signature alg
*/
if( !mbedtls_pk_can_do( peer_pk, pk_alg ) )
{
MBEDTLS_SSL_DEBUG_MSG( 1, ( "sig_alg doesn't match cert key" ) );
return( MBEDTLS_ERR_SSL_BAD_HS_CERTIFICATE_VERIFY );
}
i++;
}
else
#endif /* MBEDTLS_SSL_PROTO_TLS1_2 */
{
MBEDTLS_SSL_DEBUG_MSG( 1, ( "should never happen" ) );
return( MBEDTLS_ERR_SSL_INTERNAL_ERROR );
}
if( i + 2 > ssl->in_hslen )
{
MBEDTLS_SSL_DEBUG_MSG( 1, ( "bad certificate verify message" ) );
return( MBEDTLS_ERR_SSL_BAD_HS_CERTIFICATE_VERIFY );
}
sig_len = ( ssl->in_msg[i] << 8 ) | ssl->in_msg[i+1];
i += 2;
if( i + sig_len != ssl->in_hslen )
{
MBEDTLS_SSL_DEBUG_MSG( 1, ( "bad certificate verify message" ) );
return( MBEDTLS_ERR_SSL_BAD_HS_CERTIFICATE_VERIFY );
}
/* Calculate hash and verify signature */
{
size_t dummy_hlen;
ssl->handshake->calc_verify( ssl, hash, &dummy_hlen );
}
if( ( ret = mbedtls_pk_verify( peer_pk,
md_alg, hash_start, hashlen,
ssl->in_msg + i, sig_len ) ) != 0 )
{
MBEDTLS_SSL_DEBUG_RET( 1, "mbedtls_pk_verify", ret );
return( ret );
}
mbedtls_ssl_update_handshake_status( ssl );
MBEDTLS_SSL_DEBUG_MSG( 2, ( "<= parse certificate verify" ) );
return( ret );
}
#endif /* MBEDTLS_KEY_EXCHANGE_CERT_REQ_ALLOWED_ENABLED */
#if defined(MBEDTLS_SSL_SESSION_TICKETS)
static int ssl_write_new_session_ticket( mbedtls_ssl_context *ssl )
{
int ret = MBEDTLS_ERR_ERROR_CORRUPTION_DETECTED;
size_t tlen;
uint32_t lifetime;
MBEDTLS_SSL_DEBUG_MSG( 2, ( "=> write new session ticket" ) );
ssl->out_msgtype = MBEDTLS_SSL_MSG_HANDSHAKE;
ssl->out_msg[0] = MBEDTLS_SSL_HS_NEW_SESSION_TICKET;
/*
* struct {
* uint32 ticket_lifetime_hint;
* opaque ticket<0..2^16-1>;
* } NewSessionTicket;
*
* 4 . 7 ticket_lifetime_hint (0 = unspecified)
* 8 . 9 ticket_len (n)
* 10 . 9+n ticket content
*/
if( ( ret = ssl->conf->f_ticket_write( ssl->conf->p_ticket,
ssl->session_negotiate,
ssl->out_msg + 10,
ssl->out_msg + MBEDTLS_SSL_OUT_CONTENT_LEN,
&tlen, &lifetime ) ) != 0 )
{
MBEDTLS_SSL_DEBUG_RET( 1, "mbedtls_ssl_ticket_write", ret );
tlen = 0;
}
ssl->out_msg[4] = ( lifetime >> 24 ) & 0xFF;
ssl->out_msg[5] = ( lifetime >> 16 ) & 0xFF;
ssl->out_msg[6] = ( lifetime >> 8 ) & 0xFF;
ssl->out_msg[7] = ( lifetime ) & 0xFF;
ssl->out_msg[8] = (unsigned char)( ( tlen >> 8 ) & 0xFF );
ssl->out_msg[9] = (unsigned char)( ( tlen ) & 0xFF );
ssl->out_msglen = 10 + tlen;
/*
* Morally equivalent to updating ssl->state, but NewSessionTicket and
* ChangeCipherSpec share the same state.
*/
ssl->handshake->new_session_ticket = 0;
if( ( ret = mbedtls_ssl_write_handshake_msg( ssl ) ) != 0 )
{
MBEDTLS_SSL_DEBUG_RET( 1, "mbedtls_ssl_write_handshake_msg", ret );
return( ret );
}
MBEDTLS_SSL_DEBUG_MSG( 2, ( "<= write new session ticket" ) );
return( 0 );
}
#endif /* MBEDTLS_SSL_SESSION_TICKETS */
/*
* SSL handshake -- server side -- single step
*/
int mbedtls_ssl_handshake_server_step( mbedtls_ssl_context *ssl )
{
int ret = 0;
if( ssl->state == MBEDTLS_SSL_HANDSHAKE_OVER || ssl->handshake == NULL )
return( MBEDTLS_ERR_SSL_BAD_INPUT_DATA );
MBEDTLS_SSL_DEBUG_MSG( 2, ( "server state: %d", ssl->state ) );
if( ( ret = mbedtls_ssl_flush_output( ssl ) ) != 0 )
return( ret );
#if defined(MBEDTLS_SSL_PROTO_DTLS)
if( ssl->conf->transport == MBEDTLS_SSL_TRANSPORT_DATAGRAM &&
ssl->handshake->retransmit_state == MBEDTLS_SSL_RETRANS_SENDING )
{
if( ( ret = mbedtls_ssl_flight_transmit( ssl ) ) != 0 )
return( ret );
}
#endif /* MBEDTLS_SSL_PROTO_DTLS */
switch( ssl->state )
{
case MBEDTLS_SSL_HELLO_REQUEST:
ssl->state = MBEDTLS_SSL_CLIENT_HELLO;
break;
/*
* <== ClientHello
*/
case MBEDTLS_SSL_CLIENT_HELLO:
ret = ssl_parse_client_hello( ssl );
break;
#if defined(MBEDTLS_SSL_PROTO_DTLS)
case MBEDTLS_SSL_SERVER_HELLO_VERIFY_REQUEST_SENT:
return( MBEDTLS_ERR_SSL_HELLO_VERIFY_REQUIRED );
#endif
/*
* ==> ServerHello
* Certificate
* ( ServerKeyExchange )
* ( CertificateRequest )
* ServerHelloDone
*/
case MBEDTLS_SSL_SERVER_HELLO:
ret = ssl_write_server_hello( ssl );
break;
case MBEDTLS_SSL_SERVER_CERTIFICATE:
ret = mbedtls_ssl_write_certificate( ssl );
break;
case MBEDTLS_SSL_SERVER_KEY_EXCHANGE:
ret = ssl_write_server_key_exchange( ssl );
break;
case MBEDTLS_SSL_CERTIFICATE_REQUEST:
ret = ssl_write_certificate_request( ssl );
break;
case MBEDTLS_SSL_SERVER_HELLO_DONE:
ret = ssl_write_server_hello_done( ssl );
break;
/*
* <== ( Certificate/Alert )
* ClientKeyExchange
* ( CertificateVerify )
* ChangeCipherSpec
* Finished
*/
case MBEDTLS_SSL_CLIENT_CERTIFICATE:
ret = mbedtls_ssl_parse_certificate( ssl );
break;
case MBEDTLS_SSL_CLIENT_KEY_EXCHANGE:
ret = ssl_parse_client_key_exchange( ssl );
break;
case MBEDTLS_SSL_CERTIFICATE_VERIFY:
ret = ssl_parse_certificate_verify( ssl );
break;
case MBEDTLS_SSL_CLIENT_CHANGE_CIPHER_SPEC:
ret = mbedtls_ssl_parse_change_cipher_spec( ssl );
break;
case MBEDTLS_SSL_CLIENT_FINISHED:
ret = mbedtls_ssl_parse_finished( ssl );
break;
/*
* ==> ( NewSessionTicket )
* ChangeCipherSpec
* Finished
*/
case MBEDTLS_SSL_SERVER_CHANGE_CIPHER_SPEC:
#if defined(MBEDTLS_SSL_SESSION_TICKETS)
if( ssl->handshake->new_session_ticket != 0 )
ret = ssl_write_new_session_ticket( ssl );
else
#endif
ret = mbedtls_ssl_write_change_cipher_spec( ssl );
break;
case MBEDTLS_SSL_SERVER_FINISHED:
ret = mbedtls_ssl_write_finished( ssl );
break;
case MBEDTLS_SSL_FLUSH_BUFFERS:
MBEDTLS_SSL_DEBUG_MSG( 2, ( "handshake: done" ) );
ssl->state = MBEDTLS_SSL_HANDSHAKE_WRAPUP;
break;
case MBEDTLS_SSL_HANDSHAKE_WRAPUP:
mbedtls_ssl_handshake_wrapup( ssl );
break;
default:
MBEDTLS_SSL_DEBUG_MSG( 1, ( "invalid state %d", ssl->state ) );
return( MBEDTLS_ERR_SSL_BAD_INPUT_DATA );
}
return( ret );
}
#endif /* MBEDTLS_SSL_SRV_C */
|
0 | repos/gpt4all.zig/src/zig-libcurl/zig-mbedtls/mbedtls | repos/gpt4all.zig/src/zig-libcurl/zig-mbedtls/mbedtls/library/nist_kw.c | /*
* Implementation of NIST SP 800-38F key wrapping, supporting KW and KWP modes
* only
*
* Copyright The Mbed TLS Contributors
* SPDX-License-Identifier: Apache-2.0
*
* 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.
*/
/*
* Definition of Key Wrapping:
* https://nvlpubs.nist.gov/nistpubs/SpecialPublications/NIST.SP.800-38F.pdf
* RFC 3394 "Advanced Encryption Standard (AES) Key Wrap Algorithm"
* RFC 5649 "Advanced Encryption Standard (AES) Key Wrap with Padding Algorithm"
*
* Note: RFC 3394 defines different methodology for intermediate operations for
* the wrapping and unwrapping operation than the definition in NIST SP 800-38F.
*/
#include "common.h"
#if defined(MBEDTLS_NIST_KW_C)
#include "mbedtls/nist_kw.h"
#include "mbedtls/platform_util.h"
#include "mbedtls/error.h"
#include <stdint.h>
#include <string.h>
#if defined(MBEDTLS_SELF_TEST) && defined(MBEDTLS_AES_C)
#if defined(MBEDTLS_PLATFORM_C)
#include "mbedtls/platform.h"
#else
#include <stdio.h>
#define mbedtls_printf printf
#endif /* MBEDTLS_PLATFORM_C */
#endif /* MBEDTLS_SELF_TEST && MBEDTLS_AES_C */
#if !defined(MBEDTLS_NIST_KW_ALT)
#define KW_SEMIBLOCK_LENGTH 8
#define MIN_SEMIBLOCKS_COUNT 3
/* constant-time buffer comparison */
static inline unsigned char mbedtls_nist_kw_safer_memcmp( const void *a, const void *b, size_t n )
{
size_t i;
volatile const unsigned char *A = (volatile const unsigned char *) a;
volatile const unsigned char *B = (volatile const unsigned char *) b;
volatile unsigned char diff = 0;
for( i = 0; i < n; i++ )
{
/* Read volatile data in order before computing diff.
* This avoids IAR compiler warning:
* 'the order of volatile accesses is undefined ..' */
unsigned char x = A[i], y = B[i];
diff |= x ^ y;
}
return( diff );
}
/*! The 64-bit default integrity check value (ICV) for KW mode. */
static const unsigned char NIST_KW_ICV1[] = {0xA6, 0xA6, 0xA6, 0xA6, 0xA6, 0xA6, 0xA6, 0xA6};
/*! The 32-bit default integrity check value (ICV) for KWP mode. */
static const unsigned char NIST_KW_ICV2[] = {0xA6, 0x59, 0x59, 0xA6};
#ifndef GET_UINT32_BE
#define GET_UINT32_BE(n,b,i) \
do { \
(n) = ( (uint32_t) (b)[(i) ] << 24 ) \
| ( (uint32_t) (b)[(i) + 1] << 16 ) \
| ( (uint32_t) (b)[(i) + 2] << 8 ) \
| ( (uint32_t) (b)[(i) + 3] ); \
} while( 0 )
#endif
#ifndef PUT_UINT32_BE
#define PUT_UINT32_BE(n,b,i) \
do { \
(b)[(i) ] = (unsigned char) ( (n) >> 24 ); \
(b)[(i) + 1] = (unsigned char) ( (n) >> 16 ); \
(b)[(i) + 2] = (unsigned char) ( (n) >> 8 ); \
(b)[(i) + 3] = (unsigned char) ( (n) ); \
} while( 0 )
#endif
/*
* Initialize context
*/
void mbedtls_nist_kw_init( mbedtls_nist_kw_context *ctx )
{
memset( ctx, 0, sizeof( mbedtls_nist_kw_context ) );
}
int mbedtls_nist_kw_setkey( mbedtls_nist_kw_context *ctx,
mbedtls_cipher_id_t cipher,
const unsigned char *key,
unsigned int keybits,
const int is_wrap )
{
int ret = MBEDTLS_ERR_ERROR_CORRUPTION_DETECTED;
const mbedtls_cipher_info_t *cipher_info;
cipher_info = mbedtls_cipher_info_from_values( cipher,
keybits,
MBEDTLS_MODE_ECB );
if( cipher_info == NULL )
return( MBEDTLS_ERR_CIPHER_BAD_INPUT_DATA );
if( cipher_info->block_size != 16 )
return( MBEDTLS_ERR_CIPHER_BAD_INPUT_DATA );
/*
* SP 800-38F currently defines AES cipher as the only block cipher allowed:
* "For KW and KWP, the underlying block cipher shall be approved, and the
* block size shall be 128 bits. Currently, the AES block cipher, with key
* lengths of 128, 192, or 256 bits, is the only block cipher that fits
* this profile."
* Currently we don't support other 128 bit block ciphers for key wrapping,
* such as Camellia and Aria.
*/
if( cipher != MBEDTLS_CIPHER_ID_AES )
return( MBEDTLS_ERR_CIPHER_FEATURE_UNAVAILABLE );
mbedtls_cipher_free( &ctx->cipher_ctx );
if( ( ret = mbedtls_cipher_setup( &ctx->cipher_ctx, cipher_info ) ) != 0 )
return( ret );
if( ( ret = mbedtls_cipher_setkey( &ctx->cipher_ctx, key, keybits,
is_wrap ? MBEDTLS_ENCRYPT :
MBEDTLS_DECRYPT )
) != 0 )
{
return( ret );
}
return( 0 );
}
/*
* Free context
*/
void mbedtls_nist_kw_free( mbedtls_nist_kw_context *ctx )
{
mbedtls_cipher_free( &ctx->cipher_ctx );
mbedtls_platform_zeroize( ctx, sizeof( mbedtls_nist_kw_context ) );
}
/*
* Helper function for Xoring the uint64_t "t" with the encrypted A.
* Defined in NIST SP 800-38F section 6.1
*/
static void calc_a_xor_t( unsigned char A[KW_SEMIBLOCK_LENGTH], uint64_t t )
{
size_t i = 0;
for( i = 0; i < sizeof( t ); i++ )
{
A[i] ^= ( t >> ( ( sizeof( t ) - 1 - i ) * 8 ) ) & 0xff;
}
}
/*
* KW-AE as defined in SP 800-38F section 6.2
* KWP-AE as defined in SP 800-38F section 6.3
*/
int mbedtls_nist_kw_wrap( mbedtls_nist_kw_context *ctx,
mbedtls_nist_kw_mode_t mode,
const unsigned char *input, size_t in_len,
unsigned char *output, size_t *out_len, size_t out_size )
{
int ret = 0;
size_t semiblocks = 0;
size_t s;
size_t olen, padlen = 0;
uint64_t t = 0;
unsigned char outbuff[KW_SEMIBLOCK_LENGTH * 2];
unsigned char inbuff[KW_SEMIBLOCK_LENGTH * 2];
*out_len = 0;
/*
* Generate the String to work on
*/
if( mode == MBEDTLS_KW_MODE_KW )
{
if( out_size < in_len + KW_SEMIBLOCK_LENGTH )
{
return( MBEDTLS_ERR_CIPHER_BAD_INPUT_DATA );
}
/*
* According to SP 800-38F Table 1, the plaintext length for KW
* must be between 2 to 2^54-1 semiblocks inclusive.
*/
if( in_len < 16 ||
#if SIZE_MAX > 0x1FFFFFFFFFFFFF8
in_len > 0x1FFFFFFFFFFFFF8 ||
#endif
in_len % KW_SEMIBLOCK_LENGTH != 0 )
{
return( MBEDTLS_ERR_CIPHER_BAD_INPUT_DATA );
}
memcpy( output, NIST_KW_ICV1, KW_SEMIBLOCK_LENGTH );
memmove( output + KW_SEMIBLOCK_LENGTH, input, in_len );
}
else
{
if( in_len % 8 != 0 )
{
padlen = ( 8 - ( in_len % 8 ) );
}
if( out_size < in_len + KW_SEMIBLOCK_LENGTH + padlen )
{
return( MBEDTLS_ERR_CIPHER_BAD_INPUT_DATA );
}
/*
* According to SP 800-38F Table 1, the plaintext length for KWP
* must be between 1 and 2^32-1 octets inclusive.
*/
if( in_len < 1
#if SIZE_MAX > 0xFFFFFFFF
|| in_len > 0xFFFFFFFF
#endif
)
{
return( MBEDTLS_ERR_CIPHER_BAD_INPUT_DATA );
}
memcpy( output, NIST_KW_ICV2, KW_SEMIBLOCK_LENGTH / 2 );
PUT_UINT32_BE( ( in_len & 0xffffffff ), output,
KW_SEMIBLOCK_LENGTH / 2 );
memcpy( output + KW_SEMIBLOCK_LENGTH, input, in_len );
memset( output + KW_SEMIBLOCK_LENGTH + in_len, 0, padlen );
}
semiblocks = ( ( in_len + padlen ) / KW_SEMIBLOCK_LENGTH ) + 1;
s = 6 * ( semiblocks - 1 );
if( mode == MBEDTLS_KW_MODE_KWP
&& in_len <= KW_SEMIBLOCK_LENGTH )
{
memcpy( inbuff, output, 16 );
ret = mbedtls_cipher_update( &ctx->cipher_ctx,
inbuff, 16, output, &olen );
if( ret != 0 )
goto cleanup;
}
else
{
unsigned char *R2 = output + KW_SEMIBLOCK_LENGTH;
unsigned char *A = output;
/*
* Do the wrapping function W, as defined in RFC 3394 section 2.2.1
*/
if( semiblocks < MIN_SEMIBLOCKS_COUNT )
{
ret = MBEDTLS_ERR_CIPHER_BAD_INPUT_DATA;
goto cleanup;
}
/* Calculate intermediate values */
for( t = 1; t <= s; t++ )
{
memcpy( inbuff, A, KW_SEMIBLOCK_LENGTH );
memcpy( inbuff + KW_SEMIBLOCK_LENGTH, R2, KW_SEMIBLOCK_LENGTH );
ret = mbedtls_cipher_update( &ctx->cipher_ctx,
inbuff, 16, outbuff, &olen );
if( ret != 0 )
goto cleanup;
memcpy( A, outbuff, KW_SEMIBLOCK_LENGTH );
calc_a_xor_t( A, t );
memcpy( R2, outbuff + KW_SEMIBLOCK_LENGTH, KW_SEMIBLOCK_LENGTH );
R2 += KW_SEMIBLOCK_LENGTH;
if( R2 >= output + ( semiblocks * KW_SEMIBLOCK_LENGTH ) )
R2 = output + KW_SEMIBLOCK_LENGTH;
}
}
*out_len = semiblocks * KW_SEMIBLOCK_LENGTH;
cleanup:
if( ret != 0)
{
memset( output, 0, semiblocks * KW_SEMIBLOCK_LENGTH );
}
mbedtls_platform_zeroize( inbuff, KW_SEMIBLOCK_LENGTH * 2 );
mbedtls_platform_zeroize( outbuff, KW_SEMIBLOCK_LENGTH * 2 );
return( ret );
}
/*
* W-1 function as defined in RFC 3394 section 2.2.2
* This function assumes the following:
* 1. Output buffer is at least of size ( semiblocks - 1 ) * KW_SEMIBLOCK_LENGTH.
* 2. The input buffer is of size semiblocks * KW_SEMIBLOCK_LENGTH.
* 3. Minimal number of semiblocks is 3.
* 4. A is a buffer to hold the first semiblock of the input buffer.
*/
static int unwrap( mbedtls_nist_kw_context *ctx,
const unsigned char *input, size_t semiblocks,
unsigned char A[KW_SEMIBLOCK_LENGTH],
unsigned char *output, size_t* out_len )
{
int ret = 0;
const size_t s = 6 * ( semiblocks - 1 );
size_t olen;
uint64_t t = 0;
unsigned char outbuff[KW_SEMIBLOCK_LENGTH * 2];
unsigned char inbuff[KW_SEMIBLOCK_LENGTH * 2];
unsigned char *R = NULL;
*out_len = 0;
if( semiblocks < MIN_SEMIBLOCKS_COUNT )
{
return( MBEDTLS_ERR_CIPHER_BAD_INPUT_DATA );
}
memcpy( A, input, KW_SEMIBLOCK_LENGTH );
memmove( output, input + KW_SEMIBLOCK_LENGTH, ( semiblocks - 1 ) * KW_SEMIBLOCK_LENGTH );
R = output + ( semiblocks - 2 ) * KW_SEMIBLOCK_LENGTH;
/* Calculate intermediate values */
for( t = s; t >= 1; t-- )
{
calc_a_xor_t( A, t );
memcpy( inbuff, A, KW_SEMIBLOCK_LENGTH );
memcpy( inbuff + KW_SEMIBLOCK_LENGTH, R, KW_SEMIBLOCK_LENGTH );
ret = mbedtls_cipher_update( &ctx->cipher_ctx,
inbuff, 16, outbuff, &olen );
if( ret != 0 )
goto cleanup;
memcpy( A, outbuff, KW_SEMIBLOCK_LENGTH );
/* Set R as LSB64 of outbuff */
memcpy( R, outbuff + KW_SEMIBLOCK_LENGTH, KW_SEMIBLOCK_LENGTH );
if( R == output )
R = output + ( semiblocks - 2 ) * KW_SEMIBLOCK_LENGTH;
else
R -= KW_SEMIBLOCK_LENGTH;
}
*out_len = ( semiblocks - 1 ) * KW_SEMIBLOCK_LENGTH;
cleanup:
if( ret != 0)
memset( output, 0, ( semiblocks - 1 ) * KW_SEMIBLOCK_LENGTH );
mbedtls_platform_zeroize( inbuff, sizeof( inbuff ) );
mbedtls_platform_zeroize( outbuff, sizeof( outbuff ) );
return( ret );
}
/*
* KW-AD as defined in SP 800-38F section 6.2
* KWP-AD as defined in SP 800-38F section 6.3
*/
int mbedtls_nist_kw_unwrap( mbedtls_nist_kw_context *ctx,
mbedtls_nist_kw_mode_t mode,
const unsigned char *input, size_t in_len,
unsigned char *output, size_t *out_len, size_t out_size )
{
int ret = 0;
size_t i, olen;
unsigned char A[KW_SEMIBLOCK_LENGTH];
unsigned char diff, bad_padding = 0;
*out_len = 0;
if( out_size < in_len - KW_SEMIBLOCK_LENGTH )
{
return( MBEDTLS_ERR_CIPHER_BAD_INPUT_DATA );
}
if( mode == MBEDTLS_KW_MODE_KW )
{
/*
* According to SP 800-38F Table 1, the ciphertext length for KW
* must be between 3 to 2^54 semiblocks inclusive.
*/
if( in_len < 24 ||
#if SIZE_MAX > 0x200000000000000
in_len > 0x200000000000000 ||
#endif
in_len % KW_SEMIBLOCK_LENGTH != 0 )
{
return( MBEDTLS_ERR_CIPHER_BAD_INPUT_DATA );
}
ret = unwrap( ctx, input, in_len / KW_SEMIBLOCK_LENGTH,
A, output, out_len );
if( ret != 0 )
goto cleanup;
/* Check ICV in "constant-time" */
diff = mbedtls_nist_kw_safer_memcmp( NIST_KW_ICV1, A, KW_SEMIBLOCK_LENGTH );
if( diff != 0 )
{
ret = MBEDTLS_ERR_CIPHER_AUTH_FAILED;
goto cleanup;
}
}
else if( mode == MBEDTLS_KW_MODE_KWP )
{
size_t padlen = 0;
uint32_t Plen;
/*
* According to SP 800-38F Table 1, the ciphertext length for KWP
* must be between 2 to 2^29 semiblocks inclusive.
*/
if( in_len < KW_SEMIBLOCK_LENGTH * 2 ||
#if SIZE_MAX > 0x100000000
in_len > 0x100000000 ||
#endif
in_len % KW_SEMIBLOCK_LENGTH != 0 )
{
return( MBEDTLS_ERR_CIPHER_BAD_INPUT_DATA );
}
if( in_len == KW_SEMIBLOCK_LENGTH * 2 )
{
unsigned char outbuff[KW_SEMIBLOCK_LENGTH * 2];
ret = mbedtls_cipher_update( &ctx->cipher_ctx,
input, 16, outbuff, &olen );
if( ret != 0 )
goto cleanup;
memcpy( A, outbuff, KW_SEMIBLOCK_LENGTH );
memcpy( output, outbuff + KW_SEMIBLOCK_LENGTH, KW_SEMIBLOCK_LENGTH );
mbedtls_platform_zeroize( outbuff, sizeof( outbuff ) );
*out_len = KW_SEMIBLOCK_LENGTH;
}
else
{
/* in_len >= KW_SEMIBLOCK_LENGTH * 3 */
ret = unwrap( ctx, input, in_len / KW_SEMIBLOCK_LENGTH,
A, output, out_len );
if( ret != 0 )
goto cleanup;
}
/* Check ICV in "constant-time" */
diff = mbedtls_nist_kw_safer_memcmp( NIST_KW_ICV2, A, KW_SEMIBLOCK_LENGTH / 2 );
if( diff != 0 )
{
ret = MBEDTLS_ERR_CIPHER_AUTH_FAILED;
}
GET_UINT32_BE( Plen, A, KW_SEMIBLOCK_LENGTH / 2 );
/*
* Plen is the length of the plaintext, when the input is valid.
* If Plen is larger than the plaintext and padding, padlen will be
* larger than 8, because of the type wrap around.
*/
padlen = in_len - KW_SEMIBLOCK_LENGTH - Plen;
if ( padlen > 7 )
{
padlen &= 7;
ret = MBEDTLS_ERR_CIPHER_AUTH_FAILED;
}
/* Check padding in "constant-time" */
for( diff = 0, i = 0; i < KW_SEMIBLOCK_LENGTH; i++ )
{
if( i >= KW_SEMIBLOCK_LENGTH - padlen )
diff |= output[*out_len - KW_SEMIBLOCK_LENGTH + i];
else
bad_padding |= output[*out_len - KW_SEMIBLOCK_LENGTH + i];
}
if( diff != 0 )
{
ret = MBEDTLS_ERR_CIPHER_AUTH_FAILED;
}
if( ret != 0 )
{
goto cleanup;
}
memset( output + Plen, 0, padlen );
*out_len = Plen;
}
else
{
ret = MBEDTLS_ERR_CIPHER_FEATURE_UNAVAILABLE;
goto cleanup;
}
cleanup:
if( ret != 0 )
{
memset( output, 0, *out_len );
*out_len = 0;
}
mbedtls_platform_zeroize( &bad_padding, sizeof( bad_padding) );
mbedtls_platform_zeroize( &diff, sizeof( diff ) );
mbedtls_platform_zeroize( A, sizeof( A ) );
return( ret );
}
#endif /* !MBEDTLS_NIST_KW_ALT */
#if defined(MBEDTLS_SELF_TEST) && defined(MBEDTLS_AES_C)
#define KW_TESTS 3
/*
* Test vectors taken from NIST
* https://csrc.nist.gov/Projects/Cryptographic-Algorithm-Validation-Program/CAVP-TESTING-BLOCK-CIPHER-MODES#KW
*/
static const unsigned int key_len[KW_TESTS] = { 16, 24, 32 };
static const unsigned char kw_key[KW_TESTS][32] = {
{ 0x75, 0x75, 0xda, 0x3a, 0x93, 0x60, 0x7c, 0xc2,
0xbf, 0xd8, 0xce, 0xc7, 0xaa, 0xdf, 0xd9, 0xa6 },
{ 0x2d, 0x85, 0x26, 0x08, 0x1d, 0x02, 0xfb, 0x5b,
0x85, 0xf6, 0x9a, 0xc2, 0x86, 0xec, 0xd5, 0x7d,
0x40, 0xdf, 0x5d, 0xf3, 0x49, 0x47, 0x44, 0xd3 },
{ 0x11, 0x2a, 0xd4, 0x1b, 0x48, 0x56, 0xc7, 0x25,
0x4a, 0x98, 0x48, 0xd3, 0x0f, 0xdd, 0x78, 0x33,
0x5b, 0x03, 0x9a, 0x48, 0xa8, 0x96, 0x2c, 0x4d,
0x1c, 0xb7, 0x8e, 0xab, 0xd5, 0xda, 0xd7, 0x88 }
};
static const unsigned char kw_msg[KW_TESTS][40] = {
{ 0x42, 0x13, 0x6d, 0x3c, 0x38, 0x4a, 0x3e, 0xea,
0xc9, 0x5a, 0x06, 0x6f, 0xd2, 0x8f, 0xed, 0x3f },
{ 0x95, 0xc1, 0x1b, 0xf5, 0x35, 0x3a, 0xfe, 0xdb,
0x98, 0xfd, 0xd6, 0xc8, 0xca, 0x6f, 0xdb, 0x6d,
0xa5, 0x4b, 0x74, 0xb4, 0x99, 0x0f, 0xdc, 0x45,
0xc0, 0x9d, 0x15, 0x8f, 0x51, 0xce, 0x62, 0x9d,
0xe2, 0xaf, 0x26, 0xe3, 0x25, 0x0e, 0x6b, 0x4c },
{ 0x1b, 0x20, 0xbf, 0x19, 0x90, 0xb0, 0x65, 0xd7,
0x98, 0xe1, 0xb3, 0x22, 0x64, 0xad, 0x50, 0xa8,
0x74, 0x74, 0x92, 0xba, 0x09, 0xa0, 0x4d, 0xd1 }
};
static const size_t kw_msg_len[KW_TESTS] = { 16, 40, 24 };
static const size_t kw_out_len[KW_TESTS] = { 24, 48, 32 };
static const unsigned char kw_res[KW_TESTS][48] = {
{ 0x03, 0x1f, 0x6b, 0xd7, 0xe6, 0x1e, 0x64, 0x3d,
0xf6, 0x85, 0x94, 0x81, 0x6f, 0x64, 0xca, 0xa3,
0xf5, 0x6f, 0xab, 0xea, 0x25, 0x48, 0xf5, 0xfb },
{ 0x44, 0x3c, 0x6f, 0x15, 0x09, 0x83, 0x71, 0x91,
0x3e, 0x5c, 0x81, 0x4c, 0xa1, 0xa0, 0x42, 0xec,
0x68, 0x2f, 0x7b, 0x13, 0x6d, 0x24, 0x3a, 0x4d,
0x6c, 0x42, 0x6f, 0xc6, 0x97, 0x15, 0x63, 0xe8,
0xa1, 0x4a, 0x55, 0x8e, 0x09, 0x64, 0x16, 0x19,
0xbf, 0x03, 0xfc, 0xaf, 0x90, 0xb1, 0xfc, 0x2d },
{ 0xba, 0x8a, 0x25, 0x9a, 0x47, 0x1b, 0x78, 0x7d,
0xd5, 0xd5, 0x40, 0xec, 0x25, 0xd4, 0x3d, 0x87,
0x20, 0x0f, 0xda, 0xdc, 0x6d, 0x1f, 0x05, 0xd9,
0x16, 0x58, 0x4f, 0xa9, 0xf6, 0xcb, 0xf5, 0x12 }
};
static const unsigned char kwp_key[KW_TESTS][32] = {
{ 0x78, 0x65, 0xe2, 0x0f, 0x3c, 0x21, 0x65, 0x9a,
0xb4, 0x69, 0x0b, 0x62, 0x9c, 0xdf, 0x3c, 0xc4 },
{ 0xf5, 0xf8, 0x96, 0xa3, 0xbd, 0x2f, 0x4a, 0x98,
0x23, 0xef, 0x16, 0x2b, 0x00, 0xb8, 0x05, 0xd7,
0xde, 0x1e, 0xa4, 0x66, 0x26, 0x96, 0xa2, 0x58 },
{ 0x95, 0xda, 0x27, 0x00, 0xca, 0x6f, 0xd9, 0xa5,
0x25, 0x54, 0xee, 0x2a, 0x8d, 0xf1, 0x38, 0x6f,
0x5b, 0x94, 0xa1, 0xa6, 0x0e, 0xd8, 0xa4, 0xae,
0xf6, 0x0a, 0x8d, 0x61, 0xab, 0x5f, 0x22, 0x5a }
};
static const unsigned char kwp_msg[KW_TESTS][31] = {
{ 0xbd, 0x68, 0x43, 0xd4, 0x20, 0x37, 0x8d, 0xc8,
0x96 },
{ 0x6c, 0xcd, 0xd5, 0x85, 0x18, 0x40, 0x97, 0xeb,
0xd5, 0xc3, 0xaf, 0x3e, 0x47, 0xd0, 0x2c, 0x19,
0x14, 0x7b, 0x4d, 0x99, 0x5f, 0x96, 0x43, 0x66,
0x91, 0x56, 0x75, 0x8c, 0x13, 0x16, 0x8f },
{ 0xd1 }
};
static const size_t kwp_msg_len[KW_TESTS] = { 9, 31, 1 };
static const unsigned char kwp_res[KW_TESTS][48] = {
{ 0x41, 0xec, 0xa9, 0x56, 0xd4, 0xaa, 0x04, 0x7e,
0xb5, 0xcf, 0x4e, 0xfe, 0x65, 0x96, 0x61, 0xe7,
0x4d, 0xb6, 0xf8, 0xc5, 0x64, 0xe2, 0x35, 0x00 },
{ 0x4e, 0x9b, 0xc2, 0xbc, 0xbc, 0x6c, 0x1e, 0x13,
0xd3, 0x35, 0xbc, 0xc0, 0xf7, 0x73, 0x6a, 0x88,
0xfa, 0x87, 0x53, 0x66, 0x15, 0xbb, 0x8e, 0x63,
0x8b, 0xcc, 0x81, 0x66, 0x84, 0x68, 0x17, 0x90,
0x67, 0xcf, 0xa9, 0x8a, 0x9d, 0x0e, 0x33, 0x26 },
{ 0x06, 0xba, 0x7a, 0xe6, 0xf3, 0x24, 0x8c, 0xfd,
0xcf, 0x26, 0x75, 0x07, 0xfa, 0x00, 0x1b, 0xc4 }
};
static const size_t kwp_out_len[KW_TESTS] = { 24, 40, 16 };
int mbedtls_nist_kw_self_test( int verbose )
{
mbedtls_nist_kw_context ctx;
unsigned char out[48];
size_t olen;
int i;
int ret = 0;
mbedtls_nist_kw_init( &ctx );
for( i = 0; i < KW_TESTS; i++ )
{
if( verbose != 0 )
mbedtls_printf( " KW-AES-%u ", (unsigned int) key_len[i] * 8 );
ret = mbedtls_nist_kw_setkey( &ctx, MBEDTLS_CIPHER_ID_AES,
kw_key[i], key_len[i] * 8, 1 );
if( ret != 0 )
{
if( verbose != 0 )
mbedtls_printf( " KW: setup failed " );
goto end;
}
ret = mbedtls_nist_kw_wrap( &ctx, MBEDTLS_KW_MODE_KW, kw_msg[i],
kw_msg_len[i], out, &olen, sizeof( out ) );
if( ret != 0 || kw_out_len[i] != olen ||
memcmp( out, kw_res[i], kw_out_len[i] ) != 0 )
{
if( verbose != 0 )
mbedtls_printf( "failed. ");
ret = 1;
goto end;
}
if( ( ret = mbedtls_nist_kw_setkey( &ctx, MBEDTLS_CIPHER_ID_AES,
kw_key[i], key_len[i] * 8, 0 ) )
!= 0 )
{
if( verbose != 0 )
mbedtls_printf( " KW: setup failed ");
goto end;
}
ret = mbedtls_nist_kw_unwrap( &ctx, MBEDTLS_KW_MODE_KW,
out, olen, out, &olen, sizeof( out ) );
if( ret != 0 || olen != kw_msg_len[i] ||
memcmp( out, kw_msg[i], kw_msg_len[i] ) != 0 )
{
if( verbose != 0 )
mbedtls_printf( "failed\n" );
ret = 1;
goto end;
}
if( verbose != 0 )
mbedtls_printf( " passed\n" );
}
for( i = 0; i < KW_TESTS; i++ )
{
olen = sizeof( out );
if( verbose != 0 )
mbedtls_printf( " KWP-AES-%u ", (unsigned int) key_len[i] * 8 );
ret = mbedtls_nist_kw_setkey( &ctx, MBEDTLS_CIPHER_ID_AES, kwp_key[i],
key_len[i] * 8, 1 );
if( ret != 0 )
{
if( verbose != 0 )
mbedtls_printf( " KWP: setup failed " );
goto end;
}
ret = mbedtls_nist_kw_wrap( &ctx, MBEDTLS_KW_MODE_KWP, kwp_msg[i],
kwp_msg_len[i], out, &olen, sizeof( out ) );
if( ret != 0 || kwp_out_len[i] != olen ||
memcmp( out, kwp_res[i], kwp_out_len[i] ) != 0 )
{
if( verbose != 0 )
mbedtls_printf( "failed. ");
ret = 1;
goto end;
}
if( ( ret = mbedtls_nist_kw_setkey( &ctx, MBEDTLS_CIPHER_ID_AES,
kwp_key[i], key_len[i] * 8, 0 ) )
!= 0 )
{
if( verbose != 0 )
mbedtls_printf( " KWP: setup failed ");
goto end;
}
ret = mbedtls_nist_kw_unwrap( &ctx, MBEDTLS_KW_MODE_KWP, out,
olen, out, &olen, sizeof( out ) );
if( ret != 0 || olen != kwp_msg_len[i] ||
memcmp( out, kwp_msg[i], kwp_msg_len[i] ) != 0 )
{
if( verbose != 0 )
mbedtls_printf( "failed. ");
ret = 1;
goto end;
}
if( verbose != 0 )
mbedtls_printf( " passed\n" );
}
end:
mbedtls_nist_kw_free( &ctx );
if( verbose != 0 )
mbedtls_printf( "\n" );
return( ret );
}
#endif /* MBEDTLS_SELF_TEST && MBEDTLS_AES_C */
#endif /* MBEDTLS_NIST_KW_C */
|
0 | repos/gpt4all.zig/src/zig-libcurl/zig-mbedtls/mbedtls | repos/gpt4all.zig/src/zig-libcurl/zig-mbedtls/mbedtls/library/psa_crypto_driver_wrappers.h | /*
* Function signatures for functionality that can be provided by
* cryptographic accelerators.
* Warning: This file will be auto-generated in the future.
*/
/* Copyright The Mbed TLS Contributors
* SPDX-License-Identifier: Apache-2.0
*
* 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.
*/
#ifndef PSA_CRYPTO_DRIVER_WRAPPERS_H
#define PSA_CRYPTO_DRIVER_WRAPPERS_H
#include "psa/crypto.h"
#include "psa/crypto_driver_common.h"
/*
* Signature functions
*/
psa_status_t psa_driver_wrapper_sign_message(
const psa_key_attributes_t *attributes,
const uint8_t *key_buffer,
size_t key_buffer_size,
psa_algorithm_t alg,
const uint8_t *input,
size_t input_length,
uint8_t *signature,
size_t signature_size,
size_t *signature_length );
psa_status_t psa_driver_wrapper_verify_message(
const psa_key_attributes_t *attributes,
const uint8_t *key_buffer,
size_t key_buffer_size,
psa_algorithm_t alg,
const uint8_t *input,
size_t input_length,
const uint8_t *signature,
size_t signature_length );
psa_status_t psa_driver_wrapper_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 );
psa_status_t psa_driver_wrapper_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 );
/*
* Key handling functions
*/
psa_status_t psa_driver_wrapper_import_key(
const psa_key_attributes_t *attributes,
const uint8_t *data, size_t data_length,
uint8_t *key_buffer, size_t key_buffer_size,
size_t *key_buffer_length, size_t *bits );
psa_status_t psa_driver_wrapper_export_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 );
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 );
psa_status_t psa_driver_wrapper_get_key_buffer_size(
const psa_key_attributes_t *attributes,
size_t *key_buffer_size );
psa_status_t psa_driver_wrapper_generate_key(
const psa_key_attributes_t *attributes,
uint8_t *key_buffer, size_t key_buffer_size, size_t *key_buffer_length );
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 );
/*
* Cipher functions
*/
psa_status_t psa_driver_wrapper_cipher_encrypt(
const psa_key_attributes_t *attributes,
const uint8_t *key_buffer,
size_t key_buffer_size,
psa_algorithm_t alg,
const uint8_t *input,
size_t input_length,
uint8_t *output,
size_t output_size,
size_t *output_length );
psa_status_t psa_driver_wrapper_cipher_decrypt(
const psa_key_attributes_t *attributes,
const uint8_t *key_buffer,
size_t key_buffer_size,
psa_algorithm_t alg,
const uint8_t *input,
size_t input_length,
uint8_t *output,
size_t output_size,
size_t *output_length );
psa_status_t psa_driver_wrapper_cipher_encrypt_setup(
psa_cipher_operation_t *operation,
const psa_key_attributes_t *attributes,
const uint8_t *key_buffer, size_t key_buffer_size,
psa_algorithm_t alg );
psa_status_t psa_driver_wrapper_cipher_decrypt_setup(
psa_cipher_operation_t *operation,
const psa_key_attributes_t *attributes,
const uint8_t *key_buffer, size_t key_buffer_size,
psa_algorithm_t alg );
psa_status_t psa_driver_wrapper_cipher_set_iv(
psa_cipher_operation_t *operation,
const uint8_t *iv,
size_t iv_length );
psa_status_t psa_driver_wrapper_cipher_update(
psa_cipher_operation_t *operation,
const uint8_t *input,
size_t input_length,
uint8_t *output,
size_t output_size,
size_t *output_length );
psa_status_t psa_driver_wrapper_cipher_finish(
psa_cipher_operation_t *operation,
uint8_t *output,
size_t output_size,
size_t *output_length );
psa_status_t psa_driver_wrapper_cipher_abort(
psa_cipher_operation_t *operation );
/*
* Hashing functions
*/
psa_status_t psa_driver_wrapper_hash_compute(
psa_algorithm_t alg,
const uint8_t *input,
size_t input_length,
uint8_t *hash,
size_t hash_size,
size_t *hash_length);
psa_status_t psa_driver_wrapper_hash_setup(
psa_hash_operation_t *operation,
psa_algorithm_t alg );
psa_status_t psa_driver_wrapper_hash_clone(
const psa_hash_operation_t *source_operation,
psa_hash_operation_t *target_operation );
psa_status_t psa_driver_wrapper_hash_update(
psa_hash_operation_t *operation,
const uint8_t *input,
size_t input_length );
psa_status_t psa_driver_wrapper_hash_finish(
psa_hash_operation_t *operation,
uint8_t *hash,
size_t hash_size,
size_t *hash_length );
psa_status_t psa_driver_wrapper_hash_abort(
psa_hash_operation_t *operation );
/*
* AEAD functions
*/
psa_status_t psa_driver_wrapper_aead_encrypt(
const psa_key_attributes_t *attributes,
const uint8_t *key_buffer, size_t key_buffer_size,
psa_algorithm_t alg,
const uint8_t *nonce, size_t nonce_length,
const uint8_t *additional_data, size_t additional_data_length,
const uint8_t *plaintext, size_t plaintext_length,
uint8_t *ciphertext, size_t ciphertext_size, size_t *ciphertext_length );
psa_status_t psa_driver_wrapper_aead_decrypt(
const psa_key_attributes_t *attributes,
const uint8_t *key_buffer, size_t key_buffer_size,
psa_algorithm_t alg,
const uint8_t *nonce, size_t nonce_length,
const uint8_t *additional_data, size_t additional_data_length,
const uint8_t *ciphertext, size_t ciphertext_length,
uint8_t *plaintext, size_t plaintext_size, size_t *plaintext_length );
/*
* MAC functions
*/
psa_status_t psa_driver_wrapper_mac_compute(
const psa_key_attributes_t *attributes,
const uint8_t *key_buffer,
size_t key_buffer_size,
psa_algorithm_t alg,
const uint8_t *input,
size_t input_length,
uint8_t *mac,
size_t mac_size,
size_t *mac_length );
psa_status_t psa_driver_wrapper_mac_sign_setup(
psa_mac_operation_t *operation,
const psa_key_attributes_t *attributes,
const uint8_t *key_buffer,
size_t key_buffer_size,
psa_algorithm_t alg );
psa_status_t psa_driver_wrapper_mac_verify_setup(
psa_mac_operation_t *operation,
const psa_key_attributes_t *attributes,
const uint8_t *key_buffer,
size_t key_buffer_size,
psa_algorithm_t alg );
psa_status_t psa_driver_wrapper_mac_update(
psa_mac_operation_t *operation,
const uint8_t *input,
size_t input_length );
psa_status_t psa_driver_wrapper_mac_sign_finish(
psa_mac_operation_t *operation,
uint8_t *mac,
size_t mac_size,
size_t *mac_length );
psa_status_t psa_driver_wrapper_mac_verify_finish(
psa_mac_operation_t *operation,
const uint8_t *mac,
size_t mac_length );
psa_status_t psa_driver_wrapper_mac_abort(
psa_mac_operation_t *operation );
#endif /* PSA_CRYPTO_DRIVER_WRAPPERS_H */
/* End of automatically generated file. */
|
0 | repos/gpt4all.zig/src/zig-libcurl/zig-mbedtls/mbedtls | repos/gpt4all.zig/src/zig-libcurl/zig-mbedtls/mbedtls/library/mps_trace.c | /*
* Message Processing Stack, Trace module
*
* Copyright The Mbed TLS Contributors
* SPDX-License-Identifier: Apache-2.0
*
* 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.
*
* This file is part of Mbed TLS (https://tls.mbed.org)
*/
#include "common.h"
#if defined(MBEDTLS_SSL_PROTO_TLS1_3_EXPERIMENTAL)
#include "mps_common.h"
#if defined(MBEDTLS_MPS_ENABLE_TRACE)
#include "mps_trace.h"
#include <stdarg.h>
static int trace_depth = 0;
#define color_default "\x1B[0m"
#define color_red "\x1B[1;31m"
#define color_green "\x1B[1;32m"
#define color_yellow "\x1B[1;33m"
#define color_blue "\x1B[1;34m"
#define color_magenta "\x1B[1;35m"
#define color_cyan "\x1B[1;36m"
#define color_white "\x1B[1;37m"
static char const * colors[] =
{
color_default,
color_green,
color_yellow,
color_magenta,
color_cyan,
color_blue,
color_white
};
#define MPS_TRACE_BUF_SIZE 100
void mbedtls_mps_trace_print_msg( int id, int line, const char *format, ... )
{
int ret;
char str[MPS_TRACE_BUF_SIZE];
va_list argp;
va_start( argp, format );
ret = mbedtls_vsnprintf( str, MPS_TRACE_BUF_SIZE, format, argp );
va_end( argp );
if( ret >= 0 && ret < MPS_TRACE_BUF_SIZE )
{
str[ret] = '\0';
mbedtls_printf( "[%d|L%d]: %s\n", id, line, str );
}
}
int mbedtls_mps_trace_get_depth()
{
return trace_depth;
}
void mbedtls_mps_trace_dec_depth()
{
trace_depth--;
}
void mbedtls_mps_trace_inc_depth()
{
trace_depth++;
}
void mbedtls_mps_trace_color( int id )
{
if( id > (int) ( sizeof( colors ) / sizeof( *colors ) ) )
return;
printf( "%s", colors[ id ] );
}
void mbedtls_mps_trace_indent( int level, mbedtls_mps_trace_type ty )
{
if( level > 0 )
{
while( --level )
printf( "| " );
printf( "| " );
}
switch( ty )
{
case MBEDTLS_MPS_TRACE_TYPE_COMMENT:
mbedtls_printf( "@ " );
break;
case MBEDTLS_MPS_TRACE_TYPE_CALL:
mbedtls_printf( "+--> " );
break;
case MBEDTLS_MPS_TRACE_TYPE_ERROR:
mbedtls_printf( "E " );
break;
case MBEDTLS_MPS_TRACE_TYPE_RETURN:
mbedtls_printf( "< " );
break;
default:
break;
}
}
#endif /* MBEDTLS_MPS_ENABLE_TRACE */
#endif /* MBEDTLS_SSL_PROTO_TLS1_3_EXPERIMENTAL */
|
0 | repos/gpt4all.zig/src/zig-libcurl/zig-mbedtls/mbedtls | repos/gpt4all.zig/src/zig-libcurl/zig-mbedtls/mbedtls/library/psa_crypto_se.c | /*
* PSA crypto support for secure element drivers
*/
/*
* Copyright The Mbed TLS Contributors
* SPDX-License-Identifier: Apache-2.0
*
* 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.
*/
#include "common.h"
#if defined(MBEDTLS_PSA_CRYPTO_SE_C)
#include <assert.h>
#include <stdint.h>
#include <string.h>
#include "psa/crypto_se_driver.h"
#include "psa_crypto_se.h"
#if defined(MBEDTLS_PSA_ITS_FILE_C)
#include "psa_crypto_its.h"
#else /* Native ITS implementation */
#include "psa/error.h"
#include "psa/internal_trusted_storage.h"
#endif
#include "mbedtls/platform.h"
#if !defined(MBEDTLS_PLATFORM_C)
#define mbedtls_calloc calloc
#define mbedtls_free free
#endif
/****************************************************************/
/* Driver lookup */
/****************************************************************/
/* This structure is identical to psa_drv_se_context_t declared in
* `crypto_se_driver.h`, except that some parts are writable here
* (non-const, or pointer to non-const). */
typedef struct
{
void *persistent_data;
size_t persistent_data_size;
uintptr_t transient_data;
} psa_drv_se_internal_context_t;
struct psa_se_drv_table_entry_s
{
psa_key_location_t location;
const psa_drv_se_t *methods;
union
{
psa_drv_se_internal_context_t internal;
psa_drv_se_context_t context;
} u;
};
static psa_se_drv_table_entry_t driver_table[PSA_MAX_SE_DRIVERS];
psa_se_drv_table_entry_t *psa_get_se_driver_entry(
psa_key_lifetime_t lifetime )
{
size_t i;
psa_key_location_t location = PSA_KEY_LIFETIME_GET_LOCATION( lifetime );
/* In the driver table, location=0 means an entry that isn't used.
* No driver has a location of 0 because it's a reserved value
* (which designates transparent keys). Make sure we never return
* a driver entry for location 0. */
if( location == 0 )
return( NULL );
for( i = 0; i < PSA_MAX_SE_DRIVERS; i++ )
{
if( driver_table[i].location == location )
return( &driver_table[i] );
}
return( NULL );
}
const psa_drv_se_t *psa_get_se_driver_methods(
const psa_se_drv_table_entry_t *driver )
{
return( driver->methods );
}
psa_drv_se_context_t *psa_get_se_driver_context(
psa_se_drv_table_entry_t *driver )
{
return( &driver->u.context );
}
int psa_get_se_driver( psa_key_lifetime_t lifetime,
const psa_drv_se_t **p_methods,
psa_drv_se_context_t **p_drv_context)
{
psa_se_drv_table_entry_t *driver = psa_get_se_driver_entry( lifetime );
if( p_methods != NULL )
*p_methods = ( driver ? driver->methods : NULL );
if( p_drv_context != NULL )
*p_drv_context = ( driver ? &driver->u.context : NULL );
return( driver != NULL );
}
/****************************************************************/
/* Persistent data management */
/****************************************************************/
static psa_status_t psa_get_se_driver_its_file_uid(
const psa_se_drv_table_entry_t *driver,
psa_storage_uid_t *uid )
{
if( driver->location > PSA_MAX_SE_LOCATION )
return( PSA_ERROR_NOT_SUPPORTED );
#if SIZE_MAX > UINT32_MAX
/* ITS file sizes are limited to 32 bits. */
if( driver->u.internal.persistent_data_size > UINT32_MAX )
return( PSA_ERROR_NOT_SUPPORTED );
#endif
/* See the documentation of PSA_CRYPTO_SE_DRIVER_ITS_UID_BASE. */
*uid = PSA_CRYPTO_SE_DRIVER_ITS_UID_BASE + driver->location;
return( PSA_SUCCESS );
}
psa_status_t psa_load_se_persistent_data(
const psa_se_drv_table_entry_t *driver )
{
psa_status_t status;
psa_storage_uid_t uid;
size_t length;
status = psa_get_se_driver_its_file_uid( driver, &uid );
if( status != PSA_SUCCESS )
return( status );
/* Read the amount of persistent data that the driver requests.
* If the data in storage is larger, it is truncated. If the data
* in storage is smaller, silently keep what is already at the end
* of the output buffer. */
/* psa_get_se_driver_its_file_uid ensures that the size_t
* persistent_data_size is in range, but compilers don't know that,
* so cast to reassure them. */
return( psa_its_get( uid, 0,
(uint32_t) driver->u.internal.persistent_data_size,
driver->u.internal.persistent_data,
&length ) );
}
psa_status_t psa_save_se_persistent_data(
const psa_se_drv_table_entry_t *driver )
{
psa_status_t status;
psa_storage_uid_t uid;
status = psa_get_se_driver_its_file_uid( driver, &uid );
if( status != PSA_SUCCESS )
return( status );
/* psa_get_se_driver_its_file_uid ensures that the size_t
* persistent_data_size is in range, but compilers don't know that,
* so cast to reassure them. */
return( psa_its_set( uid,
(uint32_t) driver->u.internal.persistent_data_size,
driver->u.internal.persistent_data,
0 ) );
}
psa_status_t psa_destroy_se_persistent_data( psa_key_location_t location )
{
psa_storage_uid_t uid;
if( location > PSA_MAX_SE_LOCATION )
return( PSA_ERROR_NOT_SUPPORTED );
uid = PSA_CRYPTO_SE_DRIVER_ITS_UID_BASE + location;
return( psa_its_remove( uid ) );
}
psa_status_t psa_find_se_slot_for_key(
const psa_key_attributes_t *attributes,
psa_key_creation_method_t method,
psa_se_drv_table_entry_t *driver,
psa_key_slot_number_t *slot_number )
{
psa_status_t status;
psa_key_location_t key_location =
PSA_KEY_LIFETIME_GET_LOCATION( psa_get_key_lifetime( attributes ) );
/* If the location is wrong, it's a bug in the library. */
if( driver->location != key_location )
return( PSA_ERROR_CORRUPTION_DETECTED );
/* If the driver doesn't support key creation in any way, give up now. */
if( driver->methods->key_management == NULL )
return( PSA_ERROR_NOT_SUPPORTED );
if( psa_get_key_slot_number( attributes, slot_number ) == PSA_SUCCESS )
{
/* The application wants to use a specific slot. Allow it if
* the driver supports it. On a system with isolation,
* the crypto service must check that the application is
* permitted to request this slot. */
psa_drv_se_validate_slot_number_t p_validate_slot_number =
driver->methods->key_management->p_validate_slot_number;
if( p_validate_slot_number == NULL )
return( PSA_ERROR_NOT_SUPPORTED );
status = p_validate_slot_number( &driver->u.context,
driver->u.internal.persistent_data,
attributes, method,
*slot_number );
}
else if( method == PSA_KEY_CREATION_REGISTER )
{
/* The application didn't specify a slot number. This doesn't
* make sense when registering a slot. */
return( PSA_ERROR_INVALID_ARGUMENT );
}
else
{
/* The application didn't tell us which slot to use. Let the driver
* choose. This is the normal case. */
psa_drv_se_allocate_key_t p_allocate =
driver->methods->key_management->p_allocate;
if( p_allocate == NULL )
return( PSA_ERROR_NOT_SUPPORTED );
status = p_allocate( &driver->u.context,
driver->u.internal.persistent_data,
attributes, method,
slot_number );
}
return( status );
}
psa_status_t psa_destroy_se_key( psa_se_drv_table_entry_t *driver,
psa_key_slot_number_t slot_number )
{
psa_status_t status;
psa_status_t storage_status;
/* Normally a missing method would mean that the action is not
* supported. But psa_destroy_key() is not supposed to return
* PSA_ERROR_NOT_SUPPORTED: if you can create a key, you should
* be able to destroy it. The only use case for a driver that
* does not have a way to destroy keys at all is if the keys are
* locked in a read-only state: we can use the keys but not
* destroy them. Hence, if the driver doesn't support destroying
* keys, it's really a lack of permission. */
if( driver->methods->key_management == NULL ||
driver->methods->key_management->p_destroy == NULL )
return( PSA_ERROR_NOT_PERMITTED );
status = driver->methods->key_management->p_destroy(
&driver->u.context,
driver->u.internal.persistent_data,
slot_number );
storage_status = psa_save_se_persistent_data( driver );
return( status == PSA_SUCCESS ? storage_status : status );
}
psa_status_t psa_init_all_se_drivers( void )
{
size_t i;
for( i = 0; i < PSA_MAX_SE_DRIVERS; i++ )
{
psa_se_drv_table_entry_t *driver = &driver_table[i];
if( driver->location == 0 )
continue; /* skipping unused entry */
const psa_drv_se_t *methods = psa_get_se_driver_methods( driver );
if( methods->p_init != NULL )
{
psa_status_t status = methods->p_init(
&driver->u.context,
driver->u.internal.persistent_data,
driver->location );
if( status != PSA_SUCCESS )
return( status );
status = psa_save_se_persistent_data( driver );
if( status != PSA_SUCCESS )
return( status );
}
}
return( PSA_SUCCESS );
}
/****************************************************************/
/* Driver registration */
/****************************************************************/
psa_status_t psa_register_se_driver(
psa_key_location_t location,
const psa_drv_se_t *methods)
{
size_t i;
psa_status_t status;
if( methods->hal_version != PSA_DRV_SE_HAL_VERSION )
return( PSA_ERROR_NOT_SUPPORTED );
/* Driver table entries are 0-initialized. 0 is not a valid driver
* location because it means a transparent key. */
#if defined(static_assert)
static_assert( PSA_KEY_LOCATION_LOCAL_STORAGE == 0,
"Secure element support requires 0 to mean a local key" );
#endif
if( location == PSA_KEY_LOCATION_LOCAL_STORAGE )
return( PSA_ERROR_INVALID_ARGUMENT );
if( location > PSA_MAX_SE_LOCATION )
return( PSA_ERROR_NOT_SUPPORTED );
for( i = 0; i < PSA_MAX_SE_DRIVERS; i++ )
{
if( driver_table[i].location == 0 )
break;
/* Check that location isn't already in use up to the first free
* entry. Since entries are created in order and never deleted,
* there can't be a used entry after the first free entry. */
if( driver_table[i].location == location )
return( PSA_ERROR_ALREADY_EXISTS );
}
if( i == PSA_MAX_SE_DRIVERS )
return( PSA_ERROR_INSUFFICIENT_MEMORY );
driver_table[i].location = location;
driver_table[i].methods = methods;
driver_table[i].u.internal.persistent_data_size =
methods->persistent_data_size;
if( methods->persistent_data_size != 0 )
{
driver_table[i].u.internal.persistent_data =
mbedtls_calloc( 1, methods->persistent_data_size );
if( driver_table[i].u.internal.persistent_data == NULL )
{
status = PSA_ERROR_INSUFFICIENT_MEMORY;
goto error;
}
/* Load the driver's persistent data. On first use, the persistent
* data does not exist in storage, and is initialized to
* all-bits-zero by the calloc call just above. */
status = psa_load_se_persistent_data( &driver_table[i] );
if( status != PSA_SUCCESS && status != PSA_ERROR_DOES_NOT_EXIST )
goto error;
}
return( PSA_SUCCESS );
error:
memset( &driver_table[i], 0, sizeof( driver_table[i] ) );
return( status );
}
void psa_unregister_all_se_drivers( void )
{
size_t i;
for( i = 0; i < PSA_MAX_SE_DRIVERS; i++ )
{
if( driver_table[i].u.internal.persistent_data != NULL )
mbedtls_free( driver_table[i].u.internal.persistent_data );
}
memset( driver_table, 0, sizeof( driver_table ) );
}
/****************************************************************/
/* The end */
/****************************************************************/
#endif /* MBEDTLS_PSA_CRYPTO_SE_C */
|
0 | repos/gpt4all.zig/src/zig-libcurl/zig-mbedtls/mbedtls | repos/gpt4all.zig/src/zig-libcurl/zig-mbedtls/mbedtls/library/chachapoly.c | /**
* \file chachapoly.c
*
* \brief ChaCha20-Poly1305 AEAD construction based on RFC 7539.
*
* Copyright The Mbed TLS Contributors
* SPDX-License-Identifier: Apache-2.0
*
* 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.
*/
#include "common.h"
#if defined(MBEDTLS_CHACHAPOLY_C)
#include "mbedtls/chachapoly.h"
#include "mbedtls/platform_util.h"
#include "mbedtls/error.h"
#include <string.h>
#if defined(MBEDTLS_SELF_TEST)
#if defined(MBEDTLS_PLATFORM_C)
#include "mbedtls/platform.h"
#else
#include <stdio.h>
#define mbedtls_printf printf
#endif /* MBEDTLS_PLATFORM_C */
#endif /* MBEDTLS_SELF_TEST */
#if !defined(MBEDTLS_CHACHAPOLY_ALT)
/* Parameter validation macros */
#define CHACHAPOLY_VALIDATE_RET( cond ) \
MBEDTLS_INTERNAL_VALIDATE_RET( cond, MBEDTLS_ERR_POLY1305_BAD_INPUT_DATA )
#define CHACHAPOLY_VALIDATE( cond ) \
MBEDTLS_INTERNAL_VALIDATE( cond )
#define CHACHAPOLY_STATE_INIT ( 0 )
#define CHACHAPOLY_STATE_AAD ( 1 )
#define CHACHAPOLY_STATE_CIPHERTEXT ( 2 ) /* Encrypting or decrypting */
#define CHACHAPOLY_STATE_FINISHED ( 3 )
/**
* \brief Adds nul bytes to pad the AAD for Poly1305.
*
* \param ctx The ChaCha20-Poly1305 context.
*/
static int chachapoly_pad_aad( mbedtls_chachapoly_context *ctx )
{
uint32_t partial_block_len = (uint32_t) ( ctx->aad_len % 16U );
unsigned char zeroes[15];
if( partial_block_len == 0U )
return( 0 );
memset( zeroes, 0, sizeof( zeroes ) );
return( mbedtls_poly1305_update( &ctx->poly1305_ctx,
zeroes,
16U - partial_block_len ) );
}
/**
* \brief Adds nul bytes to pad the ciphertext for Poly1305.
*
* \param ctx The ChaCha20-Poly1305 context.
*/
static int chachapoly_pad_ciphertext( mbedtls_chachapoly_context *ctx )
{
uint32_t partial_block_len = (uint32_t) ( ctx->ciphertext_len % 16U );
unsigned char zeroes[15];
if( partial_block_len == 0U )
return( 0 );
memset( zeroes, 0, sizeof( zeroes ) );
return( mbedtls_poly1305_update( &ctx->poly1305_ctx,
zeroes,
16U - partial_block_len ) );
}
void mbedtls_chachapoly_init( mbedtls_chachapoly_context *ctx )
{
CHACHAPOLY_VALIDATE( ctx != NULL );
mbedtls_chacha20_init( &ctx->chacha20_ctx );
mbedtls_poly1305_init( &ctx->poly1305_ctx );
ctx->aad_len = 0U;
ctx->ciphertext_len = 0U;
ctx->state = CHACHAPOLY_STATE_INIT;
ctx->mode = MBEDTLS_CHACHAPOLY_ENCRYPT;
}
void mbedtls_chachapoly_free( mbedtls_chachapoly_context *ctx )
{
if( ctx == NULL )
return;
mbedtls_chacha20_free( &ctx->chacha20_ctx );
mbedtls_poly1305_free( &ctx->poly1305_ctx );
ctx->aad_len = 0U;
ctx->ciphertext_len = 0U;
ctx->state = CHACHAPOLY_STATE_INIT;
ctx->mode = MBEDTLS_CHACHAPOLY_ENCRYPT;
}
int mbedtls_chachapoly_setkey( mbedtls_chachapoly_context *ctx,
const unsigned char key[32] )
{
int ret = MBEDTLS_ERR_ERROR_CORRUPTION_DETECTED;
CHACHAPOLY_VALIDATE_RET( ctx != NULL );
CHACHAPOLY_VALIDATE_RET( key != NULL );
ret = mbedtls_chacha20_setkey( &ctx->chacha20_ctx, key );
return( ret );
}
int mbedtls_chachapoly_starts( mbedtls_chachapoly_context *ctx,
const unsigned char nonce[12],
mbedtls_chachapoly_mode_t mode )
{
int ret = MBEDTLS_ERR_ERROR_CORRUPTION_DETECTED;
unsigned char poly1305_key[64];
CHACHAPOLY_VALIDATE_RET( ctx != NULL );
CHACHAPOLY_VALIDATE_RET( nonce != NULL );
/* Set counter = 0, will be update to 1 when generating Poly1305 key */
ret = mbedtls_chacha20_starts( &ctx->chacha20_ctx, nonce, 0U );
if( ret != 0 )
goto cleanup;
/* Generate the Poly1305 key by getting the ChaCha20 keystream output with
* counter = 0. This is the same as encrypting a buffer of zeroes.
* Only the first 256-bits (32 bytes) of the key is used for Poly1305.
* The other 256 bits are discarded.
*/
memset( poly1305_key, 0, sizeof( poly1305_key ) );
ret = mbedtls_chacha20_update( &ctx->chacha20_ctx, sizeof( poly1305_key ),
poly1305_key, poly1305_key );
if( ret != 0 )
goto cleanup;
ret = mbedtls_poly1305_starts( &ctx->poly1305_ctx, poly1305_key );
if( ret == 0 )
{
ctx->aad_len = 0U;
ctx->ciphertext_len = 0U;
ctx->state = CHACHAPOLY_STATE_AAD;
ctx->mode = mode;
}
cleanup:
mbedtls_platform_zeroize( poly1305_key, 64U );
return( ret );
}
int mbedtls_chachapoly_update_aad( mbedtls_chachapoly_context *ctx,
const unsigned char *aad,
size_t aad_len )
{
CHACHAPOLY_VALIDATE_RET( ctx != NULL );
CHACHAPOLY_VALIDATE_RET( aad_len == 0 || aad != NULL );
if( ctx->state != CHACHAPOLY_STATE_AAD )
return( MBEDTLS_ERR_CHACHAPOLY_BAD_STATE );
ctx->aad_len += aad_len;
return( mbedtls_poly1305_update( &ctx->poly1305_ctx, aad, aad_len ) );
}
int mbedtls_chachapoly_update( mbedtls_chachapoly_context *ctx,
size_t len,
const unsigned char *input,
unsigned char *output )
{
int ret = MBEDTLS_ERR_ERROR_CORRUPTION_DETECTED;
CHACHAPOLY_VALIDATE_RET( ctx != NULL );
CHACHAPOLY_VALIDATE_RET( len == 0 || input != NULL );
CHACHAPOLY_VALIDATE_RET( len == 0 || output != NULL );
if( ( ctx->state != CHACHAPOLY_STATE_AAD ) &&
( ctx->state != CHACHAPOLY_STATE_CIPHERTEXT ) )
{
return( MBEDTLS_ERR_CHACHAPOLY_BAD_STATE );
}
if( ctx->state == CHACHAPOLY_STATE_AAD )
{
ctx->state = CHACHAPOLY_STATE_CIPHERTEXT;
ret = chachapoly_pad_aad( ctx );
if( ret != 0 )
return( ret );
}
ctx->ciphertext_len += len;
if( ctx->mode == MBEDTLS_CHACHAPOLY_ENCRYPT )
{
ret = mbedtls_chacha20_update( &ctx->chacha20_ctx, len, input, output );
if( ret != 0 )
return( ret );
ret = mbedtls_poly1305_update( &ctx->poly1305_ctx, output, len );
if( ret != 0 )
return( ret );
}
else /* DECRYPT */
{
ret = mbedtls_poly1305_update( &ctx->poly1305_ctx, input, len );
if( ret != 0 )
return( ret );
ret = mbedtls_chacha20_update( &ctx->chacha20_ctx, len, input, output );
if( ret != 0 )
return( ret );
}
return( 0 );
}
int mbedtls_chachapoly_finish( mbedtls_chachapoly_context *ctx,
unsigned char mac[16] )
{
int ret = MBEDTLS_ERR_ERROR_CORRUPTION_DETECTED;
unsigned char len_block[16];
CHACHAPOLY_VALIDATE_RET( ctx != NULL );
CHACHAPOLY_VALIDATE_RET( mac != NULL );
if( ctx->state == CHACHAPOLY_STATE_INIT )
{
return( MBEDTLS_ERR_CHACHAPOLY_BAD_STATE );
}
if( ctx->state == CHACHAPOLY_STATE_AAD )
{
ret = chachapoly_pad_aad( ctx );
if( ret != 0 )
return( ret );
}
else if( ctx->state == CHACHAPOLY_STATE_CIPHERTEXT )
{
ret = chachapoly_pad_ciphertext( ctx );
if( ret != 0 )
return( ret );
}
ctx->state = CHACHAPOLY_STATE_FINISHED;
/* The lengths of the AAD and ciphertext are processed by
* Poly1305 as the final 128-bit block, encoded as little-endian integers.
*/
len_block[ 0] = (unsigned char)( ctx->aad_len );
len_block[ 1] = (unsigned char)( ctx->aad_len >> 8 );
len_block[ 2] = (unsigned char)( ctx->aad_len >> 16 );
len_block[ 3] = (unsigned char)( ctx->aad_len >> 24 );
len_block[ 4] = (unsigned char)( ctx->aad_len >> 32 );
len_block[ 5] = (unsigned char)( ctx->aad_len >> 40 );
len_block[ 6] = (unsigned char)( ctx->aad_len >> 48 );
len_block[ 7] = (unsigned char)( ctx->aad_len >> 56 );
len_block[ 8] = (unsigned char)( ctx->ciphertext_len );
len_block[ 9] = (unsigned char)( ctx->ciphertext_len >> 8 );
len_block[10] = (unsigned char)( ctx->ciphertext_len >> 16 );
len_block[11] = (unsigned char)( ctx->ciphertext_len >> 24 );
len_block[12] = (unsigned char)( ctx->ciphertext_len >> 32 );
len_block[13] = (unsigned char)( ctx->ciphertext_len >> 40 );
len_block[14] = (unsigned char)( ctx->ciphertext_len >> 48 );
len_block[15] = (unsigned char)( ctx->ciphertext_len >> 56 );
ret = mbedtls_poly1305_update( &ctx->poly1305_ctx, len_block, 16U );
if( ret != 0 )
return( ret );
ret = mbedtls_poly1305_finish( &ctx->poly1305_ctx, mac );
return( ret );
}
static int chachapoly_crypt_and_tag( mbedtls_chachapoly_context *ctx,
mbedtls_chachapoly_mode_t mode,
size_t length,
const unsigned char nonce[12],
const unsigned char *aad,
size_t aad_len,
const unsigned char *input,
unsigned char *output,
unsigned char tag[16] )
{
int ret = MBEDTLS_ERR_ERROR_CORRUPTION_DETECTED;
ret = mbedtls_chachapoly_starts( ctx, nonce, mode );
if( ret != 0 )
goto cleanup;
ret = mbedtls_chachapoly_update_aad( ctx, aad, aad_len );
if( ret != 0 )
goto cleanup;
ret = mbedtls_chachapoly_update( ctx, length, input, output );
if( ret != 0 )
goto cleanup;
ret = mbedtls_chachapoly_finish( ctx, tag );
cleanup:
return( ret );
}
int mbedtls_chachapoly_encrypt_and_tag( mbedtls_chachapoly_context *ctx,
size_t length,
const unsigned char nonce[12],
const unsigned char *aad,
size_t aad_len,
const unsigned char *input,
unsigned char *output,
unsigned char tag[16] )
{
CHACHAPOLY_VALIDATE_RET( ctx != NULL );
CHACHAPOLY_VALIDATE_RET( nonce != NULL );
CHACHAPOLY_VALIDATE_RET( tag != NULL );
CHACHAPOLY_VALIDATE_RET( aad_len == 0 || aad != NULL );
CHACHAPOLY_VALIDATE_RET( length == 0 || input != NULL );
CHACHAPOLY_VALIDATE_RET( length == 0 || output != NULL );
return( chachapoly_crypt_and_tag( ctx, MBEDTLS_CHACHAPOLY_ENCRYPT,
length, nonce, aad, aad_len,
input, output, tag ) );
}
int mbedtls_chachapoly_auth_decrypt( mbedtls_chachapoly_context *ctx,
size_t length,
const unsigned char nonce[12],
const unsigned char *aad,
size_t aad_len,
const unsigned char tag[16],
const unsigned char *input,
unsigned char *output )
{
int ret = MBEDTLS_ERR_ERROR_CORRUPTION_DETECTED;
unsigned char check_tag[16];
size_t i;
int diff;
CHACHAPOLY_VALIDATE_RET( ctx != NULL );
CHACHAPOLY_VALIDATE_RET( nonce != NULL );
CHACHAPOLY_VALIDATE_RET( tag != NULL );
CHACHAPOLY_VALIDATE_RET( aad_len == 0 || aad != NULL );
CHACHAPOLY_VALIDATE_RET( length == 0 || input != NULL );
CHACHAPOLY_VALIDATE_RET( length == 0 || output != NULL );
if( ( ret = chachapoly_crypt_and_tag( ctx,
MBEDTLS_CHACHAPOLY_DECRYPT, length, nonce,
aad, aad_len, input, output, check_tag ) ) != 0 )
{
return( ret );
}
/* Check tag in "constant-time" */
for( diff = 0, i = 0; i < sizeof( check_tag ); i++ )
diff |= tag[i] ^ check_tag[i];
if( diff != 0 )
{
mbedtls_platform_zeroize( output, length );
return( MBEDTLS_ERR_CHACHAPOLY_AUTH_FAILED );
}
return( 0 );
}
#endif /* MBEDTLS_CHACHAPOLY_ALT */
#if defined(MBEDTLS_SELF_TEST)
static const unsigned char test_key[1][32] =
{
{
0x80, 0x81, 0x82, 0x83, 0x84, 0x85, 0x86, 0x87,
0x88, 0x89, 0x8a, 0x8b, 0x8c, 0x8d, 0x8e, 0x8f,
0x90, 0x91, 0x92, 0x93, 0x94, 0x95, 0x96, 0x97,
0x98, 0x99, 0x9a, 0x9b, 0x9c, 0x9d, 0x9e, 0x9f
}
};
static const unsigned char test_nonce[1][12] =
{
{
0x07, 0x00, 0x00, 0x00, /* 32-bit common part */
0x40, 0x41, 0x42, 0x43, 0x44, 0x45, 0x46, 0x47 /* 64-bit IV */
}
};
static const unsigned char test_aad[1][12] =
{
{
0x50, 0x51, 0x52, 0x53, 0xc0, 0xc1, 0xc2, 0xc3,
0xc4, 0xc5, 0xc6, 0xc7
}
};
static const size_t test_aad_len[1] =
{
12U
};
static const unsigned char test_input[1][114] =
{
{
0x4c, 0x61, 0x64, 0x69, 0x65, 0x73, 0x20, 0x61,
0x6e, 0x64, 0x20, 0x47, 0x65, 0x6e, 0x74, 0x6c,
0x65, 0x6d, 0x65, 0x6e, 0x20, 0x6f, 0x66, 0x20,
0x74, 0x68, 0x65, 0x20, 0x63, 0x6c, 0x61, 0x73,
0x73, 0x20, 0x6f, 0x66, 0x20, 0x27, 0x39, 0x39,
0x3a, 0x20, 0x49, 0x66, 0x20, 0x49, 0x20, 0x63,
0x6f, 0x75, 0x6c, 0x64, 0x20, 0x6f, 0x66, 0x66,
0x65, 0x72, 0x20, 0x79, 0x6f, 0x75, 0x20, 0x6f,
0x6e, 0x6c, 0x79, 0x20, 0x6f, 0x6e, 0x65, 0x20,
0x74, 0x69, 0x70, 0x20, 0x66, 0x6f, 0x72, 0x20,
0x74, 0x68, 0x65, 0x20, 0x66, 0x75, 0x74, 0x75,
0x72, 0x65, 0x2c, 0x20, 0x73, 0x75, 0x6e, 0x73,
0x63, 0x72, 0x65, 0x65, 0x6e, 0x20, 0x77, 0x6f,
0x75, 0x6c, 0x64, 0x20, 0x62, 0x65, 0x20, 0x69,
0x74, 0x2e
}
};
static const unsigned char test_output[1][114] =
{
{
0xd3, 0x1a, 0x8d, 0x34, 0x64, 0x8e, 0x60, 0xdb,
0x7b, 0x86, 0xaf, 0xbc, 0x53, 0xef, 0x7e, 0xc2,
0xa4, 0xad, 0xed, 0x51, 0x29, 0x6e, 0x08, 0xfe,
0xa9, 0xe2, 0xb5, 0xa7, 0x36, 0xee, 0x62, 0xd6,
0x3d, 0xbe, 0xa4, 0x5e, 0x8c, 0xa9, 0x67, 0x12,
0x82, 0xfa, 0xfb, 0x69, 0xda, 0x92, 0x72, 0x8b,
0x1a, 0x71, 0xde, 0x0a, 0x9e, 0x06, 0x0b, 0x29,
0x05, 0xd6, 0xa5, 0xb6, 0x7e, 0xcd, 0x3b, 0x36,
0x92, 0xdd, 0xbd, 0x7f, 0x2d, 0x77, 0x8b, 0x8c,
0x98, 0x03, 0xae, 0xe3, 0x28, 0x09, 0x1b, 0x58,
0xfa, 0xb3, 0x24, 0xe4, 0xfa, 0xd6, 0x75, 0x94,
0x55, 0x85, 0x80, 0x8b, 0x48, 0x31, 0xd7, 0xbc,
0x3f, 0xf4, 0xde, 0xf0, 0x8e, 0x4b, 0x7a, 0x9d,
0xe5, 0x76, 0xd2, 0x65, 0x86, 0xce, 0xc6, 0x4b,
0x61, 0x16
}
};
static const size_t test_input_len[1] =
{
114U
};
static const unsigned char test_mac[1][16] =
{
{
0x1a, 0xe1, 0x0b, 0x59, 0x4f, 0x09, 0xe2, 0x6a,
0x7e, 0x90, 0x2e, 0xcb, 0xd0, 0x60, 0x06, 0x91
}
};
/* Make sure no other definition is already present. */
#undef ASSERT
#define ASSERT( cond, args ) \
do \
{ \
if( ! ( cond ) ) \
{ \
if( verbose != 0 ) \
mbedtls_printf args; \
\
return( -1 ); \
} \
} \
while( 0 )
int mbedtls_chachapoly_self_test( int verbose )
{
mbedtls_chachapoly_context ctx;
unsigned i;
int ret = MBEDTLS_ERR_ERROR_CORRUPTION_DETECTED;
unsigned char output[200];
unsigned char mac[16];
for( i = 0U; i < 1U; i++ )
{
if( verbose != 0 )
mbedtls_printf( " ChaCha20-Poly1305 test %u ", i );
mbedtls_chachapoly_init( &ctx );
ret = mbedtls_chachapoly_setkey( &ctx, test_key[i] );
ASSERT( 0 == ret, ( "setkey() error code: %i\n", ret ) );
ret = mbedtls_chachapoly_encrypt_and_tag( &ctx,
test_input_len[i],
test_nonce[i],
test_aad[i],
test_aad_len[i],
test_input[i],
output,
mac );
ASSERT( 0 == ret, ( "crypt_and_tag() error code: %i\n", ret ) );
ASSERT( 0 == memcmp( output, test_output[i], test_input_len[i] ),
( "failure (wrong output)\n" ) );
ASSERT( 0 == memcmp( mac, test_mac[i], 16U ),
( "failure (wrong MAC)\n" ) );
mbedtls_chachapoly_free( &ctx );
if( verbose != 0 )
mbedtls_printf( "passed\n" );
}
if( verbose != 0 )
mbedtls_printf( "\n" );
return( 0 );
}
#endif /* MBEDTLS_SELF_TEST */
#endif /* MBEDTLS_CHACHAPOLY_C */
|
0 | repos/gpt4all.zig/src/zig-libcurl/zig-mbedtls/mbedtls | repos/gpt4all.zig/src/zig-libcurl/zig-mbedtls/mbedtls/library/rsa_internal.c | /*
* Helper functions for the RSA module
*
* Copyright The Mbed TLS Contributors
* SPDX-License-Identifier: Apache-2.0
*
* 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.
*
*/
#include "common.h"
#if defined(MBEDTLS_RSA_C)
#include "mbedtls/rsa.h"
#include "mbedtls/bignum.h"
#include "mbedtls/rsa_internal.h"
/*
* Compute RSA prime factors from public and private exponents
*
* Summary of algorithm:
* Setting F := lcm(P-1,Q-1), the idea is as follows:
*
* (a) For any 1 <= X < N with gcd(X,N)=1, we have X^F = 1 modulo N, so X^(F/2)
* is a square root of 1 in Z/NZ. Since Z/NZ ~= Z/PZ x Z/QZ by CRT and the
* square roots of 1 in Z/PZ and Z/QZ are +1 and -1, this leaves the four
* possibilities X^(F/2) = (+-1, +-1). If it happens that X^(F/2) = (-1,+1)
* or (+1,-1), then gcd(X^(F/2) + 1, N) will be equal to one of the prime
* factors of N.
*
* (b) If we don't know F/2 but (F/2) * K for some odd (!) K, then the same
* construction still applies since (-)^K is the identity on the set of
* roots of 1 in Z/NZ.
*
* The public and private key primitives (-)^E and (-)^D are mutually inverse
* bijections on Z/NZ if and only if (-)^(DE) is the identity on Z/NZ, i.e.
* if and only if DE - 1 is a multiple of F, say DE - 1 = F * L.
* Splitting L = 2^t * K with K odd, we have
*
* DE - 1 = FL = (F/2) * (2^(t+1)) * K,
*
* so (F / 2) * K is among the numbers
*
* (DE - 1) >> 1, (DE - 1) >> 2, ..., (DE - 1) >> ord
*
* where ord is the order of 2 in (DE - 1).
* We can therefore iterate through these numbers apply the construction
* of (a) and (b) above to attempt to factor N.
*
*/
int mbedtls_rsa_deduce_primes( mbedtls_mpi const *N,
mbedtls_mpi const *E, mbedtls_mpi const *D,
mbedtls_mpi *P, mbedtls_mpi *Q )
{
int ret = 0;
uint16_t attempt; /* Number of current attempt */
uint16_t iter; /* Number of squares computed in the current attempt */
uint16_t order; /* Order of 2 in DE - 1 */
mbedtls_mpi T; /* Holds largest odd divisor of DE - 1 */
mbedtls_mpi K; /* Temporary holding the current candidate */
const unsigned char primes[] = { 2,
3, 5, 7, 11, 13, 17, 19, 23,
29, 31, 37, 41, 43, 47, 53, 59,
61, 67, 71, 73, 79, 83, 89, 97,
101, 103, 107, 109, 113, 127, 131, 137,
139, 149, 151, 157, 163, 167, 173, 179,
181, 191, 193, 197, 199, 211, 223, 227,
229, 233, 239, 241, 251
};
const size_t num_primes = sizeof( primes ) / sizeof( *primes );
if( P == NULL || Q == NULL || P->p != NULL || Q->p != NULL )
return( MBEDTLS_ERR_MPI_BAD_INPUT_DATA );
if( mbedtls_mpi_cmp_int( N, 0 ) <= 0 ||
mbedtls_mpi_cmp_int( D, 1 ) <= 0 ||
mbedtls_mpi_cmp_mpi( D, N ) >= 0 ||
mbedtls_mpi_cmp_int( E, 1 ) <= 0 ||
mbedtls_mpi_cmp_mpi( E, N ) >= 0 )
{
return( MBEDTLS_ERR_MPI_BAD_INPUT_DATA );
}
/*
* Initializations and temporary changes
*/
mbedtls_mpi_init( &K );
mbedtls_mpi_init( &T );
/* T := DE - 1 */
MBEDTLS_MPI_CHK( mbedtls_mpi_mul_mpi( &T, D, E ) );
MBEDTLS_MPI_CHK( mbedtls_mpi_sub_int( &T, &T, 1 ) );
if( ( order = (uint16_t) mbedtls_mpi_lsb( &T ) ) == 0 )
{
ret = MBEDTLS_ERR_MPI_BAD_INPUT_DATA;
goto cleanup;
}
/* After this operation, T holds the largest odd divisor of DE - 1. */
MBEDTLS_MPI_CHK( mbedtls_mpi_shift_r( &T, order ) );
/*
* Actual work
*/
/* Skip trying 2 if N == 1 mod 8 */
attempt = 0;
if( N->p[0] % 8 == 1 )
attempt = 1;
for( ; attempt < num_primes; ++attempt )
{
mbedtls_mpi_lset( &K, primes[attempt] );
/* Check if gcd(K,N) = 1 */
MBEDTLS_MPI_CHK( mbedtls_mpi_gcd( P, &K, N ) );
if( mbedtls_mpi_cmp_int( P, 1 ) != 0 )
continue;
/* Go through K^T + 1, K^(2T) + 1, K^(4T) + 1, ...
* and check whether they have nontrivial GCD with N. */
MBEDTLS_MPI_CHK( mbedtls_mpi_exp_mod( &K, &K, &T, N,
Q /* temporarily use Q for storing Montgomery
* multiplication helper values */ ) );
for( iter = 1; iter <= order; ++iter )
{
/* If we reach 1 prematurely, there's no point
* in continuing to square K */
if( mbedtls_mpi_cmp_int( &K, 1 ) == 0 )
break;
MBEDTLS_MPI_CHK( mbedtls_mpi_add_int( &K, &K, 1 ) );
MBEDTLS_MPI_CHK( mbedtls_mpi_gcd( P, &K, N ) );
if( mbedtls_mpi_cmp_int( P, 1 ) == 1 &&
mbedtls_mpi_cmp_mpi( P, N ) == -1 )
{
/*
* Have found a nontrivial divisor P of N.
* Set Q := N / P.
*/
MBEDTLS_MPI_CHK( mbedtls_mpi_div_mpi( Q, NULL, N, P ) );
goto cleanup;
}
MBEDTLS_MPI_CHK( mbedtls_mpi_sub_int( &K, &K, 1 ) );
MBEDTLS_MPI_CHK( mbedtls_mpi_mul_mpi( &K, &K, &K ) );
MBEDTLS_MPI_CHK( mbedtls_mpi_mod_mpi( &K, &K, N ) );
}
/*
* If we get here, then either we prematurely aborted the loop because
* we reached 1, or K holds primes[attempt]^(DE - 1) mod N, which must
* be 1 if D,E,N were consistent.
* Check if that's the case and abort if not, to avoid very long,
* yet eventually failing, computations if N,D,E were not sane.
*/
if( mbedtls_mpi_cmp_int( &K, 1 ) != 0 )
{
break;
}
}
ret = MBEDTLS_ERR_MPI_BAD_INPUT_DATA;
cleanup:
mbedtls_mpi_free( &K );
mbedtls_mpi_free( &T );
return( ret );
}
/*
* Given P, Q and the public exponent E, deduce D.
* This is essentially a modular inversion.
*/
int mbedtls_rsa_deduce_private_exponent( mbedtls_mpi const *P,
mbedtls_mpi const *Q,
mbedtls_mpi const *E,
mbedtls_mpi *D )
{
int ret = 0;
mbedtls_mpi K, L;
if( D == NULL || mbedtls_mpi_cmp_int( D, 0 ) != 0 )
return( MBEDTLS_ERR_MPI_BAD_INPUT_DATA );
if( mbedtls_mpi_cmp_int( P, 1 ) <= 0 ||
mbedtls_mpi_cmp_int( Q, 1 ) <= 0 ||
mbedtls_mpi_cmp_int( E, 0 ) == 0 )
{
return( MBEDTLS_ERR_MPI_BAD_INPUT_DATA );
}
mbedtls_mpi_init( &K );
mbedtls_mpi_init( &L );
/* Temporarily put K := P-1 and L := Q-1 */
MBEDTLS_MPI_CHK( mbedtls_mpi_sub_int( &K, P, 1 ) );
MBEDTLS_MPI_CHK( mbedtls_mpi_sub_int( &L, Q, 1 ) );
/* Temporarily put D := gcd(P-1, Q-1) */
MBEDTLS_MPI_CHK( mbedtls_mpi_gcd( D, &K, &L ) );
/* K := LCM(P-1, Q-1) */
MBEDTLS_MPI_CHK( mbedtls_mpi_mul_mpi( &K, &K, &L ) );
MBEDTLS_MPI_CHK( mbedtls_mpi_div_mpi( &K, NULL, &K, D ) );
/* Compute modular inverse of E in LCM(P-1, Q-1) */
MBEDTLS_MPI_CHK( mbedtls_mpi_inv_mod( D, E, &K ) );
cleanup:
mbedtls_mpi_free( &K );
mbedtls_mpi_free( &L );
return( ret );
}
/*
* Check that RSA CRT parameters are in accordance with core parameters.
*/
int mbedtls_rsa_validate_crt( const mbedtls_mpi *P, const mbedtls_mpi *Q,
const mbedtls_mpi *D, const mbedtls_mpi *DP,
const mbedtls_mpi *DQ, const mbedtls_mpi *QP )
{
int ret = 0;
mbedtls_mpi K, L;
mbedtls_mpi_init( &K );
mbedtls_mpi_init( &L );
/* Check that DP - D == 0 mod P - 1 */
if( DP != NULL )
{
if( P == NULL )
{
ret = MBEDTLS_ERR_RSA_BAD_INPUT_DATA;
goto cleanup;
}
MBEDTLS_MPI_CHK( mbedtls_mpi_sub_int( &K, P, 1 ) );
MBEDTLS_MPI_CHK( mbedtls_mpi_sub_mpi( &L, DP, D ) );
MBEDTLS_MPI_CHK( mbedtls_mpi_mod_mpi( &L, &L, &K ) );
if( mbedtls_mpi_cmp_int( &L, 0 ) != 0 )
{
ret = MBEDTLS_ERR_RSA_KEY_CHECK_FAILED;
goto cleanup;
}
}
/* Check that DQ - D == 0 mod Q - 1 */
if( DQ != NULL )
{
if( Q == NULL )
{
ret = MBEDTLS_ERR_RSA_BAD_INPUT_DATA;
goto cleanup;
}
MBEDTLS_MPI_CHK( mbedtls_mpi_sub_int( &K, Q, 1 ) );
MBEDTLS_MPI_CHK( mbedtls_mpi_sub_mpi( &L, DQ, D ) );
MBEDTLS_MPI_CHK( mbedtls_mpi_mod_mpi( &L, &L, &K ) );
if( mbedtls_mpi_cmp_int( &L, 0 ) != 0 )
{
ret = MBEDTLS_ERR_RSA_KEY_CHECK_FAILED;
goto cleanup;
}
}
/* Check that QP * Q - 1 == 0 mod P */
if( QP != NULL )
{
if( P == NULL || Q == NULL )
{
ret = MBEDTLS_ERR_RSA_BAD_INPUT_DATA;
goto cleanup;
}
MBEDTLS_MPI_CHK( mbedtls_mpi_mul_mpi( &K, QP, Q ) );
MBEDTLS_MPI_CHK( mbedtls_mpi_sub_int( &K, &K, 1 ) );
MBEDTLS_MPI_CHK( mbedtls_mpi_mod_mpi( &K, &K, P ) );
if( mbedtls_mpi_cmp_int( &K, 0 ) != 0 )
{
ret = MBEDTLS_ERR_RSA_KEY_CHECK_FAILED;
goto cleanup;
}
}
cleanup:
/* Wrap MPI error codes by RSA check failure error code */
if( ret != 0 &&
ret != MBEDTLS_ERR_RSA_KEY_CHECK_FAILED &&
ret != MBEDTLS_ERR_RSA_BAD_INPUT_DATA )
{
ret += MBEDTLS_ERR_RSA_KEY_CHECK_FAILED;
}
mbedtls_mpi_free( &K );
mbedtls_mpi_free( &L );
return( ret );
}
/*
* Check that core RSA parameters are sane.
*/
int mbedtls_rsa_validate_params( const mbedtls_mpi *N, const mbedtls_mpi *P,
const mbedtls_mpi *Q, const mbedtls_mpi *D,
const mbedtls_mpi *E,
int (*f_rng)(void *, unsigned char *, size_t),
void *p_rng )
{
int ret = 0;
mbedtls_mpi K, L;
mbedtls_mpi_init( &K );
mbedtls_mpi_init( &L );
/*
* Step 1: If PRNG provided, check that P and Q are prime
*/
#if defined(MBEDTLS_GENPRIME)
/*
* When generating keys, the strongest security we support aims for an error
* rate of at most 2^-100 and we are aiming for the same certainty here as
* well.
*/
if( f_rng != NULL && P != NULL &&
( ret = mbedtls_mpi_is_prime_ext( P, 50, f_rng, p_rng ) ) != 0 )
{
ret = MBEDTLS_ERR_RSA_KEY_CHECK_FAILED;
goto cleanup;
}
if( f_rng != NULL && Q != NULL &&
( ret = mbedtls_mpi_is_prime_ext( Q, 50, f_rng, p_rng ) ) != 0 )
{
ret = MBEDTLS_ERR_RSA_KEY_CHECK_FAILED;
goto cleanup;
}
#else
((void) f_rng);
((void) p_rng);
#endif /* MBEDTLS_GENPRIME */
/*
* Step 2: Check that 1 < N = P * Q
*/
if( P != NULL && Q != NULL && N != NULL )
{
MBEDTLS_MPI_CHK( mbedtls_mpi_mul_mpi( &K, P, Q ) );
if( mbedtls_mpi_cmp_int( N, 1 ) <= 0 ||
mbedtls_mpi_cmp_mpi( &K, N ) != 0 )
{
ret = MBEDTLS_ERR_RSA_KEY_CHECK_FAILED;
goto cleanup;
}
}
/*
* Step 3: Check and 1 < D, E < N if present.
*/
if( N != NULL && D != NULL && E != NULL )
{
if ( mbedtls_mpi_cmp_int( D, 1 ) <= 0 ||
mbedtls_mpi_cmp_int( E, 1 ) <= 0 ||
mbedtls_mpi_cmp_mpi( D, N ) >= 0 ||
mbedtls_mpi_cmp_mpi( E, N ) >= 0 )
{
ret = MBEDTLS_ERR_RSA_KEY_CHECK_FAILED;
goto cleanup;
}
}
/*
* Step 4: Check that D, E are inverse modulo P-1 and Q-1
*/
if( P != NULL && Q != NULL && D != NULL && E != NULL )
{
if( mbedtls_mpi_cmp_int( P, 1 ) <= 0 ||
mbedtls_mpi_cmp_int( Q, 1 ) <= 0 )
{
ret = MBEDTLS_ERR_RSA_KEY_CHECK_FAILED;
goto cleanup;
}
/* Compute DE-1 mod P-1 */
MBEDTLS_MPI_CHK( mbedtls_mpi_mul_mpi( &K, D, E ) );
MBEDTLS_MPI_CHK( mbedtls_mpi_sub_int( &K, &K, 1 ) );
MBEDTLS_MPI_CHK( mbedtls_mpi_sub_int( &L, P, 1 ) );
MBEDTLS_MPI_CHK( mbedtls_mpi_mod_mpi( &K, &K, &L ) );
if( mbedtls_mpi_cmp_int( &K, 0 ) != 0 )
{
ret = MBEDTLS_ERR_RSA_KEY_CHECK_FAILED;
goto cleanup;
}
/* Compute DE-1 mod Q-1 */
MBEDTLS_MPI_CHK( mbedtls_mpi_mul_mpi( &K, D, E ) );
MBEDTLS_MPI_CHK( mbedtls_mpi_sub_int( &K, &K, 1 ) );
MBEDTLS_MPI_CHK( mbedtls_mpi_sub_int( &L, Q, 1 ) );
MBEDTLS_MPI_CHK( mbedtls_mpi_mod_mpi( &K, &K, &L ) );
if( mbedtls_mpi_cmp_int( &K, 0 ) != 0 )
{
ret = MBEDTLS_ERR_RSA_KEY_CHECK_FAILED;
goto cleanup;
}
}
cleanup:
mbedtls_mpi_free( &K );
mbedtls_mpi_free( &L );
/* Wrap MPI error codes by RSA check failure error code */
if( ret != 0 && ret != MBEDTLS_ERR_RSA_KEY_CHECK_FAILED )
{
ret += MBEDTLS_ERR_RSA_KEY_CHECK_FAILED;
}
return( ret );
}
int mbedtls_rsa_deduce_crt( const mbedtls_mpi *P, const mbedtls_mpi *Q,
const mbedtls_mpi *D, mbedtls_mpi *DP,
mbedtls_mpi *DQ, mbedtls_mpi *QP )
{
int ret = 0;
mbedtls_mpi K;
mbedtls_mpi_init( &K );
/* DP = D mod P-1 */
if( DP != NULL )
{
MBEDTLS_MPI_CHK( mbedtls_mpi_sub_int( &K, P, 1 ) );
MBEDTLS_MPI_CHK( mbedtls_mpi_mod_mpi( DP, D, &K ) );
}
/* DQ = D mod Q-1 */
if( DQ != NULL )
{
MBEDTLS_MPI_CHK( mbedtls_mpi_sub_int( &K, Q, 1 ) );
MBEDTLS_MPI_CHK( mbedtls_mpi_mod_mpi( DQ, D, &K ) );
}
/* QP = Q^{-1} mod P */
if( QP != NULL )
{
MBEDTLS_MPI_CHK( mbedtls_mpi_inv_mod( QP, Q, P ) );
}
cleanup:
mbedtls_mpi_free( &K );
return( ret );
}
#endif /* MBEDTLS_RSA_C */
|
0 | repos/gpt4all.zig/src/zig-libcurl/zig-mbedtls/mbedtls | repos/gpt4all.zig/src/zig-libcurl/zig-mbedtls/mbedtls/library/ssl_tls13_keys.h | /*
* TLS 1.3 key schedule
*
* Copyright The Mbed TLS Contributors
* SPDX-License-Identifier: Apache-2.0
*
* 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.
*/
#if !defined(MBEDTLS_SSL_TLS1_3_KEYS_H)
#define MBEDTLS_SSL_TLS1_3_KEYS_H
/* This requires MBEDTLS_SSL_TLS1_3_LABEL( idx, name, string ) to be defined at
* the point of use. See e.g. the definition of mbedtls_ssl_tls1_3_labels_union
* below. */
#define MBEDTLS_SSL_TLS1_3_LABEL_LIST \
MBEDTLS_SSL_TLS1_3_LABEL( finished , "finished" ) \
MBEDTLS_SSL_TLS1_3_LABEL( resumption , "resumption" ) \
MBEDTLS_SSL_TLS1_3_LABEL( traffic_upd , "traffic upd" ) \
MBEDTLS_SSL_TLS1_3_LABEL( exporter , "exporter" ) \
MBEDTLS_SSL_TLS1_3_LABEL( key , "key" ) \
MBEDTLS_SSL_TLS1_3_LABEL( iv , "iv" ) \
MBEDTLS_SSL_TLS1_3_LABEL( c_hs_traffic, "c hs traffic" ) \
MBEDTLS_SSL_TLS1_3_LABEL( c_ap_traffic, "c ap traffic" ) \
MBEDTLS_SSL_TLS1_3_LABEL( c_e_traffic , "c e traffic" ) \
MBEDTLS_SSL_TLS1_3_LABEL( s_hs_traffic, "s hs traffic" ) \
MBEDTLS_SSL_TLS1_3_LABEL( s_ap_traffic, "s ap traffic" ) \
MBEDTLS_SSL_TLS1_3_LABEL( s_e_traffic , "s e traffic" ) \
MBEDTLS_SSL_TLS1_3_LABEL( e_exp_master, "e exp master" ) \
MBEDTLS_SSL_TLS1_3_LABEL( res_master , "res master" ) \
MBEDTLS_SSL_TLS1_3_LABEL( exp_master , "exp master" ) \
MBEDTLS_SSL_TLS1_3_LABEL( ext_binder , "ext binder" ) \
MBEDTLS_SSL_TLS1_3_LABEL( res_binder , "res binder" ) \
MBEDTLS_SSL_TLS1_3_LABEL( derived , "derived" )
#define MBEDTLS_SSL_TLS1_3_LABEL( name, string ) \
const unsigned char name [ sizeof(string) - 1 ];
union mbedtls_ssl_tls1_3_labels_union
{
MBEDTLS_SSL_TLS1_3_LABEL_LIST
};
struct mbedtls_ssl_tls1_3_labels_struct
{
MBEDTLS_SSL_TLS1_3_LABEL_LIST
};
#undef MBEDTLS_SSL_TLS1_3_LABEL
extern const struct mbedtls_ssl_tls1_3_labels_struct mbedtls_ssl_tls1_3_labels;
#define MBEDTLS_SSL_TLS1_3_LBL_WITH_LEN( LABEL ) \
mbedtls_ssl_tls1_3_labels.LABEL, \
sizeof(mbedtls_ssl_tls1_3_labels.LABEL)
#define MBEDTLS_SSL_TLS1_3_KEY_SCHEDULE_MAX_LABEL_LEN \
sizeof( union mbedtls_ssl_tls1_3_labels_union )
/* The maximum length of HKDF contexts used in the TLS 1.3 standard.
* Since contexts are always hashes of message transcripts, this can
* be approximated from above by the maximum hash size. */
#define MBEDTLS_SSL_TLS1_3_KEY_SCHEDULE_MAX_CONTEXT_LEN \
MBEDTLS_MD_MAX_SIZE
/* Maximum desired length for expanded key material generated
* by HKDF-Expand-Label.
*
* Warning: If this ever needs to be increased, the implementation
* ssl_tls1_3_hkdf_encode_label() in ssl_tls13_keys.c needs to be
* adjusted since it currently assumes that HKDF key expansion
* is never used with more than 255 Bytes of output. */
#define MBEDTLS_SSL_TLS1_3_KEY_SCHEDULE_MAX_EXPANSION_LEN 255
/**
* \brief The \c HKDF-Expand-Label function from
* the TLS 1.3 standard RFC 8446.
*
* <tt>
* HKDF-Expand-Label( Secret, Label, Context, Length ) =
* HKDF-Expand( Secret, HkdfLabel, Length )
* </tt>
*
* \param hash_alg The identifier for the hash algorithm to use.
* \param secret The \c Secret argument to \c HKDF-Expand-Label.
* This must be a readable buffer of length \p slen Bytes.
* \param slen The length of \p secret in Bytes.
* \param label The \c Label argument to \c HKDF-Expand-Label.
* This must be a readable buffer of length \p llen Bytes.
* \param llen The length of \p label in Bytes.
* \param ctx The \c Context argument to \c HKDF-Expand-Label.
* This must be a readable buffer of length \p clen Bytes.
* \param clen The length of \p context in Bytes.
* \param buf The destination buffer to hold the expanded secret.
* This must be a writable buffer of length \p blen Bytes.
* \param blen The desired size of the expanded secret in Bytes.
*
* \returns \c 0 on success.
* \return A negative error code on failure.
*/
int mbedtls_ssl_tls1_3_hkdf_expand_label(
mbedtls_md_type_t hash_alg,
const unsigned char *secret, size_t slen,
const unsigned char *label, size_t llen,
const unsigned char *ctx, size_t clen,
unsigned char *buf, size_t blen );
/**
* \brief This function is part of the TLS 1.3 key schedule.
* It extracts key and IV for the actual client/server traffic
* from the client/server traffic secrets.
*
* From RFC 8446:
*
* <tt>
* [sender]_write_key = HKDF-Expand-Label(Secret, "key", "", key_length)
* [sender]_write_iv = HKDF-Expand-Label(Secret, "iv", "", iv_length)*
* </tt>
*
* \param hash_alg The identifier for the hash algorithm to be used
* for the HKDF-based expansion of the secret.
* \param client_secret The client traffic secret.
* This must be a readable buffer of size \p slen Bytes
* \param server_secret The server traffic secret.
* This must be a readable buffer of size \p slen Bytes
* \param slen Length of the secrets \p client_secret and
* \p server_secret in Bytes.
* \param key_len The desired length of the key to be extracted in Bytes.
* \param iv_len The desired length of the IV to be extracted in Bytes.
* \param keys The address of the structure holding the generated
* keys and IVs.
*
* \returns \c 0 on success.
* \returns A negative error code on failure.
*/
int mbedtls_ssl_tls1_3_make_traffic_keys(
mbedtls_md_type_t hash_alg,
const unsigned char *client_secret,
const unsigned char *server_secret,
size_t slen, size_t key_len, size_t iv_len,
mbedtls_ssl_key_set *keys );
#define MBEDTLS_SSL_TLS1_3_CONTEXT_UNHASHED 0
#define MBEDTLS_SSL_TLS1_3_CONTEXT_HASHED 1
/**
* \brief The \c Derive-Secret function from the TLS 1.3 standard RFC 8446.
*
* <tt>
* Derive-Secret( Secret, Label, Messages ) =
* HKDF-Expand-Label( Secret, Label,
* Hash( Messages ),
* Hash.Length ) )
* </tt>
*
* \param hash_alg The identifier for the hash function used for the
* applications of HKDF.
* \param secret The \c Secret argument to the \c Derive-Secret function.
* This must be a readable buffer of length \p slen Bytes.
* \param slen The length of \p secret in Bytes.
* \param label The \c Label argument to the \c Derive-Secret function.
* This must be a readable buffer of length \p llen Bytes.
* \param llen The length of \p label in Bytes.
* \param ctx The hash of the \c Messages argument to the
* \c Derive-Secret function, or the \c Messages argument
* itself, depending on \p context_already_hashed.
* \param clen The length of \p hash.
* \param ctx_hashed This indicates whether the \p ctx contains the hash of
* the \c Messages argument in the application of the
* \c Derive-Secret function
* (value MBEDTLS_SSL_TLS1_3_CONTEXT_HASHED), or whether
* it is the content of \c Messages itself, in which case
* the function takes care of the hashing
* (value MBEDTLS_SSL_TLS1_3_CONTEXT_UNHASHED).
* \param dstbuf The target buffer to write the output of
* \c Derive-Secret to. This must be a writable buffer of
* size \p buflen Bytes.
* \param buflen The length of \p dstbuf in Bytes.
*
* \returns \c 0 on success.
* \returns A negative error code on failure.
*/
int mbedtls_ssl_tls1_3_derive_secret(
mbedtls_md_type_t hash_alg,
const unsigned char *secret, size_t slen,
const unsigned char *label, size_t llen,
const unsigned char *ctx, size_t clen,
int ctx_hashed,
unsigned char *dstbuf, size_t buflen );
/**
* \brief Compute the next secret in the TLS 1.3 key schedule
*
* The TLS 1.3 key schedule proceeds as follows to compute
* the three main secrets during the handshake: The early
* secret for early data, the handshake secret for all
* other encrypted handshake messages, and the master
* secret for all application traffic.
*
* <tt>
* 0
* |
* v
* PSK -> HKDF-Extract = Early Secret
* |
* v
* Derive-Secret( ., "derived", "" )
* |
* v
* (EC)DHE -> HKDF-Extract = Handshake Secret
* |
* v
* Derive-Secret( ., "derived", "" )
* |
* v
* 0 -> HKDF-Extract = Master Secret
* </tt>
*
* Each of the three secrets in turn is the basis for further
* key derivations, such as the derivation of traffic keys and IVs;
* see e.g. mbedtls_ssl_tls1_3_make_traffic_keys().
*
* This function implements one step in this evolution of secrets:
*
* <tt>
* old_secret
* |
* v
* Derive-Secret( ., "derived", "" )
* |
* v
* input -> HKDF-Extract = new_secret
* </tt>
*
* \param hash_alg The identifier for the hash function used for the
* applications of HKDF.
* \param secret_old The address of the buffer holding the old secret
* on function entry. If not \c NULL, this must be a
* readable buffer whose size matches the output size
* of the hash function represented by \p hash_alg.
* If \c NULL, an all \c 0 array will be used instead.
* \param input The address of the buffer holding the additional
* input for the key derivation (e.g., the PSK or the
* ephemeral (EC)DH secret). If not \c NULL, this must be
* a readable buffer whose size \p input_len Bytes.
* If \c NULL, an all \c 0 array will be used instead.
* \param input_len The length of \p input in Bytes.
* \param secret_new The address of the buffer holding the new secret
* on function exit. This must be a writable buffer
* whose size matches the output size of the hash
* function represented by \p hash_alg.
* This may be the same as \p secret_old.
*
* \returns \c 0 on success.
* \returns A negative error code on failure.
*/
int mbedtls_ssl_tls1_3_evolve_secret(
mbedtls_md_type_t hash_alg,
const unsigned char *secret_old,
const unsigned char *input, size_t input_len,
unsigned char *secret_new );
#endif /* MBEDTLS_SSL_TLS1_3_KEYS_H */
|
0 | repos/gpt4all.zig/src/zig-libcurl/zig-mbedtls/mbedtls | repos/gpt4all.zig/src/zig-libcurl/zig-mbedtls/mbedtls/library/ssl_cookie.c | /*
* DTLS cookie callbacks implementation
*
* Copyright The Mbed TLS Contributors
* SPDX-License-Identifier: Apache-2.0
*
* 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.
*/
/*
* These session callbacks use a simple chained list
* to store and retrieve the session information.
*/
#include "common.h"
#if defined(MBEDTLS_SSL_COOKIE_C)
#if defined(MBEDTLS_PLATFORM_C)
#include "mbedtls/platform.h"
#else
#define mbedtls_calloc calloc
#define mbedtls_free free
#endif
#include "mbedtls/ssl_cookie.h"
#include "mbedtls/ssl_internal.h"
#include "mbedtls/error.h"
#include "mbedtls/platform_util.h"
#include <string.h>
/*
* If DTLS is in use, then at least one of SHA-1, SHA-256, SHA-512 is
* available. Try SHA-256 first, 512 wastes resources since we need to stay
* with max 32 bytes of cookie for DTLS 1.0
*/
#if defined(MBEDTLS_SHA256_C)
#define COOKIE_MD MBEDTLS_MD_SHA224
#define COOKIE_MD_OUTLEN 32
#define COOKIE_HMAC_LEN 28
#elif defined(MBEDTLS_SHA512_C)
#define COOKIE_MD MBEDTLS_MD_SHA384
#define COOKIE_MD_OUTLEN 48
#define COOKIE_HMAC_LEN 28
#elif defined(MBEDTLS_SHA1_C)
#define COOKIE_MD MBEDTLS_MD_SHA1
#define COOKIE_MD_OUTLEN 20
#define COOKIE_HMAC_LEN 20
#else
#error "DTLS hello verify needs SHA-1 or SHA-2"
#endif
/*
* Cookies are formed of a 4-bytes timestamp (or serial number) and
* an HMAC of timestemp and client ID.
*/
#define COOKIE_LEN ( 4 + COOKIE_HMAC_LEN )
void mbedtls_ssl_cookie_init( mbedtls_ssl_cookie_ctx *ctx )
{
mbedtls_md_init( &ctx->hmac_ctx );
#if !defined(MBEDTLS_HAVE_TIME)
ctx->serial = 0;
#endif
ctx->timeout = MBEDTLS_SSL_COOKIE_TIMEOUT;
#if defined(MBEDTLS_THREADING_C)
mbedtls_mutex_init( &ctx->mutex );
#endif
}
void mbedtls_ssl_cookie_set_timeout( mbedtls_ssl_cookie_ctx *ctx, unsigned long delay )
{
ctx->timeout = delay;
}
void mbedtls_ssl_cookie_free( mbedtls_ssl_cookie_ctx *ctx )
{
mbedtls_md_free( &ctx->hmac_ctx );
#if defined(MBEDTLS_THREADING_C)
mbedtls_mutex_free( &ctx->mutex );
#endif
mbedtls_platform_zeroize( ctx, sizeof( mbedtls_ssl_cookie_ctx ) );
}
int mbedtls_ssl_cookie_setup( mbedtls_ssl_cookie_ctx *ctx,
int (*f_rng)(void *, unsigned char *, size_t),
void *p_rng )
{
int ret = MBEDTLS_ERR_ERROR_CORRUPTION_DETECTED;
unsigned char key[COOKIE_MD_OUTLEN];
if( ( ret = f_rng( p_rng, key, sizeof( key ) ) ) != 0 )
return( ret );
ret = mbedtls_md_setup( &ctx->hmac_ctx, mbedtls_md_info_from_type( COOKIE_MD ), 1 );
if( ret != 0 )
return( ret );
ret = mbedtls_md_hmac_starts( &ctx->hmac_ctx, key, sizeof( key ) );
if( ret != 0 )
return( ret );
mbedtls_platform_zeroize( key, sizeof( key ) );
return( 0 );
}
/*
* Generate the HMAC part of a cookie
*/
static int ssl_cookie_hmac( mbedtls_md_context_t *hmac_ctx,
const unsigned char time[4],
unsigned char **p, unsigned char *end,
const unsigned char *cli_id, size_t cli_id_len )
{
unsigned char hmac_out[COOKIE_MD_OUTLEN];
MBEDTLS_SSL_CHK_BUF_PTR( *p, end, COOKIE_HMAC_LEN );
if( mbedtls_md_hmac_reset( hmac_ctx ) != 0 ||
mbedtls_md_hmac_update( hmac_ctx, time, 4 ) != 0 ||
mbedtls_md_hmac_update( hmac_ctx, cli_id, cli_id_len ) != 0 ||
mbedtls_md_hmac_finish( hmac_ctx, hmac_out ) != 0 )
{
return( MBEDTLS_ERR_SSL_INTERNAL_ERROR );
}
memcpy( *p, hmac_out, COOKIE_HMAC_LEN );
*p += COOKIE_HMAC_LEN;
return( 0 );
}
/*
* Generate cookie for DTLS ClientHello verification
*/
int mbedtls_ssl_cookie_write( void *p_ctx,
unsigned char **p, unsigned char *end,
const unsigned char *cli_id, size_t cli_id_len )
{
int ret = MBEDTLS_ERR_ERROR_CORRUPTION_DETECTED;
mbedtls_ssl_cookie_ctx *ctx = (mbedtls_ssl_cookie_ctx *) p_ctx;
unsigned long t;
if( ctx == NULL || cli_id == NULL )
return( MBEDTLS_ERR_SSL_BAD_INPUT_DATA );
MBEDTLS_SSL_CHK_BUF_PTR( *p, end, COOKIE_LEN );
#if defined(MBEDTLS_HAVE_TIME)
t = (unsigned long) mbedtls_time( NULL );
#else
t = ctx->serial++;
#endif
(*p)[0] = (unsigned char)( t >> 24 );
(*p)[1] = (unsigned char)( t >> 16 );
(*p)[2] = (unsigned char)( t >> 8 );
(*p)[3] = (unsigned char)( t );
*p += 4;
#if defined(MBEDTLS_THREADING_C)
if( ( ret = mbedtls_mutex_lock( &ctx->mutex ) ) != 0 )
return( MBEDTLS_ERROR_ADD( MBEDTLS_ERR_SSL_INTERNAL_ERROR, ret ) );
#endif
ret = ssl_cookie_hmac( &ctx->hmac_ctx, *p - 4,
p, end, cli_id, cli_id_len );
#if defined(MBEDTLS_THREADING_C)
if( mbedtls_mutex_unlock( &ctx->mutex ) != 0 )
return( MBEDTLS_ERROR_ADD( MBEDTLS_ERR_SSL_INTERNAL_ERROR,
MBEDTLS_ERR_THREADING_MUTEX_ERROR ) );
#endif
return( ret );
}
/*
* Check a cookie
*/
int mbedtls_ssl_cookie_check( void *p_ctx,
const unsigned char *cookie, size_t cookie_len,
const unsigned char *cli_id, size_t cli_id_len )
{
unsigned char ref_hmac[COOKIE_HMAC_LEN];
int ret = 0;
unsigned char *p = ref_hmac;
mbedtls_ssl_cookie_ctx *ctx = (mbedtls_ssl_cookie_ctx *) p_ctx;
unsigned long cur_time, cookie_time;
if( ctx == NULL || cli_id == NULL )
return( MBEDTLS_ERR_SSL_BAD_INPUT_DATA );
if( cookie_len != COOKIE_LEN )
return( -1 );
#if defined(MBEDTLS_THREADING_C)
if( ( ret = mbedtls_mutex_lock( &ctx->mutex ) ) != 0 )
return( MBEDTLS_ERROR_ADD( MBEDTLS_ERR_SSL_INTERNAL_ERROR, ret ) );
#endif
if( ssl_cookie_hmac( &ctx->hmac_ctx, cookie,
&p, p + sizeof( ref_hmac ),
cli_id, cli_id_len ) != 0 )
ret = -1;
#if defined(MBEDTLS_THREADING_C)
if( mbedtls_mutex_unlock( &ctx->mutex ) != 0 )
return( MBEDTLS_ERROR_ADD( MBEDTLS_ERR_SSL_INTERNAL_ERROR,
MBEDTLS_ERR_THREADING_MUTEX_ERROR ) );
#endif
if( ret != 0 )
return( ret );
if( mbedtls_ssl_safer_memcmp( cookie + 4, ref_hmac, sizeof( ref_hmac ) ) != 0 )
return( -1 );
#if defined(MBEDTLS_HAVE_TIME)
cur_time = (unsigned long) mbedtls_time( NULL );
#else
cur_time = ctx->serial;
#endif
cookie_time = ( (unsigned long) cookie[0] << 24 ) |
( (unsigned long) cookie[1] << 16 ) |
( (unsigned long) cookie[2] << 8 ) |
( (unsigned long) cookie[3] );
if( ctx->timeout != 0 && cur_time - cookie_time > ctx->timeout )
return( -1 );
return( 0 );
}
#endif /* MBEDTLS_SSL_COOKIE_C */
|
0 | repos/gpt4all.zig/src/zig-libcurl/zig-mbedtls/mbedtls | repos/gpt4all.zig/src/zig-libcurl/zig-mbedtls/mbedtls/library/arc4.c | /*
* An implementation of the ARCFOUR algorithm
*
* Copyright The Mbed TLS Contributors
* SPDX-License-Identifier: Apache-2.0
*
* 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.
*/
/*
* The ARCFOUR algorithm was publicly disclosed on 94/09.
*
* http://groups.google.com/group/sci.crypt/msg/10a300c9d21afca0
*/
#include "common.h"
#if defined(MBEDTLS_ARC4_C)
#include "mbedtls/arc4.h"
#include "mbedtls/platform_util.h"
#include <string.h>
#if defined(MBEDTLS_SELF_TEST)
#if defined(MBEDTLS_PLATFORM_C)
#include "mbedtls/platform.h"
#else
#include <stdio.h>
#define mbedtls_printf printf
#endif /* MBEDTLS_PLATFORM_C */
#endif /* MBEDTLS_SELF_TEST */
#if !defined(MBEDTLS_ARC4_ALT)
void mbedtls_arc4_init( mbedtls_arc4_context *ctx )
{
memset( ctx, 0, sizeof( mbedtls_arc4_context ) );
}
void mbedtls_arc4_free( mbedtls_arc4_context *ctx )
{
if( ctx == NULL )
return;
mbedtls_platform_zeroize( ctx, sizeof( mbedtls_arc4_context ) );
}
/*
* ARC4 key schedule
*/
void mbedtls_arc4_setup( mbedtls_arc4_context *ctx, const unsigned char *key,
unsigned int keylen )
{
int i, j, a;
unsigned int k;
unsigned char *m;
ctx->x = 0;
ctx->y = 0;
m = ctx->m;
for( i = 0; i < 256; i++ )
m[i] = (unsigned char) i;
j = k = 0;
for( i = 0; i < 256; i++, k++ )
{
if( k >= keylen ) k = 0;
a = m[i];
j = ( j + a + key[k] ) & 0xFF;
m[i] = m[j];
m[j] = (unsigned char) a;
}
}
/*
* ARC4 cipher function
*/
int mbedtls_arc4_crypt( mbedtls_arc4_context *ctx, size_t length, const unsigned char *input,
unsigned char *output )
{
int x, y, a, b;
size_t i;
unsigned char *m;
x = ctx->x;
y = ctx->y;
m = ctx->m;
for( i = 0; i < length; i++ )
{
x = ( x + 1 ) & 0xFF; a = m[x];
y = ( y + a ) & 0xFF; b = m[y];
m[x] = (unsigned char) b;
m[y] = (unsigned char) a;
output[i] = (unsigned char)
( input[i] ^ m[(unsigned char)( a + b )] );
}
ctx->x = x;
ctx->y = y;
return( 0 );
}
#endif /* !MBEDTLS_ARC4_ALT */
#if defined(MBEDTLS_SELF_TEST)
/*
* ARC4 tests vectors as posted by Eric Rescorla in sep. 1994:
*
* http://groups.google.com/group/comp.security.misc/msg/10a300c9d21afca0
*/
static const unsigned char arc4_test_key[3][8] =
{
{ 0x01, 0x23, 0x45, 0x67, 0x89, 0xAB, 0xCD, 0xEF },
{ 0x01, 0x23, 0x45, 0x67, 0x89, 0xAB, 0xCD, 0xEF },
{ 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00 }
};
static const unsigned char arc4_test_pt[3][8] =
{
{ 0x01, 0x23, 0x45, 0x67, 0x89, 0xAB, 0xCD, 0xEF },
{ 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00 },
{ 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00 }
};
static const unsigned char arc4_test_ct[3][8] =
{
{ 0x75, 0xB7, 0x87, 0x80, 0x99, 0xE0, 0xC5, 0x96 },
{ 0x74, 0x94, 0xC2, 0xE7, 0x10, 0x4B, 0x08, 0x79 },
{ 0xDE, 0x18, 0x89, 0x41, 0xA3, 0x37, 0x5D, 0x3A }
};
/*
* Checkup routine
*/
int mbedtls_arc4_self_test( int verbose )
{
int i, ret = 0;
unsigned char ibuf[8];
unsigned char obuf[8];
mbedtls_arc4_context ctx;
mbedtls_arc4_init( &ctx );
for( i = 0; i < 3; i++ )
{
if( verbose != 0 )
mbedtls_printf( " ARC4 test #%d: ", i + 1 );
memcpy( ibuf, arc4_test_pt[i], 8 );
mbedtls_arc4_setup( &ctx, arc4_test_key[i], 8 );
mbedtls_arc4_crypt( &ctx, 8, ibuf, obuf );
if( memcmp( obuf, arc4_test_ct[i], 8 ) != 0 )
{
if( verbose != 0 )
mbedtls_printf( "failed\n" );
ret = 1;
goto exit;
}
if( verbose != 0 )
mbedtls_printf( "passed\n" );
}
if( verbose != 0 )
mbedtls_printf( "\n" );
exit:
mbedtls_arc4_free( &ctx );
return( ret );
}
#endif /* MBEDTLS_SELF_TEST */
#endif /* MBEDTLS_ARC4_C */
|
0 | repos/gpt4all.zig/src/zig-libcurl/zig-mbedtls/mbedtls | repos/gpt4all.zig/src/zig-libcurl/zig-mbedtls/mbedtls/library/platform.c | /*
* Platform abstraction layer
*
* Copyright The Mbed TLS Contributors
* SPDX-License-Identifier: Apache-2.0
*
* 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.
*/
#include "common.h"
#if defined(MBEDTLS_PLATFORM_C)
#include "mbedtls/platform.h"
#include "mbedtls/platform_util.h"
#include "mbedtls/error.h"
/* The compile time configuration of memory allocation via the macros
* MBEDTLS_PLATFORM_{FREE/CALLOC}_MACRO takes precedence over the runtime
* configuration via mbedtls_platform_set_calloc_free(). So, omit everything
* related to the latter if MBEDTLS_PLATFORM_{FREE/CALLOC}_MACRO are defined. */
#if defined(MBEDTLS_PLATFORM_MEMORY) && \
!( defined(MBEDTLS_PLATFORM_CALLOC_MACRO) && \
defined(MBEDTLS_PLATFORM_FREE_MACRO) )
#if !defined(MBEDTLS_PLATFORM_STD_CALLOC)
static void *platform_calloc_uninit( size_t n, size_t size )
{
((void) n);
((void) size);
return( NULL );
}
#define MBEDTLS_PLATFORM_STD_CALLOC platform_calloc_uninit
#endif /* !MBEDTLS_PLATFORM_STD_CALLOC */
#if !defined(MBEDTLS_PLATFORM_STD_FREE)
static void platform_free_uninit( void *ptr )
{
((void) ptr);
}
#define MBEDTLS_PLATFORM_STD_FREE platform_free_uninit
#endif /* !MBEDTLS_PLATFORM_STD_FREE */
static void * (*mbedtls_calloc_func)( size_t, size_t ) = MBEDTLS_PLATFORM_STD_CALLOC;
static void (*mbedtls_free_func)( void * ) = MBEDTLS_PLATFORM_STD_FREE;
void * mbedtls_calloc( size_t nmemb, size_t size )
{
return (*mbedtls_calloc_func)( nmemb, size );
}
void mbedtls_free( void * ptr )
{
(*mbedtls_free_func)( ptr );
}
int mbedtls_platform_set_calloc_free( void * (*calloc_func)( size_t, size_t ),
void (*free_func)( void * ) )
{
mbedtls_calloc_func = calloc_func;
mbedtls_free_func = free_func;
return( 0 );
}
#endif /* MBEDTLS_PLATFORM_MEMORY &&
!( defined(MBEDTLS_PLATFORM_CALLOC_MACRO) &&
defined(MBEDTLS_PLATFORM_FREE_MACRO) ) */
#if defined(MBEDTLS_PLATFORM_HAS_NON_CONFORMING_SNPRINTF)
#include <stdarg.h>
int mbedtls_platform_win32_snprintf( char *s, size_t n, const char *fmt, ... )
{
int ret = MBEDTLS_ERR_ERROR_CORRUPTION_DETECTED;
va_list argp;
va_start( argp, fmt );
ret = mbedtls_vsnprintf( s, n, fmt, argp );
va_end( argp );
return( ret );
}
#endif
#if defined(MBEDTLS_PLATFORM_SNPRINTF_ALT)
#if !defined(MBEDTLS_PLATFORM_STD_SNPRINTF)
/*
* Make dummy function to prevent NULL pointer dereferences
*/
static int platform_snprintf_uninit( char * s, size_t n,
const char * format, ... )
{
((void) s);
((void) n);
((void) format);
return( 0 );
}
#define MBEDTLS_PLATFORM_STD_SNPRINTF platform_snprintf_uninit
#endif /* !MBEDTLS_PLATFORM_STD_SNPRINTF */
int (*mbedtls_snprintf)( char * s, size_t n,
const char * format,
... ) = MBEDTLS_PLATFORM_STD_SNPRINTF;
int mbedtls_platform_set_snprintf( int (*snprintf_func)( char * s, size_t n,
const char * format,
... ) )
{
mbedtls_snprintf = snprintf_func;
return( 0 );
}
#endif /* MBEDTLS_PLATFORM_SNPRINTF_ALT */
#if defined(MBEDTLS_PLATFORM_HAS_NON_CONFORMING_VSNPRINTF)
#include <stdarg.h>
int mbedtls_platform_win32_vsnprintf( char *s, size_t n, const char *fmt, va_list arg )
{
int ret = MBEDTLS_ERR_ERROR_CORRUPTION_DETECTED;
/* Avoid calling the invalid parameter handler by checking ourselves */
if( s == NULL || n == 0 || fmt == NULL )
return( -1 );
#if defined(_TRUNCATE)
ret = vsnprintf_s( s, n, _TRUNCATE, fmt, arg );
#else
ret = vsnprintf( s, n, fmt, arg );
if( ret < 0 || (size_t) ret == n )
{
s[n-1] = '\0';
ret = -1;
}
#endif
return( ret );
}
#endif
#if defined(MBEDTLS_PLATFORM_VSNPRINTF_ALT)
#if !defined(MBEDTLS_PLATFORM_STD_VSNPRINTF)
/*
* Make dummy function to prevent NULL pointer dereferences
*/
static int platform_vsnprintf_uninit( char * s, size_t n,
const char * format, va_list arg )
{
((void) s);
((void) n);
((void) format);
((void) arg);
return( -1 );
}
#define MBEDTLS_PLATFORM_STD_VSNPRINTF platform_vsnprintf_uninit
#endif /* !MBEDTLS_PLATFORM_STD_VSNPRINTF */
int (*mbedtls_vsnprintf)( char * s, size_t n,
const char * format,
va_list arg ) = MBEDTLS_PLATFORM_STD_VSNPRINTF;
int mbedtls_platform_set_vsnprintf( int (*vsnprintf_func)( char * s, size_t n,
const char * format,
va_list arg ) )
{
mbedtls_vsnprintf = vsnprintf_func;
return( 0 );
}
#endif /* MBEDTLS_PLATFORM_VSNPRINTF_ALT */
#if defined(MBEDTLS_PLATFORM_PRINTF_ALT)
#if !defined(MBEDTLS_PLATFORM_STD_PRINTF)
/*
* Make dummy function to prevent NULL pointer dereferences
*/
static int platform_printf_uninit( const char *format, ... )
{
((void) format);
return( 0 );
}
#define MBEDTLS_PLATFORM_STD_PRINTF platform_printf_uninit
#endif /* !MBEDTLS_PLATFORM_STD_PRINTF */
int (*mbedtls_printf)( const char *, ... ) = MBEDTLS_PLATFORM_STD_PRINTF;
int mbedtls_platform_set_printf( int (*printf_func)( const char *, ... ) )
{
mbedtls_printf = printf_func;
return( 0 );
}
#endif /* MBEDTLS_PLATFORM_PRINTF_ALT */
#if defined(MBEDTLS_PLATFORM_FPRINTF_ALT)
#if !defined(MBEDTLS_PLATFORM_STD_FPRINTF)
/*
* Make dummy function to prevent NULL pointer dereferences
*/
static int platform_fprintf_uninit( FILE *stream, const char *format, ... )
{
((void) stream);
((void) format);
return( 0 );
}
#define MBEDTLS_PLATFORM_STD_FPRINTF platform_fprintf_uninit
#endif /* !MBEDTLS_PLATFORM_STD_FPRINTF */
int (*mbedtls_fprintf)( FILE *, const char *, ... ) =
MBEDTLS_PLATFORM_STD_FPRINTF;
int mbedtls_platform_set_fprintf( int (*fprintf_func)( FILE *, const char *, ... ) )
{
mbedtls_fprintf = fprintf_func;
return( 0 );
}
#endif /* MBEDTLS_PLATFORM_FPRINTF_ALT */
#if defined(MBEDTLS_PLATFORM_EXIT_ALT)
#if !defined(MBEDTLS_PLATFORM_STD_EXIT)
/*
* Make dummy function to prevent NULL pointer dereferences
*/
static void platform_exit_uninit( int status )
{
((void) status);
}
#define MBEDTLS_PLATFORM_STD_EXIT platform_exit_uninit
#endif /* !MBEDTLS_PLATFORM_STD_EXIT */
void (*mbedtls_exit)( int status ) = MBEDTLS_PLATFORM_STD_EXIT;
int mbedtls_platform_set_exit( void (*exit_func)( int status ) )
{
mbedtls_exit = exit_func;
return( 0 );
}
#endif /* MBEDTLS_PLATFORM_EXIT_ALT */
#if defined(MBEDTLS_HAVE_TIME)
#if defined(MBEDTLS_PLATFORM_TIME_ALT)
#if !defined(MBEDTLS_PLATFORM_STD_TIME)
/*
* Make dummy function to prevent NULL pointer dereferences
*/
static mbedtls_time_t platform_time_uninit( mbedtls_time_t* timer )
{
((void) timer);
return( 0 );
}
#define MBEDTLS_PLATFORM_STD_TIME platform_time_uninit
#endif /* !MBEDTLS_PLATFORM_STD_TIME */
mbedtls_time_t (*mbedtls_time)( mbedtls_time_t* timer ) = MBEDTLS_PLATFORM_STD_TIME;
int mbedtls_platform_set_time( mbedtls_time_t (*time_func)( mbedtls_time_t* timer ) )
{
mbedtls_time = time_func;
return( 0 );
}
#endif /* MBEDTLS_PLATFORM_TIME_ALT */
#endif /* MBEDTLS_HAVE_TIME */
#if defined(MBEDTLS_ENTROPY_NV_SEED)
#if !defined(MBEDTLS_PLATFORM_NO_STD_FUNCTIONS) && defined(MBEDTLS_FS_IO)
/* Default implementations for the platform independent seed functions use
* standard libc file functions to read from and write to a pre-defined filename
*/
int mbedtls_platform_std_nv_seed_read( unsigned char *buf, size_t buf_len )
{
FILE *file;
size_t n;
if( ( file = fopen( MBEDTLS_PLATFORM_STD_NV_SEED_FILE, "rb" ) ) == NULL )
return( -1 );
if( ( n = fread( buf, 1, buf_len, file ) ) != buf_len )
{
fclose( file );
mbedtls_platform_zeroize( buf, buf_len );
return( -1 );
}
fclose( file );
return( (int)n );
}
int mbedtls_platform_std_nv_seed_write( unsigned char *buf, size_t buf_len )
{
FILE *file;
size_t n;
if( ( file = fopen( MBEDTLS_PLATFORM_STD_NV_SEED_FILE, "w" ) ) == NULL )
return -1;
if( ( n = fwrite( buf, 1, buf_len, file ) ) != buf_len )
{
fclose( file );
return -1;
}
fclose( file );
return( (int)n );
}
#endif /* MBEDTLS_PLATFORM_NO_STD_FUNCTIONS */
#if defined(MBEDTLS_PLATFORM_NV_SEED_ALT)
#if !defined(MBEDTLS_PLATFORM_STD_NV_SEED_READ)
/*
* Make dummy function to prevent NULL pointer dereferences
*/
static int platform_nv_seed_read_uninit( unsigned char *buf, size_t buf_len )
{
((void) buf);
((void) buf_len);
return( -1 );
}
#define MBEDTLS_PLATFORM_STD_NV_SEED_READ platform_nv_seed_read_uninit
#endif /* !MBEDTLS_PLATFORM_STD_NV_SEED_READ */
#if !defined(MBEDTLS_PLATFORM_STD_NV_SEED_WRITE)
/*
* Make dummy function to prevent NULL pointer dereferences
*/
static int platform_nv_seed_write_uninit( unsigned char *buf, size_t buf_len )
{
((void) buf);
((void) buf_len);
return( -1 );
}
#define MBEDTLS_PLATFORM_STD_NV_SEED_WRITE platform_nv_seed_write_uninit
#endif /* !MBEDTLS_PLATFORM_STD_NV_SEED_WRITE */
int (*mbedtls_nv_seed_read)( unsigned char *buf, size_t buf_len ) =
MBEDTLS_PLATFORM_STD_NV_SEED_READ;
int (*mbedtls_nv_seed_write)( unsigned char *buf, size_t buf_len ) =
MBEDTLS_PLATFORM_STD_NV_SEED_WRITE;
int mbedtls_platform_set_nv_seed(
int (*nv_seed_read_func)( unsigned char *buf, size_t buf_len ),
int (*nv_seed_write_func)( unsigned char *buf, size_t buf_len ) )
{
mbedtls_nv_seed_read = nv_seed_read_func;
mbedtls_nv_seed_write = nv_seed_write_func;
return( 0 );
}
#endif /* MBEDTLS_PLATFORM_NV_SEED_ALT */
#endif /* MBEDTLS_ENTROPY_NV_SEED */
#if !defined(MBEDTLS_PLATFORM_SETUP_TEARDOWN_ALT)
/*
* Placeholder platform setup that does nothing by default
*/
int mbedtls_platform_setup( mbedtls_platform_context *ctx )
{
(void)ctx;
return( 0 );
}
/*
* Placeholder platform teardown that does nothing by default
*/
void mbedtls_platform_teardown( mbedtls_platform_context *ctx )
{
(void)ctx;
}
#endif /* MBEDTLS_PLATFORM_SETUP_TEARDOWN_ALT */
#endif /* MBEDTLS_PLATFORM_C */
|
0 | repos/gpt4all.zig/src/zig-libcurl/zig-mbedtls/mbedtls | repos/gpt4all.zig/src/zig-libcurl/zig-mbedtls/mbedtls/library/x509.c | /*
* X.509 common functions for parsing and verification
*
* Copyright The Mbed TLS Contributors
* SPDX-License-Identifier: Apache-2.0
*
* 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.
*/
/*
* The ITU-T X.509 standard defines a certificate format for PKI.
*
* http://www.ietf.org/rfc/rfc5280.txt (Certificates and CRLs)
* http://www.ietf.org/rfc/rfc3279.txt (Alg IDs for CRLs)
* http://www.ietf.org/rfc/rfc2986.txt (CSRs, aka PKCS#10)
*
* http://www.itu.int/ITU-T/studygroups/com17/languages/X.680-0207.pdf
* http://www.itu.int/ITU-T/studygroups/com17/languages/X.690-0207.pdf
*/
#include "common.h"
#if defined(MBEDTLS_X509_USE_C)
#include "mbedtls/x509.h"
#include "mbedtls/asn1.h"
#include "mbedtls/error.h"
#include "mbedtls/oid.h"
#include <stdio.h>
#include <string.h>
#if defined(MBEDTLS_PEM_PARSE_C)
#include "mbedtls/pem.h"
#endif
#if defined(MBEDTLS_PLATFORM_C)
#include "mbedtls/platform.h"
#else
#include <stdio.h>
#include <stdlib.h>
#define mbedtls_free free
#define mbedtls_calloc calloc
#define mbedtls_printf printf
#define mbedtls_snprintf snprintf
#endif
#if defined(MBEDTLS_HAVE_TIME)
#include "mbedtls/platform_time.h"
#endif
#if defined(MBEDTLS_HAVE_TIME_DATE)
#include "mbedtls/platform_util.h"
#include <time.h>
#endif
#define CHECK(code) if( ( ret = ( code ) ) != 0 ){ return( ret ); }
#define CHECK_RANGE(min, max, val) \
do \
{ \
if( ( val ) < ( min ) || ( val ) > ( max ) ) \
{ \
return( ret ); \
} \
} while( 0 )
/*
* CertificateSerialNumber ::= INTEGER
*/
int mbedtls_x509_get_serial( unsigned char **p, const unsigned char *end,
mbedtls_x509_buf *serial )
{
int ret = MBEDTLS_ERR_ERROR_CORRUPTION_DETECTED;
if( ( end - *p ) < 1 )
return( MBEDTLS_ERROR_ADD( MBEDTLS_ERR_X509_INVALID_SERIAL,
MBEDTLS_ERR_ASN1_OUT_OF_DATA ) );
if( **p != ( MBEDTLS_ASN1_CONTEXT_SPECIFIC | MBEDTLS_ASN1_PRIMITIVE | 2 ) &&
**p != MBEDTLS_ASN1_INTEGER )
return( MBEDTLS_ERROR_ADD( MBEDTLS_ERR_X509_INVALID_SERIAL,
MBEDTLS_ERR_ASN1_UNEXPECTED_TAG ) );
serial->tag = *(*p)++;
if( ( ret = mbedtls_asn1_get_len( p, end, &serial->len ) ) != 0 )
return( MBEDTLS_ERROR_ADD( MBEDTLS_ERR_X509_INVALID_SERIAL, ret ) );
serial->p = *p;
*p += serial->len;
return( 0 );
}
/* Get an algorithm identifier without parameters (eg for signatures)
*
* AlgorithmIdentifier ::= SEQUENCE {
* algorithm OBJECT IDENTIFIER,
* parameters ANY DEFINED BY algorithm OPTIONAL }
*/
int mbedtls_x509_get_alg_null( unsigned char **p, const unsigned char *end,
mbedtls_x509_buf *alg )
{
int ret = MBEDTLS_ERR_ERROR_CORRUPTION_DETECTED;
if( ( ret = mbedtls_asn1_get_alg_null( p, end, alg ) ) != 0 )
return( MBEDTLS_ERROR_ADD( MBEDTLS_ERR_X509_INVALID_ALG, ret ) );
return( 0 );
}
/*
* Parse an algorithm identifier with (optional) parameters
*/
int mbedtls_x509_get_alg( unsigned char **p, const unsigned char *end,
mbedtls_x509_buf *alg, mbedtls_x509_buf *params )
{
int ret = MBEDTLS_ERR_ERROR_CORRUPTION_DETECTED;
if( ( ret = mbedtls_asn1_get_alg( p, end, alg, params ) ) != 0 )
return( MBEDTLS_ERROR_ADD( MBEDTLS_ERR_X509_INVALID_ALG, ret ) );
return( 0 );
}
#if defined(MBEDTLS_X509_RSASSA_PSS_SUPPORT)
/*
* HashAlgorithm ::= AlgorithmIdentifier
*
* AlgorithmIdentifier ::= SEQUENCE {
* algorithm OBJECT IDENTIFIER,
* parameters ANY DEFINED BY algorithm OPTIONAL }
*
* For HashAlgorithm, parameters MUST be NULL or absent.
*/
static int x509_get_hash_alg( const mbedtls_x509_buf *alg, mbedtls_md_type_t *md_alg )
{
int ret = MBEDTLS_ERR_ERROR_CORRUPTION_DETECTED;
unsigned char *p;
const unsigned char *end;
mbedtls_x509_buf md_oid;
size_t len;
/* Make sure we got a SEQUENCE and setup bounds */
if( alg->tag != ( MBEDTLS_ASN1_CONSTRUCTED | MBEDTLS_ASN1_SEQUENCE ) )
return( MBEDTLS_ERROR_ADD( MBEDTLS_ERR_X509_INVALID_ALG,
MBEDTLS_ERR_ASN1_UNEXPECTED_TAG ) );
p = alg->p;
end = p + alg->len;
if( p >= end )
return( MBEDTLS_ERROR_ADD( MBEDTLS_ERR_X509_INVALID_ALG,
MBEDTLS_ERR_ASN1_OUT_OF_DATA ) );
/* Parse md_oid */
md_oid.tag = *p;
if( ( ret = mbedtls_asn1_get_tag( &p, end, &md_oid.len, MBEDTLS_ASN1_OID ) ) != 0 )
return( MBEDTLS_ERROR_ADD( MBEDTLS_ERR_X509_INVALID_ALG, ret ) );
md_oid.p = p;
p += md_oid.len;
/* Get md_alg from md_oid */
if( ( ret = mbedtls_oid_get_md_alg( &md_oid, md_alg ) ) != 0 )
return( MBEDTLS_ERROR_ADD( MBEDTLS_ERR_X509_INVALID_ALG, ret ) );
/* Make sure params is absent of NULL */
if( p == end )
return( 0 );
if( ( ret = mbedtls_asn1_get_tag( &p, end, &len, MBEDTLS_ASN1_NULL ) ) != 0 || len != 0 )
return( MBEDTLS_ERROR_ADD( MBEDTLS_ERR_X509_INVALID_ALG, ret ) );
if( p != end )
return( MBEDTLS_ERROR_ADD( MBEDTLS_ERR_X509_INVALID_ALG,
MBEDTLS_ERR_ASN1_LENGTH_MISMATCH ) );
return( 0 );
}
/*
* RSASSA-PSS-params ::= SEQUENCE {
* hashAlgorithm [0] HashAlgorithm DEFAULT sha1Identifier,
* maskGenAlgorithm [1] MaskGenAlgorithm DEFAULT mgf1SHA1Identifier,
* saltLength [2] INTEGER DEFAULT 20,
* trailerField [3] INTEGER DEFAULT 1 }
* -- Note that the tags in this Sequence are explicit.
*
* RFC 4055 (which defines use of RSASSA-PSS in PKIX) states that the value
* of trailerField MUST be 1, and PKCS#1 v2.2 doesn't even define any other
* option. Enfore this at parsing time.
*/
int mbedtls_x509_get_rsassa_pss_params( const mbedtls_x509_buf *params,
mbedtls_md_type_t *md_alg, mbedtls_md_type_t *mgf_md,
int *salt_len )
{
int ret = MBEDTLS_ERR_ERROR_CORRUPTION_DETECTED;
unsigned char *p;
const unsigned char *end, *end2;
size_t len;
mbedtls_x509_buf alg_id, alg_params;
/* First set everything to defaults */
*md_alg = MBEDTLS_MD_SHA1;
*mgf_md = MBEDTLS_MD_SHA1;
*salt_len = 20;
/* Make sure params is a SEQUENCE and setup bounds */
if( params->tag != ( MBEDTLS_ASN1_CONSTRUCTED | MBEDTLS_ASN1_SEQUENCE ) )
return( MBEDTLS_ERROR_ADD( MBEDTLS_ERR_X509_INVALID_ALG,
MBEDTLS_ERR_ASN1_UNEXPECTED_TAG ) );
p = (unsigned char *) params->p;
end = p + params->len;
if( p == end )
return( 0 );
/*
* HashAlgorithm
*/
if( ( ret = mbedtls_asn1_get_tag( &p, end, &len,
MBEDTLS_ASN1_CONTEXT_SPECIFIC | MBEDTLS_ASN1_CONSTRUCTED | 0 ) ) == 0 )
{
end2 = p + len;
/* HashAlgorithm ::= AlgorithmIdentifier (without parameters) */
if( ( ret = mbedtls_x509_get_alg_null( &p, end2, &alg_id ) ) != 0 )
return( ret );
if( ( ret = mbedtls_oid_get_md_alg( &alg_id, md_alg ) ) != 0 )
return( MBEDTLS_ERROR_ADD( MBEDTLS_ERR_X509_INVALID_ALG, ret ) );
if( p != end2 )
return( MBEDTLS_ERROR_ADD( MBEDTLS_ERR_X509_INVALID_ALG,
MBEDTLS_ERR_ASN1_LENGTH_MISMATCH ) );
}
else if( ret != MBEDTLS_ERR_ASN1_UNEXPECTED_TAG )
return( MBEDTLS_ERROR_ADD( MBEDTLS_ERR_X509_INVALID_ALG, ret ) );
if( p == end )
return( 0 );
/*
* MaskGenAlgorithm
*/
if( ( ret = mbedtls_asn1_get_tag( &p, end, &len,
MBEDTLS_ASN1_CONTEXT_SPECIFIC | MBEDTLS_ASN1_CONSTRUCTED | 1 ) ) == 0 )
{
end2 = p + len;
/* MaskGenAlgorithm ::= AlgorithmIdentifier (params = HashAlgorithm) */
if( ( ret = mbedtls_x509_get_alg( &p, end2, &alg_id, &alg_params ) ) != 0 )
return( ret );
/* Only MFG1 is recognised for now */
if( MBEDTLS_OID_CMP( MBEDTLS_OID_MGF1, &alg_id ) != 0 )
return( MBEDTLS_ERROR_ADD( MBEDTLS_ERR_X509_FEATURE_UNAVAILABLE,
MBEDTLS_ERR_OID_NOT_FOUND ) );
/* Parse HashAlgorithm */
if( ( ret = x509_get_hash_alg( &alg_params, mgf_md ) ) != 0 )
return( ret );
if( p != end2 )
return( MBEDTLS_ERROR_ADD( MBEDTLS_ERR_X509_INVALID_ALG,
MBEDTLS_ERR_ASN1_LENGTH_MISMATCH ) );
}
else if( ret != MBEDTLS_ERR_ASN1_UNEXPECTED_TAG )
return( MBEDTLS_ERROR_ADD( MBEDTLS_ERR_X509_INVALID_ALG, ret ) );
if( p == end )
return( 0 );
/*
* salt_len
*/
if( ( ret = mbedtls_asn1_get_tag( &p, end, &len,
MBEDTLS_ASN1_CONTEXT_SPECIFIC | MBEDTLS_ASN1_CONSTRUCTED | 2 ) ) == 0 )
{
end2 = p + len;
if( ( ret = mbedtls_asn1_get_int( &p, end2, salt_len ) ) != 0 )
return( MBEDTLS_ERROR_ADD( MBEDTLS_ERR_X509_INVALID_ALG, ret ) );
if( p != end2 )
return( MBEDTLS_ERROR_ADD( MBEDTLS_ERR_X509_INVALID_ALG,
MBEDTLS_ERR_ASN1_LENGTH_MISMATCH ) );
}
else if( ret != MBEDTLS_ERR_ASN1_UNEXPECTED_TAG )
return( MBEDTLS_ERROR_ADD( MBEDTLS_ERR_X509_INVALID_ALG, ret ) );
if( p == end )
return( 0 );
/*
* trailer_field (if present, must be 1)
*/
if( ( ret = mbedtls_asn1_get_tag( &p, end, &len,
MBEDTLS_ASN1_CONTEXT_SPECIFIC | MBEDTLS_ASN1_CONSTRUCTED | 3 ) ) == 0 )
{
int trailer_field;
end2 = p + len;
if( ( ret = mbedtls_asn1_get_int( &p, end2, &trailer_field ) ) != 0 )
return( MBEDTLS_ERROR_ADD( MBEDTLS_ERR_X509_INVALID_ALG, ret ) );
if( p != end2 )
return( MBEDTLS_ERROR_ADD( MBEDTLS_ERR_X509_INVALID_ALG,
MBEDTLS_ERR_ASN1_LENGTH_MISMATCH ) );
if( trailer_field != 1 )
return( MBEDTLS_ERR_X509_INVALID_ALG );
}
else if( ret != MBEDTLS_ERR_ASN1_UNEXPECTED_TAG )
return( MBEDTLS_ERROR_ADD( MBEDTLS_ERR_X509_INVALID_ALG, ret ) );
if( p != end )
return( MBEDTLS_ERROR_ADD( MBEDTLS_ERR_X509_INVALID_ALG,
MBEDTLS_ERR_ASN1_LENGTH_MISMATCH ) );
return( 0 );
}
#endif /* MBEDTLS_X509_RSASSA_PSS_SUPPORT */
/*
* AttributeTypeAndValue ::= SEQUENCE {
* type AttributeType,
* value AttributeValue }
*
* AttributeType ::= OBJECT IDENTIFIER
*
* AttributeValue ::= ANY DEFINED BY AttributeType
*/
static int x509_get_attr_type_value( unsigned char **p,
const unsigned char *end,
mbedtls_x509_name *cur )
{
int ret = MBEDTLS_ERR_ERROR_CORRUPTION_DETECTED;
size_t len;
mbedtls_x509_buf *oid;
mbedtls_x509_buf *val;
if( ( ret = mbedtls_asn1_get_tag( p, end, &len,
MBEDTLS_ASN1_CONSTRUCTED | MBEDTLS_ASN1_SEQUENCE ) ) != 0 )
return( MBEDTLS_ERROR_ADD( MBEDTLS_ERR_X509_INVALID_NAME, ret ) );
end = *p + len;
if( ( end - *p ) < 1 )
return( MBEDTLS_ERROR_ADD( MBEDTLS_ERR_X509_INVALID_NAME,
MBEDTLS_ERR_ASN1_OUT_OF_DATA ) );
oid = &cur->oid;
oid->tag = **p;
if( ( ret = mbedtls_asn1_get_tag( p, end, &oid->len, MBEDTLS_ASN1_OID ) ) != 0 )
return( MBEDTLS_ERROR_ADD( MBEDTLS_ERR_X509_INVALID_NAME, ret ) );
oid->p = *p;
*p += oid->len;
if( ( end - *p ) < 1 )
return( MBEDTLS_ERROR_ADD( MBEDTLS_ERR_X509_INVALID_NAME,
MBEDTLS_ERR_ASN1_OUT_OF_DATA ) );
if( **p != MBEDTLS_ASN1_BMP_STRING && **p != MBEDTLS_ASN1_UTF8_STRING &&
**p != MBEDTLS_ASN1_T61_STRING && **p != MBEDTLS_ASN1_PRINTABLE_STRING &&
**p != MBEDTLS_ASN1_IA5_STRING && **p != MBEDTLS_ASN1_UNIVERSAL_STRING &&
**p != MBEDTLS_ASN1_BIT_STRING )
return( MBEDTLS_ERROR_ADD( MBEDTLS_ERR_X509_INVALID_NAME,
MBEDTLS_ERR_ASN1_UNEXPECTED_TAG ) );
val = &cur->val;
val->tag = *(*p)++;
if( ( ret = mbedtls_asn1_get_len( p, end, &val->len ) ) != 0 )
return( MBEDTLS_ERROR_ADD( MBEDTLS_ERR_X509_INVALID_NAME, ret ) );
val->p = *p;
*p += val->len;
if( *p != end )
{
return( MBEDTLS_ERROR_ADD( MBEDTLS_ERR_X509_INVALID_NAME,
MBEDTLS_ERR_ASN1_LENGTH_MISMATCH ) );
}
cur->next = NULL;
return( 0 );
}
/*
* Name ::= CHOICE { -- only one possibility for now --
* rdnSequence RDNSequence }
*
* RDNSequence ::= SEQUENCE OF RelativeDistinguishedName
*
* RelativeDistinguishedName ::=
* SET OF AttributeTypeAndValue
*
* AttributeTypeAndValue ::= SEQUENCE {
* type AttributeType,
* value AttributeValue }
*
* AttributeType ::= OBJECT IDENTIFIER
*
* AttributeValue ::= ANY DEFINED BY AttributeType
*
* The data structure is optimized for the common case where each RDN has only
* one element, which is represented as a list of AttributeTypeAndValue.
* For the general case we still use a flat list, but we mark elements of the
* same set so that they are "merged" together in the functions that consume
* this list, eg mbedtls_x509_dn_gets().
*/
int mbedtls_x509_get_name( unsigned char **p, const unsigned char *end,
mbedtls_x509_name *cur )
{
int ret = MBEDTLS_ERR_ERROR_CORRUPTION_DETECTED;
size_t set_len;
const unsigned char *end_set;
/* don't use recursion, we'd risk stack overflow if not optimized */
while( 1 )
{
/*
* parse SET
*/
if( ( ret = mbedtls_asn1_get_tag( p, end, &set_len,
MBEDTLS_ASN1_CONSTRUCTED | MBEDTLS_ASN1_SET ) ) != 0 )
return( MBEDTLS_ERROR_ADD( MBEDTLS_ERR_X509_INVALID_NAME, ret ) );
end_set = *p + set_len;
while( 1 )
{
if( ( ret = x509_get_attr_type_value( p, end_set, cur ) ) != 0 )
return( ret );
if( *p == end_set )
break;
/* Mark this item as being no the only one in a set */
cur->next_merged = 1;
cur->next = mbedtls_calloc( 1, sizeof( mbedtls_x509_name ) );
if( cur->next == NULL )
return( MBEDTLS_ERR_X509_ALLOC_FAILED );
cur = cur->next;
}
/*
* continue until end of SEQUENCE is reached
*/
if( *p == end )
return( 0 );
cur->next = mbedtls_calloc( 1, sizeof( mbedtls_x509_name ) );
if( cur->next == NULL )
return( MBEDTLS_ERR_X509_ALLOC_FAILED );
cur = cur->next;
}
}
static int x509_parse_int( unsigned char **p, size_t n, int *res )
{
*res = 0;
for( ; n > 0; --n )
{
if( ( **p < '0') || ( **p > '9' ) )
return ( MBEDTLS_ERR_X509_INVALID_DATE );
*res *= 10;
*res += ( *(*p)++ - '0' );
}
return( 0 );
}
static int x509_date_is_valid(const mbedtls_x509_time *t )
{
int ret = MBEDTLS_ERR_X509_INVALID_DATE;
int month_len;
CHECK_RANGE( 0, 9999, t->year );
CHECK_RANGE( 0, 23, t->hour );
CHECK_RANGE( 0, 59, t->min );
CHECK_RANGE( 0, 59, t->sec );
switch( t->mon )
{
case 1: case 3: case 5: case 7: case 8: case 10: case 12:
month_len = 31;
break;
case 4: case 6: case 9: case 11:
month_len = 30;
break;
case 2:
if( ( !( t->year % 4 ) && t->year % 100 ) ||
!( t->year % 400 ) )
month_len = 29;
else
month_len = 28;
break;
default:
return( ret );
}
CHECK_RANGE( 1, month_len, t->day );
return( 0 );
}
/*
* Parse an ASN1_UTC_TIME (yearlen=2) or ASN1_GENERALIZED_TIME (yearlen=4)
* field.
*/
static int x509_parse_time( unsigned char **p, size_t len, size_t yearlen,
mbedtls_x509_time *tm )
{
int ret = MBEDTLS_ERR_ERROR_CORRUPTION_DETECTED;
/*
* Minimum length is 10 or 12 depending on yearlen
*/
if ( len < yearlen + 8 )
return ( MBEDTLS_ERR_X509_INVALID_DATE );
len -= yearlen + 8;
/*
* Parse year, month, day, hour, minute
*/
CHECK( x509_parse_int( p, yearlen, &tm->year ) );
if ( 2 == yearlen )
{
if ( tm->year < 50 )
tm->year += 100;
tm->year += 1900;
}
CHECK( x509_parse_int( p, 2, &tm->mon ) );
CHECK( x509_parse_int( p, 2, &tm->day ) );
CHECK( x509_parse_int( p, 2, &tm->hour ) );
CHECK( x509_parse_int( p, 2, &tm->min ) );
/*
* Parse seconds if present
*/
if ( len >= 2 )
{
CHECK( x509_parse_int( p, 2, &tm->sec ) );
len -= 2;
}
else
return ( MBEDTLS_ERR_X509_INVALID_DATE );
/*
* Parse trailing 'Z' if present
*/
if ( 1 == len && 'Z' == **p )
{
(*p)++;
len--;
}
/*
* We should have parsed all characters at this point
*/
if ( 0 != len )
return ( MBEDTLS_ERR_X509_INVALID_DATE );
CHECK( x509_date_is_valid( tm ) );
return ( 0 );
}
/*
* Time ::= CHOICE {
* utcTime UTCTime,
* generalTime GeneralizedTime }
*/
int mbedtls_x509_get_time( unsigned char **p, const unsigned char *end,
mbedtls_x509_time *tm )
{
int ret = MBEDTLS_ERR_ERROR_CORRUPTION_DETECTED;
size_t len, year_len;
unsigned char tag;
if( ( end - *p ) < 1 )
return( MBEDTLS_ERROR_ADD( MBEDTLS_ERR_X509_INVALID_DATE,
MBEDTLS_ERR_ASN1_OUT_OF_DATA ) );
tag = **p;
if( tag == MBEDTLS_ASN1_UTC_TIME )
year_len = 2;
else if( tag == MBEDTLS_ASN1_GENERALIZED_TIME )
year_len = 4;
else
return( MBEDTLS_ERROR_ADD( MBEDTLS_ERR_X509_INVALID_DATE,
MBEDTLS_ERR_ASN1_UNEXPECTED_TAG ) );
(*p)++;
ret = mbedtls_asn1_get_len( p, end, &len );
if( ret != 0 )
return( MBEDTLS_ERROR_ADD( MBEDTLS_ERR_X509_INVALID_DATE, ret ) );
return x509_parse_time( p, len, year_len, tm );
}
int mbedtls_x509_get_sig( unsigned char **p, const unsigned char *end, mbedtls_x509_buf *sig )
{
int ret = MBEDTLS_ERR_ERROR_CORRUPTION_DETECTED;
size_t len;
int tag_type;
if( ( end - *p ) < 1 )
return( MBEDTLS_ERROR_ADD( MBEDTLS_ERR_X509_INVALID_SIGNATURE,
MBEDTLS_ERR_ASN1_OUT_OF_DATA ) );
tag_type = **p;
if( ( ret = mbedtls_asn1_get_bitstring_null( p, end, &len ) ) != 0 )
return( MBEDTLS_ERROR_ADD( MBEDTLS_ERR_X509_INVALID_SIGNATURE, ret ) );
sig->tag = tag_type;
sig->len = len;
sig->p = *p;
*p += len;
return( 0 );
}
/*
* Get signature algorithm from alg OID and optional parameters
*/
int mbedtls_x509_get_sig_alg( const mbedtls_x509_buf *sig_oid, const mbedtls_x509_buf *sig_params,
mbedtls_md_type_t *md_alg, mbedtls_pk_type_t *pk_alg,
void **sig_opts )
{
int ret = MBEDTLS_ERR_ERROR_CORRUPTION_DETECTED;
if( *sig_opts != NULL )
return( MBEDTLS_ERR_X509_BAD_INPUT_DATA );
if( ( ret = mbedtls_oid_get_sig_alg( sig_oid, md_alg, pk_alg ) ) != 0 )
return( MBEDTLS_ERROR_ADD( MBEDTLS_ERR_X509_UNKNOWN_SIG_ALG, ret ) );
#if defined(MBEDTLS_X509_RSASSA_PSS_SUPPORT)
if( *pk_alg == MBEDTLS_PK_RSASSA_PSS )
{
mbedtls_pk_rsassa_pss_options *pss_opts;
pss_opts = mbedtls_calloc( 1, sizeof( mbedtls_pk_rsassa_pss_options ) );
if( pss_opts == NULL )
return( MBEDTLS_ERR_X509_ALLOC_FAILED );
ret = mbedtls_x509_get_rsassa_pss_params( sig_params,
md_alg,
&pss_opts->mgf1_hash_id,
&pss_opts->expected_salt_len );
if( ret != 0 )
{
mbedtls_free( pss_opts );
return( ret );
}
*sig_opts = (void *) pss_opts;
}
else
#endif /* MBEDTLS_X509_RSASSA_PSS_SUPPORT */
{
/* Make sure parameters are absent or NULL */
if( ( sig_params->tag != MBEDTLS_ASN1_NULL && sig_params->tag != 0 ) ||
sig_params->len != 0 )
return( MBEDTLS_ERR_X509_INVALID_ALG );
}
return( 0 );
}
/*
* X.509 Extensions (No parsing of extensions, pointer should
* be either manually updated or extensions should be parsed!)
*/
int mbedtls_x509_get_ext( unsigned char **p, const unsigned char *end,
mbedtls_x509_buf *ext, int tag )
{
int ret = MBEDTLS_ERR_ERROR_CORRUPTION_DETECTED;
size_t len;
/* Extension structure use EXPLICIT tagging. That is, the actual
* `Extensions` structure is wrapped by a tag-length pair using
* the respective context-specific tag. */
ret = mbedtls_asn1_get_tag( p, end, &ext->len,
MBEDTLS_ASN1_CONTEXT_SPECIFIC | MBEDTLS_ASN1_CONSTRUCTED | tag );
if( ret != 0 )
return( MBEDTLS_ERROR_ADD( MBEDTLS_ERR_X509_INVALID_EXTENSIONS, ret ) );
ext->tag = MBEDTLS_ASN1_CONTEXT_SPECIFIC | MBEDTLS_ASN1_CONSTRUCTED | tag;
ext->p = *p;
end = *p + ext->len;
/*
* Extensions ::= SEQUENCE SIZE (1..MAX) OF Extension
*/
if( ( ret = mbedtls_asn1_get_tag( p, end, &len,
MBEDTLS_ASN1_CONSTRUCTED | MBEDTLS_ASN1_SEQUENCE ) ) != 0 )
return( MBEDTLS_ERROR_ADD( MBEDTLS_ERR_X509_INVALID_EXTENSIONS, ret ) );
if( end != *p + len )
return( MBEDTLS_ERROR_ADD( MBEDTLS_ERR_X509_INVALID_EXTENSIONS,
MBEDTLS_ERR_ASN1_LENGTH_MISMATCH ) );
return( 0 );
}
/*
* Store the name in printable form into buf; no more
* than size characters will be written
*/
int mbedtls_x509_dn_gets( char *buf, size_t size, const mbedtls_x509_name *dn )
{
int ret = MBEDTLS_ERR_ERROR_CORRUPTION_DETECTED;
size_t i, n;
unsigned char c, merge = 0;
const mbedtls_x509_name *name;
const char *short_name = NULL;
char s[MBEDTLS_X509_MAX_DN_NAME_SIZE], *p;
memset( s, 0, sizeof( s ) );
name = dn;
p = buf;
n = size;
while( name != NULL )
{
if( !name->oid.p )
{
name = name->next;
continue;
}
if( name != dn )
{
ret = mbedtls_snprintf( p, n, merge ? " + " : ", " );
MBEDTLS_X509_SAFE_SNPRINTF;
}
ret = mbedtls_oid_get_attr_short_name( &name->oid, &short_name );
if( ret == 0 )
ret = mbedtls_snprintf( p, n, "%s=", short_name );
else
ret = mbedtls_snprintf( p, n, "\?\?=" );
MBEDTLS_X509_SAFE_SNPRINTF;
for( i = 0; i < name->val.len; i++ )
{
if( i >= sizeof( s ) - 1 )
break;
c = name->val.p[i];
if( c < 32 || c >= 127 )
s[i] = '?';
else s[i] = c;
}
s[i] = '\0';
ret = mbedtls_snprintf( p, n, "%s", s );
MBEDTLS_X509_SAFE_SNPRINTF;
merge = name->next_merged;
name = name->next;
}
return( (int) ( size - n ) );
}
/*
* Store the serial in printable form into buf; no more
* than size characters will be written
*/
int mbedtls_x509_serial_gets( char *buf, size_t size, const mbedtls_x509_buf *serial )
{
int ret = MBEDTLS_ERR_ERROR_CORRUPTION_DETECTED;
size_t i, n, nr;
char *p;
p = buf;
n = size;
nr = ( serial->len <= 32 )
? serial->len : 28;
for( i = 0; i < nr; i++ )
{
if( i == 0 && nr > 1 && serial->p[i] == 0x0 )
continue;
ret = mbedtls_snprintf( p, n, "%02X%s",
serial->p[i], ( i < nr - 1 ) ? ":" : "" );
MBEDTLS_X509_SAFE_SNPRINTF;
}
if( nr != serial->len )
{
ret = mbedtls_snprintf( p, n, "...." );
MBEDTLS_X509_SAFE_SNPRINTF;
}
return( (int) ( size - n ) );
}
/*
* Helper for writing signature algorithms
*/
int mbedtls_x509_sig_alg_gets( char *buf, size_t size, const mbedtls_x509_buf *sig_oid,
mbedtls_pk_type_t pk_alg, mbedtls_md_type_t md_alg,
const void *sig_opts )
{
int ret = MBEDTLS_ERR_ERROR_CORRUPTION_DETECTED;
char *p = buf;
size_t n = size;
const char *desc = NULL;
ret = mbedtls_oid_get_sig_alg_desc( sig_oid, &desc );
if( ret != 0 )
ret = mbedtls_snprintf( p, n, "???" );
else
ret = mbedtls_snprintf( p, n, "%s", desc );
MBEDTLS_X509_SAFE_SNPRINTF;
#if defined(MBEDTLS_X509_RSASSA_PSS_SUPPORT)
if( pk_alg == MBEDTLS_PK_RSASSA_PSS )
{
const mbedtls_pk_rsassa_pss_options *pss_opts;
const mbedtls_md_info_t *md_info, *mgf_md_info;
pss_opts = (const mbedtls_pk_rsassa_pss_options *) sig_opts;
md_info = mbedtls_md_info_from_type( md_alg );
mgf_md_info = mbedtls_md_info_from_type( pss_opts->mgf1_hash_id );
ret = mbedtls_snprintf( p, n, " (%s, MGF1-%s, 0x%02X)",
md_info ? mbedtls_md_get_name( md_info ) : "???",
mgf_md_info ? mbedtls_md_get_name( mgf_md_info ) : "???",
(unsigned int) pss_opts->expected_salt_len );
MBEDTLS_X509_SAFE_SNPRINTF;
}
#else
((void) pk_alg);
((void) md_alg);
((void) sig_opts);
#endif /* MBEDTLS_X509_RSASSA_PSS_SUPPORT */
return( (int)( size - n ) );
}
/*
* Helper for writing "RSA key size", "EC key size", etc
*/
int mbedtls_x509_key_size_helper( char *buf, size_t buf_size, const char *name )
{
char *p = buf;
size_t n = buf_size;
int ret = MBEDTLS_ERR_ERROR_CORRUPTION_DETECTED;
ret = mbedtls_snprintf( p, n, "%s key size", name );
MBEDTLS_X509_SAFE_SNPRINTF;
return( 0 );
}
#if defined(MBEDTLS_HAVE_TIME_DATE)
/*
* Set the time structure to the current time.
* Return 0 on success, non-zero on failure.
*/
static int x509_get_current_time( mbedtls_x509_time *now )
{
struct tm *lt, tm_buf;
mbedtls_time_t tt;
int ret = 0;
tt = mbedtls_time( NULL );
lt = mbedtls_platform_gmtime_r( &tt, &tm_buf );
if( lt == NULL )
ret = -1;
else
{
now->year = lt->tm_year + 1900;
now->mon = lt->tm_mon + 1;
now->day = lt->tm_mday;
now->hour = lt->tm_hour;
now->min = lt->tm_min;
now->sec = lt->tm_sec;
}
return( ret );
}
/*
* Return 0 if before <= after, 1 otherwise
*/
static int x509_check_time( const mbedtls_x509_time *before, const mbedtls_x509_time *after )
{
if( before->year > after->year )
return( 1 );
if( before->year == after->year &&
before->mon > after->mon )
return( 1 );
if( before->year == after->year &&
before->mon == after->mon &&
before->day > after->day )
return( 1 );
if( before->year == after->year &&
before->mon == after->mon &&
before->day == after->day &&
before->hour > after->hour )
return( 1 );
if( before->year == after->year &&
before->mon == after->mon &&
before->day == after->day &&
before->hour == after->hour &&
before->min > after->min )
return( 1 );
if( before->year == after->year &&
before->mon == after->mon &&
before->day == after->day &&
before->hour == after->hour &&
before->min == after->min &&
before->sec > after->sec )
return( 1 );
return( 0 );
}
int mbedtls_x509_time_is_past( const mbedtls_x509_time *to )
{
mbedtls_x509_time now;
if( x509_get_current_time( &now ) != 0 )
return( 1 );
return( x509_check_time( &now, to ) );
}
int mbedtls_x509_time_is_future( const mbedtls_x509_time *from )
{
mbedtls_x509_time now;
if( x509_get_current_time( &now ) != 0 )
return( 1 );
return( x509_check_time( from, &now ) );
}
#else /* MBEDTLS_HAVE_TIME_DATE */
int mbedtls_x509_time_is_past( const mbedtls_x509_time *to )
{
((void) to);
return( 0 );
}
int mbedtls_x509_time_is_future( const mbedtls_x509_time *from )
{
((void) from);
return( 0 );
}
#endif /* MBEDTLS_HAVE_TIME_DATE */
#if defined(MBEDTLS_SELF_TEST)
#include "mbedtls/x509_crt.h"
#include "mbedtls/certs.h"
/*
* Checkup routine
*/
int mbedtls_x509_self_test( int verbose )
{
int ret = 0;
#if defined(MBEDTLS_CERTS_C) && defined(MBEDTLS_SHA256_C)
uint32_t flags;
mbedtls_x509_crt cacert;
mbedtls_x509_crt clicert;
if( verbose != 0 )
mbedtls_printf( " X.509 certificate load: " );
mbedtls_x509_crt_init( &cacert );
mbedtls_x509_crt_init( &clicert );
ret = mbedtls_x509_crt_parse( &clicert, (const unsigned char *) mbedtls_test_cli_crt,
mbedtls_test_cli_crt_len );
if( ret != 0 )
{
if( verbose != 0 )
mbedtls_printf( "failed\n" );
goto cleanup;
}
ret = mbedtls_x509_crt_parse( &cacert, (const unsigned char *) mbedtls_test_ca_crt,
mbedtls_test_ca_crt_len );
if( ret != 0 )
{
if( verbose != 0 )
mbedtls_printf( "failed\n" );
goto cleanup;
}
if( verbose != 0 )
mbedtls_printf( "passed\n X.509 signature verify: ");
ret = mbedtls_x509_crt_verify( &clicert, &cacert, NULL, NULL, &flags, NULL, NULL );
if( ret != 0 )
{
if( verbose != 0 )
mbedtls_printf( "failed\n" );
goto cleanup;
}
if( verbose != 0 )
mbedtls_printf( "passed\n\n");
cleanup:
mbedtls_x509_crt_free( &cacert );
mbedtls_x509_crt_free( &clicert );
#else
((void) verbose);
#endif /* MBEDTLS_CERTS_C && MBEDTLS_SHA256_C */
return( ret );
}
#endif /* MBEDTLS_SELF_TEST */
#endif /* MBEDTLS_X509_USE_C */
|
0 | repos/gpt4all.zig/src/zig-libcurl/zig-mbedtls/mbedtls | repos/gpt4all.zig/src/zig-libcurl/zig-mbedtls/mbedtls/library/psa_crypto_mac.c | /*
* PSA MAC layer on top of Mbed TLS software crypto
*/
/*
* Copyright The Mbed TLS Contributors
* SPDX-License-Identifier: Apache-2.0
*
* 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.
*/
#include "common.h"
#if defined(MBEDTLS_PSA_CRYPTO_C)
#include <psa/crypto.h>
#include "psa_crypto_core.h"
#include "psa_crypto_mac.h"
#include <mbedtls/md.h>
#include <mbedtls/error.h>
#include <string.h>
/* Use builtin defines specific to this compilation unit, since the test driver
* relies on the software driver. */
#if( defined(MBEDTLS_PSA_BUILTIN_ALG_CMAC) || \
( defined(PSA_CRYPTO_DRIVER_TEST) && defined(MBEDTLS_PSA_ACCEL_ALG_CMAC) ) )
#define BUILTIN_ALG_CMAC 1
#endif
#if( defined(MBEDTLS_PSA_BUILTIN_ALG_HMAC) || \
( defined(PSA_CRYPTO_DRIVER_TEST) && defined(MBEDTLS_PSA_ACCEL_ALG_HMAC) ) )
#define BUILTIN_ALG_HMAC 1
#endif
#if defined(BUILTIN_ALG_HMAC)
static size_t psa_get_hash_block_size( psa_algorithm_t alg )
{
switch( alg )
{
case PSA_ALG_MD2:
return( 16 );
case PSA_ALG_MD4:
return( 64 );
case PSA_ALG_MD5:
return( 64 );
case PSA_ALG_RIPEMD160:
return( 64 );
case PSA_ALG_SHA_1:
return( 64 );
case PSA_ALG_SHA_224:
return( 64 );
case PSA_ALG_SHA_256:
return( 64 );
case PSA_ALG_SHA_384:
return( 128 );
case PSA_ALG_SHA_512:
return( 128 );
default:
return( 0 );
}
}
static psa_status_t psa_hmac_abort_internal(
mbedtls_psa_hmac_operation_t *hmac )
{
mbedtls_platform_zeroize( hmac->opad, sizeof( hmac->opad ) );
return( psa_hash_abort( &hmac->hash_ctx ) );
}
static psa_status_t psa_hmac_setup_internal(
mbedtls_psa_hmac_operation_t *hmac,
const uint8_t *key,
size_t key_length,
psa_algorithm_t hash_alg )
{
uint8_t ipad[PSA_HMAC_MAX_HASH_BLOCK_SIZE];
size_t i;
size_t hash_size = PSA_HASH_LENGTH( hash_alg );
size_t block_size = psa_get_hash_block_size( hash_alg );
psa_status_t status;
hmac->alg = hash_alg;
/* Sanity checks on block_size, to guarantee that there won't be a buffer
* overflow below. This should never trigger if the hash algorithm
* is implemented correctly. */
/* The size checks against the ipad and opad buffers cannot be written
* `block_size > sizeof( ipad ) || block_size > sizeof( hmac->opad )`
* because that triggers -Wlogical-op on GCC 7.3. */
if( block_size > sizeof( ipad ) )
return( PSA_ERROR_NOT_SUPPORTED );
if( block_size > sizeof( hmac->opad ) )
return( PSA_ERROR_NOT_SUPPORTED );
if( block_size < hash_size )
return( PSA_ERROR_NOT_SUPPORTED );
if( key_length > block_size )
{
status = psa_hash_compute( hash_alg, key, key_length,
ipad, sizeof( ipad ), &key_length );
if( status != PSA_SUCCESS )
goto cleanup;
}
/* A 0-length key is not commonly used in HMAC when used as a MAC,
* but it is permitted. It is common when HMAC is used in HKDF, for
* example. Don't call `memcpy` in the 0-length because `key` could be
* an invalid pointer which would make the behavior undefined. */
else if( key_length != 0 )
memcpy( ipad, key, key_length );
/* ipad contains the key followed by garbage. Xor and fill with 0x36
* to create the ipad value. */
for( i = 0; i < key_length; i++ )
ipad[i] ^= 0x36;
memset( ipad + key_length, 0x36, block_size - key_length );
/* Copy the key material from ipad to opad, flipping the requisite bits,
* and filling the rest of opad with the requisite constant. */
for( i = 0; i < key_length; i++ )
hmac->opad[i] = ipad[i] ^ 0x36 ^ 0x5C;
memset( hmac->opad + key_length, 0x5C, block_size - key_length );
status = psa_hash_setup( &hmac->hash_ctx, hash_alg );
if( status != PSA_SUCCESS )
goto cleanup;
status = psa_hash_update( &hmac->hash_ctx, ipad, block_size );
cleanup:
mbedtls_platform_zeroize( ipad, sizeof( ipad ) );
return( status );
}
static psa_status_t psa_hmac_update_internal(
mbedtls_psa_hmac_operation_t *hmac,
const uint8_t *data,
size_t data_length )
{
return( psa_hash_update( &hmac->hash_ctx, data, data_length ) );
}
static psa_status_t psa_hmac_finish_internal(
mbedtls_psa_hmac_operation_t *hmac,
uint8_t *mac,
size_t mac_size )
{
uint8_t tmp[MBEDTLS_MD_MAX_SIZE];
psa_algorithm_t hash_alg = hmac->alg;
size_t hash_size = 0;
size_t block_size = psa_get_hash_block_size( hash_alg );
psa_status_t status;
status = psa_hash_finish( &hmac->hash_ctx, tmp, sizeof( tmp ), &hash_size );
if( status != PSA_SUCCESS )
return( status );
/* From here on, tmp needs to be wiped. */
status = psa_hash_setup( &hmac->hash_ctx, hash_alg );
if( status != PSA_SUCCESS )
goto exit;
status = psa_hash_update( &hmac->hash_ctx, hmac->opad, block_size );
if( status != PSA_SUCCESS )
goto exit;
status = psa_hash_update( &hmac->hash_ctx, tmp, hash_size );
if( status != PSA_SUCCESS )
goto exit;
status = psa_hash_finish( &hmac->hash_ctx, tmp, sizeof( tmp ), &hash_size );
if( status != PSA_SUCCESS )
goto exit;
memcpy( mac, tmp, mac_size );
exit:
mbedtls_platform_zeroize( tmp, hash_size );
return( status );
}
#endif /* BUILTIN_ALG_HMAC */
#if defined(BUILTIN_ALG_CMAC)
static psa_status_t cmac_setup( mbedtls_psa_mac_operation_t *operation,
const psa_key_attributes_t *attributes,
const uint8_t *key_buffer )
{
int ret = MBEDTLS_ERR_ERROR_CORRUPTION_DETECTED;
#if defined(PSA_WANT_KEY_TYPE_DES)
/* Mbed TLS CMAC does not accept 3DES with only two keys, nor does it accept
* to do CMAC with pure DES, so return NOT_SUPPORTED here. */
if( psa_get_key_type( attributes ) == PSA_KEY_TYPE_DES &&
( psa_get_key_bits( attributes ) == 64 ||
psa_get_key_bits( attributes ) == 128 ) )
return( PSA_ERROR_NOT_SUPPORTED );
#endif
const mbedtls_cipher_info_t * cipher_info =
mbedtls_cipher_info_from_psa(
PSA_ALG_CMAC,
psa_get_key_type( attributes ),
psa_get_key_bits( attributes ),
NULL );
if( cipher_info == NULL )
return( PSA_ERROR_NOT_SUPPORTED );
ret = mbedtls_cipher_setup( &operation->ctx.cmac, cipher_info );
if( ret != 0 )
goto exit;
ret = mbedtls_cipher_cmac_starts( &operation->ctx.cmac,
key_buffer,
psa_get_key_bits( attributes ) );
exit:
return( mbedtls_to_psa_error( ret ) );
}
#endif /* BUILTIN_ALG_CMAC */
/* Implement the PSA driver MAC interface on top of mbed TLS if either the
* software driver or the test driver requires it. */
#if defined(BUILTIN_ALG_HMAC) || defined(BUILTIN_ALG_CMAC)
/* Initialize this driver's MAC operation structure. Once this function has been
* called, mbedtls_psa_mac_abort can run and will do the right thing. */
static psa_status_t mac_init(
mbedtls_psa_mac_operation_t *operation,
psa_algorithm_t alg )
{
psa_status_t status = PSA_ERROR_CORRUPTION_DETECTED;
operation->alg = alg;
#if defined(BUILTIN_ALG_CMAC)
if( PSA_ALG_FULL_LENGTH_MAC( operation->alg ) == PSA_ALG_CMAC )
{
mbedtls_cipher_init( &operation->ctx.cmac );
status = PSA_SUCCESS;
}
else
#endif /* BUILTIN_ALG_CMAC */
#if defined(BUILTIN_ALG_HMAC)
if( PSA_ALG_IS_HMAC( operation->alg ) )
{
/* We'll set up the hash operation later in psa_hmac_setup_internal. */
operation->ctx.hmac.alg = 0;
status = PSA_SUCCESS;
}
else
#endif /* BUILTIN_ALG_HMAC */
{
status = PSA_ERROR_NOT_SUPPORTED;
}
if( status != PSA_SUCCESS )
memset( operation, 0, sizeof( *operation ) );
return( status );
}
static psa_status_t mac_abort( mbedtls_psa_mac_operation_t *operation )
{
if( operation->alg == 0 )
{
/* The object has (apparently) been initialized but it is not
* in use. It's ok to call abort on such an object, and there's
* nothing to do. */
return( PSA_SUCCESS );
}
else
#if defined(BUILTIN_ALG_CMAC)
if( PSA_ALG_FULL_LENGTH_MAC( operation->alg ) == PSA_ALG_CMAC )
{
mbedtls_cipher_free( &operation->ctx.cmac );
}
else
#endif /* BUILTIN_ALG_CMAC */
#if defined(BUILTIN_ALG_HMAC)
if( PSA_ALG_IS_HMAC( operation->alg ) )
{
psa_hmac_abort_internal( &operation->ctx.hmac );
}
else
#endif /* BUILTIN_ALG_HMAC */
{
/* Sanity check (shouldn't happen: operation->alg should
* always have been initialized to a valid value). */
goto bad_state;
}
operation->alg = 0;
return( PSA_SUCCESS );
bad_state:
/* If abort is called on an uninitialized object, we can't trust
* anything. Wipe the object in case it contains confidential data.
* This may result in a memory leak if a pointer gets overwritten,
* but it's too late to do anything about this. */
memset( operation, 0, sizeof( *operation ) );
return( PSA_ERROR_BAD_STATE );
}
static psa_status_t mac_setup( mbedtls_psa_mac_operation_t *operation,
const psa_key_attributes_t *attributes,
const uint8_t *key_buffer,
size_t key_buffer_size,
psa_algorithm_t alg )
{
psa_status_t status = PSA_ERROR_CORRUPTION_DETECTED;
/* A context must be freshly initialized before it can be set up. */
if( operation->alg != 0 )
return( PSA_ERROR_BAD_STATE );
status = mac_init( operation, alg );
if( status != PSA_SUCCESS )
return( status );
#if defined(BUILTIN_ALG_CMAC)
if( PSA_ALG_FULL_LENGTH_MAC( alg ) == PSA_ALG_CMAC )
{
/* Key buffer size for CMAC is dictated by the key bits set on the
* attributes, and previously validated by the core on key import. */
(void) key_buffer_size;
status = cmac_setup( operation, attributes, key_buffer );
}
else
#endif /* BUILTIN_ALG_CMAC */
#if defined(BUILTIN_ALG_HMAC)
if( PSA_ALG_IS_HMAC( alg ) )
{
status = psa_hmac_setup_internal( &operation->ctx.hmac,
key_buffer,
key_buffer_size,
PSA_ALG_HMAC_GET_HASH( alg ) );
}
else
#endif /* BUILTIN_ALG_HMAC */
{
(void) attributes;
(void) key_buffer;
(void) key_buffer_size;
status = PSA_ERROR_NOT_SUPPORTED;
}
if( status != PSA_SUCCESS )
mac_abort( operation );
return( status );
}
static psa_status_t mac_update(
mbedtls_psa_mac_operation_t *operation,
const uint8_t *input,
size_t input_length )
{
if( operation->alg == 0 )
return( PSA_ERROR_BAD_STATE );
#if defined(BUILTIN_ALG_CMAC)
if( PSA_ALG_FULL_LENGTH_MAC( operation->alg ) == PSA_ALG_CMAC )
{
return( mbedtls_to_psa_error(
mbedtls_cipher_cmac_update( &operation->ctx.cmac,
input, input_length ) ) );
}
else
#endif /* BUILTIN_ALG_CMAC */
#if defined(BUILTIN_ALG_HMAC)
if( PSA_ALG_IS_HMAC( operation->alg ) )
{
return( psa_hmac_update_internal( &operation->ctx.hmac,
input, input_length ) );
}
else
#endif /* BUILTIN_ALG_HMAC */
{
/* This shouldn't happen if `operation` was initialized by
* a setup function. */
(void) input;
(void) input_length;
return( PSA_ERROR_BAD_STATE );
}
}
static psa_status_t mac_finish_internal( mbedtls_psa_mac_operation_t *operation,
uint8_t *mac,
size_t mac_size )
{
#if defined(BUILTIN_ALG_CMAC)
if( PSA_ALG_FULL_LENGTH_MAC( operation->alg ) == PSA_ALG_CMAC )
{
uint8_t tmp[PSA_BLOCK_CIPHER_BLOCK_MAX_SIZE];
int ret = mbedtls_cipher_cmac_finish( &operation->ctx.cmac, tmp );
if( ret == 0 )
memcpy( mac, tmp, mac_size );
mbedtls_platform_zeroize( tmp, sizeof( tmp ) );
return( mbedtls_to_psa_error( ret ) );
}
else
#endif /* BUILTIN_ALG_CMAC */
#if defined(BUILTIN_ALG_HMAC)
if( PSA_ALG_IS_HMAC( operation->alg ) )
{
return( psa_hmac_finish_internal( &operation->ctx.hmac,
mac, mac_size ) );
}
else
#endif /* BUILTIN_ALG_HMAC */
{
/* This shouldn't happen if `operation` was initialized by
* a setup function. */
(void) operation;
(void) mac;
(void) mac_size;
return( PSA_ERROR_BAD_STATE );
}
}
static psa_status_t mac_sign_finish(
mbedtls_psa_mac_operation_t *operation,
uint8_t *mac,
size_t mac_size,
size_t *mac_length )
{
psa_status_t status = PSA_ERROR_CORRUPTION_DETECTED;
if( operation->alg == 0 )
return( PSA_ERROR_BAD_STATE );
status = mac_finish_internal( operation, mac, mac_size );
if( status == PSA_SUCCESS )
*mac_length = mac_size;
return( status );
}
static psa_status_t mac_verify_finish(
mbedtls_psa_mac_operation_t *operation,
const uint8_t *mac,
size_t mac_length )
{
uint8_t actual_mac[PSA_MAC_MAX_SIZE];
psa_status_t status = PSA_ERROR_CORRUPTION_DETECTED;
if( operation->alg == 0 )
return( PSA_ERROR_BAD_STATE );
/* Consistency check: requested MAC length fits our local buffer */
if( mac_length > sizeof( actual_mac ) )
return( PSA_ERROR_INVALID_ARGUMENT );
status = mac_finish_internal( operation, actual_mac, mac_length );
if( status != PSA_SUCCESS )
goto cleanup;
if( mbedtls_psa_safer_memcmp( mac, actual_mac, mac_length ) != 0 )
status = PSA_ERROR_INVALID_SIGNATURE;
cleanup:
mbedtls_platform_zeroize( actual_mac, sizeof( actual_mac ) );
return( status );
}
static psa_status_t mac_compute(
const psa_key_attributes_t *attributes,
const uint8_t *key_buffer,
size_t key_buffer_size,
psa_algorithm_t alg,
const uint8_t *input,
size_t input_length,
uint8_t *mac,
size_t mac_size,
size_t *mac_length )
{
psa_status_t status = PSA_ERROR_CORRUPTION_DETECTED;
mbedtls_psa_mac_operation_t operation = MBEDTLS_PSA_MAC_OPERATION_INIT;
status = mac_setup( &operation,
attributes, key_buffer, key_buffer_size,
alg );
if( status != PSA_SUCCESS )
goto exit;
if( input_length > 0 )
{
status = mac_update( &operation, input, input_length );
if( status != PSA_SUCCESS )
goto exit;
}
status = mac_finish_internal( &operation, mac, mac_size );
if( status == PSA_SUCCESS )
*mac_length = mac_size;
exit:
mac_abort( &operation );
return( status );
}
#endif /* BUILTIN_ALG_HMAC || BUILTIN_ALG_CMAC */
#if defined(MBEDTLS_PSA_BUILTIN_MAC)
psa_status_t mbedtls_psa_mac_compute(
const psa_key_attributes_t *attributes,
const uint8_t *key_buffer,
size_t key_buffer_size,
psa_algorithm_t alg,
const uint8_t *input,
size_t input_length,
uint8_t *mac,
size_t mac_size,
size_t *mac_length )
{
return( mac_compute( attributes, key_buffer, key_buffer_size, alg,
input, input_length,
mac, mac_size, mac_length ) );
}
psa_status_t mbedtls_psa_mac_sign_setup(
mbedtls_psa_mac_operation_t *operation,
const psa_key_attributes_t *attributes,
const uint8_t *key_buffer,
size_t key_buffer_size,
psa_algorithm_t alg )
{
return( mac_setup( operation, attributes,
key_buffer, key_buffer_size, alg ) );
}
psa_status_t mbedtls_psa_mac_verify_setup(
mbedtls_psa_mac_operation_t *operation,
const psa_key_attributes_t *attributes,
const uint8_t *key_buffer,
size_t key_buffer_size,
psa_algorithm_t alg )
{
return( mac_setup( operation, attributes,
key_buffer, key_buffer_size, alg ) );
}
psa_status_t mbedtls_psa_mac_update(
mbedtls_psa_mac_operation_t *operation,
const uint8_t *input,
size_t input_length )
{
return( mac_update( operation, input, input_length ) );
}
psa_status_t mbedtls_psa_mac_sign_finish(
mbedtls_psa_mac_operation_t *operation,
uint8_t *mac,
size_t mac_size,
size_t *mac_length )
{
return( mac_sign_finish( operation, mac, mac_size, mac_length ) );
}
psa_status_t mbedtls_psa_mac_verify_finish(
mbedtls_psa_mac_operation_t *operation,
const uint8_t *mac,
size_t mac_length )
{
return( mac_verify_finish( operation, mac, mac_length ) );
}
psa_status_t mbedtls_psa_mac_abort(
mbedtls_psa_mac_operation_t *operation )
{
return( mac_abort( operation ) );
}
#endif /* MBEDTLS_PSA_BUILTIN_MAC */
/*
* BEYOND THIS POINT, TEST DRIVER ENTRY POINTS ONLY.
*/
#if defined(PSA_CRYPTO_DRIVER_TEST)
static int is_mac_accelerated( psa_algorithm_t alg )
{
#if defined(MBEDTLS_PSA_ACCEL_ALG_HMAC)
if( PSA_ALG_IS_HMAC( alg ) )
return( 1 );
#endif
switch( PSA_ALG_FULL_LENGTH_MAC( alg ) )
{
#if defined(MBEDTLS_PSA_ACCEL_ALG_CMAC)
case PSA_ALG_CMAC:
return( 1 );
#endif
default:
return( 0 );
}
}
psa_status_t mbedtls_transparent_test_driver_mac_compute(
const psa_key_attributes_t *attributes,
const uint8_t *key_buffer,
size_t key_buffer_size,
psa_algorithm_t alg,
const uint8_t *input,
size_t input_length,
uint8_t *mac,
size_t mac_size,
size_t *mac_length )
{
if( is_mac_accelerated( alg ) )
return( mac_compute( attributes, key_buffer, key_buffer_size, alg,
input, input_length,
mac, mac_size, mac_length ) );
else
return( PSA_ERROR_NOT_SUPPORTED );
}
psa_status_t mbedtls_transparent_test_driver_mac_sign_setup(
mbedtls_transparent_test_driver_mac_operation_t *operation,
const psa_key_attributes_t *attributes,
const uint8_t *key_buffer,
size_t key_buffer_size,
psa_algorithm_t alg )
{
if( is_mac_accelerated( alg ) )
return( mac_setup( operation, attributes,
key_buffer, key_buffer_size, alg ) );
else
return( PSA_ERROR_NOT_SUPPORTED );
}
psa_status_t mbedtls_transparent_test_driver_mac_verify_setup(
mbedtls_transparent_test_driver_mac_operation_t *operation,
const psa_key_attributes_t *attributes,
const uint8_t *key_buffer,
size_t key_buffer_size,
psa_algorithm_t alg )
{
if( is_mac_accelerated( alg ) )
return( mac_setup( operation, attributes,
key_buffer, key_buffer_size, alg ) );
else
return( PSA_ERROR_NOT_SUPPORTED );
}
psa_status_t mbedtls_transparent_test_driver_mac_update(
mbedtls_transparent_test_driver_mac_operation_t *operation,
const uint8_t *input,
size_t input_length )
{
if( is_mac_accelerated( operation->alg ) )
return( mac_update( operation, input, input_length ) );
else
return( PSA_ERROR_BAD_STATE );
}
psa_status_t mbedtls_transparent_test_driver_mac_sign_finish(
mbedtls_transparent_test_driver_mac_operation_t *operation,
uint8_t *mac,
size_t mac_size,
size_t *mac_length )
{
if( is_mac_accelerated( operation->alg ) )
return( mac_sign_finish( operation, mac, mac_size, mac_length ) );
else
return( PSA_ERROR_BAD_STATE );
}
psa_status_t mbedtls_transparent_test_driver_mac_verify_finish(
mbedtls_transparent_test_driver_mac_operation_t *operation,
const uint8_t *mac,
size_t mac_length )
{
if( is_mac_accelerated( operation->alg ) )
return( mac_verify_finish( operation, mac, mac_length ) );
else
return( PSA_ERROR_BAD_STATE );
}
psa_status_t mbedtls_transparent_test_driver_mac_abort(
mbedtls_transparent_test_driver_mac_operation_t *operation )
{
return( mac_abort( operation ) );
}
psa_status_t mbedtls_opaque_test_driver_mac_compute(
const psa_key_attributes_t *attributes,
const uint8_t *key_buffer,
size_t key_buffer_size,
psa_algorithm_t alg,
const uint8_t *input,
size_t input_length,
uint8_t *mac,
size_t mac_size,
size_t *mac_length )
{
/* Opaque driver testing is not implemented yet through this mechanism. */
(void) attributes;
(void) key_buffer;
(void) key_buffer_size;
(void) alg;
(void) input;
(void) input_length;
(void) mac;
(void) mac_size;
(void) mac_length;
return( PSA_ERROR_NOT_SUPPORTED );
}
psa_status_t mbedtls_opaque_test_driver_mac_sign_setup(
mbedtls_opaque_test_driver_mac_operation_t *operation,
const psa_key_attributes_t *attributes,
const uint8_t *key_buffer,
size_t key_buffer_size,
psa_algorithm_t alg )
{
/* Opaque driver testing is not implemented yet through this mechanism. */
(void) operation;
(void) attributes;
(void) key_buffer;
(void) key_buffer_size;
(void) alg;
return( PSA_ERROR_NOT_SUPPORTED );
}
psa_status_t mbedtls_opaque_test_driver_mac_verify_setup(
mbedtls_opaque_test_driver_mac_operation_t *operation,
const psa_key_attributes_t *attributes,
const uint8_t *key_buffer,
size_t key_buffer_size,
psa_algorithm_t alg )
{
/* Opaque driver testing is not implemented yet through this mechanism. */
(void) operation;
(void) attributes;
(void) key_buffer;
(void) key_buffer_size;
(void) alg;
return( PSA_ERROR_NOT_SUPPORTED );
}
psa_status_t mbedtls_opaque_test_driver_mac_update(
mbedtls_opaque_test_driver_mac_operation_t *operation,
const uint8_t *input,
size_t input_length )
{
/* Opaque driver testing is not implemented yet through this mechanism. */
(void) operation;
(void) input;
(void) input_length;
return( PSA_ERROR_NOT_SUPPORTED );
}
psa_status_t mbedtls_opaque_test_driver_mac_sign_finish(
mbedtls_opaque_test_driver_mac_operation_t *operation,
uint8_t *mac,
size_t mac_size,
size_t *mac_length )
{
/* Opaque driver testing is not implemented yet through this mechanism. */
(void) operation;
(void) mac;
(void) mac_size;
(void) mac_length;
return( PSA_ERROR_NOT_SUPPORTED );
}
psa_status_t mbedtls_opaque_test_driver_mac_verify_finish(
mbedtls_opaque_test_driver_mac_operation_t *operation,
const uint8_t *mac,
size_t mac_length )
{
/* Opaque driver testing is not implemented yet through this mechanism. */
(void) operation;
(void) mac;
(void) mac_length;
return( PSA_ERROR_NOT_SUPPORTED );
}
psa_status_t mbedtls_opaque_test_driver_mac_abort(
mbedtls_opaque_test_driver_mac_operation_t *operation )
{
/* Opaque driver testing is not implemented yet through this mechanism. */
(void) operation;
return( PSA_ERROR_NOT_SUPPORTED );
}
#endif /* PSA_CRYPTO_DRIVER_TEST */
#endif /* MBEDTLS_PSA_CRYPTO_C */
|
0 | repos/gpt4all.zig/src/zig-libcurl/zig-mbedtls/mbedtls | repos/gpt4all.zig/src/zig-libcurl/zig-mbedtls/mbedtls/library/psa_crypto_ecp.h | /*
* PSA ECP layer on top of Mbed TLS crypto
*/
/*
* Copyright The Mbed TLS Contributors
* SPDX-License-Identifier: Apache-2.0
*
* 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.
*/
#ifndef PSA_CRYPTO_ECP_H
#define PSA_CRYPTO_ECP_H
#include <psa/crypto.h>
#include <mbedtls/ecp.h>
/** Load the contents of a key buffer into an internal ECP representation
*
* \param[in] type The type of key contained in \p data.
* \param[in] curve_bits The nominal bit-size of the curve.
* It must be consistent with the representation
* passed in \p data.
* This can be 0, in which case the bit-size
* is inferred from \p data_length (which is possible
* for all key types and representation formats
* formats that are currently supported or will
* be in the foreseeable future).
* \param[in] data The buffer from which to load the representation.
* \param[in] data_length The size in bytes of \p data.
* \param[out] p_ecp Returns a pointer to an ECP context on success.
* The caller is responsible for freeing both the
* contents of the context and the context itself
* when done.
*/
psa_status_t mbedtls_psa_ecp_load_representation( psa_key_type_t type,
size_t curve_bits,
const uint8_t *data,
size_t data_length,
mbedtls_ecp_keypair **p_ecp );
/** Import an ECP key in binary format.
*
* \note The signature of this function is that of a PSA driver
* import_key entry point. This function behaves as an import_key
* entry point as defined in the PSA driver interface specification for
* transparent drivers.
*
* \param[in] attributes The attributes for the key to import.
* \param[in] data The buffer containing the key data in import
* format.
* \param[in] data_length Size of the \p data buffer in bytes.
* \param[out] key_buffer The buffer containing the key data in output
* format.
* \param[in] key_buffer_size Size of the \p key_buffer buffer in bytes. This
* size is greater or equal to \p data_length.
* \param[out] key_buffer_length The length of the data written in \p
* key_buffer in bytes.
* \param[out] bits The key size in number of bits.
*
* \retval #PSA_SUCCESS The ECP key was imported successfully.
* \retval #PSA_ERROR_INVALID_ARGUMENT
* The key data is not correctly formatted.
* \retval #PSA_ERROR_NOT_SUPPORTED
* \retval #PSA_ERROR_INSUFFICIENT_MEMORY
* \retval #PSA_ERROR_CORRUPTION_DETECTED
*/
psa_status_t mbedtls_psa_ecp_import_key(
const psa_key_attributes_t *attributes,
const uint8_t *data, size_t data_length,
uint8_t *key_buffer, size_t key_buffer_size,
size_t *key_buffer_length, size_t *bits );
/** Export an ECP key to export representation
*
* \param[in] type The type of key (public/private) to export
* \param[in] ecp The internal ECP representation from which to export
* \param[out] data The buffer to export to
* \param[in] data_size The length of the buffer to export to
* \param[out] data_length The amount of bytes written to \p data
*/
psa_status_t mbedtls_psa_ecp_export_key( psa_key_type_t type,
mbedtls_ecp_keypair *ecp,
uint8_t *data,
size_t data_size,
size_t *data_length );
/** Export an ECP public key or the public part of an ECP key pair in binary
* format.
*
* \note The signature of this function is that of a PSA driver
* export_public_key entry point. This function behaves as an
* export_public_key entry point as defined in the PSA driver interface
* specification.
*
* \param[in] attributes The attributes for the key to export.
* \param[in] key_buffer Material or context of the key to export.
* \param[in] key_buffer_size Size of the \p key_buffer buffer in bytes.
* \param[out] data Buffer where the key data is to be written.
* \param[in] data_size Size of the \p data buffer in bytes.
* \param[out] data_length On success, the number of bytes written in
* \p data
*
* \retval #PSA_SUCCESS The ECP public key was exported successfully.
* \retval #PSA_ERROR_NOT_SUPPORTED
* \retval #PSA_ERROR_COMMUNICATION_FAILURE
* \retval #PSA_ERROR_HARDWARE_FAILURE
* \retval #PSA_ERROR_CORRUPTION_DETECTED
* \retval #PSA_ERROR_STORAGE_FAILURE
* \retval #PSA_ERROR_INSUFFICIENT_MEMORY
*/
psa_status_t mbedtls_psa_ecp_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 );
/**
* \brief Generate an ECP key.
*
* \note The signature of the function is that of a PSA driver generate_key
* entry point.
*
* \param[in] attributes The attributes for the ECP key to generate.
* \param[out] key_buffer Buffer where the key data is to be written.
* \param[in] key_buffer_size Size of \p key_buffer in bytes.
* \param[out] key_buffer_length On success, the number of bytes written in
* \p key_buffer.
*
* \retval #PSA_SUCCESS
* The key was successfully generated.
* \retval #PSA_ERROR_NOT_SUPPORTED
* Key length or type not supported.
* \retval #PSA_ERROR_BUFFER_TOO_SMALL
* The size of \p key_buffer is too small.
*/
psa_status_t mbedtls_psa_ecp_generate_key(
const psa_key_attributes_t *attributes,
uint8_t *key_buffer, size_t key_buffer_size, size_t *key_buffer_length );
/** Sign an already-calculated hash with ECDSA.
*
* \note The signature of this function is that of a PSA driver
* sign_hash entry point. This function behaves as a sign_hash
* entry point as defined in the PSA driver interface specification for
* transparent drivers.
*
* \param[in] attributes The attributes of the ECC key to use for the
* operation.
* \param[in] key_buffer The buffer containing the ECC key context.
* format.
* \param[in] key_buffer_size Size of the \p key_buffer buffer in bytes.
* \param[in] alg Randomized or deterministic ECDSA algorithm.
* \param[in] hash The hash or message to sign.
* \param[in] hash_length Size of the \p hash buffer in bytes.
* \param[out] signature Buffer where the 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
* \retval #PSA_ERROR_BUFFER_TOO_SMALL
* The size of the \p signature buffer is too small. You can
* determine a sufficient buffer size by calling
* #PSA_SIGN_OUTPUT_SIZE(\c PSA_KEY_TYPE_ECC_KEY_PAIR, \c key_bits,
* \p alg) where \c key_bits is the bit-size of the ECC key.
* \retval #PSA_ERROR_NOT_SUPPORTED
* \retval #PSA_ERROR_INVALID_ARGUMENT
* \retval #PSA_ERROR_INSUFFICIENT_MEMORY
* \retval #PSA_ERROR_CORRUPTION_DETECTED
* \retval #PSA_ERROR_INSUFFICIENT_ENTROPY
*/
psa_status_t mbedtls_psa_ecdsa_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 );
/**
* \brief Verify an ECDSA hash or short message signature.
*
* \note The signature of this function is that of a PSA driver
* verify_hash entry point. This function behaves as a verify_hash
* entry point as defined in the PSA driver interface specification for
* transparent drivers.
*
* \param[in] attributes The attributes of the ECC key to use for the
* operation.
* \param[in] key_buffer The buffer containing the ECC key context.
* format.
* \param[in] key_buffer_size Size of the \p key_buffer buffer in bytes.
* \param[in] alg Randomized or deterministic ECDSA algorithm.
* \param[in] hash The hash or message 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
* \retval #PSA_ERROR_INVALID_ARGUMENT
* \retval #PSA_ERROR_INSUFFICIENT_MEMORY
*/
psa_status_t mbedtls_psa_ecdsa_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 );
/*
* BEYOND THIS POINT, TEST DRIVER ENTRY POINTS ONLY.
*/
#if defined(PSA_CRYPTO_DRIVER_TEST)
psa_status_t mbedtls_transparent_test_driver_ecp_import_key(
const psa_key_attributes_t *attributes,
const uint8_t *data, size_t data_length,
uint8_t *key_buffer, size_t key_buffer_size,
size_t *key_buffer_length, size_t *bits );
psa_status_t mbedtls_transparent_test_driver_ecp_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 );
psa_status_t mbedtls_transparent_test_driver_ecp_generate_key(
const psa_key_attributes_t *attributes,
uint8_t *key_buffer, size_t key_buffer_size, size_t *key_buffer_length );
psa_status_t mbedtls_transparent_test_driver_ecdsa_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 );
psa_status_t mbedtls_transparent_test_driver_ecdsa_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 /* PSA_CRYPTO_DRIVER_TEST */
#endif /* PSA_CRYPTO_ECP_H */
|
0 | repos/gpt4all.zig/src/zig-libcurl/zig-mbedtls/mbedtls | repos/gpt4all.zig/src/zig-libcurl/zig-mbedtls/mbedtls/library/mps_trace.h | /*
* Copyright The Mbed TLS Contributors
* SPDX-License-Identifier: Apache-2.0
*
* 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.
*
* This file is part of mbed TLS (https://tls.mbed.org)
*/
/**
* \file mps_trace.h
*
* \brief Tracing module for MPS
*/
#ifndef MBEDTLS_MPS_MBEDTLS_MPS_TRACE_H
#define MBEDTLS_MPS_MBEDTLS_MPS_TRACE_H
#include "common.h"
#include "mps_common.h"
#include "mps_trace.h"
#if defined(MBEDTLS_PLATFORM_C)
#include "mbedtls/platform.h"
#else
#include <stdio.h>
#define mbedtls_printf printf
#define mbedtls_vsnprintf vsnprintf
#endif /* MBEDTLS_PLATFORM_C */
#if defined(MBEDTLS_MPS_ENABLE_TRACE)
/*
* Adapt this to enable/disable tracing output
* from the various layers of the MPS.
*/
#define MBEDTLS_MPS_TRACE_ENABLE_LAYER_1
#define MBEDTLS_MPS_TRACE_ENABLE_LAYER_2
#define MBEDTLS_MPS_TRACE_ENABLE_LAYER_3
#define MBEDTLS_MPS_TRACE_ENABLE_LAYER_4
#define MBEDTLS_MPS_TRACE_ENABLE_READER
#define MBEDTLS_MPS_TRACE_ENABLE_WRITER
/*
* To use the existing trace module, only change
* MBEDTLS_MPS_TRACE_ENABLE_XXX above, but don't modify the
* rest of this file.
*/
typedef enum
{
MBEDTLS_MPS_TRACE_TYPE_COMMENT,
MBEDTLS_MPS_TRACE_TYPE_CALL,
MBEDTLS_MPS_TRACE_TYPE_ERROR,
MBEDTLS_MPS_TRACE_TYPE_RETURN
} mbedtls_mps_trace_type;
#define MBEDTLS_MPS_TRACE_BIT_LAYER_1 1
#define MBEDTLS_MPS_TRACE_BIT_LAYER_2 2
#define MBEDTLS_MPS_TRACE_BIT_LAYER_3 3
#define MBEDTLS_MPS_TRACE_BIT_LAYER_4 4
#define MBEDTLS_MPS_TRACE_BIT_WRITER 5
#define MBEDTLS_MPS_TRACE_BIT_READER 6
#if defined(MBEDTLS_MPS_TRACE_ENABLE_LAYER_1)
#define MBEDTLS_MPS_TRACE_MASK_LAYER_1 (1u << MBEDTLS_MPS_TRACE_BIT_LAYER_1 )
#else
#define MBEDTLS_MPS_TRACE_MASK_LAYER_1 0
#endif
#if defined(MBEDTLS_MPS_TRACE_ENABLE_LAYER_2)
#define MBEDTLS_MPS_TRACE_MASK_LAYER_2 (1u << MBEDTLS_MPS_TRACE_BIT_LAYER_2 )
#else
#define MBEDTLS_MPS_TRACE_MASK_LAYER_2 0
#endif
#if defined(MBEDTLS_MPS_TRACE_ENABLE_LAYER_3)
#define MBEDTLS_MPS_TRACE_MASK_LAYER_3 (1u << MBEDTLS_MPS_TRACE_BIT_LAYER_3 )
#else
#define MBEDTLS_MPS_TRACE_MASK_LAYER_3 0
#endif
#if defined(MBEDTLS_MPS_TRACE_ENABLE_LAYER_4)
#define MBEDTLS_MPS_TRACE_MASK_LAYER_4 (1u << MBEDTLS_MPS_TRACE_BIT_LAYER_4 )
#else
#define MBEDTLS_MPS_TRACE_MASK_LAYER_4 0
#endif
#if defined(MBEDTLS_MPS_TRACE_ENABLE_READER)
#define MBEDTLS_MPS_TRACE_MASK_READER (1u << MBEDTLS_MPS_TRACE_BIT_READER )
#else
#define MBEDTLS_MPS_TRACE_MASK_READER 0
#endif
#if defined(MBEDTLS_MPS_TRACE_ENABLE_WRITER)
#define MBEDTLS_MPS_TRACE_MASK_WRITER (1u << MBEDTLS_MPS_TRACE_BIT_WRITER )
#else
#define MBEDTLS_MPS_TRACE_MASK_WRITER 0
#endif
#define MBEDTLS_MPS_TRACE_MASK ( MBEDTLS_MPS_TRACE_MASK_LAYER_1 | \
MBEDTLS_MPS_TRACE_MASK_LAYER_2 | \
MBEDTLS_MPS_TRACE_MASK_LAYER_3 | \
MBEDTLS_MPS_TRACE_MASK_LAYER_4 | \
MBEDTLS_MPS_TRACE_MASK_READER | \
MBEDTLS_MPS_TRACE_MASK_WRITER )
/* We have to avoid globals because E-ACSL chokes on them...
* Wrap everything in stub functions. */
int mbedtls_mps_trace_get_depth( void );
void mbedtls_mps_trace_inc_depth( void );
void mbedtls_mps_trace_dec_depth( void );
void mbedtls_mps_trace_color( int id );
void mbedtls_mps_trace_indent( int level, mbedtls_mps_trace_type ty );
void mbedtls_mps_trace_print_msg( int id, int line, const char *format, ... );
#define MBEDTLS_MPS_TRACE( type, ... ) \
do { \
if( ! ( MBEDTLS_MPS_TRACE_MASK & ( 1u << mbedtls_mps_trace_id ) ) ) \
break; \
mbedtls_mps_trace_indent( mbedtls_mps_trace_get_depth(), type ); \
mbedtls_mps_trace_color( mbedtls_mps_trace_id ); \
mbedtls_mps_trace_print_msg( mbedtls_mps_trace_id, __LINE__, __VA_ARGS__ ); \
mbedtls_mps_trace_color( 0 ); \
} while( 0 )
#define MBEDTLS_MPS_TRACE_INIT( ... ) \
do { \
if( ! ( MBEDTLS_MPS_TRACE_MASK & ( 1u << mbedtls_mps_trace_id ) ) ) \
break; \
MBEDTLS_MPS_TRACE( MBEDTLS_MPS_TRACE_TYPE_CALL, __VA_ARGS__ ); \
mbedtls_mps_trace_inc_depth(); \
} while( 0 )
#define MBEDTLS_MPS_TRACE_END( val ) \
do { \
if( ! ( MBEDTLS_MPS_TRACE_MASK & ( 1u << mbedtls_mps_trace_id ) ) ) \
break; \
MBEDTLS_MPS_TRACE( MBEDTLS_MPS_TRACE_TYPE_RETURN, "%d (-%#04x)", \
(int) (val), -((unsigned)(val)) ); \
mbedtls_mps_trace_dec_depth(); \
} while( 0 )
#define MBEDTLS_MPS_TRACE_RETURN( val ) \
do { \
/* Breaks tail recursion. */ \
int ret__ = val; \
MBEDTLS_MPS_TRACE_END( ret__ ); \
return( ret__ ); \
} while( 0 )
#else /* MBEDTLS_MPS_TRACE */
#define MBEDTLS_MPS_TRACE( type, ... ) do { } while( 0 )
#define MBEDTLS_MPS_TRACE_INIT( ... ) do { } while( 0 )
#define MBEDTLS_MPS_TRACE_END do { } while( 0 )
#define MBEDTLS_MPS_TRACE_RETURN( val ) return( val );
#endif /* MBEDTLS_MPS_TRACE */
#endif /* MBEDTLS_MPS_MBEDTLS_MPS_TRACE_H */
|
0 | repos/gpt4all.zig/src/zig-libcurl/zig-mbedtls/mbedtls | repos/gpt4all.zig/src/zig-libcurl/zig-mbedtls/mbedtls/library/psa_crypto_its.h | /** \file psa_crypto_its.h
* \brief Interface of trusted storage that crypto is built on.
*/
/*
* Copyright The Mbed TLS Contributors
* SPDX-License-Identifier: Apache-2.0
*
* 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.
*/
#ifndef PSA_CRYPTO_ITS_H
#define PSA_CRYPTO_ITS_H
#include <stddef.h>
#include <stdint.h>
#include <psa/crypto_types.h>
#include <psa/crypto_values.h>
#ifdef __cplusplus
extern "C" {
#endif
/** \brief Flags used when creating a data entry
*/
typedef uint32_t psa_storage_create_flags_t;
/** \brief A type for UIDs used for identifying data
*/
typedef uint64_t psa_storage_uid_t;
#define PSA_STORAGE_FLAG_NONE 0 /**< No flags to pass */
#define PSA_STORAGE_FLAG_WRITE_ONCE (1 << 0) /**< The data associated with the uid will not be able to be modified or deleted. Intended to be used to set bits in `psa_storage_create_flags_t`*/
/**
* \brief A container for metadata associated with a specific uid
*/
struct psa_storage_info_t
{
uint32_t size; /**< The size of the data associated with a uid **/
psa_storage_create_flags_t flags; /**< The flags set when the uid was created **/
};
/** Flag indicating that \ref psa_storage_create and \ref psa_storage_set_extended are supported */
#define PSA_STORAGE_SUPPORT_SET_EXTENDED (1 << 0)
/** \brief PSA storage specific error codes
*/
#define PSA_ERROR_INVALID_SIGNATURE ((psa_status_t)-149)
#define PSA_ERROR_DATA_CORRUPT ((psa_status_t)-152)
#define PSA_ITS_API_VERSION_MAJOR 1 /**< The major version number of the PSA ITS API. It will be incremented on significant updates that may include breaking changes */
#define PSA_ITS_API_VERSION_MINOR 1 /**< The minor version number of the PSA ITS API. It will be incremented in small updates that are unlikely to include breaking changes */
/**
* \brief create a new or modify an existing uid/value pair
*
* \param[in] uid the identifier for the data
* \param[in] data_length The size in bytes of the data in `p_data`
* \param[in] p_data A buffer containing the data
* \param[in] create_flags The flags that the data will be stored with
*
* \return A status indicating the success/failure of the operation
*
* \retval #PSA_SUCCESS The operation completed successfully
* \retval #PSA_ERROR_NOT_PERMITTED The operation failed because the provided `uid` value was already created with PSA_STORAGE_WRITE_ONCE_FLAG
* \retval #PSA_ERROR_NOT_SUPPORTED The operation failed because one or more of the flags provided in `create_flags` is not supported or is not valid
* \retval #PSA_ERROR_INSUFFICIENT_STORAGE The operation failed because there was insufficient space on the storage medium
* \retval #PSA_ERROR_STORAGE_FAILURE The operation failed because the physical storage has failed (Fatal error)
* \retval #PSA_ERROR_INVALID_ARGUMENT The operation failed because one of the provided pointers(`p_data`)
* is invalid, for example is `NULL` or references memory the caller cannot access
*/
psa_status_t psa_its_set(psa_storage_uid_t uid,
uint32_t data_length,
const void *p_data,
psa_storage_create_flags_t create_flags);
/**
* \brief Retrieve the value associated with a provided uid
*
* \param[in] uid The uid value
* \param[in] data_offset The starting offset of the data requested
* \param[in] data_length the amount of data requested (and the minimum allocated size of the `p_data` buffer)
* \param[out] p_data The buffer where the data will be placed upon successful completion
* \param[out] p_data_length The amount of data returned in the p_data buffer
*
*
* \return A status indicating the success/failure of the operation
*
* \retval #PSA_SUCCESS The operation completed successfully
* \retval #PSA_ERROR_DOES_NOT_EXIST The operation failed because the provided `uid` value was not found in the storage
* \retval #PSA_ERROR_STORAGE_FAILURE The operation failed because the physical storage has failed (Fatal error)
* \retval #PSA_ERROR_DATA_CORRUPT The operation failed because stored data has been corrupted
* \retval #PSA_ERROR_INVALID_ARGUMENT The operation failed because one of the provided pointers(`p_data`, `p_data_length`)
* is invalid. For example is `NULL` or references memory the caller cannot access.
* In addition, this can also happen if an invalid offset was provided.
*/
psa_status_t psa_its_get(psa_storage_uid_t uid,
uint32_t data_offset,
uint32_t data_length,
void *p_data,
size_t *p_data_length );
/**
* \brief Retrieve the metadata about the provided uid
*
* \param[in] uid The uid value
* \param[out] p_info A pointer to the `psa_storage_info_t` struct that will be populated with the metadata
*
* \return A status indicating the success/failure of the operation
*
* \retval #PSA_SUCCESS The operation completed successfully
* \retval #PSA_ERROR_DOES_NOT_EXIST The operation failed because the provided uid value was not found in the storage
* \retval #PSA_ERROR_DATA_CORRUPT The operation failed because stored data has been corrupted
* \retval #PSA_ERROR_INVALID_ARGUMENT The operation failed because one of the provided pointers(`p_info`)
* is invalid, for example is `NULL` or references memory the caller cannot access
*/
psa_status_t psa_its_get_info(psa_storage_uid_t uid,
struct psa_storage_info_t *p_info);
/**
* \brief Remove the provided key and its associated data from the storage
*
* \param[in] uid The uid value
*
* \return A status indicating the success/failure of the operation
*
* \retval #PSA_SUCCESS The operation completed successfully
* \retval #PSA_ERROR_DOES_NOT_EXIST The operation failed because the provided key value was not found in the storage
* \retval #PSA_ERROR_NOT_PERMITTED The operation failed because the provided key value was created with PSA_STORAGE_WRITE_ONCE_FLAG
* \retval #PSA_ERROR_STORAGE_FAILURE The operation failed because the physical storage has failed (Fatal error)
*/
psa_status_t psa_its_remove(psa_storage_uid_t uid);
#ifdef __cplusplus
}
#endif
#endif /* PSA_CRYPTO_ITS_H */
|
0 | repos/gpt4all.zig/src/zig-libcurl/zig-mbedtls/mbedtls | repos/gpt4all.zig/src/zig-libcurl/zig-mbedtls/mbedtls/library/aria.c | /*
* ARIA implementation
*
* Copyright The Mbed TLS Contributors
* SPDX-License-Identifier: Apache-2.0
*
* 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.
*/
/*
* This implementation is based on the following standards:
* [1] http://210.104.33.10/ARIA/doc/ARIA-specification-e.pdf
* [2] https://tools.ietf.org/html/rfc5794
*/
#include "common.h"
#if defined(MBEDTLS_ARIA_C)
#include "mbedtls/aria.h"
#include <string.h>
#if defined(MBEDTLS_SELF_TEST)
#if defined(MBEDTLS_PLATFORM_C)
#include "mbedtls/platform.h"
#else
#include <stdio.h>
#define mbedtls_printf printf
#endif /* MBEDTLS_PLATFORM_C */
#endif /* MBEDTLS_SELF_TEST */
#if !defined(MBEDTLS_ARIA_ALT)
#include "mbedtls/platform_util.h"
#if ( defined(__ARMCC_VERSION) || defined(_MSC_VER) ) && \
!defined(inline) && !defined(__cplusplus)
#define inline __inline
#endif
/* Parameter validation macros */
#define ARIA_VALIDATE_RET( cond ) \
MBEDTLS_INTERNAL_VALIDATE_RET( cond, MBEDTLS_ERR_ARIA_BAD_INPUT_DATA )
#define ARIA_VALIDATE( cond ) \
MBEDTLS_INTERNAL_VALIDATE( cond )
/*
* 32-bit integer manipulation macros (little endian)
*/
#ifndef GET_UINT32_LE
#define GET_UINT32_LE( n, b, i ) \
{ \
(n) = ( (uint32_t) (b)[(i) ] ) \
| ( (uint32_t) (b)[(i) + 1] << 8 ) \
| ( (uint32_t) (b)[(i) + 2] << 16 ) \
| ( (uint32_t) (b)[(i) + 3] << 24 ); \
}
#endif
#ifndef PUT_UINT32_LE
#define PUT_UINT32_LE( n, b, i ) \
{ \
(b)[(i) ] = (unsigned char) ( ( (n) ) & 0xFF ); \
(b)[(i) + 1] = (unsigned char) ( ( (n) >> 8 ) & 0xFF ); \
(b)[(i) + 2] = (unsigned char) ( ( (n) >> 16 ) & 0xFF ); \
(b)[(i) + 3] = (unsigned char) ( ( (n) >> 24 ) & 0xFF ); \
}
#endif
/*
* modify byte order: ( A B C D ) -> ( B A D C ), i.e. swap pairs of bytes
*
* This is submatrix P1 in [1] Appendix B.1
*
* Common compilers fail to translate this to minimal number of instructions,
* so let's provide asm versions for common platforms with C fallback.
*/
#if defined(MBEDTLS_HAVE_ASM)
#if defined(__arm__) /* rev16 available from v6 up */
/* armcc5 --gnu defines __GNUC__ but doesn't support GNU's extended asm */
#if defined(__GNUC__) && \
( !defined(__ARMCC_VERSION) || __ARMCC_VERSION >= 6000000 ) && \
__ARM_ARCH >= 6
static inline uint32_t aria_p1( uint32_t x )
{
uint32_t r;
__asm( "rev16 %0, %1" : "=l" (r) : "l" (x) );
return( r );
}
#define ARIA_P1 aria_p1
#elif defined(__ARMCC_VERSION) && __ARMCC_VERSION < 6000000 && \
( __TARGET_ARCH_ARM >= 6 || __TARGET_ARCH_THUMB >= 3 )
static inline uint32_t aria_p1( uint32_t x )
{
uint32_t r;
__asm( "rev16 r, x" );
return( r );
}
#define ARIA_P1 aria_p1
#endif
#endif /* arm */
#if defined(__GNUC__) && \
defined(__i386__) || defined(__amd64__) || defined( __x86_64__)
/* I couldn't find an Intel equivalent of rev16, so two instructions */
#define ARIA_P1(x) ARIA_P2( ARIA_P3( x ) )
#endif /* x86 gnuc */
#endif /* MBEDTLS_HAVE_ASM && GNUC */
#if !defined(ARIA_P1)
#define ARIA_P1(x) ((((x) >> 8) & 0x00FF00FF) ^ (((x) & 0x00FF00FF) << 8))
#endif
/*
* modify byte order: ( A B C D ) -> ( C D A B ), i.e. rotate by 16 bits
*
* This is submatrix P2 in [1] Appendix B.1
*
* Common compilers will translate this to a single instruction.
*/
#define ARIA_P2(x) (((x) >> 16) ^ ((x) << 16))
/*
* modify byte order: ( A B C D ) -> ( D C B A ), i.e. change endianness
*
* This is submatrix P3 in [1] Appendix B.1
*
* Some compilers fail to translate this to a single instruction,
* so let's provide asm versions for common platforms with C fallback.
*/
#if defined(MBEDTLS_HAVE_ASM)
#if defined(__arm__) /* rev available from v6 up */
/* armcc5 --gnu defines __GNUC__ but doesn't support GNU's extended asm */
#if defined(__GNUC__) && \
( !defined(__ARMCC_VERSION) || __ARMCC_VERSION >= 6000000 ) && \
__ARM_ARCH >= 6
static inline uint32_t aria_p3( uint32_t x )
{
uint32_t r;
__asm( "rev %0, %1" : "=l" (r) : "l" (x) );
return( r );
}
#define ARIA_P3 aria_p3
#elif defined(__ARMCC_VERSION) && __ARMCC_VERSION < 6000000 && \
( __TARGET_ARCH_ARM >= 6 || __TARGET_ARCH_THUMB >= 3 )
static inline uint32_t aria_p3( uint32_t x )
{
uint32_t r;
__asm( "rev r, x" );
return( r );
}
#define ARIA_P3 aria_p3
#endif
#endif /* arm */
#if defined(__GNUC__) && \
defined(__i386__) || defined(__amd64__) || defined( __x86_64__)
static inline uint32_t aria_p3( uint32_t x )
{
__asm( "bswap %0" : "=r" (x) : "0" (x) );
return( x );
}
#define ARIA_P3 aria_p3
#endif /* x86 gnuc */
#endif /* MBEDTLS_HAVE_ASM && GNUC */
#if !defined(ARIA_P3)
#define ARIA_P3(x) ARIA_P2( ARIA_P1 ( x ) )
#endif
/*
* ARIA Affine Transform
* (a, b, c, d) = state in/out
*
* If we denote the first byte of input by 0, ..., the last byte by f,
* then inputs are: a = 0123, b = 4567, c = 89ab, d = cdef.
*
* Reading [1] 2.4 or [2] 2.4.3 in columns and performing simple
* rearrangements on adjacent pairs, output is:
*
* a = 3210 + 4545 + 6767 + 88aa + 99bb + dccd + effe
* = 3210 + 4567 + 6745 + 89ab + 98ba + dcfe + efcd
* b = 0101 + 2323 + 5476 + 8998 + baab + eecc + ffdd
* = 0123 + 2301 + 5476 + 89ab + ba98 + efcd + fedc
* c = 0022 + 1133 + 4554 + 7667 + ab89 + dcdc + fefe
* = 0123 + 1032 + 4567 + 7654 + ab89 + dcfe + fedc
* d = 1001 + 2332 + 6644 + 7755 + 9898 + baba + cdef
* = 1032 + 2301 + 6745 + 7654 + 98ba + ba98 + cdef
*
* Note: another presentation of the A transform can be found as the first
* half of App. B.1 in [1] in terms of 4-byte operators P1, P2, P3 and P4.
* The implementation below uses only P1 and P2 as they are sufficient.
*/
static inline void aria_a( uint32_t *a, uint32_t *b,
uint32_t *c, uint32_t *d )
{
uint32_t ta, tb, tc;
ta = *b; // 4567
*b = *a; // 0123
*a = ARIA_P2( ta ); // 6745
tb = ARIA_P2( *d ); // efcd
*d = ARIA_P1( *c ); // 98ba
*c = ARIA_P1( tb ); // fedc
ta ^= *d; // 4567+98ba
tc = ARIA_P2( *b ); // 2301
ta = ARIA_P1( ta ) ^ tc ^ *c; // 2301+5476+89ab+fedc
tb ^= ARIA_P2( *d ); // ba98+efcd
tc ^= ARIA_P1( *a ); // 2301+7654
*b ^= ta ^ tb; // 0123+2301+5476+89ab+ba98+efcd+fedc OUT
tb = ARIA_P2( tb ) ^ ta; // 2301+5476+89ab+98ba+cdef+fedc
*a ^= ARIA_P1( tb ); // 3210+4567+6745+89ab+98ba+dcfe+efcd OUT
ta = ARIA_P2( ta ); // 0123+7654+ab89+dcfe
*d ^= ARIA_P1( ta ) ^ tc; // 1032+2301+6745+7654+98ba+ba98+cdef OUT
tc = ARIA_P2( tc ); // 0123+5476
*c ^= ARIA_P1( tc ) ^ ta; // 0123+1032+4567+7654+ab89+dcfe+fedc OUT
}
/*
* ARIA Substitution Layer SL1 / SL2
* (a, b, c, d) = state in/out
* (sa, sb, sc, sd) = 256 8-bit S-Boxes (see below)
*
* By passing sb1, sb2, is1, is2 as S-Boxes you get SL1
* By passing is1, is2, sb1, sb2 as S-Boxes you get SL2
*/
static inline void aria_sl( uint32_t *a, uint32_t *b,
uint32_t *c, uint32_t *d,
const uint8_t sa[256], const uint8_t sb[256],
const uint8_t sc[256], const uint8_t sd[256] )
{
*a = ( (uint32_t) sa[ *a & 0xFF] ) ^
(((uint32_t) sb[(*a >> 8) & 0xFF]) << 8) ^
(((uint32_t) sc[(*a >> 16) & 0xFF]) << 16) ^
(((uint32_t) sd[ *a >> 24 ]) << 24);
*b = ( (uint32_t) sa[ *b & 0xFF] ) ^
(((uint32_t) sb[(*b >> 8) & 0xFF]) << 8) ^
(((uint32_t) sc[(*b >> 16) & 0xFF]) << 16) ^
(((uint32_t) sd[ *b >> 24 ]) << 24);
*c = ( (uint32_t) sa[ *c & 0xFF] ) ^
(((uint32_t) sb[(*c >> 8) & 0xFF]) << 8) ^
(((uint32_t) sc[(*c >> 16) & 0xFF]) << 16) ^
(((uint32_t) sd[ *c >> 24 ]) << 24);
*d = ( (uint32_t) sa[ *d & 0xFF] ) ^
(((uint32_t) sb[(*d >> 8) & 0xFF]) << 8) ^
(((uint32_t) sc[(*d >> 16) & 0xFF]) << 16) ^
(((uint32_t) sd[ *d >> 24 ]) << 24);
}
/*
* S-Boxes
*/
static const uint8_t aria_sb1[256] =
{
0x63, 0x7C, 0x77, 0x7B, 0xF2, 0x6B, 0x6F, 0xC5, 0x30, 0x01, 0x67, 0x2B,
0xFE, 0xD7, 0xAB, 0x76, 0xCA, 0x82, 0xC9, 0x7D, 0xFA, 0x59, 0x47, 0xF0,
0xAD, 0xD4, 0xA2, 0xAF, 0x9C, 0xA4, 0x72, 0xC0, 0xB7, 0xFD, 0x93, 0x26,
0x36, 0x3F, 0xF7, 0xCC, 0x34, 0xA5, 0xE5, 0xF1, 0x71, 0xD8, 0x31, 0x15,
0x04, 0xC7, 0x23, 0xC3, 0x18, 0x96, 0x05, 0x9A, 0x07, 0x12, 0x80, 0xE2,
0xEB, 0x27, 0xB2, 0x75, 0x09, 0x83, 0x2C, 0x1A, 0x1B, 0x6E, 0x5A, 0xA0,
0x52, 0x3B, 0xD6, 0xB3, 0x29, 0xE3, 0x2F, 0x84, 0x53, 0xD1, 0x00, 0xED,
0x20, 0xFC, 0xB1, 0x5B, 0x6A, 0xCB, 0xBE, 0x39, 0x4A, 0x4C, 0x58, 0xCF,
0xD0, 0xEF, 0xAA, 0xFB, 0x43, 0x4D, 0x33, 0x85, 0x45, 0xF9, 0x02, 0x7F,
0x50, 0x3C, 0x9F, 0xA8, 0x51, 0xA3, 0x40, 0x8F, 0x92, 0x9D, 0x38, 0xF5,
0xBC, 0xB6, 0xDA, 0x21, 0x10, 0xFF, 0xF3, 0xD2, 0xCD, 0x0C, 0x13, 0xEC,
0x5F, 0x97, 0x44, 0x17, 0xC4, 0xA7, 0x7E, 0x3D, 0x64, 0x5D, 0x19, 0x73,
0x60, 0x81, 0x4F, 0xDC, 0x22, 0x2A, 0x90, 0x88, 0x46, 0xEE, 0xB8, 0x14,
0xDE, 0x5E, 0x0B, 0xDB, 0xE0, 0x32, 0x3A, 0x0A, 0x49, 0x06, 0x24, 0x5C,
0xC2, 0xD3, 0xAC, 0x62, 0x91, 0x95, 0xE4, 0x79, 0xE7, 0xC8, 0x37, 0x6D,
0x8D, 0xD5, 0x4E, 0xA9, 0x6C, 0x56, 0xF4, 0xEA, 0x65, 0x7A, 0xAE, 0x08,
0xBA, 0x78, 0x25, 0x2E, 0x1C, 0xA6, 0xB4, 0xC6, 0xE8, 0xDD, 0x74, 0x1F,
0x4B, 0xBD, 0x8B, 0x8A, 0x70, 0x3E, 0xB5, 0x66, 0x48, 0x03, 0xF6, 0x0E,
0x61, 0x35, 0x57, 0xB9, 0x86, 0xC1, 0x1D, 0x9E, 0xE1, 0xF8, 0x98, 0x11,
0x69, 0xD9, 0x8E, 0x94, 0x9B, 0x1E, 0x87, 0xE9, 0xCE, 0x55, 0x28, 0xDF,
0x8C, 0xA1, 0x89, 0x0D, 0xBF, 0xE6, 0x42, 0x68, 0x41, 0x99, 0x2D, 0x0F,
0xB0, 0x54, 0xBB, 0x16
};
static const uint8_t aria_sb2[256] =
{
0xE2, 0x4E, 0x54, 0xFC, 0x94, 0xC2, 0x4A, 0xCC, 0x62, 0x0D, 0x6A, 0x46,
0x3C, 0x4D, 0x8B, 0xD1, 0x5E, 0xFA, 0x64, 0xCB, 0xB4, 0x97, 0xBE, 0x2B,
0xBC, 0x77, 0x2E, 0x03, 0xD3, 0x19, 0x59, 0xC1, 0x1D, 0x06, 0x41, 0x6B,
0x55, 0xF0, 0x99, 0x69, 0xEA, 0x9C, 0x18, 0xAE, 0x63, 0xDF, 0xE7, 0xBB,
0x00, 0x73, 0x66, 0xFB, 0x96, 0x4C, 0x85, 0xE4, 0x3A, 0x09, 0x45, 0xAA,
0x0F, 0xEE, 0x10, 0xEB, 0x2D, 0x7F, 0xF4, 0x29, 0xAC, 0xCF, 0xAD, 0x91,
0x8D, 0x78, 0xC8, 0x95, 0xF9, 0x2F, 0xCE, 0xCD, 0x08, 0x7A, 0x88, 0x38,
0x5C, 0x83, 0x2A, 0x28, 0x47, 0xDB, 0xB8, 0xC7, 0x93, 0xA4, 0x12, 0x53,
0xFF, 0x87, 0x0E, 0x31, 0x36, 0x21, 0x58, 0x48, 0x01, 0x8E, 0x37, 0x74,
0x32, 0xCA, 0xE9, 0xB1, 0xB7, 0xAB, 0x0C, 0xD7, 0xC4, 0x56, 0x42, 0x26,
0x07, 0x98, 0x60, 0xD9, 0xB6, 0xB9, 0x11, 0x40, 0xEC, 0x20, 0x8C, 0xBD,
0xA0, 0xC9, 0x84, 0x04, 0x49, 0x23, 0xF1, 0x4F, 0x50, 0x1F, 0x13, 0xDC,
0xD8, 0xC0, 0x9E, 0x57, 0xE3, 0xC3, 0x7B, 0x65, 0x3B, 0x02, 0x8F, 0x3E,
0xE8, 0x25, 0x92, 0xE5, 0x15, 0xDD, 0xFD, 0x17, 0xA9, 0xBF, 0xD4, 0x9A,
0x7E, 0xC5, 0x39, 0x67, 0xFE, 0x76, 0x9D, 0x43, 0xA7, 0xE1, 0xD0, 0xF5,
0x68, 0xF2, 0x1B, 0x34, 0x70, 0x05, 0xA3, 0x8A, 0xD5, 0x79, 0x86, 0xA8,
0x30, 0xC6, 0x51, 0x4B, 0x1E, 0xA6, 0x27, 0xF6, 0x35, 0xD2, 0x6E, 0x24,
0x16, 0x82, 0x5F, 0xDA, 0xE6, 0x75, 0xA2, 0xEF, 0x2C, 0xB2, 0x1C, 0x9F,
0x5D, 0x6F, 0x80, 0x0A, 0x72, 0x44, 0x9B, 0x6C, 0x90, 0x0B, 0x5B, 0x33,
0x7D, 0x5A, 0x52, 0xF3, 0x61, 0xA1, 0xF7, 0xB0, 0xD6, 0x3F, 0x7C, 0x6D,
0xED, 0x14, 0xE0, 0xA5, 0x3D, 0x22, 0xB3, 0xF8, 0x89, 0xDE, 0x71, 0x1A,
0xAF, 0xBA, 0xB5, 0x81
};
static const uint8_t aria_is1[256] =
{
0x52, 0x09, 0x6A, 0xD5, 0x30, 0x36, 0xA5, 0x38, 0xBF, 0x40, 0xA3, 0x9E,
0x81, 0xF3, 0xD7, 0xFB, 0x7C, 0xE3, 0x39, 0x82, 0x9B, 0x2F, 0xFF, 0x87,
0x34, 0x8E, 0x43, 0x44, 0xC4, 0xDE, 0xE9, 0xCB, 0x54, 0x7B, 0x94, 0x32,
0xA6, 0xC2, 0x23, 0x3D, 0xEE, 0x4C, 0x95, 0x0B, 0x42, 0xFA, 0xC3, 0x4E,
0x08, 0x2E, 0xA1, 0x66, 0x28, 0xD9, 0x24, 0xB2, 0x76, 0x5B, 0xA2, 0x49,
0x6D, 0x8B, 0xD1, 0x25, 0x72, 0xF8, 0xF6, 0x64, 0x86, 0x68, 0x98, 0x16,
0xD4, 0xA4, 0x5C, 0xCC, 0x5D, 0x65, 0xB6, 0x92, 0x6C, 0x70, 0x48, 0x50,
0xFD, 0xED, 0xB9, 0xDA, 0x5E, 0x15, 0x46, 0x57, 0xA7, 0x8D, 0x9D, 0x84,
0x90, 0xD8, 0xAB, 0x00, 0x8C, 0xBC, 0xD3, 0x0A, 0xF7, 0xE4, 0x58, 0x05,
0xB8, 0xB3, 0x45, 0x06, 0xD0, 0x2C, 0x1E, 0x8F, 0xCA, 0x3F, 0x0F, 0x02,
0xC1, 0xAF, 0xBD, 0x03, 0x01, 0x13, 0x8A, 0x6B, 0x3A, 0x91, 0x11, 0x41,
0x4F, 0x67, 0xDC, 0xEA, 0x97, 0xF2, 0xCF, 0xCE, 0xF0, 0xB4, 0xE6, 0x73,
0x96, 0xAC, 0x74, 0x22, 0xE7, 0xAD, 0x35, 0x85, 0xE2, 0xF9, 0x37, 0xE8,
0x1C, 0x75, 0xDF, 0x6E, 0x47, 0xF1, 0x1A, 0x71, 0x1D, 0x29, 0xC5, 0x89,
0x6F, 0xB7, 0x62, 0x0E, 0xAA, 0x18, 0xBE, 0x1B, 0xFC, 0x56, 0x3E, 0x4B,
0xC6, 0xD2, 0x79, 0x20, 0x9A, 0xDB, 0xC0, 0xFE, 0x78, 0xCD, 0x5A, 0xF4,
0x1F, 0xDD, 0xA8, 0x33, 0x88, 0x07, 0xC7, 0x31, 0xB1, 0x12, 0x10, 0x59,
0x27, 0x80, 0xEC, 0x5F, 0x60, 0x51, 0x7F, 0xA9, 0x19, 0xB5, 0x4A, 0x0D,
0x2D, 0xE5, 0x7A, 0x9F, 0x93, 0xC9, 0x9C, 0xEF, 0xA0, 0xE0, 0x3B, 0x4D,
0xAE, 0x2A, 0xF5, 0xB0, 0xC8, 0xEB, 0xBB, 0x3C, 0x83, 0x53, 0x99, 0x61,
0x17, 0x2B, 0x04, 0x7E, 0xBA, 0x77, 0xD6, 0x26, 0xE1, 0x69, 0x14, 0x63,
0x55, 0x21, 0x0C, 0x7D
};
static const uint8_t aria_is2[256] =
{
0x30, 0x68, 0x99, 0x1B, 0x87, 0xB9, 0x21, 0x78, 0x50, 0x39, 0xDB, 0xE1,
0x72, 0x09, 0x62, 0x3C, 0x3E, 0x7E, 0x5E, 0x8E, 0xF1, 0xA0, 0xCC, 0xA3,
0x2A, 0x1D, 0xFB, 0xB6, 0xD6, 0x20, 0xC4, 0x8D, 0x81, 0x65, 0xF5, 0x89,
0xCB, 0x9D, 0x77, 0xC6, 0x57, 0x43, 0x56, 0x17, 0xD4, 0x40, 0x1A, 0x4D,
0xC0, 0x63, 0x6C, 0xE3, 0xB7, 0xC8, 0x64, 0x6A, 0x53, 0xAA, 0x38, 0x98,
0x0C, 0xF4, 0x9B, 0xED, 0x7F, 0x22, 0x76, 0xAF, 0xDD, 0x3A, 0x0B, 0x58,
0x67, 0x88, 0x06, 0xC3, 0x35, 0x0D, 0x01, 0x8B, 0x8C, 0xC2, 0xE6, 0x5F,
0x02, 0x24, 0x75, 0x93, 0x66, 0x1E, 0xE5, 0xE2, 0x54, 0xD8, 0x10, 0xCE,
0x7A, 0xE8, 0x08, 0x2C, 0x12, 0x97, 0x32, 0xAB, 0xB4, 0x27, 0x0A, 0x23,
0xDF, 0xEF, 0xCA, 0xD9, 0xB8, 0xFA, 0xDC, 0x31, 0x6B, 0xD1, 0xAD, 0x19,
0x49, 0xBD, 0x51, 0x96, 0xEE, 0xE4, 0xA8, 0x41, 0xDA, 0xFF, 0xCD, 0x55,
0x86, 0x36, 0xBE, 0x61, 0x52, 0xF8, 0xBB, 0x0E, 0x82, 0x48, 0x69, 0x9A,
0xE0, 0x47, 0x9E, 0x5C, 0x04, 0x4B, 0x34, 0x15, 0x79, 0x26, 0xA7, 0xDE,
0x29, 0xAE, 0x92, 0xD7, 0x84, 0xE9, 0xD2, 0xBA, 0x5D, 0xF3, 0xC5, 0xB0,
0xBF, 0xA4, 0x3B, 0x71, 0x44, 0x46, 0x2B, 0xFC, 0xEB, 0x6F, 0xD5, 0xF6,
0x14, 0xFE, 0x7C, 0x70, 0x5A, 0x7D, 0xFD, 0x2F, 0x18, 0x83, 0x16, 0xA5,
0x91, 0x1F, 0x05, 0x95, 0x74, 0xA9, 0xC1, 0x5B, 0x4A, 0x85, 0x6D, 0x13,
0x07, 0x4F, 0x4E, 0x45, 0xB2, 0x0F, 0xC9, 0x1C, 0xA6, 0xBC, 0xEC, 0x73,
0x90, 0x7B, 0xCF, 0x59, 0x8F, 0xA1, 0xF9, 0x2D, 0xF2, 0xB1, 0x00, 0x94,
0x37, 0x9F, 0xD0, 0x2E, 0x9C, 0x6E, 0x28, 0x3F, 0x80, 0xF0, 0x3D, 0xD3,
0x25, 0x8A, 0xB5, 0xE7, 0x42, 0xB3, 0xC7, 0xEA, 0xF7, 0x4C, 0x11, 0x33,
0x03, 0xA2, 0xAC, 0x60
};
/*
* Helper for key schedule: r = FO( p, k ) ^ x
*/
static void aria_fo_xor( uint32_t r[4], const uint32_t p[4],
const uint32_t k[4], const uint32_t x[4] )
{
uint32_t a, b, c, d;
a = p[0] ^ k[0];
b = p[1] ^ k[1];
c = p[2] ^ k[2];
d = p[3] ^ k[3];
aria_sl( &a, &b, &c, &d, aria_sb1, aria_sb2, aria_is1, aria_is2 );
aria_a( &a, &b, &c, &d );
r[0] = a ^ x[0];
r[1] = b ^ x[1];
r[2] = c ^ x[2];
r[3] = d ^ x[3];
}
/*
* Helper for key schedule: r = FE( p, k ) ^ x
*/
static void aria_fe_xor( uint32_t r[4], const uint32_t p[4],
const uint32_t k[4], const uint32_t x[4] )
{
uint32_t a, b, c, d;
a = p[0] ^ k[0];
b = p[1] ^ k[1];
c = p[2] ^ k[2];
d = p[3] ^ k[3];
aria_sl( &a, &b, &c, &d, aria_is1, aria_is2, aria_sb1, aria_sb2 );
aria_a( &a, &b, &c, &d );
r[0] = a ^ x[0];
r[1] = b ^ x[1];
r[2] = c ^ x[2];
r[3] = d ^ x[3];
}
/*
* Big endian 128-bit rotation: r = a ^ (b <<< n), used only in key setup.
*
* We chose to store bytes into 32-bit words in little-endian format (see
* GET/PUT_UINT32_LE) so we need to reverse bytes here.
*/
static void aria_rot128( uint32_t r[4], const uint32_t a[4],
const uint32_t b[4], uint8_t n )
{
uint8_t i, j;
uint32_t t, u;
const uint8_t n1 = n % 32; // bit offset
const uint8_t n2 = n1 ? 32 - n1 : 0; // reverse bit offset
j = ( n / 32 ) % 4; // initial word offset
t = ARIA_P3( b[j] ); // big endian
for( i = 0; i < 4; i++ )
{
j = ( j + 1 ) % 4; // get next word, big endian
u = ARIA_P3( b[j] );
t <<= n1; // rotate
t |= u >> n2;
t = ARIA_P3( t ); // back to little endian
r[i] = a[i] ^ t; // store
t = u; // move to next word
}
}
/*
* Set encryption key
*/
int mbedtls_aria_setkey_enc( mbedtls_aria_context *ctx,
const unsigned char *key, unsigned int keybits )
{
/* round constant masks */
const uint32_t rc[3][4] =
{
{ 0xB7C17C51, 0x940A2227, 0xE8AB13FE, 0xE06E9AFA },
{ 0xCC4AB16D, 0x20C8219E, 0xD5B128FF, 0xB0E25DEF },
{ 0x1D3792DB, 0x70E92621, 0x75972403, 0x0EC9E804 }
};
int i;
uint32_t w[4][4], *w2;
ARIA_VALIDATE_RET( ctx != NULL );
ARIA_VALIDATE_RET( key != NULL );
if( keybits != 128 && keybits != 192 && keybits != 256 )
return( MBEDTLS_ERR_ARIA_BAD_INPUT_DATA );
/* Copy key to W0 (and potential remainder to W1) */
GET_UINT32_LE( w[0][0], key, 0 );
GET_UINT32_LE( w[0][1], key, 4 );
GET_UINT32_LE( w[0][2], key, 8 );
GET_UINT32_LE( w[0][3], key, 12 );
memset( w[1], 0, 16 );
if( keybits >= 192 )
{
GET_UINT32_LE( w[1][0], key, 16 ); // 192 bit key
GET_UINT32_LE( w[1][1], key, 20 );
}
if( keybits == 256 )
{
GET_UINT32_LE( w[1][2], key, 24 ); // 256 bit key
GET_UINT32_LE( w[1][3], key, 28 );
}
i = ( keybits - 128 ) >> 6; // index: 0, 1, 2
ctx->nr = 12 + 2 * i; // no. rounds: 12, 14, 16
aria_fo_xor( w[1], w[0], rc[i], w[1] ); // W1 = FO(W0, CK1) ^ KR
i = i < 2 ? i + 1 : 0;
aria_fe_xor( w[2], w[1], rc[i], w[0] ); // W2 = FE(W1, CK2) ^ W0
i = i < 2 ? i + 1 : 0;
aria_fo_xor( w[3], w[2], rc[i], w[1] ); // W3 = FO(W2, CK3) ^ W1
for( i = 0; i < 4; i++ ) // create round keys
{
w2 = w[(i + 1) & 3];
aria_rot128( ctx->rk[i ], w[i], w2, 128 - 19 );
aria_rot128( ctx->rk[i + 4], w[i], w2, 128 - 31 );
aria_rot128( ctx->rk[i + 8], w[i], w2, 61 );
aria_rot128( ctx->rk[i + 12], w[i], w2, 31 );
}
aria_rot128( ctx->rk[16], w[0], w[1], 19 );
/* w holds enough info to reconstruct the round keys */
mbedtls_platform_zeroize( w, sizeof( w ) );
return( 0 );
}
/*
* Set decryption key
*/
int mbedtls_aria_setkey_dec( mbedtls_aria_context *ctx,
const unsigned char *key, unsigned int keybits )
{
int i, j, k, ret;
ARIA_VALIDATE_RET( ctx != NULL );
ARIA_VALIDATE_RET( key != NULL );
ret = mbedtls_aria_setkey_enc( ctx, key, keybits );
if( ret != 0 )
return( ret );
/* flip the order of round keys */
for( i = 0, j = ctx->nr; i < j; i++, j-- )
{
for( k = 0; k < 4; k++ )
{
uint32_t t = ctx->rk[i][k];
ctx->rk[i][k] = ctx->rk[j][k];
ctx->rk[j][k] = t;
}
}
/* apply affine transform to middle keys */
for( i = 1; i < ctx->nr; i++ )
{
aria_a( &ctx->rk[i][0], &ctx->rk[i][1],
&ctx->rk[i][2], &ctx->rk[i][3] );
}
return( 0 );
}
/*
* Encrypt a block
*/
int mbedtls_aria_crypt_ecb( mbedtls_aria_context *ctx,
const unsigned char input[MBEDTLS_ARIA_BLOCKSIZE],
unsigned char output[MBEDTLS_ARIA_BLOCKSIZE] )
{
int i;
uint32_t a, b, c, d;
ARIA_VALIDATE_RET( ctx != NULL );
ARIA_VALIDATE_RET( input != NULL );
ARIA_VALIDATE_RET( output != NULL );
GET_UINT32_LE( a, input, 0 );
GET_UINT32_LE( b, input, 4 );
GET_UINT32_LE( c, input, 8 );
GET_UINT32_LE( d, input, 12 );
i = 0;
while( 1 )
{
a ^= ctx->rk[i][0];
b ^= ctx->rk[i][1];
c ^= ctx->rk[i][2];
d ^= ctx->rk[i][3];
i++;
aria_sl( &a, &b, &c, &d, aria_sb1, aria_sb2, aria_is1, aria_is2 );
aria_a( &a, &b, &c, &d );
a ^= ctx->rk[i][0];
b ^= ctx->rk[i][1];
c ^= ctx->rk[i][2];
d ^= ctx->rk[i][3];
i++;
aria_sl( &a, &b, &c, &d, aria_is1, aria_is2, aria_sb1, aria_sb2 );
if( i >= ctx->nr )
break;
aria_a( &a, &b, &c, &d );
}
/* final key mixing */
a ^= ctx->rk[i][0];
b ^= ctx->rk[i][1];
c ^= ctx->rk[i][2];
d ^= ctx->rk[i][3];
PUT_UINT32_LE( a, output, 0 );
PUT_UINT32_LE( b, output, 4 );
PUT_UINT32_LE( c, output, 8 );
PUT_UINT32_LE( d, output, 12 );
return( 0 );
}
/* Initialize context */
void mbedtls_aria_init( mbedtls_aria_context *ctx )
{
ARIA_VALIDATE( ctx != NULL );
memset( ctx, 0, sizeof( mbedtls_aria_context ) );
}
/* Clear context */
void mbedtls_aria_free( mbedtls_aria_context *ctx )
{
if( ctx == NULL )
return;
mbedtls_platform_zeroize( ctx, sizeof( mbedtls_aria_context ) );
}
#if defined(MBEDTLS_CIPHER_MODE_CBC)
/*
* ARIA-CBC buffer encryption/decryption
*/
int mbedtls_aria_crypt_cbc( mbedtls_aria_context *ctx,
int mode,
size_t length,
unsigned char iv[MBEDTLS_ARIA_BLOCKSIZE],
const unsigned char *input,
unsigned char *output )
{
int i;
unsigned char temp[MBEDTLS_ARIA_BLOCKSIZE];
ARIA_VALIDATE_RET( ctx != NULL );
ARIA_VALIDATE_RET( mode == MBEDTLS_ARIA_ENCRYPT ||
mode == MBEDTLS_ARIA_DECRYPT );
ARIA_VALIDATE_RET( length == 0 || input != NULL );
ARIA_VALIDATE_RET( length == 0 || output != NULL );
ARIA_VALIDATE_RET( iv != NULL );
if( length % MBEDTLS_ARIA_BLOCKSIZE )
return( MBEDTLS_ERR_ARIA_INVALID_INPUT_LENGTH );
if( mode == MBEDTLS_ARIA_DECRYPT )
{
while( length > 0 )
{
memcpy( temp, input, MBEDTLS_ARIA_BLOCKSIZE );
mbedtls_aria_crypt_ecb( ctx, input, output );
for( i = 0; i < MBEDTLS_ARIA_BLOCKSIZE; i++ )
output[i] = (unsigned char)( output[i] ^ iv[i] );
memcpy( iv, temp, MBEDTLS_ARIA_BLOCKSIZE );
input += MBEDTLS_ARIA_BLOCKSIZE;
output += MBEDTLS_ARIA_BLOCKSIZE;
length -= MBEDTLS_ARIA_BLOCKSIZE;
}
}
else
{
while( length > 0 )
{
for( i = 0; i < MBEDTLS_ARIA_BLOCKSIZE; i++ )
output[i] = (unsigned char)( input[i] ^ iv[i] );
mbedtls_aria_crypt_ecb( ctx, output, output );
memcpy( iv, output, MBEDTLS_ARIA_BLOCKSIZE );
input += MBEDTLS_ARIA_BLOCKSIZE;
output += MBEDTLS_ARIA_BLOCKSIZE;
length -= MBEDTLS_ARIA_BLOCKSIZE;
}
}
return( 0 );
}
#endif /* MBEDTLS_CIPHER_MODE_CBC */
#if defined(MBEDTLS_CIPHER_MODE_CFB)
/*
* ARIA-CFB128 buffer encryption/decryption
*/
int mbedtls_aria_crypt_cfb128( mbedtls_aria_context *ctx,
int mode,
size_t length,
size_t *iv_off,
unsigned char iv[MBEDTLS_ARIA_BLOCKSIZE],
const unsigned char *input,
unsigned char *output )
{
unsigned char c;
size_t n;
ARIA_VALIDATE_RET( ctx != NULL );
ARIA_VALIDATE_RET( mode == MBEDTLS_ARIA_ENCRYPT ||
mode == MBEDTLS_ARIA_DECRYPT );
ARIA_VALIDATE_RET( length == 0 || input != NULL );
ARIA_VALIDATE_RET( length == 0 || output != NULL );
ARIA_VALIDATE_RET( iv != NULL );
ARIA_VALIDATE_RET( iv_off != NULL );
n = *iv_off;
/* An overly large value of n can lead to an unlimited
* buffer overflow. Therefore, guard against this
* outside of parameter validation. */
if( n >= MBEDTLS_ARIA_BLOCKSIZE )
return( MBEDTLS_ERR_ARIA_BAD_INPUT_DATA );
if( mode == MBEDTLS_ARIA_DECRYPT )
{
while( length-- )
{
if( n == 0 )
mbedtls_aria_crypt_ecb( ctx, iv, iv );
c = *input++;
*output++ = c ^ iv[n];
iv[n] = c;
n = ( n + 1 ) & 0x0F;
}
}
else
{
while( length-- )
{
if( n == 0 )
mbedtls_aria_crypt_ecb( ctx, iv, iv );
iv[n] = *output++ = (unsigned char)( iv[n] ^ *input++ );
n = ( n + 1 ) & 0x0F;
}
}
*iv_off = n;
return( 0 );
}
#endif /* MBEDTLS_CIPHER_MODE_CFB */
#if defined(MBEDTLS_CIPHER_MODE_CTR)
/*
* ARIA-CTR buffer encryption/decryption
*/
int mbedtls_aria_crypt_ctr( mbedtls_aria_context *ctx,
size_t length,
size_t *nc_off,
unsigned char nonce_counter[MBEDTLS_ARIA_BLOCKSIZE],
unsigned char stream_block[MBEDTLS_ARIA_BLOCKSIZE],
const unsigned char *input,
unsigned char *output )
{
int c, i;
size_t n;
ARIA_VALIDATE_RET( ctx != NULL );
ARIA_VALIDATE_RET( length == 0 || input != NULL );
ARIA_VALIDATE_RET( length == 0 || output != NULL );
ARIA_VALIDATE_RET( nonce_counter != NULL );
ARIA_VALIDATE_RET( stream_block != NULL );
ARIA_VALIDATE_RET( nc_off != NULL );
n = *nc_off;
/* An overly large value of n can lead to an unlimited
* buffer overflow. Therefore, guard against this
* outside of parameter validation. */
if( n >= MBEDTLS_ARIA_BLOCKSIZE )
return( MBEDTLS_ERR_ARIA_BAD_INPUT_DATA );
while( length-- )
{
if( n == 0 ) {
mbedtls_aria_crypt_ecb( ctx, nonce_counter,
stream_block );
for( i = MBEDTLS_ARIA_BLOCKSIZE; i > 0; i-- )
if( ++nonce_counter[i - 1] != 0 )
break;
}
c = *input++;
*output++ = (unsigned char)( c ^ stream_block[n] );
n = ( n + 1 ) & 0x0F;
}
*nc_off = n;
return( 0 );
}
#endif /* MBEDTLS_CIPHER_MODE_CTR */
#endif /* !MBEDTLS_ARIA_ALT */
#if defined(MBEDTLS_SELF_TEST)
/*
* Basic ARIA ECB test vectors from RFC 5794
*/
static const uint8_t aria_test1_ecb_key[32] = // test key
{
0x00, 0x01, 0x02, 0x03, 0x04, 0x05, 0x06, 0x07, // 128 bit
0x08, 0x09, 0x0A, 0x0B, 0x0C, 0x0D, 0x0E, 0x0F,
0x10, 0x11, 0x12, 0x13, 0x14, 0x15, 0x16, 0x17, // 192 bit
0x18, 0x19, 0x1A, 0x1B, 0x1C, 0x1D, 0x1E, 0x1F // 256 bit
};
static const uint8_t aria_test1_ecb_pt[MBEDTLS_ARIA_BLOCKSIZE] = // plaintext
{
0x00, 0x11, 0x22, 0x33, 0x44, 0x55, 0x66, 0x77, // same for all
0x88, 0x99, 0xAA, 0xBB, 0xCC, 0xDD, 0xEE, 0xFF // key sizes
};
static const uint8_t aria_test1_ecb_ct[3][MBEDTLS_ARIA_BLOCKSIZE] = // ciphertext
{
{ 0xD7, 0x18, 0xFB, 0xD6, 0xAB, 0x64, 0x4C, 0x73, // 128 bit
0x9D, 0xA9, 0x5F, 0x3B, 0xE6, 0x45, 0x17, 0x78 },
{ 0x26, 0x44, 0x9C, 0x18, 0x05, 0xDB, 0xE7, 0xAA, // 192 bit
0x25, 0xA4, 0x68, 0xCE, 0x26, 0x3A, 0x9E, 0x79 },
{ 0xF9, 0x2B, 0xD7, 0xC7, 0x9F, 0xB7, 0x2E, 0x2F, // 256 bit
0x2B, 0x8F, 0x80, 0xC1, 0x97, 0x2D, 0x24, 0xFC }
};
/*
* Mode tests from "Test Vectors for ARIA" Version 1.0
* http://210.104.33.10/ARIA/doc/ARIA-testvector-e.pdf
*/
#if (defined(MBEDTLS_CIPHER_MODE_CBC) || defined(MBEDTLS_CIPHER_MODE_CFB) || \
defined(MBEDTLS_CIPHER_MODE_CTR))
static const uint8_t aria_test2_key[32] =
{
0x00, 0x11, 0x22, 0x33, 0x44, 0x55, 0x66, 0x77, // 128 bit
0x88, 0x99, 0xaa, 0xbb, 0xcc, 0xdd, 0xee, 0xff,
0x00, 0x11, 0x22, 0x33, 0x44, 0x55, 0x66, 0x77, // 192 bit
0x88, 0x99, 0xaa, 0xbb, 0xcc, 0xdd, 0xee, 0xff // 256 bit
};
static const uint8_t aria_test2_pt[48] =
{
0x11, 0x11, 0x11, 0x11, 0xaa, 0xaa, 0xaa, 0xaa, // same for all
0x11, 0x11, 0x11, 0x11, 0xbb, 0xbb, 0xbb, 0xbb,
0x11, 0x11, 0x11, 0x11, 0xcc, 0xcc, 0xcc, 0xcc,
0x11, 0x11, 0x11, 0x11, 0xdd, 0xdd, 0xdd, 0xdd,
0x22, 0x22, 0x22, 0x22, 0xaa, 0xaa, 0xaa, 0xaa,
0x22, 0x22, 0x22, 0x22, 0xbb, 0xbb, 0xbb, 0xbb,
};
#endif
#if (defined(MBEDTLS_CIPHER_MODE_CBC) || defined(MBEDTLS_CIPHER_MODE_CFB))
static const uint8_t aria_test2_iv[MBEDTLS_ARIA_BLOCKSIZE] =
{
0x0f, 0x1e, 0x2d, 0x3c, 0x4b, 0x5a, 0x69, 0x78, // same for CBC, CFB
0x87, 0x96, 0xa5, 0xb4, 0xc3, 0xd2, 0xe1, 0xf0 // CTR has zero IV
};
#endif
#if defined(MBEDTLS_CIPHER_MODE_CBC)
static const uint8_t aria_test2_cbc_ct[3][48] = // CBC ciphertext
{
{ 0x49, 0xd6, 0x18, 0x60, 0xb1, 0x49, 0x09, 0x10, // 128-bit key
0x9c, 0xef, 0x0d, 0x22, 0xa9, 0x26, 0x81, 0x34,
0xfa, 0xdf, 0x9f, 0xb2, 0x31, 0x51, 0xe9, 0x64,
0x5f, 0xba, 0x75, 0x01, 0x8b, 0xdb, 0x15, 0x38,
0xb5, 0x33, 0x34, 0x63, 0x4b, 0xbf, 0x7d, 0x4c,
0xd4, 0xb5, 0x37, 0x70, 0x33, 0x06, 0x0c, 0x15 },
{ 0xaf, 0xe6, 0xcf, 0x23, 0x97, 0x4b, 0x53, 0x3c, // 192-bit key
0x67, 0x2a, 0x82, 0x62, 0x64, 0xea, 0x78, 0x5f,
0x4e, 0x4f, 0x7f, 0x78, 0x0d, 0xc7, 0xf3, 0xf1,
0xe0, 0x96, 0x2b, 0x80, 0x90, 0x23, 0x86, 0xd5,
0x14, 0xe9, 0xc3, 0xe7, 0x72, 0x59, 0xde, 0x92,
0xdd, 0x11, 0x02, 0xff, 0xab, 0x08, 0x6c, 0x1e },
{ 0x52, 0x3a, 0x8a, 0x80, 0x6a, 0xe6, 0x21, 0xf1, // 256-bit key
0x55, 0xfd, 0xd2, 0x8d, 0xbc, 0x34, 0xe1, 0xab,
0x7b, 0x9b, 0x42, 0x43, 0x2a, 0xd8, 0xb2, 0xef,
0xb9, 0x6e, 0x23, 0xb1, 0x3f, 0x0a, 0x6e, 0x52,
0xf3, 0x61, 0x85, 0xd5, 0x0a, 0xd0, 0x02, 0xc5,
0xf6, 0x01, 0xbe, 0xe5, 0x49, 0x3f, 0x11, 0x8b }
};
#endif /* MBEDTLS_CIPHER_MODE_CBC */
#if defined(MBEDTLS_CIPHER_MODE_CFB)
static const uint8_t aria_test2_cfb_ct[3][48] = // CFB ciphertext
{
{ 0x37, 0x20, 0xe5, 0x3b, 0xa7, 0xd6, 0x15, 0x38, // 128-bit key
0x34, 0x06, 0xb0, 0x9f, 0x0a, 0x05, 0xa2, 0x00,
0xc0, 0x7c, 0x21, 0xe6, 0x37, 0x0f, 0x41, 0x3a,
0x5d, 0x13, 0x25, 0x00, 0xa6, 0x82, 0x85, 0x01,
0x7c, 0x61, 0xb4, 0x34, 0xc7, 0xb7, 0xca, 0x96,
0x85, 0xa5, 0x10, 0x71, 0x86, 0x1e, 0x4d, 0x4b },
{ 0x41, 0x71, 0xf7, 0x19, 0x2b, 0xf4, 0x49, 0x54, // 192-bit key
0x94, 0xd2, 0x73, 0x61, 0x29, 0x64, 0x0f, 0x5c,
0x4d, 0x87, 0xa9, 0xa2, 0x13, 0x66, 0x4c, 0x94,
0x48, 0x47, 0x7c, 0x6e, 0xcc, 0x20, 0x13, 0x59,
0x8d, 0x97, 0x66, 0x95, 0x2d, 0xd8, 0xc3, 0x86,
0x8f, 0x17, 0xe3, 0x6e, 0xf6, 0x6f, 0xd8, 0x4b },
{ 0x26, 0x83, 0x47, 0x05, 0xb0, 0xf2, 0xc0, 0xe2, // 256-bit key
0x58, 0x8d, 0x4a, 0x7f, 0x09, 0x00, 0x96, 0x35,
0xf2, 0x8b, 0xb9, 0x3d, 0x8c, 0x31, 0xf8, 0x70,
0xec, 0x1e, 0x0b, 0xdb, 0x08, 0x2b, 0x66, 0xfa,
0x40, 0x2d, 0xd9, 0xc2, 0x02, 0xbe, 0x30, 0x0c,
0x45, 0x17, 0xd1, 0x96, 0xb1, 0x4d, 0x4c, 0xe1 }
};
#endif /* MBEDTLS_CIPHER_MODE_CFB */
#if defined(MBEDTLS_CIPHER_MODE_CTR)
static const uint8_t aria_test2_ctr_ct[3][48] = // CTR ciphertext
{
{ 0xac, 0x5d, 0x7d, 0xe8, 0x05, 0xa0, 0xbf, 0x1c, // 128-bit key
0x57, 0xc8, 0x54, 0x50, 0x1a, 0xf6, 0x0f, 0xa1,
0x14, 0x97, 0xe2, 0xa3, 0x45, 0x19, 0xde, 0xa1,
0x56, 0x9e, 0x91, 0xe5, 0xb5, 0xcc, 0xae, 0x2f,
0xf3, 0xbf, 0xa1, 0xbf, 0x97, 0x5f, 0x45, 0x71,
0xf4, 0x8b, 0xe1, 0x91, 0x61, 0x35, 0x46, 0xc3 },
{ 0x08, 0x62, 0x5c, 0xa8, 0xfe, 0x56, 0x9c, 0x19, // 192-bit key
0xba, 0x7a, 0xf3, 0x76, 0x0a, 0x6e, 0xd1, 0xce,
0xf4, 0xd1, 0x99, 0x26, 0x3e, 0x99, 0x9d, 0xde,
0x14, 0x08, 0x2d, 0xbb, 0xa7, 0x56, 0x0b, 0x79,
0xa4, 0xc6, 0xb4, 0x56, 0xb8, 0x70, 0x7d, 0xce,
0x75, 0x1f, 0x98, 0x54, 0xf1, 0x88, 0x93, 0xdf },
{ 0x30, 0x02, 0x6c, 0x32, 0x96, 0x66, 0x14, 0x17, // 256-bit key
0x21, 0x17, 0x8b, 0x99, 0xc0, 0xa1, 0xf1, 0xb2,
0xf0, 0x69, 0x40, 0x25, 0x3f, 0x7b, 0x30, 0x89,
0xe2, 0xa3, 0x0e, 0xa8, 0x6a, 0xa3, 0xc8, 0x8f,
0x59, 0x40, 0xf0, 0x5a, 0xd7, 0xee, 0x41, 0xd7,
0x13, 0x47, 0xbb, 0x72, 0x61, 0xe3, 0x48, 0xf1 }
};
#endif /* MBEDTLS_CIPHER_MODE_CFB */
#define ARIA_SELF_TEST_IF_FAIL \
{ \
if( verbose ) \
mbedtls_printf( "failed\n" ); \
goto exit; \
} else { \
if( verbose ) \
mbedtls_printf( "passed\n" ); \
}
/*
* Checkup routine
*/
int mbedtls_aria_self_test( int verbose )
{
int i;
uint8_t blk[MBEDTLS_ARIA_BLOCKSIZE];
mbedtls_aria_context ctx;
int ret = 1;
#if (defined(MBEDTLS_CIPHER_MODE_CFB) || defined(MBEDTLS_CIPHER_MODE_CTR))
size_t j;
#endif
#if (defined(MBEDTLS_CIPHER_MODE_CBC) || \
defined(MBEDTLS_CIPHER_MODE_CFB) || \
defined(MBEDTLS_CIPHER_MODE_CTR))
uint8_t buf[48], iv[MBEDTLS_ARIA_BLOCKSIZE];
#endif
mbedtls_aria_init( &ctx );
/*
* Test set 1
*/
for( i = 0; i < 3; i++ )
{
/* test ECB encryption */
if( verbose )
mbedtls_printf( " ARIA-ECB-%d (enc): ", 128 + 64 * i );
mbedtls_aria_setkey_enc( &ctx, aria_test1_ecb_key, 128 + 64 * i );
mbedtls_aria_crypt_ecb( &ctx, aria_test1_ecb_pt, blk );
if( memcmp( blk, aria_test1_ecb_ct[i], MBEDTLS_ARIA_BLOCKSIZE ) != 0 )
ARIA_SELF_TEST_IF_FAIL;
/* test ECB decryption */
if( verbose )
mbedtls_printf( " ARIA-ECB-%d (dec): ", 128 + 64 * i );
mbedtls_aria_setkey_dec( &ctx, aria_test1_ecb_key, 128 + 64 * i );
mbedtls_aria_crypt_ecb( &ctx, aria_test1_ecb_ct[i], blk );
if( memcmp( blk, aria_test1_ecb_pt, MBEDTLS_ARIA_BLOCKSIZE ) != 0 )
ARIA_SELF_TEST_IF_FAIL;
}
if( verbose )
mbedtls_printf( "\n" );
/*
* Test set 2
*/
#if defined(MBEDTLS_CIPHER_MODE_CBC)
for( i = 0; i < 3; i++ )
{
/* Test CBC encryption */
if( verbose )
mbedtls_printf( " ARIA-CBC-%d (enc): ", 128 + 64 * i );
mbedtls_aria_setkey_enc( &ctx, aria_test2_key, 128 + 64 * i );
memcpy( iv, aria_test2_iv, MBEDTLS_ARIA_BLOCKSIZE );
memset( buf, 0x55, sizeof( buf ) );
mbedtls_aria_crypt_cbc( &ctx, MBEDTLS_ARIA_ENCRYPT, 48, iv,
aria_test2_pt, buf );
if( memcmp( buf, aria_test2_cbc_ct[i], 48 ) != 0 )
ARIA_SELF_TEST_IF_FAIL;
/* Test CBC decryption */
if( verbose )
mbedtls_printf( " ARIA-CBC-%d (dec): ", 128 + 64 * i );
mbedtls_aria_setkey_dec( &ctx, aria_test2_key, 128 + 64 * i );
memcpy( iv, aria_test2_iv, MBEDTLS_ARIA_BLOCKSIZE );
memset( buf, 0xAA, sizeof( buf ) );
mbedtls_aria_crypt_cbc( &ctx, MBEDTLS_ARIA_DECRYPT, 48, iv,
aria_test2_cbc_ct[i], buf );
if( memcmp( buf, aria_test2_pt, 48 ) != 0 )
ARIA_SELF_TEST_IF_FAIL;
}
if( verbose )
mbedtls_printf( "\n" );
#endif /* MBEDTLS_CIPHER_MODE_CBC */
#if defined(MBEDTLS_CIPHER_MODE_CFB)
for( i = 0; i < 3; i++ )
{
/* Test CFB encryption */
if( verbose )
mbedtls_printf( " ARIA-CFB-%d (enc): ", 128 + 64 * i );
mbedtls_aria_setkey_enc( &ctx, aria_test2_key, 128 + 64 * i );
memcpy( iv, aria_test2_iv, MBEDTLS_ARIA_BLOCKSIZE );
memset( buf, 0x55, sizeof( buf ) );
j = 0;
mbedtls_aria_crypt_cfb128( &ctx, MBEDTLS_ARIA_ENCRYPT, 48, &j, iv,
aria_test2_pt, buf );
if( memcmp( buf, aria_test2_cfb_ct[i], 48 ) != 0 )
ARIA_SELF_TEST_IF_FAIL;
/* Test CFB decryption */
if( verbose )
mbedtls_printf( " ARIA-CFB-%d (dec): ", 128 + 64 * i );
mbedtls_aria_setkey_enc( &ctx, aria_test2_key, 128 + 64 * i );
memcpy( iv, aria_test2_iv, MBEDTLS_ARIA_BLOCKSIZE );
memset( buf, 0xAA, sizeof( buf ) );
j = 0;
mbedtls_aria_crypt_cfb128( &ctx, MBEDTLS_ARIA_DECRYPT, 48, &j,
iv, aria_test2_cfb_ct[i], buf );
if( memcmp( buf, aria_test2_pt, 48 ) != 0 )
ARIA_SELF_TEST_IF_FAIL;
}
if( verbose )
mbedtls_printf( "\n" );
#endif /* MBEDTLS_CIPHER_MODE_CFB */
#if defined(MBEDTLS_CIPHER_MODE_CTR)
for( i = 0; i < 3; i++ )
{
/* Test CTR encryption */
if( verbose )
mbedtls_printf( " ARIA-CTR-%d (enc): ", 128 + 64 * i );
mbedtls_aria_setkey_enc( &ctx, aria_test2_key, 128 + 64 * i );
memset( iv, 0, MBEDTLS_ARIA_BLOCKSIZE ); // IV = 0
memset( buf, 0x55, sizeof( buf ) );
j = 0;
mbedtls_aria_crypt_ctr( &ctx, 48, &j, iv, blk,
aria_test2_pt, buf );
if( memcmp( buf, aria_test2_ctr_ct[i], 48 ) != 0 )
ARIA_SELF_TEST_IF_FAIL;
/* Test CTR decryption */
if( verbose )
mbedtls_printf( " ARIA-CTR-%d (dec): ", 128 + 64 * i );
mbedtls_aria_setkey_enc( &ctx, aria_test2_key, 128 + 64 * i );
memset( iv, 0, MBEDTLS_ARIA_BLOCKSIZE ); // IV = 0
memset( buf, 0xAA, sizeof( buf ) );
j = 0;
mbedtls_aria_crypt_ctr( &ctx, 48, &j, iv, blk,
aria_test2_ctr_ct[i], buf );
if( memcmp( buf, aria_test2_pt, 48 ) != 0 )
ARIA_SELF_TEST_IF_FAIL;
}
if( verbose )
mbedtls_printf( "\n" );
#endif /* MBEDTLS_CIPHER_MODE_CTR */
ret = 0;
exit:
mbedtls_aria_free( &ctx );
return( ret );
}
#endif /* MBEDTLS_SELF_TEST */
#endif /* MBEDTLS_ARIA_C */
|
0 | repos/gpt4all.zig/src/zig-libcurl/zig-mbedtls/mbedtls | repos/gpt4all.zig/src/zig-libcurl/zig-mbedtls/mbedtls/library/threading.c | /*
* Threading abstraction layer
*
* Copyright The Mbed TLS Contributors
* SPDX-License-Identifier: Apache-2.0
*
* 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.
*/
/*
* Ensure gmtime_r is available even with -std=c99; must be defined before
* config.h, which pulls in glibc's features.h. Harmless on other platforms.
*/
#if !defined(_POSIX_C_SOURCE)
#define _POSIX_C_SOURCE 200112L
#endif
#include "common.h"
#if defined(MBEDTLS_THREADING_C)
#include "mbedtls/threading.h"
#if defined(MBEDTLS_HAVE_TIME_DATE) && !defined(MBEDTLS_PLATFORM_GMTIME_R_ALT)
#if !defined(_WIN32) && (defined(unix) || \
defined(__unix) || defined(__unix__) || (defined(__APPLE__) && \
defined(__MACH__)))
#include <unistd.h>
#endif /* !_WIN32 && (unix || __unix || __unix__ ||
* (__APPLE__ && __MACH__)) */
#if !( ( defined(_POSIX_VERSION) && _POSIX_VERSION >= 200809L ) || \
( defined(_POSIX_THREAD_SAFE_FUNCTIONS ) && \
_POSIX_THREAD_SAFE_FUNCTIONS >= 200112L ) )
/*
* This is a convenience shorthand macro to avoid checking the long
* preprocessor conditions above. Ideally, we could expose this macro in
* platform_util.h and simply use it in platform_util.c, threading.c and
* threading.h. However, this macro is not part of the Mbed TLS public API, so
* we keep it private by only defining it in this file
*/
#if ! ( defined(_WIN32) && !defined(EFIX64) && !defined(EFI32) )
#define THREADING_USE_GMTIME
#endif /* ! ( defined(_WIN32) && !defined(EFIX64) && !defined(EFI32) ) */
#endif /* !( ( defined(_POSIX_VERSION) && _POSIX_VERSION >= 200809L ) || \
( defined(_POSIX_THREAD_SAFE_FUNCTIONS ) && \
_POSIX_THREAD_SAFE_FUNCTIONS >= 200112L ) ) */
#endif /* MBEDTLS_HAVE_TIME_DATE && !MBEDTLS_PLATFORM_GMTIME_R_ALT */
#if defined(MBEDTLS_THREADING_PTHREAD)
static void threading_mutex_init_pthread( mbedtls_threading_mutex_t *mutex )
{
if( mutex == NULL )
return;
/* A nonzero value of is_valid indicates a successfully initialized
* mutex. This is a workaround for not being able to return an error
* code for this function. The lock/unlock functions return an error
* if is_valid is nonzero. The Mbed TLS unit test code uses this field
* to distinguish more states of the mutex; see
* tests/src/threading_helpers for details. */
mutex->is_valid = pthread_mutex_init( &mutex->mutex, NULL ) == 0;
}
static void threading_mutex_free_pthread( mbedtls_threading_mutex_t *mutex )
{
if( mutex == NULL || !mutex->is_valid )
return;
(void) pthread_mutex_destroy( &mutex->mutex );
mutex->is_valid = 0;
}
static int threading_mutex_lock_pthread( mbedtls_threading_mutex_t *mutex )
{
if( mutex == NULL || ! mutex->is_valid )
return( MBEDTLS_ERR_THREADING_BAD_INPUT_DATA );
if( pthread_mutex_lock( &mutex->mutex ) != 0 )
return( MBEDTLS_ERR_THREADING_MUTEX_ERROR );
return( 0 );
}
static int threading_mutex_unlock_pthread( mbedtls_threading_mutex_t *mutex )
{
if( mutex == NULL || ! mutex->is_valid )
return( MBEDTLS_ERR_THREADING_BAD_INPUT_DATA );
if( pthread_mutex_unlock( &mutex->mutex ) != 0 )
return( MBEDTLS_ERR_THREADING_MUTEX_ERROR );
return( 0 );
}
void (*mbedtls_mutex_init)( mbedtls_threading_mutex_t * ) = threading_mutex_init_pthread;
void (*mbedtls_mutex_free)( mbedtls_threading_mutex_t * ) = threading_mutex_free_pthread;
int (*mbedtls_mutex_lock)( mbedtls_threading_mutex_t * ) = threading_mutex_lock_pthread;
int (*mbedtls_mutex_unlock)( mbedtls_threading_mutex_t * ) = threading_mutex_unlock_pthread;
/*
* With phtreads we can statically initialize mutexes
*/
#define MUTEX_INIT = { PTHREAD_MUTEX_INITIALIZER, 1 }
#endif /* MBEDTLS_THREADING_PTHREAD */
#if defined(MBEDTLS_THREADING_ALT)
static int threading_mutex_fail( mbedtls_threading_mutex_t *mutex )
{
((void) mutex );
return( MBEDTLS_ERR_THREADING_BAD_INPUT_DATA );
}
static void threading_mutex_dummy( mbedtls_threading_mutex_t *mutex )
{
((void) mutex );
return;
}
void (*mbedtls_mutex_init)( mbedtls_threading_mutex_t * ) = threading_mutex_dummy;
void (*mbedtls_mutex_free)( mbedtls_threading_mutex_t * ) = threading_mutex_dummy;
int (*mbedtls_mutex_lock)( mbedtls_threading_mutex_t * ) = threading_mutex_fail;
int (*mbedtls_mutex_unlock)( mbedtls_threading_mutex_t * ) = threading_mutex_fail;
/*
* Set functions pointers and initialize global mutexes
*/
void mbedtls_threading_set_alt( void (*mutex_init)( mbedtls_threading_mutex_t * ),
void (*mutex_free)( mbedtls_threading_mutex_t * ),
int (*mutex_lock)( mbedtls_threading_mutex_t * ),
int (*mutex_unlock)( mbedtls_threading_mutex_t * ) )
{
mbedtls_mutex_init = mutex_init;
mbedtls_mutex_free = mutex_free;
mbedtls_mutex_lock = mutex_lock;
mbedtls_mutex_unlock = mutex_unlock;
#if defined(MBEDTLS_FS_IO)
mbedtls_mutex_init( &mbedtls_threading_readdir_mutex );
#endif
#if defined(THREADING_USE_GMTIME)
mbedtls_mutex_init( &mbedtls_threading_gmtime_mutex );
#endif
}
/*
* Free global mutexes
*/
void mbedtls_threading_free_alt( void )
{
#if defined(MBEDTLS_FS_IO)
mbedtls_mutex_free( &mbedtls_threading_readdir_mutex );
#endif
#if defined(THREADING_USE_GMTIME)
mbedtls_mutex_free( &mbedtls_threading_gmtime_mutex );
#endif
}
#endif /* MBEDTLS_THREADING_ALT */
/*
* Define global mutexes
*/
#ifndef MUTEX_INIT
#define MUTEX_INIT
#endif
#if defined(MBEDTLS_FS_IO)
mbedtls_threading_mutex_t mbedtls_threading_readdir_mutex MUTEX_INIT;
#endif
#if defined(THREADING_USE_GMTIME)
mbedtls_threading_mutex_t mbedtls_threading_gmtime_mutex MUTEX_INIT;
#endif
#endif /* MBEDTLS_THREADING_C */
|
0 | repos/gpt4all.zig/src/zig-libcurl/zig-mbedtls/mbedtls | repos/gpt4all.zig/src/zig-libcurl/zig-mbedtls/mbedtls/library/x509write_crt.c | /*
* X.509 certificate writing
*
* Copyright The Mbed TLS Contributors
* SPDX-License-Identifier: Apache-2.0
*
* 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.
*/
/*
* References:
* - certificates: RFC 5280, updated by RFC 6818
* - CSRs: PKCS#10 v1.7 aka RFC 2986
* - attributes: PKCS#9 v2.0 aka RFC 2985
*/
#include "common.h"
#if defined(MBEDTLS_X509_CRT_WRITE_C)
#include "mbedtls/x509_crt.h"
#include "mbedtls/asn1write.h"
#include "mbedtls/error.h"
#include "mbedtls/oid.h"
#include "mbedtls/platform_util.h"
#include "mbedtls/sha1.h"
#include <string.h>
#if defined(MBEDTLS_PEM_WRITE_C)
#include "mbedtls/pem.h"
#endif /* MBEDTLS_PEM_WRITE_C */
void mbedtls_x509write_crt_init( mbedtls_x509write_cert *ctx )
{
memset( ctx, 0, sizeof( mbedtls_x509write_cert ) );
mbedtls_mpi_init( &ctx->serial );
ctx->version = MBEDTLS_X509_CRT_VERSION_3;
}
void mbedtls_x509write_crt_free( mbedtls_x509write_cert *ctx )
{
mbedtls_mpi_free( &ctx->serial );
mbedtls_asn1_free_named_data_list( &ctx->subject );
mbedtls_asn1_free_named_data_list( &ctx->issuer );
mbedtls_asn1_free_named_data_list( &ctx->extensions );
mbedtls_platform_zeroize( ctx, sizeof( mbedtls_x509write_cert ) );
}
void mbedtls_x509write_crt_set_version( mbedtls_x509write_cert *ctx,
int version )
{
ctx->version = version;
}
void mbedtls_x509write_crt_set_md_alg( mbedtls_x509write_cert *ctx,
mbedtls_md_type_t md_alg )
{
ctx->md_alg = md_alg;
}
void mbedtls_x509write_crt_set_subject_key( mbedtls_x509write_cert *ctx,
mbedtls_pk_context *key )
{
ctx->subject_key = key;
}
void mbedtls_x509write_crt_set_issuer_key( mbedtls_x509write_cert *ctx,
mbedtls_pk_context *key )
{
ctx->issuer_key = key;
}
int mbedtls_x509write_crt_set_subject_name( mbedtls_x509write_cert *ctx,
const char *subject_name )
{
return mbedtls_x509_string_to_names( &ctx->subject, subject_name );
}
int mbedtls_x509write_crt_set_issuer_name( mbedtls_x509write_cert *ctx,
const char *issuer_name )
{
return mbedtls_x509_string_to_names( &ctx->issuer, issuer_name );
}
int mbedtls_x509write_crt_set_serial( mbedtls_x509write_cert *ctx,
const mbedtls_mpi *serial )
{
int ret = MBEDTLS_ERR_ERROR_CORRUPTION_DETECTED;
if( ( ret = mbedtls_mpi_copy( &ctx->serial, serial ) ) != 0 )
return( ret );
return( 0 );
}
int mbedtls_x509write_crt_set_validity( mbedtls_x509write_cert *ctx,
const char *not_before,
const char *not_after )
{
if( strlen( not_before ) != MBEDTLS_X509_RFC5280_UTC_TIME_LEN - 1 ||
strlen( not_after ) != MBEDTLS_X509_RFC5280_UTC_TIME_LEN - 1 )
{
return( MBEDTLS_ERR_X509_BAD_INPUT_DATA );
}
strncpy( ctx->not_before, not_before, MBEDTLS_X509_RFC5280_UTC_TIME_LEN );
strncpy( ctx->not_after , not_after , MBEDTLS_X509_RFC5280_UTC_TIME_LEN );
ctx->not_before[MBEDTLS_X509_RFC5280_UTC_TIME_LEN - 1] = 'Z';
ctx->not_after[MBEDTLS_X509_RFC5280_UTC_TIME_LEN - 1] = 'Z';
return( 0 );
}
int mbedtls_x509write_crt_set_extension( mbedtls_x509write_cert *ctx,
const char *oid, size_t oid_len,
int critical,
const unsigned char *val, size_t val_len )
{
return( mbedtls_x509_set_extension( &ctx->extensions, oid, oid_len,
critical, val, val_len ) );
}
int mbedtls_x509write_crt_set_basic_constraints( mbedtls_x509write_cert *ctx,
int is_ca, int max_pathlen )
{
int ret = MBEDTLS_ERR_ERROR_CORRUPTION_DETECTED;
unsigned char buf[9];
unsigned char *c = buf + sizeof(buf);
size_t len = 0;
memset( buf, 0, sizeof(buf) );
if( is_ca && max_pathlen > 127 )
return( MBEDTLS_ERR_X509_BAD_INPUT_DATA );
if( is_ca )
{
if( max_pathlen >= 0 )
{
MBEDTLS_ASN1_CHK_ADD( len, mbedtls_asn1_write_int( &c, buf,
max_pathlen ) );
}
MBEDTLS_ASN1_CHK_ADD( len, mbedtls_asn1_write_bool( &c, buf, 1 ) );
}
MBEDTLS_ASN1_CHK_ADD( len, mbedtls_asn1_write_len( &c, buf, len ) );
MBEDTLS_ASN1_CHK_ADD( len, mbedtls_asn1_write_tag( &c, buf,
MBEDTLS_ASN1_CONSTRUCTED |
MBEDTLS_ASN1_SEQUENCE ) );
return(
mbedtls_x509write_crt_set_extension( ctx, MBEDTLS_OID_BASIC_CONSTRAINTS,
MBEDTLS_OID_SIZE( MBEDTLS_OID_BASIC_CONSTRAINTS ),
is_ca, buf + sizeof(buf) - len, len ) );
}
#if defined(MBEDTLS_SHA1_C)
int mbedtls_x509write_crt_set_subject_key_identifier( mbedtls_x509write_cert *ctx )
{
int ret = MBEDTLS_ERR_ERROR_CORRUPTION_DETECTED;
unsigned char buf[MBEDTLS_MPI_MAX_SIZE * 2 + 20]; /* tag, length + 2xMPI */
unsigned char *c = buf + sizeof(buf);
size_t len = 0;
memset( buf, 0, sizeof(buf) );
MBEDTLS_ASN1_CHK_ADD( len,
mbedtls_pk_write_pubkey( &c, buf, ctx->subject_key ) );
ret = mbedtls_sha1_ret( buf + sizeof( buf ) - len, len,
buf + sizeof( buf ) - 20 );
if( ret != 0 )
return( ret );
c = buf + sizeof( buf ) - 20;
len = 20;
MBEDTLS_ASN1_CHK_ADD( len, mbedtls_asn1_write_len( &c, buf, len ) );
MBEDTLS_ASN1_CHK_ADD( len,
mbedtls_asn1_write_tag( &c, buf, MBEDTLS_ASN1_OCTET_STRING ) );
return mbedtls_x509write_crt_set_extension( ctx,
MBEDTLS_OID_SUBJECT_KEY_IDENTIFIER,
MBEDTLS_OID_SIZE( MBEDTLS_OID_SUBJECT_KEY_IDENTIFIER ),
0, buf + sizeof(buf) - len, len );
}
int mbedtls_x509write_crt_set_authority_key_identifier( mbedtls_x509write_cert *ctx )
{
int ret = MBEDTLS_ERR_ERROR_CORRUPTION_DETECTED;
unsigned char buf[MBEDTLS_MPI_MAX_SIZE * 2 + 20]; /* tag, length + 2xMPI */
unsigned char *c = buf + sizeof( buf );
size_t len = 0;
memset( buf, 0, sizeof(buf) );
MBEDTLS_ASN1_CHK_ADD( len,
mbedtls_pk_write_pubkey( &c, buf, ctx->issuer_key ) );
ret = mbedtls_sha1_ret( buf + sizeof( buf ) - len, len,
buf + sizeof( buf ) - 20 );
if( ret != 0 )
return( ret );
c = buf + sizeof( buf ) - 20;
len = 20;
MBEDTLS_ASN1_CHK_ADD( len, mbedtls_asn1_write_len( &c, buf, len ) );
MBEDTLS_ASN1_CHK_ADD( len,
mbedtls_asn1_write_tag( &c, buf, MBEDTLS_ASN1_CONTEXT_SPECIFIC | 0 ) );
MBEDTLS_ASN1_CHK_ADD( len, mbedtls_asn1_write_len( &c, buf, len ) );
MBEDTLS_ASN1_CHK_ADD( len,
mbedtls_asn1_write_tag( &c, buf,
MBEDTLS_ASN1_CONSTRUCTED |
MBEDTLS_ASN1_SEQUENCE ) );
return mbedtls_x509write_crt_set_extension(
ctx, MBEDTLS_OID_AUTHORITY_KEY_IDENTIFIER,
MBEDTLS_OID_SIZE( MBEDTLS_OID_AUTHORITY_KEY_IDENTIFIER ),
0, buf + sizeof( buf ) - len, len );
}
#endif /* MBEDTLS_SHA1_C */
int mbedtls_x509write_crt_set_key_usage( mbedtls_x509write_cert *ctx,
unsigned int key_usage )
{
unsigned char buf[5] = {0}, ku[2] = {0};
unsigned char *c;
int ret = MBEDTLS_ERR_ERROR_CORRUPTION_DETECTED;
const unsigned int allowed_bits = MBEDTLS_X509_KU_DIGITAL_SIGNATURE |
MBEDTLS_X509_KU_NON_REPUDIATION |
MBEDTLS_X509_KU_KEY_ENCIPHERMENT |
MBEDTLS_X509_KU_DATA_ENCIPHERMENT |
MBEDTLS_X509_KU_KEY_AGREEMENT |
MBEDTLS_X509_KU_KEY_CERT_SIGN |
MBEDTLS_X509_KU_CRL_SIGN |
MBEDTLS_X509_KU_ENCIPHER_ONLY |
MBEDTLS_X509_KU_DECIPHER_ONLY;
/* Check that nothing other than the allowed flags is set */
if( ( key_usage & ~allowed_bits ) != 0 )
return( MBEDTLS_ERR_X509_FEATURE_UNAVAILABLE );
c = buf + 5;
ku[0] = (unsigned char)( key_usage );
ku[1] = (unsigned char)( key_usage >> 8 );
ret = mbedtls_asn1_write_named_bitstring( &c, buf, ku, 9 );
if( ret < 0 )
return( ret );
else if( ret < 3 || ret > 5 )
return( MBEDTLS_ERR_X509_INVALID_FORMAT );
ret = mbedtls_x509write_crt_set_extension( ctx, MBEDTLS_OID_KEY_USAGE,
MBEDTLS_OID_SIZE( MBEDTLS_OID_KEY_USAGE ),
1, c, (size_t)ret );
if( ret != 0 )
return( ret );
return( 0 );
}
int mbedtls_x509write_crt_set_ns_cert_type( mbedtls_x509write_cert *ctx,
unsigned char ns_cert_type )
{
unsigned char buf[4] = {0};
unsigned char *c;
int ret = MBEDTLS_ERR_ERROR_CORRUPTION_DETECTED;
c = buf + 4;
ret = mbedtls_asn1_write_named_bitstring( &c, buf, &ns_cert_type, 8 );
if( ret < 3 || ret > 4 )
return( ret );
ret = mbedtls_x509write_crt_set_extension( ctx, MBEDTLS_OID_NS_CERT_TYPE,
MBEDTLS_OID_SIZE( MBEDTLS_OID_NS_CERT_TYPE ),
0, c, (size_t)ret );
if( ret != 0 )
return( ret );
return( 0 );
}
static int x509_write_time( unsigned char **p, unsigned char *start,
const char *t, size_t size )
{
int ret = MBEDTLS_ERR_ERROR_CORRUPTION_DETECTED;
size_t len = 0;
/*
* write MBEDTLS_ASN1_UTC_TIME if year < 2050 (2 bytes shorter)
*/
if( t[0] == '2' && t[1] == '0' && t[2] < '5' )
{
MBEDTLS_ASN1_CHK_ADD( len, mbedtls_asn1_write_raw_buffer( p, start,
(const unsigned char *) t + 2,
size - 2 ) );
MBEDTLS_ASN1_CHK_ADD( len, mbedtls_asn1_write_len( p, start, len ) );
MBEDTLS_ASN1_CHK_ADD( len, mbedtls_asn1_write_tag( p, start,
MBEDTLS_ASN1_UTC_TIME ) );
}
else
{
MBEDTLS_ASN1_CHK_ADD( len, mbedtls_asn1_write_raw_buffer( p, start,
(const unsigned char *) t,
size ) );
MBEDTLS_ASN1_CHK_ADD( len, mbedtls_asn1_write_len( p, start, len ) );
MBEDTLS_ASN1_CHK_ADD( len, mbedtls_asn1_write_tag( p, start,
MBEDTLS_ASN1_GENERALIZED_TIME ) );
}
return( (int) len );
}
int mbedtls_x509write_crt_der( mbedtls_x509write_cert *ctx,
unsigned char *buf, size_t size,
int (*f_rng)(void *, unsigned char *, size_t),
void *p_rng )
{
int ret = MBEDTLS_ERR_ERROR_CORRUPTION_DETECTED;
const char *sig_oid;
size_t sig_oid_len = 0;
unsigned char *c, *c2;
unsigned char hash[64];
unsigned char sig[MBEDTLS_PK_SIGNATURE_MAX_SIZE];
size_t sub_len = 0, pub_len = 0, sig_and_oid_len = 0, sig_len;
size_t len = 0;
mbedtls_pk_type_t pk_alg;
/*
* Prepare data to be signed at the end of the target buffer
*/
c = buf + size;
/* Signature algorithm needed in TBS, and later for actual signature */
/* There's no direct way of extracting a signature algorithm
* (represented as an element of mbedtls_pk_type_t) from a PK instance. */
if( mbedtls_pk_can_do( ctx->issuer_key, MBEDTLS_PK_RSA ) )
pk_alg = MBEDTLS_PK_RSA;
else if( mbedtls_pk_can_do( ctx->issuer_key, MBEDTLS_PK_ECDSA ) )
pk_alg = MBEDTLS_PK_ECDSA;
else
return( MBEDTLS_ERR_X509_INVALID_ALG );
if( ( ret = mbedtls_oid_get_oid_by_sig_alg( pk_alg, ctx->md_alg,
&sig_oid, &sig_oid_len ) ) != 0 )
{
return( ret );
}
/*
* Extensions ::= SEQUENCE SIZE (1..MAX) OF Extension
*/
/* Only for v3 */
if( ctx->version == MBEDTLS_X509_CRT_VERSION_3 )
{
MBEDTLS_ASN1_CHK_ADD( len,
mbedtls_x509_write_extensions( &c,
buf, ctx->extensions ) );
MBEDTLS_ASN1_CHK_ADD( len, mbedtls_asn1_write_len( &c, buf, len ) );
MBEDTLS_ASN1_CHK_ADD( len,
mbedtls_asn1_write_tag( &c, buf,
MBEDTLS_ASN1_CONSTRUCTED |
MBEDTLS_ASN1_SEQUENCE ) );
MBEDTLS_ASN1_CHK_ADD( len, mbedtls_asn1_write_len( &c, buf, len ) );
MBEDTLS_ASN1_CHK_ADD( len,
mbedtls_asn1_write_tag( &c, buf,
MBEDTLS_ASN1_CONTEXT_SPECIFIC |
MBEDTLS_ASN1_CONSTRUCTED | 3 ) );
}
/*
* SubjectPublicKeyInfo
*/
MBEDTLS_ASN1_CHK_ADD( pub_len,
mbedtls_pk_write_pubkey_der( ctx->subject_key,
buf, c - buf ) );
c -= pub_len;
len += pub_len;
/*
* Subject ::= Name
*/
MBEDTLS_ASN1_CHK_ADD( len,
mbedtls_x509_write_names( &c, buf,
ctx->subject ) );
/*
* Validity ::= SEQUENCE {
* notBefore Time,
* notAfter Time }
*/
sub_len = 0;
MBEDTLS_ASN1_CHK_ADD( sub_len,
x509_write_time( &c, buf, ctx->not_after,
MBEDTLS_X509_RFC5280_UTC_TIME_LEN ) );
MBEDTLS_ASN1_CHK_ADD( sub_len,
x509_write_time( &c, buf, ctx->not_before,
MBEDTLS_X509_RFC5280_UTC_TIME_LEN ) );
len += sub_len;
MBEDTLS_ASN1_CHK_ADD( len, mbedtls_asn1_write_len( &c, buf, sub_len ) );
MBEDTLS_ASN1_CHK_ADD( len,
mbedtls_asn1_write_tag( &c, buf,
MBEDTLS_ASN1_CONSTRUCTED |
MBEDTLS_ASN1_SEQUENCE ) );
/*
* Issuer ::= Name
*/
MBEDTLS_ASN1_CHK_ADD( len, mbedtls_x509_write_names( &c, buf,
ctx->issuer ) );
/*
* Signature ::= AlgorithmIdentifier
*/
MBEDTLS_ASN1_CHK_ADD( len,
mbedtls_asn1_write_algorithm_identifier( &c, buf,
sig_oid, strlen( sig_oid ), 0 ) );
/*
* Serial ::= INTEGER
*/
MBEDTLS_ASN1_CHK_ADD( len, mbedtls_asn1_write_mpi( &c, buf,
&ctx->serial ) );
/*
* Version ::= INTEGER { v1(0), v2(1), v3(2) }
*/
/* Can be omitted for v1 */
if( ctx->version != MBEDTLS_X509_CRT_VERSION_1 )
{
sub_len = 0;
MBEDTLS_ASN1_CHK_ADD( sub_len,
mbedtls_asn1_write_int( &c, buf, ctx->version ) );
len += sub_len;
MBEDTLS_ASN1_CHK_ADD( len,
mbedtls_asn1_write_len( &c, buf, sub_len ) );
MBEDTLS_ASN1_CHK_ADD( len,
mbedtls_asn1_write_tag( &c, buf,
MBEDTLS_ASN1_CONTEXT_SPECIFIC |
MBEDTLS_ASN1_CONSTRUCTED | 0 ) );
}
MBEDTLS_ASN1_CHK_ADD( len, mbedtls_asn1_write_len( &c, buf, len ) );
MBEDTLS_ASN1_CHK_ADD( len,
mbedtls_asn1_write_tag( &c, buf, MBEDTLS_ASN1_CONSTRUCTED |
MBEDTLS_ASN1_SEQUENCE ) );
/*
* Make signature
*/
/* Compute hash of CRT. */
if( ( ret = mbedtls_md( mbedtls_md_info_from_type( ctx->md_alg ), c,
len, hash ) ) != 0 )
{
return( ret );
}
if( ( ret = mbedtls_pk_sign( ctx->issuer_key, ctx->md_alg,
hash, 0, sig, &sig_len,
f_rng, p_rng ) ) != 0 )
{
return( ret );
}
/* Move CRT to the front of the buffer to have space
* for the signature. */
memmove( buf, c, len );
c = buf + len;
/* Add signature at the end of the buffer,
* making sure that it doesn't underflow
* into the CRT buffer. */
c2 = buf + size;
MBEDTLS_ASN1_CHK_ADD( sig_and_oid_len, mbedtls_x509_write_sig( &c2, c,
sig_oid, sig_oid_len, sig, sig_len ) );
/*
* Memory layout after this step:
*
* buf c=buf+len c2 buf+size
* [CRT0,...,CRTn, UNUSED, ..., UNUSED, SIG0, ..., SIGm]
*/
/* Move raw CRT to just before the signature. */
c = c2 - len;
memmove( c, buf, len );
len += sig_and_oid_len;
MBEDTLS_ASN1_CHK_ADD( len, mbedtls_asn1_write_len( &c, buf, len ) );
MBEDTLS_ASN1_CHK_ADD( len, mbedtls_asn1_write_tag( &c, buf,
MBEDTLS_ASN1_CONSTRUCTED |
MBEDTLS_ASN1_SEQUENCE ) );
return( (int) len );
}
#define PEM_BEGIN_CRT "-----BEGIN CERTIFICATE-----\n"
#define PEM_END_CRT "-----END CERTIFICATE-----\n"
#if defined(MBEDTLS_PEM_WRITE_C)
int mbedtls_x509write_crt_pem( mbedtls_x509write_cert *crt,
unsigned char *buf, size_t size,
int (*f_rng)(void *, unsigned char *, size_t),
void *p_rng )
{
int ret = MBEDTLS_ERR_ERROR_CORRUPTION_DETECTED;
size_t olen;
if( ( ret = mbedtls_x509write_crt_der( crt, buf, size,
f_rng, p_rng ) ) < 0 )
{
return( ret );
}
if( ( ret = mbedtls_pem_write_buffer( PEM_BEGIN_CRT, PEM_END_CRT,
buf + size - ret, ret,
buf, size, &olen ) ) != 0 )
{
return( ret );
}
return( 0 );
}
#endif /* MBEDTLS_PEM_WRITE_C */
#endif /* MBEDTLS_X509_CRT_WRITE_C */
|
0 | repos/gpt4all.zig/src/zig-libcurl/zig-mbedtls/mbedtls | repos/gpt4all.zig/src/zig-libcurl/zig-mbedtls/mbedtls/library/version.c | /*
* Version information
*
* Copyright The Mbed TLS Contributors
* SPDX-License-Identifier: Apache-2.0
*
* 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.
*/
#include "common.h"
#if defined(MBEDTLS_VERSION_C)
#include "mbedtls/version.h"
#include <string.h>
unsigned int mbedtls_version_get_number( void )
{
return( MBEDTLS_VERSION_NUMBER );
}
void mbedtls_version_get_string( char *string )
{
memcpy( string, MBEDTLS_VERSION_STRING,
sizeof( MBEDTLS_VERSION_STRING ) );
}
void mbedtls_version_get_string_full( char *string )
{
memcpy( string, MBEDTLS_VERSION_STRING_FULL,
sizeof( MBEDTLS_VERSION_STRING_FULL ) );
}
#endif /* MBEDTLS_VERSION_C */
|
0 | repos/gpt4all.zig/src/zig-libcurl/zig-mbedtls/mbedtls | repos/gpt4all.zig/src/zig-libcurl/zig-mbedtls/mbedtls/library/psa_crypto.c | /*
* PSA crypto layer on top of Mbed TLS crypto
*/
/*
* Copyright The Mbed TLS Contributors
* SPDX-License-Identifier: Apache-2.0
*
* 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.
*/
#include "common.h"
#if defined(MBEDTLS_PSA_CRYPTO_C)
#if defined(MBEDTLS_PSA_CRYPTO_CONFIG)
#include "check_crypto_config.h"
#endif
#include "psa/crypto.h"
#include "psa_crypto_cipher.h"
#include "psa_crypto_core.h"
#include "psa_crypto_invasive.h"
#include "psa_crypto_driver_wrappers.h"
#include "psa_crypto_ecp.h"
#include "psa_crypto_hash.h"
#include "psa_crypto_mac.h"
#include "psa_crypto_rsa.h"
#include "psa_crypto_ecp.h"
#if defined(MBEDTLS_PSA_CRYPTO_SE_C)
#include "psa_crypto_se.h"
#endif
#include "psa_crypto_slot_management.h"
/* Include internal declarations that are useful for implementing persistently
* stored keys. */
#include "psa_crypto_storage.h"
#include "psa_crypto_random_impl.h"
#include <assert.h>
#include <stdlib.h>
#include <string.h>
#include "mbedtls/platform.h"
#if !defined(MBEDTLS_PLATFORM_C)
#define mbedtls_calloc calloc
#define mbedtls_free free
#endif
#include "mbedtls/aes.h"
#include "mbedtls/arc4.h"
#include "mbedtls/asn1.h"
#include "mbedtls/asn1write.h"
#include "mbedtls/bignum.h"
#include "mbedtls/blowfish.h"
#include "mbedtls/camellia.h"
#include "mbedtls/chacha20.h"
#include "mbedtls/chachapoly.h"
#include "mbedtls/cipher.h"
#include "mbedtls/ccm.h"
#include "mbedtls/cmac.h"
#include "mbedtls/des.h"
#include "mbedtls/ecdh.h"
#include "mbedtls/ecp.h"
#include "mbedtls/entropy.h"
#include "mbedtls/error.h"
#include "mbedtls/gcm.h"
#include "mbedtls/md2.h"
#include "mbedtls/md4.h"
#include "mbedtls/md5.h"
#include "mbedtls/md.h"
#include "mbedtls/md_internal.h"
#include "mbedtls/pk.h"
#include "mbedtls/pk_internal.h"
#include "mbedtls/platform_util.h"
#include "mbedtls/error.h"
#include "mbedtls/ripemd160.h"
#include "mbedtls/rsa.h"
#include "mbedtls/sha1.h"
#include "mbedtls/sha256.h"
#include "mbedtls/sha512.h"
#include "mbedtls/xtea.h"
#define ARRAY_LENGTH( array ) ( sizeof( array ) / sizeof( *( array ) ) )
/****************************************************************/
/* Global data, support functions and library management */
/****************************************************************/
static int key_type_is_raw_bytes( psa_key_type_t type )
{
return( PSA_KEY_TYPE_IS_UNSTRUCTURED( type ) );
}
/* Values for psa_global_data_t::rng_state */
#define RNG_NOT_INITIALIZED 0
#define RNG_INITIALIZED 1
#define RNG_SEEDED 2
typedef struct
{
mbedtls_psa_random_context_t rng;
unsigned initialized : 1;
unsigned rng_state : 2;
} psa_global_data_t;
static psa_global_data_t global_data;
#if !defined(MBEDTLS_PSA_CRYPTO_EXTERNAL_RNG)
mbedtls_psa_drbg_context_t *const mbedtls_psa_random_state =
&global_data.rng.drbg;
#endif
#define GUARD_MODULE_INITIALIZED \
if( global_data.initialized == 0 ) \
return( PSA_ERROR_BAD_STATE );
psa_status_t mbedtls_to_psa_error( int ret )
{
/* Mbed TLS error codes can combine a high-level error code and a
* low-level error code. The low-level error usually reflects the
* root cause better, so dispatch on that preferably. */
int low_level_ret = - ( -ret & 0x007f );
switch( low_level_ret != 0 ? low_level_ret : ret )
{
case 0:
return( PSA_SUCCESS );
case MBEDTLS_ERR_AES_INVALID_KEY_LENGTH:
case MBEDTLS_ERR_AES_INVALID_INPUT_LENGTH:
case MBEDTLS_ERR_AES_FEATURE_UNAVAILABLE:
return( PSA_ERROR_NOT_SUPPORTED );
case MBEDTLS_ERR_AES_HW_ACCEL_FAILED:
return( PSA_ERROR_HARDWARE_FAILURE );
case MBEDTLS_ERR_ARC4_HW_ACCEL_FAILED:
return( PSA_ERROR_HARDWARE_FAILURE );
case MBEDTLS_ERR_ASN1_OUT_OF_DATA:
case MBEDTLS_ERR_ASN1_UNEXPECTED_TAG:
case MBEDTLS_ERR_ASN1_INVALID_LENGTH:
case MBEDTLS_ERR_ASN1_LENGTH_MISMATCH:
case MBEDTLS_ERR_ASN1_INVALID_DATA:
return( PSA_ERROR_INVALID_ARGUMENT );
case MBEDTLS_ERR_ASN1_ALLOC_FAILED:
return( PSA_ERROR_INSUFFICIENT_MEMORY );
case MBEDTLS_ERR_ASN1_BUF_TOO_SMALL:
return( PSA_ERROR_BUFFER_TOO_SMALL );
#if defined(MBEDTLS_ERR_BLOWFISH_BAD_INPUT_DATA)
case MBEDTLS_ERR_BLOWFISH_BAD_INPUT_DATA:
#elif defined(MBEDTLS_ERR_BLOWFISH_INVALID_KEY_LENGTH)
case MBEDTLS_ERR_BLOWFISH_INVALID_KEY_LENGTH:
#endif
case MBEDTLS_ERR_BLOWFISH_INVALID_INPUT_LENGTH:
return( PSA_ERROR_NOT_SUPPORTED );
case MBEDTLS_ERR_BLOWFISH_HW_ACCEL_FAILED:
return( PSA_ERROR_HARDWARE_FAILURE );
#if defined(MBEDTLS_ERR_CAMELLIA_BAD_INPUT_DATA)
case MBEDTLS_ERR_CAMELLIA_BAD_INPUT_DATA:
#elif defined(MBEDTLS_ERR_CAMELLIA_INVALID_KEY_LENGTH)
case MBEDTLS_ERR_CAMELLIA_INVALID_KEY_LENGTH:
#endif
case MBEDTLS_ERR_CAMELLIA_INVALID_INPUT_LENGTH:
return( PSA_ERROR_NOT_SUPPORTED );
case MBEDTLS_ERR_CAMELLIA_HW_ACCEL_FAILED:
return( PSA_ERROR_HARDWARE_FAILURE );
case MBEDTLS_ERR_CCM_BAD_INPUT:
return( PSA_ERROR_INVALID_ARGUMENT );
case MBEDTLS_ERR_CCM_AUTH_FAILED:
return( PSA_ERROR_INVALID_SIGNATURE );
case MBEDTLS_ERR_CCM_HW_ACCEL_FAILED:
return( PSA_ERROR_HARDWARE_FAILURE );
case MBEDTLS_ERR_CHACHA20_BAD_INPUT_DATA:
return( PSA_ERROR_INVALID_ARGUMENT );
case MBEDTLS_ERR_CHACHAPOLY_BAD_STATE:
return( PSA_ERROR_BAD_STATE );
case MBEDTLS_ERR_CHACHAPOLY_AUTH_FAILED:
return( PSA_ERROR_INVALID_SIGNATURE );
case MBEDTLS_ERR_CIPHER_FEATURE_UNAVAILABLE:
return( PSA_ERROR_NOT_SUPPORTED );
case MBEDTLS_ERR_CIPHER_BAD_INPUT_DATA:
return( PSA_ERROR_INVALID_ARGUMENT );
case MBEDTLS_ERR_CIPHER_ALLOC_FAILED:
return( PSA_ERROR_INSUFFICIENT_MEMORY );
case MBEDTLS_ERR_CIPHER_INVALID_PADDING:
return( PSA_ERROR_INVALID_PADDING );
case MBEDTLS_ERR_CIPHER_FULL_BLOCK_EXPECTED:
return( PSA_ERROR_INVALID_ARGUMENT );
case MBEDTLS_ERR_CIPHER_AUTH_FAILED:
return( PSA_ERROR_INVALID_SIGNATURE );
case MBEDTLS_ERR_CIPHER_INVALID_CONTEXT:
return( PSA_ERROR_CORRUPTION_DETECTED );
case MBEDTLS_ERR_CIPHER_HW_ACCEL_FAILED:
return( PSA_ERROR_HARDWARE_FAILURE );
case MBEDTLS_ERR_CMAC_HW_ACCEL_FAILED:
return( PSA_ERROR_HARDWARE_FAILURE );
#if !( defined(MBEDTLS_PSA_CRYPTO_EXTERNAL_RNG) || \
defined(MBEDTLS_PSA_HMAC_DRBG_MD_TYPE) )
/* Only check CTR_DRBG error codes if underlying mbedtls_xxx
* functions are passed a CTR_DRBG instance. */
case MBEDTLS_ERR_CTR_DRBG_ENTROPY_SOURCE_FAILED:
return( PSA_ERROR_INSUFFICIENT_ENTROPY );
case MBEDTLS_ERR_CTR_DRBG_REQUEST_TOO_BIG:
case MBEDTLS_ERR_CTR_DRBG_INPUT_TOO_BIG:
return( PSA_ERROR_NOT_SUPPORTED );
case MBEDTLS_ERR_CTR_DRBG_FILE_IO_ERROR:
return( PSA_ERROR_INSUFFICIENT_ENTROPY );
#endif
case MBEDTLS_ERR_DES_INVALID_INPUT_LENGTH:
return( PSA_ERROR_NOT_SUPPORTED );
case MBEDTLS_ERR_DES_HW_ACCEL_FAILED:
return( PSA_ERROR_HARDWARE_FAILURE );
case MBEDTLS_ERR_ENTROPY_NO_SOURCES_DEFINED:
case MBEDTLS_ERR_ENTROPY_NO_STRONG_SOURCE:
case MBEDTLS_ERR_ENTROPY_SOURCE_FAILED:
return( PSA_ERROR_INSUFFICIENT_ENTROPY );
case MBEDTLS_ERR_GCM_AUTH_FAILED:
return( PSA_ERROR_INVALID_SIGNATURE );
case MBEDTLS_ERR_GCM_BAD_INPUT:
return( PSA_ERROR_INVALID_ARGUMENT );
case MBEDTLS_ERR_GCM_HW_ACCEL_FAILED:
return( PSA_ERROR_HARDWARE_FAILURE );
#if !defined(MBEDTLS_PSA_CRYPTO_EXTERNAL_RNG) && \
defined(MBEDTLS_PSA_HMAC_DRBG_MD_TYPE)
/* Only check HMAC_DRBG error codes if underlying mbedtls_xxx
* functions are passed a HMAC_DRBG instance. */
case MBEDTLS_ERR_HMAC_DRBG_ENTROPY_SOURCE_FAILED:
return( PSA_ERROR_INSUFFICIENT_ENTROPY );
case MBEDTLS_ERR_HMAC_DRBG_REQUEST_TOO_BIG:
case MBEDTLS_ERR_HMAC_DRBG_INPUT_TOO_BIG:
return( PSA_ERROR_NOT_SUPPORTED );
case MBEDTLS_ERR_HMAC_DRBG_FILE_IO_ERROR:
return( PSA_ERROR_INSUFFICIENT_ENTROPY );
#endif
case MBEDTLS_ERR_MD2_HW_ACCEL_FAILED:
case MBEDTLS_ERR_MD4_HW_ACCEL_FAILED:
case MBEDTLS_ERR_MD5_HW_ACCEL_FAILED:
return( PSA_ERROR_HARDWARE_FAILURE );
case MBEDTLS_ERR_MD_FEATURE_UNAVAILABLE:
return( PSA_ERROR_NOT_SUPPORTED );
case MBEDTLS_ERR_MD_BAD_INPUT_DATA:
return( PSA_ERROR_INVALID_ARGUMENT );
case MBEDTLS_ERR_MD_ALLOC_FAILED:
return( PSA_ERROR_INSUFFICIENT_MEMORY );
case MBEDTLS_ERR_MD_FILE_IO_ERROR:
return( PSA_ERROR_STORAGE_FAILURE );
case MBEDTLS_ERR_MD_HW_ACCEL_FAILED:
return( PSA_ERROR_HARDWARE_FAILURE );
case MBEDTLS_ERR_MPI_FILE_IO_ERROR:
return( PSA_ERROR_STORAGE_FAILURE );
case MBEDTLS_ERR_MPI_BAD_INPUT_DATA:
return( PSA_ERROR_INVALID_ARGUMENT );
case MBEDTLS_ERR_MPI_INVALID_CHARACTER:
return( PSA_ERROR_INVALID_ARGUMENT );
case MBEDTLS_ERR_MPI_BUFFER_TOO_SMALL:
return( PSA_ERROR_BUFFER_TOO_SMALL );
case MBEDTLS_ERR_MPI_NEGATIVE_VALUE:
return( PSA_ERROR_INVALID_ARGUMENT );
case MBEDTLS_ERR_MPI_DIVISION_BY_ZERO:
return( PSA_ERROR_INVALID_ARGUMENT );
case MBEDTLS_ERR_MPI_NOT_ACCEPTABLE:
return( PSA_ERROR_INVALID_ARGUMENT );
case MBEDTLS_ERR_MPI_ALLOC_FAILED:
return( PSA_ERROR_INSUFFICIENT_MEMORY );
case MBEDTLS_ERR_PK_ALLOC_FAILED:
return( PSA_ERROR_INSUFFICIENT_MEMORY );
case MBEDTLS_ERR_PK_TYPE_MISMATCH:
case MBEDTLS_ERR_PK_BAD_INPUT_DATA:
return( PSA_ERROR_INVALID_ARGUMENT );
case MBEDTLS_ERR_PK_FILE_IO_ERROR:
return( PSA_ERROR_STORAGE_FAILURE );
case MBEDTLS_ERR_PK_KEY_INVALID_VERSION:
case MBEDTLS_ERR_PK_KEY_INVALID_FORMAT:
return( PSA_ERROR_INVALID_ARGUMENT );
case MBEDTLS_ERR_PK_UNKNOWN_PK_ALG:
return( PSA_ERROR_NOT_SUPPORTED );
case MBEDTLS_ERR_PK_PASSWORD_REQUIRED:
case MBEDTLS_ERR_PK_PASSWORD_MISMATCH:
return( PSA_ERROR_NOT_PERMITTED );
case MBEDTLS_ERR_PK_INVALID_PUBKEY:
return( PSA_ERROR_INVALID_ARGUMENT );
case MBEDTLS_ERR_PK_INVALID_ALG:
case MBEDTLS_ERR_PK_UNKNOWN_NAMED_CURVE:
case MBEDTLS_ERR_PK_FEATURE_UNAVAILABLE:
return( PSA_ERROR_NOT_SUPPORTED );
case MBEDTLS_ERR_PK_SIG_LEN_MISMATCH:
return( PSA_ERROR_INVALID_SIGNATURE );
case MBEDTLS_ERR_PK_HW_ACCEL_FAILED:
return( PSA_ERROR_HARDWARE_FAILURE );
case MBEDTLS_ERR_PLATFORM_HW_ACCEL_FAILED:
return( PSA_ERROR_HARDWARE_FAILURE );
case MBEDTLS_ERR_PLATFORM_FEATURE_UNSUPPORTED:
return( PSA_ERROR_NOT_SUPPORTED );
case MBEDTLS_ERR_RIPEMD160_HW_ACCEL_FAILED:
return( PSA_ERROR_HARDWARE_FAILURE );
case MBEDTLS_ERR_RSA_BAD_INPUT_DATA:
return( PSA_ERROR_INVALID_ARGUMENT );
case MBEDTLS_ERR_RSA_INVALID_PADDING:
return( PSA_ERROR_INVALID_PADDING );
case MBEDTLS_ERR_RSA_KEY_GEN_FAILED:
return( PSA_ERROR_HARDWARE_FAILURE );
case MBEDTLS_ERR_RSA_KEY_CHECK_FAILED:
return( PSA_ERROR_INVALID_ARGUMENT );
case MBEDTLS_ERR_RSA_PUBLIC_FAILED:
case MBEDTLS_ERR_RSA_PRIVATE_FAILED:
return( PSA_ERROR_CORRUPTION_DETECTED );
case MBEDTLS_ERR_RSA_VERIFY_FAILED:
return( PSA_ERROR_INVALID_SIGNATURE );
case MBEDTLS_ERR_RSA_OUTPUT_TOO_LARGE:
return( PSA_ERROR_BUFFER_TOO_SMALL );
case MBEDTLS_ERR_RSA_RNG_FAILED:
return( PSA_ERROR_INSUFFICIENT_ENTROPY );
case MBEDTLS_ERR_RSA_UNSUPPORTED_OPERATION:
return( PSA_ERROR_NOT_SUPPORTED );
case MBEDTLS_ERR_RSA_HW_ACCEL_FAILED:
return( PSA_ERROR_HARDWARE_FAILURE );
case MBEDTLS_ERR_SHA1_HW_ACCEL_FAILED:
case MBEDTLS_ERR_SHA256_HW_ACCEL_FAILED:
case MBEDTLS_ERR_SHA512_HW_ACCEL_FAILED:
return( PSA_ERROR_HARDWARE_FAILURE );
case MBEDTLS_ERR_XTEA_INVALID_INPUT_LENGTH:
return( PSA_ERROR_INVALID_ARGUMENT );
case MBEDTLS_ERR_XTEA_HW_ACCEL_FAILED:
return( PSA_ERROR_HARDWARE_FAILURE );
case MBEDTLS_ERR_ECP_BAD_INPUT_DATA:
case MBEDTLS_ERR_ECP_INVALID_KEY:
return( PSA_ERROR_INVALID_ARGUMENT );
case MBEDTLS_ERR_ECP_BUFFER_TOO_SMALL:
return( PSA_ERROR_BUFFER_TOO_SMALL );
case MBEDTLS_ERR_ECP_FEATURE_UNAVAILABLE:
return( PSA_ERROR_NOT_SUPPORTED );
case MBEDTLS_ERR_ECP_SIG_LEN_MISMATCH:
case MBEDTLS_ERR_ECP_VERIFY_FAILED:
return( PSA_ERROR_INVALID_SIGNATURE );
case MBEDTLS_ERR_ECP_ALLOC_FAILED:
return( PSA_ERROR_INSUFFICIENT_MEMORY );
case MBEDTLS_ERR_ECP_RANDOM_FAILED:
return( PSA_ERROR_INSUFFICIENT_ENTROPY );
case MBEDTLS_ERR_ECP_HW_ACCEL_FAILED:
return( PSA_ERROR_HARDWARE_FAILURE );
case MBEDTLS_ERR_ERROR_CORRUPTION_DETECTED:
return( PSA_ERROR_CORRUPTION_DETECTED );
default:
return( PSA_ERROR_GENERIC_ERROR );
}
}
/****************************************************************/
/* Key management */
/****************************************************************/
#if defined(MBEDTLS_PSA_CRYPTO_SE_C)
static inline int psa_key_slot_is_external( const psa_key_slot_t *slot )
{
return( psa_key_lifetime_is_external( slot->attr.lifetime ) );
}
#endif /* MBEDTLS_PSA_CRYPTO_SE_C */
/* For now the MBEDTLS_PSA_ACCEL_ guards are also used here since the
* current test driver in key_management.c is using this function
* when accelerators are used for ECC key pair and public key.
* Once that dependency is resolved these guards can be removed.
*/
#if defined(MBEDTLS_PSA_BUILTIN_KEY_TYPE_ECC_KEY_PAIR) || \
defined(MBEDTLS_PSA_BUILTIN_KEY_TYPE_ECC_PUBLIC_KEY) || \
defined(MBEDTLS_PSA_ACCEL_KEY_TYPE_ECC_KEY_PAIR) || \
defined(MBEDTLS_PSA_ACCEL_KEY_TYPE_ECC_PUBLIC_KEY)
mbedtls_ecp_group_id mbedtls_ecc_group_of_psa( psa_ecc_family_t curve,
size_t bits,
int bits_is_sloppy )
{
switch( curve )
{
case PSA_ECC_FAMILY_SECP_R1:
switch( bits )
{
#if defined(PSA_WANT_ECC_SECP_R1_192)
case 192:
return( MBEDTLS_ECP_DP_SECP192R1 );
#endif
#if defined(PSA_WANT_ECC_SECP_R1_224)
case 224:
return( MBEDTLS_ECP_DP_SECP224R1 );
#endif
#if defined(PSA_WANT_ECC_SECP_R1_256)
case 256:
return( MBEDTLS_ECP_DP_SECP256R1 );
#endif
#if defined(PSA_WANT_ECC_SECP_R1_384)
case 384:
return( MBEDTLS_ECP_DP_SECP384R1 );
#endif
#if defined(PSA_WANT_ECC_SECP_R1_521)
case 521:
return( MBEDTLS_ECP_DP_SECP521R1 );
case 528:
if( bits_is_sloppy )
return( MBEDTLS_ECP_DP_SECP521R1 );
break;
#endif
}
break;
case PSA_ECC_FAMILY_BRAINPOOL_P_R1:
switch( bits )
{
#if defined(PSA_WANT_ECC_BRAINPOOL_P_R1_256)
case 256:
return( MBEDTLS_ECP_DP_BP256R1 );
#endif
#if defined(PSA_WANT_ECC_BRAINPOOL_P_R1_384)
case 384:
return( MBEDTLS_ECP_DP_BP384R1 );
#endif
#if defined(PSA_WANT_ECC_BRAINPOOL_P_R1_512)
case 512:
return( MBEDTLS_ECP_DP_BP512R1 );
#endif
}
break;
case PSA_ECC_FAMILY_MONTGOMERY:
switch( bits )
{
#if defined(PSA_WANT_ECC_MONTGOMERY_255)
case 255:
return( MBEDTLS_ECP_DP_CURVE25519 );
case 256:
if( bits_is_sloppy )
return( MBEDTLS_ECP_DP_CURVE25519 );
break;
#endif
#if defined(PSA_WANT_ECC_MONTGOMERY_448)
case 448:
return( MBEDTLS_ECP_DP_CURVE448 );
#endif
}
break;
case PSA_ECC_FAMILY_SECP_K1:
switch( bits )
{
#if defined(PSA_WANT_ECC_SECP_K1_192)
case 192:
return( MBEDTLS_ECP_DP_SECP192K1 );
#endif
#if defined(PSA_WANT_ECC_SECP_K1_224)
case 224:
return( MBEDTLS_ECP_DP_SECP224K1 );
#endif
#if defined(PSA_WANT_ECC_SECP_K1_256)
case 256:
return( MBEDTLS_ECP_DP_SECP256K1 );
#endif
}
break;
}
(void) bits_is_sloppy;
return( MBEDTLS_ECP_DP_NONE );
}
#endif /* defined(MBEDTLS_PSA_BUILTIN_KEY_TYPE_ECC_KEY_PAIR) ||
* defined(MBEDTLS_PSA_BUILTIN_KEY_TYPE_ECC_PUBLIC_KEY) ||
* defined(MBEDTLS_PSA_ACCEL_KEY_TYPE_ECC_KEY_PAIR) ||
* defined(MBEDTLS_PSA_ACCEL_KEY_TYPE_ECC_PUBLIC_KEY) */
static psa_status_t validate_unstructured_key_bit_size( psa_key_type_t type,
size_t bits )
{
/* Check that the bit size is acceptable for the key type */
switch( type )
{
case PSA_KEY_TYPE_RAW_DATA:
case PSA_KEY_TYPE_HMAC:
case PSA_KEY_TYPE_DERIVE:
break;
#if defined(PSA_WANT_KEY_TYPE_AES)
case PSA_KEY_TYPE_AES:
if( bits != 128 && bits != 192 && bits != 256 )
return( PSA_ERROR_INVALID_ARGUMENT );
break;
#endif
#if defined(PSA_WANT_KEY_TYPE_CAMELLIA)
case PSA_KEY_TYPE_CAMELLIA:
if( bits != 128 && bits != 192 && bits != 256 )
return( PSA_ERROR_INVALID_ARGUMENT );
break;
#endif
#if defined(PSA_WANT_KEY_TYPE_DES)
case PSA_KEY_TYPE_DES:
if( bits != 64 && bits != 128 && bits != 192 )
return( PSA_ERROR_INVALID_ARGUMENT );
break;
#endif
#if defined(PSA_WANT_KEY_TYPE_ARC4)
case PSA_KEY_TYPE_ARC4:
if( bits < 8 || bits > 2048 )
return( PSA_ERROR_INVALID_ARGUMENT );
break;
#endif
#if defined(PSA_WANT_KEY_TYPE_CHACHA20)
case PSA_KEY_TYPE_CHACHA20:
if( bits != 256 )
return( PSA_ERROR_INVALID_ARGUMENT );
break;
#endif
default:
return( PSA_ERROR_NOT_SUPPORTED );
}
if( bits % 8 != 0 )
return( PSA_ERROR_INVALID_ARGUMENT );
return( PSA_SUCCESS );
}
/** Check whether a given key type is valid for use with a given MAC algorithm
*
* Upon successful return of this function, the behavior of #PSA_MAC_LENGTH
* when called with the validated \p algorithm and \p key_type is well-defined.
*
* \param[in] algorithm The specific MAC algorithm (can be wildcard).
* \param[in] key_type The key type of the key to be used with the
* \p algorithm.
*
* \retval #PSA_SUCCESS
* The \p key_type is valid for use with the \p algorithm
* \retval #PSA_ERROR_INVALID_ARGUMENT
* The \p key_type is not valid for use with the \p algorithm
*/
MBEDTLS_STATIC_TESTABLE psa_status_t psa_mac_key_can_do(
psa_algorithm_t algorithm,
psa_key_type_t key_type )
{
if( PSA_ALG_IS_HMAC( algorithm ) )
{
if( key_type == PSA_KEY_TYPE_HMAC )
return( PSA_SUCCESS );
}
if( PSA_ALG_IS_BLOCK_CIPHER_MAC( algorithm ) )
{
/* Check that we're calling PSA_BLOCK_CIPHER_BLOCK_LENGTH with a cipher
* key. */
if( ( key_type & PSA_KEY_TYPE_CATEGORY_MASK ) ==
PSA_KEY_TYPE_CATEGORY_SYMMETRIC )
{
/* PSA_BLOCK_CIPHER_BLOCK_LENGTH returns 1 for stream ciphers and
* the block length (larger than 1) for block ciphers. */
if( PSA_BLOCK_CIPHER_BLOCK_LENGTH( key_type ) > 1 )
return( PSA_SUCCESS );
}
}
return( PSA_ERROR_INVALID_ARGUMENT );
}
psa_status_t psa_allocate_buffer_to_slot( psa_key_slot_t *slot,
size_t buffer_length )
{
if( slot->key.data != NULL )
return( PSA_ERROR_ALREADY_EXISTS );
slot->key.data = mbedtls_calloc( 1, buffer_length );
if( slot->key.data == NULL )
return( PSA_ERROR_INSUFFICIENT_MEMORY );
slot->key.bytes = buffer_length;
return( PSA_SUCCESS );
}
psa_status_t psa_copy_key_material_into_slot( psa_key_slot_t *slot,
const uint8_t* data,
size_t data_length )
{
psa_status_t status = psa_allocate_buffer_to_slot( slot,
data_length );
if( status != PSA_SUCCESS )
return( status );
memcpy( slot->key.data, data, data_length );
return( PSA_SUCCESS );
}
psa_status_t psa_import_key_into_slot(
const psa_key_attributes_t *attributes,
const uint8_t *data, size_t data_length,
uint8_t *key_buffer, size_t key_buffer_size,
size_t *key_buffer_length, size_t *bits )
{
psa_status_t status = PSA_ERROR_CORRUPTION_DETECTED;
psa_key_type_t type = attributes->core.type;
/* zero-length keys are never supported. */
if( data_length == 0 )
return( PSA_ERROR_NOT_SUPPORTED );
if( key_type_is_raw_bytes( type ) )
{
*bits = PSA_BYTES_TO_BITS( data_length );
/* Ensure that the bytes-to-bits conversion hasn't overflown. */
if( data_length > SIZE_MAX / 8 )
return( PSA_ERROR_NOT_SUPPORTED );
/* Enforce a size limit, and in particular ensure that the bit
* size fits in its representation type. */
if( ( *bits ) > PSA_MAX_KEY_BITS )
return( PSA_ERROR_NOT_SUPPORTED );
status = validate_unstructured_key_bit_size( type, *bits );
if( status != PSA_SUCCESS )
return( status );
/* Copy the key material. */
memcpy( key_buffer, data, data_length );
*key_buffer_length = data_length;
(void)key_buffer_size;
return( PSA_SUCCESS );
}
else if( PSA_KEY_TYPE_IS_ASYMMETRIC( type ) )
{
#if defined(MBEDTLS_PSA_BUILTIN_KEY_TYPE_ECC_KEY_PAIR) || \
defined(MBEDTLS_PSA_BUILTIN_KEY_TYPE_ECC_PUBLIC_KEY)
if( PSA_KEY_TYPE_IS_ECC( type ) )
{
return( mbedtls_psa_ecp_import_key( attributes,
data, data_length,
key_buffer, key_buffer_size,
key_buffer_length,
bits ) );
}
#endif /* defined(MBEDTLS_PSA_BUILTIN_KEY_TYPE_ECC_KEY_PAIR) ||
* defined(MBEDTLS_PSA_BUILTIN_KEY_TYPE_ECC_PUBLIC_KEY) */
#if defined(MBEDTLS_PSA_BUILTIN_KEY_TYPE_RSA_KEY_PAIR) || \
defined(MBEDTLS_PSA_BUILTIN_KEY_TYPE_RSA_PUBLIC_KEY)
if( PSA_KEY_TYPE_IS_RSA( type ) )
{
return( mbedtls_psa_rsa_import_key( attributes,
data, data_length,
key_buffer, key_buffer_size,
key_buffer_length,
bits ) );
}
#endif /* defined(MBEDTLS_PSA_BUILTIN_KEY_TYPE_RSA_KEY_PAIR) ||
* defined(MBEDTLS_PSA_BUILTIN_KEY_TYPE_RSA_PUBLIC_KEY) */
}
return( PSA_ERROR_NOT_SUPPORTED );
}
/** Calculate the intersection of two algorithm usage policies.
*
* Return 0 (which allows no operation) on incompatibility.
*/
static psa_algorithm_t psa_key_policy_algorithm_intersection(
psa_key_type_t key_type,
psa_algorithm_t alg1,
psa_algorithm_t alg2 )
{
/* Common case: both sides actually specify the same policy. */
if( alg1 == alg2 )
return( alg1 );
/* If the policies are from the same hash-and-sign family, check
* if one is a wildcard. If so the other has the specific algorithm. */
if( PSA_ALG_IS_HASH_AND_SIGN( alg1 ) &&
PSA_ALG_IS_HASH_AND_SIGN( alg2 ) &&
( alg1 & ~PSA_ALG_HASH_MASK ) == ( alg2 & ~PSA_ALG_HASH_MASK ) )
{
if( PSA_ALG_SIGN_GET_HASH( alg1 ) == PSA_ALG_ANY_HASH )
return( alg2 );
if( PSA_ALG_SIGN_GET_HASH( alg2 ) == PSA_ALG_ANY_HASH )
return( alg1 );
}
/* If the policies are from the same AEAD family, check whether
* one of them is a minimum-tag-length wildcard. Calculate the most
* restrictive tag length. */
if( PSA_ALG_IS_AEAD( alg1 ) && PSA_ALG_IS_AEAD( alg2 ) &&
( PSA_ALG_AEAD_WITH_SHORTENED_TAG( alg1, 0 ) ==
PSA_ALG_AEAD_WITH_SHORTENED_TAG( alg2, 0 ) ) )
{
size_t alg1_len = PSA_ALG_AEAD_GET_TAG_LENGTH( alg1 );
size_t alg2_len = PSA_ALG_AEAD_GET_TAG_LENGTH( alg2 );
size_t restricted_len = alg1_len > alg2_len ? alg1_len : alg2_len;
/* If both are wildcards, return most restrictive wildcard */
if( ( ( alg1 & PSA_ALG_AEAD_AT_LEAST_THIS_LENGTH_FLAG ) != 0 ) &&
( ( alg2 & PSA_ALG_AEAD_AT_LEAST_THIS_LENGTH_FLAG ) != 0 ) )
{
return( PSA_ALG_AEAD_WITH_AT_LEAST_THIS_LENGTH_TAG(
alg1, restricted_len ) );
}
/* If only one is a wildcard, return specific algorithm if compatible. */
if( ( ( alg1 & PSA_ALG_AEAD_AT_LEAST_THIS_LENGTH_FLAG ) != 0 ) &&
( alg1_len <= alg2_len ) )
{
return( alg2 );
}
if( ( ( alg2 & PSA_ALG_AEAD_AT_LEAST_THIS_LENGTH_FLAG ) != 0 ) &&
( alg2_len <= alg1_len ) )
{
return( alg1 );
}
}
/* If the policies are from the same MAC family, check whether one
* of them is a minimum-MAC-length policy. Calculate the most
* restrictive tag length. */
if( PSA_ALG_IS_MAC( alg1 ) && PSA_ALG_IS_MAC( alg2 ) &&
( PSA_ALG_FULL_LENGTH_MAC( alg1 ) ==
PSA_ALG_FULL_LENGTH_MAC( alg2 ) ) )
{
/* Validate the combination of key type and algorithm. Since the base
* algorithm of alg1 and alg2 are the same, we only need this once. */
if( PSA_SUCCESS != psa_mac_key_can_do( alg1, key_type ) )
return( 0 );
/* Get the (exact or at-least) output lengths for both sides of the
* requested intersection. None of the currently supported algorithms
* have an output length dependent on the actual key size, so setting it
* to a bogus value of 0 is currently OK.
*
* Note that for at-least-this-length wildcard algorithms, the output
* length is set to the shortest allowed length, which allows us to
* calculate the most restrictive tag length for the intersection. */
size_t alg1_len = PSA_MAC_LENGTH( key_type, 0, alg1 );
size_t alg2_len = PSA_MAC_LENGTH( key_type, 0, alg2 );
size_t restricted_len = alg1_len > alg2_len ? alg1_len : alg2_len;
/* If both are wildcards, return most restrictive wildcard */
if( ( ( alg1 & PSA_ALG_MAC_AT_LEAST_THIS_LENGTH_FLAG ) != 0 ) &&
( ( alg2 & PSA_ALG_MAC_AT_LEAST_THIS_LENGTH_FLAG ) != 0 ) )
{
return( PSA_ALG_AT_LEAST_THIS_LENGTH_MAC( alg1, restricted_len ) );
}
/* If only one is an at-least-this-length policy, the intersection would
* be the other (fixed-length) policy as long as said fixed length is
* equal to or larger than the shortest allowed length. */
if( ( alg1 & PSA_ALG_MAC_AT_LEAST_THIS_LENGTH_FLAG ) != 0 )
{
return( ( alg1_len <= alg2_len ) ? alg2 : 0 );
}
if( ( alg2 & PSA_ALG_MAC_AT_LEAST_THIS_LENGTH_FLAG ) != 0 )
{
return( ( alg2_len <= alg1_len ) ? alg1 : 0 );
}
/* If none of them are wildcards, check whether they define the same tag
* length. This is still possible here when one is default-length and
* the other specific-length. Ensure to always return the
* specific-length version for the intersection. */
if( alg1_len == alg2_len )
return( PSA_ALG_TRUNCATED_MAC( alg1, alg1_len ) );
}
/* If the policies are incompatible, allow nothing. */
return( 0 );
}
static int psa_key_algorithm_permits( psa_key_type_t key_type,
psa_algorithm_t policy_alg,
psa_algorithm_t requested_alg )
{
/* Common case: the policy only allows requested_alg. */
if( requested_alg == policy_alg )
return( 1 );
/* If policy_alg is a hash-and-sign with a wildcard for the hash,
* and requested_alg is the same hash-and-sign family with any hash,
* then requested_alg is compliant with policy_alg. */
if( PSA_ALG_IS_HASH_AND_SIGN( requested_alg ) &&
PSA_ALG_SIGN_GET_HASH( policy_alg ) == PSA_ALG_ANY_HASH )
{
return( ( policy_alg & ~PSA_ALG_HASH_MASK ) ==
( requested_alg & ~PSA_ALG_HASH_MASK ) );
}
/* If policy_alg is a wildcard AEAD algorithm of the same base as
* the requested algorithm, check the requested tag length to be
* equal-length or longer than the wildcard-specified length. */
if( PSA_ALG_IS_AEAD( policy_alg ) &&
PSA_ALG_IS_AEAD( requested_alg ) &&
( PSA_ALG_AEAD_WITH_SHORTENED_TAG( policy_alg, 0 ) ==
PSA_ALG_AEAD_WITH_SHORTENED_TAG( requested_alg, 0 ) ) &&
( ( policy_alg & PSA_ALG_AEAD_AT_LEAST_THIS_LENGTH_FLAG ) != 0 ) )
{
return( PSA_ALG_AEAD_GET_TAG_LENGTH( policy_alg ) <=
PSA_ALG_AEAD_GET_TAG_LENGTH( requested_alg ) );
}
/* If policy_alg is a MAC algorithm of the same base as the requested
* algorithm, check whether their MAC lengths are compatible. */
if( PSA_ALG_IS_MAC( policy_alg ) &&
PSA_ALG_IS_MAC( requested_alg ) &&
( PSA_ALG_FULL_LENGTH_MAC( policy_alg ) ==
PSA_ALG_FULL_LENGTH_MAC( requested_alg ) ) )
{
/* Validate the combination of key type and algorithm. Since the policy
* and requested algorithms are the same, we only need this once. */
if( PSA_SUCCESS != psa_mac_key_can_do( policy_alg, key_type ) )
return( 0 );
/* Get both the requested output length for the algorithm which is to be
* verified, and the default output length for the base algorithm.
* Note that none of the currently supported algorithms have an output
* length dependent on actual key size, so setting it to a bogus value
* of 0 is currently OK. */
size_t requested_output_length = PSA_MAC_LENGTH(
key_type, 0, requested_alg );
size_t default_output_length = PSA_MAC_LENGTH(
key_type, 0,
PSA_ALG_FULL_LENGTH_MAC( requested_alg ) );
/* If the policy is default-length, only allow an algorithm with
* a declared exact-length matching the default. */
if( PSA_MAC_TRUNCATED_LENGTH( policy_alg ) == 0 )
return( requested_output_length == default_output_length );
/* If the requested algorithm is default-length, allow it if the policy
* length exactly matches the default length. */
if( PSA_MAC_TRUNCATED_LENGTH( requested_alg ) == 0 &&
PSA_MAC_TRUNCATED_LENGTH( policy_alg ) == default_output_length )
{
return( 1 );
}
/* If policy_alg is an at-least-this-length wildcard MAC algorithm,
* check for the requested MAC length to be equal to or longer than the
* minimum allowed length. */
if( ( policy_alg & PSA_ALG_MAC_AT_LEAST_THIS_LENGTH_FLAG ) != 0 )
{
return( PSA_MAC_TRUNCATED_LENGTH( policy_alg ) <=
requested_output_length );
}
}
/* If policy_alg is a generic key agreement operation, then using it for
* a key derivation with that key agreement should also be allowed. This
* behaviour is expected to be defined in a future specification version. */
if( PSA_ALG_IS_RAW_KEY_AGREEMENT( policy_alg ) &&
PSA_ALG_IS_KEY_AGREEMENT( requested_alg ) )
{
return( PSA_ALG_KEY_AGREEMENT_GET_BASE( requested_alg ) ==
policy_alg );
}
/* If it isn't explicitly permitted, it's forbidden. */
return( 0 );
}
/** Test whether a policy permits an algorithm.
*
* The caller must test usage flags separately.
*
* \note This function requires providing the key type for which the policy is
* being validated, since some algorithm policy definitions (e.g. MAC)
* have different properties depending on what kind of cipher it is
* combined with.
*
* \retval PSA_SUCCESS When \p alg is a specific algorithm
* allowed by the \p policy.
* \retval PSA_ERROR_INVALID_ARGUMENT When \p alg is not a specific algorithm
* \retval PSA_ERROR_NOT_PERMITTED When \p alg is a specific algorithm, but
* the \p policy does not allow it.
*/
static psa_status_t psa_key_policy_permits( const psa_key_policy_t *policy,
psa_key_type_t key_type,
psa_algorithm_t alg )
{
/* '0' is not a valid algorithm */
if( alg == 0 )
return( PSA_ERROR_INVALID_ARGUMENT );
/* A requested algorithm cannot be a wildcard. */
if( PSA_ALG_IS_WILDCARD( alg ) )
return( PSA_ERROR_INVALID_ARGUMENT );
if( psa_key_algorithm_permits( key_type, policy->alg, alg ) ||
psa_key_algorithm_permits( key_type, policy->alg2, alg ) )
return( PSA_SUCCESS );
else
return( PSA_ERROR_NOT_PERMITTED );
}
/** Restrict a key policy based on a constraint.
*
* \note This function requires providing the key type for which the policy is
* being restricted, since some algorithm policy definitions (e.g. MAC)
* have different properties depending on what kind of cipher it is
* combined with.
*
* \param[in] key_type The key type for which to restrict the policy
* \param[in,out] policy The policy to restrict.
* \param[in] constraint The policy constraint to apply.
*
* \retval #PSA_SUCCESS
* \c *policy contains the intersection of the original value of
* \c *policy and \c *constraint.
* \retval #PSA_ERROR_INVALID_ARGUMENT
* \c key_type, \c *policy and \c *constraint are incompatible.
* \c *policy is unchanged.
*/
static psa_status_t psa_restrict_key_policy(
psa_key_type_t key_type,
psa_key_policy_t *policy,
const psa_key_policy_t *constraint )
{
psa_algorithm_t intersection_alg =
psa_key_policy_algorithm_intersection( key_type, policy->alg,
constraint->alg );
psa_algorithm_t intersection_alg2 =
psa_key_policy_algorithm_intersection( key_type, policy->alg2,
constraint->alg2 );
if( intersection_alg == 0 && policy->alg != 0 && constraint->alg != 0 )
return( PSA_ERROR_INVALID_ARGUMENT );
if( intersection_alg2 == 0 && policy->alg2 != 0 && constraint->alg2 != 0 )
return( PSA_ERROR_INVALID_ARGUMENT );
policy->usage &= constraint->usage;
policy->alg = intersection_alg;
policy->alg2 = intersection_alg2;
return( PSA_SUCCESS );
}
/** Get the description of a key given its identifier and policy constraints
* and lock it.
*
* The key must have allow all the usage flags set in \p usage. If \p alg is
* nonzero, the key must allow operations with this algorithm. If \p alg is
* zero, the algorithm is not checked.
*
* In case of a persistent key, the function loads the description of the key
* into a key slot if not already done.
*
* On success, the returned key slot is locked. It is the responsibility of
* the caller to unlock the key slot when it does not access it anymore.
*/
static psa_status_t psa_get_and_lock_key_slot_with_policy(
mbedtls_svc_key_id_t key,
psa_key_slot_t **p_slot,
psa_key_usage_t usage,
psa_algorithm_t alg )
{
psa_status_t status = PSA_ERROR_CORRUPTION_DETECTED;
psa_key_slot_t *slot;
status = psa_get_and_lock_key_slot( key, p_slot );
if( status != PSA_SUCCESS )
return( status );
slot = *p_slot;
/* Enforce that usage policy for the key slot contains all the flags
* required by the usage parameter. There is one exception: public
* keys can always be exported, so we treat public key objects as
* if they had the export flag. */
if( PSA_KEY_TYPE_IS_PUBLIC_KEY( slot->attr.type ) )
usage &= ~PSA_KEY_USAGE_EXPORT;
if( ( slot->attr.policy.usage & usage ) != usage )
{
status = PSA_ERROR_NOT_PERMITTED;
goto error;
}
/* Enforce that the usage policy permits the requested algortihm. */
if( alg != 0 )
{
status = psa_key_policy_permits( &slot->attr.policy,
slot->attr.type,
alg );
if( status != PSA_SUCCESS )
goto error;
}
return( PSA_SUCCESS );
error:
*p_slot = NULL;
psa_unlock_key_slot( slot );
return( status );
}
/** Get a key slot containing a transparent key and lock it.
*
* A transparent key is a key for which the key material is directly
* available, as opposed to a key in a secure element.
*
* This is a temporary function to use instead of
* psa_get_and_lock_key_slot_with_policy() until secure element support is
* fully implemented.
*
* On success, the returned key slot is locked. It is the responsibility of the
* caller to unlock the key slot when it does not access it anymore.
*/
#if defined(MBEDTLS_PSA_CRYPTO_SE_C)
static psa_status_t psa_get_and_lock_transparent_key_slot_with_policy(
mbedtls_svc_key_id_t key,
psa_key_slot_t **p_slot,
psa_key_usage_t usage,
psa_algorithm_t alg )
{
psa_status_t status = psa_get_and_lock_key_slot_with_policy( key, p_slot,
usage, alg );
if( status != PSA_SUCCESS )
return( status );
if( psa_key_slot_is_external( *p_slot ) )
{
psa_unlock_key_slot( *p_slot );
*p_slot = NULL;
return( PSA_ERROR_NOT_SUPPORTED );
}
return( PSA_SUCCESS );
}
#else /* MBEDTLS_PSA_CRYPTO_SE_C */
/* With no secure element support, all keys are transparent. */
#define psa_get_and_lock_transparent_key_slot_with_policy( key, p_slot, usage, alg ) \
psa_get_and_lock_key_slot_with_policy( key, p_slot, usage, alg )
#endif /* MBEDTLS_PSA_CRYPTO_SE_C */
psa_status_t psa_remove_key_data_from_memory( psa_key_slot_t *slot )
{
/* Data pointer will always be either a valid pointer or NULL in an
* initialized slot, so we can just free it. */
if( slot->key.data != NULL )
mbedtls_platform_zeroize( slot->key.data, slot->key.bytes);
mbedtls_free( slot->key.data );
slot->key.data = NULL;
slot->key.bytes = 0;
return( PSA_SUCCESS );
}
/** Completely wipe a slot in memory, including its policy.
* Persistent storage is not affected. */
psa_status_t psa_wipe_key_slot( psa_key_slot_t *slot )
{
psa_status_t status = psa_remove_key_data_from_memory( slot );
/*
* As the return error code may not be handled in case of multiple errors,
* do our best to report an unexpected lock counter: if available
* call MBEDTLS_PARAM_FAILED that may terminate execution (if called as
* part of the execution of a test suite this will stop the test suite
* execution).
*/
if( slot->lock_count != 1 )
{
#ifdef MBEDTLS_CHECK_PARAMS
MBEDTLS_PARAM_FAILED( slot->lock_count == 1 );
#endif
status = PSA_ERROR_CORRUPTION_DETECTED;
}
/* Multipart operations may still be using the key. This is safe
* because all multipart operation objects are independent from
* the key slot: if they need to access the key after the setup
* phase, they have a copy of the key. Note that this means that
* key material can linger until all operations are completed. */
/* At this point, key material and other type-specific content has
* been wiped. Clear remaining metadata. We can call memset and not
* zeroize because the metadata is not particularly sensitive. */
memset( slot, 0, sizeof( *slot ) );
return( status );
}
psa_status_t psa_destroy_key( mbedtls_svc_key_id_t key )
{
psa_key_slot_t *slot;
psa_status_t status; /* status of the last operation */
psa_status_t overall_status = PSA_SUCCESS;
#if defined(MBEDTLS_PSA_CRYPTO_SE_C)
psa_se_drv_table_entry_t *driver;
#endif /* MBEDTLS_PSA_CRYPTO_SE_C */
if( mbedtls_svc_key_id_is_null( key ) )
return( PSA_SUCCESS );
/*
* Get the description of the key in a key slot. In case of a persistent
* key, this will load the key description from persistent memory if not
* done yet. We cannot avoid this loading as without it we don't know if
* the key is operated by an SE or not and this information is needed by
* the current implementation.
*/
status = psa_get_and_lock_key_slot( key, &slot );
if( status != PSA_SUCCESS )
return( status );
/*
* If the key slot containing the key description is under access by the
* library (apart from the present access), the key cannot be destroyed
* yet. For the time being, just return in error. Eventually (to be
* implemented), the key should be destroyed when all accesses have
* stopped.
*/
if( slot->lock_count > 1 )
{
psa_unlock_key_slot( slot );
return( PSA_ERROR_GENERIC_ERROR );
}
if( PSA_KEY_LIFETIME_IS_READ_ONLY( slot->attr.lifetime ) )
{
/* Refuse the destruction of a read-only key (which may or may not work
* if we attempt it, depending on whether the key is merely read-only
* by policy or actually physically read-only).
* Just do the best we can, which is to wipe the copy in memory
* (done in this function's cleanup code). */
overall_status = PSA_ERROR_NOT_PERMITTED;
goto exit;
}
#if defined(MBEDTLS_PSA_CRYPTO_SE_C)
driver = psa_get_se_driver_entry( slot->attr.lifetime );
if( driver != NULL )
{
/* For a key in a secure element, we need to do three things:
* remove the key file in internal storage, destroy the
* key inside the secure element, and update the driver's
* persistent data. Start a transaction that will encompass these
* three actions. */
psa_crypto_prepare_transaction( PSA_CRYPTO_TRANSACTION_DESTROY_KEY );
psa_crypto_transaction.key.lifetime = slot->attr.lifetime;
psa_crypto_transaction.key.slot = psa_key_slot_get_slot_number( slot );
psa_crypto_transaction.key.id = slot->attr.id;
status = psa_crypto_save_transaction( );
if( status != PSA_SUCCESS )
{
(void) psa_crypto_stop_transaction( );
/* We should still try to destroy the key in the secure
* element and the key metadata in storage. This is especially
* important if the error is that the storage is full.
* But how to do it exactly without risking an inconsistent
* state after a reset?
* https://github.com/ARMmbed/mbed-crypto/issues/215
*/
overall_status = status;
goto exit;
}
status = psa_destroy_se_key( driver,
psa_key_slot_get_slot_number( slot ) );
if( overall_status == PSA_SUCCESS )
overall_status = status;
}
#endif /* MBEDTLS_PSA_CRYPTO_SE_C */
#if defined(MBEDTLS_PSA_CRYPTO_STORAGE_C)
if( ! PSA_KEY_LIFETIME_IS_VOLATILE( slot->attr.lifetime ) )
{
status = psa_destroy_persistent_key( slot->attr.id );
if( overall_status == PSA_SUCCESS )
overall_status = status;
/* TODO: other slots may have a copy of the same key. We should
* invalidate them.
* https://github.com/ARMmbed/mbed-crypto/issues/214
*/
}
#endif /* defined(MBEDTLS_PSA_CRYPTO_STORAGE_C) */
#if defined(MBEDTLS_PSA_CRYPTO_SE_C)
if( driver != NULL )
{
status = psa_save_se_persistent_data( driver );
if( overall_status == PSA_SUCCESS )
overall_status = status;
status = psa_crypto_stop_transaction( );
if( overall_status == PSA_SUCCESS )
overall_status = status;
}
#endif /* MBEDTLS_PSA_CRYPTO_SE_C */
exit:
status = psa_wipe_key_slot( slot );
/* Prioritize CORRUPTION_DETECTED from wiping over a storage error */
if( status != PSA_SUCCESS )
overall_status = status;
return( overall_status );
}
#if defined(MBEDTLS_PSA_BUILTIN_KEY_TYPE_RSA_KEY_PAIR) || \
defined(MBEDTLS_PSA_BUILTIN_KEY_TYPE_RSA_PUBLIC_KEY)
static psa_status_t psa_get_rsa_public_exponent(
const mbedtls_rsa_context *rsa,
psa_key_attributes_t *attributes )
{
mbedtls_mpi mpi;
int ret = MBEDTLS_ERR_ERROR_CORRUPTION_DETECTED;
uint8_t *buffer = NULL;
size_t buflen;
mbedtls_mpi_init( &mpi );
ret = mbedtls_rsa_export( rsa, NULL, NULL, NULL, NULL, &mpi );
if( ret != 0 )
goto exit;
if( mbedtls_mpi_cmp_int( &mpi, 65537 ) == 0 )
{
/* It's the default value, which is reported as an empty string,
* so there's nothing to do. */
goto exit;
}
buflen = mbedtls_mpi_size( &mpi );
buffer = mbedtls_calloc( 1, buflen );
if( buffer == NULL )
{
ret = MBEDTLS_ERR_MPI_ALLOC_FAILED;
goto exit;
}
ret = mbedtls_mpi_write_binary( &mpi, buffer, buflen );
if( ret != 0 )
goto exit;
attributes->domain_parameters = buffer;
attributes->domain_parameters_size = buflen;
exit:
mbedtls_mpi_free( &mpi );
if( ret != 0 )
mbedtls_free( buffer );
return( mbedtls_to_psa_error( ret ) );
}
#endif /* defined(MBEDTLS_PSA_BUILTIN_KEY_TYPE_RSA_KEY_PAIR) ||
* defined(MBEDTLS_PSA_BUILTIN_KEY_TYPE_RSA_PUBLIC_KEY) */
/** Retrieve all the publicly-accessible attributes of a key.
*/
psa_status_t psa_get_key_attributes( mbedtls_svc_key_id_t key,
psa_key_attributes_t *attributes )
{
psa_status_t status = PSA_ERROR_CORRUPTION_DETECTED;
psa_status_t unlock_status = PSA_ERROR_CORRUPTION_DETECTED;
psa_key_slot_t *slot;
psa_reset_key_attributes( attributes );
status = psa_get_and_lock_key_slot_with_policy( key, &slot, 0, 0 );
if( status != PSA_SUCCESS )
return( status );
attributes->core = slot->attr;
attributes->core.flags &= ( MBEDTLS_PSA_KA_MASK_EXTERNAL_ONLY |
MBEDTLS_PSA_KA_MASK_DUAL_USE );
#if defined(MBEDTLS_PSA_CRYPTO_SE_C)
if( psa_key_slot_is_external( slot ) )
psa_set_key_slot_number( attributes,
psa_key_slot_get_slot_number( slot ) );
#endif /* MBEDTLS_PSA_CRYPTO_SE_C */
switch( slot->attr.type )
{
#if defined(MBEDTLS_PSA_BUILTIN_KEY_TYPE_RSA_KEY_PAIR) || \
defined(MBEDTLS_PSA_BUILTIN_KEY_TYPE_RSA_PUBLIC_KEY)
case PSA_KEY_TYPE_RSA_KEY_PAIR:
case PSA_KEY_TYPE_RSA_PUBLIC_KEY:
#if defined(MBEDTLS_PSA_CRYPTO_SE_C)
/* TODO: reporting the public exponent for opaque keys
* is not yet implemented.
* https://github.com/ARMmbed/mbed-crypto/issues/216
*/
if( psa_key_slot_is_external( slot ) )
break;
#endif /* MBEDTLS_PSA_CRYPTO_SE_C */
{
mbedtls_rsa_context *rsa = NULL;
status = mbedtls_psa_rsa_load_representation(
slot->attr.type,
slot->key.data,
slot->key.bytes,
&rsa );
if( status != PSA_SUCCESS )
break;
status = psa_get_rsa_public_exponent( rsa,
attributes );
mbedtls_rsa_free( rsa );
mbedtls_free( rsa );
}
break;
#endif /* defined(MBEDTLS_PSA_BUILTIN_KEY_TYPE_RSA_KEY_PAIR) ||
* defined(MBEDTLS_PSA_BUILTIN_KEY_TYPE_RSA_PUBLIC_KEY) */
default:
/* Nothing else to do. */
break;
}
if( status != PSA_SUCCESS )
psa_reset_key_attributes( attributes );
unlock_status = psa_unlock_key_slot( slot );
return( ( status == PSA_SUCCESS ) ? unlock_status : status );
}
#if defined(MBEDTLS_PSA_CRYPTO_SE_C)
psa_status_t psa_get_key_slot_number(
const psa_key_attributes_t *attributes,
psa_key_slot_number_t *slot_number )
{
if( attributes->core.flags & MBEDTLS_PSA_KA_FLAG_HAS_SLOT_NUMBER )
{
*slot_number = attributes->slot_number;
return( PSA_SUCCESS );
}
else
return( PSA_ERROR_INVALID_ARGUMENT );
}
#endif /* MBEDTLS_PSA_CRYPTO_SE_C */
static psa_status_t psa_export_key_buffer_internal( const uint8_t *key_buffer,
size_t key_buffer_size,
uint8_t *data,
size_t data_size,
size_t *data_length )
{
if( key_buffer_size > data_size )
return( PSA_ERROR_BUFFER_TOO_SMALL );
memcpy( data, key_buffer, key_buffer_size );
memset( data + key_buffer_size, 0,
data_size - key_buffer_size );
*data_length = key_buffer_size;
return( PSA_SUCCESS );
}
psa_status_t psa_export_key_internal(
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 )
{
psa_key_type_t type = attributes->core.type;
if( key_type_is_raw_bytes( type ) ||
PSA_KEY_TYPE_IS_RSA( type ) ||
PSA_KEY_TYPE_IS_ECC( type ) )
{
return( psa_export_key_buffer_internal(
key_buffer, key_buffer_size,
data, data_size, data_length ) );
}
else
{
/* This shouldn't happen in the reference implementation, but
it is valid for a special-purpose implementation to omit
support for exporting certain key types. */
return( PSA_ERROR_NOT_SUPPORTED );
}
}
psa_status_t psa_export_key( mbedtls_svc_key_id_t key,
uint8_t *data,
size_t data_size,
size_t *data_length )
{
psa_status_t status = PSA_ERROR_CORRUPTION_DETECTED;
psa_status_t unlock_status = PSA_ERROR_CORRUPTION_DETECTED;
psa_key_slot_t *slot;
/* Reject a zero-length output buffer now, since this can never be a
* valid key representation. This way we know that data must be a valid
* pointer and we can do things like memset(data, ..., data_size). */
if( data_size == 0 )
return( PSA_ERROR_BUFFER_TOO_SMALL );
/* Set the key to empty now, so that even when there are errors, we always
* set data_length to a value between 0 and data_size. On error, setting
* the key to empty is a good choice because an empty key representation is
* unlikely to be accepted anywhere. */
*data_length = 0;
/* Export requires the EXPORT flag. There is an exception for public keys,
* which don't require any flag, but
* psa_get_and_lock_key_slot_with_policy() takes care of this.
*/
status = psa_get_and_lock_key_slot_with_policy( key, &slot,
PSA_KEY_USAGE_EXPORT, 0 );
if( status != PSA_SUCCESS )
return( status );
psa_key_attributes_t attributes = {
.core = slot->attr
};
status = psa_driver_wrapper_export_key( &attributes,
slot->key.data, slot->key.bytes,
data, data_size, data_length );
unlock_status = psa_unlock_key_slot( slot );
return( ( status == PSA_SUCCESS ) ? unlock_status : status );
}
psa_status_t psa_export_public_key_internal(
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 )
{
psa_key_type_t type = attributes->core.type;
if( PSA_KEY_TYPE_IS_RSA( type ) || PSA_KEY_TYPE_IS_ECC( type ) )
{
if( PSA_KEY_TYPE_IS_PUBLIC_KEY( type ) )
{
/* Exporting public -> public */
return( psa_export_key_buffer_internal(
key_buffer, key_buffer_size,
data, data_size, data_length ) );
}
if( PSA_KEY_TYPE_IS_RSA( type ) )
{
#if defined(MBEDTLS_PSA_BUILTIN_KEY_TYPE_RSA_KEY_PAIR) || \
defined(MBEDTLS_PSA_BUILTIN_KEY_TYPE_RSA_PUBLIC_KEY)
return( mbedtls_psa_rsa_export_public_key( attributes,
key_buffer,
key_buffer_size,
data,
data_size,
data_length ) );
#else
/* We don't know how to convert a private RSA key to public. */
return( PSA_ERROR_NOT_SUPPORTED );
#endif /* defined(MBEDTLS_PSA_BUILTIN_KEY_TYPE_RSA_KEY_PAIR) ||
* defined(MBEDTLS_PSA_BUILTIN_KEY_TYPE_RSA_PUBLIC_KEY) */
}
else
{
#if defined(MBEDTLS_PSA_BUILTIN_KEY_TYPE_ECC_KEY_PAIR) || \
defined(MBEDTLS_PSA_BUILTIN_KEY_TYPE_ECC_PUBLIC_KEY)
return( mbedtls_psa_ecp_export_public_key( attributes,
key_buffer,
key_buffer_size,
data,
data_size,
data_length ) );
#else
/* We don't know how to convert a private ECC key to public */
return( PSA_ERROR_NOT_SUPPORTED );
#endif /* defined(MBEDTLS_PSA_BUILTIN_KEY_TYPE_ECC_KEY_PAIR) ||
* defined(MBEDTLS_PSA_BUILTIN_KEY_TYPE_ECC_PUBLIC_KEY) */
}
}
else
{
/* This shouldn't happen in the reference implementation, but
it is valid for a special-purpose implementation to omit
support for exporting certain key types. */
return( PSA_ERROR_NOT_SUPPORTED );
}
}
psa_status_t psa_export_public_key( mbedtls_svc_key_id_t key,
uint8_t *data,
size_t data_size,
size_t *data_length )
{
psa_status_t status = PSA_ERROR_CORRUPTION_DETECTED;
psa_status_t unlock_status = PSA_ERROR_CORRUPTION_DETECTED;
psa_key_slot_t *slot;
/* Reject a zero-length output buffer now, since this can never be a
* valid key representation. This way we know that data must be a valid
* pointer and we can do things like memset(data, ..., data_size). */
if( data_size == 0 )
return( PSA_ERROR_BUFFER_TOO_SMALL );
/* Set the key to empty now, so that even when there are errors, we always
* set data_length to a value between 0 and data_size. On error, setting
* the key to empty is a good choice because an empty key representation is
* unlikely to be accepted anywhere. */
*data_length = 0;
/* Exporting a public key doesn't require a usage flag. */
status = psa_get_and_lock_key_slot_with_policy( key, &slot, 0, 0 );
if( status != PSA_SUCCESS )
return( status );
if( ! PSA_KEY_TYPE_IS_ASYMMETRIC( slot->attr.type ) )
{
status = PSA_ERROR_INVALID_ARGUMENT;
goto exit;
}
psa_key_attributes_t attributes = {
.core = slot->attr
};
status = psa_driver_wrapper_export_public_key(
&attributes, slot->key.data, slot->key.bytes,
data, data_size, data_length );
exit:
unlock_status = psa_unlock_key_slot( slot );
return( ( status == PSA_SUCCESS ) ? unlock_status : status );
}
#if defined(static_assert)
static_assert( ( MBEDTLS_PSA_KA_MASK_EXTERNAL_ONLY & MBEDTLS_PSA_KA_MASK_DUAL_USE ) == 0,
"One or more key attribute flag is listed as both external-only and dual-use" );
static_assert( ( PSA_KA_MASK_INTERNAL_ONLY & MBEDTLS_PSA_KA_MASK_DUAL_USE ) == 0,
"One or more key attribute flag is listed as both internal-only and dual-use" );
static_assert( ( PSA_KA_MASK_INTERNAL_ONLY & MBEDTLS_PSA_KA_MASK_EXTERNAL_ONLY ) == 0,
"One or more key attribute flag is listed as both internal-only and external-only" );
#endif
/** Validate that a key policy is internally well-formed.
*
* This function only rejects invalid policies. It does not validate the
* consistency of the policy with respect to other attributes of the key
* such as the key type.
*/
static psa_status_t psa_validate_key_policy( const psa_key_policy_t *policy )
{
if( ( policy->usage & ~( PSA_KEY_USAGE_EXPORT |
PSA_KEY_USAGE_COPY |
PSA_KEY_USAGE_ENCRYPT |
PSA_KEY_USAGE_DECRYPT |
PSA_KEY_USAGE_SIGN_MESSAGE |
PSA_KEY_USAGE_VERIFY_MESSAGE |
PSA_KEY_USAGE_SIGN_HASH |
PSA_KEY_USAGE_VERIFY_HASH |
PSA_KEY_USAGE_DERIVE ) ) != 0 )
return( PSA_ERROR_INVALID_ARGUMENT );
return( PSA_SUCCESS );
}
/** Validate the internal consistency of key attributes.
*
* This function only rejects invalid attribute values. If does not
* validate the consistency of the attributes with any key data that may
* be involved in the creation of the key.
*
* Call this function early in the key creation process.
*
* \param[in] attributes Key attributes for the new key.
* \param[out] p_drv On any return, the driver for the key, if any.
* NULL for a transparent key.
*
*/
static psa_status_t psa_validate_key_attributes(
const psa_key_attributes_t *attributes,
psa_se_drv_table_entry_t **p_drv )
{
psa_status_t status = PSA_ERROR_INVALID_ARGUMENT;
psa_key_lifetime_t lifetime = psa_get_key_lifetime( attributes );
mbedtls_svc_key_id_t key = psa_get_key_id( attributes );
status = psa_validate_key_location( lifetime, p_drv );
if( status != PSA_SUCCESS )
return( status );
status = psa_validate_key_persistence( lifetime );
if( status != PSA_SUCCESS )
return( status );
if ( PSA_KEY_LIFETIME_IS_VOLATILE( lifetime ) )
{
if( MBEDTLS_SVC_KEY_ID_GET_KEY_ID( key ) != 0 )
return( PSA_ERROR_INVALID_ARGUMENT );
}
else
{
if( !psa_is_valid_key_id( psa_get_key_id( attributes ), 0 ) )
return( PSA_ERROR_INVALID_ARGUMENT );
}
status = psa_validate_key_policy( &attributes->core.policy );
if( status != PSA_SUCCESS )
return( status );
/* Refuse to create overly large keys.
* Note that this doesn't trigger on import if the attributes don't
* explicitly specify a size (so psa_get_key_bits returns 0), so
* psa_import_key() needs its own checks. */
if( psa_get_key_bits( attributes ) > PSA_MAX_KEY_BITS )
return( PSA_ERROR_NOT_SUPPORTED );
/* Reject invalid flags. These should not be reachable through the API. */
if( attributes->core.flags & ~ ( MBEDTLS_PSA_KA_MASK_EXTERNAL_ONLY |
MBEDTLS_PSA_KA_MASK_DUAL_USE ) )
return( PSA_ERROR_INVALID_ARGUMENT );
return( PSA_SUCCESS );
}
/** Prepare a key slot to receive key material.
*
* This function allocates a key slot and sets its metadata.
*
* If this function fails, call psa_fail_key_creation().
*
* This function is intended to be used as follows:
* -# Call psa_start_key_creation() to allocate a key slot, prepare
* it with the specified attributes, and in case of a volatile key assign it
* a volatile key identifier.
* -# Populate the slot with the key material.
* -# Call psa_finish_key_creation() to finalize the creation of the slot.
* In case of failure at any step, stop the sequence and call
* psa_fail_key_creation().
*
* On success, the key slot is locked. It is the responsibility of the caller
* to unlock the key slot when it does not access it anymore.
*
* \param method An identification of the calling function.
* \param[in] attributes Key attributes for the new key.
* \param[out] p_slot On success, a pointer to the prepared slot.
* \param[out] p_drv On any return, the driver for the key, if any.
* NULL for a transparent key.
*
* \retval #PSA_SUCCESS
* The key slot is ready to receive key material.
* \return If this function fails, the key slot is an invalid state.
* You must call psa_fail_key_creation() to wipe and free the slot.
*/
static psa_status_t psa_start_key_creation(
psa_key_creation_method_t method,
const psa_key_attributes_t *attributes,
psa_key_slot_t **p_slot,
psa_se_drv_table_entry_t **p_drv )
{
psa_status_t status;
psa_key_id_t volatile_key_id;
psa_key_slot_t *slot;
(void) method;
*p_drv = NULL;
status = psa_validate_key_attributes( attributes, p_drv );
if( status != PSA_SUCCESS )
return( status );
status = psa_get_empty_key_slot( &volatile_key_id, p_slot );
if( status != PSA_SUCCESS )
return( status );
slot = *p_slot;
/* We're storing the declared bit-size of the key. It's up to each
* creation mechanism to verify that this information is correct.
* It's automatically correct for mechanisms that use the bit-size as
* an input (generate, device) but not for those where the bit-size
* is optional (import, copy). In case of a volatile key, assign it the
* volatile key identifier associated to the slot returned to contain its
* definition. */
slot->attr = attributes->core;
if( PSA_KEY_LIFETIME_IS_VOLATILE( slot->attr.lifetime ) )
{
#if !defined(MBEDTLS_PSA_CRYPTO_KEY_ID_ENCODES_OWNER)
slot->attr.id = volatile_key_id;
#else
slot->attr.id.key_id = volatile_key_id;
#endif
}
/* Erase external-only flags from the internal copy. To access
* external-only flags, query `attributes`. Thanks to the check
* in psa_validate_key_attributes(), this leaves the dual-use
* flags and any internal flag that psa_get_empty_key_slot()
* may have set. */
slot->attr.flags &= ~MBEDTLS_PSA_KA_MASK_EXTERNAL_ONLY;
#if defined(MBEDTLS_PSA_CRYPTO_SE_C)
/* For a key in a secure element, we need to do three things
* when creating or registering a persistent key:
* create the key file in internal storage, create the
* key inside the secure element, and update the driver's
* persistent data. This is done by starting a transaction that will
* encompass these three actions.
* For registering a volatile key, we just need to find an appropriate
* slot number inside the SE. Since the key is designated volatile, creating
* a transaction is not required. */
/* The first thing to do is to find a slot number for the new key.
* We save the slot number in persistent storage as part of the
* transaction data. It will be needed to recover if the power
* fails during the key creation process, to clean up on the secure
* element side after restarting. Obtaining a slot number from the
* secure element driver updates its persistent state, but we do not yet
* save the driver's persistent state, so that if the power fails,
* we can roll back to a state where the key doesn't exist. */
if( *p_drv != NULL )
{
psa_key_slot_number_t slot_number;
status = psa_find_se_slot_for_key( attributes, method, *p_drv,
&slot_number );
if( status != PSA_SUCCESS )
return( status );
if( ! PSA_KEY_LIFETIME_IS_VOLATILE( attributes->core.lifetime ) )
{
psa_crypto_prepare_transaction( PSA_CRYPTO_TRANSACTION_CREATE_KEY );
psa_crypto_transaction.key.lifetime = slot->attr.lifetime;
psa_crypto_transaction.key.slot = slot_number;
psa_crypto_transaction.key.id = slot->attr.id;
status = psa_crypto_save_transaction( );
if( status != PSA_SUCCESS )
{
(void) psa_crypto_stop_transaction( );
return( status );
}
}
status = psa_copy_key_material_into_slot(
slot, (uint8_t *)( &slot_number ), sizeof( slot_number ) );
}
if( *p_drv == NULL && method == PSA_KEY_CREATION_REGISTER )
{
/* Key registration only makes sense with a secure element. */
return( PSA_ERROR_INVALID_ARGUMENT );
}
#endif /* MBEDTLS_PSA_CRYPTO_SE_C */
return( PSA_SUCCESS );
}
/** Finalize the creation of a key once its key material has been set.
*
* This entails writing the key to persistent storage.
*
* If this function fails, call psa_fail_key_creation().
* See the documentation of psa_start_key_creation() for the intended use
* of this function.
*
* If the finalization succeeds, the function unlocks the key slot (it was
* locked by psa_start_key_creation()) and the key slot cannot be accessed
* anymore as part of the key creation process.
*
* \param[in,out] slot Pointer to the slot with key material.
* \param[in] driver The secure element driver for the key,
* or NULL for a transparent key.
* \param[out] key On success, identifier of the key. Note that the
* key identifier is also stored in the key slot.
*
* \retval #PSA_SUCCESS
* The key was successfully created.
* \retval #PSA_ERROR_INSUFFICIENT_MEMORY
* \retval #PSA_ERROR_INSUFFICIENT_STORAGE
* \retval #PSA_ERROR_ALREADY_EXISTS
* \retval #PSA_ERROR_DATA_INVALID
* \retval #PSA_ERROR_DATA_CORRUPT
* \retval #PSA_ERROR_STORAGE_FAILURE
*
* \return If this function fails, the key slot is an invalid state.
* You must call psa_fail_key_creation() to wipe and free the slot.
*/
static psa_status_t psa_finish_key_creation(
psa_key_slot_t *slot,
psa_se_drv_table_entry_t *driver,
mbedtls_svc_key_id_t *key)
{
psa_status_t status = PSA_SUCCESS;
(void) slot;
(void) driver;
#if defined(MBEDTLS_PSA_CRYPTO_STORAGE_C)
if( ! PSA_KEY_LIFETIME_IS_VOLATILE( slot->attr.lifetime ) )
{
#if defined(MBEDTLS_PSA_CRYPTO_SE_C)
if( driver != NULL )
{
psa_se_key_data_storage_t data;
psa_key_slot_number_t slot_number =
psa_key_slot_get_slot_number( slot ) ;
#if defined(static_assert)
static_assert( sizeof( slot_number ) ==
sizeof( data.slot_number ),
"Slot number size does not match psa_se_key_data_storage_t" );
#endif
memcpy( &data.slot_number, &slot_number, sizeof( slot_number ) );
status = psa_save_persistent_key( &slot->attr,
(uint8_t*) &data,
sizeof( data ) );
}
else
#endif /* MBEDTLS_PSA_CRYPTO_SE_C */
{
/* Key material is saved in export representation in the slot, so
* just pass the slot buffer for storage. */
status = psa_save_persistent_key( &slot->attr,
slot->key.data,
slot->key.bytes );
}
}
#endif /* defined(MBEDTLS_PSA_CRYPTO_STORAGE_C) */
#if defined(MBEDTLS_PSA_CRYPTO_SE_C)
/* Finish the transaction for a key creation. This does not
* happen when registering an existing key. Detect this case
* by checking whether a transaction is in progress (actual
* creation of a persistent key in a secure element requires a transaction,
* but registration or volatile key creation doesn't use one). */
if( driver != NULL &&
psa_crypto_transaction.unknown.type == PSA_CRYPTO_TRANSACTION_CREATE_KEY )
{
status = psa_save_se_persistent_data( driver );
if( status != PSA_SUCCESS )
{
psa_destroy_persistent_key( slot->attr.id );
return( status );
}
status = psa_crypto_stop_transaction( );
}
#endif /* MBEDTLS_PSA_CRYPTO_SE_C */
if( status == PSA_SUCCESS )
{
*key = slot->attr.id;
status = psa_unlock_key_slot( slot );
if( status != PSA_SUCCESS )
*key = MBEDTLS_SVC_KEY_ID_INIT;
}
return( status );
}
/** Abort the creation of a key.
*
* You may call this function after calling psa_start_key_creation(),
* or after psa_finish_key_creation() fails. In other circumstances, this
* function may not clean up persistent storage.
* See the documentation of psa_start_key_creation() for the intended use
* of this function.
*
* \param[in,out] slot Pointer to the slot with key material.
* \param[in] driver The secure element driver for the key,
* or NULL for a transparent key.
*/
static void psa_fail_key_creation( psa_key_slot_t *slot,
psa_se_drv_table_entry_t *driver )
{
(void) driver;
if( slot == NULL )
return;
#if defined(MBEDTLS_PSA_CRYPTO_SE_C)
/* TODO: If the key has already been created in the secure
* element, and the failure happened later (when saving metadata
* to internal storage), we need to destroy the key in the secure
* element.
* https://github.com/ARMmbed/mbed-crypto/issues/217
*/
/* Abort the ongoing transaction if any (there may not be one if
* the creation process failed before starting one, or if the
* key creation is a registration of a key in a secure element).
* Earlier functions must already have done what it takes to undo any
* partial creation. All that's left is to update the transaction data
* itself. */
(void) psa_crypto_stop_transaction( );
#endif /* MBEDTLS_PSA_CRYPTO_SE_C */
psa_wipe_key_slot( slot );
}
/** Validate optional attributes during key creation.
*
* Some key attributes are optional during key creation. If they are
* specified in the attributes structure, check that they are consistent
* with the data in the slot.
*
* This function should be called near the end of key creation, after
* the slot in memory is fully populated but before saving persistent data.
*/
static psa_status_t psa_validate_optional_attributes(
const psa_key_slot_t *slot,
const psa_key_attributes_t *attributes )
{
if( attributes->core.type != 0 )
{
if( attributes->core.type != slot->attr.type )
return( PSA_ERROR_INVALID_ARGUMENT );
}
if( attributes->domain_parameters_size != 0 )
{
#if defined(MBEDTLS_PSA_BUILTIN_KEY_TYPE_RSA_KEY_PAIR) || \
defined(MBEDTLS_PSA_BUILTIN_KEY_TYPE_RSA_PUBLIC_KEY)
if( PSA_KEY_TYPE_IS_RSA( slot->attr.type ) )
{
mbedtls_rsa_context *rsa = NULL;
mbedtls_mpi actual, required;
int ret = MBEDTLS_ERR_ERROR_CORRUPTION_DETECTED;
psa_status_t status = mbedtls_psa_rsa_load_representation(
slot->attr.type,
slot->key.data,
slot->key.bytes,
&rsa );
if( status != PSA_SUCCESS )
return( status );
mbedtls_mpi_init( &actual );
mbedtls_mpi_init( &required );
ret = mbedtls_rsa_export( rsa,
NULL, NULL, NULL, NULL, &actual );
mbedtls_rsa_free( rsa );
mbedtls_free( rsa );
if( ret != 0 )
goto rsa_exit;
ret = mbedtls_mpi_read_binary( &required,
attributes->domain_parameters,
attributes->domain_parameters_size );
if( ret != 0 )
goto rsa_exit;
if( mbedtls_mpi_cmp_mpi( &actual, &required ) != 0 )
ret = MBEDTLS_ERR_RSA_BAD_INPUT_DATA;
rsa_exit:
mbedtls_mpi_free( &actual );
mbedtls_mpi_free( &required );
if( ret != 0)
return( mbedtls_to_psa_error( ret ) );
}
else
#endif /* defined(MBEDTLS_PSA_BUILTIN_KEY_TYPE_RSA_KEY_PAIR) ||
* defined(MBEDTLS_PSA_BUILTIN_KEY_TYPE_RSA_PUBLIC_KEY) */
{
return( PSA_ERROR_INVALID_ARGUMENT );
}
}
if( attributes->core.bits != 0 )
{
if( attributes->core.bits != slot->attr.bits )
return( PSA_ERROR_INVALID_ARGUMENT );
}
return( PSA_SUCCESS );
}
psa_status_t psa_import_key( const psa_key_attributes_t *attributes,
const uint8_t *data,
size_t data_length,
mbedtls_svc_key_id_t *key )
{
psa_status_t status;
psa_key_slot_t *slot = NULL;
psa_se_drv_table_entry_t *driver = NULL;
size_t bits;
*key = MBEDTLS_SVC_KEY_ID_INIT;
/* Reject zero-length symmetric keys (including raw data key objects).
* This also rejects any key which might be encoded as an empty string,
* which is never valid. */
if( data_length == 0 )
return( PSA_ERROR_INVALID_ARGUMENT );
status = psa_start_key_creation( PSA_KEY_CREATION_IMPORT, attributes,
&slot, &driver );
if( status != PSA_SUCCESS )
goto exit;
/* In the case of a transparent key or an opaque key stored in local
* storage (thus not in the case of generating a key in a secure element
* or cryptoprocessor with storage), we have to allocate a buffer to
* hold the generated key material. */
if( slot->key.data == NULL )
{
status = psa_allocate_buffer_to_slot( slot, data_length );
if( status != PSA_SUCCESS )
goto exit;
}
bits = slot->attr.bits;
status = psa_driver_wrapper_import_key( attributes,
data, data_length,
slot->key.data,
slot->key.bytes,
&slot->key.bytes, &bits );
if( status != PSA_SUCCESS )
goto exit;
if( slot->attr.bits == 0 )
slot->attr.bits = (psa_key_bits_t) bits;
else if( bits != slot->attr.bits )
{
status = PSA_ERROR_INVALID_ARGUMENT;
goto exit;
}
status = psa_validate_optional_attributes( slot, attributes );
if( status != PSA_SUCCESS )
goto exit;
status = psa_finish_key_creation( slot, driver, key );
exit:
if( status != PSA_SUCCESS )
psa_fail_key_creation( slot, driver );
return( status );
}
#if defined(MBEDTLS_PSA_CRYPTO_SE_C)
psa_status_t mbedtls_psa_register_se_key(
const psa_key_attributes_t *attributes )
{
psa_status_t status;
psa_key_slot_t *slot = NULL;
psa_se_drv_table_entry_t *driver = NULL;
mbedtls_svc_key_id_t key = MBEDTLS_SVC_KEY_ID_INIT;
/* Leaving attributes unspecified is not currently supported.
* It could make sense to query the key type and size from the
* secure element, but not all secure elements support this
* and the driver HAL doesn't currently support it. */
if( psa_get_key_type( attributes ) == PSA_KEY_TYPE_NONE )
return( PSA_ERROR_NOT_SUPPORTED );
if( psa_get_key_bits( attributes ) == 0 )
return( PSA_ERROR_NOT_SUPPORTED );
status = psa_start_key_creation( PSA_KEY_CREATION_REGISTER, attributes,
&slot, &driver );
if( status != PSA_SUCCESS )
goto exit;
status = psa_finish_key_creation( slot, driver, &key );
exit:
if( status != PSA_SUCCESS )
psa_fail_key_creation( slot, driver );
/* Registration doesn't keep the key in RAM. */
psa_close_key( key );
return( status );
}
#endif /* MBEDTLS_PSA_CRYPTO_SE_C */
static psa_status_t psa_copy_key_material( const psa_key_slot_t *source,
psa_key_slot_t *target )
{
psa_status_t status = psa_copy_key_material_into_slot( target,
source->key.data,
source->key.bytes );
if( status != PSA_SUCCESS )
return( status );
target->attr.type = source->attr.type;
target->attr.bits = source->attr.bits;
return( PSA_SUCCESS );
}
psa_status_t psa_copy_key( mbedtls_svc_key_id_t source_key,
const psa_key_attributes_t *specified_attributes,
mbedtls_svc_key_id_t *target_key )
{
psa_status_t status = PSA_ERROR_CORRUPTION_DETECTED;
psa_status_t unlock_status = PSA_ERROR_CORRUPTION_DETECTED;
psa_key_slot_t *source_slot = NULL;
psa_key_slot_t *target_slot = NULL;
psa_key_attributes_t actual_attributes = *specified_attributes;
psa_se_drv_table_entry_t *driver = NULL;
*target_key = MBEDTLS_SVC_KEY_ID_INIT;
status = psa_get_and_lock_transparent_key_slot_with_policy(
source_key, &source_slot, PSA_KEY_USAGE_COPY, 0 );
if( status != PSA_SUCCESS )
goto exit;
status = psa_validate_optional_attributes( source_slot,
specified_attributes );
if( status != PSA_SUCCESS )
goto exit;
status = psa_restrict_key_policy( source_slot->attr.type,
&actual_attributes.core.policy,
&source_slot->attr.policy );
if( status != PSA_SUCCESS )
goto exit;
status = psa_start_key_creation( PSA_KEY_CREATION_COPY, &actual_attributes,
&target_slot, &driver );
if( status != PSA_SUCCESS )
goto exit;
#if defined(MBEDTLS_PSA_CRYPTO_SE_C)
if( driver != NULL )
{
/* Copying to a secure element is not implemented yet. */
status = PSA_ERROR_NOT_SUPPORTED;
goto exit;
}
#endif /* MBEDTLS_PSA_CRYPTO_SE_C */
if( psa_key_lifetime_is_external( actual_attributes.core.lifetime ) )
{
/*
* Copying through an opaque driver is not implemented yet, consider
* a lifetime with an external location as an invalid parameter for
* now.
*/
status = PSA_ERROR_INVALID_ARGUMENT;
goto exit;
}
status = psa_copy_key_material( source_slot, target_slot );
if( status != PSA_SUCCESS )
goto exit;
status = psa_finish_key_creation( target_slot, driver, target_key );
exit:
if( status != PSA_SUCCESS )
psa_fail_key_creation( target_slot, driver );
unlock_status = psa_unlock_key_slot( source_slot );
return( ( status == PSA_SUCCESS ) ? unlock_status : status );
}
/****************************************************************/
/* Message digests */
/****************************************************************/
psa_status_t psa_hash_abort( psa_hash_operation_t *operation )
{
/* Aborting a non-active operation is allowed */
if( operation->id == 0 )
return( PSA_SUCCESS );
psa_status_t status = psa_driver_wrapper_hash_abort( operation );
operation->id = 0;
return( status );
}
psa_status_t psa_hash_setup( psa_hash_operation_t *operation,
psa_algorithm_t alg )
{
psa_status_t status = PSA_ERROR_CORRUPTION_DETECTED;
/* A context must be freshly initialized before it can be set up. */
if( operation->id != 0 )
{
status = PSA_ERROR_BAD_STATE;
goto exit;
}
if( !PSA_ALG_IS_HASH( alg ) )
{
status = PSA_ERROR_INVALID_ARGUMENT;
goto exit;
}
/* Ensure all of the context is zeroized, since PSA_HASH_OPERATION_INIT only
* directly zeroes the int-sized dummy member of the context union. */
memset( &operation->ctx, 0, sizeof( operation->ctx ) );
status = psa_driver_wrapper_hash_setup( operation, alg );
exit:
if( status != PSA_SUCCESS )
psa_hash_abort( operation );
return status;
}
psa_status_t psa_hash_update( psa_hash_operation_t *operation,
const uint8_t *input,
size_t input_length )
{
psa_status_t status = PSA_ERROR_CORRUPTION_DETECTED;
if( operation->id == 0 )
{
status = PSA_ERROR_BAD_STATE;
goto exit;
}
/* Don't require hash implementations to behave correctly on a
* zero-length input, which may have an invalid pointer. */
if( input_length == 0 )
return( PSA_SUCCESS );
status = psa_driver_wrapper_hash_update( operation, input, input_length );
exit:
if( status != PSA_SUCCESS )
psa_hash_abort( operation );
return( status );
}
psa_status_t psa_hash_finish( psa_hash_operation_t *operation,
uint8_t *hash,
size_t hash_size,
size_t *hash_length )
{
*hash_length = 0;
if( operation->id == 0 )
return( PSA_ERROR_BAD_STATE );
psa_status_t status = psa_driver_wrapper_hash_finish(
operation, hash, hash_size, hash_length );
psa_hash_abort( operation );
return( status );
}
psa_status_t psa_hash_verify( psa_hash_operation_t *operation,
const uint8_t *hash,
size_t hash_length )
{
uint8_t actual_hash[MBEDTLS_MD_MAX_SIZE];
size_t actual_hash_length;
psa_status_t status = psa_hash_finish(
operation,
actual_hash, sizeof( actual_hash ),
&actual_hash_length );
if( status != PSA_SUCCESS )
goto exit;
if( actual_hash_length != hash_length )
{
status = PSA_ERROR_INVALID_SIGNATURE;
goto exit;
}
if( mbedtls_psa_safer_memcmp( hash, actual_hash, actual_hash_length ) != 0 )
status = PSA_ERROR_INVALID_SIGNATURE;
exit:
if( status != PSA_SUCCESS )
psa_hash_abort(operation);
return( status );
}
psa_status_t psa_hash_compute( psa_algorithm_t alg,
const uint8_t *input, size_t input_length,
uint8_t *hash, size_t hash_size,
size_t *hash_length )
{
*hash_length = 0;
if( !PSA_ALG_IS_HASH( alg ) )
return( PSA_ERROR_INVALID_ARGUMENT );
return( psa_driver_wrapper_hash_compute( alg, input, input_length,
hash, hash_size, hash_length ) );
}
psa_status_t psa_hash_compare( psa_algorithm_t alg,
const uint8_t *input, size_t input_length,
const uint8_t *hash, size_t hash_length )
{
uint8_t actual_hash[MBEDTLS_MD_MAX_SIZE];
size_t actual_hash_length;
if( !PSA_ALG_IS_HASH( alg ) )
return( PSA_ERROR_INVALID_ARGUMENT );
psa_status_t status = psa_driver_wrapper_hash_compute(
alg, input, input_length,
actual_hash, sizeof(actual_hash),
&actual_hash_length );
if( status != PSA_SUCCESS )
return( status );
if( actual_hash_length != hash_length )
return( PSA_ERROR_INVALID_SIGNATURE );
if( mbedtls_psa_safer_memcmp( hash, actual_hash, actual_hash_length ) != 0 )
return( PSA_ERROR_INVALID_SIGNATURE );
return( PSA_SUCCESS );
}
psa_status_t psa_hash_clone( const psa_hash_operation_t *source_operation,
psa_hash_operation_t *target_operation )
{
if( source_operation->id == 0 ||
target_operation->id != 0 )
{
return( PSA_ERROR_BAD_STATE );
}
psa_status_t status = psa_driver_wrapper_hash_clone( source_operation,
target_operation );
if( status != PSA_SUCCESS )
psa_hash_abort( target_operation );
return( status );
}
/****************************************************************/
/* MAC */
/****************************************************************/
psa_status_t psa_mac_abort( psa_mac_operation_t *operation )
{
/* Aborting a non-active operation is allowed */
if( operation->id == 0 )
return( PSA_SUCCESS );
psa_status_t status = psa_driver_wrapper_mac_abort( operation );
operation->mac_size = 0;
operation->is_sign = 0;
operation->id = 0;
return( status );
}
static psa_status_t psa_mac_finalize_alg_and_key_validation(
psa_algorithm_t alg,
const psa_key_attributes_t *attributes,
uint8_t *mac_size )
{
psa_status_t status = PSA_ERROR_CORRUPTION_DETECTED;
psa_key_type_t key_type = psa_get_key_type( attributes );
size_t key_bits = psa_get_key_bits( attributes );
if( ! PSA_ALG_IS_MAC( alg ) )
return( PSA_ERROR_INVALID_ARGUMENT );
/* Validate the combination of key type and algorithm */
status = psa_mac_key_can_do( alg, key_type );
if( status != PSA_SUCCESS )
return( status );
/* Get the output length for the algorithm and key combination */
*mac_size = PSA_MAC_LENGTH( key_type, key_bits, alg );
if( *mac_size < 4 )
{
/* A very short MAC is too short for security since it can be
* brute-forced. Ancient protocols with 32-bit MACs do exist,
* so we make this our minimum, even though 32 bits is still
* too small for security. */
return( PSA_ERROR_NOT_SUPPORTED );
}
if( *mac_size > PSA_MAC_LENGTH( key_type, key_bits,
PSA_ALG_FULL_LENGTH_MAC( alg ) ) )
{
/* It's impossible to "truncate" to a larger length than the full length
* of the algorithm. */
return( PSA_ERROR_INVALID_ARGUMENT );
}
return( PSA_SUCCESS );
}
static psa_status_t psa_mac_setup( psa_mac_operation_t *operation,
mbedtls_svc_key_id_t key,
psa_algorithm_t alg,
int is_sign )
{
psa_status_t status = PSA_ERROR_CORRUPTION_DETECTED;
psa_status_t unlock_status = PSA_ERROR_CORRUPTION_DETECTED;
psa_key_slot_t *slot = NULL;
/* A context must be freshly initialized before it can be set up. */
if( operation->id != 0 )
{
status = PSA_ERROR_BAD_STATE;
goto exit;
}
status = psa_get_and_lock_key_slot_with_policy(
key,
&slot,
is_sign ? PSA_KEY_USAGE_SIGN_HASH : PSA_KEY_USAGE_VERIFY_HASH,
alg );
if( status != PSA_SUCCESS )
goto exit;
psa_key_attributes_t attributes = {
.core = slot->attr
};
status = psa_mac_finalize_alg_and_key_validation( alg, &attributes,
&operation->mac_size );
if( status != PSA_SUCCESS )
goto exit;
operation->is_sign = is_sign;
/* Dispatch the MAC setup call with validated input */
if( is_sign )
{
status = psa_driver_wrapper_mac_sign_setup( operation,
&attributes,
slot->key.data,
slot->key.bytes,
alg );
}
else
{
status = psa_driver_wrapper_mac_verify_setup( operation,
&attributes,
slot->key.data,
slot->key.bytes,
alg );
}
exit:
if( status != PSA_SUCCESS )
psa_mac_abort( operation );
unlock_status = psa_unlock_key_slot( slot );
return( ( status == PSA_SUCCESS ) ? unlock_status : status );
}
psa_status_t psa_mac_sign_setup( psa_mac_operation_t *operation,
mbedtls_svc_key_id_t key,
psa_algorithm_t alg )
{
return( psa_mac_setup( operation, key, alg, 1 ) );
}
psa_status_t psa_mac_verify_setup( psa_mac_operation_t *operation,
mbedtls_svc_key_id_t key,
psa_algorithm_t alg )
{
return( psa_mac_setup( operation, key, alg, 0 ) );
}
psa_status_t psa_mac_update( psa_mac_operation_t *operation,
const uint8_t *input,
size_t input_length )
{
if( operation->id == 0 )
return( PSA_ERROR_BAD_STATE );
/* Don't require hash implementations to behave correctly on a
* zero-length input, which may have an invalid pointer. */
if( input_length == 0 )
return( PSA_SUCCESS );
psa_status_t status = psa_driver_wrapper_mac_update( operation,
input, input_length );
if( status != PSA_SUCCESS )
psa_mac_abort( operation );
return( status );
}
psa_status_t psa_mac_sign_finish( psa_mac_operation_t *operation,
uint8_t *mac,
size_t mac_size,
size_t *mac_length )
{
psa_status_t status = PSA_ERROR_CORRUPTION_DETECTED;
psa_status_t abort_status = PSA_ERROR_CORRUPTION_DETECTED;
if( operation->id == 0 )
{
status = PSA_ERROR_BAD_STATE;
goto exit;
}
if( ! operation->is_sign )
{
status = PSA_ERROR_BAD_STATE;
goto exit;
}
/* Sanity check. This will guarantee that mac_size != 0 (and so mac != NULL)
* once all the error checks are done. */
if( operation->mac_size == 0 )
{
status = PSA_ERROR_BAD_STATE;
goto exit;
}
if( mac_size < operation->mac_size )
{
status = PSA_ERROR_BUFFER_TOO_SMALL;
goto exit;
}
status = psa_driver_wrapper_mac_sign_finish( operation,
mac, operation->mac_size,
mac_length );
exit:
/* In case of success, set the potential excess room in the output buffer
* to an invalid value, to avoid potentially leaking a longer MAC.
* In case of error, set the output length and content to a safe default,
* such that in case the caller misses an error check, the output would be
* an unachievable MAC.
*/
if( status != PSA_SUCCESS )
{
*mac_length = mac_size;
operation->mac_size = 0;
}
if( mac_size > operation->mac_size )
memset( &mac[operation->mac_size], '!',
mac_size - operation->mac_size );
abort_status = psa_mac_abort( operation );
return( status == PSA_SUCCESS ? abort_status : status );
}
psa_status_t psa_mac_verify_finish( psa_mac_operation_t *operation,
const uint8_t *mac,
size_t mac_length )
{
psa_status_t status = PSA_ERROR_CORRUPTION_DETECTED;
psa_status_t abort_status = PSA_ERROR_CORRUPTION_DETECTED;
if( operation->id == 0 )
{
status = PSA_ERROR_BAD_STATE;
goto exit;
}
if( operation->is_sign )
{
status = PSA_ERROR_BAD_STATE;
goto exit;
}
if( operation->mac_size != mac_length )
{
status = PSA_ERROR_INVALID_SIGNATURE;
goto exit;
}
status = psa_driver_wrapper_mac_verify_finish( operation,
mac, mac_length );
exit:
abort_status = psa_mac_abort( operation );
return( status == PSA_SUCCESS ? abort_status : status );
}
static psa_status_t psa_mac_compute_internal( mbedtls_svc_key_id_t key,
psa_algorithm_t alg,
const uint8_t *input,
size_t input_length,
uint8_t *mac,
size_t mac_size,
size_t *mac_length,
int is_sign )
{
psa_status_t status = PSA_ERROR_CORRUPTION_DETECTED;
psa_status_t unlock_status = PSA_ERROR_CORRUPTION_DETECTED;
psa_key_slot_t *slot;
uint8_t operation_mac_size = 0;
status = psa_get_and_lock_key_slot_with_policy(
key, &slot,
is_sign ? PSA_KEY_USAGE_SIGN_HASH : PSA_KEY_USAGE_VERIFY_HASH,
alg );
if( status != PSA_SUCCESS )
goto exit;
psa_key_attributes_t attributes = {
.core = slot->attr
};
status = psa_mac_finalize_alg_and_key_validation( alg, &attributes,
&operation_mac_size );
if( status != PSA_SUCCESS )
goto exit;
if( mac_size < operation_mac_size )
{
status = PSA_ERROR_BUFFER_TOO_SMALL;
goto exit;
}
status = psa_driver_wrapper_mac_compute(
&attributes,
slot->key.data, slot->key.bytes,
alg,
input, input_length,
mac, operation_mac_size, mac_length );
exit:
/* In case of success, set the potential excess room in the output buffer
* to an invalid value, to avoid potentially leaking a longer MAC.
* In case of error, set the output length and content to a safe default,
* such that in case the caller misses an error check, the output would be
* an unachievable MAC.
*/
if( status != PSA_SUCCESS )
{
*mac_length = mac_size;
operation_mac_size = 0;
}
if( mac_size > operation_mac_size )
memset( &mac[operation_mac_size], '!', mac_size - operation_mac_size );
unlock_status = psa_unlock_key_slot( slot );
return( ( status == PSA_SUCCESS ) ? unlock_status : status );
}
psa_status_t psa_mac_compute( mbedtls_svc_key_id_t key,
psa_algorithm_t alg,
const uint8_t *input,
size_t input_length,
uint8_t *mac,
size_t mac_size,
size_t *mac_length)
{
return( psa_mac_compute_internal( key, alg,
input, input_length,
mac, mac_size, mac_length, 1 ) );
}
psa_status_t psa_mac_verify( mbedtls_svc_key_id_t key,
psa_algorithm_t alg,
const uint8_t *input,
size_t input_length,
const uint8_t *mac,
size_t mac_length)
{
psa_status_t status = PSA_ERROR_CORRUPTION_DETECTED;
uint8_t actual_mac[PSA_MAC_MAX_SIZE];
size_t actual_mac_length;
status = psa_mac_compute_internal( key, alg,
input, input_length,
actual_mac, sizeof( actual_mac ),
&actual_mac_length, 0 );
if( status != PSA_SUCCESS )
goto exit;
if( mac_length != actual_mac_length )
{
status = PSA_ERROR_INVALID_SIGNATURE;
goto exit;
}
if( mbedtls_psa_safer_memcmp( mac, actual_mac, actual_mac_length ) != 0 )
{
status = PSA_ERROR_INVALID_SIGNATURE;
goto exit;
}
exit:
mbedtls_platform_zeroize( actual_mac, sizeof( actual_mac ) );
return ( status );
}
/****************************************************************/
/* Asymmetric cryptography */
/****************************************************************/
static psa_status_t psa_sign_verify_check_alg( int input_is_message,
psa_algorithm_t alg )
{
if( input_is_message )
{
if( ! PSA_ALG_IS_SIGN_MESSAGE( alg ) )
return( PSA_ERROR_INVALID_ARGUMENT );
if ( PSA_ALG_IS_HASH_AND_SIGN( alg ) )
{
if( ! PSA_ALG_IS_HASH( PSA_ALG_SIGN_GET_HASH( alg ) ) )
return( PSA_ERROR_INVALID_ARGUMENT );
}
}
else
{
if( ! PSA_ALG_IS_HASH_AND_SIGN( alg ) )
return( PSA_ERROR_INVALID_ARGUMENT );
}
return( PSA_SUCCESS );
}
static psa_status_t psa_sign_internal( mbedtls_svc_key_id_t key,
int input_is_message,
psa_algorithm_t alg,
const uint8_t * input,
size_t input_length,
uint8_t * signature,
size_t signature_size,
size_t * signature_length )
{
psa_status_t status = PSA_ERROR_CORRUPTION_DETECTED;
psa_status_t unlock_status = PSA_ERROR_CORRUPTION_DETECTED;
psa_key_slot_t *slot;
*signature_length = 0;
status = psa_sign_verify_check_alg( input_is_message, alg );
if( status != PSA_SUCCESS )
return status;
/* Immediately reject a zero-length signature buffer. This guarantees
* that signature must be a valid pointer. (On the other hand, the input
* buffer can in principle be empty since it doesn't actually have
* to be a hash.) */
if( signature_size == 0 )
return( PSA_ERROR_BUFFER_TOO_SMALL );
status = psa_get_and_lock_key_slot_with_policy(
key, &slot,
input_is_message ? PSA_KEY_USAGE_SIGN_MESSAGE :
PSA_KEY_USAGE_SIGN_HASH,
alg );
if( status != PSA_SUCCESS )
goto exit;
if( ! PSA_KEY_TYPE_IS_KEY_PAIR( slot->attr.type ) )
{
status = PSA_ERROR_INVALID_ARGUMENT;
goto exit;
}
psa_key_attributes_t attributes = {
.core = slot->attr
};
if( input_is_message )
{
status = psa_driver_wrapper_sign_message(
&attributes, slot->key.data, slot->key.bytes,
alg, input, input_length,
signature, signature_size, signature_length );
}
else
{
status = psa_driver_wrapper_sign_hash(
&attributes, slot->key.data, slot->key.bytes,
alg, input, input_length,
signature, signature_size, signature_length );
}
exit:
/* Fill the unused part of the output buffer (the whole buffer on error,
* the trailing part on success) with something that isn't a valid signature
* (barring an attack on the signature and deliberately-crafted input),
* in case the caller doesn't check the return status properly. */
if( status == PSA_SUCCESS )
memset( signature + *signature_length, '!',
signature_size - *signature_length );
else
memset( signature, '!', signature_size );
/* If signature_size is 0 then we have nothing to do. We must not call
* memset because signature may be NULL in this case. */
unlock_status = psa_unlock_key_slot( slot );
return( ( status == PSA_SUCCESS ) ? unlock_status : status );
}
static psa_status_t psa_verify_internal( mbedtls_svc_key_id_t key,
int input_is_message,
psa_algorithm_t alg,
const uint8_t * input,
size_t input_length,
const uint8_t * signature,
size_t signature_length )
{
psa_status_t status = PSA_ERROR_CORRUPTION_DETECTED;
psa_status_t unlock_status = PSA_ERROR_CORRUPTION_DETECTED;
psa_key_slot_t *slot;
status = psa_sign_verify_check_alg( input_is_message, alg );
if( status != PSA_SUCCESS )
return status;
status = psa_get_and_lock_key_slot_with_policy(
key, &slot,
input_is_message ? PSA_KEY_USAGE_VERIFY_MESSAGE :
PSA_KEY_USAGE_VERIFY_HASH,
alg );
if( status != PSA_SUCCESS )
return( status );
psa_key_attributes_t attributes = {
.core = slot->attr
};
if( input_is_message )
{
status = psa_driver_wrapper_verify_message(
&attributes, slot->key.data, slot->key.bytes,
alg, input, input_length,
signature, signature_length );
}
else
{
status = psa_driver_wrapper_verify_hash(
&attributes, slot->key.data, slot->key.bytes,
alg, input, input_length,
signature, signature_length );
}
unlock_status = psa_unlock_key_slot( slot );
return( ( status == PSA_SUCCESS ) ? unlock_status : status );
}
psa_status_t psa_sign_message_builtin(
const psa_key_attributes_t *attributes,
const uint8_t *key_buffer,
size_t key_buffer_size,
psa_algorithm_t alg,
const uint8_t *input,
size_t input_length,
uint8_t *signature,
size_t signature_size,
size_t *signature_length )
{
psa_status_t status = PSA_ERROR_CORRUPTION_DETECTED;
if ( PSA_ALG_IS_HASH_AND_SIGN( alg ) )
{
size_t hash_length;
uint8_t hash[PSA_HASH_MAX_SIZE];
status = psa_driver_wrapper_hash_compute(
PSA_ALG_SIGN_GET_HASH( alg ),
input, input_length,
hash, sizeof( hash ), &hash_length );
if( status != PSA_SUCCESS )
return status;
return psa_driver_wrapper_sign_hash(
attributes, key_buffer, key_buffer_size,
alg, hash, hash_length,
signature, signature_size, signature_length );
}
return( PSA_ERROR_NOT_SUPPORTED );
}
psa_status_t psa_sign_message( mbedtls_svc_key_id_t key,
psa_algorithm_t alg,
const uint8_t * input,
size_t input_length,
uint8_t * signature,
size_t signature_size,
size_t * signature_length )
{
return psa_sign_internal(
key, 1, alg, input, input_length,
signature, signature_size, signature_length );
}
psa_status_t psa_verify_message_builtin(
const psa_key_attributes_t *attributes,
const uint8_t *key_buffer,
size_t key_buffer_size,
psa_algorithm_t alg,
const uint8_t *input,
size_t input_length,
const uint8_t *signature,
size_t signature_length )
{
psa_status_t status = PSA_ERROR_CORRUPTION_DETECTED;
if ( PSA_ALG_IS_HASH_AND_SIGN( alg ) )
{
size_t hash_length;
uint8_t hash[PSA_HASH_MAX_SIZE];
status = psa_driver_wrapper_hash_compute(
PSA_ALG_SIGN_GET_HASH( alg ),
input, input_length,
hash, sizeof( hash ), &hash_length );
if( status != PSA_SUCCESS )
return status;
return psa_driver_wrapper_verify_hash(
attributes, key_buffer, key_buffer_size,
alg, hash, hash_length,
signature, signature_length );
}
return( PSA_ERROR_NOT_SUPPORTED );
}
psa_status_t psa_verify_message( mbedtls_svc_key_id_t key,
psa_algorithm_t alg,
const uint8_t * input,
size_t input_length,
const uint8_t * signature,
size_t signature_length )
{
return psa_verify_internal(
key, 1, alg, input, input_length,
signature, signature_length );
}
psa_status_t psa_sign_hash_builtin(
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 )
{
if( attributes->core.type == PSA_KEY_TYPE_RSA_KEY_PAIR )
{
if( PSA_ALG_IS_RSA_PKCS1V15_SIGN( alg ) ||
PSA_ALG_IS_RSA_PSS( alg) )
{
#if defined(MBEDTLS_PSA_BUILTIN_ALG_RSA_PKCS1V15_SIGN) || \
defined(MBEDTLS_PSA_BUILTIN_ALG_RSA_PSS)
return( mbedtls_psa_rsa_sign_hash(
attributes,
key_buffer, key_buffer_size,
alg, hash, hash_length,
signature, signature_size, signature_length ) );
#endif /* defined(MBEDTLS_PSA_BUILTIN_ALG_RSA_PKCS1V15_SIGN) ||
* defined(MBEDTLS_PSA_BUILTIN_ALG_RSA_PSS) */
}
else
{
return( PSA_ERROR_INVALID_ARGUMENT );
}
}
else
if( PSA_KEY_TYPE_IS_ECC( attributes->core.type ) )
{
if( PSA_ALG_IS_ECDSA( alg ) )
{
#if defined(MBEDTLS_PSA_BUILTIN_ALG_ECDSA) || \
defined(MBEDTLS_PSA_BUILTIN_ALG_DETERMINISTIC_ECDSA)
return( mbedtls_psa_ecdsa_sign_hash(
attributes,
key_buffer, key_buffer_size,
alg, hash, hash_length,
signature, signature_size, signature_length ) );
#endif /* defined(MBEDTLS_PSA_BUILTIN_ALG_ECDSA) ||
* defined(MBEDTLS_PSA_BUILTIN_ALG_DETERMINISTIC_ECDSA) */
}
else
{
return( PSA_ERROR_INVALID_ARGUMENT );
}
}
(void)key_buffer;
(void)key_buffer_size;
(void)hash;
(void)hash_length;
(void)signature;
(void)signature_size;
(void)signature_length;
return( PSA_ERROR_NOT_SUPPORTED );
}
psa_status_t psa_sign_hash( mbedtls_svc_key_id_t key,
psa_algorithm_t alg,
const uint8_t *hash,
size_t hash_length,
uint8_t *signature,
size_t signature_size,
size_t *signature_length )
{
return psa_sign_internal(
key, 0, alg, hash, hash_length,
signature, signature_size, signature_length );
}
psa_status_t psa_verify_hash_builtin(
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 )
{
if( PSA_KEY_TYPE_IS_RSA( attributes->core.type ) )
{
if( PSA_ALG_IS_RSA_PKCS1V15_SIGN( alg ) ||
PSA_ALG_IS_RSA_PSS( alg) )
{
#if defined(MBEDTLS_PSA_BUILTIN_ALG_RSA_PKCS1V15_SIGN) || \
defined(MBEDTLS_PSA_BUILTIN_ALG_RSA_PSS)
return( mbedtls_psa_rsa_verify_hash(
attributes,
key_buffer, key_buffer_size,
alg, hash, hash_length,
signature, signature_length ) );
#endif /* defined(MBEDTLS_PSA_BUILTIN_ALG_RSA_PKCS1V15_SIGN) ||
* defined(MBEDTLS_PSA_BUILTIN_ALG_RSA_PSS) */
}
else
{
return( PSA_ERROR_INVALID_ARGUMENT );
}
}
else
if( PSA_KEY_TYPE_IS_ECC( attributes->core.type ) )
{
if( PSA_ALG_IS_ECDSA( alg ) )
{
#if defined(MBEDTLS_PSA_BUILTIN_ALG_ECDSA) || \
defined(MBEDTLS_PSA_BUILTIN_ALG_DETERMINISTIC_ECDSA)
return( mbedtls_psa_ecdsa_verify_hash(
attributes,
key_buffer, key_buffer_size,
alg, hash, hash_length,
signature, signature_length ) );
#endif /* defined(MBEDTLS_PSA_BUILTIN_ALG_ECDSA) ||
* defined(MBEDTLS_PSA_BUILTIN_ALG_DETERMINISTIC_ECDSA) */
}
else
{
return( PSA_ERROR_INVALID_ARGUMENT );
}
}
(void)key_buffer;
(void)key_buffer_size;
(void)hash;
(void)hash_length;
(void)signature;
(void)signature_length;
return( PSA_ERROR_NOT_SUPPORTED );
}
psa_status_t psa_verify_hash( mbedtls_svc_key_id_t key,
psa_algorithm_t alg,
const uint8_t *hash,
size_t hash_length,
const uint8_t *signature,
size_t signature_length )
{
return psa_verify_internal(
key, 0, alg, hash, hash_length,
signature, signature_length );
}
#if defined(MBEDTLS_PSA_BUILTIN_ALG_RSA_OAEP)
static void psa_rsa_oaep_set_padding_mode( psa_algorithm_t alg,
mbedtls_rsa_context *rsa )
{
psa_algorithm_t hash_alg = PSA_ALG_RSA_OAEP_GET_HASH( alg );
const mbedtls_md_info_t *md_info = mbedtls_md_info_from_psa( hash_alg );
mbedtls_md_type_t md_alg = mbedtls_md_get_type( md_info );
mbedtls_rsa_set_padding( rsa, MBEDTLS_RSA_PKCS_V21, md_alg );
}
#endif /* defined(MBEDTLS_PSA_BUILTIN_ALG_RSA_OAEP) */
psa_status_t psa_asymmetric_encrypt( mbedtls_svc_key_id_t key,
psa_algorithm_t alg,
const uint8_t *input,
size_t input_length,
const uint8_t *salt,
size_t salt_length,
uint8_t *output,
size_t output_size,
size_t *output_length )
{
psa_status_t status = PSA_ERROR_CORRUPTION_DETECTED;
psa_status_t unlock_status = PSA_ERROR_CORRUPTION_DETECTED;
psa_key_slot_t *slot;
(void) input;
(void) input_length;
(void) salt;
(void) output;
(void) output_size;
*output_length = 0;
if( ! PSA_ALG_IS_RSA_OAEP( alg ) && salt_length != 0 )
return( PSA_ERROR_INVALID_ARGUMENT );
status = psa_get_and_lock_transparent_key_slot_with_policy(
key, &slot, PSA_KEY_USAGE_ENCRYPT, alg );
if( status != PSA_SUCCESS )
return( status );
if( ! ( PSA_KEY_TYPE_IS_PUBLIC_KEY( slot->attr.type ) ||
PSA_KEY_TYPE_IS_KEY_PAIR( slot->attr.type ) ) )
{
status = PSA_ERROR_INVALID_ARGUMENT;
goto exit;
}
#if defined(MBEDTLS_PSA_BUILTIN_ALG_RSA_PKCS1V15_CRYPT) || \
defined(MBEDTLS_PSA_BUILTIN_ALG_RSA_OAEP)
if( PSA_KEY_TYPE_IS_RSA( slot->attr.type ) )
{
mbedtls_rsa_context *rsa = NULL;
status = mbedtls_psa_rsa_load_representation( slot->attr.type,
slot->key.data,
slot->key.bytes,
&rsa );
if( status != PSA_SUCCESS )
goto rsa_exit;
if( output_size < mbedtls_rsa_get_len( rsa ) )
{
status = PSA_ERROR_BUFFER_TOO_SMALL;
goto rsa_exit;
}
#if defined(MBEDTLS_PSA_BUILTIN_ALG_RSA_PKCS1V15_CRYPT)
if( alg == PSA_ALG_RSA_PKCS1V15_CRYPT )
{
status = mbedtls_to_psa_error(
mbedtls_rsa_pkcs1_encrypt( rsa,
mbedtls_psa_get_random,
MBEDTLS_PSA_RANDOM_STATE,
MBEDTLS_RSA_PUBLIC,
input_length,
input,
output ) );
}
else
#endif /* MBEDTLS_PSA_BUILTIN_ALG_RSA_PKCS1V15_CRYPT */
#if defined(MBEDTLS_PSA_BUILTIN_ALG_RSA_OAEP)
if( PSA_ALG_IS_RSA_OAEP( alg ) )
{
psa_rsa_oaep_set_padding_mode( alg, rsa );
status = mbedtls_to_psa_error(
mbedtls_rsa_rsaes_oaep_encrypt( rsa,
mbedtls_psa_get_random,
MBEDTLS_PSA_RANDOM_STATE,
MBEDTLS_RSA_PUBLIC,
salt, salt_length,
input_length,
input,
output ) );
}
else
#endif /* MBEDTLS_PSA_BUILTIN_ALG_RSA_OAEP */
{
status = PSA_ERROR_INVALID_ARGUMENT;
goto rsa_exit;
}
rsa_exit:
if( status == PSA_SUCCESS )
*output_length = mbedtls_rsa_get_len( rsa );
mbedtls_rsa_free( rsa );
mbedtls_free( rsa );
}
else
#endif /* defined(MBEDTLS_PSA_BUILTIN_ALG_RSA_PKCS1V15_CRYPT) ||
* defined(MBEDTLS_PSA_BUILTIN_ALG_RSA_OAEP) */
{
status = PSA_ERROR_NOT_SUPPORTED;
}
exit:
unlock_status = psa_unlock_key_slot( slot );
return( ( status == PSA_SUCCESS ) ? unlock_status : status );
}
psa_status_t psa_asymmetric_decrypt( mbedtls_svc_key_id_t key,
psa_algorithm_t alg,
const uint8_t *input,
size_t input_length,
const uint8_t *salt,
size_t salt_length,
uint8_t *output,
size_t output_size,
size_t *output_length )
{
psa_status_t status = PSA_ERROR_CORRUPTION_DETECTED;
psa_status_t unlock_status = PSA_ERROR_CORRUPTION_DETECTED;
psa_key_slot_t *slot;
(void) input;
(void) input_length;
(void) salt;
(void) output;
(void) output_size;
*output_length = 0;
if( ! PSA_ALG_IS_RSA_OAEP( alg ) && salt_length != 0 )
return( PSA_ERROR_INVALID_ARGUMENT );
status = psa_get_and_lock_transparent_key_slot_with_policy(
key, &slot, PSA_KEY_USAGE_DECRYPT, alg );
if( status != PSA_SUCCESS )
return( status );
if( ! PSA_KEY_TYPE_IS_KEY_PAIR( slot->attr.type ) )
{
status = PSA_ERROR_INVALID_ARGUMENT;
goto exit;
}
#if defined(MBEDTLS_PSA_BUILTIN_ALG_RSA_PKCS1V15_CRYPT) || \
defined(MBEDTLS_PSA_BUILTIN_ALG_RSA_OAEP)
if( slot->attr.type == PSA_KEY_TYPE_RSA_KEY_PAIR )
{
mbedtls_rsa_context *rsa = NULL;
status = mbedtls_psa_rsa_load_representation( slot->attr.type,
slot->key.data,
slot->key.bytes,
&rsa );
if( status != PSA_SUCCESS )
goto exit;
if( input_length != mbedtls_rsa_get_len( rsa ) )
{
status = PSA_ERROR_INVALID_ARGUMENT;
goto rsa_exit;
}
#if defined(MBEDTLS_PSA_BUILTIN_ALG_RSA_PKCS1V15_CRYPT)
if( alg == PSA_ALG_RSA_PKCS1V15_CRYPT )
{
status = mbedtls_to_psa_error(
mbedtls_rsa_pkcs1_decrypt( rsa,
mbedtls_psa_get_random,
MBEDTLS_PSA_RANDOM_STATE,
MBEDTLS_RSA_PRIVATE,
output_length,
input,
output,
output_size ) );
}
else
#endif /* MBEDTLS_PSA_BUILTIN_ALG_RSA_PKCS1V15_CRYPT */
#if defined(MBEDTLS_PSA_BUILTIN_ALG_RSA_OAEP)
if( PSA_ALG_IS_RSA_OAEP( alg ) )
{
psa_rsa_oaep_set_padding_mode( alg, rsa );
status = mbedtls_to_psa_error(
mbedtls_rsa_rsaes_oaep_decrypt( rsa,
mbedtls_psa_get_random,
MBEDTLS_PSA_RANDOM_STATE,
MBEDTLS_RSA_PRIVATE,
salt, salt_length,
output_length,
input,
output,
output_size ) );
}
else
#endif /* MBEDTLS_PSA_BUILTIN_ALG_RSA_OAEP */
{
status = PSA_ERROR_INVALID_ARGUMENT;
}
rsa_exit:
mbedtls_rsa_free( rsa );
mbedtls_free( rsa );
}
else
#endif /* defined(MBEDTLS_PSA_BUILTIN_ALG_RSA_PKCS1V15_CRYPT) ||
* defined(MBEDTLS_PSA_BUILTIN_ALG_RSA_OAEP) */
{
status = PSA_ERROR_NOT_SUPPORTED;
}
exit:
unlock_status = psa_unlock_key_slot( slot );
return( ( status == PSA_SUCCESS ) ? unlock_status : status );
}
/****************************************************************/
/* Symmetric cryptography */
/****************************************************************/
static psa_status_t psa_cipher_setup( psa_cipher_operation_t *operation,
mbedtls_svc_key_id_t key,
psa_algorithm_t alg,
mbedtls_operation_t cipher_operation )
{
psa_status_t status = PSA_ERROR_CORRUPTION_DETECTED;
psa_status_t unlock_status = PSA_ERROR_CORRUPTION_DETECTED;
psa_key_slot_t *slot = NULL;
psa_key_usage_t usage = ( cipher_operation == MBEDTLS_ENCRYPT ?
PSA_KEY_USAGE_ENCRYPT :
PSA_KEY_USAGE_DECRYPT );
/* A context must be freshly initialized before it can be set up. */
if( operation->id != 0 )
{
status = PSA_ERROR_BAD_STATE;
goto exit;
}
if( ! PSA_ALG_IS_CIPHER( alg ) )
{
status = PSA_ERROR_INVALID_ARGUMENT;
goto exit;
}
status = psa_get_and_lock_key_slot_with_policy( key, &slot, usage, alg );
if( status != PSA_SUCCESS )
goto exit;
/* Initialize the operation struct members, except for id. The id member
* is used to indicate to psa_cipher_abort that there are resources to free,
* so we only set it (in the driver wrapper) after resources have been
* allocated/initialized. */
operation->iv_set = 0;
if( alg == PSA_ALG_ECB_NO_PADDING )
operation->iv_required = 0;
else
operation->iv_required = 1;
operation->default_iv_length = PSA_CIPHER_IV_LENGTH( slot->attr.type, alg );
psa_key_attributes_t attributes = {
.core = slot->attr
};
/* Try doing the operation through a driver before using software fallback. */
if( cipher_operation == MBEDTLS_ENCRYPT )
status = psa_driver_wrapper_cipher_encrypt_setup( operation,
&attributes,
slot->key.data,
slot->key.bytes,
alg );
else
status = psa_driver_wrapper_cipher_decrypt_setup( operation,
&attributes,
slot->key.data,
slot->key.bytes,
alg );
exit:
if( status != PSA_SUCCESS )
psa_cipher_abort( operation );
unlock_status = psa_unlock_key_slot( slot );
return( ( status == PSA_SUCCESS ) ? unlock_status : status );
}
psa_status_t psa_cipher_encrypt_setup( psa_cipher_operation_t *operation,
mbedtls_svc_key_id_t key,
psa_algorithm_t alg )
{
return( psa_cipher_setup( operation, key, alg, MBEDTLS_ENCRYPT ) );
}
psa_status_t psa_cipher_decrypt_setup( psa_cipher_operation_t *operation,
mbedtls_svc_key_id_t key,
psa_algorithm_t alg )
{
return( psa_cipher_setup( operation, key, alg, MBEDTLS_DECRYPT ) );
}
psa_status_t psa_cipher_generate_iv( psa_cipher_operation_t *operation,
uint8_t *iv,
size_t iv_size,
size_t *iv_length )
{
psa_status_t status = PSA_ERROR_CORRUPTION_DETECTED;
*iv_length = 0;
if( operation->id == 0 )
{
status = PSA_ERROR_BAD_STATE;
goto exit;
}
if( operation->iv_set || ! operation->iv_required )
{
status = PSA_ERROR_BAD_STATE;
goto exit;
}
if( iv_size < operation->default_iv_length )
{
status = PSA_ERROR_BUFFER_TOO_SMALL;
goto exit;
}
status = psa_generate_random( iv, operation->default_iv_length );
if( status != PSA_SUCCESS )
goto exit;
status = psa_driver_wrapper_cipher_set_iv( operation,
iv,
operation->default_iv_length );
exit:
if( status == PSA_SUCCESS )
{
operation->iv_set = 1;
*iv_length = operation->default_iv_length;
}
else
psa_cipher_abort( operation );
return( status );
}
psa_status_t psa_cipher_set_iv( psa_cipher_operation_t *operation,
const uint8_t *iv,
size_t iv_length )
{
psa_status_t status = PSA_ERROR_CORRUPTION_DETECTED;
if( operation->id == 0 )
{
status = PSA_ERROR_BAD_STATE;
goto exit;
}
if( operation->iv_set || ! operation->iv_required )
{
status = PSA_ERROR_BAD_STATE;
goto exit;
}
if( iv_length > PSA_CIPHER_IV_MAX_SIZE )
{
status = PSA_ERROR_INVALID_ARGUMENT;
goto exit;
}
status = psa_driver_wrapper_cipher_set_iv( operation,
iv,
iv_length );
exit:
if( status == PSA_SUCCESS )
operation->iv_set = 1;
else
psa_cipher_abort( operation );
return( status );
}
psa_status_t psa_cipher_update( psa_cipher_operation_t *operation,
const uint8_t *input,
size_t input_length,
uint8_t *output,
size_t output_size,
size_t *output_length )
{
psa_status_t status = PSA_ERROR_CORRUPTION_DETECTED;
if( operation->id == 0 )
{
status = PSA_ERROR_BAD_STATE;
goto exit;
}
if( operation->iv_required && ! operation->iv_set )
{
status = PSA_ERROR_BAD_STATE;
goto exit;
}
status = psa_driver_wrapper_cipher_update( operation,
input,
input_length,
output,
output_size,
output_length );
exit:
if( status != PSA_SUCCESS )
psa_cipher_abort( operation );
return( status );
}
psa_status_t psa_cipher_finish( psa_cipher_operation_t *operation,
uint8_t *output,
size_t output_size,
size_t *output_length )
{
psa_status_t status = PSA_ERROR_GENERIC_ERROR;
if( operation->id == 0 )
{
status = PSA_ERROR_BAD_STATE;
goto exit;
}
if( operation->iv_required && ! operation->iv_set )
{
status = PSA_ERROR_BAD_STATE;
goto exit;
}
status = psa_driver_wrapper_cipher_finish( operation,
output,
output_size,
output_length );
exit:
if( status == PSA_SUCCESS )
return( psa_cipher_abort( operation ) );
else
{
*output_length = 0;
(void) psa_cipher_abort( operation );
return( status );
}
}
psa_status_t psa_cipher_abort( psa_cipher_operation_t *operation )
{
if( operation->id == 0 )
{
/* The object has (apparently) been initialized but it is not (yet)
* in use. It's ok to call abort on such an object, and there's
* nothing to do. */
return( PSA_SUCCESS );
}
psa_driver_wrapper_cipher_abort( operation );
operation->id = 0;
operation->iv_set = 0;
operation->iv_required = 0;
return( PSA_SUCCESS );
}
psa_status_t psa_cipher_encrypt( mbedtls_svc_key_id_t key,
psa_algorithm_t alg,
const uint8_t *input,
size_t input_length,
uint8_t *output,
size_t output_size,
size_t *output_length )
{
psa_status_t status = PSA_ERROR_CORRUPTION_DETECTED;
psa_status_t unlock_status = PSA_ERROR_CORRUPTION_DETECTED;
psa_key_slot_t *slot;
psa_key_type_t key_type;
size_t iv_length;
*output_length = 0;
if( ! PSA_ALG_IS_CIPHER( alg ) )
return( PSA_ERROR_INVALID_ARGUMENT );
status = psa_get_and_lock_key_slot_with_policy( key, &slot,
PSA_KEY_USAGE_ENCRYPT,
alg );
if( status != PSA_SUCCESS )
return( status );
psa_key_attributes_t attributes = {
.core = slot->attr
};
key_type = slot->attr.type;
iv_length = PSA_CIPHER_IV_LENGTH( key_type, alg );
if( iv_length > 0 )
{
if( output_size < iv_length )
{
status = PSA_ERROR_BUFFER_TOO_SMALL;
goto exit;
}
status = psa_generate_random( output, iv_length );
if( status != PSA_SUCCESS )
goto exit;
}
status = psa_driver_wrapper_cipher_encrypt(
&attributes, slot->key.data, slot->key.bytes,
alg, input, input_length,
output, output_size, output_length );
exit:
unlock_status = psa_unlock_key_slot( slot );
return( ( status == PSA_SUCCESS ) ? unlock_status : status );
}
psa_status_t psa_cipher_decrypt( mbedtls_svc_key_id_t key,
psa_algorithm_t alg,
const uint8_t *input,
size_t input_length,
uint8_t *output,
size_t output_size,
size_t *output_length )
{
psa_status_t status = PSA_ERROR_CORRUPTION_DETECTED;
psa_status_t unlock_status = PSA_ERROR_CORRUPTION_DETECTED;
psa_key_slot_t *slot;
*output_length = 0;
if( ! PSA_ALG_IS_CIPHER( alg ) )
return( PSA_ERROR_INVALID_ARGUMENT );
status = psa_get_and_lock_key_slot_with_policy( key, &slot,
PSA_KEY_USAGE_DECRYPT,
alg );
if( status != PSA_SUCCESS )
return( status );
psa_key_attributes_t attributes = {
.core = slot->attr
};
if( input_length < PSA_CIPHER_IV_LENGTH( slot->attr.type, alg ) )
{
status = PSA_ERROR_INVALID_ARGUMENT;
goto exit;
}
status = psa_driver_wrapper_cipher_decrypt(
&attributes, slot->key.data, slot->key.bytes,
alg, input, input_length,
output, output_size, output_length );
exit:
unlock_status = psa_unlock_key_slot( slot );
return( ( status == PSA_SUCCESS ) ? unlock_status : status );
}
/****************************************************************/
/* AEAD */
/****************************************************************/
psa_status_t psa_aead_encrypt( mbedtls_svc_key_id_t key,
psa_algorithm_t alg,
const uint8_t *nonce,
size_t nonce_length,
const uint8_t *additional_data,
size_t additional_data_length,
const uint8_t *plaintext,
size_t plaintext_length,
uint8_t *ciphertext,
size_t ciphertext_size,
size_t *ciphertext_length )
{
psa_status_t status = PSA_ERROR_CORRUPTION_DETECTED;
psa_key_slot_t *slot;
*ciphertext_length = 0;
if( !PSA_ALG_IS_AEAD( alg ) || PSA_ALG_IS_WILDCARD( alg ) )
return( PSA_ERROR_NOT_SUPPORTED );
status = psa_get_and_lock_key_slot_with_policy(
key, &slot, PSA_KEY_USAGE_ENCRYPT, alg );
if( status != PSA_SUCCESS )
return( status );
psa_key_attributes_t attributes = {
.core = slot->attr
};
status = psa_driver_wrapper_aead_encrypt(
&attributes, slot->key.data, slot->key.bytes,
alg,
nonce, nonce_length,
additional_data, additional_data_length,
plaintext, plaintext_length,
ciphertext, ciphertext_size, ciphertext_length );
if( status != PSA_SUCCESS && ciphertext_size != 0 )
memset( ciphertext, 0, ciphertext_size );
psa_unlock_key_slot( slot );
return( status );
}
psa_status_t psa_aead_decrypt( mbedtls_svc_key_id_t key,
psa_algorithm_t alg,
const uint8_t *nonce,
size_t nonce_length,
const uint8_t *additional_data,
size_t additional_data_length,
const uint8_t *ciphertext,
size_t ciphertext_length,
uint8_t *plaintext,
size_t plaintext_size,
size_t *plaintext_length )
{
psa_status_t status = PSA_ERROR_CORRUPTION_DETECTED;
psa_key_slot_t *slot;
*plaintext_length = 0;
if( !PSA_ALG_IS_AEAD( alg ) || PSA_ALG_IS_WILDCARD( alg ) )
return( PSA_ERROR_NOT_SUPPORTED );
status = psa_get_and_lock_key_slot_with_policy(
key, &slot, PSA_KEY_USAGE_DECRYPT, alg );
if( status != PSA_SUCCESS )
return( status );
psa_key_attributes_t attributes = {
.core = slot->attr
};
status = psa_driver_wrapper_aead_decrypt(
&attributes, slot->key.data, slot->key.bytes,
alg,
nonce, nonce_length,
additional_data, additional_data_length,
ciphertext, ciphertext_length,
plaintext, plaintext_size, plaintext_length );
if( status != PSA_SUCCESS && plaintext_size != 0 )
memset( plaintext, 0, plaintext_size );
psa_unlock_key_slot( slot );
return( status );
}
/****************************************************************/
/* Generators */
/****************************************************************/
#if defined(MBEDTLS_PSA_BUILTIN_ALG_HKDF) || \
defined(MBEDTLS_PSA_BUILTIN_ALG_TLS12_PRF) || \
defined(MBEDTLS_PSA_BUILTIN_ALG_TLS12_PSK_TO_MS)
#define AT_LEAST_ONE_BUILTIN_KDF
#endif /* At least one builtin KDF */
#if defined(MBEDTLS_PSA_BUILTIN_ALG_HKDF) || \
defined(MBEDTLS_PSA_BUILTIN_ALG_TLS12_PRF) || \
defined(MBEDTLS_PSA_BUILTIN_ALG_TLS12_PSK_TO_MS)
static psa_status_t psa_key_derivation_start_hmac(
psa_mac_operation_t *operation,
psa_algorithm_t hash_alg,
const uint8_t *hmac_key,
size_t hmac_key_length )
{
psa_status_t status = PSA_ERROR_CORRUPTION_DETECTED;
psa_key_attributes_t attributes = PSA_KEY_ATTRIBUTES_INIT;
psa_set_key_type( &attributes, PSA_KEY_TYPE_HMAC );
psa_set_key_bits( &attributes, PSA_BYTES_TO_BITS( hmac_key_length ) );
psa_set_key_usage_flags( &attributes, PSA_KEY_USAGE_SIGN_HASH );
operation->is_sign = 1;
operation->mac_size = PSA_HASH_LENGTH( hash_alg );
status = psa_driver_wrapper_mac_sign_setup( operation,
&attributes,
hmac_key, hmac_key_length,
PSA_ALG_HMAC( hash_alg ) );
psa_reset_key_attributes( &attributes );
return( status );
}
#endif /* KDF algorithms reliant on HMAC */
#define HKDF_STATE_INIT 0 /* no input yet */
#define HKDF_STATE_STARTED 1 /* got salt */
#define HKDF_STATE_KEYED 2 /* got key */
#define HKDF_STATE_OUTPUT 3 /* output started */
static psa_algorithm_t psa_key_derivation_get_kdf_alg(
const psa_key_derivation_operation_t *operation )
{
if ( PSA_ALG_IS_KEY_AGREEMENT( operation->alg ) )
return( PSA_ALG_KEY_AGREEMENT_GET_KDF( operation->alg ) );
else
return( operation->alg );
}
psa_status_t psa_key_derivation_abort( psa_key_derivation_operation_t *operation )
{
psa_status_t status = PSA_SUCCESS;
psa_algorithm_t kdf_alg = psa_key_derivation_get_kdf_alg( operation );
if( kdf_alg == 0 )
{
/* The object has (apparently) been initialized but it is not
* in use. It's ok to call abort on such an object, and there's
* nothing to do. */
}
else
#if defined(MBEDTLS_PSA_BUILTIN_ALG_HKDF)
if( PSA_ALG_IS_HKDF( kdf_alg ) )
{
mbedtls_free( operation->ctx.hkdf.info );
status = psa_mac_abort( &operation->ctx.hkdf.hmac );
}
else
#endif /* defined(MBEDTLS_PSA_BUILTIN_ALG_HKDF */
#if defined(MBEDTLS_PSA_BUILTIN_ALG_TLS12_PRF) || \
defined(MBEDTLS_PSA_BUILTIN_ALG_TLS12_PSK_TO_MS)
if( PSA_ALG_IS_TLS12_PRF( kdf_alg ) ||
/* TLS-1.2 PSK-to-MS KDF uses the same core as TLS-1.2 PRF */
PSA_ALG_IS_TLS12_PSK_TO_MS( kdf_alg ) )
{
if( operation->ctx.tls12_prf.secret != NULL )
{
mbedtls_platform_zeroize( operation->ctx.tls12_prf.secret,
operation->ctx.tls12_prf.secret_length );
mbedtls_free( operation->ctx.tls12_prf.secret );
}
if( operation->ctx.tls12_prf.seed != NULL )
{
mbedtls_platform_zeroize( operation->ctx.tls12_prf.seed,
operation->ctx.tls12_prf.seed_length );
mbedtls_free( operation->ctx.tls12_prf.seed );
}
if( operation->ctx.tls12_prf.label != NULL )
{
mbedtls_platform_zeroize( operation->ctx.tls12_prf.label,
operation->ctx.tls12_prf.label_length );
mbedtls_free( operation->ctx.tls12_prf.label );
}
status = PSA_SUCCESS;
/* We leave the fields Ai and output_block to be erased safely by the
* mbedtls_platform_zeroize() in the end of this function. */
}
else
#endif /* defined(MBEDTLS_PSA_BUILTIN_ALG_TLS12_PRF) ||
* defined(MBEDTLS_PSA_BUILTIN_ALG_TLS12_PSK_TO_MS) */
{
status = PSA_ERROR_BAD_STATE;
}
mbedtls_platform_zeroize( operation, sizeof( *operation ) );
return( status );
}
psa_status_t psa_key_derivation_get_capacity(const psa_key_derivation_operation_t *operation,
size_t *capacity)
{
if( operation->alg == 0 )
{
/* This is a blank key derivation operation. */
return( PSA_ERROR_BAD_STATE );
}
*capacity = operation->capacity;
return( PSA_SUCCESS );
}
psa_status_t psa_key_derivation_set_capacity( psa_key_derivation_operation_t *operation,
size_t capacity )
{
if( operation->alg == 0 )
return( PSA_ERROR_BAD_STATE );
if( capacity > operation->capacity )
return( PSA_ERROR_INVALID_ARGUMENT );
operation->capacity = capacity;
return( PSA_SUCCESS );
}
#if defined(MBEDTLS_PSA_BUILTIN_ALG_HKDF)
/* Read some bytes from an HKDF-based operation. This performs a chunk
* of the expand phase of the HKDF algorithm. */
static psa_status_t psa_key_derivation_hkdf_read( psa_hkdf_key_derivation_t *hkdf,
psa_algorithm_t hash_alg,
uint8_t *output,
size_t output_length )
{
uint8_t hash_length = PSA_HASH_LENGTH( hash_alg );
size_t hmac_output_length;
psa_status_t status;
if( hkdf->state < HKDF_STATE_KEYED || ! hkdf->info_set )
return( PSA_ERROR_BAD_STATE );
hkdf->state = HKDF_STATE_OUTPUT;
while( output_length != 0 )
{
/* Copy what remains of the current block */
uint8_t n = hash_length - hkdf->offset_in_block;
if( n > output_length )
n = (uint8_t) output_length;
memcpy( output, hkdf->output_block + hkdf->offset_in_block, n );
output += n;
output_length -= n;
hkdf->offset_in_block += n;
if( output_length == 0 )
break;
/* We can't be wanting more output after block 0xff, otherwise
* the capacity check in psa_key_derivation_output_bytes() would have
* prevented this call. It could happen only if the operation
* object was corrupted or if this function is called directly
* inside the library. */
if( hkdf->block_number == 0xff )
return( PSA_ERROR_BAD_STATE );
/* We need a new block */
++hkdf->block_number;
hkdf->offset_in_block = 0;
status = psa_key_derivation_start_hmac( &hkdf->hmac,
hash_alg,
hkdf->prk,
hash_length );
if( status != PSA_SUCCESS )
return( status );
if( hkdf->block_number != 1 )
{
status = psa_mac_update( &hkdf->hmac,
hkdf->output_block,
hash_length );
if( status != PSA_SUCCESS )
return( status );
}
status = psa_mac_update( &hkdf->hmac,
hkdf->info,
hkdf->info_length );
if( status != PSA_SUCCESS )
return( status );
status = psa_mac_update( &hkdf->hmac,
&hkdf->block_number, 1 );
if( status != PSA_SUCCESS )
return( status );
status = psa_mac_sign_finish( &hkdf->hmac,
hkdf->output_block,
sizeof( hkdf->output_block ),
&hmac_output_length );
if( status != PSA_SUCCESS )
return( status );
}
return( PSA_SUCCESS );
}
#endif /* MBEDTLS_PSA_BUILTIN_ALG_HKDF */
#if defined(MBEDTLS_PSA_BUILTIN_ALG_TLS12_PRF) || \
defined(MBEDTLS_PSA_BUILTIN_ALG_TLS12_PSK_TO_MS)
static psa_status_t psa_key_derivation_tls12_prf_generate_next_block(
psa_tls12_prf_key_derivation_t *tls12_prf,
psa_algorithm_t alg )
{
psa_algorithm_t hash_alg = PSA_ALG_HKDF_GET_HASH( alg );
uint8_t hash_length = PSA_HASH_LENGTH( hash_alg );
psa_mac_operation_t hmac = PSA_MAC_OPERATION_INIT;
size_t hmac_output_length;
psa_status_t status, cleanup_status;
/* We can't be wanting more output after block 0xff, otherwise
* the capacity check in psa_key_derivation_output_bytes() would have
* prevented this call. It could happen only if the operation
* object was corrupted or if this function is called directly
* inside the library. */
if( tls12_prf->block_number == 0xff )
return( PSA_ERROR_CORRUPTION_DETECTED );
/* We need a new block */
++tls12_prf->block_number;
tls12_prf->left_in_block = hash_length;
/* Recall the definition of the TLS-1.2-PRF from RFC 5246:
*
* PRF(secret, label, seed) = P_<hash>(secret, label + seed)
*
* P_hash(secret, seed) = HMAC_hash(secret, A(1) + seed) +
* HMAC_hash(secret, A(2) + seed) +
* HMAC_hash(secret, A(3) + seed) + ...
*
* A(0) = seed
* A(i) = HMAC_hash(secret, A(i-1))
*
* The `psa_tls12_prf_key_derivation` structure saves the block
* `HMAC_hash(secret, A(i) + seed)` from which the output
* is currently extracted as `output_block` and where i is
* `block_number`.
*/
status = psa_key_derivation_start_hmac( &hmac,
hash_alg,
tls12_prf->secret,
tls12_prf->secret_length );
if( status != PSA_SUCCESS )
goto cleanup;
/* Calculate A(i) where i = tls12_prf->block_number. */
if( tls12_prf->block_number == 1 )
{
/* A(1) = HMAC_hash(secret, A(0)), where A(0) = seed. (The RFC overloads
* the variable seed and in this instance means it in the context of the
* P_hash function, where seed = label + seed.) */
status = psa_mac_update( &hmac,
tls12_prf->label,
tls12_prf->label_length );
if( status != PSA_SUCCESS )
goto cleanup;
status = psa_mac_update( &hmac,
tls12_prf->seed,
tls12_prf->seed_length );
if( status != PSA_SUCCESS )
goto cleanup;
}
else
{
/* A(i) = HMAC_hash(secret, A(i-1)) */
status = psa_mac_update( &hmac, tls12_prf->Ai, hash_length );
if( status != PSA_SUCCESS )
goto cleanup;
}
status = psa_mac_sign_finish( &hmac,
tls12_prf->Ai, hash_length,
&hmac_output_length );
if( hmac_output_length != hash_length )
status = PSA_ERROR_CORRUPTION_DETECTED;
if( status != PSA_SUCCESS )
goto cleanup;
/* Calculate HMAC_hash(secret, A(i) + label + seed). */
status = psa_key_derivation_start_hmac( &hmac,
hash_alg,
tls12_prf->secret,
tls12_prf->secret_length );
if( status != PSA_SUCCESS )
goto cleanup;
status = psa_mac_update( &hmac, tls12_prf->Ai, hash_length );
if( status != PSA_SUCCESS )
goto cleanup;
status = psa_mac_update( &hmac, tls12_prf->label, tls12_prf->label_length );
if( status != PSA_SUCCESS )
goto cleanup;
status = psa_mac_update( &hmac, tls12_prf->seed, tls12_prf->seed_length );
if( status != PSA_SUCCESS )
goto cleanup;
status = psa_mac_sign_finish( &hmac,
tls12_prf->output_block, hash_length,
&hmac_output_length );
if( status != PSA_SUCCESS )
goto cleanup;
cleanup:
cleanup_status = psa_mac_abort( &hmac );
if( status == PSA_SUCCESS && cleanup_status != PSA_SUCCESS )
status = cleanup_status;
return( status );
}
static psa_status_t psa_key_derivation_tls12_prf_read(
psa_tls12_prf_key_derivation_t *tls12_prf,
psa_algorithm_t alg,
uint8_t *output,
size_t output_length )
{
psa_algorithm_t hash_alg = PSA_ALG_TLS12_PRF_GET_HASH( alg );
uint8_t hash_length = PSA_HASH_LENGTH( hash_alg );
psa_status_t status;
uint8_t offset, length;
switch( tls12_prf->state )
{
case PSA_TLS12_PRF_STATE_LABEL_SET:
tls12_prf->state = PSA_TLS12_PRF_STATE_OUTPUT;
break;
case PSA_TLS12_PRF_STATE_OUTPUT:
break;
default:
return( PSA_ERROR_BAD_STATE );
}
while( output_length != 0 )
{
/* Check if we have fully processed the current block. */
if( tls12_prf->left_in_block == 0 )
{
status = psa_key_derivation_tls12_prf_generate_next_block( tls12_prf,
alg );
if( status != PSA_SUCCESS )
return( status );
continue;
}
if( tls12_prf->left_in_block > output_length )
length = (uint8_t) output_length;
else
length = tls12_prf->left_in_block;
offset = hash_length - tls12_prf->left_in_block;
memcpy( output, tls12_prf->output_block + offset, length );
output += length;
output_length -= length;
tls12_prf->left_in_block -= length;
}
return( PSA_SUCCESS );
}
#endif /* MBEDTLS_PSA_BUILTIN_ALG_TLS12_PRF ||
* MBEDTLS_PSA_BUILTIN_ALG_TLS12_PSK_TO_MS */
psa_status_t psa_key_derivation_output_bytes(
psa_key_derivation_operation_t *operation,
uint8_t *output,
size_t output_length )
{
psa_status_t status;
psa_algorithm_t kdf_alg = psa_key_derivation_get_kdf_alg( operation );
if( operation->alg == 0 )
{
/* This is a blank operation. */
return( PSA_ERROR_BAD_STATE );
}
if( output_length > operation->capacity )
{
operation->capacity = 0;
/* Go through the error path to wipe all confidential data now
* that the operation object is useless. */
status = PSA_ERROR_INSUFFICIENT_DATA;
goto exit;
}
if( output_length == 0 && operation->capacity == 0 )
{
/* Edge case: this is a finished operation, and 0 bytes
* were requested. The right error in this case could
* be either INSUFFICIENT_CAPACITY or BAD_STATE. Return
* INSUFFICIENT_CAPACITY, which is right for a finished
* operation, for consistency with the case when
* output_length > 0. */
return( PSA_ERROR_INSUFFICIENT_DATA );
}
operation->capacity -= output_length;
#if defined(MBEDTLS_PSA_BUILTIN_ALG_HKDF)
if( PSA_ALG_IS_HKDF( kdf_alg ) )
{
psa_algorithm_t hash_alg = PSA_ALG_HKDF_GET_HASH( kdf_alg );
status = psa_key_derivation_hkdf_read( &operation->ctx.hkdf, hash_alg,
output, output_length );
}
else
#endif /* MBEDTLS_PSA_BUILTIN_ALG_HKDF */
#if defined(MBEDTLS_PSA_BUILTIN_ALG_TLS12_PRF) || \
defined(MBEDTLS_PSA_BUILTIN_ALG_TLS12_PSK_TO_MS)
if( PSA_ALG_IS_TLS12_PRF( kdf_alg ) ||
PSA_ALG_IS_TLS12_PSK_TO_MS( kdf_alg ) )
{
status = psa_key_derivation_tls12_prf_read( &operation->ctx.tls12_prf,
kdf_alg, output,
output_length );
}
else
#endif /* MBEDTLS_PSA_BUILTIN_ALG_TLS12_PRF ||
* MBEDTLS_PSA_BUILTIN_ALG_TLS12_PSK_TO_MS */
{
(void) kdf_alg;
return( PSA_ERROR_BAD_STATE );
}
exit:
if( status != PSA_SUCCESS )
{
/* Preserve the algorithm upon errors, but clear all sensitive state.
* This allows us to differentiate between exhausted operations and
* blank operations, so we can return PSA_ERROR_BAD_STATE on blank
* operations. */
psa_algorithm_t alg = operation->alg;
psa_key_derivation_abort( operation );
operation->alg = alg;
memset( output, '!', output_length );
}
return( status );
}
#if defined(MBEDTLS_PSA_BUILTIN_KEY_TYPE_DES)
static void psa_des_set_key_parity( uint8_t *data, size_t data_size )
{
if( data_size >= 8 )
mbedtls_des_key_set_parity( data );
if( data_size >= 16 )
mbedtls_des_key_set_parity( data + 8 );
if( data_size >= 24 )
mbedtls_des_key_set_parity( data + 16 );
}
#endif /* MBEDTLS_PSA_BUILTIN_KEY_TYPE_DES */
static psa_status_t psa_generate_derived_key_internal(
psa_key_slot_t *slot,
size_t bits,
psa_key_derivation_operation_t *operation )
{
uint8_t *data = NULL;
size_t bytes = PSA_BITS_TO_BYTES( bits );
psa_status_t status;
if( ! key_type_is_raw_bytes( slot->attr.type ) )
return( PSA_ERROR_INVALID_ARGUMENT );
if( bits % 8 != 0 )
return( PSA_ERROR_INVALID_ARGUMENT );
data = mbedtls_calloc( 1, bytes );
if( data == NULL )
return( PSA_ERROR_INSUFFICIENT_MEMORY );
status = psa_key_derivation_output_bytes( operation, data, bytes );
if( status != PSA_SUCCESS )
goto exit;
#if defined(MBEDTLS_PSA_BUILTIN_KEY_TYPE_DES)
if( slot->attr.type == PSA_KEY_TYPE_DES )
psa_des_set_key_parity( data, bytes );
#endif /* MBEDTLS_PSA_BUILTIN_KEY_TYPE_DES */
status = psa_allocate_buffer_to_slot( slot, bytes );
if( status != PSA_SUCCESS )
goto exit;
slot->attr.bits = (psa_key_bits_t) bits;
psa_key_attributes_t attributes = {
.core = slot->attr
};
status = psa_driver_wrapper_import_key( &attributes,
data, bytes,
slot->key.data,
slot->key.bytes,
&slot->key.bytes, &bits );
if( bits != slot->attr.bits )
status = PSA_ERROR_INVALID_ARGUMENT;
exit:
mbedtls_free( data );
return( status );
}
psa_status_t psa_key_derivation_output_key( const psa_key_attributes_t *attributes,
psa_key_derivation_operation_t *operation,
mbedtls_svc_key_id_t *key )
{
psa_status_t status;
psa_key_slot_t *slot = NULL;
psa_se_drv_table_entry_t *driver = NULL;
*key = MBEDTLS_SVC_KEY_ID_INIT;
/* Reject any attempt to create a zero-length key so that we don't
* risk tripping up later, e.g. on a malloc(0) that returns NULL. */
if( psa_get_key_bits( attributes ) == 0 )
return( PSA_ERROR_INVALID_ARGUMENT );
if( ! operation->can_output_key )
return( PSA_ERROR_NOT_PERMITTED );
status = psa_start_key_creation( PSA_KEY_CREATION_DERIVE, attributes,
&slot, &driver );
#if defined(MBEDTLS_PSA_CRYPTO_SE_C)
if( driver != NULL )
{
/* Deriving a key in a secure element is not implemented yet. */
status = PSA_ERROR_NOT_SUPPORTED;
}
#endif /* MBEDTLS_PSA_CRYPTO_SE_C */
if( status == PSA_SUCCESS )
{
status = psa_generate_derived_key_internal( slot,
attributes->core.bits,
operation );
}
if( status == PSA_SUCCESS )
status = psa_finish_key_creation( slot, driver, key );
if( status != PSA_SUCCESS )
psa_fail_key_creation( slot, driver );
return( status );
}
/****************************************************************/
/* Key derivation */
/****************************************************************/
#if defined(AT_LEAST_ONE_BUILTIN_KDF)
static psa_status_t psa_key_derivation_setup_kdf(
psa_key_derivation_operation_t *operation,
psa_algorithm_t kdf_alg )
{
int is_kdf_alg_supported;
/* Make sure that operation->ctx is properly zero-initialised. (Macro
* initialisers for this union leave some bytes unspecified.) */
memset( &operation->ctx, 0, sizeof( operation->ctx ) );
/* Make sure that kdf_alg is a supported key derivation algorithm. */
#if defined(MBEDTLS_PSA_BUILTIN_ALG_HKDF)
if( PSA_ALG_IS_HKDF( kdf_alg ) )
is_kdf_alg_supported = 1;
else
#endif
#if defined(MBEDTLS_PSA_BUILTIN_ALG_TLS12_PRF)
if( PSA_ALG_IS_TLS12_PRF( kdf_alg ) )
is_kdf_alg_supported = 1;
else
#endif
#if defined(MBEDTLS_PSA_BUILTIN_ALG_TLS12_PSK_TO_MS)
if( PSA_ALG_IS_TLS12_PSK_TO_MS( kdf_alg ) )
is_kdf_alg_supported = 1;
else
#endif
is_kdf_alg_supported = 0;
if( is_kdf_alg_supported )
{
psa_algorithm_t hash_alg = PSA_ALG_HKDF_GET_HASH( kdf_alg );
size_t hash_size = PSA_HASH_LENGTH( hash_alg );
if( hash_size == 0 )
return( PSA_ERROR_NOT_SUPPORTED );
if( ( PSA_ALG_IS_TLS12_PRF( kdf_alg ) ||
PSA_ALG_IS_TLS12_PSK_TO_MS( kdf_alg ) ) &&
! ( hash_alg == PSA_ALG_SHA_256 || hash_alg == PSA_ALG_SHA_384 ) )
{
return( PSA_ERROR_NOT_SUPPORTED );
}
operation->capacity = 255 * hash_size;
return( PSA_SUCCESS );
}
return( PSA_ERROR_NOT_SUPPORTED );
}
#endif /* AT_LEAST_ONE_BUILTIN_KDF */
psa_status_t psa_key_derivation_setup( psa_key_derivation_operation_t *operation,
psa_algorithm_t alg )
{
psa_status_t status;
if( operation->alg != 0 )
return( PSA_ERROR_BAD_STATE );
if( PSA_ALG_IS_RAW_KEY_AGREEMENT( alg ) )
return( PSA_ERROR_INVALID_ARGUMENT );
else if( PSA_ALG_IS_KEY_AGREEMENT( alg ) )
{
#if defined(AT_LEAST_ONE_BUILTIN_KDF)
psa_algorithm_t kdf_alg = PSA_ALG_KEY_AGREEMENT_GET_KDF( alg );
status = psa_key_derivation_setup_kdf( operation, kdf_alg );
#else
return( PSA_ERROR_NOT_SUPPORTED );
#endif /* AT_LEAST_ONE_BUILTIN_KDF */
}
else if( PSA_ALG_IS_KEY_DERIVATION( alg ) )
{
#if defined(AT_LEAST_ONE_BUILTIN_KDF)
status = psa_key_derivation_setup_kdf( operation, alg );
#else
return( PSA_ERROR_NOT_SUPPORTED );
#endif /* AT_LEAST_ONE_BUILTIN_KDF */
}
else
return( PSA_ERROR_INVALID_ARGUMENT );
if( status == PSA_SUCCESS )
operation->alg = alg;
return( status );
}
#if defined(MBEDTLS_PSA_BUILTIN_ALG_HKDF)
static psa_status_t psa_hkdf_input( psa_hkdf_key_derivation_t *hkdf,
psa_algorithm_t hash_alg,
psa_key_derivation_step_t step,
const uint8_t *data,
size_t data_length )
{
psa_status_t status;
switch( step )
{
case PSA_KEY_DERIVATION_INPUT_SALT:
if( hkdf->state != HKDF_STATE_INIT )
return( PSA_ERROR_BAD_STATE );
else
{
status = psa_key_derivation_start_hmac( &hkdf->hmac,
hash_alg,
data, data_length );
if( status != PSA_SUCCESS )
return( status );
hkdf->state = HKDF_STATE_STARTED;
return( PSA_SUCCESS );
}
case PSA_KEY_DERIVATION_INPUT_SECRET:
/* If no salt was provided, use an empty salt. */
if( hkdf->state == HKDF_STATE_INIT )
{
status = psa_key_derivation_start_hmac( &hkdf->hmac,
hash_alg,
NULL, 0 );
if( status != PSA_SUCCESS )
return( status );
hkdf->state = HKDF_STATE_STARTED;
}
if( hkdf->state != HKDF_STATE_STARTED )
return( PSA_ERROR_BAD_STATE );
status = psa_mac_update( &hkdf->hmac,
data, data_length );
if( status != PSA_SUCCESS )
return( status );
status = psa_mac_sign_finish( &hkdf->hmac,
hkdf->prk,
sizeof( hkdf->prk ),
&data_length );
if( status != PSA_SUCCESS )
return( status );
hkdf->offset_in_block = PSA_HASH_LENGTH( hash_alg );
hkdf->block_number = 0;
hkdf->state = HKDF_STATE_KEYED;
return( PSA_SUCCESS );
case PSA_KEY_DERIVATION_INPUT_INFO:
if( hkdf->state == HKDF_STATE_OUTPUT )
return( PSA_ERROR_BAD_STATE );
if( hkdf->info_set )
return( PSA_ERROR_BAD_STATE );
hkdf->info_length = data_length;
if( data_length != 0 )
{
hkdf->info = mbedtls_calloc( 1, data_length );
if( hkdf->info == NULL )
return( PSA_ERROR_INSUFFICIENT_MEMORY );
memcpy( hkdf->info, data, data_length );
}
hkdf->info_set = 1;
return( PSA_SUCCESS );
default:
return( PSA_ERROR_INVALID_ARGUMENT );
}
}
#endif /* MBEDTLS_PSA_BUILTIN_ALG_HKDF */
#if defined(MBEDTLS_PSA_BUILTIN_ALG_TLS12_PRF) || \
defined(MBEDTLS_PSA_BUILTIN_ALG_TLS12_PSK_TO_MS)
static psa_status_t psa_tls12_prf_set_seed( psa_tls12_prf_key_derivation_t *prf,
const uint8_t *data,
size_t data_length )
{
if( prf->state != PSA_TLS12_PRF_STATE_INIT )
return( PSA_ERROR_BAD_STATE );
if( data_length != 0 )
{
prf->seed = mbedtls_calloc( 1, data_length );
if( prf->seed == NULL )
return( PSA_ERROR_INSUFFICIENT_MEMORY );
memcpy( prf->seed, data, data_length );
prf->seed_length = data_length;
}
prf->state = PSA_TLS12_PRF_STATE_SEED_SET;
return( PSA_SUCCESS );
}
static psa_status_t psa_tls12_prf_set_key( psa_tls12_prf_key_derivation_t *prf,
const uint8_t *data,
size_t data_length )
{
if( prf->state != PSA_TLS12_PRF_STATE_SEED_SET )
return( PSA_ERROR_BAD_STATE );
if( data_length != 0 )
{
prf->secret = mbedtls_calloc( 1, data_length );
if( prf->secret == NULL )
return( PSA_ERROR_INSUFFICIENT_MEMORY );
memcpy( prf->secret, data, data_length );
prf->secret_length = data_length;
}
prf->state = PSA_TLS12_PRF_STATE_KEY_SET;
return( PSA_SUCCESS );
}
static psa_status_t psa_tls12_prf_set_label( psa_tls12_prf_key_derivation_t *prf,
const uint8_t *data,
size_t data_length )
{
if( prf->state != PSA_TLS12_PRF_STATE_KEY_SET )
return( PSA_ERROR_BAD_STATE );
if( data_length != 0 )
{
prf->label = mbedtls_calloc( 1, data_length );
if( prf->label == NULL )
return( PSA_ERROR_INSUFFICIENT_MEMORY );
memcpy( prf->label, data, data_length );
prf->label_length = data_length;
}
prf->state = PSA_TLS12_PRF_STATE_LABEL_SET;
return( PSA_SUCCESS );
}
static psa_status_t psa_tls12_prf_input( psa_tls12_prf_key_derivation_t *prf,
psa_key_derivation_step_t step,
const uint8_t *data,
size_t data_length )
{
switch( step )
{
case PSA_KEY_DERIVATION_INPUT_SEED:
return( psa_tls12_prf_set_seed( prf, data, data_length ) );
case PSA_KEY_DERIVATION_INPUT_SECRET:
return( psa_tls12_prf_set_key( prf, data, data_length ) );
case PSA_KEY_DERIVATION_INPUT_LABEL:
return( psa_tls12_prf_set_label( prf, data, data_length ) );
default:
return( PSA_ERROR_INVALID_ARGUMENT );
}
}
#endif /* MBEDTLS_PSA_BUILTIN_ALG_TLS12_PRF) ||
* MBEDTLS_PSA_BUILTIN_ALG_TLS12_PSK_TO_MS */
#if defined(MBEDTLS_PSA_BUILTIN_ALG_TLS12_PSK_TO_MS)
static psa_status_t psa_tls12_prf_psk_to_ms_set_key(
psa_tls12_prf_key_derivation_t *prf,
const uint8_t *data,
size_t data_length )
{
psa_status_t status;
uint8_t pms[ 4 + 2 * PSA_TLS12_PSK_TO_MS_PSK_MAX_SIZE ];
uint8_t *cur = pms;
if( data_length > PSA_TLS12_PSK_TO_MS_PSK_MAX_SIZE )
return( PSA_ERROR_INVALID_ARGUMENT );
/* Quoting RFC 4279, Section 2:
*
* The premaster secret is formed as follows: if the PSK is N octets
* long, concatenate a uint16 with the value N, N zero octets, a second
* uint16 with the value N, and the PSK itself.
*/
*cur++ = ( data_length >> 8 ) & 0xff;
*cur++ = ( data_length >> 0 ) & 0xff;
memset( cur, 0, data_length );
cur += data_length;
*cur++ = pms[0];
*cur++ = pms[1];
memcpy( cur, data, data_length );
cur += data_length;
status = psa_tls12_prf_set_key( prf, pms, cur - pms );
mbedtls_platform_zeroize( pms, sizeof( pms ) );
return( status );
}
static psa_status_t psa_tls12_prf_psk_to_ms_input(
psa_tls12_prf_key_derivation_t *prf,
psa_key_derivation_step_t step,
const uint8_t *data,
size_t data_length )
{
if( step == PSA_KEY_DERIVATION_INPUT_SECRET )
{
return( psa_tls12_prf_psk_to_ms_set_key( prf,
data, data_length ) );
}
return( psa_tls12_prf_input( prf, step, data, data_length ) );
}
#endif /* MBEDTLS_PSA_BUILTIN_ALG_TLS12_PSK_TO_MS */
/** Check whether the given key type is acceptable for the given
* input step of a key derivation.
*
* Secret inputs must have the type #PSA_KEY_TYPE_DERIVE.
* Non-secret inputs must have the type #PSA_KEY_TYPE_RAW_DATA.
* Both secret and non-secret inputs can alternatively have the type
* #PSA_KEY_TYPE_NONE, which is never the type of a key object, meaning
* that the input was passed as a buffer rather than via a key object.
*/
static int psa_key_derivation_check_input_type(
psa_key_derivation_step_t step,
psa_key_type_t key_type )
{
switch( step )
{
case PSA_KEY_DERIVATION_INPUT_SECRET:
if( key_type == PSA_KEY_TYPE_DERIVE )
return( PSA_SUCCESS );
if( key_type == PSA_KEY_TYPE_NONE )
return( PSA_SUCCESS );
break;
case PSA_KEY_DERIVATION_INPUT_LABEL:
case PSA_KEY_DERIVATION_INPUT_SALT:
case PSA_KEY_DERIVATION_INPUT_INFO:
case PSA_KEY_DERIVATION_INPUT_SEED:
if( key_type == PSA_KEY_TYPE_RAW_DATA )
return( PSA_SUCCESS );
if( key_type == PSA_KEY_TYPE_NONE )
return( PSA_SUCCESS );
break;
}
return( PSA_ERROR_INVALID_ARGUMENT );
}
static psa_status_t psa_key_derivation_input_internal(
psa_key_derivation_operation_t *operation,
psa_key_derivation_step_t step,
psa_key_type_t key_type,
const uint8_t *data,
size_t data_length )
{
psa_status_t status;
psa_algorithm_t kdf_alg = psa_key_derivation_get_kdf_alg( operation );
status = psa_key_derivation_check_input_type( step, key_type );
if( status != PSA_SUCCESS )
goto exit;
#if defined(MBEDTLS_PSA_BUILTIN_ALG_HKDF)
if( PSA_ALG_IS_HKDF( kdf_alg ) )
{
status = psa_hkdf_input( &operation->ctx.hkdf,
PSA_ALG_HKDF_GET_HASH( kdf_alg ),
step, data, data_length );
}
else
#endif /* MBEDTLS_PSA_BUILTIN_ALG_HKDF */
#if defined(MBEDTLS_PSA_BUILTIN_ALG_TLS12_PRF)
if( PSA_ALG_IS_TLS12_PRF( kdf_alg ) )
{
status = psa_tls12_prf_input( &operation->ctx.tls12_prf,
step, data, data_length );
}
else
#endif /* MBEDTLS_PSA_BUILTIN_ALG_TLS12_PRF */
#if defined(MBEDTLS_PSA_BUILTIN_ALG_TLS12_PSK_TO_MS)
if( PSA_ALG_IS_TLS12_PSK_TO_MS( kdf_alg ) )
{
status = psa_tls12_prf_psk_to_ms_input( &operation->ctx.tls12_prf,
step, data, data_length );
}
else
#endif /* MBEDTLS_PSA_BUILTIN_ALG_TLS12_PSK_TO_MS */
{
/* This can't happen unless the operation object was not initialized */
(void) data;
(void) data_length;
(void) kdf_alg;
return( PSA_ERROR_BAD_STATE );
}
exit:
if( status != PSA_SUCCESS )
psa_key_derivation_abort( operation );
return( status );
}
psa_status_t psa_key_derivation_input_bytes(
psa_key_derivation_operation_t *operation,
psa_key_derivation_step_t step,
const uint8_t *data,
size_t data_length )
{
return( psa_key_derivation_input_internal( operation, step,
PSA_KEY_TYPE_NONE,
data, data_length ) );
}
psa_status_t psa_key_derivation_input_key(
psa_key_derivation_operation_t *operation,
psa_key_derivation_step_t step,
mbedtls_svc_key_id_t key )
{
psa_status_t status = PSA_ERROR_CORRUPTION_DETECTED;
psa_status_t unlock_status = PSA_ERROR_CORRUPTION_DETECTED;
psa_key_slot_t *slot;
status = psa_get_and_lock_transparent_key_slot_with_policy(
key, &slot, PSA_KEY_USAGE_DERIVE, operation->alg );
if( status != PSA_SUCCESS )
{
psa_key_derivation_abort( operation );
return( status );
}
/* Passing a key object as a SECRET input unlocks the permission
* to output to a key object. */
if( step == PSA_KEY_DERIVATION_INPUT_SECRET )
operation->can_output_key = 1;
status = psa_key_derivation_input_internal( operation,
step, slot->attr.type,
slot->key.data,
slot->key.bytes );
unlock_status = psa_unlock_key_slot( slot );
return( ( status == PSA_SUCCESS ) ? unlock_status : status );
}
/****************************************************************/
/* Key agreement */
/****************************************************************/
#if defined(MBEDTLS_PSA_BUILTIN_ALG_ECDH)
static psa_status_t psa_key_agreement_ecdh( const uint8_t *peer_key,
size_t peer_key_length,
const mbedtls_ecp_keypair *our_key,
uint8_t *shared_secret,
size_t shared_secret_size,
size_t *shared_secret_length )
{
mbedtls_ecp_keypair *their_key = NULL;
mbedtls_ecdh_context ecdh;
psa_status_t status;
size_t bits = 0;
psa_ecc_family_t curve = mbedtls_ecc_group_to_psa( our_key->grp.id, &bits );
mbedtls_ecdh_init( &ecdh );
status = mbedtls_psa_ecp_load_representation(
PSA_KEY_TYPE_ECC_PUBLIC_KEY(curve),
bits,
peer_key,
peer_key_length,
&their_key );
if( status != PSA_SUCCESS )
goto exit;
status = mbedtls_to_psa_error(
mbedtls_ecdh_get_params( &ecdh, their_key, MBEDTLS_ECDH_THEIRS ) );
if( status != PSA_SUCCESS )
goto exit;
status = mbedtls_to_psa_error(
mbedtls_ecdh_get_params( &ecdh, our_key, MBEDTLS_ECDH_OURS ) );
if( status != PSA_SUCCESS )
goto exit;
status = mbedtls_to_psa_error(
mbedtls_ecdh_calc_secret( &ecdh,
shared_secret_length,
shared_secret, shared_secret_size,
mbedtls_psa_get_random,
MBEDTLS_PSA_RANDOM_STATE ) );
if( status != PSA_SUCCESS )
goto exit;
if( PSA_BITS_TO_BYTES( bits ) != *shared_secret_length )
status = PSA_ERROR_CORRUPTION_DETECTED;
exit:
if( status != PSA_SUCCESS )
mbedtls_platform_zeroize( shared_secret, shared_secret_size );
mbedtls_ecdh_free( &ecdh );
mbedtls_ecp_keypair_free( their_key );
mbedtls_free( their_key );
return( status );
}
#endif /* MBEDTLS_PSA_BUILTIN_ALG_ECDH */
#define PSA_KEY_AGREEMENT_MAX_SHARED_SECRET_SIZE MBEDTLS_ECP_MAX_BYTES
static psa_status_t psa_key_agreement_raw_internal( psa_algorithm_t alg,
psa_key_slot_t *private_key,
const uint8_t *peer_key,
size_t peer_key_length,
uint8_t *shared_secret,
size_t shared_secret_size,
size_t *shared_secret_length )
{
switch( alg )
{
#if defined(MBEDTLS_PSA_BUILTIN_ALG_ECDH)
case PSA_ALG_ECDH:
if( ! PSA_KEY_TYPE_IS_ECC_KEY_PAIR( private_key->attr.type ) )
return( PSA_ERROR_INVALID_ARGUMENT );
mbedtls_ecp_keypair *ecp = NULL;
psa_status_t status = mbedtls_psa_ecp_load_representation(
private_key->attr.type,
private_key->attr.bits,
private_key->key.data,
private_key->key.bytes,
&ecp );
if( status != PSA_SUCCESS )
return( status );
status = psa_key_agreement_ecdh( peer_key, peer_key_length,
ecp,
shared_secret, shared_secret_size,
shared_secret_length );
mbedtls_ecp_keypair_free( ecp );
mbedtls_free( ecp );
return( status );
#endif /* MBEDTLS_PSA_BUILTIN_ALG_ECDH */
default:
(void) private_key;
(void) peer_key;
(void) peer_key_length;
(void) shared_secret;
(void) shared_secret_size;
(void) shared_secret_length;
return( PSA_ERROR_NOT_SUPPORTED );
}
}
/* Note that if this function fails, you must call psa_key_derivation_abort()
* to potentially free embedded data structures and wipe confidential data.
*/
static psa_status_t psa_key_agreement_internal( psa_key_derivation_operation_t *operation,
psa_key_derivation_step_t step,
psa_key_slot_t *private_key,
const uint8_t *peer_key,
size_t peer_key_length )
{
psa_status_t status;
uint8_t shared_secret[PSA_KEY_AGREEMENT_MAX_SHARED_SECRET_SIZE];
size_t shared_secret_length = 0;
psa_algorithm_t ka_alg = PSA_ALG_KEY_AGREEMENT_GET_BASE( operation->alg );
/* Step 1: run the secret agreement algorithm to generate the shared
* secret. */
status = psa_key_agreement_raw_internal( ka_alg,
private_key,
peer_key, peer_key_length,
shared_secret,
sizeof( shared_secret ),
&shared_secret_length );
if( status != PSA_SUCCESS )
goto exit;
/* Step 2: set up the key derivation to generate key material from
* the shared secret. A shared secret is permitted wherever a key
* of type DERIVE is permitted. */
status = psa_key_derivation_input_internal( operation, step,
PSA_KEY_TYPE_DERIVE,
shared_secret,
shared_secret_length );
exit:
mbedtls_platform_zeroize( shared_secret, shared_secret_length );
return( status );
}
psa_status_t psa_key_derivation_key_agreement( psa_key_derivation_operation_t *operation,
psa_key_derivation_step_t step,
mbedtls_svc_key_id_t private_key,
const uint8_t *peer_key,
size_t peer_key_length )
{
psa_status_t status = PSA_ERROR_CORRUPTION_DETECTED;
psa_status_t unlock_status = PSA_ERROR_CORRUPTION_DETECTED;
psa_key_slot_t *slot;
if( ! PSA_ALG_IS_KEY_AGREEMENT( operation->alg ) )
return( PSA_ERROR_INVALID_ARGUMENT );
status = psa_get_and_lock_transparent_key_slot_with_policy(
private_key, &slot, PSA_KEY_USAGE_DERIVE, operation->alg );
if( status != PSA_SUCCESS )
return( status );
status = psa_key_agreement_internal( operation, step,
slot,
peer_key, peer_key_length );
if( status != PSA_SUCCESS )
psa_key_derivation_abort( operation );
else
{
/* If a private key has been added as SECRET, we allow the derived
* key material to be used as a key in PSA Crypto. */
if( step == PSA_KEY_DERIVATION_INPUT_SECRET )
operation->can_output_key = 1;
}
unlock_status = psa_unlock_key_slot( slot );
return( ( status == PSA_SUCCESS ) ? unlock_status : status );
}
psa_status_t psa_raw_key_agreement( psa_algorithm_t alg,
mbedtls_svc_key_id_t private_key,
const uint8_t *peer_key,
size_t peer_key_length,
uint8_t *output,
size_t output_size,
size_t *output_length )
{
psa_status_t status = PSA_ERROR_CORRUPTION_DETECTED;
psa_status_t unlock_status = PSA_ERROR_CORRUPTION_DETECTED;
psa_key_slot_t *slot = NULL;
if( ! PSA_ALG_IS_KEY_AGREEMENT( alg ) )
{
status = PSA_ERROR_INVALID_ARGUMENT;
goto exit;
}
status = psa_get_and_lock_transparent_key_slot_with_policy(
private_key, &slot, PSA_KEY_USAGE_DERIVE, alg );
if( status != PSA_SUCCESS )
goto exit;
status = psa_key_agreement_raw_internal( alg, slot,
peer_key, peer_key_length,
output, output_size,
output_length );
exit:
if( status != PSA_SUCCESS )
{
/* If an error happens and is not handled properly, the output
* may be used as a key to protect sensitive data. Arrange for such
* a key to be random, which is likely to result in decryption or
* verification errors. This is better than filling the buffer with
* some constant data such as zeros, which would result in the data
* being protected with a reproducible, easily knowable key.
*/
psa_generate_random( output, output_size );
*output_length = output_size;
}
unlock_status = psa_unlock_key_slot( slot );
return( ( status == PSA_SUCCESS ) ? unlock_status : status );
}
/****************************************************************/
/* Random generation */
/****************************************************************/
/** Initialize the PSA random generator.
*/
static void mbedtls_psa_random_init( mbedtls_psa_random_context_t *rng )
{
#if defined(MBEDTLS_PSA_CRYPTO_EXTERNAL_RNG)
memset( rng, 0, sizeof( *rng ) );
#else /* MBEDTLS_PSA_CRYPTO_EXTERNAL_RNG */
/* Set default configuration if
* mbedtls_psa_crypto_configure_entropy_sources() hasn't been called. */
if( rng->entropy_init == NULL )
rng->entropy_init = mbedtls_entropy_init;
if( rng->entropy_free == NULL )
rng->entropy_free = mbedtls_entropy_free;
rng->entropy_init( &rng->entropy );
#if defined(MBEDTLS_PSA_INJECT_ENTROPY) && \
defined(MBEDTLS_NO_DEFAULT_ENTROPY_SOURCES)
/* The PSA entropy injection feature depends on using NV seed as an entropy
* source. Add NV seed as an entropy source for PSA entropy injection. */
mbedtls_entropy_add_source( &rng->entropy,
mbedtls_nv_seed_poll, NULL,
MBEDTLS_ENTROPY_BLOCK_SIZE,
MBEDTLS_ENTROPY_SOURCE_STRONG );
#endif
mbedtls_psa_drbg_init( MBEDTLS_PSA_RANDOM_STATE );
#endif /* MBEDTLS_PSA_CRYPTO_EXTERNAL_RNG */
}
/** Deinitialize the PSA random generator.
*/
static void mbedtls_psa_random_free( mbedtls_psa_random_context_t *rng )
{
#if defined(MBEDTLS_PSA_CRYPTO_EXTERNAL_RNG)
memset( rng, 0, sizeof( *rng ) );
#else /* MBEDTLS_PSA_CRYPTO_EXTERNAL_RNG */
mbedtls_psa_drbg_free( MBEDTLS_PSA_RANDOM_STATE );
rng->entropy_free( &rng->entropy );
#endif /* MBEDTLS_PSA_CRYPTO_EXTERNAL_RNG */
}
/** Seed the PSA random generator.
*/
static psa_status_t mbedtls_psa_random_seed( mbedtls_psa_random_context_t *rng )
{
#if defined(MBEDTLS_PSA_CRYPTO_EXTERNAL_RNG)
/* Do nothing: the external RNG seeds itself. */
(void) rng;
return( PSA_SUCCESS );
#else /* MBEDTLS_PSA_CRYPTO_EXTERNAL_RNG */
const unsigned char drbg_seed[] = "PSA";
int ret = mbedtls_psa_drbg_seed( &rng->entropy,
drbg_seed, sizeof( drbg_seed ) - 1 );
return mbedtls_to_psa_error( ret );
#endif /* MBEDTLS_PSA_CRYPTO_EXTERNAL_RNG */
}
psa_status_t psa_generate_random( uint8_t *output,
size_t output_size )
{
GUARD_MODULE_INITIALIZED;
#if defined(MBEDTLS_PSA_CRYPTO_EXTERNAL_RNG)
size_t output_length = 0;
psa_status_t status = mbedtls_psa_external_get_random( &global_data.rng,
output, output_size,
&output_length );
if( status != PSA_SUCCESS )
return( status );
/* Breaking up a request into smaller chunks is currently not supported
* for the extrernal RNG interface. */
if( output_length != output_size )
return( PSA_ERROR_INSUFFICIENT_ENTROPY );
return( PSA_SUCCESS );
#else /* MBEDTLS_PSA_CRYPTO_EXTERNAL_RNG */
while( output_size > 0 )
{
size_t request_size =
( output_size > MBEDTLS_PSA_RANDOM_MAX_REQUEST ?
MBEDTLS_PSA_RANDOM_MAX_REQUEST :
output_size );
int ret = mbedtls_psa_get_random( MBEDTLS_PSA_RANDOM_STATE,
output, request_size );
if( ret != 0 )
return( mbedtls_to_psa_error( ret ) );
output_size -= request_size;
output += request_size;
}
return( PSA_SUCCESS );
#endif /* MBEDTLS_PSA_CRYPTO_EXTERNAL_RNG */
}
/* Wrapper function allowing the classic API to use the PSA RNG.
*
* `mbedtls_psa_get_random(MBEDTLS_PSA_RANDOM_STATE, ...)` calls
* `psa_generate_random(...)`. The state parameter is ignored since the
* PSA API doesn't support passing an explicit state.
*
* In the non-external case, psa_generate_random() calls an
* `mbedtls_xxx_drbg_random` function which has exactly the same signature
* and semantics as mbedtls_psa_get_random(). As an optimization,
* instead of doing this back-and-forth between the PSA API and the
* classic API, psa_crypto_random_impl.h defines `mbedtls_psa_get_random`
* as a constant function pointer to `mbedtls_xxx_drbg_random`.
*/
#if defined (MBEDTLS_PSA_CRYPTO_EXTERNAL_RNG)
int mbedtls_psa_get_random( void *p_rng,
unsigned char *output,
size_t output_size )
{
/* This function takes a pointer to the RNG state because that's what
* classic mbedtls functions using an RNG expect. The PSA RNG manages
* its own state internally and doesn't let the caller access that state.
* So we just ignore the state parameter, and in practice we'll pass
* NULL. */
(void) p_rng;
psa_status_t status = psa_generate_random( output, output_size );
if( status == PSA_SUCCESS )
return( 0 );
else
return( MBEDTLS_ERR_ENTROPY_SOURCE_FAILED );
}
#endif /* MBEDTLS_PSA_CRYPTO_EXTERNAL_RNG */
#if defined(MBEDTLS_PSA_INJECT_ENTROPY)
#include "mbedtls/entropy_poll.h"
psa_status_t mbedtls_psa_inject_entropy( const uint8_t *seed,
size_t seed_size )
{
if( global_data.initialized )
return( PSA_ERROR_NOT_PERMITTED );
if( ( ( seed_size < MBEDTLS_ENTROPY_MIN_PLATFORM ) ||
( seed_size < MBEDTLS_ENTROPY_BLOCK_SIZE ) ) ||
( seed_size > MBEDTLS_ENTROPY_MAX_SEED_SIZE ) )
return( PSA_ERROR_INVALID_ARGUMENT );
return( mbedtls_psa_storage_inject_entropy( seed, seed_size ) );
}
#endif /* MBEDTLS_PSA_INJECT_ENTROPY */
/** Validate the key type and size for key generation
*
* \param type The key type
* \param bits The number of bits of the key
*
* \retval #PSA_SUCCESS
* The key type and size are valid.
* \retval #PSA_ERROR_INVALID_ARGUMENT
* The size in bits of the key is not valid.
* \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.
*/
static psa_status_t psa_validate_key_type_and_size_for_key_generation(
psa_key_type_t type, size_t bits )
{
psa_status_t status = PSA_ERROR_CORRUPTION_DETECTED;
if( key_type_is_raw_bytes( type ) )
{
status = validate_unstructured_key_bit_size( type, bits );
if( status != PSA_SUCCESS )
return( status );
}
else
#if defined(PSA_WANT_KEY_TYPE_RSA_KEY_PAIR)
if( PSA_KEY_TYPE_IS_RSA( type ) && PSA_KEY_TYPE_IS_KEY_PAIR( type ) )
{
if( bits > PSA_VENDOR_RSA_MAX_KEY_BITS )
return( PSA_ERROR_NOT_SUPPORTED );
/* Accept only byte-aligned keys, for the same reasons as
* in psa_import_rsa_key(). */
if( bits % 8 != 0 )
return( PSA_ERROR_NOT_SUPPORTED );
}
else
#endif /* defined(PSA_WANT_KEY_TYPE_RSA_KEY_PAIR) */
#if defined(PSA_WANT_KEY_TYPE_ECC_KEY_PAIR)
if( PSA_KEY_TYPE_IS_ECC( type ) && PSA_KEY_TYPE_IS_KEY_PAIR( type ) )
{
/* To avoid empty block, return successfully here. */
return( PSA_SUCCESS );
}
else
#endif /* defined(PSA_WANT_KEY_TYPE_ECC_KEY_PAIR) */
{
return( PSA_ERROR_NOT_SUPPORTED );
}
return( PSA_SUCCESS );
}
psa_status_t psa_generate_key_internal(
const psa_key_attributes_t *attributes,
uint8_t *key_buffer, size_t key_buffer_size, size_t *key_buffer_length )
{
psa_status_t status = PSA_ERROR_CORRUPTION_DETECTED;
psa_key_type_t type = attributes->core.type;
if( ( attributes->domain_parameters == NULL ) &&
( attributes->domain_parameters_size != 0 ) )
return( PSA_ERROR_INVALID_ARGUMENT );
if( key_type_is_raw_bytes( type ) )
{
status = psa_generate_random( key_buffer, key_buffer_size );
if( status != PSA_SUCCESS )
return( status );
#if defined(MBEDTLS_PSA_BUILTIN_KEY_TYPE_DES)
if( type == PSA_KEY_TYPE_DES )
psa_des_set_key_parity( key_buffer, key_buffer_size );
#endif /* MBEDTLS_PSA_BUILTIN_KEY_TYPE_DES */
}
else
#if defined(MBEDTLS_PSA_BUILTIN_KEY_TYPE_RSA_KEY_PAIR) && \
defined(MBEDTLS_GENPRIME)
if ( type == PSA_KEY_TYPE_RSA_KEY_PAIR )
{
return( mbedtls_psa_rsa_generate_key( attributes,
key_buffer,
key_buffer_size,
key_buffer_length ) );
}
else
#endif /* defined(MBEDTLS_PSA_BUILTIN_KEY_TYPE_RSA_KEY_PAIR)
* defined(MBEDTLS_GENPRIME) */
#if defined(MBEDTLS_PSA_BUILTIN_KEY_TYPE_ECC_KEY_PAIR)
if ( PSA_KEY_TYPE_IS_ECC( type ) && PSA_KEY_TYPE_IS_KEY_PAIR( type ) )
{
return( mbedtls_psa_ecp_generate_key( attributes,
key_buffer,
key_buffer_size,
key_buffer_length ) );
}
else
#endif /* defined(MBEDTLS_PSA_BUILTIN_KEY_TYPE_ECC_KEY_PAIR) */
{
(void)key_buffer_length;
return( PSA_ERROR_NOT_SUPPORTED );
}
return( PSA_SUCCESS );
}
psa_status_t psa_generate_key( const psa_key_attributes_t *attributes,
mbedtls_svc_key_id_t *key )
{
psa_status_t status;
psa_key_slot_t *slot = NULL;
psa_se_drv_table_entry_t *driver = NULL;
size_t key_buffer_size;
*key = MBEDTLS_SVC_KEY_ID_INIT;
/* Reject any attempt to create a zero-length key so that we don't
* risk tripping up later, e.g. on a malloc(0) that returns NULL. */
if( psa_get_key_bits( attributes ) == 0 )
return( PSA_ERROR_INVALID_ARGUMENT );
status = psa_start_key_creation( PSA_KEY_CREATION_GENERATE, attributes,
&slot, &driver );
if( status != PSA_SUCCESS )
goto exit;
/* In the case of a transparent key or an opaque key stored in local
* storage (thus not in the case of generating a key in a secure element
* or cryptoprocessor with storage), we have to allocate a buffer to
* hold the generated key material. */
if( slot->key.data == NULL )
{
if ( PSA_KEY_LIFETIME_GET_LOCATION( attributes->core.lifetime ) ==
PSA_KEY_LOCATION_LOCAL_STORAGE )
{
status = psa_validate_key_type_and_size_for_key_generation(
attributes->core.type, attributes->core.bits );
if( status != PSA_SUCCESS )
goto exit;
key_buffer_size = PSA_EXPORT_KEY_OUTPUT_SIZE(
attributes->core.type,
attributes->core.bits );
}
else
{
status = psa_driver_wrapper_get_key_buffer_size(
attributes, &key_buffer_size );
if( status != PSA_SUCCESS )
goto exit;
}
status = psa_allocate_buffer_to_slot( slot, key_buffer_size );
if( status != PSA_SUCCESS )
goto exit;
}
status = psa_driver_wrapper_generate_key( attributes,
slot->key.data, slot->key.bytes, &slot->key.bytes );
if( status != PSA_SUCCESS )
psa_remove_key_data_from_memory( slot );
exit:
if( status == PSA_SUCCESS )
status = psa_finish_key_creation( slot, driver, key );
if( status != PSA_SUCCESS )
psa_fail_key_creation( slot, driver );
return( status );
}
/****************************************************************/
/* Module setup */
/****************************************************************/
#if !defined(MBEDTLS_PSA_CRYPTO_EXTERNAL_RNG)
psa_status_t mbedtls_psa_crypto_configure_entropy_sources(
void (* entropy_init )( mbedtls_entropy_context *ctx ),
void (* entropy_free )( mbedtls_entropy_context *ctx ) )
{
if( global_data.rng_state != RNG_NOT_INITIALIZED )
return( PSA_ERROR_BAD_STATE );
global_data.rng.entropy_init = entropy_init;
global_data.rng.entropy_free = entropy_free;
return( PSA_SUCCESS );
}
#endif /* !defined(MBEDTLS_PSA_CRYPTO_EXTERNAL_RNG) */
void mbedtls_psa_crypto_free( void )
{
psa_wipe_all_key_slots( );
if( global_data.rng_state != RNG_NOT_INITIALIZED )
{
mbedtls_psa_random_free( &global_data.rng );
}
/* Wipe all remaining data, including configuration.
* In particular, this sets all state indicator to the value
* indicating "uninitialized". */
mbedtls_platform_zeroize( &global_data, sizeof( global_data ) );
#if defined(MBEDTLS_PSA_CRYPTO_SE_C)
/* Unregister all secure element drivers, so that we restart from
* a pristine state. */
psa_unregister_all_se_drivers( );
#endif /* MBEDTLS_PSA_CRYPTO_SE_C */
}
#if defined(PSA_CRYPTO_STORAGE_HAS_TRANSACTIONS)
/** Recover a transaction that was interrupted by a power failure.
*
* This function is called during initialization, before psa_crypto_init()
* returns. If this function returns a failure status, the initialization
* fails.
*/
static psa_status_t psa_crypto_recover_transaction(
const psa_crypto_transaction_t *transaction )
{
switch( transaction->unknown.type )
{
case PSA_CRYPTO_TRANSACTION_CREATE_KEY:
case PSA_CRYPTO_TRANSACTION_DESTROY_KEY:
/* TODO - fall through to the failure case until this
* is implemented.
* https://github.com/ARMmbed/mbed-crypto/issues/218
*/
default:
/* We found an unsupported transaction in the storage.
* We don't know what state the storage is in. Give up. */
return( PSA_ERROR_DATA_INVALID );
}
}
#endif /* PSA_CRYPTO_STORAGE_HAS_TRANSACTIONS */
psa_status_t psa_crypto_init( void )
{
psa_status_t status;
/* Double initialization is explicitly allowed. */
if( global_data.initialized != 0 )
return( PSA_SUCCESS );
/* Initialize and seed the random generator. */
mbedtls_psa_random_init( &global_data.rng );
global_data.rng_state = RNG_INITIALIZED;
status = mbedtls_psa_random_seed( &global_data.rng );
if( status != PSA_SUCCESS )
goto exit;
global_data.rng_state = RNG_SEEDED;
status = psa_initialize_key_slots( );
if( status != PSA_SUCCESS )
goto exit;
#if defined(MBEDTLS_PSA_CRYPTO_SE_C)
status = psa_init_all_se_drivers( );
if( status != PSA_SUCCESS )
goto exit;
#endif /* MBEDTLS_PSA_CRYPTO_SE_C */
#if defined(PSA_CRYPTO_STORAGE_HAS_TRANSACTIONS)
status = psa_crypto_load_transaction( );
if( status == PSA_SUCCESS )
{
status = psa_crypto_recover_transaction( &psa_crypto_transaction );
if( status != PSA_SUCCESS )
goto exit;
status = psa_crypto_stop_transaction( );
}
else if( status == PSA_ERROR_DOES_NOT_EXIST )
{
/* There's no transaction to complete. It's all good. */
status = PSA_SUCCESS;
}
#endif /* PSA_CRYPTO_STORAGE_HAS_TRANSACTIONS */
/* All done. */
global_data.initialized = 1;
exit:
if( status != PSA_SUCCESS )
mbedtls_psa_crypto_free( );
return( status );
}
#endif /* MBEDTLS_PSA_CRYPTO_C */
|
0 | repos/gpt4all.zig/src/zig-libcurl/zig-mbedtls/mbedtls | repos/gpt4all.zig/src/zig-libcurl/zig-mbedtls/mbedtls/library/ecdh.c | /*
* Elliptic curve Diffie-Hellman
*
* Copyright The Mbed TLS Contributors
* SPDX-License-Identifier: Apache-2.0
*
* 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.
*/
/*
* References:
*
* SEC1 http://www.secg.org/index.php?action=secg,docs_secg
* RFC 4492
*/
#include "common.h"
#if defined(MBEDTLS_ECDH_C)
#include "mbedtls/ecdh.h"
#include "mbedtls/platform_util.h"
#include "mbedtls/error.h"
#include <string.h>
/* Parameter validation macros based on platform_util.h */
#define ECDH_VALIDATE_RET( cond ) \
MBEDTLS_INTERNAL_VALIDATE_RET( cond, MBEDTLS_ERR_ECP_BAD_INPUT_DATA )
#define ECDH_VALIDATE( cond ) \
MBEDTLS_INTERNAL_VALIDATE( cond )
#if defined(MBEDTLS_ECDH_LEGACY_CONTEXT)
typedef mbedtls_ecdh_context mbedtls_ecdh_context_mbed;
#endif
static mbedtls_ecp_group_id mbedtls_ecdh_grp_id(
const mbedtls_ecdh_context *ctx )
{
#if defined(MBEDTLS_ECDH_LEGACY_CONTEXT)
return( ctx->grp.id );
#else
return( ctx->grp_id );
#endif
}
int mbedtls_ecdh_can_do( mbedtls_ecp_group_id gid )
{
/* At this time, all groups support ECDH. */
(void) gid;
return( 1 );
}
#if !defined(MBEDTLS_ECDH_GEN_PUBLIC_ALT)
/*
* Generate public key (restartable version)
*
* Note: this internal function relies on its caller preserving the value of
* the output parameter 'd' across continuation calls. This would not be
* acceptable for a public function but is OK here as we control call sites.
*/
static int ecdh_gen_public_restartable( mbedtls_ecp_group *grp,
mbedtls_mpi *d, mbedtls_ecp_point *Q,
int (*f_rng)(void *, unsigned char *, size_t),
void *p_rng,
mbedtls_ecp_restart_ctx *rs_ctx )
{
int ret = MBEDTLS_ERR_ERROR_CORRUPTION_DETECTED;
/* If multiplication is in progress, we already generated a privkey */
#if defined(MBEDTLS_ECP_RESTARTABLE)
if( rs_ctx == NULL || rs_ctx->rsm == NULL )
#endif
MBEDTLS_MPI_CHK( mbedtls_ecp_gen_privkey( grp, d, f_rng, p_rng ) );
MBEDTLS_MPI_CHK( mbedtls_ecp_mul_restartable( grp, Q, d, &grp->G,
f_rng, p_rng, rs_ctx ) );
cleanup:
return( ret );
}
/*
* Generate public key
*/
int mbedtls_ecdh_gen_public( mbedtls_ecp_group *grp, mbedtls_mpi *d, mbedtls_ecp_point *Q,
int (*f_rng)(void *, unsigned char *, size_t),
void *p_rng )
{
ECDH_VALIDATE_RET( grp != NULL );
ECDH_VALIDATE_RET( d != NULL );
ECDH_VALIDATE_RET( Q != NULL );
ECDH_VALIDATE_RET( f_rng != NULL );
return( ecdh_gen_public_restartable( grp, d, Q, f_rng, p_rng, NULL ) );
}
#endif /* !MBEDTLS_ECDH_GEN_PUBLIC_ALT */
#if !defined(MBEDTLS_ECDH_COMPUTE_SHARED_ALT)
/*
* Compute shared secret (SEC1 3.3.1)
*/
static int ecdh_compute_shared_restartable( mbedtls_ecp_group *grp,
mbedtls_mpi *z,
const mbedtls_ecp_point *Q, const mbedtls_mpi *d,
int (*f_rng)(void *, unsigned char *, size_t),
void *p_rng,
mbedtls_ecp_restart_ctx *rs_ctx )
{
int ret = MBEDTLS_ERR_ERROR_CORRUPTION_DETECTED;
mbedtls_ecp_point P;
mbedtls_ecp_point_init( &P );
MBEDTLS_MPI_CHK( mbedtls_ecp_mul_restartable( grp, &P, d, Q,
f_rng, p_rng, rs_ctx ) );
if( mbedtls_ecp_is_zero( &P ) )
{
ret = MBEDTLS_ERR_ECP_BAD_INPUT_DATA;
goto cleanup;
}
MBEDTLS_MPI_CHK( mbedtls_mpi_copy( z, &P.X ) );
cleanup:
mbedtls_ecp_point_free( &P );
return( ret );
}
/*
* Compute shared secret (SEC1 3.3.1)
*/
int mbedtls_ecdh_compute_shared( mbedtls_ecp_group *grp, mbedtls_mpi *z,
const mbedtls_ecp_point *Q, const mbedtls_mpi *d,
int (*f_rng)(void *, unsigned char *, size_t),
void *p_rng )
{
ECDH_VALIDATE_RET( grp != NULL );
ECDH_VALIDATE_RET( Q != NULL );
ECDH_VALIDATE_RET( d != NULL );
ECDH_VALIDATE_RET( z != NULL );
return( ecdh_compute_shared_restartable( grp, z, Q, d,
f_rng, p_rng, NULL ) );
}
#endif /* !MBEDTLS_ECDH_COMPUTE_SHARED_ALT */
static void ecdh_init_internal( mbedtls_ecdh_context_mbed *ctx )
{
mbedtls_ecp_group_init( &ctx->grp );
mbedtls_mpi_init( &ctx->d );
mbedtls_ecp_point_init( &ctx->Q );
mbedtls_ecp_point_init( &ctx->Qp );
mbedtls_mpi_init( &ctx->z );
#if defined(MBEDTLS_ECP_RESTARTABLE)
mbedtls_ecp_restart_init( &ctx->rs );
#endif
}
/*
* Initialize context
*/
void mbedtls_ecdh_init( mbedtls_ecdh_context *ctx )
{
ECDH_VALIDATE( ctx != NULL );
#if defined(MBEDTLS_ECDH_LEGACY_CONTEXT)
ecdh_init_internal( ctx );
mbedtls_ecp_point_init( &ctx->Vi );
mbedtls_ecp_point_init( &ctx->Vf );
mbedtls_mpi_init( &ctx->_d );
#else
memset( ctx, 0, sizeof( mbedtls_ecdh_context ) );
ctx->var = MBEDTLS_ECDH_VARIANT_NONE;
#endif
ctx->point_format = MBEDTLS_ECP_PF_UNCOMPRESSED;
#if defined(MBEDTLS_ECP_RESTARTABLE)
ctx->restart_enabled = 0;
#endif
}
static int ecdh_setup_internal( mbedtls_ecdh_context_mbed *ctx,
mbedtls_ecp_group_id grp_id )
{
int ret = MBEDTLS_ERR_ERROR_CORRUPTION_DETECTED;
ret = mbedtls_ecp_group_load( &ctx->grp, grp_id );
if( ret != 0 )
{
return( MBEDTLS_ERR_ECP_FEATURE_UNAVAILABLE );
}
return( 0 );
}
/*
* Setup context
*/
int mbedtls_ecdh_setup( mbedtls_ecdh_context *ctx, mbedtls_ecp_group_id grp_id )
{
ECDH_VALIDATE_RET( ctx != NULL );
#if defined(MBEDTLS_ECDH_LEGACY_CONTEXT)
return( ecdh_setup_internal( ctx, grp_id ) );
#else
switch( grp_id )
{
#if defined(MBEDTLS_ECDH_VARIANT_EVEREST_ENABLED)
case MBEDTLS_ECP_DP_CURVE25519:
ctx->point_format = MBEDTLS_ECP_PF_COMPRESSED;
ctx->var = MBEDTLS_ECDH_VARIANT_EVEREST;
ctx->grp_id = grp_id;
return( mbedtls_everest_setup( &ctx->ctx.everest_ecdh, grp_id ) );
#endif
default:
ctx->point_format = MBEDTLS_ECP_PF_UNCOMPRESSED;
ctx->var = MBEDTLS_ECDH_VARIANT_MBEDTLS_2_0;
ctx->grp_id = grp_id;
ecdh_init_internal( &ctx->ctx.mbed_ecdh );
return( ecdh_setup_internal( &ctx->ctx.mbed_ecdh, grp_id ) );
}
#endif
}
static void ecdh_free_internal( mbedtls_ecdh_context_mbed *ctx )
{
mbedtls_ecp_group_free( &ctx->grp );
mbedtls_mpi_free( &ctx->d );
mbedtls_ecp_point_free( &ctx->Q );
mbedtls_ecp_point_free( &ctx->Qp );
mbedtls_mpi_free( &ctx->z );
#if defined(MBEDTLS_ECP_RESTARTABLE)
mbedtls_ecp_restart_free( &ctx->rs );
#endif
}
#if defined(MBEDTLS_ECP_RESTARTABLE)
/*
* Enable restartable operations for context
*/
void mbedtls_ecdh_enable_restart( mbedtls_ecdh_context *ctx )
{
ECDH_VALIDATE( ctx != NULL );
ctx->restart_enabled = 1;
}
#endif
/*
* Free context
*/
void mbedtls_ecdh_free( mbedtls_ecdh_context *ctx )
{
if( ctx == NULL )
return;
#if defined(MBEDTLS_ECDH_LEGACY_CONTEXT)
mbedtls_ecp_point_free( &ctx->Vi );
mbedtls_ecp_point_free( &ctx->Vf );
mbedtls_mpi_free( &ctx->_d );
ecdh_free_internal( ctx );
#else
switch( ctx->var )
{
#if defined(MBEDTLS_ECDH_VARIANT_EVEREST_ENABLED)
case MBEDTLS_ECDH_VARIANT_EVEREST:
mbedtls_everest_free( &ctx->ctx.everest_ecdh );
break;
#endif
case MBEDTLS_ECDH_VARIANT_MBEDTLS_2_0:
ecdh_free_internal( &ctx->ctx.mbed_ecdh );
break;
default:
break;
}
ctx->point_format = MBEDTLS_ECP_PF_UNCOMPRESSED;
ctx->var = MBEDTLS_ECDH_VARIANT_NONE;
ctx->grp_id = MBEDTLS_ECP_DP_NONE;
#endif
}
static int ecdh_make_params_internal( mbedtls_ecdh_context_mbed *ctx,
size_t *olen, int point_format,
unsigned char *buf, size_t blen,
int (*f_rng)(void *,
unsigned char *,
size_t),
void *p_rng,
int restart_enabled )
{
int ret = MBEDTLS_ERR_ERROR_CORRUPTION_DETECTED;
size_t grp_len, pt_len;
#if defined(MBEDTLS_ECP_RESTARTABLE)
mbedtls_ecp_restart_ctx *rs_ctx = NULL;
#endif
if( ctx->grp.pbits == 0 )
return( MBEDTLS_ERR_ECP_BAD_INPUT_DATA );
#if defined(MBEDTLS_ECP_RESTARTABLE)
if( restart_enabled )
rs_ctx = &ctx->rs;
#else
(void) restart_enabled;
#endif
#if defined(MBEDTLS_ECP_RESTARTABLE)
if( ( ret = ecdh_gen_public_restartable( &ctx->grp, &ctx->d, &ctx->Q,
f_rng, p_rng, rs_ctx ) ) != 0 )
return( ret );
#else
if( ( ret = mbedtls_ecdh_gen_public( &ctx->grp, &ctx->d, &ctx->Q,
f_rng, p_rng ) ) != 0 )
return( ret );
#endif /* MBEDTLS_ECP_RESTARTABLE */
if( ( ret = mbedtls_ecp_tls_write_group( &ctx->grp, &grp_len, buf,
blen ) ) != 0 )
return( ret );
buf += grp_len;
blen -= grp_len;
if( ( ret = mbedtls_ecp_tls_write_point( &ctx->grp, &ctx->Q, point_format,
&pt_len, buf, blen ) ) != 0 )
return( ret );
*olen = grp_len + pt_len;
return( 0 );
}
/*
* Setup and write the ServerKeyExchange parameters (RFC 4492)
* struct {
* ECParameters curve_params;
* ECPoint public;
* } ServerECDHParams;
*/
int mbedtls_ecdh_make_params( mbedtls_ecdh_context *ctx, size_t *olen,
unsigned char *buf, size_t blen,
int (*f_rng)(void *, unsigned char *, size_t),
void *p_rng )
{
int restart_enabled = 0;
ECDH_VALIDATE_RET( ctx != NULL );
ECDH_VALIDATE_RET( olen != NULL );
ECDH_VALIDATE_RET( buf != NULL );
ECDH_VALIDATE_RET( f_rng != NULL );
#if defined(MBEDTLS_ECP_RESTARTABLE)
restart_enabled = ctx->restart_enabled;
#else
(void) restart_enabled;
#endif
#if defined(MBEDTLS_ECDH_LEGACY_CONTEXT)
return( ecdh_make_params_internal( ctx, olen, ctx->point_format, buf, blen,
f_rng, p_rng, restart_enabled ) );
#else
switch( ctx->var )
{
#if defined(MBEDTLS_ECDH_VARIANT_EVEREST_ENABLED)
case MBEDTLS_ECDH_VARIANT_EVEREST:
return( mbedtls_everest_make_params( &ctx->ctx.everest_ecdh, olen,
buf, blen, f_rng, p_rng ) );
#endif
case MBEDTLS_ECDH_VARIANT_MBEDTLS_2_0:
return( ecdh_make_params_internal( &ctx->ctx.mbed_ecdh, olen,
ctx->point_format, buf, blen,
f_rng, p_rng,
restart_enabled ) );
default:
return MBEDTLS_ERR_ECP_BAD_INPUT_DATA;
}
#endif
}
static int ecdh_read_params_internal( mbedtls_ecdh_context_mbed *ctx,
const unsigned char **buf,
const unsigned char *end )
{
return( mbedtls_ecp_tls_read_point( &ctx->grp, &ctx->Qp, buf,
end - *buf ) );
}
/*
* Read the ServerKeyExhange parameters (RFC 4492)
* struct {
* ECParameters curve_params;
* ECPoint public;
* } ServerECDHParams;
*/
int mbedtls_ecdh_read_params( mbedtls_ecdh_context *ctx,
const unsigned char **buf,
const unsigned char *end )
{
int ret = MBEDTLS_ERR_ERROR_CORRUPTION_DETECTED;
mbedtls_ecp_group_id grp_id;
ECDH_VALIDATE_RET( ctx != NULL );
ECDH_VALIDATE_RET( buf != NULL );
ECDH_VALIDATE_RET( *buf != NULL );
ECDH_VALIDATE_RET( end != NULL );
if( ( ret = mbedtls_ecp_tls_read_group_id( &grp_id, buf, end - *buf ) )
!= 0 )
return( ret );
if( ( ret = mbedtls_ecdh_setup( ctx, grp_id ) ) != 0 )
return( ret );
#if defined(MBEDTLS_ECDH_LEGACY_CONTEXT)
return( ecdh_read_params_internal( ctx, buf, end ) );
#else
switch( ctx->var )
{
#if defined(MBEDTLS_ECDH_VARIANT_EVEREST_ENABLED)
case MBEDTLS_ECDH_VARIANT_EVEREST:
return( mbedtls_everest_read_params( &ctx->ctx.everest_ecdh,
buf, end) );
#endif
case MBEDTLS_ECDH_VARIANT_MBEDTLS_2_0:
return( ecdh_read_params_internal( &ctx->ctx.mbed_ecdh,
buf, end ) );
default:
return MBEDTLS_ERR_ECP_BAD_INPUT_DATA;
}
#endif
}
static int ecdh_get_params_internal( mbedtls_ecdh_context_mbed *ctx,
const mbedtls_ecp_keypair *key,
mbedtls_ecdh_side side )
{
int ret = MBEDTLS_ERR_ERROR_CORRUPTION_DETECTED;
/* If it's not our key, just import the public part as Qp */
if( side == MBEDTLS_ECDH_THEIRS )
return( mbedtls_ecp_copy( &ctx->Qp, &key->Q ) );
/* Our key: import public (as Q) and private parts */
if( side != MBEDTLS_ECDH_OURS )
return( MBEDTLS_ERR_ECP_BAD_INPUT_DATA );
if( ( ret = mbedtls_ecp_copy( &ctx->Q, &key->Q ) ) != 0 ||
( ret = mbedtls_mpi_copy( &ctx->d, &key->d ) ) != 0 )
return( ret );
return( 0 );
}
/*
* Get parameters from a keypair
*/
int mbedtls_ecdh_get_params( mbedtls_ecdh_context *ctx,
const mbedtls_ecp_keypair *key,
mbedtls_ecdh_side side )
{
int ret = MBEDTLS_ERR_ERROR_CORRUPTION_DETECTED;
ECDH_VALIDATE_RET( ctx != NULL );
ECDH_VALIDATE_RET( key != NULL );
ECDH_VALIDATE_RET( side == MBEDTLS_ECDH_OURS ||
side == MBEDTLS_ECDH_THEIRS );
if( mbedtls_ecdh_grp_id( ctx ) == MBEDTLS_ECP_DP_NONE )
{
/* This is the first call to get_params(). Set up the context
* for use with the group. */
if( ( ret = mbedtls_ecdh_setup( ctx, key->grp.id ) ) != 0 )
return( ret );
}
else
{
/* This is not the first call to get_params(). Check that the
* current key's group is the same as the context's, which was set
* from the first key's group. */
if( mbedtls_ecdh_grp_id( ctx ) != key->grp.id )
return( MBEDTLS_ERR_ECP_BAD_INPUT_DATA );
}
#if defined(MBEDTLS_ECDH_LEGACY_CONTEXT)
return( ecdh_get_params_internal( ctx, key, side ) );
#else
switch( ctx->var )
{
#if defined(MBEDTLS_ECDH_VARIANT_EVEREST_ENABLED)
case MBEDTLS_ECDH_VARIANT_EVEREST:
{
mbedtls_everest_ecdh_side s = side == MBEDTLS_ECDH_OURS ?
MBEDTLS_EVEREST_ECDH_OURS :
MBEDTLS_EVEREST_ECDH_THEIRS;
return( mbedtls_everest_get_params( &ctx->ctx.everest_ecdh,
key, s) );
}
#endif
case MBEDTLS_ECDH_VARIANT_MBEDTLS_2_0:
return( ecdh_get_params_internal( &ctx->ctx.mbed_ecdh,
key, side ) );
default:
return MBEDTLS_ERR_ECP_BAD_INPUT_DATA;
}
#endif
}
static int ecdh_make_public_internal( mbedtls_ecdh_context_mbed *ctx,
size_t *olen, int point_format,
unsigned char *buf, size_t blen,
int (*f_rng)(void *,
unsigned char *,
size_t),
void *p_rng,
int restart_enabled )
{
int ret = MBEDTLS_ERR_ERROR_CORRUPTION_DETECTED;
#if defined(MBEDTLS_ECP_RESTARTABLE)
mbedtls_ecp_restart_ctx *rs_ctx = NULL;
#endif
if( ctx->grp.pbits == 0 )
return( MBEDTLS_ERR_ECP_BAD_INPUT_DATA );
#if defined(MBEDTLS_ECP_RESTARTABLE)
if( restart_enabled )
rs_ctx = &ctx->rs;
#else
(void) restart_enabled;
#endif
#if defined(MBEDTLS_ECP_RESTARTABLE)
if( ( ret = ecdh_gen_public_restartable( &ctx->grp, &ctx->d, &ctx->Q,
f_rng, p_rng, rs_ctx ) ) != 0 )
return( ret );
#else
if( ( ret = mbedtls_ecdh_gen_public( &ctx->grp, &ctx->d, &ctx->Q,
f_rng, p_rng ) ) != 0 )
return( ret );
#endif /* MBEDTLS_ECP_RESTARTABLE */
return mbedtls_ecp_tls_write_point( &ctx->grp, &ctx->Q, point_format, olen,
buf, blen );
}
/*
* Setup and export the client public value
*/
int mbedtls_ecdh_make_public( mbedtls_ecdh_context *ctx, size_t *olen,
unsigned char *buf, size_t blen,
int (*f_rng)(void *, unsigned char *, size_t),
void *p_rng )
{
int restart_enabled = 0;
ECDH_VALIDATE_RET( ctx != NULL );
ECDH_VALIDATE_RET( olen != NULL );
ECDH_VALIDATE_RET( buf != NULL );
ECDH_VALIDATE_RET( f_rng != NULL );
#if defined(MBEDTLS_ECP_RESTARTABLE)
restart_enabled = ctx->restart_enabled;
#endif
#if defined(MBEDTLS_ECDH_LEGACY_CONTEXT)
return( ecdh_make_public_internal( ctx, olen, ctx->point_format, buf, blen,
f_rng, p_rng, restart_enabled ) );
#else
switch( ctx->var )
{
#if defined(MBEDTLS_ECDH_VARIANT_EVEREST_ENABLED)
case MBEDTLS_ECDH_VARIANT_EVEREST:
return( mbedtls_everest_make_public( &ctx->ctx.everest_ecdh, olen,
buf, blen, f_rng, p_rng ) );
#endif
case MBEDTLS_ECDH_VARIANT_MBEDTLS_2_0:
return( ecdh_make_public_internal( &ctx->ctx.mbed_ecdh, olen,
ctx->point_format, buf, blen,
f_rng, p_rng,
restart_enabled ) );
default:
return MBEDTLS_ERR_ECP_BAD_INPUT_DATA;
}
#endif
}
static int ecdh_read_public_internal( mbedtls_ecdh_context_mbed *ctx,
const unsigned char *buf, size_t blen )
{
int ret = MBEDTLS_ERR_ERROR_CORRUPTION_DETECTED;
const unsigned char *p = buf;
if( ( ret = mbedtls_ecp_tls_read_point( &ctx->grp, &ctx->Qp, &p,
blen ) ) != 0 )
return( ret );
if( (size_t)( p - buf ) != blen )
return( MBEDTLS_ERR_ECP_BAD_INPUT_DATA );
return( 0 );
}
/*
* Parse and import the client's public value
*/
int mbedtls_ecdh_read_public( mbedtls_ecdh_context *ctx,
const unsigned char *buf, size_t blen )
{
ECDH_VALIDATE_RET( ctx != NULL );
ECDH_VALIDATE_RET( buf != NULL );
#if defined(MBEDTLS_ECDH_LEGACY_CONTEXT)
return( ecdh_read_public_internal( ctx, buf, blen ) );
#else
switch( ctx->var )
{
#if defined(MBEDTLS_ECDH_VARIANT_EVEREST_ENABLED)
case MBEDTLS_ECDH_VARIANT_EVEREST:
return( mbedtls_everest_read_public( &ctx->ctx.everest_ecdh,
buf, blen ) );
#endif
case MBEDTLS_ECDH_VARIANT_MBEDTLS_2_0:
return( ecdh_read_public_internal( &ctx->ctx.mbed_ecdh,
buf, blen ) );
default:
return MBEDTLS_ERR_ECP_BAD_INPUT_DATA;
}
#endif
}
static int ecdh_calc_secret_internal( mbedtls_ecdh_context_mbed *ctx,
size_t *olen, unsigned char *buf,
size_t blen,
int (*f_rng)(void *,
unsigned char *,
size_t),
void *p_rng,
int restart_enabled )
{
int ret = MBEDTLS_ERR_ERROR_CORRUPTION_DETECTED;
#if defined(MBEDTLS_ECP_RESTARTABLE)
mbedtls_ecp_restart_ctx *rs_ctx = NULL;
#endif
if( ctx == NULL || ctx->grp.pbits == 0 )
return( MBEDTLS_ERR_ECP_BAD_INPUT_DATA );
#if defined(MBEDTLS_ECP_RESTARTABLE)
if( restart_enabled )
rs_ctx = &ctx->rs;
#else
(void) restart_enabled;
#endif
#if defined(MBEDTLS_ECP_RESTARTABLE)
if( ( ret = ecdh_compute_shared_restartable( &ctx->grp, &ctx->z, &ctx->Qp,
&ctx->d, f_rng, p_rng,
rs_ctx ) ) != 0 )
{
return( ret );
}
#else
if( ( ret = mbedtls_ecdh_compute_shared( &ctx->grp, &ctx->z, &ctx->Qp,
&ctx->d, f_rng, p_rng ) ) != 0 )
{
return( ret );
}
#endif /* MBEDTLS_ECP_RESTARTABLE */
if( mbedtls_mpi_size( &ctx->z ) > blen )
return( MBEDTLS_ERR_ECP_BAD_INPUT_DATA );
*olen = ctx->grp.pbits / 8 + ( ( ctx->grp.pbits % 8 ) != 0 );
if( mbedtls_ecp_get_type( &ctx->grp ) == MBEDTLS_ECP_TYPE_MONTGOMERY )
return mbedtls_mpi_write_binary_le( &ctx->z, buf, *olen );
return mbedtls_mpi_write_binary( &ctx->z, buf, *olen );
}
/*
* Derive and export the shared secret
*/
int mbedtls_ecdh_calc_secret( mbedtls_ecdh_context *ctx, size_t *olen,
unsigned char *buf, size_t blen,
int (*f_rng)(void *, unsigned char *, size_t),
void *p_rng )
{
int restart_enabled = 0;
ECDH_VALIDATE_RET( ctx != NULL );
ECDH_VALIDATE_RET( olen != NULL );
ECDH_VALIDATE_RET( buf != NULL );
#if defined(MBEDTLS_ECP_RESTARTABLE)
restart_enabled = ctx->restart_enabled;
#endif
#if defined(MBEDTLS_ECDH_LEGACY_CONTEXT)
return( ecdh_calc_secret_internal( ctx, olen, buf, blen, f_rng, p_rng,
restart_enabled ) );
#else
switch( ctx->var )
{
#if defined(MBEDTLS_ECDH_VARIANT_EVEREST_ENABLED)
case MBEDTLS_ECDH_VARIANT_EVEREST:
return( mbedtls_everest_calc_secret( &ctx->ctx.everest_ecdh, olen,
buf, blen, f_rng, p_rng ) );
#endif
case MBEDTLS_ECDH_VARIANT_MBEDTLS_2_0:
return( ecdh_calc_secret_internal( &ctx->ctx.mbed_ecdh, olen, buf,
blen, f_rng, p_rng,
restart_enabled ) );
default:
return( MBEDTLS_ERR_ECP_BAD_INPUT_DATA );
}
#endif
}
#endif /* MBEDTLS_ECDH_C */
|
0 | repos/gpt4all.zig/src/zig-libcurl/zig-mbedtls/mbedtls | repos/gpt4all.zig/src/zig-libcurl/zig-mbedtls/mbedtls/library/md2.c | /*
* RFC 1115/1319 compliant MD2 implementation
*
* Copyright The Mbed TLS Contributors
* SPDX-License-Identifier: Apache-2.0
*
* 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.
*/
/*
* The MD2 algorithm was designed by Ron Rivest in 1989.
*
* http://www.ietf.org/rfc/rfc1115.txt
* http://www.ietf.org/rfc/rfc1319.txt
*/
#include "common.h"
#if defined(MBEDTLS_MD2_C)
#include "mbedtls/md2.h"
#include "mbedtls/platform_util.h"
#include "mbedtls/error.h"
#include <string.h>
#if defined(MBEDTLS_SELF_TEST)
#if defined(MBEDTLS_PLATFORM_C)
#include "mbedtls/platform.h"
#else
#include <stdio.h>
#define mbedtls_printf printf
#endif /* MBEDTLS_PLATFORM_C */
#endif /* MBEDTLS_SELF_TEST */
#if !defined(MBEDTLS_MD2_ALT)
static const unsigned char PI_SUBST[256] =
{
0x29, 0x2E, 0x43, 0xC9, 0xA2, 0xD8, 0x7C, 0x01, 0x3D, 0x36,
0x54, 0xA1, 0xEC, 0xF0, 0x06, 0x13, 0x62, 0xA7, 0x05, 0xF3,
0xC0, 0xC7, 0x73, 0x8C, 0x98, 0x93, 0x2B, 0xD9, 0xBC, 0x4C,
0x82, 0xCA, 0x1E, 0x9B, 0x57, 0x3C, 0xFD, 0xD4, 0xE0, 0x16,
0x67, 0x42, 0x6F, 0x18, 0x8A, 0x17, 0xE5, 0x12, 0xBE, 0x4E,
0xC4, 0xD6, 0xDA, 0x9E, 0xDE, 0x49, 0xA0, 0xFB, 0xF5, 0x8E,
0xBB, 0x2F, 0xEE, 0x7A, 0xA9, 0x68, 0x79, 0x91, 0x15, 0xB2,
0x07, 0x3F, 0x94, 0xC2, 0x10, 0x89, 0x0B, 0x22, 0x5F, 0x21,
0x80, 0x7F, 0x5D, 0x9A, 0x5A, 0x90, 0x32, 0x27, 0x35, 0x3E,
0xCC, 0xE7, 0xBF, 0xF7, 0x97, 0x03, 0xFF, 0x19, 0x30, 0xB3,
0x48, 0xA5, 0xB5, 0xD1, 0xD7, 0x5E, 0x92, 0x2A, 0xAC, 0x56,
0xAA, 0xC6, 0x4F, 0xB8, 0x38, 0xD2, 0x96, 0xA4, 0x7D, 0xB6,
0x76, 0xFC, 0x6B, 0xE2, 0x9C, 0x74, 0x04, 0xF1, 0x45, 0x9D,
0x70, 0x59, 0x64, 0x71, 0x87, 0x20, 0x86, 0x5B, 0xCF, 0x65,
0xE6, 0x2D, 0xA8, 0x02, 0x1B, 0x60, 0x25, 0xAD, 0xAE, 0xB0,
0xB9, 0xF6, 0x1C, 0x46, 0x61, 0x69, 0x34, 0x40, 0x7E, 0x0F,
0x55, 0x47, 0xA3, 0x23, 0xDD, 0x51, 0xAF, 0x3A, 0xC3, 0x5C,
0xF9, 0xCE, 0xBA, 0xC5, 0xEA, 0x26, 0x2C, 0x53, 0x0D, 0x6E,
0x85, 0x28, 0x84, 0x09, 0xD3, 0xDF, 0xCD, 0xF4, 0x41, 0x81,
0x4D, 0x52, 0x6A, 0xDC, 0x37, 0xC8, 0x6C, 0xC1, 0xAB, 0xFA,
0x24, 0xE1, 0x7B, 0x08, 0x0C, 0xBD, 0xB1, 0x4A, 0x78, 0x88,
0x95, 0x8B, 0xE3, 0x63, 0xE8, 0x6D, 0xE9, 0xCB, 0xD5, 0xFE,
0x3B, 0x00, 0x1D, 0x39, 0xF2, 0xEF, 0xB7, 0x0E, 0x66, 0x58,
0xD0, 0xE4, 0xA6, 0x77, 0x72, 0xF8, 0xEB, 0x75, 0x4B, 0x0A,
0x31, 0x44, 0x50, 0xB4, 0x8F, 0xED, 0x1F, 0x1A, 0xDB, 0x99,
0x8D, 0x33, 0x9F, 0x11, 0x83, 0x14
};
void mbedtls_md2_init( mbedtls_md2_context *ctx )
{
memset( ctx, 0, sizeof( mbedtls_md2_context ) );
}
void mbedtls_md2_free( mbedtls_md2_context *ctx )
{
if( ctx == NULL )
return;
mbedtls_platform_zeroize( ctx, sizeof( mbedtls_md2_context ) );
}
void mbedtls_md2_clone( mbedtls_md2_context *dst,
const mbedtls_md2_context *src )
{
*dst = *src;
}
/*
* MD2 context setup
*/
int mbedtls_md2_starts_ret( mbedtls_md2_context *ctx )
{
memset( ctx->cksum, 0, 16 );
memset( ctx->state, 0, 46 );
memset( ctx->buffer, 0, 16 );
ctx->left = 0;
return( 0 );
}
#if !defined(MBEDTLS_DEPRECATED_REMOVED)
void mbedtls_md2_starts( mbedtls_md2_context *ctx )
{
mbedtls_md2_starts_ret( ctx );
}
#endif
#if !defined(MBEDTLS_MD2_PROCESS_ALT)
int mbedtls_internal_md2_process( mbedtls_md2_context *ctx )
{
int i, j;
unsigned char t = 0;
for( i = 0; i < 16; i++ )
{
ctx->state[i + 16] = ctx->buffer[i];
ctx->state[i + 32] =
(unsigned char)( ctx->buffer[i] ^ ctx->state[i]);
}
for( i = 0; i < 18; i++ )
{
for( j = 0; j < 48; j++ )
{
ctx->state[j] = (unsigned char)
( ctx->state[j] ^ PI_SUBST[t] );
t = ctx->state[j];
}
t = (unsigned char)( t + i );
}
t = ctx->cksum[15];
for( i = 0; i < 16; i++ )
{
ctx->cksum[i] = (unsigned char)
( ctx->cksum[i] ^ PI_SUBST[ctx->buffer[i] ^ t] );
t = ctx->cksum[i];
}
/* Zeroise variables to clear sensitive data from memory. */
mbedtls_platform_zeroize( &t, sizeof( t ) );
return( 0 );
}
#if !defined(MBEDTLS_DEPRECATED_REMOVED)
void mbedtls_md2_process( mbedtls_md2_context *ctx )
{
mbedtls_internal_md2_process( ctx );
}
#endif
#endif /* !MBEDTLS_MD2_PROCESS_ALT */
/*
* MD2 process buffer
*/
int mbedtls_md2_update_ret( mbedtls_md2_context *ctx,
const unsigned char *input,
size_t ilen )
{
int ret = MBEDTLS_ERR_ERROR_CORRUPTION_DETECTED;
size_t fill;
while( ilen > 0 )
{
if( ilen > 16 - ctx->left )
fill = 16 - ctx->left;
else
fill = ilen;
memcpy( ctx->buffer + ctx->left, input, fill );
ctx->left += fill;
input += fill;
ilen -= fill;
if( ctx->left == 16 )
{
ctx->left = 0;
if( ( ret = mbedtls_internal_md2_process( ctx ) ) != 0 )
return( ret );
}
}
return( 0 );
}
#if !defined(MBEDTLS_DEPRECATED_REMOVED)
void mbedtls_md2_update( mbedtls_md2_context *ctx,
const unsigned char *input,
size_t ilen )
{
mbedtls_md2_update_ret( ctx, input, ilen );
}
#endif
/*
* MD2 final digest
*/
int mbedtls_md2_finish_ret( mbedtls_md2_context *ctx,
unsigned char output[16] )
{
int ret = MBEDTLS_ERR_ERROR_CORRUPTION_DETECTED;
size_t i;
unsigned char x;
x = (unsigned char)( 16 - ctx->left );
for( i = ctx->left; i < 16; i++ )
ctx->buffer[i] = x;
if( ( ret = mbedtls_internal_md2_process( ctx ) ) != 0 )
return( ret );
memcpy( ctx->buffer, ctx->cksum, 16 );
if( ( ret = mbedtls_internal_md2_process( ctx ) ) != 0 )
return( ret );
memcpy( output, ctx->state, 16 );
return( 0 );
}
#if !defined(MBEDTLS_DEPRECATED_REMOVED)
void mbedtls_md2_finish( mbedtls_md2_context *ctx,
unsigned char output[16] )
{
mbedtls_md2_finish_ret( ctx, output );
}
#endif
#endif /* !MBEDTLS_MD2_ALT */
/*
* output = MD2( input buffer )
*/
int mbedtls_md2_ret( const unsigned char *input,
size_t ilen,
unsigned char output[16] )
{
int ret = MBEDTLS_ERR_ERROR_CORRUPTION_DETECTED;
mbedtls_md2_context ctx;
mbedtls_md2_init( &ctx );
if( ( ret = mbedtls_md2_starts_ret( &ctx ) ) != 0 )
goto exit;
if( ( ret = mbedtls_md2_update_ret( &ctx, input, ilen ) ) != 0 )
goto exit;
if( ( ret = mbedtls_md2_finish_ret( &ctx, output ) ) != 0 )
goto exit;
exit:
mbedtls_md2_free( &ctx );
return( ret );
}
#if !defined(MBEDTLS_DEPRECATED_REMOVED)
void mbedtls_md2( const unsigned char *input,
size_t ilen,
unsigned char output[16] )
{
mbedtls_md2_ret( input, ilen, output );
}
#endif
#if defined(MBEDTLS_SELF_TEST)
/*
* RFC 1319 test vectors
*/
static const unsigned char md2_test_str[7][81] =
{
{ "" },
{ "a" },
{ "abc" },
{ "message digest" },
{ "abcdefghijklmnopqrstuvwxyz" },
{ "ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789" },
{ "12345678901234567890123456789012345678901234567890123456789012345678901234567890" }
};
static const size_t md2_test_strlen[7] =
{
0, 1, 3, 14, 26, 62, 80
};
static const unsigned char md2_test_sum[7][16] =
{
{ 0x83, 0x50, 0xE5, 0xA3, 0xE2, 0x4C, 0x15, 0x3D,
0xF2, 0x27, 0x5C, 0x9F, 0x80, 0x69, 0x27, 0x73 },
{ 0x32, 0xEC, 0x01, 0xEC, 0x4A, 0x6D, 0xAC, 0x72,
0xC0, 0xAB, 0x96, 0xFB, 0x34, 0xC0, 0xB5, 0xD1 },
{ 0xDA, 0x85, 0x3B, 0x0D, 0x3F, 0x88, 0xD9, 0x9B,
0x30, 0x28, 0x3A, 0x69, 0xE6, 0xDE, 0xD6, 0xBB },
{ 0xAB, 0x4F, 0x49, 0x6B, 0xFB, 0x2A, 0x53, 0x0B,
0x21, 0x9F, 0xF3, 0x30, 0x31, 0xFE, 0x06, 0xB0 },
{ 0x4E, 0x8D, 0xDF, 0xF3, 0x65, 0x02, 0x92, 0xAB,
0x5A, 0x41, 0x08, 0xC3, 0xAA, 0x47, 0x94, 0x0B },
{ 0xDA, 0x33, 0xDE, 0xF2, 0xA4, 0x2D, 0xF1, 0x39,
0x75, 0x35, 0x28, 0x46, 0xC3, 0x03, 0x38, 0xCD },
{ 0xD5, 0x97, 0x6F, 0x79, 0xD8, 0x3D, 0x3A, 0x0D,
0xC9, 0x80, 0x6C, 0x3C, 0x66, 0xF3, 0xEF, 0xD8 }
};
/*
* Checkup routine
*/
int mbedtls_md2_self_test( int verbose )
{
int i, ret = 0;
unsigned char md2sum[16];
for( i = 0; i < 7; i++ )
{
if( verbose != 0 )
mbedtls_printf( " MD2 test #%d: ", i + 1 );
ret = mbedtls_md2_ret( md2_test_str[i], md2_test_strlen[i], md2sum );
if( ret != 0 )
goto fail;
if( memcmp( md2sum, md2_test_sum[i], 16 ) != 0 )
{
ret = 1;
goto fail;
}
if( verbose != 0 )
mbedtls_printf( "passed\n" );
}
if( verbose != 0 )
mbedtls_printf( "\n" );
return( 0 );
fail:
if( verbose != 0 )
mbedtls_printf( "failed\n" );
return( ret );
}
#endif /* MBEDTLS_SELF_TEST */
#endif /* MBEDTLS_MD2_C */
|
0 | repos/gpt4all.zig/src/zig-libcurl/zig-mbedtls/mbedtls | repos/gpt4all.zig/src/zig-libcurl/zig-mbedtls/mbedtls/library/psa_crypto_cipher.c | /*
* PSA cipher driver entry points
*/
/*
* Copyright The Mbed TLS Contributors
* SPDX-License-Identifier: Apache-2.0
*
* 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.
*/
#include "common.h"
#if defined(MBEDTLS_PSA_CRYPTO_C)
#include <psa_crypto_cipher.h>
#include "psa_crypto_core.h"
#include "psa_crypto_random_impl.h"
#include "mbedtls/cipher.h"
#include "mbedtls/error.h"
#include <string.h>
#if ( defined(MBEDTLS_PSA_BUILTIN_KEY_TYPE_DES) || \
( defined(PSA_CRYPTO_DRIVER_TEST) && \
defined(MBEDTLS_PSA_ACCEL_KEY_TYPE_DES) ) )
#define BUILTIN_KEY_TYPE_DES 1
#endif
#if ( defined(MBEDTLS_PSA_BUILTIN_ALG_CBC_NO_PADDING) || \
( defined(PSA_CRYPTO_DRIVER_TEST) && \
defined(MBEDTLS_PSA_ACCEL_ALG_CBC_NO_PADDING) ) )
#define BUILTIN_ALG_CBC_NO_PADDING 1
#endif
#if ( defined(MBEDTLS_PSA_BUILTIN_ALG_CBC_PKCS7) || \
( defined(PSA_CRYPTO_DRIVER_TEST) && \
defined(MBEDTLS_PSA_ACCEL_ALG_CBC_PKCS7) ) )
#define BUILTIN_ALG_CBC_PKCS7 1
#endif
#if ( defined(MBEDTLS_PSA_BUILTIN_KEY_TYPE_CHACHA20) || \
( defined(PSA_CRYPTO_DRIVER_TEST) && \
defined(MBEDTLS_PSA_ACCEL_KEY_TYPE_CHACHA20) ) )
#define BUILTIN_KEY_TYPE_CHACHA20 1
#endif
const mbedtls_cipher_info_t *mbedtls_cipher_info_from_psa(
psa_algorithm_t alg,
psa_key_type_t key_type,
size_t key_bits,
mbedtls_cipher_id_t* cipher_id )
{
mbedtls_cipher_mode_t mode;
mbedtls_cipher_id_t cipher_id_tmp;
if( PSA_ALG_IS_AEAD( alg ) )
alg = PSA_ALG_AEAD_WITH_SHORTENED_TAG( alg, 0 );
if( PSA_ALG_IS_CIPHER( alg ) || PSA_ALG_IS_AEAD( alg ) )
{
switch( alg )
{
case PSA_ALG_STREAM_CIPHER:
mode = MBEDTLS_MODE_STREAM;
break;
case PSA_ALG_CTR:
mode = MBEDTLS_MODE_CTR;
break;
case PSA_ALG_CFB:
mode = MBEDTLS_MODE_CFB;
break;
case PSA_ALG_OFB:
mode = MBEDTLS_MODE_OFB;
break;
case PSA_ALG_ECB_NO_PADDING:
mode = MBEDTLS_MODE_ECB;
break;
case PSA_ALG_CBC_NO_PADDING:
mode = MBEDTLS_MODE_CBC;
break;
case PSA_ALG_CBC_PKCS7:
mode = MBEDTLS_MODE_CBC;
break;
case PSA_ALG_AEAD_WITH_SHORTENED_TAG( PSA_ALG_CCM, 0 ):
mode = MBEDTLS_MODE_CCM;
break;
case PSA_ALG_AEAD_WITH_SHORTENED_TAG( PSA_ALG_GCM, 0 ):
mode = MBEDTLS_MODE_GCM;
break;
case PSA_ALG_AEAD_WITH_SHORTENED_TAG( PSA_ALG_CHACHA20_POLY1305, 0 ):
mode = MBEDTLS_MODE_CHACHAPOLY;
break;
default:
return( NULL );
}
}
else if( alg == PSA_ALG_CMAC )
mode = MBEDTLS_MODE_ECB;
else
return( NULL );
switch( key_type )
{
case PSA_KEY_TYPE_AES:
cipher_id_tmp = MBEDTLS_CIPHER_ID_AES;
break;
case PSA_KEY_TYPE_DES:
/* key_bits is 64 for Single-DES, 128 for two-key Triple-DES,
* and 192 for three-key Triple-DES. */
if( key_bits == 64 )
cipher_id_tmp = MBEDTLS_CIPHER_ID_DES;
else
cipher_id_tmp = MBEDTLS_CIPHER_ID_3DES;
/* mbedtls doesn't recognize two-key Triple-DES as an algorithm,
* but two-key Triple-DES is functionally three-key Triple-DES
* with K1=K3, so that's how we present it to mbedtls. */
if( key_bits == 128 )
key_bits = 192;
break;
case PSA_KEY_TYPE_CAMELLIA:
cipher_id_tmp = MBEDTLS_CIPHER_ID_CAMELLIA;
break;
case PSA_KEY_TYPE_ARC4:
cipher_id_tmp = MBEDTLS_CIPHER_ID_ARC4;
break;
case PSA_KEY_TYPE_CHACHA20:
cipher_id_tmp = MBEDTLS_CIPHER_ID_CHACHA20;
break;
default:
return( NULL );
}
if( cipher_id != NULL )
*cipher_id = cipher_id_tmp;
return( mbedtls_cipher_info_from_values( cipher_id_tmp,
(int) key_bits, mode ) );
}
#if defined(MBEDTLS_PSA_BUILTIN_CIPHER) || defined(PSA_CRYPTO_DRIVER_TEST)
static psa_status_t cipher_setup(
mbedtls_psa_cipher_operation_t *operation,
const psa_key_attributes_t *attributes,
const uint8_t *key_buffer, size_t key_buffer_size,
psa_algorithm_t alg,
mbedtls_operation_t cipher_operation )
{
int ret = 0;
size_t key_bits;
const mbedtls_cipher_info_t *cipher_info = NULL;
psa_key_type_t key_type = attributes->core.type;
(void)key_buffer_size;
mbedtls_cipher_init( &operation->ctx.cipher );
operation->alg = alg;
key_bits = attributes->core.bits;
cipher_info = mbedtls_cipher_info_from_psa( alg, key_type,
key_bits, NULL );
if( cipher_info == NULL )
return( PSA_ERROR_NOT_SUPPORTED );
ret = mbedtls_cipher_setup( &operation->ctx.cipher, cipher_info );
if( ret != 0 )
goto exit;
#if defined(BUILTIN_KEY_TYPE_DES)
if( key_type == PSA_KEY_TYPE_DES && key_bits == 128 )
{
/* Two-key Triple-DES is 3-key Triple-DES with K1=K3 */
uint8_t keys[24];
memcpy( keys, key_buffer, 16 );
memcpy( keys + 16, key_buffer, 8 );
ret = mbedtls_cipher_setkey( &operation->ctx.cipher,
keys,
192, cipher_operation );
}
else
#endif
{
ret = mbedtls_cipher_setkey( &operation->ctx.cipher, key_buffer,
(int) key_bits, cipher_operation );
}
if( ret != 0 )
goto exit;
#if defined(BUILTIN_ALG_CBC_NO_PADDING) || \
defined(BUILTIN_ALG_CBC_PKCS7)
switch( alg )
{
case PSA_ALG_CBC_NO_PADDING:
ret = mbedtls_cipher_set_padding_mode( &operation->ctx.cipher,
MBEDTLS_PADDING_NONE );
break;
case PSA_ALG_CBC_PKCS7:
ret = mbedtls_cipher_set_padding_mode( &operation->ctx.cipher,
MBEDTLS_PADDING_PKCS7 );
break;
default:
/* The algorithm doesn't involve padding. */
ret = 0;
break;
}
if( ret != 0 )
goto exit;
#endif /* BUILTIN_ALG_CBC_NO_PADDING || BUILTIN_ALG_CBC_PKCS7 */
operation->block_length = ( PSA_ALG_IS_STREAM_CIPHER( alg ) ? 1 :
PSA_BLOCK_CIPHER_BLOCK_LENGTH( key_type ) );
operation->iv_length = PSA_CIPHER_IV_LENGTH( key_type, alg );
exit:
return( mbedtls_to_psa_error( ret ) );
}
static psa_status_t cipher_encrypt_setup(
mbedtls_psa_cipher_operation_t *operation,
const psa_key_attributes_t *attributes,
const uint8_t *key_buffer, size_t key_buffer_size,
psa_algorithm_t alg )
{
return( cipher_setup( operation, attributes,
key_buffer, key_buffer_size,
alg, MBEDTLS_ENCRYPT ) );
}
static psa_status_t cipher_decrypt_setup(
mbedtls_psa_cipher_operation_t *operation,
const psa_key_attributes_t *attributes,
const uint8_t *key_buffer, size_t key_buffer_size,
psa_algorithm_t alg )
{
return( cipher_setup( operation, attributes,
key_buffer, key_buffer_size,
alg, MBEDTLS_DECRYPT ) );
}
static psa_status_t cipher_set_iv( mbedtls_psa_cipher_operation_t *operation,
const uint8_t *iv, size_t iv_length )
{
if( iv_length != operation->iv_length )
return( PSA_ERROR_INVALID_ARGUMENT );
return( mbedtls_to_psa_error(
mbedtls_cipher_set_iv( &operation->ctx.cipher,
iv, iv_length ) ) );
}
/* Process input for which the algorithm is set to ECB mode. This requires
* manual processing, since the PSA API is defined as being able to process
* arbitrary-length calls to psa_cipher_update() with ECB mode, but the
* underlying mbedtls_cipher_update only takes full blocks. */
static psa_status_t psa_cipher_update_ecb(
mbedtls_cipher_context_t *ctx,
const uint8_t *input,
size_t input_length,
uint8_t *output,
size_t output_size,
size_t *output_length )
{
psa_status_t status = PSA_ERROR_CORRUPTION_DETECTED;
size_t block_size = ctx->cipher_info->block_size;
size_t internal_output_length = 0;
*output_length = 0;
if( input_length == 0 )
{
status = PSA_SUCCESS;
goto exit;
}
if( ctx->unprocessed_len > 0 )
{
/* Fill up to block size, and run the block if there's a full one. */
size_t bytes_to_copy = block_size - ctx->unprocessed_len;
if( input_length < bytes_to_copy )
bytes_to_copy = input_length;
memcpy( &( ctx->unprocessed_data[ctx->unprocessed_len] ),
input, bytes_to_copy );
input_length -= bytes_to_copy;
input += bytes_to_copy;
ctx->unprocessed_len += bytes_to_copy;
if( ctx->unprocessed_len == block_size )
{
status = mbedtls_to_psa_error(
mbedtls_cipher_update( ctx,
ctx->unprocessed_data,
block_size,
output, &internal_output_length ) );
if( status != PSA_SUCCESS )
goto exit;
output += internal_output_length;
output_size -= internal_output_length;
*output_length += internal_output_length;
ctx->unprocessed_len = 0;
}
}
while( input_length >= block_size )
{
/* Run all full blocks we have, one by one */
status = mbedtls_to_psa_error(
mbedtls_cipher_update( ctx, input,
block_size,
output, &internal_output_length ) );
if( status != PSA_SUCCESS )
goto exit;
input_length -= block_size;
input += block_size;
output += internal_output_length;
output_size -= internal_output_length;
*output_length += internal_output_length;
}
if( input_length > 0 )
{
/* Save unprocessed bytes for later processing */
memcpy( &( ctx->unprocessed_data[ctx->unprocessed_len] ),
input, input_length );
ctx->unprocessed_len += input_length;
}
status = PSA_SUCCESS;
exit:
return( status );
}
static psa_status_t cipher_update( mbedtls_psa_cipher_operation_t *operation,
const uint8_t *input,
size_t input_length,
uint8_t *output,
size_t output_size,
size_t *output_length )
{
psa_status_t status = PSA_ERROR_CORRUPTION_DETECTED;
size_t expected_output_size;
if( ! PSA_ALG_IS_STREAM_CIPHER( operation->alg ) )
{
/* Take the unprocessed partial block left over from previous
* update calls, if any, plus the input to this call. Remove
* the last partial block, if any. You get the data that will be
* output in this call. */
expected_output_size =
( operation->ctx.cipher.unprocessed_len + input_length )
/ operation->block_length * operation->block_length;
}
else
{
expected_output_size = input_length;
}
if( output_size < expected_output_size )
return( PSA_ERROR_BUFFER_TOO_SMALL );
if( operation->alg == PSA_ALG_ECB_NO_PADDING )
{
/* mbedtls_cipher_update has an API inconsistency: it will only
* process a single block at a time in ECB mode. Abstract away that
* inconsistency here to match the PSA API behaviour. */
status = psa_cipher_update_ecb( &operation->ctx.cipher,
input,
input_length,
output,
output_size,
output_length );
}
else
{
status = mbedtls_to_psa_error(
mbedtls_cipher_update( &operation->ctx.cipher, input,
input_length, output, output_length ) );
if( *output_length > output_size )
return( PSA_ERROR_CORRUPTION_DETECTED );
}
return( status );
}
static psa_status_t cipher_finish( mbedtls_psa_cipher_operation_t *operation,
uint8_t *output,
size_t output_size,
size_t *output_length )
{
psa_status_t status = PSA_ERROR_GENERIC_ERROR;
uint8_t temp_output_buffer[MBEDTLS_MAX_BLOCK_LENGTH];
if( operation->ctx.cipher.unprocessed_len != 0 )
{
if( operation->alg == PSA_ALG_ECB_NO_PADDING ||
operation->alg == PSA_ALG_CBC_NO_PADDING )
{
status = PSA_ERROR_INVALID_ARGUMENT;
goto exit;
}
}
status = mbedtls_to_psa_error(
mbedtls_cipher_finish( &operation->ctx.cipher,
temp_output_buffer,
output_length ) );
if( status != PSA_SUCCESS )
goto exit;
if( *output_length == 0 )
; /* Nothing to copy. Note that output may be NULL in this case. */
else if( output_size >= *output_length )
memcpy( output, temp_output_buffer, *output_length );
else
status = PSA_ERROR_BUFFER_TOO_SMALL;
exit:
mbedtls_platform_zeroize( temp_output_buffer,
sizeof( temp_output_buffer ) );
return( status );
}
static psa_status_t cipher_abort( mbedtls_psa_cipher_operation_t *operation )
{
/* Sanity check (shouldn't happen: operation->alg should
* always have been initialized to a valid value). */
if( ! PSA_ALG_IS_CIPHER( operation->alg ) )
return( PSA_ERROR_BAD_STATE );
mbedtls_cipher_free( &operation->ctx.cipher );
return( PSA_SUCCESS );
}
static psa_status_t cipher_encrypt( const psa_key_attributes_t *attributes,
const uint8_t *key_buffer,
size_t key_buffer_size,
psa_algorithm_t alg,
const uint8_t *input,
size_t input_length,
uint8_t *output,
size_t output_size,
size_t *output_length )
{
psa_status_t status = PSA_ERROR_CORRUPTION_DETECTED;
mbedtls_psa_cipher_operation_t operation = MBEDTLS_PSA_CIPHER_OPERATION_INIT;
size_t olength, accumulated_length;
status = cipher_encrypt_setup( &operation, attributes,
key_buffer, key_buffer_size, alg );
if( status != PSA_SUCCESS )
goto exit;
accumulated_length = 0;
if( operation.iv_length > 0 )
{
status = cipher_set_iv( &operation, output, operation.iv_length );
if( status != PSA_SUCCESS )
goto exit;
accumulated_length = operation.iv_length;
}
status = cipher_update( &operation, input, input_length,
output + operation.iv_length,
output_size - operation.iv_length,
&olength );
if( status != PSA_SUCCESS )
goto exit;
accumulated_length += olength;
status = cipher_finish( &operation, output + accumulated_length,
output_size - accumulated_length, &olength );
if( status != PSA_SUCCESS )
goto exit;
*output_length = accumulated_length + olength;
exit:
if( status == PSA_SUCCESS )
status = cipher_abort( &operation );
else
cipher_abort( &operation );
return( status );
}
static psa_status_t cipher_decrypt( const psa_key_attributes_t *attributes,
const uint8_t *key_buffer,
size_t key_buffer_size,
psa_algorithm_t alg,
const uint8_t *input,
size_t input_length,
uint8_t *output,
size_t output_size,
size_t *output_length )
{
psa_status_t status = PSA_ERROR_CORRUPTION_DETECTED;
mbedtls_psa_cipher_operation_t operation = MBEDTLS_PSA_CIPHER_OPERATION_INIT;
size_t olength, accumulated_length;
status = cipher_decrypt_setup( &operation, attributes,
key_buffer, key_buffer_size, alg );
if( status != PSA_SUCCESS )
goto exit;
if( operation.iv_length > 0 )
{
status = cipher_set_iv( &operation, input, operation.iv_length );
if( status != PSA_SUCCESS )
goto exit;
}
status = cipher_update( &operation, input + operation.iv_length,
input_length - operation.iv_length,
output, output_size, &olength );
if( status != PSA_SUCCESS )
goto exit;
accumulated_length = olength;
status = cipher_finish( &operation, output + accumulated_length,
output_size - accumulated_length, &olength );
if( status != PSA_SUCCESS )
goto exit;
*output_length = accumulated_length + olength;
exit:
if ( status == PSA_SUCCESS )
status = cipher_abort( &operation );
else
cipher_abort( &operation );
return( status );
}
#endif /* MBEDTLS_PSA_BUILTIN_CIPHER || PSA_CRYPTO_DRIVER_TEST */
#if defined(MBEDTLS_PSA_BUILTIN_CIPHER)
psa_status_t mbedtls_psa_cipher_encrypt_setup(
mbedtls_psa_cipher_operation_t *operation,
const psa_key_attributes_t *attributes,
const uint8_t *key_buffer, size_t key_buffer_size,
psa_algorithm_t alg )
{
return( cipher_encrypt_setup(
operation, attributes, key_buffer, key_buffer_size, alg ) );
}
psa_status_t mbedtls_psa_cipher_decrypt_setup(
mbedtls_psa_cipher_operation_t *operation,
const psa_key_attributes_t *attributes,
const uint8_t *key_buffer, size_t key_buffer_size,
psa_algorithm_t alg )
{
return( cipher_decrypt_setup(
operation, attributes, key_buffer, key_buffer_size, alg ) );
}
psa_status_t mbedtls_psa_cipher_set_iv( mbedtls_psa_cipher_operation_t *operation,
const uint8_t *iv,
size_t iv_length )
{
return( cipher_set_iv( operation, iv, iv_length ) );
}
psa_status_t mbedtls_psa_cipher_update( mbedtls_psa_cipher_operation_t *operation,
const uint8_t *input,
size_t input_length,
uint8_t *output,
size_t output_size,
size_t *output_length )
{
return( cipher_update( operation, input, input_length,
output, output_size, output_length ) );
}
psa_status_t mbedtls_psa_cipher_finish( mbedtls_psa_cipher_operation_t *operation,
uint8_t *output,
size_t output_size,
size_t *output_length )
{
return( cipher_finish( operation, output, output_size, output_length ) );
}
psa_status_t mbedtls_psa_cipher_abort( mbedtls_psa_cipher_operation_t *operation )
{
return( cipher_abort( operation ) );
}
psa_status_t mbedtls_psa_cipher_encrypt( const psa_key_attributes_t *attributes,
const uint8_t *key_buffer,
size_t key_buffer_size,
psa_algorithm_t alg,
const uint8_t *input,
size_t input_length,
uint8_t *output,
size_t output_size,
size_t *output_length )
{
return( cipher_encrypt( attributes, key_buffer, key_buffer_size,
alg, input, input_length,
output, output_size, output_length ) );
}
psa_status_t mbedtls_psa_cipher_decrypt( const psa_key_attributes_t *attributes,
const uint8_t *key_buffer,
size_t key_buffer_size,
psa_algorithm_t alg,
const uint8_t *input,
size_t input_length,
uint8_t *output,
size_t output_size,
size_t *output_length )
{
return( cipher_decrypt( attributes, key_buffer, key_buffer_size,
alg, input, input_length,
output, output_size, output_length ) );
}
#endif /* MBEDTLS_PSA_BUILTIN_CIPHER */
/*
* BEYOND THIS POINT, TEST DRIVER ENTRY POINTS ONLY.
*/
#if defined(PSA_CRYPTO_DRIVER_TEST)
psa_status_t mbedtls_transparent_test_driver_cipher_encrypt_setup(
mbedtls_psa_cipher_operation_t *operation,
const psa_key_attributes_t *attributes,
const uint8_t *key_buffer, size_t key_buffer_size,
psa_algorithm_t alg )
{
return( cipher_encrypt_setup(
operation, attributes, key_buffer, key_buffer_size, alg ) );
}
psa_status_t mbedtls_transparent_test_driver_cipher_decrypt_setup(
mbedtls_psa_cipher_operation_t *operation,
const psa_key_attributes_t *attributes,
const uint8_t *key_buffer, size_t key_buffer_size,
psa_algorithm_t alg )
{
return( cipher_decrypt_setup(
operation, attributes, key_buffer, key_buffer_size, alg ) );
}
psa_status_t mbedtls_transparent_test_driver_cipher_set_iv(
mbedtls_psa_cipher_operation_t *operation,
const uint8_t *iv, size_t iv_length )
{
return( cipher_set_iv( operation, iv, iv_length ) );
}
psa_status_t mbedtls_transparent_test_driver_cipher_update(
mbedtls_psa_cipher_operation_t *operation,
const uint8_t *input, size_t input_length,
uint8_t *output, size_t output_size, size_t *output_length )
{
return( cipher_update( operation, input, input_length,
output, output_size, output_length ) );
}
psa_status_t mbedtls_transparent_test_driver_cipher_finish(
mbedtls_psa_cipher_operation_t *operation,
uint8_t *output, size_t output_size, size_t *output_length )
{
return( cipher_finish( operation, output, output_size, output_length ) );
}
psa_status_t mbedtls_transparent_test_driver_cipher_abort(
mbedtls_psa_cipher_operation_t *operation )
{
return( cipher_abort( operation ) );
}
psa_status_t mbedtls_transparent_test_driver_cipher_encrypt(
const psa_key_attributes_t *attributes,
const uint8_t *key_buffer,
size_t key_buffer_size,
psa_algorithm_t alg,
const uint8_t *input,
size_t input_length,
uint8_t *output,
size_t output_size,
size_t *output_length )
{
return( cipher_encrypt( attributes, key_buffer, key_buffer_size,
alg, input, input_length,
output, output_size, output_length ) );
}
psa_status_t mbedtls_transparent_test_driver_cipher_decrypt(
const psa_key_attributes_t *attributes,
const uint8_t *key_buffer,
size_t key_buffer_size,
psa_algorithm_t alg,
const uint8_t *input,
size_t input_length,
uint8_t *output,
size_t output_size,
size_t *output_length )
{
return( cipher_decrypt( attributes, key_buffer, key_buffer_size,
alg, input, input_length,
output, output_size, output_length ) );
}
#endif /* PSA_CRYPTO_DRIVER_TEST */
#endif /* MBEDTLS_PSA_CRYPTO_C */
|
0 | repos/gpt4all.zig/src/zig-libcurl/zig-mbedtls/mbedtls | repos/gpt4all.zig/src/zig-libcurl/zig-mbedtls/mbedtls/library/ecp.c | /*
* Elliptic curves over GF(p): generic functions
*
* Copyright The Mbed TLS Contributors
* SPDX-License-Identifier: Apache-2.0
*
* 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.
*/
/*
* References:
*
* SEC1 http://www.secg.org/index.php?action=secg,docs_secg
* GECC = Guide to Elliptic Curve Cryptography - Hankerson, Menezes, Vanstone
* FIPS 186-3 http://csrc.nist.gov/publications/fips/fips186-3/fips_186-3.pdf
* RFC 4492 for the related TLS structures and constants
* RFC 7748 for the Curve448 and Curve25519 curve definitions
*
* [Curve25519] http://cr.yp.to/ecdh/curve25519-20060209.pdf
*
* [2] CORON, Jean-S'ebastien. Resistance against differential power analysis
* for elliptic curve cryptosystems. In : Cryptographic Hardware and
* Embedded Systems. Springer Berlin Heidelberg, 1999. p. 292-302.
* <http://link.springer.com/chapter/10.1007/3-540-48059-5_25>
*
* [3] HEDABOU, Mustapha, PINEL, Pierre, et B'EN'ETEAU, Lucien. A comb method to
* render ECC resistant against Side Channel Attacks. IACR Cryptology
* ePrint Archive, 2004, vol. 2004, p. 342.
* <http://eprint.iacr.org/2004/342.pdf>
*/
#include "common.h"
/**
* \brief Function level alternative implementation.
*
* The MBEDTLS_ECP_INTERNAL_ALT macro enables alternative implementations to
* replace certain functions in this module. The alternative implementations are
* typically hardware accelerators and need to activate the hardware before the
* computation starts and deactivate it after it finishes. The
* mbedtls_internal_ecp_init() and mbedtls_internal_ecp_free() functions serve
* this purpose.
*
* To preserve the correct functionality the following conditions must hold:
*
* - The alternative implementation must be activated by
* mbedtls_internal_ecp_init() before any of the replaceable functions is
* called.
* - mbedtls_internal_ecp_free() must \b only be called when the alternative
* implementation is activated.
* - mbedtls_internal_ecp_init() must \b not be called when the alternative
* implementation is activated.
* - Public functions must not return while the alternative implementation is
* activated.
* - Replaceable functions are guarded by \c MBEDTLS_ECP_XXX_ALT macros and
* before calling them an \code if( mbedtls_internal_ecp_grp_capable( grp ) )
* \endcode ensures that the alternative implementation supports the current
* group.
*/
#if defined(MBEDTLS_ECP_INTERNAL_ALT)
#endif
#if defined(MBEDTLS_ECP_C)
#include "mbedtls/ecp.h"
#include "mbedtls/threading.h"
#include "mbedtls/platform_util.h"
#include "mbedtls/error.h"
#include "mbedtls/bn_mul.h"
#include "ecp_invasive.h"
#include <string.h>
#if !defined(MBEDTLS_ECP_ALT)
/* Parameter validation macros based on platform_util.h */
#define ECP_VALIDATE_RET( cond ) \
MBEDTLS_INTERNAL_VALIDATE_RET( cond, MBEDTLS_ERR_ECP_BAD_INPUT_DATA )
#define ECP_VALIDATE( cond ) \
MBEDTLS_INTERNAL_VALIDATE( cond )
#if defined(MBEDTLS_PLATFORM_C)
#include "mbedtls/platform.h"
#else
#include <stdlib.h>
#include <stdio.h>
#define mbedtls_printf printf
#define mbedtls_calloc calloc
#define mbedtls_free free
#endif
#include "mbedtls/ecp_internal.h"
#if !defined(MBEDTLS_ECP_NO_INTERNAL_RNG)
#if defined(MBEDTLS_HMAC_DRBG_C)
#include "mbedtls/hmac_drbg.h"
#elif defined(MBEDTLS_CTR_DRBG_C)
#include "mbedtls/ctr_drbg.h"
#else
#error "Invalid configuration detected. Include check_config.h to ensure that the configuration is valid."
#endif
#endif /* MBEDTLS_ECP_NO_INTERNAL_RNG */
#if ( defined(__ARMCC_VERSION) || defined(_MSC_VER) ) && \
!defined(inline) && !defined(__cplusplus)
#define inline __inline
#endif
#if defined(MBEDTLS_SELF_TEST)
/*
* Counts of point addition and doubling, and field multiplications.
* Used to test resistance of point multiplication to simple timing attacks.
*/
static unsigned long add_count, dbl_count, mul_count;
#endif
#if !defined(MBEDTLS_ECP_NO_INTERNAL_RNG)
/*
* Currently ecp_mul() takes a RNG function as an argument, used for
* side-channel protection, but it can be NULL. The initial reasoning was
* that people will pass non-NULL RNG when they care about side-channels, but
* unfortunately we have some APIs that call ecp_mul() with a NULL RNG, with
* no opportunity for the user to do anything about it.
*
* The obvious strategies for addressing that include:
* - change those APIs so that they take RNG arguments;
* - require a global RNG to be available to all crypto modules.
*
* Unfortunately those would break compatibility. So what we do instead is
* have our own internal DRBG instance, seeded from the secret scalar.
*
* The following is a light-weight abstraction layer for doing that with
* HMAC_DRBG (first choice) or CTR_DRBG.
*/
#if defined(MBEDTLS_HMAC_DRBG_C)
/* DRBG context type */
typedef mbedtls_hmac_drbg_context ecp_drbg_context;
/* DRBG context init */
static inline void ecp_drbg_init( ecp_drbg_context *ctx )
{
mbedtls_hmac_drbg_init( ctx );
}
/* DRBG context free */
static inline void ecp_drbg_free( ecp_drbg_context *ctx )
{
mbedtls_hmac_drbg_free( ctx );
}
/* DRBG function */
static inline int ecp_drbg_random( void *p_rng,
unsigned char *output, size_t output_len )
{
return( mbedtls_hmac_drbg_random( p_rng, output, output_len ) );
}
/* DRBG context seeding */
static int ecp_drbg_seed( ecp_drbg_context *ctx,
const mbedtls_mpi *secret, size_t secret_len )
{
int ret;
unsigned char secret_bytes[MBEDTLS_ECP_MAX_BYTES];
/* The list starts with strong hashes */
const mbedtls_md_type_t md_type = mbedtls_md_list()[0];
const mbedtls_md_info_t *md_info = mbedtls_md_info_from_type( md_type );
if( secret_len > MBEDTLS_ECP_MAX_BYTES )
{
ret = MBEDTLS_ERR_ECP_RANDOM_FAILED;
goto cleanup;
}
MBEDTLS_MPI_CHK( mbedtls_mpi_write_binary( secret,
secret_bytes, secret_len ) );
ret = mbedtls_hmac_drbg_seed_buf( ctx, md_info, secret_bytes, secret_len );
cleanup:
mbedtls_platform_zeroize( secret_bytes, secret_len );
return( ret );
}
#elif defined(MBEDTLS_CTR_DRBG_C)
/* DRBG context type */
typedef mbedtls_ctr_drbg_context ecp_drbg_context;
/* DRBG context init */
static inline void ecp_drbg_init( ecp_drbg_context *ctx )
{
mbedtls_ctr_drbg_init( ctx );
}
/* DRBG context free */
static inline void ecp_drbg_free( ecp_drbg_context *ctx )
{
mbedtls_ctr_drbg_free( ctx );
}
/* DRBG function */
static inline int ecp_drbg_random( void *p_rng,
unsigned char *output, size_t output_len )
{
return( mbedtls_ctr_drbg_random( p_rng, output, output_len ) );
}
/*
* Since CTR_DRBG doesn't have a seed_buf() function the way HMAC_DRBG does,
* we need to pass an entropy function when seeding. So we use a dummy
* function for that, and pass the actual entropy as customisation string.
* (During seeding of CTR_DRBG the entropy input and customisation string are
* concatenated before being used to update the secret state.)
*/
static int ecp_ctr_drbg_null_entropy(void *ctx, unsigned char *out, size_t len)
{
(void) ctx;
memset( out, 0, len );
return( 0 );
}
/* DRBG context seeding */
static int ecp_drbg_seed( ecp_drbg_context *ctx,
const mbedtls_mpi *secret, size_t secret_len )
{
int ret;
unsigned char secret_bytes[MBEDTLS_ECP_MAX_BYTES];
if( secret_len > MBEDTLS_ECP_MAX_BYTES )
{
ret = MBEDTLS_ERR_ECP_RANDOM_FAILED;
goto cleanup;
}
MBEDTLS_MPI_CHK( mbedtls_mpi_write_binary( secret,
secret_bytes, secret_len ) );
ret = mbedtls_ctr_drbg_seed( ctx, ecp_ctr_drbg_null_entropy, NULL,
secret_bytes, secret_len );
cleanup:
mbedtls_platform_zeroize( secret_bytes, secret_len );
return( ret );
}
#else
#error "Invalid configuration detected. Include check_config.h to ensure that the configuration is valid."
#endif /* DRBG modules */
#endif /* MBEDTLS_ECP_NO_INTERNAL_RNG */
#if defined(MBEDTLS_ECP_RESTARTABLE)
/*
* Maximum number of "basic operations" to be done in a row.
*
* Default value 0 means that ECC operations will not yield.
* Note that regardless of the value of ecp_max_ops, always at
* least one step is performed before yielding.
*
* Setting ecp_max_ops=1 can be suitable for testing purposes
* as it will interrupt computation at all possible points.
*/
static unsigned ecp_max_ops = 0;
/*
* Set ecp_max_ops
*/
void mbedtls_ecp_set_max_ops( unsigned max_ops )
{
ecp_max_ops = max_ops;
}
/*
* Check if restart is enabled
*/
int mbedtls_ecp_restart_is_enabled( void )
{
return( ecp_max_ops != 0 );
}
/*
* Restart sub-context for ecp_mul_comb()
*/
struct mbedtls_ecp_restart_mul
{
mbedtls_ecp_point R; /* current intermediate result */
size_t i; /* current index in various loops, 0 outside */
mbedtls_ecp_point *T; /* table for precomputed points */
unsigned char T_size; /* number of points in table T */
enum { /* what were we doing last time we returned? */
ecp_rsm_init = 0, /* nothing so far, dummy initial state */
ecp_rsm_pre_dbl, /* precompute 2^n multiples */
ecp_rsm_pre_norm_dbl, /* normalize precomputed 2^n multiples */
ecp_rsm_pre_add, /* precompute remaining points by adding */
ecp_rsm_pre_norm_add, /* normalize all precomputed points */
ecp_rsm_comb_core, /* ecp_mul_comb_core() */
ecp_rsm_final_norm, /* do the final normalization */
} state;
#if !defined(MBEDTLS_ECP_NO_INTERNAL_RNG)
ecp_drbg_context drbg_ctx;
unsigned char drbg_seeded;
#endif
};
/*
* Init restart_mul sub-context
*/
static void ecp_restart_rsm_init( mbedtls_ecp_restart_mul_ctx *ctx )
{
mbedtls_ecp_point_init( &ctx->R );
ctx->i = 0;
ctx->T = NULL;
ctx->T_size = 0;
ctx->state = ecp_rsm_init;
#if !defined(MBEDTLS_ECP_NO_INTERNAL_RNG)
ecp_drbg_init( &ctx->drbg_ctx );
ctx->drbg_seeded = 0;
#endif
}
/*
* Free the components of a restart_mul sub-context
*/
static void ecp_restart_rsm_free( mbedtls_ecp_restart_mul_ctx *ctx )
{
unsigned char i;
if( ctx == NULL )
return;
mbedtls_ecp_point_free( &ctx->R );
if( ctx->T != NULL )
{
for( i = 0; i < ctx->T_size; i++ )
mbedtls_ecp_point_free( ctx->T + i );
mbedtls_free( ctx->T );
}
#if !defined(MBEDTLS_ECP_NO_INTERNAL_RNG)
ecp_drbg_free( &ctx->drbg_ctx );
#endif
ecp_restart_rsm_init( ctx );
}
/*
* Restart context for ecp_muladd()
*/
struct mbedtls_ecp_restart_muladd
{
mbedtls_ecp_point mP; /* mP value */
mbedtls_ecp_point R; /* R intermediate result */
enum { /* what should we do next? */
ecp_rsma_mul1 = 0, /* first multiplication */
ecp_rsma_mul2, /* second multiplication */
ecp_rsma_add, /* addition */
ecp_rsma_norm, /* normalization */
} state;
};
/*
* Init restart_muladd sub-context
*/
static void ecp_restart_ma_init( mbedtls_ecp_restart_muladd_ctx *ctx )
{
mbedtls_ecp_point_init( &ctx->mP );
mbedtls_ecp_point_init( &ctx->R );
ctx->state = ecp_rsma_mul1;
}
/*
* Free the components of a restart_muladd sub-context
*/
static void ecp_restart_ma_free( mbedtls_ecp_restart_muladd_ctx *ctx )
{
if( ctx == NULL )
return;
mbedtls_ecp_point_free( &ctx->mP );
mbedtls_ecp_point_free( &ctx->R );
ecp_restart_ma_init( ctx );
}
/*
* Initialize a restart context
*/
void mbedtls_ecp_restart_init( mbedtls_ecp_restart_ctx *ctx )
{
ECP_VALIDATE( ctx != NULL );
ctx->ops_done = 0;
ctx->depth = 0;
ctx->rsm = NULL;
ctx->ma = NULL;
}
/*
* Free the components of a restart context
*/
void mbedtls_ecp_restart_free( mbedtls_ecp_restart_ctx *ctx )
{
if( ctx == NULL )
return;
ecp_restart_rsm_free( ctx->rsm );
mbedtls_free( ctx->rsm );
ecp_restart_ma_free( ctx->ma );
mbedtls_free( ctx->ma );
mbedtls_ecp_restart_init( ctx );
}
/*
* Check if we can do the next step
*/
int mbedtls_ecp_check_budget( const mbedtls_ecp_group *grp,
mbedtls_ecp_restart_ctx *rs_ctx,
unsigned ops )
{
ECP_VALIDATE_RET( grp != NULL );
if( rs_ctx != NULL && ecp_max_ops != 0 )
{
/* scale depending on curve size: the chosen reference is 256-bit,
* and multiplication is quadratic. Round to the closest integer. */
if( grp->pbits >= 512 )
ops *= 4;
else if( grp->pbits >= 384 )
ops *= 2;
/* Avoid infinite loops: always allow first step.
* Because of that, however, it's not generally true
* that ops_done <= ecp_max_ops, so the check
* ops_done > ecp_max_ops below is mandatory. */
if( ( rs_ctx->ops_done != 0 ) &&
( rs_ctx->ops_done > ecp_max_ops ||
ops > ecp_max_ops - rs_ctx->ops_done ) )
{
return( MBEDTLS_ERR_ECP_IN_PROGRESS );
}
/* update running count */
rs_ctx->ops_done += ops;
}
return( 0 );
}
/* Call this when entering a function that needs its own sub-context */
#define ECP_RS_ENTER( SUB ) do { \
/* reset ops count for this call if top-level */ \
if( rs_ctx != NULL && rs_ctx->depth++ == 0 ) \
rs_ctx->ops_done = 0; \
\
/* set up our own sub-context if needed */ \
if( mbedtls_ecp_restart_is_enabled() && \
rs_ctx != NULL && rs_ctx->SUB == NULL ) \
{ \
rs_ctx->SUB = mbedtls_calloc( 1, sizeof( *rs_ctx->SUB ) ); \
if( rs_ctx->SUB == NULL ) \
return( MBEDTLS_ERR_ECP_ALLOC_FAILED ); \
\
ecp_restart_## SUB ##_init( rs_ctx->SUB ); \
} \
} while( 0 )
/* Call this when leaving a function that needs its own sub-context */
#define ECP_RS_LEAVE( SUB ) do { \
/* clear our sub-context when not in progress (done or error) */ \
if( rs_ctx != NULL && rs_ctx->SUB != NULL && \
ret != MBEDTLS_ERR_ECP_IN_PROGRESS ) \
{ \
ecp_restart_## SUB ##_free( rs_ctx->SUB ); \
mbedtls_free( rs_ctx->SUB ); \
rs_ctx->SUB = NULL; \
} \
\
if( rs_ctx != NULL ) \
rs_ctx->depth--; \
} while( 0 )
#else /* MBEDTLS_ECP_RESTARTABLE */
#define ECP_RS_ENTER( sub ) (void) rs_ctx;
#define ECP_RS_LEAVE( sub ) (void) rs_ctx;
#endif /* MBEDTLS_ECP_RESTARTABLE */
/*
* List of supported curves:
* - internal ID
* - TLS NamedCurve ID (RFC 4492 sec. 5.1.1, RFC 7071 sec. 2, RFC 8446 sec. 4.2.7)
* - size in bits
* - readable name
*
* Curves are listed in order: largest curves first, and for a given size,
* fastest curves first. This provides the default order for the SSL module.
*
* Reminder: update profiles in x509_crt.c when adding a new curves!
*/
static const mbedtls_ecp_curve_info ecp_supported_curves[] =
{
#if defined(MBEDTLS_ECP_DP_SECP521R1_ENABLED)
{ MBEDTLS_ECP_DP_SECP521R1, 25, 521, "secp521r1" },
#endif
#if defined(MBEDTLS_ECP_DP_BP512R1_ENABLED)
{ MBEDTLS_ECP_DP_BP512R1, 28, 512, "brainpoolP512r1" },
#endif
#if defined(MBEDTLS_ECP_DP_SECP384R1_ENABLED)
{ MBEDTLS_ECP_DP_SECP384R1, 24, 384, "secp384r1" },
#endif
#if defined(MBEDTLS_ECP_DP_BP384R1_ENABLED)
{ MBEDTLS_ECP_DP_BP384R1, 27, 384, "brainpoolP384r1" },
#endif
#if defined(MBEDTLS_ECP_DP_SECP256R1_ENABLED)
{ MBEDTLS_ECP_DP_SECP256R1, 23, 256, "secp256r1" },
#endif
#if defined(MBEDTLS_ECP_DP_SECP256K1_ENABLED)
{ MBEDTLS_ECP_DP_SECP256K1, 22, 256, "secp256k1" },
#endif
#if defined(MBEDTLS_ECP_DP_BP256R1_ENABLED)
{ MBEDTLS_ECP_DP_BP256R1, 26, 256, "brainpoolP256r1" },
#endif
#if defined(MBEDTLS_ECP_DP_SECP224R1_ENABLED)
{ MBEDTLS_ECP_DP_SECP224R1, 21, 224, "secp224r1" },
#endif
#if defined(MBEDTLS_ECP_DP_SECP224K1_ENABLED)
{ MBEDTLS_ECP_DP_SECP224K1, 20, 224, "secp224k1" },
#endif
#if defined(MBEDTLS_ECP_DP_SECP192R1_ENABLED)
{ MBEDTLS_ECP_DP_SECP192R1, 19, 192, "secp192r1" },
#endif
#if defined(MBEDTLS_ECP_DP_SECP192K1_ENABLED)
{ MBEDTLS_ECP_DP_SECP192K1, 18, 192, "secp192k1" },
#endif
#if defined(MBEDTLS_ECP_DP_CURVE25519_ENABLED)
{ MBEDTLS_ECP_DP_CURVE25519, 29, 256, "x25519" },
#endif
#if defined(MBEDTLS_ECP_DP_CURVE448_ENABLED)
{ MBEDTLS_ECP_DP_CURVE448, 30, 448, "x448" },
#endif
{ MBEDTLS_ECP_DP_NONE, 0, 0, NULL },
};
#define ECP_NB_CURVES sizeof( ecp_supported_curves ) / \
sizeof( ecp_supported_curves[0] )
static mbedtls_ecp_group_id ecp_supported_grp_id[ECP_NB_CURVES];
/*
* List of supported curves and associated info
*/
const mbedtls_ecp_curve_info *mbedtls_ecp_curve_list( void )
{
return( ecp_supported_curves );
}
/*
* List of supported curves, group ID only
*/
const mbedtls_ecp_group_id *mbedtls_ecp_grp_id_list( void )
{
static int init_done = 0;
if( ! init_done )
{
size_t i = 0;
const mbedtls_ecp_curve_info *curve_info;
for( curve_info = mbedtls_ecp_curve_list();
curve_info->grp_id != MBEDTLS_ECP_DP_NONE;
curve_info++ )
{
ecp_supported_grp_id[i++] = curve_info->grp_id;
}
ecp_supported_grp_id[i] = MBEDTLS_ECP_DP_NONE;
init_done = 1;
}
return( ecp_supported_grp_id );
}
/*
* Get the curve info for the internal identifier
*/
const mbedtls_ecp_curve_info *mbedtls_ecp_curve_info_from_grp_id( mbedtls_ecp_group_id grp_id )
{
const mbedtls_ecp_curve_info *curve_info;
for( curve_info = mbedtls_ecp_curve_list();
curve_info->grp_id != MBEDTLS_ECP_DP_NONE;
curve_info++ )
{
if( curve_info->grp_id == grp_id )
return( curve_info );
}
return( NULL );
}
/*
* Get the curve info from the TLS identifier
*/
const mbedtls_ecp_curve_info *mbedtls_ecp_curve_info_from_tls_id( uint16_t tls_id )
{
const mbedtls_ecp_curve_info *curve_info;
for( curve_info = mbedtls_ecp_curve_list();
curve_info->grp_id != MBEDTLS_ECP_DP_NONE;
curve_info++ )
{
if( curve_info->tls_id == tls_id )
return( curve_info );
}
return( NULL );
}
/*
* Get the curve info from the name
*/
const mbedtls_ecp_curve_info *mbedtls_ecp_curve_info_from_name( const char *name )
{
const mbedtls_ecp_curve_info *curve_info;
if( name == NULL )
return( NULL );
for( curve_info = mbedtls_ecp_curve_list();
curve_info->grp_id != MBEDTLS_ECP_DP_NONE;
curve_info++ )
{
if( strcmp( curve_info->name, name ) == 0 )
return( curve_info );
}
return( NULL );
}
/*
* Get the type of a curve
*/
mbedtls_ecp_curve_type mbedtls_ecp_get_type( const mbedtls_ecp_group *grp )
{
if( grp->G.X.p == NULL )
return( MBEDTLS_ECP_TYPE_NONE );
if( grp->G.Y.p == NULL )
return( MBEDTLS_ECP_TYPE_MONTGOMERY );
else
return( MBEDTLS_ECP_TYPE_SHORT_WEIERSTRASS );
}
/*
* Initialize (the components of) a point
*/
void mbedtls_ecp_point_init( mbedtls_ecp_point *pt )
{
ECP_VALIDATE( pt != NULL );
mbedtls_mpi_init( &pt->X );
mbedtls_mpi_init( &pt->Y );
mbedtls_mpi_init( &pt->Z );
}
/*
* Initialize (the components of) a group
*/
void mbedtls_ecp_group_init( mbedtls_ecp_group *grp )
{
ECP_VALIDATE( grp != NULL );
grp->id = MBEDTLS_ECP_DP_NONE;
mbedtls_mpi_init( &grp->P );
mbedtls_mpi_init( &grp->A );
mbedtls_mpi_init( &grp->B );
mbedtls_ecp_point_init( &grp->G );
mbedtls_mpi_init( &grp->N );
grp->pbits = 0;
grp->nbits = 0;
grp->h = 0;
grp->modp = NULL;
grp->t_pre = NULL;
grp->t_post = NULL;
grp->t_data = NULL;
grp->T = NULL;
grp->T_size = 0;
}
/*
* Initialize (the components of) a key pair
*/
void mbedtls_ecp_keypair_init( mbedtls_ecp_keypair *key )
{
ECP_VALIDATE( key != NULL );
mbedtls_ecp_group_init( &key->grp );
mbedtls_mpi_init( &key->d );
mbedtls_ecp_point_init( &key->Q );
}
/*
* Unallocate (the components of) a point
*/
void mbedtls_ecp_point_free( mbedtls_ecp_point *pt )
{
if( pt == NULL )
return;
mbedtls_mpi_free( &( pt->X ) );
mbedtls_mpi_free( &( pt->Y ) );
mbedtls_mpi_free( &( pt->Z ) );
}
/*
* Unallocate (the components of) a group
*/
void mbedtls_ecp_group_free( mbedtls_ecp_group *grp )
{
size_t i;
if( grp == NULL )
return;
if( grp->h != 1 )
{
mbedtls_mpi_free( &grp->P );
mbedtls_mpi_free( &grp->A );
mbedtls_mpi_free( &grp->B );
mbedtls_ecp_point_free( &grp->G );
mbedtls_mpi_free( &grp->N );
}
if( grp->T != NULL )
{
for( i = 0; i < grp->T_size; i++ )
mbedtls_ecp_point_free( &grp->T[i] );
mbedtls_free( grp->T );
}
mbedtls_platform_zeroize( grp, sizeof( mbedtls_ecp_group ) );
}
/*
* Unallocate (the components of) a key pair
*/
void mbedtls_ecp_keypair_free( mbedtls_ecp_keypair *key )
{
if( key == NULL )
return;
mbedtls_ecp_group_free( &key->grp );
mbedtls_mpi_free( &key->d );
mbedtls_ecp_point_free( &key->Q );
}
/*
* Copy the contents of a point
*/
int mbedtls_ecp_copy( mbedtls_ecp_point *P, const mbedtls_ecp_point *Q )
{
int ret = MBEDTLS_ERR_ERROR_CORRUPTION_DETECTED;
ECP_VALIDATE_RET( P != NULL );
ECP_VALIDATE_RET( Q != NULL );
MBEDTLS_MPI_CHK( mbedtls_mpi_copy( &P->X, &Q->X ) );
MBEDTLS_MPI_CHK( mbedtls_mpi_copy( &P->Y, &Q->Y ) );
MBEDTLS_MPI_CHK( mbedtls_mpi_copy( &P->Z, &Q->Z ) );
cleanup:
return( ret );
}
/*
* Copy the contents of a group object
*/
int mbedtls_ecp_group_copy( mbedtls_ecp_group *dst, const mbedtls_ecp_group *src )
{
ECP_VALIDATE_RET( dst != NULL );
ECP_VALIDATE_RET( src != NULL );
return( mbedtls_ecp_group_load( dst, src->id ) );
}
/*
* Set point to zero
*/
int mbedtls_ecp_set_zero( mbedtls_ecp_point *pt )
{
int ret = MBEDTLS_ERR_ERROR_CORRUPTION_DETECTED;
ECP_VALIDATE_RET( pt != NULL );
MBEDTLS_MPI_CHK( mbedtls_mpi_lset( &pt->X , 1 ) );
MBEDTLS_MPI_CHK( mbedtls_mpi_lset( &pt->Y , 1 ) );
MBEDTLS_MPI_CHK( mbedtls_mpi_lset( &pt->Z , 0 ) );
cleanup:
return( ret );
}
/*
* Tell if a point is zero
*/
int mbedtls_ecp_is_zero( mbedtls_ecp_point *pt )
{
ECP_VALIDATE_RET( pt != NULL );
return( mbedtls_mpi_cmp_int( &pt->Z, 0 ) == 0 );
}
/*
* Compare two points lazily
*/
int mbedtls_ecp_point_cmp( const mbedtls_ecp_point *P,
const mbedtls_ecp_point *Q )
{
ECP_VALIDATE_RET( P != NULL );
ECP_VALIDATE_RET( Q != NULL );
if( mbedtls_mpi_cmp_mpi( &P->X, &Q->X ) == 0 &&
mbedtls_mpi_cmp_mpi( &P->Y, &Q->Y ) == 0 &&
mbedtls_mpi_cmp_mpi( &P->Z, &Q->Z ) == 0 )
{
return( 0 );
}
return( MBEDTLS_ERR_ECP_BAD_INPUT_DATA );
}
/*
* Import a non-zero point from ASCII strings
*/
int mbedtls_ecp_point_read_string( mbedtls_ecp_point *P, int radix,
const char *x, const char *y )
{
int ret = MBEDTLS_ERR_ERROR_CORRUPTION_DETECTED;
ECP_VALIDATE_RET( P != NULL );
ECP_VALIDATE_RET( x != NULL );
ECP_VALIDATE_RET( y != NULL );
MBEDTLS_MPI_CHK( mbedtls_mpi_read_string( &P->X, radix, x ) );
MBEDTLS_MPI_CHK( mbedtls_mpi_read_string( &P->Y, radix, y ) );
MBEDTLS_MPI_CHK( mbedtls_mpi_lset( &P->Z, 1 ) );
cleanup:
return( ret );
}
/*
* Export a point into unsigned binary data (SEC1 2.3.3 and RFC7748)
*/
int mbedtls_ecp_point_write_binary( const mbedtls_ecp_group *grp,
const mbedtls_ecp_point *P,
int format, size_t *olen,
unsigned char *buf, size_t buflen )
{
int ret = MBEDTLS_ERR_ECP_FEATURE_UNAVAILABLE;
size_t plen;
ECP_VALIDATE_RET( grp != NULL );
ECP_VALIDATE_RET( P != NULL );
ECP_VALIDATE_RET( olen != NULL );
ECP_VALIDATE_RET( buf != NULL );
ECP_VALIDATE_RET( format == MBEDTLS_ECP_PF_UNCOMPRESSED ||
format == MBEDTLS_ECP_PF_COMPRESSED );
plen = mbedtls_mpi_size( &grp->P );
#if defined(MBEDTLS_ECP_MONTGOMERY_ENABLED)
(void) format; /* Montgomery curves always use the same point format */
if( mbedtls_ecp_get_type( grp ) == MBEDTLS_ECP_TYPE_MONTGOMERY )
{
*olen = plen;
if( buflen < *olen )
return( MBEDTLS_ERR_ECP_BUFFER_TOO_SMALL );
MBEDTLS_MPI_CHK( mbedtls_mpi_write_binary_le( &P->X, buf, plen ) );
}
#endif
#if defined(MBEDTLS_ECP_SHORT_WEIERSTRASS_ENABLED)
if( mbedtls_ecp_get_type( grp ) == MBEDTLS_ECP_TYPE_SHORT_WEIERSTRASS )
{
/*
* Common case: P == 0
*/
if( mbedtls_mpi_cmp_int( &P->Z, 0 ) == 0 )
{
if( buflen < 1 )
return( MBEDTLS_ERR_ECP_BUFFER_TOO_SMALL );
buf[0] = 0x00;
*olen = 1;
return( 0 );
}
if( format == MBEDTLS_ECP_PF_UNCOMPRESSED )
{
*olen = 2 * plen + 1;
if( buflen < *olen )
return( MBEDTLS_ERR_ECP_BUFFER_TOO_SMALL );
buf[0] = 0x04;
MBEDTLS_MPI_CHK( mbedtls_mpi_write_binary( &P->X, buf + 1, plen ) );
MBEDTLS_MPI_CHK( mbedtls_mpi_write_binary( &P->Y, buf + 1 + plen, plen ) );
}
else if( format == MBEDTLS_ECP_PF_COMPRESSED )
{
*olen = plen + 1;
if( buflen < *olen )
return( MBEDTLS_ERR_ECP_BUFFER_TOO_SMALL );
buf[0] = 0x02 + mbedtls_mpi_get_bit( &P->Y, 0 );
MBEDTLS_MPI_CHK( mbedtls_mpi_write_binary( &P->X, buf + 1, plen ) );
}
}
#endif
cleanup:
return( ret );
}
/*
* Import a point from unsigned binary data (SEC1 2.3.4 and RFC7748)
*/
int mbedtls_ecp_point_read_binary( const mbedtls_ecp_group *grp,
mbedtls_ecp_point *pt,
const unsigned char *buf, size_t ilen )
{
int ret = MBEDTLS_ERR_ECP_FEATURE_UNAVAILABLE;
size_t plen;
ECP_VALIDATE_RET( grp != NULL );
ECP_VALIDATE_RET( pt != NULL );
ECP_VALIDATE_RET( buf != NULL );
if( ilen < 1 )
return( MBEDTLS_ERR_ECP_BAD_INPUT_DATA );
plen = mbedtls_mpi_size( &grp->P );
#if defined(MBEDTLS_ECP_MONTGOMERY_ENABLED)
if( mbedtls_ecp_get_type( grp ) == MBEDTLS_ECP_TYPE_MONTGOMERY )
{
if( plen != ilen )
return( MBEDTLS_ERR_ECP_BAD_INPUT_DATA );
MBEDTLS_MPI_CHK( mbedtls_mpi_read_binary_le( &pt->X, buf, plen ) );
mbedtls_mpi_free( &pt->Y );
if( grp->id == MBEDTLS_ECP_DP_CURVE25519 )
/* Set most significant bit to 0 as prescribed in RFC7748 §5 */
MBEDTLS_MPI_CHK( mbedtls_mpi_set_bit( &pt->X, plen * 8 - 1, 0 ) );
MBEDTLS_MPI_CHK( mbedtls_mpi_lset( &pt->Z, 1 ) );
}
#endif
#if defined(MBEDTLS_ECP_SHORT_WEIERSTRASS_ENABLED)
if( mbedtls_ecp_get_type( grp ) == MBEDTLS_ECP_TYPE_SHORT_WEIERSTRASS )
{
if( buf[0] == 0x00 )
{
if( ilen == 1 )
return( mbedtls_ecp_set_zero( pt ) );
else
return( MBEDTLS_ERR_ECP_BAD_INPUT_DATA );
}
if( buf[0] != 0x04 )
return( MBEDTLS_ERR_ECP_FEATURE_UNAVAILABLE );
if( ilen != 2 * plen + 1 )
return( MBEDTLS_ERR_ECP_BAD_INPUT_DATA );
MBEDTLS_MPI_CHK( mbedtls_mpi_read_binary( &pt->X, buf + 1, plen ) );
MBEDTLS_MPI_CHK( mbedtls_mpi_read_binary( &pt->Y,
buf + 1 + plen, plen ) );
MBEDTLS_MPI_CHK( mbedtls_mpi_lset( &pt->Z, 1 ) );
}
#endif
cleanup:
return( ret );
}
/*
* Import a point from a TLS ECPoint record (RFC 4492)
* struct {
* opaque point <1..2^8-1>;
* } ECPoint;
*/
int mbedtls_ecp_tls_read_point( const mbedtls_ecp_group *grp,
mbedtls_ecp_point *pt,
const unsigned char **buf, size_t buf_len )
{
unsigned char data_len;
const unsigned char *buf_start;
ECP_VALIDATE_RET( grp != NULL );
ECP_VALIDATE_RET( pt != NULL );
ECP_VALIDATE_RET( buf != NULL );
ECP_VALIDATE_RET( *buf != NULL );
/*
* We must have at least two bytes (1 for length, at least one for data)
*/
if( buf_len < 2 )
return( MBEDTLS_ERR_ECP_BAD_INPUT_DATA );
data_len = *(*buf)++;
if( data_len < 1 || data_len > buf_len - 1 )
return( MBEDTLS_ERR_ECP_BAD_INPUT_DATA );
/*
* Save buffer start for read_binary and update buf
*/
buf_start = *buf;
*buf += data_len;
return( mbedtls_ecp_point_read_binary( grp, pt, buf_start, data_len ) );
}
/*
* Export a point as a TLS ECPoint record (RFC 4492)
* struct {
* opaque point <1..2^8-1>;
* } ECPoint;
*/
int mbedtls_ecp_tls_write_point( const mbedtls_ecp_group *grp, const mbedtls_ecp_point *pt,
int format, size_t *olen,
unsigned char *buf, size_t blen )
{
int ret = MBEDTLS_ERR_ERROR_CORRUPTION_DETECTED;
ECP_VALIDATE_RET( grp != NULL );
ECP_VALIDATE_RET( pt != NULL );
ECP_VALIDATE_RET( olen != NULL );
ECP_VALIDATE_RET( buf != NULL );
ECP_VALIDATE_RET( format == MBEDTLS_ECP_PF_UNCOMPRESSED ||
format == MBEDTLS_ECP_PF_COMPRESSED );
/*
* buffer length must be at least one, for our length byte
*/
if( blen < 1 )
return( MBEDTLS_ERR_ECP_BAD_INPUT_DATA );
if( ( ret = mbedtls_ecp_point_write_binary( grp, pt, format,
olen, buf + 1, blen - 1) ) != 0 )
return( ret );
/*
* write length to the first byte and update total length
*/
buf[0] = (unsigned char) *olen;
++*olen;
return( 0 );
}
/*
* Set a group from an ECParameters record (RFC 4492)
*/
int mbedtls_ecp_tls_read_group( mbedtls_ecp_group *grp,
const unsigned char **buf, size_t len )
{
int ret = MBEDTLS_ERR_ERROR_CORRUPTION_DETECTED;
mbedtls_ecp_group_id grp_id;
ECP_VALIDATE_RET( grp != NULL );
ECP_VALIDATE_RET( buf != NULL );
ECP_VALIDATE_RET( *buf != NULL );
if( ( ret = mbedtls_ecp_tls_read_group_id( &grp_id, buf, len ) ) != 0 )
return( ret );
return( mbedtls_ecp_group_load( grp, grp_id ) );
}
/*
* Read a group id from an ECParameters record (RFC 4492) and convert it to
* mbedtls_ecp_group_id.
*/
int mbedtls_ecp_tls_read_group_id( mbedtls_ecp_group_id *grp,
const unsigned char **buf, size_t len )
{
uint16_t tls_id;
const mbedtls_ecp_curve_info *curve_info;
ECP_VALIDATE_RET( grp != NULL );
ECP_VALIDATE_RET( buf != NULL );
ECP_VALIDATE_RET( *buf != NULL );
/*
* We expect at least three bytes (see below)
*/
if( len < 3 )
return( MBEDTLS_ERR_ECP_BAD_INPUT_DATA );
/*
* First byte is curve_type; only named_curve is handled
*/
if( *(*buf)++ != MBEDTLS_ECP_TLS_NAMED_CURVE )
return( MBEDTLS_ERR_ECP_BAD_INPUT_DATA );
/*
* Next two bytes are the namedcurve value
*/
tls_id = *(*buf)++;
tls_id <<= 8;
tls_id |= *(*buf)++;
if( ( curve_info = mbedtls_ecp_curve_info_from_tls_id( tls_id ) ) == NULL )
return( MBEDTLS_ERR_ECP_FEATURE_UNAVAILABLE );
*grp = curve_info->grp_id;
return( 0 );
}
/*
* Write the ECParameters record corresponding to a group (RFC 4492)
*/
int mbedtls_ecp_tls_write_group( const mbedtls_ecp_group *grp, size_t *olen,
unsigned char *buf, size_t blen )
{
const mbedtls_ecp_curve_info *curve_info;
ECP_VALIDATE_RET( grp != NULL );
ECP_VALIDATE_RET( buf != NULL );
ECP_VALIDATE_RET( olen != NULL );
if( ( curve_info = mbedtls_ecp_curve_info_from_grp_id( grp->id ) ) == NULL )
return( MBEDTLS_ERR_ECP_BAD_INPUT_DATA );
/*
* We are going to write 3 bytes (see below)
*/
*olen = 3;
if( blen < *olen )
return( MBEDTLS_ERR_ECP_BUFFER_TOO_SMALL );
/*
* First byte is curve_type, always named_curve
*/
*buf++ = MBEDTLS_ECP_TLS_NAMED_CURVE;
/*
* Next two bytes are the namedcurve value
*/
buf[0] = curve_info->tls_id >> 8;
buf[1] = curve_info->tls_id & 0xFF;
return( 0 );
}
/*
* Wrapper around fast quasi-modp functions, with fall-back to mbedtls_mpi_mod_mpi.
* See the documentation of struct mbedtls_ecp_group.
*
* This function is in the critial loop for mbedtls_ecp_mul, so pay attention to perf.
*/
static int ecp_modp( mbedtls_mpi *N, const mbedtls_ecp_group *grp )
{
int ret = MBEDTLS_ERR_ERROR_CORRUPTION_DETECTED;
if( grp->modp == NULL )
return( mbedtls_mpi_mod_mpi( N, N, &grp->P ) );
/* N->s < 0 is a much faster test, which fails only if N is 0 */
if( ( N->s < 0 && mbedtls_mpi_cmp_int( N, 0 ) != 0 ) ||
mbedtls_mpi_bitlen( N ) > 2 * grp->pbits )
{
return( MBEDTLS_ERR_ECP_BAD_INPUT_DATA );
}
MBEDTLS_MPI_CHK( grp->modp( N ) );
/* N->s < 0 is a much faster test, which fails only if N is 0 */
while( N->s < 0 && mbedtls_mpi_cmp_int( N, 0 ) != 0 )
MBEDTLS_MPI_CHK( mbedtls_mpi_add_mpi( N, N, &grp->P ) );
while( mbedtls_mpi_cmp_mpi( N, &grp->P ) >= 0 )
/* we known P, N and the result are positive */
MBEDTLS_MPI_CHK( mbedtls_mpi_sub_abs( N, N, &grp->P ) );
cleanup:
return( ret );
}
/*
* Fast mod-p functions expect their argument to be in the 0..p^2 range.
*
* In order to guarantee that, we need to ensure that operands of
* mbedtls_mpi_mul_mpi are in the 0..p range. So, after each operation we will
* bring the result back to this range.
*
* The following macros are shortcuts for doing that.
*/
/*
* Reduce a mbedtls_mpi mod p in-place, general case, to use after mbedtls_mpi_mul_mpi
*/
#if defined(MBEDTLS_SELF_TEST)
#define INC_MUL_COUNT mul_count++;
#else
#define INC_MUL_COUNT
#endif
#define MOD_MUL( N ) \
do \
{ \
MBEDTLS_MPI_CHK( ecp_modp( &(N), grp ) ); \
INC_MUL_COUNT \
} while( 0 )
static inline int mbedtls_mpi_mul_mod( const mbedtls_ecp_group *grp,
mbedtls_mpi *X,
const mbedtls_mpi *A,
const mbedtls_mpi *B )
{
int ret = MBEDTLS_ERR_ERROR_CORRUPTION_DETECTED;
MBEDTLS_MPI_CHK( mbedtls_mpi_mul_mpi( X, A, B ) );
MOD_MUL( *X );
cleanup:
return( ret );
}
/*
* Reduce a mbedtls_mpi mod p in-place, to use after mbedtls_mpi_sub_mpi
* N->s < 0 is a very fast test, which fails only if N is 0
*/
#define MOD_SUB( N ) \
while( (N).s < 0 && mbedtls_mpi_cmp_int( &(N), 0 ) != 0 ) \
MBEDTLS_MPI_CHK( mbedtls_mpi_add_mpi( &(N), &(N), &grp->P ) )
#if ( defined(MBEDTLS_ECP_SHORT_WEIERSTRASS_ENABLED) && \
!( defined(MBEDTLS_ECP_NO_FALLBACK) && \
defined(MBEDTLS_ECP_DOUBLE_JAC_ALT) && \
defined(MBEDTLS_ECP_ADD_MIXED_ALT) ) ) || \
( defined(MBEDTLS_ECP_MONTGOMERY_ENABLED) && \
!( defined(MBEDTLS_ECP_NO_FALLBACK) && \
defined(MBEDTLS_ECP_DOUBLE_ADD_MXZ_ALT) ) )
static inline int mbedtls_mpi_sub_mod( const mbedtls_ecp_group *grp,
mbedtls_mpi *X,
const mbedtls_mpi *A,
const mbedtls_mpi *B )
{
int ret = MBEDTLS_ERR_ERROR_CORRUPTION_DETECTED;
MBEDTLS_MPI_CHK( mbedtls_mpi_sub_mpi( X, A, B ) );
MOD_SUB( *X );
cleanup:
return( ret );
}
#endif /* All functions referencing mbedtls_mpi_sub_mod() are alt-implemented without fallback */
/*
* Reduce a mbedtls_mpi mod p in-place, to use after mbedtls_mpi_add_mpi and mbedtls_mpi_mul_int.
* We known P, N and the result are positive, so sub_abs is correct, and
* a bit faster.
*/
#define MOD_ADD( N ) \
while( mbedtls_mpi_cmp_mpi( &(N), &grp->P ) >= 0 ) \
MBEDTLS_MPI_CHK( mbedtls_mpi_sub_abs( &(N), &(N), &grp->P ) )
static inline int mbedtls_mpi_add_mod( const mbedtls_ecp_group *grp,
mbedtls_mpi *X,
const mbedtls_mpi *A,
const mbedtls_mpi *B )
{
int ret = MBEDTLS_ERR_ERROR_CORRUPTION_DETECTED;
MBEDTLS_MPI_CHK( mbedtls_mpi_add_mpi( X, A, B ) );
MOD_ADD( *X );
cleanup:
return( ret );
}
#if defined(MBEDTLS_ECP_SHORT_WEIERSTRASS_ENABLED) && \
!( defined(MBEDTLS_ECP_NO_FALLBACK) && \
defined(MBEDTLS_ECP_DOUBLE_JAC_ALT) && \
defined(MBEDTLS_ECP_ADD_MIXED_ALT) )
static inline int mbedtls_mpi_shift_l_mod( const mbedtls_ecp_group *grp,
mbedtls_mpi *X,
size_t count )
{
int ret = MBEDTLS_ERR_ERROR_CORRUPTION_DETECTED;
MBEDTLS_MPI_CHK( mbedtls_mpi_shift_l( X, count ) );
MOD_ADD( *X );
cleanup:
return( ret );
}
#endif /* All functions referencing mbedtls_mpi_shift_l_mod() are alt-implemented without fallback */
#if defined(MBEDTLS_ECP_SHORT_WEIERSTRASS_ENABLED)
/*
* For curves in short Weierstrass form, we do all the internal operations in
* Jacobian coordinates.
*
* For multiplication, we'll use a comb method with coutermeasueres against
* SPA, hence timing attacks.
*/
/*
* Normalize jacobian coordinates so that Z == 0 || Z == 1 (GECC 3.2.1)
* Cost: 1N := 1I + 3M + 1S
*/
static int ecp_normalize_jac( const mbedtls_ecp_group *grp, mbedtls_ecp_point *pt )
{
if( mbedtls_mpi_cmp_int( &pt->Z, 0 ) == 0 )
return( 0 );
#if defined(MBEDTLS_ECP_NORMALIZE_JAC_ALT)
if( mbedtls_internal_ecp_grp_capable( grp ) )
return( mbedtls_internal_ecp_normalize_jac( grp, pt ) );
#endif /* MBEDTLS_ECP_NORMALIZE_JAC_ALT */
#if defined(MBEDTLS_ECP_NO_FALLBACK) && defined(MBEDTLS_ECP_NORMALIZE_JAC_ALT)
return( MBEDTLS_ERR_ECP_FEATURE_UNAVAILABLE );
#else
int ret = MBEDTLS_ERR_ERROR_CORRUPTION_DETECTED;
mbedtls_mpi Zi, ZZi;
mbedtls_mpi_init( &Zi ); mbedtls_mpi_init( &ZZi );
/*
* X = X / Z^2 mod p
*/
MBEDTLS_MPI_CHK( mbedtls_mpi_inv_mod( &Zi, &pt->Z, &grp->P ) );
MBEDTLS_MPI_CHK( mbedtls_mpi_mul_mod( grp, &ZZi, &Zi, &Zi ) );
MBEDTLS_MPI_CHK( mbedtls_mpi_mul_mod( grp, &pt->X, &pt->X, &ZZi ) );
/*
* Y = Y / Z^3 mod p
*/
MBEDTLS_MPI_CHK( mbedtls_mpi_mul_mod( grp, &pt->Y, &pt->Y, &ZZi ) );
MBEDTLS_MPI_CHK( mbedtls_mpi_mul_mod( grp, &pt->Y, &pt->Y, &Zi ) );
/*
* Z = 1
*/
MBEDTLS_MPI_CHK( mbedtls_mpi_lset( &pt->Z, 1 ) );
cleanup:
mbedtls_mpi_free( &Zi ); mbedtls_mpi_free( &ZZi );
return( ret );
#endif /* !defined(MBEDTLS_ECP_NO_FALLBACK) || !defined(MBEDTLS_ECP_NORMALIZE_JAC_ALT) */
}
/*
* Normalize jacobian coordinates of an array of (pointers to) points,
* using Montgomery's trick to perform only one inversion mod P.
* (See for example Cohen's "A Course in Computational Algebraic Number
* Theory", Algorithm 10.3.4.)
*
* Warning: fails (returning an error) if one of the points is zero!
* This should never happen, see choice of w in ecp_mul_comb().
*
* Cost: 1N(t) := 1I + (6t - 3)M + 1S
*/
static int ecp_normalize_jac_many( const mbedtls_ecp_group *grp,
mbedtls_ecp_point *T[], size_t T_size )
{
if( T_size < 2 )
return( ecp_normalize_jac( grp, *T ) );
#if defined(MBEDTLS_ECP_NORMALIZE_JAC_MANY_ALT)
if( mbedtls_internal_ecp_grp_capable( grp ) )
return( mbedtls_internal_ecp_normalize_jac_many( grp, T, T_size ) );
#endif
#if defined(MBEDTLS_ECP_NO_FALLBACK) && defined(MBEDTLS_ECP_NORMALIZE_JAC_MANY_ALT)
return( MBEDTLS_ERR_ECP_FEATURE_UNAVAILABLE );
#else
int ret = MBEDTLS_ERR_ERROR_CORRUPTION_DETECTED;
size_t i;
mbedtls_mpi *c, u, Zi, ZZi;
if( ( c = mbedtls_calloc( T_size, sizeof( mbedtls_mpi ) ) ) == NULL )
return( MBEDTLS_ERR_ECP_ALLOC_FAILED );
for( i = 0; i < T_size; i++ )
mbedtls_mpi_init( &c[i] );
mbedtls_mpi_init( &u ); mbedtls_mpi_init( &Zi ); mbedtls_mpi_init( &ZZi );
/*
* c[i] = Z_0 * ... * Z_i
*/
MBEDTLS_MPI_CHK( mbedtls_mpi_copy( &c[0], &T[0]->Z ) );
for( i = 1; i < T_size; i++ )
{
MBEDTLS_MPI_CHK( mbedtls_mpi_mul_mod( grp, &c[i], &c[i-1], &T[i]->Z ) );
}
/*
* u = 1 / (Z_0 * ... * Z_n) mod P
*/
MBEDTLS_MPI_CHK( mbedtls_mpi_inv_mod( &u, &c[T_size-1], &grp->P ) );
for( i = T_size - 1; ; i-- )
{
/*
* Zi = 1 / Z_i mod p
* u = 1 / (Z_0 * ... * Z_i) mod P
*/
if( i == 0 ) {
MBEDTLS_MPI_CHK( mbedtls_mpi_copy( &Zi, &u ) );
}
else
{
MBEDTLS_MPI_CHK( mbedtls_mpi_mul_mod( grp, &Zi, &u, &c[i-1] ) );
MBEDTLS_MPI_CHK( mbedtls_mpi_mul_mod( grp, &u, &u, &T[i]->Z ) );
}
/*
* proceed as in normalize()
*/
MBEDTLS_MPI_CHK( mbedtls_mpi_mul_mod( grp, &ZZi, &Zi, &Zi ) );
MBEDTLS_MPI_CHK( mbedtls_mpi_mul_mod( grp, &T[i]->X, &T[i]->X, &ZZi ) );
MBEDTLS_MPI_CHK( mbedtls_mpi_mul_mod( grp, &T[i]->Y, &T[i]->Y, &ZZi ) );
MBEDTLS_MPI_CHK( mbedtls_mpi_mul_mod( grp, &T[i]->Y, &T[i]->Y, &Zi ) );
/*
* Post-precessing: reclaim some memory by shrinking coordinates
* - not storing Z (always 1)
* - shrinking other coordinates, but still keeping the same number of
* limbs as P, as otherwise it will too likely be regrown too fast.
*/
MBEDTLS_MPI_CHK( mbedtls_mpi_shrink( &T[i]->X, grp->P.n ) );
MBEDTLS_MPI_CHK( mbedtls_mpi_shrink( &T[i]->Y, grp->P.n ) );
mbedtls_mpi_free( &T[i]->Z );
if( i == 0 )
break;
}
cleanup:
mbedtls_mpi_free( &u ); mbedtls_mpi_free( &Zi ); mbedtls_mpi_free( &ZZi );
for( i = 0; i < T_size; i++ )
mbedtls_mpi_free( &c[i] );
mbedtls_free( c );
return( ret );
#endif /* !defined(MBEDTLS_ECP_NO_FALLBACK) || !defined(MBEDTLS_ECP_NORMALIZE_JAC_MANY_ALT) */
}
/*
* Conditional point inversion: Q -> -Q = (Q.X, -Q.Y, Q.Z) without leak.
* "inv" must be 0 (don't invert) or 1 (invert) or the result will be invalid
*/
static int ecp_safe_invert_jac( const mbedtls_ecp_group *grp,
mbedtls_ecp_point *Q,
unsigned char inv )
{
int ret = MBEDTLS_ERR_ERROR_CORRUPTION_DETECTED;
unsigned char nonzero;
mbedtls_mpi mQY;
mbedtls_mpi_init( &mQY );
/* Use the fact that -Q.Y mod P = P - Q.Y unless Q.Y == 0 */
MBEDTLS_MPI_CHK( mbedtls_mpi_sub_mpi( &mQY, &grp->P, &Q->Y ) );
nonzero = mbedtls_mpi_cmp_int( &Q->Y, 0 ) != 0;
MBEDTLS_MPI_CHK( mbedtls_mpi_safe_cond_assign( &Q->Y, &mQY, inv & nonzero ) );
cleanup:
mbedtls_mpi_free( &mQY );
return( ret );
}
/*
* Point doubling R = 2 P, Jacobian coordinates
*
* Based on http://www.hyperelliptic.org/EFD/g1p/auto-shortw-jacobian.html#doubling-dbl-1998-cmo-2 .
*
* We follow the variable naming fairly closely. The formula variations that trade a MUL for a SQR
* (plus a few ADDs) aren't useful as our bignum implementation doesn't distinguish squaring.
*
* Standard optimizations are applied when curve parameter A is one of { 0, -3 }.
*
* Cost: 1D := 3M + 4S (A == 0)
* 4M + 4S (A == -3)
* 3M + 6S + 1a otherwise
*/
static int ecp_double_jac( const mbedtls_ecp_group *grp, mbedtls_ecp_point *R,
const mbedtls_ecp_point *P )
{
#if defined(MBEDTLS_SELF_TEST)
dbl_count++;
#endif
#if defined(MBEDTLS_ECP_DOUBLE_JAC_ALT)
if( mbedtls_internal_ecp_grp_capable( grp ) )
return( mbedtls_internal_ecp_double_jac( grp, R, P ) );
#endif /* MBEDTLS_ECP_DOUBLE_JAC_ALT */
#if defined(MBEDTLS_ECP_NO_FALLBACK) && defined(MBEDTLS_ECP_DOUBLE_JAC_ALT)
return( MBEDTLS_ERR_ECP_FEATURE_UNAVAILABLE );
#else
int ret = MBEDTLS_ERR_ERROR_CORRUPTION_DETECTED;
mbedtls_mpi M, S, T, U;
mbedtls_mpi_init( &M ); mbedtls_mpi_init( &S ); mbedtls_mpi_init( &T ); mbedtls_mpi_init( &U );
/* Special case for A = -3 */
if( grp->A.p == NULL )
{
/* M = 3(X + Z^2)(X - Z^2) */
MBEDTLS_MPI_CHK( mbedtls_mpi_mul_mod( grp, &S, &P->Z, &P->Z ) );
MBEDTLS_MPI_CHK( mbedtls_mpi_add_mod( grp, &T, &P->X, &S ) );
MBEDTLS_MPI_CHK( mbedtls_mpi_sub_mod( grp, &U, &P->X, &S ) );
MBEDTLS_MPI_CHK( mbedtls_mpi_mul_mod( grp, &S, &T, &U ) );
MBEDTLS_MPI_CHK( mbedtls_mpi_mul_int( &M, &S, 3 ) ); MOD_ADD( M );
}
else
{
/* M = 3.X^2 */
MBEDTLS_MPI_CHK( mbedtls_mpi_mul_mod( grp, &S, &P->X, &P->X ) );
MBEDTLS_MPI_CHK( mbedtls_mpi_mul_int( &M, &S, 3 ) ); MOD_ADD( M );
/* Optimize away for "koblitz" curves with A = 0 */
if( mbedtls_mpi_cmp_int( &grp->A, 0 ) != 0 )
{
/* M += A.Z^4 */
MBEDTLS_MPI_CHK( mbedtls_mpi_mul_mod( grp, &S, &P->Z, &P->Z ) );
MBEDTLS_MPI_CHK( mbedtls_mpi_mul_mod( grp, &T, &S, &S ) );
MBEDTLS_MPI_CHK( mbedtls_mpi_mul_mod( grp, &S, &T, &grp->A ) );
MBEDTLS_MPI_CHK( mbedtls_mpi_add_mod( grp, &M, &M, &S ) );
}
}
/* S = 4.X.Y^2 */
MBEDTLS_MPI_CHK( mbedtls_mpi_mul_mod( grp, &T, &P->Y, &P->Y ) );
MBEDTLS_MPI_CHK( mbedtls_mpi_shift_l_mod( grp, &T, 1 ) );
MBEDTLS_MPI_CHK( mbedtls_mpi_mul_mod( grp, &S, &P->X, &T ) );
MBEDTLS_MPI_CHK( mbedtls_mpi_shift_l_mod( grp, &S, 1 ) );
/* U = 8.Y^4 */
MBEDTLS_MPI_CHK( mbedtls_mpi_mul_mod( grp, &U, &T, &T ) );
MBEDTLS_MPI_CHK( mbedtls_mpi_shift_l_mod( grp, &U, 1 ) );
/* T = M^2 - 2.S */
MBEDTLS_MPI_CHK( mbedtls_mpi_mul_mod( grp, &T, &M, &M ) );
MBEDTLS_MPI_CHK( mbedtls_mpi_sub_mod( grp, &T, &T, &S ) );
MBEDTLS_MPI_CHK( mbedtls_mpi_sub_mod( grp, &T, &T, &S ) );
/* S = M(S - T) - U */
MBEDTLS_MPI_CHK( mbedtls_mpi_sub_mod( grp, &S, &S, &T ) );
MBEDTLS_MPI_CHK( mbedtls_mpi_mul_mod( grp, &S, &S, &M ) );
MBEDTLS_MPI_CHK( mbedtls_mpi_sub_mod( grp, &S, &S, &U ) );
/* U = 2.Y.Z */
MBEDTLS_MPI_CHK( mbedtls_mpi_mul_mod( grp, &U, &P->Y, &P->Z ) );
MBEDTLS_MPI_CHK( mbedtls_mpi_shift_l_mod( grp, &U, 1 ) );
MBEDTLS_MPI_CHK( mbedtls_mpi_copy( &R->X, &T ) );
MBEDTLS_MPI_CHK( mbedtls_mpi_copy( &R->Y, &S ) );
MBEDTLS_MPI_CHK( mbedtls_mpi_copy( &R->Z, &U ) );
cleanup:
mbedtls_mpi_free( &M ); mbedtls_mpi_free( &S ); mbedtls_mpi_free( &T ); mbedtls_mpi_free( &U );
return( ret );
#endif /* !defined(MBEDTLS_ECP_NO_FALLBACK) || !defined(MBEDTLS_ECP_DOUBLE_JAC_ALT) */
}
/*
* Addition: R = P + Q, mixed affine-Jacobian coordinates (GECC 3.22)
*
* The coordinates of Q must be normalized (= affine),
* but those of P don't need to. R is not normalized.
*
* Special cases: (1) P or Q is zero, (2) R is zero, (3) P == Q.
* None of these cases can happen as intermediate step in ecp_mul_comb():
* - at each step, P, Q and R are multiples of the base point, the factor
* being less than its order, so none of them is zero;
* - Q is an odd multiple of the base point, P an even multiple,
* due to the choice of precomputed points in the modified comb method.
* So branches for these cases do not leak secret information.
*
* We accept Q->Z being unset (saving memory in tables) as meaning 1.
*
* Cost: 1A := 8M + 3S
*/
static int ecp_add_mixed( const mbedtls_ecp_group *grp, mbedtls_ecp_point *R,
const mbedtls_ecp_point *P, const mbedtls_ecp_point *Q )
{
#if defined(MBEDTLS_SELF_TEST)
add_count++;
#endif
#if defined(MBEDTLS_ECP_ADD_MIXED_ALT)
if( mbedtls_internal_ecp_grp_capable( grp ) )
return( mbedtls_internal_ecp_add_mixed( grp, R, P, Q ) );
#endif /* MBEDTLS_ECP_ADD_MIXED_ALT */
#if defined(MBEDTLS_ECP_NO_FALLBACK) && defined(MBEDTLS_ECP_ADD_MIXED_ALT)
return( MBEDTLS_ERR_ECP_FEATURE_UNAVAILABLE );
#else
int ret = MBEDTLS_ERR_ERROR_CORRUPTION_DETECTED;
mbedtls_mpi T1, T2, T3, T4, X, Y, Z;
/*
* Trivial cases: P == 0 or Q == 0 (case 1)
*/
if( mbedtls_mpi_cmp_int( &P->Z, 0 ) == 0 )
return( mbedtls_ecp_copy( R, Q ) );
if( Q->Z.p != NULL && mbedtls_mpi_cmp_int( &Q->Z, 0 ) == 0 )
return( mbedtls_ecp_copy( R, P ) );
/*
* Make sure Q coordinates are normalized
*/
if( Q->Z.p != NULL && mbedtls_mpi_cmp_int( &Q->Z, 1 ) != 0 )
return( MBEDTLS_ERR_ECP_BAD_INPUT_DATA );
mbedtls_mpi_init( &T1 ); mbedtls_mpi_init( &T2 ); mbedtls_mpi_init( &T3 ); mbedtls_mpi_init( &T4 );
mbedtls_mpi_init( &X ); mbedtls_mpi_init( &Y ); mbedtls_mpi_init( &Z );
MBEDTLS_MPI_CHK( mbedtls_mpi_mul_mod( grp, &T1, &P->Z, &P->Z ) );
MBEDTLS_MPI_CHK( mbedtls_mpi_mul_mod( grp, &T2, &T1, &P->Z ) );
MBEDTLS_MPI_CHK( mbedtls_mpi_mul_mod( grp, &T1, &T1, &Q->X ) );
MBEDTLS_MPI_CHK( mbedtls_mpi_mul_mod( grp, &T2, &T2, &Q->Y ) );
MBEDTLS_MPI_CHK( mbedtls_mpi_sub_mod( grp, &T1, &T1, &P->X ) );
MBEDTLS_MPI_CHK( mbedtls_mpi_sub_mod( grp, &T2, &T2, &P->Y ) );
/* Special cases (2) and (3) */
if( mbedtls_mpi_cmp_int( &T1, 0 ) == 0 )
{
if( mbedtls_mpi_cmp_int( &T2, 0 ) == 0 )
{
ret = ecp_double_jac( grp, R, P );
goto cleanup;
}
else
{
ret = mbedtls_ecp_set_zero( R );
goto cleanup;
}
}
MBEDTLS_MPI_CHK( mbedtls_mpi_mul_mod( grp, &Z, &P->Z, &T1 ) );
MBEDTLS_MPI_CHK( mbedtls_mpi_mul_mod( grp, &T3, &T1, &T1 ) );
MBEDTLS_MPI_CHK( mbedtls_mpi_mul_mod( grp, &T4, &T3, &T1 ) );
MBEDTLS_MPI_CHK( mbedtls_mpi_mul_mod( grp, &T3, &T3, &P->X ) );
MBEDTLS_MPI_CHK( mbedtls_mpi_copy( &T1, &T3 ) );
MBEDTLS_MPI_CHK( mbedtls_mpi_shift_l_mod( grp, &T1, 1 ) );
MBEDTLS_MPI_CHK( mbedtls_mpi_mul_mod( grp, &X, &T2, &T2 ) );
MBEDTLS_MPI_CHK( mbedtls_mpi_sub_mod( grp, &X, &X, &T1 ) );
MBEDTLS_MPI_CHK( mbedtls_mpi_sub_mod( grp, &X, &X, &T4 ) );
MBEDTLS_MPI_CHK( mbedtls_mpi_sub_mod( grp, &T3, &T3, &X ) );
MBEDTLS_MPI_CHK( mbedtls_mpi_mul_mod( grp, &T3, &T3, &T2 ) );
MBEDTLS_MPI_CHK( mbedtls_mpi_mul_mod( grp, &T4, &T4, &P->Y ) );
MBEDTLS_MPI_CHK( mbedtls_mpi_sub_mod( grp, &Y, &T3, &T4 ) );
MBEDTLS_MPI_CHK( mbedtls_mpi_copy( &R->X, &X ) );
MBEDTLS_MPI_CHK( mbedtls_mpi_copy( &R->Y, &Y ) );
MBEDTLS_MPI_CHK( mbedtls_mpi_copy( &R->Z, &Z ) );
cleanup:
mbedtls_mpi_free( &T1 ); mbedtls_mpi_free( &T2 ); mbedtls_mpi_free( &T3 ); mbedtls_mpi_free( &T4 );
mbedtls_mpi_free( &X ); mbedtls_mpi_free( &Y ); mbedtls_mpi_free( &Z );
return( ret );
#endif /* !defined(MBEDTLS_ECP_NO_FALLBACK) || !defined(MBEDTLS_ECP_ADD_MIXED_ALT) */
}
/*
* Randomize jacobian coordinates:
* (X, Y, Z) -> (l^2 X, l^3 Y, l Z) for random l
* This is sort of the reverse operation of ecp_normalize_jac().
*
* This countermeasure was first suggested in [2].
*/
static int ecp_randomize_jac( const mbedtls_ecp_group *grp, mbedtls_ecp_point *pt,
int (*f_rng)(void *, unsigned char *, size_t), void *p_rng )
{
#if defined(MBEDTLS_ECP_RANDOMIZE_JAC_ALT)
if( mbedtls_internal_ecp_grp_capable( grp ) )
return( mbedtls_internal_ecp_randomize_jac( grp, pt, f_rng, p_rng ) );
#endif /* MBEDTLS_ECP_RANDOMIZE_JAC_ALT */
#if defined(MBEDTLS_ECP_NO_FALLBACK) && defined(MBEDTLS_ECP_RANDOMIZE_JAC_ALT)
return( MBEDTLS_ERR_ECP_FEATURE_UNAVAILABLE );
#else
int ret = MBEDTLS_ERR_ERROR_CORRUPTION_DETECTED;
mbedtls_mpi l, ll;
mbedtls_mpi_init( &l ); mbedtls_mpi_init( &ll );
/* Generate l such that 1 < l < p */
MBEDTLS_MPI_CHK( mbedtls_mpi_random( &l, 2, &grp->P, f_rng, p_rng ) );
/* Z = l * Z */
MBEDTLS_MPI_CHK( mbedtls_mpi_mul_mod( grp, &pt->Z, &pt->Z, &l ) );
/* X = l^2 * X */
MBEDTLS_MPI_CHK( mbedtls_mpi_mul_mod( grp, &ll, &l, &l ) );
MBEDTLS_MPI_CHK( mbedtls_mpi_mul_mod( grp, &pt->X, &pt->X, &ll ) );
/* Y = l^3 * Y */
MBEDTLS_MPI_CHK( mbedtls_mpi_mul_mod( grp, &ll, &ll, &l ) );
MBEDTLS_MPI_CHK( mbedtls_mpi_mul_mod( grp, &pt->Y, &pt->Y, &ll ) );
cleanup:
mbedtls_mpi_free( &l ); mbedtls_mpi_free( &ll );
if( ret == MBEDTLS_ERR_MPI_NOT_ACCEPTABLE )
ret = MBEDTLS_ERR_ECP_RANDOM_FAILED;
return( ret );
#endif /* !defined(MBEDTLS_ECP_NO_FALLBACK) || !defined(MBEDTLS_ECP_RANDOMIZE_JAC_ALT) */
}
/*
* Check and define parameters used by the comb method (see below for details)
*/
#if MBEDTLS_ECP_WINDOW_SIZE < 2 || MBEDTLS_ECP_WINDOW_SIZE > 7
#error "MBEDTLS_ECP_WINDOW_SIZE out of bounds"
#endif
/* d = ceil( n / w ) */
#define COMB_MAX_D ( MBEDTLS_ECP_MAX_BITS + 1 ) / 2
/* number of precomputed points */
#define COMB_MAX_PRE ( 1 << ( MBEDTLS_ECP_WINDOW_SIZE - 1 ) )
/*
* Compute the representation of m that will be used with our comb method.
*
* The basic comb method is described in GECC 3.44 for example. We use a
* modified version that provides resistance to SPA by avoiding zero
* digits in the representation as in [3]. We modify the method further by
* requiring that all K_i be odd, which has the small cost that our
* representation uses one more K_i, due to carries, but saves on the size of
* the precomputed table.
*
* Summary of the comb method and its modifications:
*
* - The goal is to compute m*P for some w*d-bit integer m.
*
* - The basic comb method splits m into the w-bit integers
* x[0] .. x[d-1] where x[i] consists of the bits in m whose
* index has residue i modulo d, and computes m * P as
* S[x[0]] + 2 * S[x[1]] + .. + 2^(d-1) S[x[d-1]], where
* S[i_{w-1} .. i_0] := i_{w-1} 2^{(w-1)d} P + ... + i_1 2^d P + i_0 P.
*
* - If it happens that, say, x[i+1]=0 (=> S[x[i+1]]=0), one can replace the sum by
* .. + 2^{i-1} S[x[i-1]] - 2^i S[x[i]] + 2^{i+1} S[x[i]] + 2^{i+2} S[x[i+2]] ..,
* thereby successively converting it into a form where all summands
* are nonzero, at the cost of negative summands. This is the basic idea of [3].
*
* - More generally, even if x[i+1] != 0, we can first transform the sum as
* .. - 2^i S[x[i]] + 2^{i+1} ( S[x[i]] + S[x[i+1]] ) + 2^{i+2} S[x[i+2]] ..,
* and then replace S[x[i]] + S[x[i+1]] = S[x[i] ^ x[i+1]] + 2 S[x[i] & x[i+1]].
* Performing and iterating this procedure for those x[i] that are even
* (keeping track of carry), we can transform the original sum into one of the form
* S[x'[0]] +- 2 S[x'[1]] +- .. +- 2^{d-1} S[x'[d-1]] + 2^d S[x'[d]]
* with all x'[i] odd. It is therefore only necessary to know S at odd indices,
* which is why we are only computing half of it in the first place in
* ecp_precompute_comb and accessing it with index abs(i) / 2 in ecp_select_comb.
*
* - For the sake of compactness, only the seven low-order bits of x[i]
* are used to represent its absolute value (K_i in the paper), and the msb
* of x[i] encodes the sign (s_i in the paper): it is set if and only if
* if s_i == -1;
*
* Calling conventions:
* - x is an array of size d + 1
* - w is the size, ie number of teeth, of the comb, and must be between
* 2 and 7 (in practice, between 2 and MBEDTLS_ECP_WINDOW_SIZE)
* - m is the MPI, expected to be odd and such that bitlength(m) <= w * d
* (the result will be incorrect if these assumptions are not satisfied)
*/
static void ecp_comb_recode_core( unsigned char x[], size_t d,
unsigned char w, const mbedtls_mpi *m )
{
size_t i, j;
unsigned char c, cc, adjust;
memset( x, 0, d+1 );
/* First get the classical comb values (except for x_d = 0) */
for( i = 0; i < d; i++ )
for( j = 0; j < w; j++ )
x[i] |= mbedtls_mpi_get_bit( m, i + d * j ) << j;
/* Now make sure x_1 .. x_d are odd */
c = 0;
for( i = 1; i <= d; i++ )
{
/* Add carry and update it */
cc = x[i] & c;
x[i] = x[i] ^ c;
c = cc;
/* Adjust if needed, avoiding branches */
adjust = 1 - ( x[i] & 0x01 );
c |= x[i] & ( x[i-1] * adjust );
x[i] = x[i] ^ ( x[i-1] * adjust );
x[i-1] |= adjust << 7;
}
}
/*
* Precompute points for the adapted comb method
*
* Assumption: T must be able to hold 2^{w - 1} elements.
*
* Operation: If i = i_{w-1} ... i_1 is the binary representation of i,
* sets T[i] = i_{w-1} 2^{(w-1)d} P + ... + i_1 2^d P + P.
*
* Cost: d(w-1) D + (2^{w-1} - 1) A + 1 N(w-1) + 1 N(2^{w-1} - 1)
*
* Note: Even comb values (those where P would be omitted from the
* sum defining T[i] above) are not needed in our adaption
* the comb method. See ecp_comb_recode_core().
*
* This function currently works in four steps:
* (1) [dbl] Computation of intermediate T[i] for 2-power values of i
* (2) [norm_dbl] Normalization of coordinates of these T[i]
* (3) [add] Computation of all T[i]
* (4) [norm_add] Normalization of all T[i]
*
* Step 1 can be interrupted but not the others; together with the final
* coordinate normalization they are the largest steps done at once, depending
* on the window size. Here are operation counts for P-256:
*
* step (2) (3) (4)
* w = 5 142 165 208
* w = 4 136 77 160
* w = 3 130 33 136
* w = 2 124 11 124
*
* So if ECC operations are blocking for too long even with a low max_ops
* value, it's useful to set MBEDTLS_ECP_WINDOW_SIZE to a lower value in order
* to minimize maximum blocking time.
*/
static int ecp_precompute_comb( const mbedtls_ecp_group *grp,
mbedtls_ecp_point T[], const mbedtls_ecp_point *P,
unsigned char w, size_t d,
mbedtls_ecp_restart_ctx *rs_ctx )
{
int ret = MBEDTLS_ERR_ERROR_CORRUPTION_DETECTED;
unsigned char i;
size_t j = 0;
const unsigned char T_size = 1U << ( w - 1 );
mbedtls_ecp_point *cur, *TT[COMB_MAX_PRE - 1];
#if defined(MBEDTLS_ECP_RESTARTABLE)
if( rs_ctx != NULL && rs_ctx->rsm != NULL )
{
if( rs_ctx->rsm->state == ecp_rsm_pre_dbl )
goto dbl;
if( rs_ctx->rsm->state == ecp_rsm_pre_norm_dbl )
goto norm_dbl;
if( rs_ctx->rsm->state == ecp_rsm_pre_add )
goto add;
if( rs_ctx->rsm->state == ecp_rsm_pre_norm_add )
goto norm_add;
}
#else
(void) rs_ctx;
#endif
#if defined(MBEDTLS_ECP_RESTARTABLE)
if( rs_ctx != NULL && rs_ctx->rsm != NULL )
{
rs_ctx->rsm->state = ecp_rsm_pre_dbl;
/* initial state for the loop */
rs_ctx->rsm->i = 0;
}
dbl:
#endif
/*
* Set T[0] = P and
* T[2^{l-1}] = 2^{dl} P for l = 1 .. w-1 (this is not the final value)
*/
MBEDTLS_MPI_CHK( mbedtls_ecp_copy( &T[0], P ) );
#if defined(MBEDTLS_ECP_RESTARTABLE)
if( rs_ctx != NULL && rs_ctx->rsm != NULL && rs_ctx->rsm->i != 0 )
j = rs_ctx->rsm->i;
else
#endif
j = 0;
for( ; j < d * ( w - 1 ); j++ )
{
MBEDTLS_ECP_BUDGET( MBEDTLS_ECP_OPS_DBL );
i = 1U << ( j / d );
cur = T + i;
if( j % d == 0 )
MBEDTLS_MPI_CHK( mbedtls_ecp_copy( cur, T + ( i >> 1 ) ) );
MBEDTLS_MPI_CHK( ecp_double_jac( grp, cur, cur ) );
}
#if defined(MBEDTLS_ECP_RESTARTABLE)
if( rs_ctx != NULL && rs_ctx->rsm != NULL )
rs_ctx->rsm->state = ecp_rsm_pre_norm_dbl;
norm_dbl:
#endif
/*
* Normalize current elements in T. As T has holes,
* use an auxiliary array of pointers to elements in T.
*/
j = 0;
for( i = 1; i < T_size; i <<= 1 )
TT[j++] = T + i;
MBEDTLS_ECP_BUDGET( MBEDTLS_ECP_OPS_INV + 6 * j - 2 );
MBEDTLS_MPI_CHK( ecp_normalize_jac_many( grp, TT, j ) );
#if defined(MBEDTLS_ECP_RESTARTABLE)
if( rs_ctx != NULL && rs_ctx->rsm != NULL )
rs_ctx->rsm->state = ecp_rsm_pre_add;
add:
#endif
/*
* Compute the remaining ones using the minimal number of additions
* Be careful to update T[2^l] only after using it!
*/
MBEDTLS_ECP_BUDGET( ( T_size - 1 ) * MBEDTLS_ECP_OPS_ADD );
for( i = 1; i < T_size; i <<= 1 )
{
j = i;
while( j-- )
MBEDTLS_MPI_CHK( ecp_add_mixed( grp, &T[i + j], &T[j], &T[i] ) );
}
#if defined(MBEDTLS_ECP_RESTARTABLE)
if( rs_ctx != NULL && rs_ctx->rsm != NULL )
rs_ctx->rsm->state = ecp_rsm_pre_norm_add;
norm_add:
#endif
/*
* Normalize final elements in T. Even though there are no holes now, we
* still need the auxiliary array for homogeneity with the previous
* call. Also, skip T[0] which is already normalised, being a copy of P.
*/
for( j = 0; j + 1 < T_size; j++ )
TT[j] = T + j + 1;
MBEDTLS_ECP_BUDGET( MBEDTLS_ECP_OPS_INV + 6 * j - 2 );
MBEDTLS_MPI_CHK( ecp_normalize_jac_many( grp, TT, j ) );
cleanup:
#if defined(MBEDTLS_ECP_RESTARTABLE)
if( rs_ctx != NULL && rs_ctx->rsm != NULL &&
ret == MBEDTLS_ERR_ECP_IN_PROGRESS )
{
if( rs_ctx->rsm->state == ecp_rsm_pre_dbl )
rs_ctx->rsm->i = j;
}
#endif
return( ret );
}
/*
* Select precomputed point: R = sign(i) * T[ abs(i) / 2 ]
*
* See ecp_comb_recode_core() for background
*/
static int ecp_select_comb( const mbedtls_ecp_group *grp, mbedtls_ecp_point *R,
const mbedtls_ecp_point T[], unsigned char T_size,
unsigned char i )
{
int ret = MBEDTLS_ERR_ERROR_CORRUPTION_DETECTED;
unsigned char ii, j;
/* Ignore the "sign" bit and scale down */
ii = ( i & 0x7Fu ) >> 1;
/* Read the whole table to thwart cache-based timing attacks */
for( j = 0; j < T_size; j++ )
{
MBEDTLS_MPI_CHK( mbedtls_mpi_safe_cond_assign( &R->X, &T[j].X, j == ii ) );
MBEDTLS_MPI_CHK( mbedtls_mpi_safe_cond_assign( &R->Y, &T[j].Y, j == ii ) );
}
/* Safely invert result if i is "negative" */
MBEDTLS_MPI_CHK( ecp_safe_invert_jac( grp, R, i >> 7 ) );
cleanup:
return( ret );
}
/*
* Core multiplication algorithm for the (modified) comb method.
* This part is actually common with the basic comb method (GECC 3.44)
*
* Cost: d A + d D + 1 R
*/
static int ecp_mul_comb_core( const mbedtls_ecp_group *grp, mbedtls_ecp_point *R,
const mbedtls_ecp_point T[], unsigned char T_size,
const unsigned char x[], size_t d,
int (*f_rng)(void *, unsigned char *, size_t),
void *p_rng,
mbedtls_ecp_restart_ctx *rs_ctx )
{
int ret = MBEDTLS_ERR_ERROR_CORRUPTION_DETECTED;
mbedtls_ecp_point Txi;
size_t i;
mbedtls_ecp_point_init( &Txi );
#if !defined(MBEDTLS_ECP_RESTARTABLE)
(void) rs_ctx;
#endif
#if defined(MBEDTLS_ECP_RESTARTABLE)
if( rs_ctx != NULL && rs_ctx->rsm != NULL &&
rs_ctx->rsm->state != ecp_rsm_comb_core )
{
rs_ctx->rsm->i = 0;
rs_ctx->rsm->state = ecp_rsm_comb_core;
}
/* new 'if' instead of nested for the sake of the 'else' branch */
if( rs_ctx != NULL && rs_ctx->rsm != NULL && rs_ctx->rsm->i != 0 )
{
/* restore current index (R already pointing to rs_ctx->rsm->R) */
i = rs_ctx->rsm->i;
}
else
#endif
{
/* Start with a non-zero point and randomize its coordinates */
i = d;
MBEDTLS_MPI_CHK( ecp_select_comb( grp, R, T, T_size, x[i] ) );
MBEDTLS_MPI_CHK( mbedtls_mpi_lset( &R->Z, 1 ) );
#if defined(MBEDTLS_ECP_NO_INTERNAL_RNG)
if( f_rng != 0 )
#endif
MBEDTLS_MPI_CHK( ecp_randomize_jac( grp, R, f_rng, p_rng ) );
}
while( i != 0 )
{
MBEDTLS_ECP_BUDGET( MBEDTLS_ECP_OPS_DBL + MBEDTLS_ECP_OPS_ADD );
--i;
MBEDTLS_MPI_CHK( ecp_double_jac( grp, R, R ) );
MBEDTLS_MPI_CHK( ecp_select_comb( grp, &Txi, T, T_size, x[i] ) );
MBEDTLS_MPI_CHK( ecp_add_mixed( grp, R, R, &Txi ) );
}
cleanup:
mbedtls_ecp_point_free( &Txi );
#if defined(MBEDTLS_ECP_RESTARTABLE)
if( rs_ctx != NULL && rs_ctx->rsm != NULL &&
ret == MBEDTLS_ERR_ECP_IN_PROGRESS )
{
rs_ctx->rsm->i = i;
/* no need to save R, already pointing to rs_ctx->rsm->R */
}
#endif
return( ret );
}
/*
* Recode the scalar to get constant-time comb multiplication
*
* As the actual scalar recoding needs an odd scalar as a starting point,
* this wrapper ensures that by replacing m by N - m if necessary, and
* informs the caller that the result of multiplication will be negated.
*
* This works because we only support large prime order for Short Weierstrass
* curves, so N is always odd hence either m or N - m is.
*
* See ecp_comb_recode_core() for background.
*/
static int ecp_comb_recode_scalar( const mbedtls_ecp_group *grp,
const mbedtls_mpi *m,
unsigned char k[COMB_MAX_D + 1],
size_t d,
unsigned char w,
unsigned char *parity_trick )
{
int ret = MBEDTLS_ERR_ERROR_CORRUPTION_DETECTED;
mbedtls_mpi M, mm;
mbedtls_mpi_init( &M );
mbedtls_mpi_init( &mm );
/* N is always odd (see above), just make extra sure */
if( mbedtls_mpi_get_bit( &grp->N, 0 ) != 1 )
return( MBEDTLS_ERR_ECP_BAD_INPUT_DATA );
/* do we need the parity trick? */
*parity_trick = ( mbedtls_mpi_get_bit( m, 0 ) == 0 );
/* execute parity fix in constant time */
MBEDTLS_MPI_CHK( mbedtls_mpi_copy( &M, m ) );
MBEDTLS_MPI_CHK( mbedtls_mpi_sub_mpi( &mm, &grp->N, m ) );
MBEDTLS_MPI_CHK( mbedtls_mpi_safe_cond_assign( &M, &mm, *parity_trick ) );
/* actual scalar recoding */
ecp_comb_recode_core( k, d, w, &M );
cleanup:
mbedtls_mpi_free( &mm );
mbedtls_mpi_free( &M );
return( ret );
}
/*
* Perform comb multiplication (for short Weierstrass curves)
* once the auxiliary table has been pre-computed.
*
* Scalar recoding may use a parity trick that makes us compute -m * P,
* if that is the case we'll need to recover m * P at the end.
*/
static int ecp_mul_comb_after_precomp( const mbedtls_ecp_group *grp,
mbedtls_ecp_point *R,
const mbedtls_mpi *m,
const mbedtls_ecp_point *T,
unsigned char T_size,
unsigned char w,
size_t d,
int (*f_rng)(void *, unsigned char *, size_t),
void *p_rng,
mbedtls_ecp_restart_ctx *rs_ctx )
{
int ret = MBEDTLS_ERR_ERROR_CORRUPTION_DETECTED;
unsigned char parity_trick;
unsigned char k[COMB_MAX_D + 1];
mbedtls_ecp_point *RR = R;
#if defined(MBEDTLS_ECP_RESTARTABLE)
if( rs_ctx != NULL && rs_ctx->rsm != NULL )
{
RR = &rs_ctx->rsm->R;
if( rs_ctx->rsm->state == ecp_rsm_final_norm )
goto final_norm;
}
#endif
MBEDTLS_MPI_CHK( ecp_comb_recode_scalar( grp, m, k, d, w,
&parity_trick ) );
MBEDTLS_MPI_CHK( ecp_mul_comb_core( grp, RR, T, T_size, k, d,
f_rng, p_rng, rs_ctx ) );
MBEDTLS_MPI_CHK( ecp_safe_invert_jac( grp, RR, parity_trick ) );
#if defined(MBEDTLS_ECP_RESTARTABLE)
if( rs_ctx != NULL && rs_ctx->rsm != NULL )
rs_ctx->rsm->state = ecp_rsm_final_norm;
final_norm:
MBEDTLS_ECP_BUDGET( MBEDTLS_ECP_OPS_INV );
#endif
/*
* Knowledge of the jacobian coordinates may leak the last few bits of the
* scalar [1], and since our MPI implementation isn't constant-flow,
* inversion (used for coordinate normalization) may leak the full value
* of its input via side-channels [2].
*
* [1] https://eprint.iacr.org/2003/191
* [2] https://eprint.iacr.org/2020/055
*
* Avoid the leak by randomizing coordinates before we normalize them.
*/
#if defined(MBEDTLS_ECP_NO_INTERNAL_RNG)
if( f_rng != 0 )
#endif
MBEDTLS_MPI_CHK( ecp_randomize_jac( grp, RR, f_rng, p_rng ) );
MBEDTLS_MPI_CHK( ecp_normalize_jac( grp, RR ) );
#if defined(MBEDTLS_ECP_RESTARTABLE)
if( rs_ctx != NULL && rs_ctx->rsm != NULL )
MBEDTLS_MPI_CHK( mbedtls_ecp_copy( R, RR ) );
#endif
cleanup:
return( ret );
}
/*
* Pick window size based on curve size and whether we optimize for base point
*/
static unsigned char ecp_pick_window_size( const mbedtls_ecp_group *grp,
unsigned char p_eq_g )
{
unsigned char w;
/*
* Minimize the number of multiplications, that is minimize
* 10 * d * w + 18 * 2^(w-1) + 11 * d + 7 * w, with d = ceil( nbits / w )
* (see costs of the various parts, with 1S = 1M)
*/
w = grp->nbits >= 384 ? 5 : 4;
/*
* If P == G, pre-compute a bit more, since this may be re-used later.
* Just adding one avoids upping the cost of the first mul too much,
* and the memory cost too.
*/
if( p_eq_g )
w++;
/*
* Make sure w is within bounds.
* (The last test is useful only for very small curves in the test suite.)
*/
#if( MBEDTLS_ECP_WINDOW_SIZE < 6 )
if( w > MBEDTLS_ECP_WINDOW_SIZE )
w = MBEDTLS_ECP_WINDOW_SIZE;
#endif
if( w >= grp->nbits )
w = 2;
return( w );
}
/*
* Multiplication using the comb method - for curves in short Weierstrass form
*
* This function is mainly responsible for administrative work:
* - managing the restart context if enabled
* - managing the table of precomputed points (passed between the below two
* functions): allocation, computation, ownership tranfer, freeing.
*
* It delegates the actual arithmetic work to:
* ecp_precompute_comb() and ecp_mul_comb_with_precomp()
*
* See comments on ecp_comb_recode_core() regarding the computation strategy.
*/
static int ecp_mul_comb( mbedtls_ecp_group *grp, mbedtls_ecp_point *R,
const mbedtls_mpi *m, const mbedtls_ecp_point *P,
int (*f_rng)(void *, unsigned char *, size_t),
void *p_rng,
mbedtls_ecp_restart_ctx *rs_ctx )
{
int ret = MBEDTLS_ERR_ERROR_CORRUPTION_DETECTED;
unsigned char w, p_eq_g, i;
size_t d;
unsigned char T_size = 0, T_ok = 0;
mbedtls_ecp_point *T = NULL;
#if !defined(MBEDTLS_ECP_NO_INTERNAL_RNG)
ecp_drbg_context drbg_ctx;
ecp_drbg_init( &drbg_ctx );
#endif
ECP_RS_ENTER( rsm );
#if !defined(MBEDTLS_ECP_NO_INTERNAL_RNG)
if( f_rng == NULL )
{
/* Adjust pointers */
f_rng = &ecp_drbg_random;
#if defined(MBEDTLS_ECP_RESTARTABLE)
if( rs_ctx != NULL && rs_ctx->rsm != NULL )
p_rng = &rs_ctx->rsm->drbg_ctx;
else
#endif
p_rng = &drbg_ctx;
/* Initialize internal DRBG if necessary */
#if defined(MBEDTLS_ECP_RESTARTABLE)
if( rs_ctx == NULL || rs_ctx->rsm == NULL ||
rs_ctx->rsm->drbg_seeded == 0 )
#endif
{
const size_t m_len = ( grp->nbits + 7 ) / 8;
MBEDTLS_MPI_CHK( ecp_drbg_seed( p_rng, m, m_len ) );
}
#if defined(MBEDTLS_ECP_RESTARTABLE)
if( rs_ctx != NULL && rs_ctx->rsm != NULL )
rs_ctx->rsm->drbg_seeded = 1;
#endif
}
#endif /* !MBEDTLS_ECP_NO_INTERNAL_RNG */
/* Is P the base point ? */
#if MBEDTLS_ECP_FIXED_POINT_OPTIM == 1
p_eq_g = ( mbedtls_mpi_cmp_mpi( &P->Y, &grp->G.Y ) == 0 &&
mbedtls_mpi_cmp_mpi( &P->X, &grp->G.X ) == 0 );
#else
p_eq_g = 0;
#endif
/* Pick window size and deduce related sizes */
w = ecp_pick_window_size( grp, p_eq_g );
T_size = 1U << ( w - 1 );
d = ( grp->nbits + w - 1 ) / w;
/* Pre-computed table: do we have it already for the base point? */
if( p_eq_g && grp->T != NULL )
{
/* second pointer to the same table, will be deleted on exit */
T = grp->T;
T_ok = 1;
}
else
#if defined(MBEDTLS_ECP_RESTARTABLE)
/* Pre-computed table: do we have one in progress? complete? */
if( rs_ctx != NULL && rs_ctx->rsm != NULL && rs_ctx->rsm->T != NULL )
{
/* transfer ownership of T from rsm to local function */
T = rs_ctx->rsm->T;
rs_ctx->rsm->T = NULL;
rs_ctx->rsm->T_size = 0;
/* This effectively jumps to the call to mul_comb_after_precomp() */
T_ok = rs_ctx->rsm->state >= ecp_rsm_comb_core;
}
else
#endif
/* Allocate table if we didn't have any */
{
T = mbedtls_calloc( T_size, sizeof( mbedtls_ecp_point ) );
if( T == NULL )
{
ret = MBEDTLS_ERR_ECP_ALLOC_FAILED;
goto cleanup;
}
for( i = 0; i < T_size; i++ )
mbedtls_ecp_point_init( &T[i] );
T_ok = 0;
}
/* Compute table (or finish computing it) if not done already */
if( !T_ok )
{
MBEDTLS_MPI_CHK( ecp_precompute_comb( grp, T, P, w, d, rs_ctx ) );
if( p_eq_g )
{
/* almost transfer ownership of T to the group, but keep a copy of
* the pointer to use for calling the next function more easily */
grp->T = T;
grp->T_size = T_size;
}
}
/* Actual comb multiplication using precomputed points */
MBEDTLS_MPI_CHK( ecp_mul_comb_after_precomp( grp, R, m,
T, T_size, w, d,
f_rng, p_rng, rs_ctx ) );
cleanup:
#if !defined(MBEDTLS_ECP_NO_INTERNAL_RNG)
ecp_drbg_free( &drbg_ctx );
#endif
/* does T belong to the group? */
if( T == grp->T )
T = NULL;
/* does T belong to the restart context? */
#if defined(MBEDTLS_ECP_RESTARTABLE)
if( rs_ctx != NULL && rs_ctx->rsm != NULL && ret == MBEDTLS_ERR_ECP_IN_PROGRESS && T != NULL )
{
/* transfer ownership of T from local function to rsm */
rs_ctx->rsm->T_size = T_size;
rs_ctx->rsm->T = T;
T = NULL;
}
#endif
/* did T belong to us? then let's destroy it! */
if( T != NULL )
{
for( i = 0; i < T_size; i++ )
mbedtls_ecp_point_free( &T[i] );
mbedtls_free( T );
}
/* don't free R while in progress in case R == P */
#if defined(MBEDTLS_ECP_RESTARTABLE)
if( ret != MBEDTLS_ERR_ECP_IN_PROGRESS )
#endif
/* prevent caller from using invalid value */
if( ret != 0 )
mbedtls_ecp_point_free( R );
ECP_RS_LEAVE( rsm );
return( ret );
}
#endif /* MBEDTLS_ECP_SHORT_WEIERSTRASS_ENABLED */
#if defined(MBEDTLS_ECP_MONTGOMERY_ENABLED)
/*
* For Montgomery curves, we do all the internal arithmetic in projective
* coordinates. Import/export of points uses only the x coordinates, which is
* internaly represented as X / Z.
*
* For scalar multiplication, we'll use a Montgomery ladder.
*/
/*
* Normalize Montgomery x/z coordinates: X = X/Z, Z = 1
* Cost: 1M + 1I
*/
static int ecp_normalize_mxz( const mbedtls_ecp_group *grp, mbedtls_ecp_point *P )
{
#if defined(MBEDTLS_ECP_NORMALIZE_MXZ_ALT)
if( mbedtls_internal_ecp_grp_capable( grp ) )
return( mbedtls_internal_ecp_normalize_mxz( grp, P ) );
#endif /* MBEDTLS_ECP_NORMALIZE_MXZ_ALT */
#if defined(MBEDTLS_ECP_NO_FALLBACK) && defined(MBEDTLS_ECP_NORMALIZE_MXZ_ALT)
return( MBEDTLS_ERR_ECP_FEATURE_UNAVAILABLE );
#else
int ret = MBEDTLS_ERR_ERROR_CORRUPTION_DETECTED;
MBEDTLS_MPI_CHK( mbedtls_mpi_inv_mod( &P->Z, &P->Z, &grp->P ) );
MBEDTLS_MPI_CHK( mbedtls_mpi_mul_mod( grp, &P->X, &P->X, &P->Z ) );
MBEDTLS_MPI_CHK( mbedtls_mpi_lset( &P->Z, 1 ) );
cleanup:
return( ret );
#endif /* !defined(MBEDTLS_ECP_NO_FALLBACK) || !defined(MBEDTLS_ECP_NORMALIZE_MXZ_ALT) */
}
/*
* Randomize projective x/z coordinates:
* (X, Z) -> (l X, l Z) for random l
* This is sort of the reverse operation of ecp_normalize_mxz().
*
* This countermeasure was first suggested in [2].
* Cost: 2M
*/
static int ecp_randomize_mxz( const mbedtls_ecp_group *grp, mbedtls_ecp_point *P,
int (*f_rng)(void *, unsigned char *, size_t), void *p_rng )
{
#if defined(MBEDTLS_ECP_RANDOMIZE_MXZ_ALT)
if( mbedtls_internal_ecp_grp_capable( grp ) )
return( mbedtls_internal_ecp_randomize_mxz( grp, P, f_rng, p_rng ) );
#endif /* MBEDTLS_ECP_RANDOMIZE_MXZ_ALT */
#if defined(MBEDTLS_ECP_NO_FALLBACK) && defined(MBEDTLS_ECP_RANDOMIZE_MXZ_ALT)
return( MBEDTLS_ERR_ECP_FEATURE_UNAVAILABLE );
#else
int ret = MBEDTLS_ERR_ERROR_CORRUPTION_DETECTED;
mbedtls_mpi l;
mbedtls_mpi_init( &l );
/* Generate l such that 1 < l < p */
MBEDTLS_MPI_CHK( mbedtls_mpi_random( &l, 2, &grp->P, f_rng, p_rng ) );
MBEDTLS_MPI_CHK( mbedtls_mpi_mul_mod( grp, &P->X, &P->X, &l ) );
MBEDTLS_MPI_CHK( mbedtls_mpi_mul_mod( grp, &P->Z, &P->Z, &l ) );
cleanup:
mbedtls_mpi_free( &l );
if( ret == MBEDTLS_ERR_MPI_NOT_ACCEPTABLE )
ret = MBEDTLS_ERR_ECP_RANDOM_FAILED;
return( ret );
#endif /* !defined(MBEDTLS_ECP_NO_FALLBACK) || !defined(MBEDTLS_ECP_RANDOMIZE_MXZ_ALT) */
}
/*
* Double-and-add: R = 2P, S = P + Q, with d = X(P - Q),
* for Montgomery curves in x/z coordinates.
*
* http://www.hyperelliptic.org/EFD/g1p/auto-code/montgom/xz/ladder/mladd-1987-m.op3
* with
* d = X1
* P = (X2, Z2)
* Q = (X3, Z3)
* R = (X4, Z4)
* S = (X5, Z5)
* and eliminating temporary variables tO, ..., t4.
*
* Cost: 5M + 4S
*/
static int ecp_double_add_mxz( const mbedtls_ecp_group *grp,
mbedtls_ecp_point *R, mbedtls_ecp_point *S,
const mbedtls_ecp_point *P, const mbedtls_ecp_point *Q,
const mbedtls_mpi *d )
{
#if defined(MBEDTLS_ECP_DOUBLE_ADD_MXZ_ALT)
if( mbedtls_internal_ecp_grp_capable( grp ) )
return( mbedtls_internal_ecp_double_add_mxz( grp, R, S, P, Q, d ) );
#endif /* MBEDTLS_ECP_DOUBLE_ADD_MXZ_ALT */
#if defined(MBEDTLS_ECP_NO_FALLBACK) && defined(MBEDTLS_ECP_DOUBLE_ADD_MXZ_ALT)
return( MBEDTLS_ERR_ECP_FEATURE_UNAVAILABLE );
#else
int ret = MBEDTLS_ERR_ERROR_CORRUPTION_DETECTED;
mbedtls_mpi A, AA, B, BB, E, C, D, DA, CB;
mbedtls_mpi_init( &A ); mbedtls_mpi_init( &AA ); mbedtls_mpi_init( &B );
mbedtls_mpi_init( &BB ); mbedtls_mpi_init( &E ); mbedtls_mpi_init( &C );
mbedtls_mpi_init( &D ); mbedtls_mpi_init( &DA ); mbedtls_mpi_init( &CB );
MBEDTLS_MPI_CHK( mbedtls_mpi_add_mod( grp, &A, &P->X, &P->Z ) );
MBEDTLS_MPI_CHK( mbedtls_mpi_mul_mod( grp, &AA, &A, &A ) );
MBEDTLS_MPI_CHK( mbedtls_mpi_sub_mod( grp, &B, &P->X, &P->Z ) );
MBEDTLS_MPI_CHK( mbedtls_mpi_mul_mod( grp, &BB, &B, &B ) );
MBEDTLS_MPI_CHK( mbedtls_mpi_sub_mod( grp, &E, &AA, &BB ) );
MBEDTLS_MPI_CHK( mbedtls_mpi_add_mod( grp, &C, &Q->X, &Q->Z ) );
MBEDTLS_MPI_CHK( mbedtls_mpi_sub_mod( grp, &D, &Q->X, &Q->Z ) );
MBEDTLS_MPI_CHK( mbedtls_mpi_mul_mod( grp, &DA, &D, &A ) );
MBEDTLS_MPI_CHK( mbedtls_mpi_mul_mod( grp, &CB, &C, &B ) );
MBEDTLS_MPI_CHK( mbedtls_mpi_add_mod( grp, &S->X, &DA, &CB ) );
MBEDTLS_MPI_CHK( mbedtls_mpi_mul_mod( grp, &S->X, &S->X, &S->X ) );
MBEDTLS_MPI_CHK( mbedtls_mpi_sub_mod( grp, &S->Z, &DA, &CB ) );
MBEDTLS_MPI_CHK( mbedtls_mpi_mul_mod( grp, &S->Z, &S->Z, &S->Z ) );
MBEDTLS_MPI_CHK( mbedtls_mpi_mul_mod( grp, &S->Z, d, &S->Z ) );
MBEDTLS_MPI_CHK( mbedtls_mpi_mul_mod( grp, &R->X, &AA, &BB ) );
MBEDTLS_MPI_CHK( mbedtls_mpi_mul_mod( grp, &R->Z, &grp->A, &E ) );
MBEDTLS_MPI_CHK( mbedtls_mpi_add_mod( grp, &R->Z, &BB, &R->Z ) );
MBEDTLS_MPI_CHK( mbedtls_mpi_mul_mod( grp, &R->Z, &E, &R->Z ) );
cleanup:
mbedtls_mpi_free( &A ); mbedtls_mpi_free( &AA ); mbedtls_mpi_free( &B );
mbedtls_mpi_free( &BB ); mbedtls_mpi_free( &E ); mbedtls_mpi_free( &C );
mbedtls_mpi_free( &D ); mbedtls_mpi_free( &DA ); mbedtls_mpi_free( &CB );
return( ret );
#endif /* !defined(MBEDTLS_ECP_NO_FALLBACK) || !defined(MBEDTLS_ECP_DOUBLE_ADD_MXZ_ALT) */
}
/*
* Multiplication with Montgomery ladder in x/z coordinates,
* for curves in Montgomery form
*/
static int ecp_mul_mxz( mbedtls_ecp_group *grp, mbedtls_ecp_point *R,
const mbedtls_mpi *m, const mbedtls_ecp_point *P,
int (*f_rng)(void *, unsigned char *, size_t),
void *p_rng )
{
int ret = MBEDTLS_ERR_ERROR_CORRUPTION_DETECTED;
size_t i;
unsigned char b;
mbedtls_ecp_point RP;
mbedtls_mpi PX;
#if !defined(MBEDTLS_ECP_NO_INTERNAL_RNG)
ecp_drbg_context drbg_ctx;
ecp_drbg_init( &drbg_ctx );
#endif
mbedtls_ecp_point_init( &RP ); mbedtls_mpi_init( &PX );
#if !defined(MBEDTLS_ECP_NO_INTERNAL_RNG)
if( f_rng == NULL )
{
const size_t m_len = ( grp->nbits + 7 ) / 8;
MBEDTLS_MPI_CHK( ecp_drbg_seed( &drbg_ctx, m, m_len ) );
f_rng = &ecp_drbg_random;
p_rng = &drbg_ctx;
}
#endif /* !MBEDTLS_ECP_NO_INTERNAL_RNG */
/* Save PX and read from P before writing to R, in case P == R */
MBEDTLS_MPI_CHK( mbedtls_mpi_copy( &PX, &P->X ) );
MBEDTLS_MPI_CHK( mbedtls_ecp_copy( &RP, P ) );
/* Set R to zero in modified x/z coordinates */
MBEDTLS_MPI_CHK( mbedtls_mpi_lset( &R->X, 1 ) );
MBEDTLS_MPI_CHK( mbedtls_mpi_lset( &R->Z, 0 ) );
mbedtls_mpi_free( &R->Y );
/* RP.X might be sligtly larger than P, so reduce it */
MOD_ADD( RP.X );
/* Randomize coordinates of the starting point */
#if defined(MBEDTLS_ECP_NO_INTERNAL_RNG)
if( f_rng != NULL )
#endif
MBEDTLS_MPI_CHK( ecp_randomize_mxz( grp, &RP, f_rng, p_rng ) );
/* Loop invariant: R = result so far, RP = R + P */
i = mbedtls_mpi_bitlen( m ); /* one past the (zero-based) most significant bit */
while( i-- > 0 )
{
b = mbedtls_mpi_get_bit( m, i );
/*
* if (b) R = 2R + P else R = 2R,
* which is:
* if (b) double_add( RP, R, RP, R )
* else double_add( R, RP, R, RP )
* but using safe conditional swaps to avoid leaks
*/
MBEDTLS_MPI_CHK( mbedtls_mpi_safe_cond_swap( &R->X, &RP.X, b ) );
MBEDTLS_MPI_CHK( mbedtls_mpi_safe_cond_swap( &R->Z, &RP.Z, b ) );
MBEDTLS_MPI_CHK( ecp_double_add_mxz( grp, R, &RP, R, &RP, &PX ) );
MBEDTLS_MPI_CHK( mbedtls_mpi_safe_cond_swap( &R->X, &RP.X, b ) );
MBEDTLS_MPI_CHK( mbedtls_mpi_safe_cond_swap( &R->Z, &RP.Z, b ) );
}
/*
* Knowledge of the projective coordinates may leak the last few bits of the
* scalar [1], and since our MPI implementation isn't constant-flow,
* inversion (used for coordinate normalization) may leak the full value
* of its input via side-channels [2].
*
* [1] https://eprint.iacr.org/2003/191
* [2] https://eprint.iacr.org/2020/055
*
* Avoid the leak by randomizing coordinates before we normalize them.
*/
#if defined(MBEDTLS_ECP_NO_INTERNAL_RNG)
if( f_rng != NULL )
#endif
MBEDTLS_MPI_CHK( ecp_randomize_mxz( grp, R, f_rng, p_rng ) );
MBEDTLS_MPI_CHK( ecp_normalize_mxz( grp, R ) );
cleanup:
#if !defined(MBEDTLS_ECP_NO_INTERNAL_RNG)
ecp_drbg_free( &drbg_ctx );
#endif
mbedtls_ecp_point_free( &RP ); mbedtls_mpi_free( &PX );
return( ret );
}
#endif /* MBEDTLS_ECP_MONTGOMERY_ENABLED */
/*
* Restartable multiplication R = m * P
*/
int mbedtls_ecp_mul_restartable( mbedtls_ecp_group *grp, mbedtls_ecp_point *R,
const mbedtls_mpi *m, const mbedtls_ecp_point *P,
int (*f_rng)(void *, unsigned char *, size_t), void *p_rng,
mbedtls_ecp_restart_ctx *rs_ctx )
{
int ret = MBEDTLS_ERR_ECP_BAD_INPUT_DATA;
#if defined(MBEDTLS_ECP_INTERNAL_ALT)
char is_grp_capable = 0;
#endif
ECP_VALIDATE_RET( grp != NULL );
ECP_VALIDATE_RET( R != NULL );
ECP_VALIDATE_RET( m != NULL );
ECP_VALIDATE_RET( P != NULL );
#if defined(MBEDTLS_ECP_RESTARTABLE)
/* reset ops count for this call if top-level */
if( rs_ctx != NULL && rs_ctx->depth++ == 0 )
rs_ctx->ops_done = 0;
#else
(void) rs_ctx;
#endif
#if defined(MBEDTLS_ECP_INTERNAL_ALT)
if( ( is_grp_capable = mbedtls_internal_ecp_grp_capable( grp ) ) )
MBEDTLS_MPI_CHK( mbedtls_internal_ecp_init( grp ) );
#endif /* MBEDTLS_ECP_INTERNAL_ALT */
#if defined(MBEDTLS_ECP_RESTARTABLE)
/* skip argument check when restarting */
if( rs_ctx == NULL || rs_ctx->rsm == NULL )
#endif
{
/* check_privkey is free */
MBEDTLS_ECP_BUDGET( MBEDTLS_ECP_OPS_CHK );
/* Common sanity checks */
MBEDTLS_MPI_CHK( mbedtls_ecp_check_privkey( grp, m ) );
MBEDTLS_MPI_CHK( mbedtls_ecp_check_pubkey( grp, P ) );
}
ret = MBEDTLS_ERR_ECP_BAD_INPUT_DATA;
#if defined(MBEDTLS_ECP_MONTGOMERY_ENABLED)
if( mbedtls_ecp_get_type( grp ) == MBEDTLS_ECP_TYPE_MONTGOMERY )
MBEDTLS_MPI_CHK( ecp_mul_mxz( grp, R, m, P, f_rng, p_rng ) );
#endif
#if defined(MBEDTLS_ECP_SHORT_WEIERSTRASS_ENABLED)
if( mbedtls_ecp_get_type( grp ) == MBEDTLS_ECP_TYPE_SHORT_WEIERSTRASS )
MBEDTLS_MPI_CHK( ecp_mul_comb( grp, R, m, P, f_rng, p_rng, rs_ctx ) );
#endif
cleanup:
#if defined(MBEDTLS_ECP_INTERNAL_ALT)
if( is_grp_capable )
mbedtls_internal_ecp_free( grp );
#endif /* MBEDTLS_ECP_INTERNAL_ALT */
#if defined(MBEDTLS_ECP_RESTARTABLE)
if( rs_ctx != NULL )
rs_ctx->depth--;
#endif
return( ret );
}
/*
* Multiplication R = m * P
*/
int mbedtls_ecp_mul( mbedtls_ecp_group *grp, mbedtls_ecp_point *R,
const mbedtls_mpi *m, const mbedtls_ecp_point *P,
int (*f_rng)(void *, unsigned char *, size_t), void *p_rng )
{
ECP_VALIDATE_RET( grp != NULL );
ECP_VALIDATE_RET( R != NULL );
ECP_VALIDATE_RET( m != NULL );
ECP_VALIDATE_RET( P != NULL );
return( mbedtls_ecp_mul_restartable( grp, R, m, P, f_rng, p_rng, NULL ) );
}
#if defined(MBEDTLS_ECP_SHORT_WEIERSTRASS_ENABLED)
/*
* Check that an affine point is valid as a public key,
* short weierstrass curves (SEC1 3.2.3.1)
*/
static int ecp_check_pubkey_sw( const mbedtls_ecp_group *grp, const mbedtls_ecp_point *pt )
{
int ret = MBEDTLS_ERR_ERROR_CORRUPTION_DETECTED;
mbedtls_mpi YY, RHS;
/* pt coordinates must be normalized for our checks */
if( mbedtls_mpi_cmp_int( &pt->X, 0 ) < 0 ||
mbedtls_mpi_cmp_int( &pt->Y, 0 ) < 0 ||
mbedtls_mpi_cmp_mpi( &pt->X, &grp->P ) >= 0 ||
mbedtls_mpi_cmp_mpi( &pt->Y, &grp->P ) >= 0 )
return( MBEDTLS_ERR_ECP_INVALID_KEY );
mbedtls_mpi_init( &YY ); mbedtls_mpi_init( &RHS );
/*
* YY = Y^2
* RHS = X (X^2 + A) + B = X^3 + A X + B
*/
MBEDTLS_MPI_CHK( mbedtls_mpi_mul_mod( grp, &YY, &pt->Y, &pt->Y ) );
MBEDTLS_MPI_CHK( mbedtls_mpi_mul_mod( grp, &RHS, &pt->X, &pt->X ) );
/* Special case for A = -3 */
if( grp->A.p == NULL )
{
MBEDTLS_MPI_CHK( mbedtls_mpi_sub_int( &RHS, &RHS, 3 ) ); MOD_SUB( RHS );
}
else
{
MBEDTLS_MPI_CHK( mbedtls_mpi_add_mod( grp, &RHS, &RHS, &grp->A ) );
}
MBEDTLS_MPI_CHK( mbedtls_mpi_mul_mod( grp, &RHS, &RHS, &pt->X ) );
MBEDTLS_MPI_CHK( mbedtls_mpi_add_mod( grp, &RHS, &RHS, &grp->B ) );
if( mbedtls_mpi_cmp_mpi( &YY, &RHS ) != 0 )
ret = MBEDTLS_ERR_ECP_INVALID_KEY;
cleanup:
mbedtls_mpi_free( &YY ); mbedtls_mpi_free( &RHS );
return( ret );
}
#endif /* MBEDTLS_ECP_SHORT_WEIERSTRASS_ENABLED */
#if defined(MBEDTLS_ECP_SHORT_WEIERSTRASS_ENABLED)
/*
* R = m * P with shortcuts for m == 0, m == 1 and m == -1
* NOT constant-time - ONLY for short Weierstrass!
*/
static int mbedtls_ecp_mul_shortcuts( mbedtls_ecp_group *grp,
mbedtls_ecp_point *R,
const mbedtls_mpi *m,
const mbedtls_ecp_point *P,
mbedtls_ecp_restart_ctx *rs_ctx )
{
int ret = MBEDTLS_ERR_ERROR_CORRUPTION_DETECTED;
if( mbedtls_mpi_cmp_int( m, 0 ) == 0 )
{
MBEDTLS_MPI_CHK( mbedtls_ecp_set_zero( R ) );
}
else if( mbedtls_mpi_cmp_int( m, 1 ) == 0 )
{
MBEDTLS_MPI_CHK( mbedtls_ecp_copy( R, P ) );
}
else if( mbedtls_mpi_cmp_int( m, -1 ) == 0 )
{
MBEDTLS_MPI_CHK( mbedtls_ecp_copy( R, P ) );
if( mbedtls_mpi_cmp_int( &R->Y, 0 ) != 0 )
MBEDTLS_MPI_CHK( mbedtls_mpi_sub_mpi( &R->Y, &grp->P, &R->Y ) );
}
else
{
MBEDTLS_MPI_CHK( mbedtls_ecp_mul_restartable( grp, R, m, P,
NULL, NULL, rs_ctx ) );
}
cleanup:
return( ret );
}
/*
* Restartable linear combination
* NOT constant-time
*/
int mbedtls_ecp_muladd_restartable(
mbedtls_ecp_group *grp, mbedtls_ecp_point *R,
const mbedtls_mpi *m, const mbedtls_ecp_point *P,
const mbedtls_mpi *n, const mbedtls_ecp_point *Q,
mbedtls_ecp_restart_ctx *rs_ctx )
{
int ret = MBEDTLS_ERR_ERROR_CORRUPTION_DETECTED;
mbedtls_ecp_point mP;
mbedtls_ecp_point *pmP = &mP;
mbedtls_ecp_point *pR = R;
#if defined(MBEDTLS_ECP_INTERNAL_ALT)
char is_grp_capable = 0;
#endif
ECP_VALIDATE_RET( grp != NULL );
ECP_VALIDATE_RET( R != NULL );
ECP_VALIDATE_RET( m != NULL );
ECP_VALIDATE_RET( P != NULL );
ECP_VALIDATE_RET( n != NULL );
ECP_VALIDATE_RET( Q != NULL );
if( mbedtls_ecp_get_type( grp ) != MBEDTLS_ECP_TYPE_SHORT_WEIERSTRASS )
return( MBEDTLS_ERR_ECP_FEATURE_UNAVAILABLE );
mbedtls_ecp_point_init( &mP );
ECP_RS_ENTER( ma );
#if defined(MBEDTLS_ECP_RESTARTABLE)
if( rs_ctx != NULL && rs_ctx->ma != NULL )
{
/* redirect intermediate results to restart context */
pmP = &rs_ctx->ma->mP;
pR = &rs_ctx->ma->R;
/* jump to next operation */
if( rs_ctx->ma->state == ecp_rsma_mul2 )
goto mul2;
if( rs_ctx->ma->state == ecp_rsma_add )
goto add;
if( rs_ctx->ma->state == ecp_rsma_norm )
goto norm;
}
#endif /* MBEDTLS_ECP_RESTARTABLE */
MBEDTLS_MPI_CHK( mbedtls_ecp_mul_shortcuts( grp, pmP, m, P, rs_ctx ) );
#if defined(MBEDTLS_ECP_RESTARTABLE)
if( rs_ctx != NULL && rs_ctx->ma != NULL )
rs_ctx->ma->state = ecp_rsma_mul2;
mul2:
#endif
MBEDTLS_MPI_CHK( mbedtls_ecp_mul_shortcuts( grp, pR, n, Q, rs_ctx ) );
#if defined(MBEDTLS_ECP_INTERNAL_ALT)
if( ( is_grp_capable = mbedtls_internal_ecp_grp_capable( grp ) ) )
MBEDTLS_MPI_CHK( mbedtls_internal_ecp_init( grp ) );
#endif /* MBEDTLS_ECP_INTERNAL_ALT */
#if defined(MBEDTLS_ECP_RESTARTABLE)
if( rs_ctx != NULL && rs_ctx->ma != NULL )
rs_ctx->ma->state = ecp_rsma_add;
add:
#endif
MBEDTLS_ECP_BUDGET( MBEDTLS_ECP_OPS_ADD );
MBEDTLS_MPI_CHK( ecp_add_mixed( grp, pR, pmP, pR ) );
#if defined(MBEDTLS_ECP_RESTARTABLE)
if( rs_ctx != NULL && rs_ctx->ma != NULL )
rs_ctx->ma->state = ecp_rsma_norm;
norm:
#endif
MBEDTLS_ECP_BUDGET( MBEDTLS_ECP_OPS_INV );
MBEDTLS_MPI_CHK( ecp_normalize_jac( grp, pR ) );
#if defined(MBEDTLS_ECP_RESTARTABLE)
if( rs_ctx != NULL && rs_ctx->ma != NULL )
MBEDTLS_MPI_CHK( mbedtls_ecp_copy( R, pR ) );
#endif
cleanup:
#if defined(MBEDTLS_ECP_INTERNAL_ALT)
if( is_grp_capable )
mbedtls_internal_ecp_free( grp );
#endif /* MBEDTLS_ECP_INTERNAL_ALT */
mbedtls_ecp_point_free( &mP );
ECP_RS_LEAVE( ma );
return( ret );
}
/*
* Linear combination
* NOT constant-time
*/
int mbedtls_ecp_muladd( mbedtls_ecp_group *grp, mbedtls_ecp_point *R,
const mbedtls_mpi *m, const mbedtls_ecp_point *P,
const mbedtls_mpi *n, const mbedtls_ecp_point *Q )
{
ECP_VALIDATE_RET( grp != NULL );
ECP_VALIDATE_RET( R != NULL );
ECP_VALIDATE_RET( m != NULL );
ECP_VALIDATE_RET( P != NULL );
ECP_VALIDATE_RET( n != NULL );
ECP_VALIDATE_RET( Q != NULL );
return( mbedtls_ecp_muladd_restartable( grp, R, m, P, n, Q, NULL ) );
}
#endif /* MBEDTLS_ECP_SHORT_WEIERSTRASS_ENABLED */
#if defined(MBEDTLS_ECP_MONTGOMERY_ENABLED)
#if defined(MBEDTLS_ECP_DP_CURVE25519_ENABLED)
#define ECP_MPI_INIT(s, n, p) {s, (n), (mbedtls_mpi_uint *)(p)}
#define ECP_MPI_INIT_ARRAY(x) \
ECP_MPI_INIT(1, sizeof(x) / sizeof(mbedtls_mpi_uint), x)
/*
* Constants for the two points other than 0, 1, -1 (mod p) in
* https://cr.yp.to/ecdh.html#validate
* See ecp_check_pubkey_x25519().
*/
static const mbedtls_mpi_uint x25519_bad_point_1[] = {
MBEDTLS_BYTES_TO_T_UINT_8( 0xe0, 0xeb, 0x7a, 0x7c, 0x3b, 0x41, 0xb8, 0xae ),
MBEDTLS_BYTES_TO_T_UINT_8( 0x16, 0x56, 0xe3, 0xfa, 0xf1, 0x9f, 0xc4, 0x6a ),
MBEDTLS_BYTES_TO_T_UINT_8( 0xda, 0x09, 0x8d, 0xeb, 0x9c, 0x32, 0xb1, 0xfd ),
MBEDTLS_BYTES_TO_T_UINT_8( 0x86, 0x62, 0x05, 0x16, 0x5f, 0x49, 0xb8, 0x00 ),
};
static const mbedtls_mpi_uint x25519_bad_point_2[] = {
MBEDTLS_BYTES_TO_T_UINT_8( 0x5f, 0x9c, 0x95, 0xbc, 0xa3, 0x50, 0x8c, 0x24 ),
MBEDTLS_BYTES_TO_T_UINT_8( 0xb1, 0xd0, 0xb1, 0x55, 0x9c, 0x83, 0xef, 0x5b ),
MBEDTLS_BYTES_TO_T_UINT_8( 0x04, 0x44, 0x5c, 0xc4, 0x58, 0x1c, 0x8e, 0x86 ),
MBEDTLS_BYTES_TO_T_UINT_8( 0xd8, 0x22, 0x4e, 0xdd, 0xd0, 0x9f, 0x11, 0x57 ),
};
static const mbedtls_mpi ecp_x25519_bad_point_1 = ECP_MPI_INIT_ARRAY(
x25519_bad_point_1 );
static const mbedtls_mpi ecp_x25519_bad_point_2 = ECP_MPI_INIT_ARRAY(
x25519_bad_point_2 );
#endif /* MBEDTLS_ECP_DP_CURVE25519_ENABLED */
/*
* Check that the input point is not one of the low-order points.
* This is recommended by the "May the Fourth" paper:
* https://eprint.iacr.org/2017/806.pdf
* Those points are never sent by an honest peer.
*/
static int ecp_check_bad_points_mx( const mbedtls_mpi *X, const mbedtls_mpi *P,
const mbedtls_ecp_group_id grp_id )
{
int ret;
mbedtls_mpi XmP;
mbedtls_mpi_init( &XmP );
/* Reduce X mod P so that we only need to check values less than P.
* We know X < 2^256 so we can proceed by subtraction. */
MBEDTLS_MPI_CHK( mbedtls_mpi_copy( &XmP, X ) );
while( mbedtls_mpi_cmp_mpi( &XmP, P ) >= 0 )
MBEDTLS_MPI_CHK( mbedtls_mpi_sub_mpi( &XmP, &XmP, P ) );
/* Check against the known bad values that are less than P. For Curve448
* these are 0, 1 and -1. For Curve25519 we check the values less than P
* from the following list: https://cr.yp.to/ecdh.html#validate */
if( mbedtls_mpi_cmp_int( &XmP, 1 ) <= 0 ) /* takes care of 0 and 1 */
{
ret = MBEDTLS_ERR_ECP_INVALID_KEY;
goto cleanup;
}
#if defined(MBEDTLS_ECP_DP_CURVE25519_ENABLED)
if( grp_id == MBEDTLS_ECP_DP_CURVE25519 )
{
if( mbedtls_mpi_cmp_mpi( &XmP, &ecp_x25519_bad_point_1 ) == 0 )
{
ret = MBEDTLS_ERR_ECP_INVALID_KEY;
goto cleanup;
}
if( mbedtls_mpi_cmp_mpi( &XmP, &ecp_x25519_bad_point_2 ) == 0 )
{
ret = MBEDTLS_ERR_ECP_INVALID_KEY;
goto cleanup;
}
}
#else
(void) grp_id;
#endif
/* Final check: check if XmP + 1 is P (final because it changes XmP!) */
MBEDTLS_MPI_CHK( mbedtls_mpi_add_int( &XmP, &XmP, 1 ) );
if( mbedtls_mpi_cmp_mpi( &XmP, P ) == 0 )
{
ret = MBEDTLS_ERR_ECP_INVALID_KEY;
goto cleanup;
}
ret = 0;
cleanup:
mbedtls_mpi_free( &XmP );
return( ret );
}
/*
* Check validity of a public key for Montgomery curves with x-only schemes
*/
static int ecp_check_pubkey_mx( const mbedtls_ecp_group *grp, const mbedtls_ecp_point *pt )
{
/* [Curve25519 p. 5] Just check X is the correct number of bytes */
/* Allow any public value, if it's too big then we'll just reduce it mod p
* (RFC 7748 sec. 5 para. 3). */
if( mbedtls_mpi_size( &pt->X ) > ( grp->nbits + 7 ) / 8 )
return( MBEDTLS_ERR_ECP_INVALID_KEY );
/* Implicit in all standards (as they don't consider negative numbers):
* X must be non-negative. This is normally ensured by the way it's
* encoded for transmission, but let's be extra sure. */
if( mbedtls_mpi_cmp_int( &pt->X, 0 ) < 0 )
return( MBEDTLS_ERR_ECP_INVALID_KEY );
return( ecp_check_bad_points_mx( &pt->X, &grp->P, grp->id ) );
}
#endif /* MBEDTLS_ECP_MONTGOMERY_ENABLED */
/*
* Check that a point is valid as a public key
*/
int mbedtls_ecp_check_pubkey( const mbedtls_ecp_group *grp,
const mbedtls_ecp_point *pt )
{
ECP_VALIDATE_RET( grp != NULL );
ECP_VALIDATE_RET( pt != NULL );
/* Must use affine coordinates */
if( mbedtls_mpi_cmp_int( &pt->Z, 1 ) != 0 )
return( MBEDTLS_ERR_ECP_INVALID_KEY );
#if defined(MBEDTLS_ECP_MONTGOMERY_ENABLED)
if( mbedtls_ecp_get_type( grp ) == MBEDTLS_ECP_TYPE_MONTGOMERY )
return( ecp_check_pubkey_mx( grp, pt ) );
#endif
#if defined(MBEDTLS_ECP_SHORT_WEIERSTRASS_ENABLED)
if( mbedtls_ecp_get_type( grp ) == MBEDTLS_ECP_TYPE_SHORT_WEIERSTRASS )
return( ecp_check_pubkey_sw( grp, pt ) );
#endif
return( MBEDTLS_ERR_ECP_BAD_INPUT_DATA );
}
/*
* Check that an mbedtls_mpi is valid as a private key
*/
int mbedtls_ecp_check_privkey( const mbedtls_ecp_group *grp,
const mbedtls_mpi *d )
{
ECP_VALIDATE_RET( grp != NULL );
ECP_VALIDATE_RET( d != NULL );
#if defined(MBEDTLS_ECP_MONTGOMERY_ENABLED)
if( mbedtls_ecp_get_type( grp ) == MBEDTLS_ECP_TYPE_MONTGOMERY )
{
/* see RFC 7748 sec. 5 para. 5 */
if( mbedtls_mpi_get_bit( d, 0 ) != 0 ||
mbedtls_mpi_get_bit( d, 1 ) != 0 ||
mbedtls_mpi_bitlen( d ) - 1 != grp->nbits ) /* mbedtls_mpi_bitlen is one-based! */
return( MBEDTLS_ERR_ECP_INVALID_KEY );
/* see [Curve25519] page 5 */
if( grp->nbits == 254 && mbedtls_mpi_get_bit( d, 2 ) != 0 )
return( MBEDTLS_ERR_ECP_INVALID_KEY );
return( 0 );
}
#endif /* MBEDTLS_ECP_MONTGOMERY_ENABLED */
#if defined(MBEDTLS_ECP_SHORT_WEIERSTRASS_ENABLED)
if( mbedtls_ecp_get_type( grp ) == MBEDTLS_ECP_TYPE_SHORT_WEIERSTRASS )
{
/* see SEC1 3.2 */
if( mbedtls_mpi_cmp_int( d, 1 ) < 0 ||
mbedtls_mpi_cmp_mpi( d, &grp->N ) >= 0 )
return( MBEDTLS_ERR_ECP_INVALID_KEY );
else
return( 0 );
}
#endif /* MBEDTLS_ECP_SHORT_WEIERSTRASS_ENABLED */
return( MBEDTLS_ERR_ECP_BAD_INPUT_DATA );
}
#if defined(MBEDTLS_ECP_MONTGOMERY_ENABLED)
MBEDTLS_STATIC_TESTABLE
int mbedtls_ecp_gen_privkey_mx( size_t high_bit,
mbedtls_mpi *d,
int (*f_rng)(void *, unsigned char *, size_t),
void *p_rng )
{
int ret = MBEDTLS_ERR_ECP_BAD_INPUT_DATA;
size_t n_random_bytes = high_bit / 8 + 1;
/* [Curve25519] page 5 */
/* Generate a (high_bit+1)-bit random number by generating just enough
* random bytes, then shifting out extra bits from the top (necessary
* when (high_bit+1) is not a multiple of 8). */
MBEDTLS_MPI_CHK( mbedtls_mpi_fill_random( d, n_random_bytes,
f_rng, p_rng ) );
MBEDTLS_MPI_CHK( mbedtls_mpi_shift_r( d, 8 * n_random_bytes - high_bit - 1 ) );
MBEDTLS_MPI_CHK( mbedtls_mpi_set_bit( d, high_bit, 1 ) );
/* Make sure the last two bits are unset for Curve448, three bits for
Curve25519 */
MBEDTLS_MPI_CHK( mbedtls_mpi_set_bit( d, 0, 0 ) );
MBEDTLS_MPI_CHK( mbedtls_mpi_set_bit( d, 1, 0 ) );
if( high_bit == 254 )
{
MBEDTLS_MPI_CHK( mbedtls_mpi_set_bit( d, 2, 0 ) );
}
cleanup:
return( ret );
}
#endif /* MBEDTLS_ECP_MONTGOMERY_ENABLED */
#if defined(MBEDTLS_ECP_SHORT_WEIERSTRASS_ENABLED)
static int mbedtls_ecp_gen_privkey_sw(
const mbedtls_mpi *N, mbedtls_mpi *d,
int (*f_rng)(void *, unsigned char *, size_t), void *p_rng )
{
int ret = mbedtls_mpi_random( d, 1, N, f_rng, p_rng );
switch( ret )
{
case MBEDTLS_ERR_MPI_NOT_ACCEPTABLE:
return( MBEDTLS_ERR_ECP_RANDOM_FAILED );
default:
return( ret );
}
}
#endif /* MBEDTLS_ECP_SHORT_WEIERSTRASS_ENABLED */
/*
* Generate a private key
*/
int mbedtls_ecp_gen_privkey( const mbedtls_ecp_group *grp,
mbedtls_mpi *d,
int (*f_rng)(void *, unsigned char *, size_t),
void *p_rng )
{
ECP_VALIDATE_RET( grp != NULL );
ECP_VALIDATE_RET( d != NULL );
ECP_VALIDATE_RET( f_rng != NULL );
#if defined(MBEDTLS_ECP_MONTGOMERY_ENABLED)
if( mbedtls_ecp_get_type( grp ) == MBEDTLS_ECP_TYPE_MONTGOMERY )
return( mbedtls_ecp_gen_privkey_mx( grp->nbits, d, f_rng, p_rng ) );
#endif /* MBEDTLS_ECP_MONTGOMERY_ENABLED */
#if defined(MBEDTLS_ECP_SHORT_WEIERSTRASS_ENABLED)
if( mbedtls_ecp_get_type( grp ) == MBEDTLS_ECP_TYPE_SHORT_WEIERSTRASS )
return( mbedtls_ecp_gen_privkey_sw( &grp->N, d, f_rng, p_rng ) );
#endif /* MBEDTLS_ECP_SHORT_WEIERSTRASS_ENABLED */
return( MBEDTLS_ERR_ECP_BAD_INPUT_DATA );
}
/*
* Generate a keypair with configurable base point
*/
int mbedtls_ecp_gen_keypair_base( mbedtls_ecp_group *grp,
const mbedtls_ecp_point *G,
mbedtls_mpi *d, mbedtls_ecp_point *Q,
int (*f_rng)(void *, unsigned char *, size_t),
void *p_rng )
{
int ret = MBEDTLS_ERR_ERROR_CORRUPTION_DETECTED;
ECP_VALIDATE_RET( grp != NULL );
ECP_VALIDATE_RET( d != NULL );
ECP_VALIDATE_RET( G != NULL );
ECP_VALIDATE_RET( Q != NULL );
ECP_VALIDATE_RET( f_rng != NULL );
MBEDTLS_MPI_CHK( mbedtls_ecp_gen_privkey( grp, d, f_rng, p_rng ) );
MBEDTLS_MPI_CHK( mbedtls_ecp_mul( grp, Q, d, G, f_rng, p_rng ) );
cleanup:
return( ret );
}
/*
* Generate key pair, wrapper for conventional base point
*/
int mbedtls_ecp_gen_keypair( mbedtls_ecp_group *grp,
mbedtls_mpi *d, mbedtls_ecp_point *Q,
int (*f_rng)(void *, unsigned char *, size_t),
void *p_rng )
{
ECP_VALIDATE_RET( grp != NULL );
ECP_VALIDATE_RET( d != NULL );
ECP_VALIDATE_RET( Q != NULL );
ECP_VALIDATE_RET( f_rng != NULL );
return( mbedtls_ecp_gen_keypair_base( grp, &grp->G, d, Q, f_rng, p_rng ) );
}
/*
* Generate a keypair, prettier wrapper
*/
int mbedtls_ecp_gen_key( mbedtls_ecp_group_id grp_id, mbedtls_ecp_keypair *key,
int (*f_rng)(void *, unsigned char *, size_t), void *p_rng )
{
int ret = MBEDTLS_ERR_ERROR_CORRUPTION_DETECTED;
ECP_VALIDATE_RET( key != NULL );
ECP_VALIDATE_RET( f_rng != NULL );
if( ( ret = mbedtls_ecp_group_load( &key->grp, grp_id ) ) != 0 )
return( ret );
return( mbedtls_ecp_gen_keypair( &key->grp, &key->d, &key->Q, f_rng, p_rng ) );
}
#define ECP_CURVE25519_KEY_SIZE 32
/*
* Read a private key.
*/
int mbedtls_ecp_read_key( mbedtls_ecp_group_id grp_id, mbedtls_ecp_keypair *key,
const unsigned char *buf, size_t buflen )
{
int ret = 0;
ECP_VALIDATE_RET( key != NULL );
ECP_VALIDATE_RET( buf != NULL );
if( ( ret = mbedtls_ecp_group_load( &key->grp, grp_id ) ) != 0 )
return( ret );
ret = MBEDTLS_ERR_ECP_FEATURE_UNAVAILABLE;
#if defined(MBEDTLS_ECP_MONTGOMERY_ENABLED)
if( mbedtls_ecp_get_type( &key->grp ) == MBEDTLS_ECP_TYPE_MONTGOMERY )
{
/*
* If it is Curve25519 curve then mask the key as mandated by RFC7748
*/
if( grp_id == MBEDTLS_ECP_DP_CURVE25519 )
{
if( buflen != ECP_CURVE25519_KEY_SIZE )
return MBEDTLS_ERR_ECP_INVALID_KEY;
MBEDTLS_MPI_CHK( mbedtls_mpi_read_binary_le( &key->d, buf, buflen ) );
/* Set the three least significant bits to 0 */
MBEDTLS_MPI_CHK( mbedtls_mpi_set_bit( &key->d, 0, 0 ) );
MBEDTLS_MPI_CHK( mbedtls_mpi_set_bit( &key->d, 1, 0 ) );
MBEDTLS_MPI_CHK( mbedtls_mpi_set_bit( &key->d, 2, 0 ) );
/* Set the most significant bit to 0 */
MBEDTLS_MPI_CHK(
mbedtls_mpi_set_bit( &key->d,
ECP_CURVE25519_KEY_SIZE * 8 - 1, 0 )
);
/* Set the second most significant bit to 1 */
MBEDTLS_MPI_CHK(
mbedtls_mpi_set_bit( &key->d,
ECP_CURVE25519_KEY_SIZE * 8 - 2, 1 )
);
}
else
ret = MBEDTLS_ERR_ECP_FEATURE_UNAVAILABLE;
}
#endif
#if defined(MBEDTLS_ECP_SHORT_WEIERSTRASS_ENABLED)
if( mbedtls_ecp_get_type( &key->grp ) == MBEDTLS_ECP_TYPE_SHORT_WEIERSTRASS )
{
MBEDTLS_MPI_CHK( mbedtls_mpi_read_binary( &key->d, buf, buflen ) );
MBEDTLS_MPI_CHK( mbedtls_ecp_check_privkey( &key->grp, &key->d ) );
}
#endif
cleanup:
if( ret != 0 )
mbedtls_mpi_free( &key->d );
return( ret );
}
/*
* Write a private key.
*/
int mbedtls_ecp_write_key( mbedtls_ecp_keypair *key,
unsigned char *buf, size_t buflen )
{
int ret = MBEDTLS_ERR_ECP_FEATURE_UNAVAILABLE;
ECP_VALIDATE_RET( key != NULL );
ECP_VALIDATE_RET( buf != NULL );
#if defined(MBEDTLS_ECP_MONTGOMERY_ENABLED)
if( mbedtls_ecp_get_type( &key->grp ) == MBEDTLS_ECP_TYPE_MONTGOMERY )
{
if( key->grp.id == MBEDTLS_ECP_DP_CURVE25519 )
{
if( buflen < ECP_CURVE25519_KEY_SIZE )
return MBEDTLS_ERR_ECP_BUFFER_TOO_SMALL;
MBEDTLS_MPI_CHK( mbedtls_mpi_write_binary_le( &key->d, buf, buflen ) );
}
else
ret = MBEDTLS_ERR_ECP_FEATURE_UNAVAILABLE;
}
#endif
#if defined(MBEDTLS_ECP_SHORT_WEIERSTRASS_ENABLED)
if( mbedtls_ecp_get_type( &key->grp ) == MBEDTLS_ECP_TYPE_SHORT_WEIERSTRASS )
{
MBEDTLS_MPI_CHK( mbedtls_mpi_write_binary( &key->d, buf, buflen ) );
}
#endif
cleanup:
return( ret );
}
/*
* Check a public-private key pair
*/
int mbedtls_ecp_check_pub_priv( const mbedtls_ecp_keypair *pub, const mbedtls_ecp_keypair *prv )
{
int ret = MBEDTLS_ERR_ERROR_CORRUPTION_DETECTED;
mbedtls_ecp_point Q;
mbedtls_ecp_group grp;
ECP_VALIDATE_RET( pub != NULL );
ECP_VALIDATE_RET( prv != NULL );
if( pub->grp.id == MBEDTLS_ECP_DP_NONE ||
pub->grp.id != prv->grp.id ||
mbedtls_mpi_cmp_mpi( &pub->Q.X, &prv->Q.X ) ||
mbedtls_mpi_cmp_mpi( &pub->Q.Y, &prv->Q.Y ) ||
mbedtls_mpi_cmp_mpi( &pub->Q.Z, &prv->Q.Z ) )
{
return( MBEDTLS_ERR_ECP_BAD_INPUT_DATA );
}
mbedtls_ecp_point_init( &Q );
mbedtls_ecp_group_init( &grp );
/* mbedtls_ecp_mul() needs a non-const group... */
mbedtls_ecp_group_copy( &grp, &prv->grp );
/* Also checks d is valid */
MBEDTLS_MPI_CHK( mbedtls_ecp_mul( &grp, &Q, &prv->d, &prv->grp.G, NULL, NULL ) );
if( mbedtls_mpi_cmp_mpi( &Q.X, &prv->Q.X ) ||
mbedtls_mpi_cmp_mpi( &Q.Y, &prv->Q.Y ) ||
mbedtls_mpi_cmp_mpi( &Q.Z, &prv->Q.Z ) )
{
ret = MBEDTLS_ERR_ECP_BAD_INPUT_DATA;
goto cleanup;
}
cleanup:
mbedtls_ecp_point_free( &Q );
mbedtls_ecp_group_free( &grp );
return( ret );
}
#if defined(MBEDTLS_SELF_TEST)
/* Adjust the exponent to be a valid private point for the specified curve.
* This is sometimes necessary because we use a single set of exponents
* for all curves but the validity of values depends on the curve. */
static int self_test_adjust_exponent( const mbedtls_ecp_group *grp,
mbedtls_mpi *m )
{
int ret = 0;
switch( grp->id )
{
/* If Curve25519 is available, then that's what we use for the
* Montgomery test, so we don't need the adjustment code. */
#if ! defined(MBEDTLS_ECP_DP_CURVE25519_ENABLED)
#if defined(MBEDTLS_ECP_DP_CURVE448_ENABLED)
case MBEDTLS_ECP_DP_CURVE448:
/* Move highest bit from 254 to N-1. Setting bit N-1 is
* necessary to enforce the highest-bit-set constraint. */
MBEDTLS_MPI_CHK( mbedtls_mpi_set_bit( m, 254, 0 ) );
MBEDTLS_MPI_CHK( mbedtls_mpi_set_bit( m, grp->nbits, 1 ) );
/* Copy second-highest bit from 253 to N-2. This is not
* necessary but improves the test variety a bit. */
MBEDTLS_MPI_CHK(
mbedtls_mpi_set_bit( m, grp->nbits - 1,
mbedtls_mpi_get_bit( m, 253 ) ) );
break;
#endif
#endif /* ! defined(MBEDTLS_ECP_DP_CURVE25519_ENABLED) */
default:
/* Non-Montgomery curves and Curve25519 need no adjustment. */
(void) grp;
(void) m;
goto cleanup;
}
cleanup:
return( ret );
}
/* Calculate R = m.P for each m in exponents. Check that the number of
* basic operations doesn't depend on the value of m. */
static int self_test_point( int verbose,
mbedtls_ecp_group *grp,
mbedtls_ecp_point *R,
mbedtls_mpi *m,
const mbedtls_ecp_point *P,
const char *const *exponents,
size_t n_exponents )
{
int ret = 0;
size_t i = 0;
unsigned long add_c_prev, dbl_c_prev, mul_c_prev;
add_count = 0;
dbl_count = 0;
mul_count = 0;
MBEDTLS_MPI_CHK( mbedtls_mpi_read_string( m, 16, exponents[0] ) );
MBEDTLS_MPI_CHK( self_test_adjust_exponent( grp, m ) );
MBEDTLS_MPI_CHK( mbedtls_ecp_mul( grp, R, m, P, NULL, NULL ) );
for( i = 1; i < n_exponents; i++ )
{
add_c_prev = add_count;
dbl_c_prev = dbl_count;
mul_c_prev = mul_count;
add_count = 0;
dbl_count = 0;
mul_count = 0;
MBEDTLS_MPI_CHK( mbedtls_mpi_read_string( m, 16, exponents[i] ) );
MBEDTLS_MPI_CHK( self_test_adjust_exponent( grp, m ) );
MBEDTLS_MPI_CHK( mbedtls_ecp_mul( grp, R, m, P, NULL, NULL ) );
if( add_count != add_c_prev ||
dbl_count != dbl_c_prev ||
mul_count != mul_c_prev )
{
ret = 1;
break;
}
}
cleanup:
if( verbose != 0 )
{
if( ret != 0 )
mbedtls_printf( "failed (%u)\n", (unsigned int) i );
else
mbedtls_printf( "passed\n" );
}
return( ret );
}
/*
* Checkup routine
*/
int mbedtls_ecp_self_test( int verbose )
{
int ret = MBEDTLS_ERR_ERROR_CORRUPTION_DETECTED;
mbedtls_ecp_group grp;
mbedtls_ecp_point R, P;
mbedtls_mpi m;
#if defined(MBEDTLS_ECP_SHORT_WEIERSTRASS_ENABLED)
/* Exponents especially adapted for secp192k1, which has the lowest
* order n of all supported curves (secp192r1 is in a slightly larger
* field but the order of its base point is slightly smaller). */
const char *sw_exponents[] =
{
"000000000000000000000000000000000000000000000001", /* one */
"FFFFFFFFFFFFFFFFFFFFFFFE26F2FC170F69466A74DEFD8C", /* n - 1 */
"5EA6F389A38B8BC81E767753B15AA5569E1782E30ABE7D25", /* random */
"400000000000000000000000000000000000000000000000", /* one and zeros */
"7FFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFF", /* all ones */
"555555555555555555555555555555555555555555555555", /* 101010... */
};
#endif /* MBEDTLS_ECP_SHORT_WEIERSTRASS_ENABLED */
#if defined(MBEDTLS_ECP_MONTGOMERY_ENABLED)
const char *m_exponents[] =
{
/* Valid private values for Curve25519. In a build with Curve448
* but not Curve25519, they will be adjusted in
* self_test_adjust_exponent(). */
"4000000000000000000000000000000000000000000000000000000000000000",
"5C3C3C3C3C3C3C3C3C3C3C3C3C3C3C3C3C3C3C3C3C3C3C3C3C3C3C3C3C3C3C30",
"5715ECCE24583F7A7023C24164390586842E816D7280A49EF6DF4EAE6B280BF8",
"41A2B017516F6D254E1F002BCCBADD54BE30F8CEC737A0E912B4963B6BA74460",
"5555555555555555555555555555555555555555555555555555555555555550",
"7FFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFF8",
};
#endif /* MBEDTLS_ECP_MONTGOMERY_ENABLED */
mbedtls_ecp_group_init( &grp );
mbedtls_ecp_point_init( &R );
mbedtls_ecp_point_init( &P );
mbedtls_mpi_init( &m );
#if defined(MBEDTLS_ECP_SHORT_WEIERSTRASS_ENABLED)
/* Use secp192r1 if available, or any available curve */
#if defined(MBEDTLS_ECP_DP_SECP192R1_ENABLED)
MBEDTLS_MPI_CHK( mbedtls_ecp_group_load( &grp, MBEDTLS_ECP_DP_SECP192R1 ) );
#else
MBEDTLS_MPI_CHK( mbedtls_ecp_group_load( &grp, mbedtls_ecp_curve_list()->grp_id ) );
#endif
if( verbose != 0 )
mbedtls_printf( " ECP SW test #1 (constant op_count, base point G): " );
/* Do a dummy multiplication first to trigger precomputation */
MBEDTLS_MPI_CHK( mbedtls_mpi_lset( &m, 2 ) );
MBEDTLS_MPI_CHK( mbedtls_ecp_mul( &grp, &P, &m, &grp.G, NULL, NULL ) );
ret = self_test_point( verbose,
&grp, &R, &m, &grp.G,
sw_exponents,
sizeof( sw_exponents ) / sizeof( sw_exponents[0] ));
if( ret != 0 )
goto cleanup;
if( verbose != 0 )
mbedtls_printf( " ECP SW test #2 (constant op_count, other point): " );
/* We computed P = 2G last time, use it */
ret = self_test_point( verbose,
&grp, &R, &m, &P,
sw_exponents,
sizeof( sw_exponents ) / sizeof( sw_exponents[0] ));
if( ret != 0 )
goto cleanup;
mbedtls_ecp_group_free( &grp );
mbedtls_ecp_point_free( &R );
#endif /* MBEDTLS_ECP_SHORT_WEIERSTRASS_ENABLED */
#if defined(MBEDTLS_ECP_MONTGOMERY_ENABLED)
if( verbose != 0 )
mbedtls_printf( " ECP Montgomery test (constant op_count): " );
#if defined(MBEDTLS_ECP_DP_CURVE25519_ENABLED)
MBEDTLS_MPI_CHK( mbedtls_ecp_group_load( &grp, MBEDTLS_ECP_DP_CURVE25519 ) );
#elif defined(MBEDTLS_ECP_DP_CURVE448_ENABLED)
MBEDTLS_MPI_CHK( mbedtls_ecp_group_load( &grp, MBEDTLS_ECP_DP_CURVE448 ) );
#else
#error "MBEDTLS_ECP_MONTGOMERY_ENABLED is defined, but no curve is supported for self-test"
#endif
ret = self_test_point( verbose,
&grp, &R, &m, &grp.G,
m_exponents,
sizeof( m_exponents ) / sizeof( m_exponents[0] ));
if( ret != 0 )
goto cleanup;
#endif /* MBEDTLS_ECP_MONTGOMERY_ENABLED */
cleanup:
if( ret < 0 && verbose != 0 )
mbedtls_printf( "Unexpected error, return code = %08X\n", (unsigned int) ret );
mbedtls_ecp_group_free( &grp );
mbedtls_ecp_point_free( &R );
mbedtls_ecp_point_free( &P );
mbedtls_mpi_free( &m );
if( verbose != 0 )
mbedtls_printf( "\n" );
return( ret );
}
#endif /* MBEDTLS_SELF_TEST */
#endif /* !MBEDTLS_ECP_ALT */
#endif /* MBEDTLS_ECP_C */
|
0 | repos/gpt4all.zig/src/zig-libcurl/zig-mbedtls/mbedtls | repos/gpt4all.zig/src/zig-libcurl/zig-mbedtls/mbedtls/library/pkcs12.c | /*
* PKCS#12 Personal Information Exchange Syntax
*
* Copyright The Mbed TLS Contributors
* SPDX-License-Identifier: Apache-2.0
*
* 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.
*/
/*
* The PKCS #12 Personal Information Exchange Syntax Standard v1.1
*
* http://www.rsa.com/rsalabs/pkcs/files/h11301-wp-pkcs-12v1-1-personal-information-exchange-syntax.pdf
* ftp://ftp.rsasecurity.com/pub/pkcs/pkcs-12/pkcs-12v1-1.asn
*/
#include "common.h"
#if defined(MBEDTLS_PKCS12_C)
#include "mbedtls/pkcs12.h"
#include "mbedtls/asn1.h"
#include "mbedtls/cipher.h"
#include "mbedtls/platform_util.h"
#include "mbedtls/error.h"
#include <string.h>
#if defined(MBEDTLS_ARC4_C)
#include "mbedtls/arc4.h"
#endif
#if defined(MBEDTLS_DES_C)
#include "mbedtls/des.h"
#endif
#if defined(MBEDTLS_ASN1_PARSE_C)
static int pkcs12_parse_pbe_params( mbedtls_asn1_buf *params,
mbedtls_asn1_buf *salt, int *iterations )
{
int ret = MBEDTLS_ERR_ERROR_CORRUPTION_DETECTED;
unsigned char **p = ¶ms->p;
const unsigned char *end = params->p + params->len;
/*
* pkcs-12PbeParams ::= SEQUENCE {
* salt OCTET STRING,
* iterations INTEGER
* }
*
*/
if( params->tag != ( MBEDTLS_ASN1_CONSTRUCTED | MBEDTLS_ASN1_SEQUENCE ) )
return( MBEDTLS_ERROR_ADD( MBEDTLS_ERR_PKCS12_PBE_INVALID_FORMAT,
MBEDTLS_ERR_ASN1_UNEXPECTED_TAG ) );
if( ( ret = mbedtls_asn1_get_tag( p, end, &salt->len, MBEDTLS_ASN1_OCTET_STRING ) ) != 0 )
return( MBEDTLS_ERROR_ADD( MBEDTLS_ERR_PKCS12_PBE_INVALID_FORMAT, ret ) );
salt->p = *p;
*p += salt->len;
if( ( ret = mbedtls_asn1_get_int( p, end, iterations ) ) != 0 )
return( MBEDTLS_ERROR_ADD( MBEDTLS_ERR_PKCS12_PBE_INVALID_FORMAT, ret ) );
if( *p != end )
return( MBEDTLS_ERROR_ADD( MBEDTLS_ERR_PKCS12_PBE_INVALID_FORMAT,
MBEDTLS_ERR_ASN1_LENGTH_MISMATCH ) );
return( 0 );
}
#define PKCS12_MAX_PWDLEN 128
static int pkcs12_pbe_derive_key_iv( mbedtls_asn1_buf *pbe_params, mbedtls_md_type_t md_type,
const unsigned char *pwd, size_t pwdlen,
unsigned char *key, size_t keylen,
unsigned char *iv, size_t ivlen )
{
int ret, iterations = 0;
mbedtls_asn1_buf salt;
size_t i;
unsigned char unipwd[PKCS12_MAX_PWDLEN * 2 + 2];
if( pwdlen > PKCS12_MAX_PWDLEN )
return( MBEDTLS_ERR_PKCS12_BAD_INPUT_DATA );
memset( &salt, 0, sizeof(mbedtls_asn1_buf) );
memset( &unipwd, 0, sizeof(unipwd) );
if( ( ret = pkcs12_parse_pbe_params( pbe_params, &salt,
&iterations ) ) != 0 )
return( ret );
for( i = 0; i < pwdlen; i++ )
unipwd[i * 2 + 1] = pwd[i];
if( ( ret = mbedtls_pkcs12_derivation( key, keylen, unipwd, pwdlen * 2 + 2,
salt.p, salt.len, md_type,
MBEDTLS_PKCS12_DERIVE_KEY, iterations ) ) != 0 )
{
return( ret );
}
if( iv == NULL || ivlen == 0 )
return( 0 );
if( ( ret = mbedtls_pkcs12_derivation( iv, ivlen, unipwd, pwdlen * 2 + 2,
salt.p, salt.len, md_type,
MBEDTLS_PKCS12_DERIVE_IV, iterations ) ) != 0 )
{
return( ret );
}
return( 0 );
}
#undef PKCS12_MAX_PWDLEN
int mbedtls_pkcs12_pbe_sha1_rc4_128( mbedtls_asn1_buf *pbe_params, int mode,
const unsigned char *pwd, size_t pwdlen,
const unsigned char *data, size_t len,
unsigned char *output )
{
#if !defined(MBEDTLS_ARC4_C)
((void) pbe_params);
((void) mode);
((void) pwd);
((void) pwdlen);
((void) data);
((void) len);
((void) output);
return( MBEDTLS_ERR_PKCS12_FEATURE_UNAVAILABLE );
#else
int ret = MBEDTLS_ERR_ERROR_CORRUPTION_DETECTED;
unsigned char key[16];
mbedtls_arc4_context ctx;
((void) mode);
mbedtls_arc4_init( &ctx );
if( ( ret = pkcs12_pbe_derive_key_iv( pbe_params, MBEDTLS_MD_SHA1,
pwd, pwdlen,
key, 16, NULL, 0 ) ) != 0 )
{
return( ret );
}
mbedtls_arc4_setup( &ctx, key, 16 );
if( ( ret = mbedtls_arc4_crypt( &ctx, len, data, output ) ) != 0 )
goto exit;
exit:
mbedtls_platform_zeroize( key, sizeof( key ) );
mbedtls_arc4_free( &ctx );
return( ret );
#endif /* MBEDTLS_ARC4_C */
}
int mbedtls_pkcs12_pbe( mbedtls_asn1_buf *pbe_params, int mode,
mbedtls_cipher_type_t cipher_type, mbedtls_md_type_t md_type,
const unsigned char *pwd, size_t pwdlen,
const unsigned char *data, size_t len,
unsigned char *output )
{
int ret, keylen = 0;
unsigned char key[32];
unsigned char iv[16];
const mbedtls_cipher_info_t *cipher_info;
mbedtls_cipher_context_t cipher_ctx;
size_t olen = 0;
cipher_info = mbedtls_cipher_info_from_type( cipher_type );
if( cipher_info == NULL )
return( MBEDTLS_ERR_PKCS12_FEATURE_UNAVAILABLE );
keylen = cipher_info->key_bitlen / 8;
if( ( ret = pkcs12_pbe_derive_key_iv( pbe_params, md_type, pwd, pwdlen,
key, keylen,
iv, cipher_info->iv_size ) ) != 0 )
{
return( ret );
}
mbedtls_cipher_init( &cipher_ctx );
if( ( ret = mbedtls_cipher_setup( &cipher_ctx, cipher_info ) ) != 0 )
goto exit;
if( ( ret = mbedtls_cipher_setkey( &cipher_ctx, key, 8 * keylen, (mbedtls_operation_t) mode ) ) != 0 )
goto exit;
if( ( ret = mbedtls_cipher_set_iv( &cipher_ctx, iv, cipher_info->iv_size ) ) != 0 )
goto exit;
if( ( ret = mbedtls_cipher_reset( &cipher_ctx ) ) != 0 )
goto exit;
if( ( ret = mbedtls_cipher_update( &cipher_ctx, data, len,
output, &olen ) ) != 0 )
{
goto exit;
}
if( ( ret = mbedtls_cipher_finish( &cipher_ctx, output + olen, &olen ) ) != 0 )
ret = MBEDTLS_ERR_PKCS12_PASSWORD_MISMATCH;
exit:
mbedtls_platform_zeroize( key, sizeof( key ) );
mbedtls_platform_zeroize( iv, sizeof( iv ) );
mbedtls_cipher_free( &cipher_ctx );
return( ret );
}
#endif /* MBEDTLS_ASN1_PARSE_C */
static void pkcs12_fill_buffer( unsigned char *data, size_t data_len,
const unsigned char *filler, size_t fill_len )
{
unsigned char *p = data;
size_t use_len;
while( data_len > 0 )
{
use_len = ( data_len > fill_len ) ? fill_len : data_len;
memcpy( p, filler, use_len );
p += use_len;
data_len -= use_len;
}
}
int mbedtls_pkcs12_derivation( unsigned char *data, size_t datalen,
const unsigned char *pwd, size_t pwdlen,
const unsigned char *salt, size_t saltlen,
mbedtls_md_type_t md_type, int id, int iterations )
{
int ret = MBEDTLS_ERR_ERROR_CORRUPTION_DETECTED;
unsigned int j;
unsigned char diversifier[128];
unsigned char salt_block[128], pwd_block[128], hash_block[128];
unsigned char hash_output[MBEDTLS_MD_MAX_SIZE];
unsigned char *p;
unsigned char c;
size_t hlen, use_len, v, i;
const mbedtls_md_info_t *md_info;
mbedtls_md_context_t md_ctx;
// This version only allows max of 64 bytes of password or salt
if( datalen > 128 || pwdlen > 64 || saltlen > 64 )
return( MBEDTLS_ERR_PKCS12_BAD_INPUT_DATA );
md_info = mbedtls_md_info_from_type( md_type );
if( md_info == NULL )
return( MBEDTLS_ERR_PKCS12_FEATURE_UNAVAILABLE );
mbedtls_md_init( &md_ctx );
if( ( ret = mbedtls_md_setup( &md_ctx, md_info, 0 ) ) != 0 )
return( ret );
hlen = mbedtls_md_get_size( md_info );
if( hlen <= 32 )
v = 64;
else
v = 128;
memset( diversifier, (unsigned char) id, v );
pkcs12_fill_buffer( salt_block, v, salt, saltlen );
pkcs12_fill_buffer( pwd_block, v, pwd, pwdlen );
p = data;
while( datalen > 0 )
{
// Calculate hash( diversifier || salt_block || pwd_block )
if( ( ret = mbedtls_md_starts( &md_ctx ) ) != 0 )
goto exit;
if( ( ret = mbedtls_md_update( &md_ctx, diversifier, v ) ) != 0 )
goto exit;
if( ( ret = mbedtls_md_update( &md_ctx, salt_block, v ) ) != 0 )
goto exit;
if( ( ret = mbedtls_md_update( &md_ctx, pwd_block, v ) ) != 0 )
goto exit;
if( ( ret = mbedtls_md_finish( &md_ctx, hash_output ) ) != 0 )
goto exit;
// Perform remaining ( iterations - 1 ) recursive hash calculations
for( i = 1; i < (size_t) iterations; i++ )
{
if( ( ret = mbedtls_md( md_info, hash_output, hlen, hash_output ) ) != 0 )
goto exit;
}
use_len = ( datalen > hlen ) ? hlen : datalen;
memcpy( p, hash_output, use_len );
datalen -= use_len;
p += use_len;
if( datalen == 0 )
break;
// Concatenating copies of hash_output into hash_block (B)
pkcs12_fill_buffer( hash_block, v, hash_output, hlen );
// B += 1
for( i = v; i > 0; i-- )
if( ++hash_block[i - 1] != 0 )
break;
// salt_block += B
c = 0;
for( i = v; i > 0; i-- )
{
j = salt_block[i - 1] + hash_block[i - 1] + c;
c = (unsigned char) (j >> 8);
salt_block[i - 1] = j & 0xFF;
}
// pwd_block += B
c = 0;
for( i = v; i > 0; i-- )
{
j = pwd_block[i - 1] + hash_block[i - 1] + c;
c = (unsigned char) (j >> 8);
pwd_block[i - 1] = j & 0xFF;
}
}
ret = 0;
exit:
mbedtls_platform_zeroize( salt_block, sizeof( salt_block ) );
mbedtls_platform_zeroize( pwd_block, sizeof( pwd_block ) );
mbedtls_platform_zeroize( hash_block, sizeof( hash_block ) );
mbedtls_platform_zeroize( hash_output, sizeof( hash_output ) );
mbedtls_md_free( &md_ctx );
return( ret );
}
#endif /* MBEDTLS_PKCS12_C */
|
0 | repos/gpt4all.zig/src/zig-libcurl/zig-mbedtls/mbedtls | repos/gpt4all.zig/src/zig-libcurl/zig-mbedtls/mbedtls/library/timing.c | /*
* Portable interface to the CPU cycle counter
*
* Copyright The Mbed TLS Contributors
* SPDX-License-Identifier: Apache-2.0
*
* 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.
*/
#include "common.h"
#if defined(MBEDTLS_SELF_TEST) && defined(MBEDTLS_PLATFORM_C)
#include "mbedtls/platform.h"
#else
#include <stdio.h>
#define mbedtls_printf printf
#endif
#if defined(MBEDTLS_TIMING_C)
#include "mbedtls/timing.h"
#if !defined(MBEDTLS_TIMING_ALT)
#if !defined(unix) && !defined(__unix__) && !defined(__unix) && \
!defined(__APPLE__) && !defined(_WIN32) && !defined(__QNXNTO__) && \
!defined(__HAIKU__) && !defined(__midipix__)
#error "This module only works on Unix and Windows, see MBEDTLS_TIMING_C in config.h"
#endif
#ifndef asm
#define asm __asm
#endif
#if defined(_WIN32) && !defined(EFIX64) && !defined(EFI32)
#include <windows.h>
#include <process.h>
struct _hr_time
{
LARGE_INTEGER start;
};
#else
#include <unistd.h>
#include <sys/types.h>
#include <sys/time.h>
#include <signal.h>
#include <time.h>
struct _hr_time
{
struct timeval start;
};
#endif /* _WIN32 && !EFIX64 && !EFI32 */
#if !defined(HAVE_HARDCLOCK) && defined(MBEDTLS_HAVE_ASM) && \
( defined(_MSC_VER) && defined(_M_IX86) ) || defined(__WATCOMC__)
#define HAVE_HARDCLOCK
unsigned long mbedtls_timing_hardclock( void )
{
unsigned long tsc;
__asm rdtsc
__asm mov [tsc], eax
return( tsc );
}
#endif /* !HAVE_HARDCLOCK && MBEDTLS_HAVE_ASM &&
( _MSC_VER && _M_IX86 ) || __WATCOMC__ */
/* some versions of mingw-64 have 32-bit longs even on x84_64 */
#if !defined(HAVE_HARDCLOCK) && defined(MBEDTLS_HAVE_ASM) && \
defined(__GNUC__) && ( defined(__i386__) || ( \
( defined(__amd64__) || defined( __x86_64__) ) && __SIZEOF_LONG__ == 4 ) )
#define HAVE_HARDCLOCK
unsigned long mbedtls_timing_hardclock( void )
{
unsigned long lo, hi;
asm volatile( "rdtsc" : "=a" (lo), "=d" (hi) );
return( lo );
}
#endif /* !HAVE_HARDCLOCK && MBEDTLS_HAVE_ASM &&
__GNUC__ && __i386__ */
#if !defined(HAVE_HARDCLOCK) && defined(MBEDTLS_HAVE_ASM) && \
defined(__GNUC__) && ( defined(__amd64__) || defined(__x86_64__) )
#define HAVE_HARDCLOCK
unsigned long mbedtls_timing_hardclock( void )
{
unsigned long lo, hi;
asm volatile( "rdtsc" : "=a" (lo), "=d" (hi) );
return( lo | ( hi << 32 ) );
}
#endif /* !HAVE_HARDCLOCK && MBEDTLS_HAVE_ASM &&
__GNUC__ && ( __amd64__ || __x86_64__ ) */
#if !defined(HAVE_HARDCLOCK) && defined(MBEDTLS_HAVE_ASM) && \
defined(__GNUC__) && ( defined(__powerpc__) || defined(__ppc__) )
#define HAVE_HARDCLOCK
unsigned long mbedtls_timing_hardclock( void )
{
unsigned long tbl, tbu0, tbu1;
do
{
asm volatile( "mftbu %0" : "=r" (tbu0) );
asm volatile( "mftb %0" : "=r" (tbl ) );
asm volatile( "mftbu %0" : "=r" (tbu1) );
}
while( tbu0 != tbu1 );
return( tbl );
}
#endif /* !HAVE_HARDCLOCK && MBEDTLS_HAVE_ASM &&
__GNUC__ && ( __powerpc__ || __ppc__ ) */
#if !defined(HAVE_HARDCLOCK) && defined(MBEDTLS_HAVE_ASM) && \
defined(__GNUC__) && defined(__sparc64__)
#if defined(__OpenBSD__)
#warning OpenBSD does not allow access to tick register using software version instead
#else
#define HAVE_HARDCLOCK
unsigned long mbedtls_timing_hardclock( void )
{
unsigned long tick;
asm volatile( "rdpr %%tick, %0;" : "=&r" (tick) );
return( tick );
}
#endif /* __OpenBSD__ */
#endif /* !HAVE_HARDCLOCK && MBEDTLS_HAVE_ASM &&
__GNUC__ && __sparc64__ */
#if !defined(HAVE_HARDCLOCK) && defined(MBEDTLS_HAVE_ASM) && \
defined(__GNUC__) && defined(__sparc__) && !defined(__sparc64__)
#define HAVE_HARDCLOCK
unsigned long mbedtls_timing_hardclock( void )
{
unsigned long tick;
asm volatile( ".byte 0x83, 0x41, 0x00, 0x00" );
asm volatile( "mov %%g1, %0" : "=r" (tick) );
return( tick );
}
#endif /* !HAVE_HARDCLOCK && MBEDTLS_HAVE_ASM &&
__GNUC__ && __sparc__ && !__sparc64__ */
#if !defined(HAVE_HARDCLOCK) && defined(MBEDTLS_HAVE_ASM) && \
defined(__GNUC__) && defined(__alpha__)
#define HAVE_HARDCLOCK
unsigned long mbedtls_timing_hardclock( void )
{
unsigned long cc;
asm volatile( "rpcc %0" : "=r" (cc) );
return( cc & 0xFFFFFFFF );
}
#endif /* !HAVE_HARDCLOCK && MBEDTLS_HAVE_ASM &&
__GNUC__ && __alpha__ */
#if !defined(HAVE_HARDCLOCK) && defined(MBEDTLS_HAVE_ASM) && \
defined(__GNUC__) && defined(__ia64__)
#define HAVE_HARDCLOCK
unsigned long mbedtls_timing_hardclock( void )
{
unsigned long itc;
asm volatile( "mov %0 = ar.itc" : "=r" (itc) );
return( itc );
}
#endif /* !HAVE_HARDCLOCK && MBEDTLS_HAVE_ASM &&
__GNUC__ && __ia64__ */
#if !defined(HAVE_HARDCLOCK) && defined(_MSC_VER) && \
!defined(EFIX64) && !defined(EFI32)
#define HAVE_HARDCLOCK
unsigned long mbedtls_timing_hardclock( void )
{
LARGE_INTEGER offset;
QueryPerformanceCounter( &offset );
return( (unsigned long)( offset.QuadPart ) );
}
#endif /* !HAVE_HARDCLOCK && _MSC_VER && !EFIX64 && !EFI32 */
#if !defined(HAVE_HARDCLOCK)
#define HAVE_HARDCLOCK
static int hardclock_init = 0;
static struct timeval tv_init;
unsigned long mbedtls_timing_hardclock( void )
{
struct timeval tv_cur;
if( hardclock_init == 0 )
{
gettimeofday( &tv_init, NULL );
hardclock_init = 1;
}
gettimeofday( &tv_cur, NULL );
return( ( tv_cur.tv_sec - tv_init.tv_sec ) * 1000000
+ ( tv_cur.tv_usec - tv_init.tv_usec ) );
}
#endif /* !HAVE_HARDCLOCK */
volatile int mbedtls_timing_alarmed = 0;
#if defined(_WIN32) && !defined(EFIX64) && !defined(EFI32)
unsigned long mbedtls_timing_get_timer( struct mbedtls_timing_hr_time *val, int reset )
{
struct _hr_time *t = (struct _hr_time *) val;
if( reset )
{
QueryPerformanceCounter( &t->start );
return( 0 );
}
else
{
unsigned long delta;
LARGE_INTEGER now, hfreq;
QueryPerformanceCounter( &now );
QueryPerformanceFrequency( &hfreq );
delta = (unsigned long)( ( now.QuadPart - t->start.QuadPart ) * 1000ul
/ hfreq.QuadPart );
return( delta );
}
}
/* It's OK to use a global because alarm() is supposed to be global anyway */
static DWORD alarmMs;
static void TimerProc( void *TimerContext )
{
(void) TimerContext;
Sleep( alarmMs );
mbedtls_timing_alarmed = 1;
/* _endthread will be called implicitly on return
* That ensures execution of thread funcition's epilogue */
}
void mbedtls_set_alarm( int seconds )
{
if( seconds == 0 )
{
/* No need to create a thread for this simple case.
* Also, this shorcut is more reliable at least on MinGW32 */
mbedtls_timing_alarmed = 1;
return;
}
mbedtls_timing_alarmed = 0;
alarmMs = seconds * 1000;
(void) _beginthread( TimerProc, 0, NULL );
}
#else /* _WIN32 && !EFIX64 && !EFI32 */
unsigned long mbedtls_timing_get_timer( struct mbedtls_timing_hr_time *val, int reset )
{
struct _hr_time *t = (struct _hr_time *) val;
if( reset )
{
gettimeofday( &t->start, NULL );
return( 0 );
}
else
{
unsigned long delta;
struct timeval now;
gettimeofday( &now, NULL );
delta = ( now.tv_sec - t->start.tv_sec ) * 1000ul
+ ( now.tv_usec - t->start.tv_usec ) / 1000;
return( delta );
}
}
static void sighandler( int signum )
{
mbedtls_timing_alarmed = 1;
signal( signum, sighandler );
}
void mbedtls_set_alarm( int seconds )
{
mbedtls_timing_alarmed = 0;
signal( SIGALRM, sighandler );
alarm( seconds );
if( seconds == 0 )
{
/* alarm(0) cancelled any previous pending alarm, but the
handler won't fire, so raise the flag straight away. */
mbedtls_timing_alarmed = 1;
}
}
#endif /* _WIN32 && !EFIX64 && !EFI32 */
/*
* Set delays to watch
*/
void mbedtls_timing_set_delay( void *data, uint32_t int_ms, uint32_t fin_ms )
{
mbedtls_timing_delay_context *ctx = (mbedtls_timing_delay_context *) data;
ctx->int_ms = int_ms;
ctx->fin_ms = fin_ms;
if( fin_ms != 0 )
(void) mbedtls_timing_get_timer( &ctx->timer, 1 );
}
/*
* Get number of delays expired
*/
int mbedtls_timing_get_delay( void *data )
{
mbedtls_timing_delay_context *ctx = (mbedtls_timing_delay_context *) data;
unsigned long elapsed_ms;
if( ctx->fin_ms == 0 )
return( -1 );
elapsed_ms = mbedtls_timing_get_timer( &ctx->timer, 0 );
if( elapsed_ms >= ctx->fin_ms )
return( 2 );
if( elapsed_ms >= ctx->int_ms )
return( 1 );
return( 0 );
}
#endif /* !MBEDTLS_TIMING_ALT */
#if defined(MBEDTLS_SELF_TEST)
/*
* Busy-waits for the given number of milliseconds.
* Used for testing mbedtls_timing_hardclock.
*/
static void busy_msleep( unsigned long msec )
{
struct mbedtls_timing_hr_time hires;
unsigned long i = 0; /* for busy-waiting */
volatile unsigned long j; /* to prevent optimisation */
(void) mbedtls_timing_get_timer( &hires, 1 );
while( mbedtls_timing_get_timer( &hires, 0 ) < msec )
i++;
j = i;
(void) j;
}
#define FAIL do \
{ \
if( verbose != 0 ) \
{ \
mbedtls_printf( "failed at line %d\n", __LINE__ ); \
mbedtls_printf( " cycles=%lu ratio=%lu millisecs=%lu secs=%lu hardfail=%d a=%lu b=%lu\n", \
cycles, ratio, millisecs, secs, hardfail, \
(unsigned long) a, (unsigned long) b ); \
mbedtls_printf( " elapsed(hires)=%lu elapsed(ctx)=%lu status(ctx)=%d\n", \
mbedtls_timing_get_timer( &hires, 0 ), \
mbedtls_timing_get_timer( &ctx.timer, 0 ), \
mbedtls_timing_get_delay( &ctx ) ); \
} \
return( 1 ); \
} while( 0 )
/*
* Checkup routine
*
* Warning: this is work in progress, some tests may not be reliable enough
* yet! False positives may happen.
*/
int mbedtls_timing_self_test( int verbose )
{
unsigned long cycles = 0, ratio = 0;
unsigned long millisecs = 0, secs = 0;
int hardfail = 0;
struct mbedtls_timing_hr_time hires;
uint32_t a = 0, b = 0;
mbedtls_timing_delay_context ctx;
if( verbose != 0 )
mbedtls_printf( " TIMING tests note: will take some time!\n" );
if( verbose != 0 )
mbedtls_printf( " TIMING test #1 (set_alarm / get_timer): " );
{
secs = 1;
(void) mbedtls_timing_get_timer( &hires, 1 );
mbedtls_set_alarm( (int) secs );
while( !mbedtls_timing_alarmed )
;
millisecs = mbedtls_timing_get_timer( &hires, 0 );
/* For some reason on Windows it looks like alarm has an extra delay
* (maybe related to creating a new thread). Allow some room here. */
if( millisecs < 800 * secs || millisecs > 1200 * secs + 300 )
FAIL;
}
if( verbose != 0 )
mbedtls_printf( "passed\n" );
if( verbose != 0 )
mbedtls_printf( " TIMING test #2 (set/get_delay ): " );
{
a = 800;
b = 400;
mbedtls_timing_set_delay( &ctx, a, a + b ); /* T = 0 */
busy_msleep( a - a / 4 ); /* T = a - a/4 */
if( mbedtls_timing_get_delay( &ctx ) != 0 )
FAIL;
busy_msleep( a / 4 + b / 4 ); /* T = a + b/4 */
if( mbedtls_timing_get_delay( &ctx ) != 1 )
FAIL;
busy_msleep( b ); /* T = a + b + b/4 */
if( mbedtls_timing_get_delay( &ctx ) != 2 )
FAIL;
}
mbedtls_timing_set_delay( &ctx, 0, 0 );
busy_msleep( 200 );
if( mbedtls_timing_get_delay( &ctx ) != -1 )
FAIL;
if( verbose != 0 )
mbedtls_printf( "passed\n" );
if( verbose != 0 )
mbedtls_printf( " TIMING test #3 (hardclock / get_timer): " );
/*
* Allow one failure for possible counter wrapping.
* On a 4Ghz 32-bit machine the cycle counter wraps about once per second;
* since the whole test is about 10ms, it shouldn't happen twice in a row.
*/
hard_test:
if( hardfail > 1 )
{
if( verbose != 0 )
mbedtls_printf( "failed (ignored)\n" );
goto hard_test_done;
}
/* Get a reference ratio cycles/ms */
millisecs = 1;
cycles = mbedtls_timing_hardclock();
busy_msleep( millisecs );
cycles = mbedtls_timing_hardclock() - cycles;
ratio = cycles / millisecs;
/* Check that the ratio is mostly constant */
for( millisecs = 2; millisecs <= 4; millisecs++ )
{
cycles = mbedtls_timing_hardclock();
busy_msleep( millisecs );
cycles = mbedtls_timing_hardclock() - cycles;
/* Allow variation up to 20% */
if( cycles / millisecs < ratio - ratio / 5 ||
cycles / millisecs > ratio + ratio / 5 )
{
hardfail++;
goto hard_test;
}
}
if( verbose != 0 )
mbedtls_printf( "passed\n" );
hard_test_done:
if( verbose != 0 )
mbedtls_printf( "\n" );
return( 0 );
}
#endif /* MBEDTLS_SELF_TEST */
#endif /* MBEDTLS_TIMING_C */
|
0 | repos/gpt4all.zig/src/zig-libcurl/zig-mbedtls/mbedtls | repos/gpt4all.zig/src/zig-libcurl/zig-mbedtls/mbedtls/library/psa_crypto_aead.h | /*
* PSA AEAD driver entry points
*/
/*
* Copyright The Mbed TLS Contributors
* SPDX-License-Identifier: Apache-2.0
*
* 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.
*/
#ifndef PSA_CRYPTO_AEAD_H
#define PSA_CRYPTO_AEAD_H
#include <psa/crypto.h>
/**
* \brief Process an authenticated encryption operation.
*
* \note The signature of this function is that of a PSA driver
* aead_encrypt entry point. This function behaves as an aead_encrypt
* entry point as defined in the PSA driver interface specification for
* transparent drivers.
*
* \param[in] attributes The attributes of the key to use for the
* operation.
* \param[in] key_buffer The buffer containing the key context.
* \param key_buffer_size Size of the \p key_buffer buffer in bytes.
* \param alg The AEAD algorithm to compute.
* \param[in] nonce Nonce or IV to use.
* \param nonce_length Size of the nonce buffer in bytes. This must
* be appropriate for the selected algorithm.
* The default nonce size is
* PSA_AEAD_NONCE_LENGTH(key_type, alg) where
* key_type is the type of key.
* \param[in] additional_data Additional data that will be authenticated
* but not encrypted.
* \param additional_data_length Size of additional_data in bytes.
* \param[in] plaintext Data that will be authenticated and encrypted.
* \param plaintext_length Size of plaintext in bytes.
* \param[out] ciphertext Output buffer for the authenticated and
* encrypted data. The additional data is not
* part of this output. For algorithms where the
* encrypted data and the authentication tag are
* defined as separate outputs, the
* authentication tag is appended to the
* encrypted data.
* \param ciphertext_size Size of the ciphertext buffer in bytes. This
* must be appropriate for the selected algorithm
* and key:
* - A sufficient output size is
* PSA_AEAD_ENCRYPT_OUTPUT_SIZE(key_type, alg,
* plaintext_length) where key_type is the type
* of key.
* - PSA_AEAD_ENCRYPT_OUTPUT_MAX_SIZE(
* plaintext_length) evaluates to the maximum
* ciphertext size of any supported AEAD
* encryption.
* \param[out] ciphertext_length On success, the size of the output in the
* ciphertext buffer.
*
* \retval #PSA_SUCCESS Success.
* \retval #PSA_ERROR_NOT_SUPPORTED
* \p alg is not supported.
* \retval #PSA_ERROR_INSUFFICIENT_MEMORY
* \retval #PSA_ERROR_BUFFER_TOO_SMALL
* ciphertext_size is too small.
* \retval #PSA_ERROR_CORRUPTION_DETECTED
*/
psa_status_t mbedtls_psa_aead_encrypt(
const psa_key_attributes_t *attributes,
const uint8_t *key_buffer, size_t key_buffer_size,
psa_algorithm_t alg,
const uint8_t *nonce, size_t nonce_length,
const uint8_t *additional_data, size_t additional_data_length,
const uint8_t *plaintext, size_t plaintext_length,
uint8_t *ciphertext, size_t ciphertext_size, size_t *ciphertext_length );
/**
* \brief Process an authenticated decryption operation.
*
* \note The signature of this function is that of a PSA driver
* aead_decrypt entry point. This function behaves as an aead_decrypt
* entry point as defined in the PSA driver interface specification for
* transparent drivers.
*
* \param[in] attributes The attributes of the key to use for the
* operation.
* \param[in] key_buffer The buffer containing the key context.
* \param key_buffer_size Size of the \p key_buffer buffer in bytes.
* \param alg The AEAD algorithm to compute.
* \param[in] nonce Nonce or IV to use.
* \param nonce_length Size of the nonce buffer in bytes. This must
* be appropriate for the selected algorithm.
* The default nonce size is
* PSA_AEAD_NONCE_LENGTH(key_type, alg) where
* key_type is the type of key.
* \param[in] additional_data Additional data that has been authenticated
* but not encrypted.
* \param additional_data_length Size of additional_data in bytes.
* \param[in] ciphertext Data that has been authenticated and
* encrypted. For algorithms where the encrypted
* data and the authentication tag are defined
* as separate inputs, the buffer contains
* encrypted data followed by the authentication
* tag.
* \param ciphertext_length Size of ciphertext in bytes.
* \param[out] plaintext Output buffer for the decrypted data.
* \param plaintext_size Size of the plaintext buffer in bytes. This
* must be appropriate for the selected algorithm
* and key:
* - A sufficient output size is
* PSA_AEAD_DECRYPT_OUTPUT_SIZE(key_type, alg,
* ciphertext_length) where key_type is the
* type of key.
* - PSA_AEAD_DECRYPT_OUTPUT_MAX_SIZE(
* ciphertext_length) evaluates to the maximum
* plaintext size of any supported AEAD
* decryption.
* \param[out] plaintext_length On success, the size of the output in the
* plaintext buffer.
*
* \retval #PSA_SUCCESS Success.
* \retval #PSA_ERROR_INVALID_SIGNATURE
* The cipher is not authentic.
* \retval #PSA_ERROR_NOT_SUPPORTED
* \p alg is not supported.
* \retval #PSA_ERROR_INSUFFICIENT_MEMORY
* \retval #PSA_ERROR_BUFFER_TOO_SMALL
* plaintext_size is too small.
* \retval #PSA_ERROR_CORRUPTION_DETECTED
*/
psa_status_t mbedtls_psa_aead_decrypt(
const psa_key_attributes_t *attributes,
const uint8_t *key_buffer, size_t key_buffer_size,
psa_algorithm_t alg,
const uint8_t *nonce, size_t nonce_length,
const uint8_t *additional_data, size_t additional_data_length,
const uint8_t *ciphertext, size_t ciphertext_length,
uint8_t *plaintext, size_t plaintext_size, size_t *plaintext_length );
#endif /* PSA_CRYPTO_AEAD */
|
0 | repos/gpt4all.zig/src/zig-libcurl/zig-mbedtls/mbedtls | repos/gpt4all.zig/src/zig-libcurl/zig-mbedtls/mbedtls/library/cipher_wrap.c | /**
* \file cipher_wrap.c
*
* \brief Generic cipher wrapper for mbed TLS
*
* \author Adriaan de Jong <[email protected]>
*
* Copyright The Mbed TLS Contributors
* SPDX-License-Identifier: Apache-2.0
*
* 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.
*/
#include "common.h"
#if defined(MBEDTLS_CIPHER_C)
#include "mbedtls/cipher_internal.h"
#include "mbedtls/error.h"
#if defined(MBEDTLS_CHACHAPOLY_C)
#include "mbedtls/chachapoly.h"
#endif
#if defined(MBEDTLS_AES_C)
#include "mbedtls/aes.h"
#endif
#if defined(MBEDTLS_ARC4_C)
#include "mbedtls/arc4.h"
#endif
#if defined(MBEDTLS_CAMELLIA_C)
#include "mbedtls/camellia.h"
#endif
#if defined(MBEDTLS_ARIA_C)
#include "mbedtls/aria.h"
#endif
#if defined(MBEDTLS_DES_C)
#include "mbedtls/des.h"
#endif
#if defined(MBEDTLS_BLOWFISH_C)
#include "mbedtls/blowfish.h"
#endif
#if defined(MBEDTLS_CHACHA20_C)
#include "mbedtls/chacha20.h"
#endif
#if defined(MBEDTLS_GCM_C)
#include "mbedtls/gcm.h"
#endif
#if defined(MBEDTLS_CCM_C)
#include "mbedtls/ccm.h"
#endif
#if defined(MBEDTLS_NIST_KW_C)
#include "mbedtls/nist_kw.h"
#endif
#if defined(MBEDTLS_CIPHER_NULL_CIPHER)
#include <string.h>
#endif
#if defined(MBEDTLS_PLATFORM_C)
#include "mbedtls/platform.h"
#else
#include <stdlib.h>
#define mbedtls_calloc calloc
#define mbedtls_free free
#endif
#if defined(MBEDTLS_GCM_C)
/* shared by all GCM ciphers */
static void *gcm_ctx_alloc( void )
{
void *ctx = mbedtls_calloc( 1, sizeof( mbedtls_gcm_context ) );
if( ctx != NULL )
mbedtls_gcm_init( (mbedtls_gcm_context *) ctx );
return( ctx );
}
static void gcm_ctx_free( void *ctx )
{
mbedtls_gcm_free( ctx );
mbedtls_free( ctx );
}
#endif /* MBEDTLS_GCM_C */
#if defined(MBEDTLS_CCM_C)
/* shared by all CCM ciphers */
static void *ccm_ctx_alloc( void )
{
void *ctx = mbedtls_calloc( 1, sizeof( mbedtls_ccm_context ) );
if( ctx != NULL )
mbedtls_ccm_init( (mbedtls_ccm_context *) ctx );
return( ctx );
}
static void ccm_ctx_free( void *ctx )
{
mbedtls_ccm_free( ctx );
mbedtls_free( ctx );
}
#endif /* MBEDTLS_CCM_C */
#if defined(MBEDTLS_AES_C)
static int aes_crypt_ecb_wrap( void *ctx, mbedtls_operation_t operation,
const unsigned char *input, unsigned char *output )
{
return mbedtls_aes_crypt_ecb( (mbedtls_aes_context *) ctx, operation, input, output );
}
#if defined(MBEDTLS_CIPHER_MODE_CBC)
static int aes_crypt_cbc_wrap( void *ctx, mbedtls_operation_t operation, size_t length,
unsigned char *iv, const unsigned char *input, unsigned char *output )
{
return mbedtls_aes_crypt_cbc( (mbedtls_aes_context *) ctx, operation, length, iv, input,
output );
}
#endif /* MBEDTLS_CIPHER_MODE_CBC */
#if defined(MBEDTLS_CIPHER_MODE_CFB)
static int aes_crypt_cfb128_wrap( void *ctx, mbedtls_operation_t operation,
size_t length, size_t *iv_off, unsigned char *iv,
const unsigned char *input, unsigned char *output )
{
return mbedtls_aes_crypt_cfb128( (mbedtls_aes_context *) ctx, operation, length, iv_off, iv,
input, output );
}
#endif /* MBEDTLS_CIPHER_MODE_CFB */
#if defined(MBEDTLS_CIPHER_MODE_OFB)
static int aes_crypt_ofb_wrap( void *ctx, size_t length, size_t *iv_off,
unsigned char *iv, const unsigned char *input, unsigned char *output )
{
return mbedtls_aes_crypt_ofb( (mbedtls_aes_context *) ctx, length, iv_off,
iv, input, output );
}
#endif /* MBEDTLS_CIPHER_MODE_OFB */
#if defined(MBEDTLS_CIPHER_MODE_CTR)
static int aes_crypt_ctr_wrap( void *ctx, size_t length, size_t *nc_off,
unsigned char *nonce_counter, unsigned char *stream_block,
const unsigned char *input, unsigned char *output )
{
return mbedtls_aes_crypt_ctr( (mbedtls_aes_context *) ctx, length, nc_off, nonce_counter,
stream_block, input, output );
}
#endif /* MBEDTLS_CIPHER_MODE_CTR */
#if defined(MBEDTLS_CIPHER_MODE_XTS)
static int aes_crypt_xts_wrap( void *ctx, mbedtls_operation_t operation,
size_t length,
const unsigned char data_unit[16],
const unsigned char *input,
unsigned char *output )
{
mbedtls_aes_xts_context *xts_ctx = ctx;
int mode;
switch( operation )
{
case MBEDTLS_ENCRYPT:
mode = MBEDTLS_AES_ENCRYPT;
break;
case MBEDTLS_DECRYPT:
mode = MBEDTLS_AES_DECRYPT;
break;
default:
return MBEDTLS_ERR_CIPHER_BAD_INPUT_DATA;
}
return mbedtls_aes_crypt_xts( xts_ctx, mode, length,
data_unit, input, output );
}
#endif /* MBEDTLS_CIPHER_MODE_XTS */
static int aes_setkey_dec_wrap( void *ctx, const unsigned char *key,
unsigned int key_bitlen )
{
return mbedtls_aes_setkey_dec( (mbedtls_aes_context *) ctx, key, key_bitlen );
}
static int aes_setkey_enc_wrap( void *ctx, const unsigned char *key,
unsigned int key_bitlen )
{
return mbedtls_aes_setkey_enc( (mbedtls_aes_context *) ctx, key, key_bitlen );
}
static void * aes_ctx_alloc( void )
{
mbedtls_aes_context *aes = mbedtls_calloc( 1, sizeof( mbedtls_aes_context ) );
if( aes == NULL )
return( NULL );
mbedtls_aes_init( aes );
return( aes );
}
static void aes_ctx_free( void *ctx )
{
mbedtls_aes_free( (mbedtls_aes_context *) ctx );
mbedtls_free( ctx );
}
static const mbedtls_cipher_base_t aes_info = {
MBEDTLS_CIPHER_ID_AES,
aes_crypt_ecb_wrap,
#if defined(MBEDTLS_CIPHER_MODE_CBC)
aes_crypt_cbc_wrap,
#endif
#if defined(MBEDTLS_CIPHER_MODE_CFB)
aes_crypt_cfb128_wrap,
#endif
#if defined(MBEDTLS_CIPHER_MODE_OFB)
aes_crypt_ofb_wrap,
#endif
#if defined(MBEDTLS_CIPHER_MODE_CTR)
aes_crypt_ctr_wrap,
#endif
#if defined(MBEDTLS_CIPHER_MODE_XTS)
NULL,
#endif
#if defined(MBEDTLS_CIPHER_MODE_STREAM)
NULL,
#endif
aes_setkey_enc_wrap,
aes_setkey_dec_wrap,
aes_ctx_alloc,
aes_ctx_free
};
static const mbedtls_cipher_info_t aes_128_ecb_info = {
MBEDTLS_CIPHER_AES_128_ECB,
MBEDTLS_MODE_ECB,
128,
"AES-128-ECB",
0,
0,
16,
&aes_info
};
static const mbedtls_cipher_info_t aes_192_ecb_info = {
MBEDTLS_CIPHER_AES_192_ECB,
MBEDTLS_MODE_ECB,
192,
"AES-192-ECB",
0,
0,
16,
&aes_info
};
static const mbedtls_cipher_info_t aes_256_ecb_info = {
MBEDTLS_CIPHER_AES_256_ECB,
MBEDTLS_MODE_ECB,
256,
"AES-256-ECB",
0,
0,
16,
&aes_info
};
#if defined(MBEDTLS_CIPHER_MODE_CBC)
static const mbedtls_cipher_info_t aes_128_cbc_info = {
MBEDTLS_CIPHER_AES_128_CBC,
MBEDTLS_MODE_CBC,
128,
"AES-128-CBC",
16,
0,
16,
&aes_info
};
static const mbedtls_cipher_info_t aes_192_cbc_info = {
MBEDTLS_CIPHER_AES_192_CBC,
MBEDTLS_MODE_CBC,
192,
"AES-192-CBC",
16,
0,
16,
&aes_info
};
static const mbedtls_cipher_info_t aes_256_cbc_info = {
MBEDTLS_CIPHER_AES_256_CBC,
MBEDTLS_MODE_CBC,
256,
"AES-256-CBC",
16,
0,
16,
&aes_info
};
#endif /* MBEDTLS_CIPHER_MODE_CBC */
#if defined(MBEDTLS_CIPHER_MODE_CFB)
static const mbedtls_cipher_info_t aes_128_cfb128_info = {
MBEDTLS_CIPHER_AES_128_CFB128,
MBEDTLS_MODE_CFB,
128,
"AES-128-CFB128",
16,
0,
16,
&aes_info
};
static const mbedtls_cipher_info_t aes_192_cfb128_info = {
MBEDTLS_CIPHER_AES_192_CFB128,
MBEDTLS_MODE_CFB,
192,
"AES-192-CFB128",
16,
0,
16,
&aes_info
};
static const mbedtls_cipher_info_t aes_256_cfb128_info = {
MBEDTLS_CIPHER_AES_256_CFB128,
MBEDTLS_MODE_CFB,
256,
"AES-256-CFB128",
16,
0,
16,
&aes_info
};
#endif /* MBEDTLS_CIPHER_MODE_CFB */
#if defined(MBEDTLS_CIPHER_MODE_OFB)
static const mbedtls_cipher_info_t aes_128_ofb_info = {
MBEDTLS_CIPHER_AES_128_OFB,
MBEDTLS_MODE_OFB,
128,
"AES-128-OFB",
16,
0,
16,
&aes_info
};
static const mbedtls_cipher_info_t aes_192_ofb_info = {
MBEDTLS_CIPHER_AES_192_OFB,
MBEDTLS_MODE_OFB,
192,
"AES-192-OFB",
16,
0,
16,
&aes_info
};
static const mbedtls_cipher_info_t aes_256_ofb_info = {
MBEDTLS_CIPHER_AES_256_OFB,
MBEDTLS_MODE_OFB,
256,
"AES-256-OFB",
16,
0,
16,
&aes_info
};
#endif /* MBEDTLS_CIPHER_MODE_OFB */
#if defined(MBEDTLS_CIPHER_MODE_CTR)
static const mbedtls_cipher_info_t aes_128_ctr_info = {
MBEDTLS_CIPHER_AES_128_CTR,
MBEDTLS_MODE_CTR,
128,
"AES-128-CTR",
16,
0,
16,
&aes_info
};
static const mbedtls_cipher_info_t aes_192_ctr_info = {
MBEDTLS_CIPHER_AES_192_CTR,
MBEDTLS_MODE_CTR,
192,
"AES-192-CTR",
16,
0,
16,
&aes_info
};
static const mbedtls_cipher_info_t aes_256_ctr_info = {
MBEDTLS_CIPHER_AES_256_CTR,
MBEDTLS_MODE_CTR,
256,
"AES-256-CTR",
16,
0,
16,
&aes_info
};
#endif /* MBEDTLS_CIPHER_MODE_CTR */
#if defined(MBEDTLS_CIPHER_MODE_XTS)
static int xts_aes_setkey_enc_wrap( void *ctx, const unsigned char *key,
unsigned int key_bitlen )
{
mbedtls_aes_xts_context *xts_ctx = ctx;
return( mbedtls_aes_xts_setkey_enc( xts_ctx, key, key_bitlen ) );
}
static int xts_aes_setkey_dec_wrap( void *ctx, const unsigned char *key,
unsigned int key_bitlen )
{
mbedtls_aes_xts_context *xts_ctx = ctx;
return( mbedtls_aes_xts_setkey_dec( xts_ctx, key, key_bitlen ) );
}
static void *xts_aes_ctx_alloc( void )
{
mbedtls_aes_xts_context *xts_ctx = mbedtls_calloc( 1, sizeof( *xts_ctx ) );
if( xts_ctx != NULL )
mbedtls_aes_xts_init( xts_ctx );
return( xts_ctx );
}
static void xts_aes_ctx_free( void *ctx )
{
mbedtls_aes_xts_context *xts_ctx = ctx;
if( xts_ctx == NULL )
return;
mbedtls_aes_xts_free( xts_ctx );
mbedtls_free( xts_ctx );
}
static const mbedtls_cipher_base_t xts_aes_info = {
MBEDTLS_CIPHER_ID_AES,
NULL,
#if defined(MBEDTLS_CIPHER_MODE_CBC)
NULL,
#endif
#if defined(MBEDTLS_CIPHER_MODE_CFB)
NULL,
#endif
#if defined(MBEDTLS_CIPHER_MODE_OFB)
NULL,
#endif
#if defined(MBEDTLS_CIPHER_MODE_CTR)
NULL,
#endif
#if defined(MBEDTLS_CIPHER_MODE_XTS)
aes_crypt_xts_wrap,
#endif
#if defined(MBEDTLS_CIPHER_MODE_STREAM)
NULL,
#endif
xts_aes_setkey_enc_wrap,
xts_aes_setkey_dec_wrap,
xts_aes_ctx_alloc,
xts_aes_ctx_free
};
static const mbedtls_cipher_info_t aes_128_xts_info = {
MBEDTLS_CIPHER_AES_128_XTS,
MBEDTLS_MODE_XTS,
256,
"AES-128-XTS",
16,
0,
16,
&xts_aes_info
};
static const mbedtls_cipher_info_t aes_256_xts_info = {
MBEDTLS_CIPHER_AES_256_XTS,
MBEDTLS_MODE_XTS,
512,
"AES-256-XTS",
16,
0,
16,
&xts_aes_info
};
#endif /* MBEDTLS_CIPHER_MODE_XTS */
#if defined(MBEDTLS_GCM_C)
static int gcm_aes_setkey_wrap( void *ctx, const unsigned char *key,
unsigned int key_bitlen )
{
return mbedtls_gcm_setkey( (mbedtls_gcm_context *) ctx, MBEDTLS_CIPHER_ID_AES,
key, key_bitlen );
}
static const mbedtls_cipher_base_t gcm_aes_info = {
MBEDTLS_CIPHER_ID_AES,
NULL,
#if defined(MBEDTLS_CIPHER_MODE_CBC)
NULL,
#endif
#if defined(MBEDTLS_CIPHER_MODE_CFB)
NULL,
#endif
#if defined(MBEDTLS_CIPHER_MODE_OFB)
NULL,
#endif
#if defined(MBEDTLS_CIPHER_MODE_CTR)
NULL,
#endif
#if defined(MBEDTLS_CIPHER_MODE_XTS)
NULL,
#endif
#if defined(MBEDTLS_CIPHER_MODE_STREAM)
NULL,
#endif
gcm_aes_setkey_wrap,
gcm_aes_setkey_wrap,
gcm_ctx_alloc,
gcm_ctx_free,
};
static const mbedtls_cipher_info_t aes_128_gcm_info = {
MBEDTLS_CIPHER_AES_128_GCM,
MBEDTLS_MODE_GCM,
128,
"AES-128-GCM",
12,
MBEDTLS_CIPHER_VARIABLE_IV_LEN,
16,
&gcm_aes_info
};
static const mbedtls_cipher_info_t aes_192_gcm_info = {
MBEDTLS_CIPHER_AES_192_GCM,
MBEDTLS_MODE_GCM,
192,
"AES-192-GCM",
12,
MBEDTLS_CIPHER_VARIABLE_IV_LEN,
16,
&gcm_aes_info
};
static const mbedtls_cipher_info_t aes_256_gcm_info = {
MBEDTLS_CIPHER_AES_256_GCM,
MBEDTLS_MODE_GCM,
256,
"AES-256-GCM",
12,
MBEDTLS_CIPHER_VARIABLE_IV_LEN,
16,
&gcm_aes_info
};
#endif /* MBEDTLS_GCM_C */
#if defined(MBEDTLS_CCM_C)
static int ccm_aes_setkey_wrap( void *ctx, const unsigned char *key,
unsigned int key_bitlen )
{
return mbedtls_ccm_setkey( (mbedtls_ccm_context *) ctx, MBEDTLS_CIPHER_ID_AES,
key, key_bitlen );
}
static const mbedtls_cipher_base_t ccm_aes_info = {
MBEDTLS_CIPHER_ID_AES,
NULL,
#if defined(MBEDTLS_CIPHER_MODE_CBC)
NULL,
#endif
#if defined(MBEDTLS_CIPHER_MODE_CFB)
NULL,
#endif
#if defined(MBEDTLS_CIPHER_MODE_OFB)
NULL,
#endif
#if defined(MBEDTLS_CIPHER_MODE_CTR)
NULL,
#endif
#if defined(MBEDTLS_CIPHER_MODE_XTS)
NULL,
#endif
#if defined(MBEDTLS_CIPHER_MODE_STREAM)
NULL,
#endif
ccm_aes_setkey_wrap,
ccm_aes_setkey_wrap,
ccm_ctx_alloc,
ccm_ctx_free,
};
static const mbedtls_cipher_info_t aes_128_ccm_info = {
MBEDTLS_CIPHER_AES_128_CCM,
MBEDTLS_MODE_CCM,
128,
"AES-128-CCM",
12,
MBEDTLS_CIPHER_VARIABLE_IV_LEN,
16,
&ccm_aes_info
};
static const mbedtls_cipher_info_t aes_192_ccm_info = {
MBEDTLS_CIPHER_AES_192_CCM,
MBEDTLS_MODE_CCM,
192,
"AES-192-CCM",
12,
MBEDTLS_CIPHER_VARIABLE_IV_LEN,
16,
&ccm_aes_info
};
static const mbedtls_cipher_info_t aes_256_ccm_info = {
MBEDTLS_CIPHER_AES_256_CCM,
MBEDTLS_MODE_CCM,
256,
"AES-256-CCM",
12,
MBEDTLS_CIPHER_VARIABLE_IV_LEN,
16,
&ccm_aes_info
};
#endif /* MBEDTLS_CCM_C */
#endif /* MBEDTLS_AES_C */
#if defined(MBEDTLS_CAMELLIA_C)
static int camellia_crypt_ecb_wrap( void *ctx, mbedtls_operation_t operation,
const unsigned char *input, unsigned char *output )
{
return mbedtls_camellia_crypt_ecb( (mbedtls_camellia_context *) ctx, operation, input,
output );
}
#if defined(MBEDTLS_CIPHER_MODE_CBC)
static int camellia_crypt_cbc_wrap( void *ctx, mbedtls_operation_t operation,
size_t length, unsigned char *iv,
const unsigned char *input, unsigned char *output )
{
return mbedtls_camellia_crypt_cbc( (mbedtls_camellia_context *) ctx, operation, length, iv,
input, output );
}
#endif /* MBEDTLS_CIPHER_MODE_CBC */
#if defined(MBEDTLS_CIPHER_MODE_CFB)
static int camellia_crypt_cfb128_wrap( void *ctx, mbedtls_operation_t operation,
size_t length, size_t *iv_off, unsigned char *iv,
const unsigned char *input, unsigned char *output )
{
return mbedtls_camellia_crypt_cfb128( (mbedtls_camellia_context *) ctx, operation, length,
iv_off, iv, input, output );
}
#endif /* MBEDTLS_CIPHER_MODE_CFB */
#if defined(MBEDTLS_CIPHER_MODE_CTR)
static int camellia_crypt_ctr_wrap( void *ctx, size_t length, size_t *nc_off,
unsigned char *nonce_counter, unsigned char *stream_block,
const unsigned char *input, unsigned char *output )
{
return mbedtls_camellia_crypt_ctr( (mbedtls_camellia_context *) ctx, length, nc_off,
nonce_counter, stream_block, input, output );
}
#endif /* MBEDTLS_CIPHER_MODE_CTR */
static int camellia_setkey_dec_wrap( void *ctx, const unsigned char *key,
unsigned int key_bitlen )
{
return mbedtls_camellia_setkey_dec( (mbedtls_camellia_context *) ctx, key, key_bitlen );
}
static int camellia_setkey_enc_wrap( void *ctx, const unsigned char *key,
unsigned int key_bitlen )
{
return mbedtls_camellia_setkey_enc( (mbedtls_camellia_context *) ctx, key, key_bitlen );
}
static void * camellia_ctx_alloc( void )
{
mbedtls_camellia_context *ctx;
ctx = mbedtls_calloc( 1, sizeof( mbedtls_camellia_context ) );
if( ctx == NULL )
return( NULL );
mbedtls_camellia_init( ctx );
return( ctx );
}
static void camellia_ctx_free( void *ctx )
{
mbedtls_camellia_free( (mbedtls_camellia_context *) ctx );
mbedtls_free( ctx );
}
static const mbedtls_cipher_base_t camellia_info = {
MBEDTLS_CIPHER_ID_CAMELLIA,
camellia_crypt_ecb_wrap,
#if defined(MBEDTLS_CIPHER_MODE_CBC)
camellia_crypt_cbc_wrap,
#endif
#if defined(MBEDTLS_CIPHER_MODE_CFB)
camellia_crypt_cfb128_wrap,
#endif
#if defined(MBEDTLS_CIPHER_MODE_OFB)
NULL,
#endif
#if defined(MBEDTLS_CIPHER_MODE_CTR)
camellia_crypt_ctr_wrap,
#endif
#if defined(MBEDTLS_CIPHER_MODE_XTS)
NULL,
#endif
#if defined(MBEDTLS_CIPHER_MODE_STREAM)
NULL,
#endif
camellia_setkey_enc_wrap,
camellia_setkey_dec_wrap,
camellia_ctx_alloc,
camellia_ctx_free
};
static const mbedtls_cipher_info_t camellia_128_ecb_info = {
MBEDTLS_CIPHER_CAMELLIA_128_ECB,
MBEDTLS_MODE_ECB,
128,
"CAMELLIA-128-ECB",
0,
0,
16,
&camellia_info
};
static const mbedtls_cipher_info_t camellia_192_ecb_info = {
MBEDTLS_CIPHER_CAMELLIA_192_ECB,
MBEDTLS_MODE_ECB,
192,
"CAMELLIA-192-ECB",
0,
0,
16,
&camellia_info
};
static const mbedtls_cipher_info_t camellia_256_ecb_info = {
MBEDTLS_CIPHER_CAMELLIA_256_ECB,
MBEDTLS_MODE_ECB,
256,
"CAMELLIA-256-ECB",
0,
0,
16,
&camellia_info
};
#if defined(MBEDTLS_CIPHER_MODE_CBC)
static const mbedtls_cipher_info_t camellia_128_cbc_info = {
MBEDTLS_CIPHER_CAMELLIA_128_CBC,
MBEDTLS_MODE_CBC,
128,
"CAMELLIA-128-CBC",
16,
0,
16,
&camellia_info
};
static const mbedtls_cipher_info_t camellia_192_cbc_info = {
MBEDTLS_CIPHER_CAMELLIA_192_CBC,
MBEDTLS_MODE_CBC,
192,
"CAMELLIA-192-CBC",
16,
0,
16,
&camellia_info
};
static const mbedtls_cipher_info_t camellia_256_cbc_info = {
MBEDTLS_CIPHER_CAMELLIA_256_CBC,
MBEDTLS_MODE_CBC,
256,
"CAMELLIA-256-CBC",
16,
0,
16,
&camellia_info
};
#endif /* MBEDTLS_CIPHER_MODE_CBC */
#if defined(MBEDTLS_CIPHER_MODE_CFB)
static const mbedtls_cipher_info_t camellia_128_cfb128_info = {
MBEDTLS_CIPHER_CAMELLIA_128_CFB128,
MBEDTLS_MODE_CFB,
128,
"CAMELLIA-128-CFB128",
16,
0,
16,
&camellia_info
};
static const mbedtls_cipher_info_t camellia_192_cfb128_info = {
MBEDTLS_CIPHER_CAMELLIA_192_CFB128,
MBEDTLS_MODE_CFB,
192,
"CAMELLIA-192-CFB128",
16,
0,
16,
&camellia_info
};
static const mbedtls_cipher_info_t camellia_256_cfb128_info = {
MBEDTLS_CIPHER_CAMELLIA_256_CFB128,
MBEDTLS_MODE_CFB,
256,
"CAMELLIA-256-CFB128",
16,
0,
16,
&camellia_info
};
#endif /* MBEDTLS_CIPHER_MODE_CFB */
#if defined(MBEDTLS_CIPHER_MODE_CTR)
static const mbedtls_cipher_info_t camellia_128_ctr_info = {
MBEDTLS_CIPHER_CAMELLIA_128_CTR,
MBEDTLS_MODE_CTR,
128,
"CAMELLIA-128-CTR",
16,
0,
16,
&camellia_info
};
static const mbedtls_cipher_info_t camellia_192_ctr_info = {
MBEDTLS_CIPHER_CAMELLIA_192_CTR,
MBEDTLS_MODE_CTR,
192,
"CAMELLIA-192-CTR",
16,
0,
16,
&camellia_info
};
static const mbedtls_cipher_info_t camellia_256_ctr_info = {
MBEDTLS_CIPHER_CAMELLIA_256_CTR,
MBEDTLS_MODE_CTR,
256,
"CAMELLIA-256-CTR",
16,
0,
16,
&camellia_info
};
#endif /* MBEDTLS_CIPHER_MODE_CTR */
#if defined(MBEDTLS_GCM_C)
static int gcm_camellia_setkey_wrap( void *ctx, const unsigned char *key,
unsigned int key_bitlen )
{
return mbedtls_gcm_setkey( (mbedtls_gcm_context *) ctx, MBEDTLS_CIPHER_ID_CAMELLIA,
key, key_bitlen );
}
static const mbedtls_cipher_base_t gcm_camellia_info = {
MBEDTLS_CIPHER_ID_CAMELLIA,
NULL,
#if defined(MBEDTLS_CIPHER_MODE_CBC)
NULL,
#endif
#if defined(MBEDTLS_CIPHER_MODE_CFB)
NULL,
#endif
#if defined(MBEDTLS_CIPHER_MODE_OFB)
NULL,
#endif
#if defined(MBEDTLS_CIPHER_MODE_CTR)
NULL,
#endif
#if defined(MBEDTLS_CIPHER_MODE_XTS)
NULL,
#endif
#if defined(MBEDTLS_CIPHER_MODE_STREAM)
NULL,
#endif
gcm_camellia_setkey_wrap,
gcm_camellia_setkey_wrap,
gcm_ctx_alloc,
gcm_ctx_free,
};
static const mbedtls_cipher_info_t camellia_128_gcm_info = {
MBEDTLS_CIPHER_CAMELLIA_128_GCM,
MBEDTLS_MODE_GCM,
128,
"CAMELLIA-128-GCM",
12,
MBEDTLS_CIPHER_VARIABLE_IV_LEN,
16,
&gcm_camellia_info
};
static const mbedtls_cipher_info_t camellia_192_gcm_info = {
MBEDTLS_CIPHER_CAMELLIA_192_GCM,
MBEDTLS_MODE_GCM,
192,
"CAMELLIA-192-GCM",
12,
MBEDTLS_CIPHER_VARIABLE_IV_LEN,
16,
&gcm_camellia_info
};
static const mbedtls_cipher_info_t camellia_256_gcm_info = {
MBEDTLS_CIPHER_CAMELLIA_256_GCM,
MBEDTLS_MODE_GCM,
256,
"CAMELLIA-256-GCM",
12,
MBEDTLS_CIPHER_VARIABLE_IV_LEN,
16,
&gcm_camellia_info
};
#endif /* MBEDTLS_GCM_C */
#if defined(MBEDTLS_CCM_C)
static int ccm_camellia_setkey_wrap( void *ctx, const unsigned char *key,
unsigned int key_bitlen )
{
return mbedtls_ccm_setkey( (mbedtls_ccm_context *) ctx, MBEDTLS_CIPHER_ID_CAMELLIA,
key, key_bitlen );
}
static const mbedtls_cipher_base_t ccm_camellia_info = {
MBEDTLS_CIPHER_ID_CAMELLIA,
NULL,
#if defined(MBEDTLS_CIPHER_MODE_CBC)
NULL,
#endif
#if defined(MBEDTLS_CIPHER_MODE_CFB)
NULL,
#endif
#if defined(MBEDTLS_CIPHER_MODE_OFB)
NULL,
#endif
#if defined(MBEDTLS_CIPHER_MODE_CTR)
NULL,
#endif
#if defined(MBEDTLS_CIPHER_MODE_XTS)
NULL,
#endif
#if defined(MBEDTLS_CIPHER_MODE_STREAM)
NULL,
#endif
ccm_camellia_setkey_wrap,
ccm_camellia_setkey_wrap,
ccm_ctx_alloc,
ccm_ctx_free,
};
static const mbedtls_cipher_info_t camellia_128_ccm_info = {
MBEDTLS_CIPHER_CAMELLIA_128_CCM,
MBEDTLS_MODE_CCM,
128,
"CAMELLIA-128-CCM",
12,
MBEDTLS_CIPHER_VARIABLE_IV_LEN,
16,
&ccm_camellia_info
};
static const mbedtls_cipher_info_t camellia_192_ccm_info = {
MBEDTLS_CIPHER_CAMELLIA_192_CCM,
MBEDTLS_MODE_CCM,
192,
"CAMELLIA-192-CCM",
12,
MBEDTLS_CIPHER_VARIABLE_IV_LEN,
16,
&ccm_camellia_info
};
static const mbedtls_cipher_info_t camellia_256_ccm_info = {
MBEDTLS_CIPHER_CAMELLIA_256_CCM,
MBEDTLS_MODE_CCM,
256,
"CAMELLIA-256-CCM",
12,
MBEDTLS_CIPHER_VARIABLE_IV_LEN,
16,
&ccm_camellia_info
};
#endif /* MBEDTLS_CCM_C */
#endif /* MBEDTLS_CAMELLIA_C */
#if defined(MBEDTLS_ARIA_C)
static int aria_crypt_ecb_wrap( void *ctx, mbedtls_operation_t operation,
const unsigned char *input, unsigned char *output )
{
(void) operation;
return mbedtls_aria_crypt_ecb( (mbedtls_aria_context *) ctx, input,
output );
}
#if defined(MBEDTLS_CIPHER_MODE_CBC)
static int aria_crypt_cbc_wrap( void *ctx, mbedtls_operation_t operation,
size_t length, unsigned char *iv,
const unsigned char *input, unsigned char *output )
{
return mbedtls_aria_crypt_cbc( (mbedtls_aria_context *) ctx, operation, length, iv,
input, output );
}
#endif /* MBEDTLS_CIPHER_MODE_CBC */
#if defined(MBEDTLS_CIPHER_MODE_CFB)
static int aria_crypt_cfb128_wrap( void *ctx, mbedtls_operation_t operation,
size_t length, size_t *iv_off, unsigned char *iv,
const unsigned char *input, unsigned char *output )
{
return mbedtls_aria_crypt_cfb128( (mbedtls_aria_context *) ctx, operation, length,
iv_off, iv, input, output );
}
#endif /* MBEDTLS_CIPHER_MODE_CFB */
#if defined(MBEDTLS_CIPHER_MODE_CTR)
static int aria_crypt_ctr_wrap( void *ctx, size_t length, size_t *nc_off,
unsigned char *nonce_counter, unsigned char *stream_block,
const unsigned char *input, unsigned char *output )
{
return mbedtls_aria_crypt_ctr( (mbedtls_aria_context *) ctx, length, nc_off,
nonce_counter, stream_block, input, output );
}
#endif /* MBEDTLS_CIPHER_MODE_CTR */
static int aria_setkey_dec_wrap( void *ctx, const unsigned char *key,
unsigned int key_bitlen )
{
return mbedtls_aria_setkey_dec( (mbedtls_aria_context *) ctx, key, key_bitlen );
}
static int aria_setkey_enc_wrap( void *ctx, const unsigned char *key,
unsigned int key_bitlen )
{
return mbedtls_aria_setkey_enc( (mbedtls_aria_context *) ctx, key, key_bitlen );
}
static void * aria_ctx_alloc( void )
{
mbedtls_aria_context *ctx;
ctx = mbedtls_calloc( 1, sizeof( mbedtls_aria_context ) );
if( ctx == NULL )
return( NULL );
mbedtls_aria_init( ctx );
return( ctx );
}
static void aria_ctx_free( void *ctx )
{
mbedtls_aria_free( (mbedtls_aria_context *) ctx );
mbedtls_free( ctx );
}
static const mbedtls_cipher_base_t aria_info = {
MBEDTLS_CIPHER_ID_ARIA,
aria_crypt_ecb_wrap,
#if defined(MBEDTLS_CIPHER_MODE_CBC)
aria_crypt_cbc_wrap,
#endif
#if defined(MBEDTLS_CIPHER_MODE_CFB)
aria_crypt_cfb128_wrap,
#endif
#if defined(MBEDTLS_CIPHER_MODE_OFB)
NULL,
#endif
#if defined(MBEDTLS_CIPHER_MODE_CTR)
aria_crypt_ctr_wrap,
#endif
#if defined(MBEDTLS_CIPHER_MODE_XTS)
NULL,
#endif
#if defined(MBEDTLS_CIPHER_MODE_STREAM)
NULL,
#endif
aria_setkey_enc_wrap,
aria_setkey_dec_wrap,
aria_ctx_alloc,
aria_ctx_free
};
static const mbedtls_cipher_info_t aria_128_ecb_info = {
MBEDTLS_CIPHER_ARIA_128_ECB,
MBEDTLS_MODE_ECB,
128,
"ARIA-128-ECB",
0,
0,
16,
&aria_info
};
static const mbedtls_cipher_info_t aria_192_ecb_info = {
MBEDTLS_CIPHER_ARIA_192_ECB,
MBEDTLS_MODE_ECB,
192,
"ARIA-192-ECB",
0,
0,
16,
&aria_info
};
static const mbedtls_cipher_info_t aria_256_ecb_info = {
MBEDTLS_CIPHER_ARIA_256_ECB,
MBEDTLS_MODE_ECB,
256,
"ARIA-256-ECB",
0,
0,
16,
&aria_info
};
#if defined(MBEDTLS_CIPHER_MODE_CBC)
static const mbedtls_cipher_info_t aria_128_cbc_info = {
MBEDTLS_CIPHER_ARIA_128_CBC,
MBEDTLS_MODE_CBC,
128,
"ARIA-128-CBC",
16,
0,
16,
&aria_info
};
static const mbedtls_cipher_info_t aria_192_cbc_info = {
MBEDTLS_CIPHER_ARIA_192_CBC,
MBEDTLS_MODE_CBC,
192,
"ARIA-192-CBC",
16,
0,
16,
&aria_info
};
static const mbedtls_cipher_info_t aria_256_cbc_info = {
MBEDTLS_CIPHER_ARIA_256_CBC,
MBEDTLS_MODE_CBC,
256,
"ARIA-256-CBC",
16,
0,
16,
&aria_info
};
#endif /* MBEDTLS_CIPHER_MODE_CBC */
#if defined(MBEDTLS_CIPHER_MODE_CFB)
static const mbedtls_cipher_info_t aria_128_cfb128_info = {
MBEDTLS_CIPHER_ARIA_128_CFB128,
MBEDTLS_MODE_CFB,
128,
"ARIA-128-CFB128",
16,
0,
16,
&aria_info
};
static const mbedtls_cipher_info_t aria_192_cfb128_info = {
MBEDTLS_CIPHER_ARIA_192_CFB128,
MBEDTLS_MODE_CFB,
192,
"ARIA-192-CFB128",
16,
0,
16,
&aria_info
};
static const mbedtls_cipher_info_t aria_256_cfb128_info = {
MBEDTLS_CIPHER_ARIA_256_CFB128,
MBEDTLS_MODE_CFB,
256,
"ARIA-256-CFB128",
16,
0,
16,
&aria_info
};
#endif /* MBEDTLS_CIPHER_MODE_CFB */
#if defined(MBEDTLS_CIPHER_MODE_CTR)
static const mbedtls_cipher_info_t aria_128_ctr_info = {
MBEDTLS_CIPHER_ARIA_128_CTR,
MBEDTLS_MODE_CTR,
128,
"ARIA-128-CTR",
16,
0,
16,
&aria_info
};
static const mbedtls_cipher_info_t aria_192_ctr_info = {
MBEDTLS_CIPHER_ARIA_192_CTR,
MBEDTLS_MODE_CTR,
192,
"ARIA-192-CTR",
16,
0,
16,
&aria_info
};
static const mbedtls_cipher_info_t aria_256_ctr_info = {
MBEDTLS_CIPHER_ARIA_256_CTR,
MBEDTLS_MODE_CTR,
256,
"ARIA-256-CTR",
16,
0,
16,
&aria_info
};
#endif /* MBEDTLS_CIPHER_MODE_CTR */
#if defined(MBEDTLS_GCM_C)
static int gcm_aria_setkey_wrap( void *ctx, const unsigned char *key,
unsigned int key_bitlen )
{
return mbedtls_gcm_setkey( (mbedtls_gcm_context *) ctx, MBEDTLS_CIPHER_ID_ARIA,
key, key_bitlen );
}
static const mbedtls_cipher_base_t gcm_aria_info = {
MBEDTLS_CIPHER_ID_ARIA,
NULL,
#if defined(MBEDTLS_CIPHER_MODE_CBC)
NULL,
#endif
#if defined(MBEDTLS_CIPHER_MODE_CFB)
NULL,
#endif
#if defined(MBEDTLS_CIPHER_MODE_OFB)
NULL,
#endif
#if defined(MBEDTLS_CIPHER_MODE_CTR)
NULL,
#endif
#if defined(MBEDTLS_CIPHER_MODE_XTS)
NULL,
#endif
#if defined(MBEDTLS_CIPHER_MODE_STREAM)
NULL,
#endif
gcm_aria_setkey_wrap,
gcm_aria_setkey_wrap,
gcm_ctx_alloc,
gcm_ctx_free,
};
static const mbedtls_cipher_info_t aria_128_gcm_info = {
MBEDTLS_CIPHER_ARIA_128_GCM,
MBEDTLS_MODE_GCM,
128,
"ARIA-128-GCM",
12,
MBEDTLS_CIPHER_VARIABLE_IV_LEN,
16,
&gcm_aria_info
};
static const mbedtls_cipher_info_t aria_192_gcm_info = {
MBEDTLS_CIPHER_ARIA_192_GCM,
MBEDTLS_MODE_GCM,
192,
"ARIA-192-GCM",
12,
MBEDTLS_CIPHER_VARIABLE_IV_LEN,
16,
&gcm_aria_info
};
static const mbedtls_cipher_info_t aria_256_gcm_info = {
MBEDTLS_CIPHER_ARIA_256_GCM,
MBEDTLS_MODE_GCM,
256,
"ARIA-256-GCM",
12,
MBEDTLS_CIPHER_VARIABLE_IV_LEN,
16,
&gcm_aria_info
};
#endif /* MBEDTLS_GCM_C */
#if defined(MBEDTLS_CCM_C)
static int ccm_aria_setkey_wrap( void *ctx, const unsigned char *key,
unsigned int key_bitlen )
{
return mbedtls_ccm_setkey( (mbedtls_ccm_context *) ctx, MBEDTLS_CIPHER_ID_ARIA,
key, key_bitlen );
}
static const mbedtls_cipher_base_t ccm_aria_info = {
MBEDTLS_CIPHER_ID_ARIA,
NULL,
#if defined(MBEDTLS_CIPHER_MODE_CBC)
NULL,
#endif
#if defined(MBEDTLS_CIPHER_MODE_CFB)
NULL,
#endif
#if defined(MBEDTLS_CIPHER_MODE_OFB)
NULL,
#endif
#if defined(MBEDTLS_CIPHER_MODE_CTR)
NULL,
#endif
#if defined(MBEDTLS_CIPHER_MODE_XTS)
NULL,
#endif
#if defined(MBEDTLS_CIPHER_MODE_STREAM)
NULL,
#endif
ccm_aria_setkey_wrap,
ccm_aria_setkey_wrap,
ccm_ctx_alloc,
ccm_ctx_free,
};
static const mbedtls_cipher_info_t aria_128_ccm_info = {
MBEDTLS_CIPHER_ARIA_128_CCM,
MBEDTLS_MODE_CCM,
128,
"ARIA-128-CCM",
12,
MBEDTLS_CIPHER_VARIABLE_IV_LEN,
16,
&ccm_aria_info
};
static const mbedtls_cipher_info_t aria_192_ccm_info = {
MBEDTLS_CIPHER_ARIA_192_CCM,
MBEDTLS_MODE_CCM,
192,
"ARIA-192-CCM",
12,
MBEDTLS_CIPHER_VARIABLE_IV_LEN,
16,
&ccm_aria_info
};
static const mbedtls_cipher_info_t aria_256_ccm_info = {
MBEDTLS_CIPHER_ARIA_256_CCM,
MBEDTLS_MODE_CCM,
256,
"ARIA-256-CCM",
12,
MBEDTLS_CIPHER_VARIABLE_IV_LEN,
16,
&ccm_aria_info
};
#endif /* MBEDTLS_CCM_C */
#endif /* MBEDTLS_ARIA_C */
#if defined(MBEDTLS_DES_C)
static int des_crypt_ecb_wrap( void *ctx, mbedtls_operation_t operation,
const unsigned char *input, unsigned char *output )
{
((void) operation);
return mbedtls_des_crypt_ecb( (mbedtls_des_context *) ctx, input, output );
}
static int des3_crypt_ecb_wrap( void *ctx, mbedtls_operation_t operation,
const unsigned char *input, unsigned char *output )
{
((void) operation);
return mbedtls_des3_crypt_ecb( (mbedtls_des3_context *) ctx, input, output );
}
#if defined(MBEDTLS_CIPHER_MODE_CBC)
static int des_crypt_cbc_wrap( void *ctx, mbedtls_operation_t operation, size_t length,
unsigned char *iv, const unsigned char *input, unsigned char *output )
{
return mbedtls_des_crypt_cbc( (mbedtls_des_context *) ctx, operation, length, iv, input,
output );
}
#endif /* MBEDTLS_CIPHER_MODE_CBC */
#if defined(MBEDTLS_CIPHER_MODE_CBC)
static int des3_crypt_cbc_wrap( void *ctx, mbedtls_operation_t operation, size_t length,
unsigned char *iv, const unsigned char *input, unsigned char *output )
{
return mbedtls_des3_crypt_cbc( (mbedtls_des3_context *) ctx, operation, length, iv, input,
output );
}
#endif /* MBEDTLS_CIPHER_MODE_CBC */
static int des_setkey_dec_wrap( void *ctx, const unsigned char *key,
unsigned int key_bitlen )
{
((void) key_bitlen);
return mbedtls_des_setkey_dec( (mbedtls_des_context *) ctx, key );
}
static int des_setkey_enc_wrap( void *ctx, const unsigned char *key,
unsigned int key_bitlen )
{
((void) key_bitlen);
return mbedtls_des_setkey_enc( (mbedtls_des_context *) ctx, key );
}
static int des3_set2key_dec_wrap( void *ctx, const unsigned char *key,
unsigned int key_bitlen )
{
((void) key_bitlen);
return mbedtls_des3_set2key_dec( (mbedtls_des3_context *) ctx, key );
}
static int des3_set2key_enc_wrap( void *ctx, const unsigned char *key,
unsigned int key_bitlen )
{
((void) key_bitlen);
return mbedtls_des3_set2key_enc( (mbedtls_des3_context *) ctx, key );
}
static int des3_set3key_dec_wrap( void *ctx, const unsigned char *key,
unsigned int key_bitlen )
{
((void) key_bitlen);
return mbedtls_des3_set3key_dec( (mbedtls_des3_context *) ctx, key );
}
static int des3_set3key_enc_wrap( void *ctx, const unsigned char *key,
unsigned int key_bitlen )
{
((void) key_bitlen);
return mbedtls_des3_set3key_enc( (mbedtls_des3_context *) ctx, key );
}
static void * des_ctx_alloc( void )
{
mbedtls_des_context *des = mbedtls_calloc( 1, sizeof( mbedtls_des_context ) );
if( des == NULL )
return( NULL );
mbedtls_des_init( des );
return( des );
}
static void des_ctx_free( void *ctx )
{
mbedtls_des_free( (mbedtls_des_context *) ctx );
mbedtls_free( ctx );
}
static void * des3_ctx_alloc( void )
{
mbedtls_des3_context *des3;
des3 = mbedtls_calloc( 1, sizeof( mbedtls_des3_context ) );
if( des3 == NULL )
return( NULL );
mbedtls_des3_init( des3 );
return( des3 );
}
static void des3_ctx_free( void *ctx )
{
mbedtls_des3_free( (mbedtls_des3_context *) ctx );
mbedtls_free( ctx );
}
static const mbedtls_cipher_base_t des_info = {
MBEDTLS_CIPHER_ID_DES,
des_crypt_ecb_wrap,
#if defined(MBEDTLS_CIPHER_MODE_CBC)
des_crypt_cbc_wrap,
#endif
#if defined(MBEDTLS_CIPHER_MODE_CFB)
NULL,
#endif
#if defined(MBEDTLS_CIPHER_MODE_OFB)
NULL,
#endif
#if defined(MBEDTLS_CIPHER_MODE_CTR)
NULL,
#endif
#if defined(MBEDTLS_CIPHER_MODE_XTS)
NULL,
#endif
#if defined(MBEDTLS_CIPHER_MODE_STREAM)
NULL,
#endif
des_setkey_enc_wrap,
des_setkey_dec_wrap,
des_ctx_alloc,
des_ctx_free
};
static const mbedtls_cipher_info_t des_ecb_info = {
MBEDTLS_CIPHER_DES_ECB,
MBEDTLS_MODE_ECB,
MBEDTLS_KEY_LENGTH_DES,
"DES-ECB",
0,
0,
8,
&des_info
};
#if defined(MBEDTLS_CIPHER_MODE_CBC)
static const mbedtls_cipher_info_t des_cbc_info = {
MBEDTLS_CIPHER_DES_CBC,
MBEDTLS_MODE_CBC,
MBEDTLS_KEY_LENGTH_DES,
"DES-CBC",
8,
0,
8,
&des_info
};
#endif /* MBEDTLS_CIPHER_MODE_CBC */
static const mbedtls_cipher_base_t des_ede_info = {
MBEDTLS_CIPHER_ID_DES,
des3_crypt_ecb_wrap,
#if defined(MBEDTLS_CIPHER_MODE_CBC)
des3_crypt_cbc_wrap,
#endif
#if defined(MBEDTLS_CIPHER_MODE_CFB)
NULL,
#endif
#if defined(MBEDTLS_CIPHER_MODE_OFB)
NULL,
#endif
#if defined(MBEDTLS_CIPHER_MODE_CTR)
NULL,
#endif
#if defined(MBEDTLS_CIPHER_MODE_XTS)
NULL,
#endif
#if defined(MBEDTLS_CIPHER_MODE_STREAM)
NULL,
#endif
des3_set2key_enc_wrap,
des3_set2key_dec_wrap,
des3_ctx_alloc,
des3_ctx_free
};
static const mbedtls_cipher_info_t des_ede_ecb_info = {
MBEDTLS_CIPHER_DES_EDE_ECB,
MBEDTLS_MODE_ECB,
MBEDTLS_KEY_LENGTH_DES_EDE,
"DES-EDE-ECB",
0,
0,
8,
&des_ede_info
};
#if defined(MBEDTLS_CIPHER_MODE_CBC)
static const mbedtls_cipher_info_t des_ede_cbc_info = {
MBEDTLS_CIPHER_DES_EDE_CBC,
MBEDTLS_MODE_CBC,
MBEDTLS_KEY_LENGTH_DES_EDE,
"DES-EDE-CBC",
8,
0,
8,
&des_ede_info
};
#endif /* MBEDTLS_CIPHER_MODE_CBC */
static const mbedtls_cipher_base_t des_ede3_info = {
MBEDTLS_CIPHER_ID_3DES,
des3_crypt_ecb_wrap,
#if defined(MBEDTLS_CIPHER_MODE_CBC)
des3_crypt_cbc_wrap,
#endif
#if defined(MBEDTLS_CIPHER_MODE_CFB)
NULL,
#endif
#if defined(MBEDTLS_CIPHER_MODE_OFB)
NULL,
#endif
#if defined(MBEDTLS_CIPHER_MODE_CTR)
NULL,
#endif
#if defined(MBEDTLS_CIPHER_MODE_XTS)
NULL,
#endif
#if defined(MBEDTLS_CIPHER_MODE_STREAM)
NULL,
#endif
des3_set3key_enc_wrap,
des3_set3key_dec_wrap,
des3_ctx_alloc,
des3_ctx_free
};
static const mbedtls_cipher_info_t des_ede3_ecb_info = {
MBEDTLS_CIPHER_DES_EDE3_ECB,
MBEDTLS_MODE_ECB,
MBEDTLS_KEY_LENGTH_DES_EDE3,
"DES-EDE3-ECB",
0,
0,
8,
&des_ede3_info
};
#if defined(MBEDTLS_CIPHER_MODE_CBC)
static const mbedtls_cipher_info_t des_ede3_cbc_info = {
MBEDTLS_CIPHER_DES_EDE3_CBC,
MBEDTLS_MODE_CBC,
MBEDTLS_KEY_LENGTH_DES_EDE3,
"DES-EDE3-CBC",
8,
0,
8,
&des_ede3_info
};
#endif /* MBEDTLS_CIPHER_MODE_CBC */
#endif /* MBEDTLS_DES_C */
#if defined(MBEDTLS_BLOWFISH_C)
static int blowfish_crypt_ecb_wrap( void *ctx, mbedtls_operation_t operation,
const unsigned char *input, unsigned char *output )
{
return mbedtls_blowfish_crypt_ecb( (mbedtls_blowfish_context *) ctx, operation, input,
output );
}
#if defined(MBEDTLS_CIPHER_MODE_CBC)
static int blowfish_crypt_cbc_wrap( void *ctx, mbedtls_operation_t operation,
size_t length, unsigned char *iv, const unsigned char *input,
unsigned char *output )
{
return mbedtls_blowfish_crypt_cbc( (mbedtls_blowfish_context *) ctx, operation, length, iv,
input, output );
}
#endif /* MBEDTLS_CIPHER_MODE_CBC */
#if defined(MBEDTLS_CIPHER_MODE_CFB)
static int blowfish_crypt_cfb64_wrap( void *ctx, mbedtls_operation_t operation,
size_t length, size_t *iv_off, unsigned char *iv,
const unsigned char *input, unsigned char *output )
{
return mbedtls_blowfish_crypt_cfb64( (mbedtls_blowfish_context *) ctx, operation, length,
iv_off, iv, input, output );
}
#endif /* MBEDTLS_CIPHER_MODE_CFB */
#if defined(MBEDTLS_CIPHER_MODE_CTR)
static int blowfish_crypt_ctr_wrap( void *ctx, size_t length, size_t *nc_off,
unsigned char *nonce_counter, unsigned char *stream_block,
const unsigned char *input, unsigned char *output )
{
return mbedtls_blowfish_crypt_ctr( (mbedtls_blowfish_context *) ctx, length, nc_off,
nonce_counter, stream_block, input, output );
}
#endif /* MBEDTLS_CIPHER_MODE_CTR */
static int blowfish_setkey_wrap( void *ctx, const unsigned char *key,
unsigned int key_bitlen )
{
return mbedtls_blowfish_setkey( (mbedtls_blowfish_context *) ctx, key, key_bitlen );
}
static void * blowfish_ctx_alloc( void )
{
mbedtls_blowfish_context *ctx;
ctx = mbedtls_calloc( 1, sizeof( mbedtls_blowfish_context ) );
if( ctx == NULL )
return( NULL );
mbedtls_blowfish_init( ctx );
return( ctx );
}
static void blowfish_ctx_free( void *ctx )
{
mbedtls_blowfish_free( (mbedtls_blowfish_context *) ctx );
mbedtls_free( ctx );
}
static const mbedtls_cipher_base_t blowfish_info = {
MBEDTLS_CIPHER_ID_BLOWFISH,
blowfish_crypt_ecb_wrap,
#if defined(MBEDTLS_CIPHER_MODE_CBC)
blowfish_crypt_cbc_wrap,
#endif
#if defined(MBEDTLS_CIPHER_MODE_CFB)
blowfish_crypt_cfb64_wrap,
#endif
#if defined(MBEDTLS_CIPHER_MODE_OFB)
NULL,
#endif
#if defined(MBEDTLS_CIPHER_MODE_CTR)
blowfish_crypt_ctr_wrap,
#endif
#if defined(MBEDTLS_CIPHER_MODE_XTS)
NULL,
#endif
#if defined(MBEDTLS_CIPHER_MODE_STREAM)
NULL,
#endif
blowfish_setkey_wrap,
blowfish_setkey_wrap,
blowfish_ctx_alloc,
blowfish_ctx_free
};
static const mbedtls_cipher_info_t blowfish_ecb_info = {
MBEDTLS_CIPHER_BLOWFISH_ECB,
MBEDTLS_MODE_ECB,
128,
"BLOWFISH-ECB",
0,
MBEDTLS_CIPHER_VARIABLE_KEY_LEN,
8,
&blowfish_info
};
#if defined(MBEDTLS_CIPHER_MODE_CBC)
static const mbedtls_cipher_info_t blowfish_cbc_info = {
MBEDTLS_CIPHER_BLOWFISH_CBC,
MBEDTLS_MODE_CBC,
128,
"BLOWFISH-CBC",
8,
MBEDTLS_CIPHER_VARIABLE_KEY_LEN,
8,
&blowfish_info
};
#endif /* MBEDTLS_CIPHER_MODE_CBC */
#if defined(MBEDTLS_CIPHER_MODE_CFB)
static const mbedtls_cipher_info_t blowfish_cfb64_info = {
MBEDTLS_CIPHER_BLOWFISH_CFB64,
MBEDTLS_MODE_CFB,
128,
"BLOWFISH-CFB64",
8,
MBEDTLS_CIPHER_VARIABLE_KEY_LEN,
8,
&blowfish_info
};
#endif /* MBEDTLS_CIPHER_MODE_CFB */
#if defined(MBEDTLS_CIPHER_MODE_CTR)
static const mbedtls_cipher_info_t blowfish_ctr_info = {
MBEDTLS_CIPHER_BLOWFISH_CTR,
MBEDTLS_MODE_CTR,
128,
"BLOWFISH-CTR",
8,
MBEDTLS_CIPHER_VARIABLE_KEY_LEN,
8,
&blowfish_info
};
#endif /* MBEDTLS_CIPHER_MODE_CTR */
#endif /* MBEDTLS_BLOWFISH_C */
#if defined(MBEDTLS_ARC4_C)
static int arc4_crypt_stream_wrap( void *ctx, size_t length,
const unsigned char *input,
unsigned char *output )
{
return( mbedtls_arc4_crypt( (mbedtls_arc4_context *) ctx, length, input, output ) );
}
static int arc4_setkey_wrap( void *ctx, const unsigned char *key,
unsigned int key_bitlen )
{
/* we get key_bitlen in bits, arc4 expects it in bytes */
if( key_bitlen % 8 != 0 )
return( MBEDTLS_ERR_CIPHER_BAD_INPUT_DATA );
mbedtls_arc4_setup( (mbedtls_arc4_context *) ctx, key, key_bitlen / 8 );
return( 0 );
}
static void * arc4_ctx_alloc( void )
{
mbedtls_arc4_context *ctx;
ctx = mbedtls_calloc( 1, sizeof( mbedtls_arc4_context ) );
if( ctx == NULL )
return( NULL );
mbedtls_arc4_init( ctx );
return( ctx );
}
static void arc4_ctx_free( void *ctx )
{
mbedtls_arc4_free( (mbedtls_arc4_context *) ctx );
mbedtls_free( ctx );
}
static const mbedtls_cipher_base_t arc4_base_info = {
MBEDTLS_CIPHER_ID_ARC4,
NULL,
#if defined(MBEDTLS_CIPHER_MODE_CBC)
NULL,
#endif
#if defined(MBEDTLS_CIPHER_MODE_CFB)
NULL,
#endif
#if defined(MBEDTLS_CIPHER_MODE_OFB)
NULL,
#endif
#if defined(MBEDTLS_CIPHER_MODE_CTR)
NULL,
#endif
#if defined(MBEDTLS_CIPHER_MODE_XTS)
NULL,
#endif
#if defined(MBEDTLS_CIPHER_MODE_STREAM)
arc4_crypt_stream_wrap,
#endif
arc4_setkey_wrap,
arc4_setkey_wrap,
arc4_ctx_alloc,
arc4_ctx_free
};
static const mbedtls_cipher_info_t arc4_128_info = {
MBEDTLS_CIPHER_ARC4_128,
MBEDTLS_MODE_STREAM,
128,
"ARC4-128",
0,
0,
1,
&arc4_base_info
};
#endif /* MBEDTLS_ARC4_C */
#if defined(MBEDTLS_CHACHA20_C)
static int chacha20_setkey_wrap( void *ctx, const unsigned char *key,
unsigned int key_bitlen )
{
if( key_bitlen != 256U )
return( MBEDTLS_ERR_CIPHER_BAD_INPUT_DATA );
if ( 0 != mbedtls_chacha20_setkey( (mbedtls_chacha20_context*)ctx, key ) )
return( MBEDTLS_ERR_CIPHER_BAD_INPUT_DATA );
return( 0 );
}
static int chacha20_stream_wrap( void *ctx, size_t length,
const unsigned char *input,
unsigned char *output )
{
int ret = MBEDTLS_ERR_ERROR_CORRUPTION_DETECTED;
ret = mbedtls_chacha20_update( ctx, length, input, output );
if( ret == MBEDTLS_ERR_CHACHA20_BAD_INPUT_DATA )
return( MBEDTLS_ERR_CIPHER_BAD_INPUT_DATA );
return( ret );
}
static void * chacha20_ctx_alloc( void )
{
mbedtls_chacha20_context *ctx;
ctx = mbedtls_calloc( 1, sizeof( mbedtls_chacha20_context ) );
if( ctx == NULL )
return( NULL );
mbedtls_chacha20_init( ctx );
return( ctx );
}
static void chacha20_ctx_free( void *ctx )
{
mbedtls_chacha20_free( (mbedtls_chacha20_context *) ctx );
mbedtls_free( ctx );
}
static const mbedtls_cipher_base_t chacha20_base_info = {
MBEDTLS_CIPHER_ID_CHACHA20,
NULL,
#if defined(MBEDTLS_CIPHER_MODE_CBC)
NULL,
#endif
#if defined(MBEDTLS_CIPHER_MODE_CFB)
NULL,
#endif
#if defined(MBEDTLS_CIPHER_MODE_OFB)
NULL,
#endif
#if defined(MBEDTLS_CIPHER_MODE_CTR)
NULL,
#endif
#if defined(MBEDTLS_CIPHER_MODE_XTS)
NULL,
#endif
#if defined(MBEDTLS_CIPHER_MODE_STREAM)
chacha20_stream_wrap,
#endif
chacha20_setkey_wrap,
chacha20_setkey_wrap,
chacha20_ctx_alloc,
chacha20_ctx_free
};
static const mbedtls_cipher_info_t chacha20_info = {
MBEDTLS_CIPHER_CHACHA20,
MBEDTLS_MODE_STREAM,
256,
"CHACHA20",
12,
0,
1,
&chacha20_base_info
};
#endif /* MBEDTLS_CHACHA20_C */
#if defined(MBEDTLS_CHACHAPOLY_C)
static int chachapoly_setkey_wrap( void *ctx,
const unsigned char *key,
unsigned int key_bitlen )
{
if( key_bitlen != 256U )
return( MBEDTLS_ERR_CIPHER_BAD_INPUT_DATA );
if ( 0 != mbedtls_chachapoly_setkey( (mbedtls_chachapoly_context*)ctx, key ) )
return( MBEDTLS_ERR_CIPHER_BAD_INPUT_DATA );
return( 0 );
}
static void * chachapoly_ctx_alloc( void )
{
mbedtls_chachapoly_context *ctx;
ctx = mbedtls_calloc( 1, sizeof( mbedtls_chachapoly_context ) );
if( ctx == NULL )
return( NULL );
mbedtls_chachapoly_init( ctx );
return( ctx );
}
static void chachapoly_ctx_free( void *ctx )
{
mbedtls_chachapoly_free( (mbedtls_chachapoly_context *) ctx );
mbedtls_free( ctx );
}
static const mbedtls_cipher_base_t chachapoly_base_info = {
MBEDTLS_CIPHER_ID_CHACHA20,
NULL,
#if defined(MBEDTLS_CIPHER_MODE_CBC)
NULL,
#endif
#if defined(MBEDTLS_CIPHER_MODE_CFB)
NULL,
#endif
#if defined(MBEDTLS_CIPHER_MODE_OFB)
NULL,
#endif
#if defined(MBEDTLS_CIPHER_MODE_CTR)
NULL,
#endif
#if defined(MBEDTLS_CIPHER_MODE_XTS)
NULL,
#endif
#if defined(MBEDTLS_CIPHER_MODE_STREAM)
NULL,
#endif
chachapoly_setkey_wrap,
chachapoly_setkey_wrap,
chachapoly_ctx_alloc,
chachapoly_ctx_free
};
static const mbedtls_cipher_info_t chachapoly_info = {
MBEDTLS_CIPHER_CHACHA20_POLY1305,
MBEDTLS_MODE_CHACHAPOLY,
256,
"CHACHA20-POLY1305",
12,
0,
1,
&chachapoly_base_info
};
#endif /* MBEDTLS_CHACHAPOLY_C */
#if defined(MBEDTLS_CIPHER_NULL_CIPHER)
static int null_crypt_stream( void *ctx, size_t length,
const unsigned char *input,
unsigned char *output )
{
((void) ctx);
memmove( output, input, length );
return( 0 );
}
static int null_setkey( void *ctx, const unsigned char *key,
unsigned int key_bitlen )
{
((void) ctx);
((void) key);
((void) key_bitlen);
return( 0 );
}
static void * null_ctx_alloc( void )
{
return( (void *) 1 );
}
static void null_ctx_free( void *ctx )
{
((void) ctx);
}
static const mbedtls_cipher_base_t null_base_info = {
MBEDTLS_CIPHER_ID_NULL,
NULL,
#if defined(MBEDTLS_CIPHER_MODE_CBC)
NULL,
#endif
#if defined(MBEDTLS_CIPHER_MODE_CFB)
NULL,
#endif
#if defined(MBEDTLS_CIPHER_MODE_OFB)
NULL,
#endif
#if defined(MBEDTLS_CIPHER_MODE_CTR)
NULL,
#endif
#if defined(MBEDTLS_CIPHER_MODE_XTS)
NULL,
#endif
#if defined(MBEDTLS_CIPHER_MODE_STREAM)
null_crypt_stream,
#endif
null_setkey,
null_setkey,
null_ctx_alloc,
null_ctx_free
};
static const mbedtls_cipher_info_t null_cipher_info = {
MBEDTLS_CIPHER_NULL,
MBEDTLS_MODE_STREAM,
0,
"NULL",
0,
0,
1,
&null_base_info
};
#endif /* defined(MBEDTLS_CIPHER_NULL_CIPHER) */
#if defined(MBEDTLS_NIST_KW_C)
static void *kw_ctx_alloc( void )
{
void *ctx = mbedtls_calloc( 1, sizeof( mbedtls_nist_kw_context ) );
if( ctx != NULL )
mbedtls_nist_kw_init( (mbedtls_nist_kw_context *) ctx );
return( ctx );
}
static void kw_ctx_free( void *ctx )
{
mbedtls_nist_kw_free( ctx );
mbedtls_free( ctx );
}
static int kw_aes_setkey_wrap( void *ctx, const unsigned char *key,
unsigned int key_bitlen )
{
return mbedtls_nist_kw_setkey( (mbedtls_nist_kw_context *) ctx,
MBEDTLS_CIPHER_ID_AES, key, key_bitlen, 1 );
}
static int kw_aes_setkey_unwrap( void *ctx, const unsigned char *key,
unsigned int key_bitlen )
{
return mbedtls_nist_kw_setkey( (mbedtls_nist_kw_context *) ctx,
MBEDTLS_CIPHER_ID_AES, key, key_bitlen, 0 );
}
static const mbedtls_cipher_base_t kw_aes_info = {
MBEDTLS_CIPHER_ID_AES,
NULL,
#if defined(MBEDTLS_CIPHER_MODE_CBC)
NULL,
#endif
#if defined(MBEDTLS_CIPHER_MODE_CFB)
NULL,
#endif
#if defined(MBEDTLS_CIPHER_MODE_OFB)
NULL,
#endif
#if defined(MBEDTLS_CIPHER_MODE_CTR)
NULL,
#endif
#if defined(MBEDTLS_CIPHER_MODE_XTS)
NULL,
#endif
#if defined(MBEDTLS_CIPHER_MODE_STREAM)
NULL,
#endif
kw_aes_setkey_wrap,
kw_aes_setkey_unwrap,
kw_ctx_alloc,
kw_ctx_free,
};
static const mbedtls_cipher_info_t aes_128_nist_kw_info = {
MBEDTLS_CIPHER_AES_128_KW,
MBEDTLS_MODE_KW,
128,
"AES-128-KW",
0,
0,
16,
&kw_aes_info
};
static const mbedtls_cipher_info_t aes_192_nist_kw_info = {
MBEDTLS_CIPHER_AES_192_KW,
MBEDTLS_MODE_KW,
192,
"AES-192-KW",
0,
0,
16,
&kw_aes_info
};
static const mbedtls_cipher_info_t aes_256_nist_kw_info = {
MBEDTLS_CIPHER_AES_256_KW,
MBEDTLS_MODE_KW,
256,
"AES-256-KW",
0,
0,
16,
&kw_aes_info
};
static const mbedtls_cipher_info_t aes_128_nist_kwp_info = {
MBEDTLS_CIPHER_AES_128_KWP,
MBEDTLS_MODE_KWP,
128,
"AES-128-KWP",
0,
0,
16,
&kw_aes_info
};
static const mbedtls_cipher_info_t aes_192_nist_kwp_info = {
MBEDTLS_CIPHER_AES_192_KWP,
MBEDTLS_MODE_KWP,
192,
"AES-192-KWP",
0,
0,
16,
&kw_aes_info
};
static const mbedtls_cipher_info_t aes_256_nist_kwp_info = {
MBEDTLS_CIPHER_AES_256_KWP,
MBEDTLS_MODE_KWP,
256,
"AES-256-KWP",
0,
0,
16,
&kw_aes_info
};
#endif /* MBEDTLS_NIST_KW_C */
const mbedtls_cipher_definition_t mbedtls_cipher_definitions[] =
{
#if defined(MBEDTLS_AES_C)
{ MBEDTLS_CIPHER_AES_128_ECB, &aes_128_ecb_info },
{ MBEDTLS_CIPHER_AES_192_ECB, &aes_192_ecb_info },
{ MBEDTLS_CIPHER_AES_256_ECB, &aes_256_ecb_info },
#if defined(MBEDTLS_CIPHER_MODE_CBC)
{ MBEDTLS_CIPHER_AES_128_CBC, &aes_128_cbc_info },
{ MBEDTLS_CIPHER_AES_192_CBC, &aes_192_cbc_info },
{ MBEDTLS_CIPHER_AES_256_CBC, &aes_256_cbc_info },
#endif
#if defined(MBEDTLS_CIPHER_MODE_CFB)
{ MBEDTLS_CIPHER_AES_128_CFB128, &aes_128_cfb128_info },
{ MBEDTLS_CIPHER_AES_192_CFB128, &aes_192_cfb128_info },
{ MBEDTLS_CIPHER_AES_256_CFB128, &aes_256_cfb128_info },
#endif
#if defined(MBEDTLS_CIPHER_MODE_OFB)
{ MBEDTLS_CIPHER_AES_128_OFB, &aes_128_ofb_info },
{ MBEDTLS_CIPHER_AES_192_OFB, &aes_192_ofb_info },
{ MBEDTLS_CIPHER_AES_256_OFB, &aes_256_ofb_info },
#endif
#if defined(MBEDTLS_CIPHER_MODE_CTR)
{ MBEDTLS_CIPHER_AES_128_CTR, &aes_128_ctr_info },
{ MBEDTLS_CIPHER_AES_192_CTR, &aes_192_ctr_info },
{ MBEDTLS_CIPHER_AES_256_CTR, &aes_256_ctr_info },
#endif
#if defined(MBEDTLS_CIPHER_MODE_XTS)
{ MBEDTLS_CIPHER_AES_128_XTS, &aes_128_xts_info },
{ MBEDTLS_CIPHER_AES_256_XTS, &aes_256_xts_info },
#endif
#if defined(MBEDTLS_GCM_C)
{ MBEDTLS_CIPHER_AES_128_GCM, &aes_128_gcm_info },
{ MBEDTLS_CIPHER_AES_192_GCM, &aes_192_gcm_info },
{ MBEDTLS_CIPHER_AES_256_GCM, &aes_256_gcm_info },
#endif
#if defined(MBEDTLS_CCM_C)
{ MBEDTLS_CIPHER_AES_128_CCM, &aes_128_ccm_info },
{ MBEDTLS_CIPHER_AES_192_CCM, &aes_192_ccm_info },
{ MBEDTLS_CIPHER_AES_256_CCM, &aes_256_ccm_info },
#endif
#endif /* MBEDTLS_AES_C */
#if defined(MBEDTLS_ARC4_C)
{ MBEDTLS_CIPHER_ARC4_128, &arc4_128_info },
#endif
#if defined(MBEDTLS_BLOWFISH_C)
{ MBEDTLS_CIPHER_BLOWFISH_ECB, &blowfish_ecb_info },
#if defined(MBEDTLS_CIPHER_MODE_CBC)
{ MBEDTLS_CIPHER_BLOWFISH_CBC, &blowfish_cbc_info },
#endif
#if defined(MBEDTLS_CIPHER_MODE_CFB)
{ MBEDTLS_CIPHER_BLOWFISH_CFB64, &blowfish_cfb64_info },
#endif
#if defined(MBEDTLS_CIPHER_MODE_CTR)
{ MBEDTLS_CIPHER_BLOWFISH_CTR, &blowfish_ctr_info },
#endif
#endif /* MBEDTLS_BLOWFISH_C */
#if defined(MBEDTLS_CAMELLIA_C)
{ MBEDTLS_CIPHER_CAMELLIA_128_ECB, &camellia_128_ecb_info },
{ MBEDTLS_CIPHER_CAMELLIA_192_ECB, &camellia_192_ecb_info },
{ MBEDTLS_CIPHER_CAMELLIA_256_ECB, &camellia_256_ecb_info },
#if defined(MBEDTLS_CIPHER_MODE_CBC)
{ MBEDTLS_CIPHER_CAMELLIA_128_CBC, &camellia_128_cbc_info },
{ MBEDTLS_CIPHER_CAMELLIA_192_CBC, &camellia_192_cbc_info },
{ MBEDTLS_CIPHER_CAMELLIA_256_CBC, &camellia_256_cbc_info },
#endif
#if defined(MBEDTLS_CIPHER_MODE_CFB)
{ MBEDTLS_CIPHER_CAMELLIA_128_CFB128, &camellia_128_cfb128_info },
{ MBEDTLS_CIPHER_CAMELLIA_192_CFB128, &camellia_192_cfb128_info },
{ MBEDTLS_CIPHER_CAMELLIA_256_CFB128, &camellia_256_cfb128_info },
#endif
#if defined(MBEDTLS_CIPHER_MODE_CTR)
{ MBEDTLS_CIPHER_CAMELLIA_128_CTR, &camellia_128_ctr_info },
{ MBEDTLS_CIPHER_CAMELLIA_192_CTR, &camellia_192_ctr_info },
{ MBEDTLS_CIPHER_CAMELLIA_256_CTR, &camellia_256_ctr_info },
#endif
#if defined(MBEDTLS_GCM_C)
{ MBEDTLS_CIPHER_CAMELLIA_128_GCM, &camellia_128_gcm_info },
{ MBEDTLS_CIPHER_CAMELLIA_192_GCM, &camellia_192_gcm_info },
{ MBEDTLS_CIPHER_CAMELLIA_256_GCM, &camellia_256_gcm_info },
#endif
#if defined(MBEDTLS_CCM_C)
{ MBEDTLS_CIPHER_CAMELLIA_128_CCM, &camellia_128_ccm_info },
{ MBEDTLS_CIPHER_CAMELLIA_192_CCM, &camellia_192_ccm_info },
{ MBEDTLS_CIPHER_CAMELLIA_256_CCM, &camellia_256_ccm_info },
#endif
#endif /* MBEDTLS_CAMELLIA_C */
#if defined(MBEDTLS_ARIA_C)
{ MBEDTLS_CIPHER_ARIA_128_ECB, &aria_128_ecb_info },
{ MBEDTLS_CIPHER_ARIA_192_ECB, &aria_192_ecb_info },
{ MBEDTLS_CIPHER_ARIA_256_ECB, &aria_256_ecb_info },
#if defined(MBEDTLS_CIPHER_MODE_CBC)
{ MBEDTLS_CIPHER_ARIA_128_CBC, &aria_128_cbc_info },
{ MBEDTLS_CIPHER_ARIA_192_CBC, &aria_192_cbc_info },
{ MBEDTLS_CIPHER_ARIA_256_CBC, &aria_256_cbc_info },
#endif
#if defined(MBEDTLS_CIPHER_MODE_CFB)
{ MBEDTLS_CIPHER_ARIA_128_CFB128, &aria_128_cfb128_info },
{ MBEDTLS_CIPHER_ARIA_192_CFB128, &aria_192_cfb128_info },
{ MBEDTLS_CIPHER_ARIA_256_CFB128, &aria_256_cfb128_info },
#endif
#if defined(MBEDTLS_CIPHER_MODE_CTR)
{ MBEDTLS_CIPHER_ARIA_128_CTR, &aria_128_ctr_info },
{ MBEDTLS_CIPHER_ARIA_192_CTR, &aria_192_ctr_info },
{ MBEDTLS_CIPHER_ARIA_256_CTR, &aria_256_ctr_info },
#endif
#if defined(MBEDTLS_GCM_C)
{ MBEDTLS_CIPHER_ARIA_128_GCM, &aria_128_gcm_info },
{ MBEDTLS_CIPHER_ARIA_192_GCM, &aria_192_gcm_info },
{ MBEDTLS_CIPHER_ARIA_256_GCM, &aria_256_gcm_info },
#endif
#if defined(MBEDTLS_CCM_C)
{ MBEDTLS_CIPHER_ARIA_128_CCM, &aria_128_ccm_info },
{ MBEDTLS_CIPHER_ARIA_192_CCM, &aria_192_ccm_info },
{ MBEDTLS_CIPHER_ARIA_256_CCM, &aria_256_ccm_info },
#endif
#endif /* MBEDTLS_ARIA_C */
#if defined(MBEDTLS_DES_C)
{ MBEDTLS_CIPHER_DES_ECB, &des_ecb_info },
{ MBEDTLS_CIPHER_DES_EDE_ECB, &des_ede_ecb_info },
{ MBEDTLS_CIPHER_DES_EDE3_ECB, &des_ede3_ecb_info },
#if defined(MBEDTLS_CIPHER_MODE_CBC)
{ MBEDTLS_CIPHER_DES_CBC, &des_cbc_info },
{ MBEDTLS_CIPHER_DES_EDE_CBC, &des_ede_cbc_info },
{ MBEDTLS_CIPHER_DES_EDE3_CBC, &des_ede3_cbc_info },
#endif
#endif /* MBEDTLS_DES_C */
#if defined(MBEDTLS_CHACHA20_C)
{ MBEDTLS_CIPHER_CHACHA20, &chacha20_info },
#endif
#if defined(MBEDTLS_CHACHAPOLY_C)
{ MBEDTLS_CIPHER_CHACHA20_POLY1305, &chachapoly_info },
#endif
#if defined(MBEDTLS_NIST_KW_C)
{ MBEDTLS_CIPHER_AES_128_KW, &aes_128_nist_kw_info },
{ MBEDTLS_CIPHER_AES_192_KW, &aes_192_nist_kw_info },
{ MBEDTLS_CIPHER_AES_256_KW, &aes_256_nist_kw_info },
{ MBEDTLS_CIPHER_AES_128_KWP, &aes_128_nist_kwp_info },
{ MBEDTLS_CIPHER_AES_192_KWP, &aes_192_nist_kwp_info },
{ MBEDTLS_CIPHER_AES_256_KWP, &aes_256_nist_kwp_info },
#endif
#if defined(MBEDTLS_CIPHER_NULL_CIPHER)
{ MBEDTLS_CIPHER_NULL, &null_cipher_info },
#endif /* MBEDTLS_CIPHER_NULL_CIPHER */
{ MBEDTLS_CIPHER_NONE, NULL }
};
#define NUM_CIPHERS ( sizeof(mbedtls_cipher_definitions) / \
sizeof(mbedtls_cipher_definitions[0]) )
int mbedtls_cipher_supported[NUM_CIPHERS];
#endif /* MBEDTLS_CIPHER_C */
|
0 | repos/gpt4all.zig/src/zig-libcurl/zig-mbedtls/mbedtls | repos/gpt4all.zig/src/zig-libcurl/zig-mbedtls/mbedtls/library/des.c | /*
* FIPS-46-3 compliant Triple-DES implementation
*
* Copyright The Mbed TLS Contributors
* SPDX-License-Identifier: Apache-2.0
*
* 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.
*/
/*
* DES, on which TDES is based, was originally designed by Horst Feistel
* at IBM in 1974, and was adopted as a standard by NIST (formerly NBS).
*
* http://csrc.nist.gov/publications/fips/fips46-3/fips46-3.pdf
*/
#include "common.h"
#if defined(MBEDTLS_DES_C)
#include "mbedtls/des.h"
#include "mbedtls/platform_util.h"
#include <string.h>
#if defined(MBEDTLS_SELF_TEST)
#if defined(MBEDTLS_PLATFORM_C)
#include "mbedtls/platform.h"
#else
#include <stdio.h>
#define mbedtls_printf printf
#endif /* MBEDTLS_PLATFORM_C */
#endif /* MBEDTLS_SELF_TEST */
#if !defined(MBEDTLS_DES_ALT)
/*
* 32-bit integer manipulation macros (big endian)
*/
#ifndef GET_UINT32_BE
#define GET_UINT32_BE(n,b,i) \
{ \
(n) = ( (uint32_t) (b)[(i) ] << 24 ) \
| ( (uint32_t) (b)[(i) + 1] << 16 ) \
| ( (uint32_t) (b)[(i) + 2] << 8 ) \
| ( (uint32_t) (b)[(i) + 3] ); \
}
#endif
#ifndef PUT_UINT32_BE
#define PUT_UINT32_BE(n,b,i) \
{ \
(b)[(i) ] = (unsigned char) ( (n) >> 24 ); \
(b)[(i) + 1] = (unsigned char) ( (n) >> 16 ); \
(b)[(i) + 2] = (unsigned char) ( (n) >> 8 ); \
(b)[(i) + 3] = (unsigned char) ( (n) ); \
}
#endif
/*
* Expanded DES S-boxes
*/
static const uint32_t SB1[64] =
{
0x01010400, 0x00000000, 0x00010000, 0x01010404,
0x01010004, 0x00010404, 0x00000004, 0x00010000,
0x00000400, 0x01010400, 0x01010404, 0x00000400,
0x01000404, 0x01010004, 0x01000000, 0x00000004,
0x00000404, 0x01000400, 0x01000400, 0x00010400,
0x00010400, 0x01010000, 0x01010000, 0x01000404,
0x00010004, 0x01000004, 0x01000004, 0x00010004,
0x00000000, 0x00000404, 0x00010404, 0x01000000,
0x00010000, 0x01010404, 0x00000004, 0x01010000,
0x01010400, 0x01000000, 0x01000000, 0x00000400,
0x01010004, 0x00010000, 0x00010400, 0x01000004,
0x00000400, 0x00000004, 0x01000404, 0x00010404,
0x01010404, 0x00010004, 0x01010000, 0x01000404,
0x01000004, 0x00000404, 0x00010404, 0x01010400,
0x00000404, 0x01000400, 0x01000400, 0x00000000,
0x00010004, 0x00010400, 0x00000000, 0x01010004
};
static const uint32_t SB2[64] =
{
0x80108020, 0x80008000, 0x00008000, 0x00108020,
0x00100000, 0x00000020, 0x80100020, 0x80008020,
0x80000020, 0x80108020, 0x80108000, 0x80000000,
0x80008000, 0x00100000, 0x00000020, 0x80100020,
0x00108000, 0x00100020, 0x80008020, 0x00000000,
0x80000000, 0x00008000, 0x00108020, 0x80100000,
0x00100020, 0x80000020, 0x00000000, 0x00108000,
0x00008020, 0x80108000, 0x80100000, 0x00008020,
0x00000000, 0x00108020, 0x80100020, 0x00100000,
0x80008020, 0x80100000, 0x80108000, 0x00008000,
0x80100000, 0x80008000, 0x00000020, 0x80108020,
0x00108020, 0x00000020, 0x00008000, 0x80000000,
0x00008020, 0x80108000, 0x00100000, 0x80000020,
0x00100020, 0x80008020, 0x80000020, 0x00100020,
0x00108000, 0x00000000, 0x80008000, 0x00008020,
0x80000000, 0x80100020, 0x80108020, 0x00108000
};
static const uint32_t SB3[64] =
{
0x00000208, 0x08020200, 0x00000000, 0x08020008,
0x08000200, 0x00000000, 0x00020208, 0x08000200,
0x00020008, 0x08000008, 0x08000008, 0x00020000,
0x08020208, 0x00020008, 0x08020000, 0x00000208,
0x08000000, 0x00000008, 0x08020200, 0x00000200,
0x00020200, 0x08020000, 0x08020008, 0x00020208,
0x08000208, 0x00020200, 0x00020000, 0x08000208,
0x00000008, 0x08020208, 0x00000200, 0x08000000,
0x08020200, 0x08000000, 0x00020008, 0x00000208,
0x00020000, 0x08020200, 0x08000200, 0x00000000,
0x00000200, 0x00020008, 0x08020208, 0x08000200,
0x08000008, 0x00000200, 0x00000000, 0x08020008,
0x08000208, 0x00020000, 0x08000000, 0x08020208,
0x00000008, 0x00020208, 0x00020200, 0x08000008,
0x08020000, 0x08000208, 0x00000208, 0x08020000,
0x00020208, 0x00000008, 0x08020008, 0x00020200
};
static const uint32_t SB4[64] =
{
0x00802001, 0x00002081, 0x00002081, 0x00000080,
0x00802080, 0x00800081, 0x00800001, 0x00002001,
0x00000000, 0x00802000, 0x00802000, 0x00802081,
0x00000081, 0x00000000, 0x00800080, 0x00800001,
0x00000001, 0x00002000, 0x00800000, 0x00802001,
0x00000080, 0x00800000, 0x00002001, 0x00002080,
0x00800081, 0x00000001, 0x00002080, 0x00800080,
0x00002000, 0x00802080, 0x00802081, 0x00000081,
0x00800080, 0x00800001, 0x00802000, 0x00802081,
0x00000081, 0x00000000, 0x00000000, 0x00802000,
0x00002080, 0x00800080, 0x00800081, 0x00000001,
0x00802001, 0x00002081, 0x00002081, 0x00000080,
0x00802081, 0x00000081, 0x00000001, 0x00002000,
0x00800001, 0x00002001, 0x00802080, 0x00800081,
0x00002001, 0x00002080, 0x00800000, 0x00802001,
0x00000080, 0x00800000, 0x00002000, 0x00802080
};
static const uint32_t SB5[64] =
{
0x00000100, 0x02080100, 0x02080000, 0x42000100,
0x00080000, 0x00000100, 0x40000000, 0x02080000,
0x40080100, 0x00080000, 0x02000100, 0x40080100,
0x42000100, 0x42080000, 0x00080100, 0x40000000,
0x02000000, 0x40080000, 0x40080000, 0x00000000,
0x40000100, 0x42080100, 0x42080100, 0x02000100,
0x42080000, 0x40000100, 0x00000000, 0x42000000,
0x02080100, 0x02000000, 0x42000000, 0x00080100,
0x00080000, 0x42000100, 0x00000100, 0x02000000,
0x40000000, 0x02080000, 0x42000100, 0x40080100,
0x02000100, 0x40000000, 0x42080000, 0x02080100,
0x40080100, 0x00000100, 0x02000000, 0x42080000,
0x42080100, 0x00080100, 0x42000000, 0x42080100,
0x02080000, 0x00000000, 0x40080000, 0x42000000,
0x00080100, 0x02000100, 0x40000100, 0x00080000,
0x00000000, 0x40080000, 0x02080100, 0x40000100
};
static const uint32_t SB6[64] =
{
0x20000010, 0x20400000, 0x00004000, 0x20404010,
0x20400000, 0x00000010, 0x20404010, 0x00400000,
0x20004000, 0x00404010, 0x00400000, 0x20000010,
0x00400010, 0x20004000, 0x20000000, 0x00004010,
0x00000000, 0x00400010, 0x20004010, 0x00004000,
0x00404000, 0x20004010, 0x00000010, 0x20400010,
0x20400010, 0x00000000, 0x00404010, 0x20404000,
0x00004010, 0x00404000, 0x20404000, 0x20000000,
0x20004000, 0x00000010, 0x20400010, 0x00404000,
0x20404010, 0x00400000, 0x00004010, 0x20000010,
0x00400000, 0x20004000, 0x20000000, 0x00004010,
0x20000010, 0x20404010, 0x00404000, 0x20400000,
0x00404010, 0x20404000, 0x00000000, 0x20400010,
0x00000010, 0x00004000, 0x20400000, 0x00404010,
0x00004000, 0x00400010, 0x20004010, 0x00000000,
0x20404000, 0x20000000, 0x00400010, 0x20004010
};
static const uint32_t SB7[64] =
{
0x00200000, 0x04200002, 0x04000802, 0x00000000,
0x00000800, 0x04000802, 0x00200802, 0x04200800,
0x04200802, 0x00200000, 0x00000000, 0x04000002,
0x00000002, 0x04000000, 0x04200002, 0x00000802,
0x04000800, 0x00200802, 0x00200002, 0x04000800,
0x04000002, 0x04200000, 0x04200800, 0x00200002,
0x04200000, 0x00000800, 0x00000802, 0x04200802,
0x00200800, 0x00000002, 0x04000000, 0x00200800,
0x04000000, 0x00200800, 0x00200000, 0x04000802,
0x04000802, 0x04200002, 0x04200002, 0x00000002,
0x00200002, 0x04000000, 0x04000800, 0x00200000,
0x04200800, 0x00000802, 0x00200802, 0x04200800,
0x00000802, 0x04000002, 0x04200802, 0x04200000,
0x00200800, 0x00000000, 0x00000002, 0x04200802,
0x00000000, 0x00200802, 0x04200000, 0x00000800,
0x04000002, 0x04000800, 0x00000800, 0x00200002
};
static const uint32_t SB8[64] =
{
0x10001040, 0x00001000, 0x00040000, 0x10041040,
0x10000000, 0x10001040, 0x00000040, 0x10000000,
0x00040040, 0x10040000, 0x10041040, 0x00041000,
0x10041000, 0x00041040, 0x00001000, 0x00000040,
0x10040000, 0x10000040, 0x10001000, 0x00001040,
0x00041000, 0x00040040, 0x10040040, 0x10041000,
0x00001040, 0x00000000, 0x00000000, 0x10040040,
0x10000040, 0x10001000, 0x00041040, 0x00040000,
0x00041040, 0x00040000, 0x10041000, 0x00001000,
0x00000040, 0x10040040, 0x00001000, 0x00041040,
0x10001000, 0x00000040, 0x10000040, 0x10040000,
0x10040040, 0x10000000, 0x00040000, 0x10001040,
0x00000000, 0x10041040, 0x00040040, 0x10000040,
0x10040000, 0x10001000, 0x10001040, 0x00000000,
0x10041040, 0x00041000, 0x00041000, 0x00001040,
0x00001040, 0x00040040, 0x10000000, 0x10041000
};
/*
* PC1: left and right halves bit-swap
*/
static const uint32_t LHs[16] =
{
0x00000000, 0x00000001, 0x00000100, 0x00000101,
0x00010000, 0x00010001, 0x00010100, 0x00010101,
0x01000000, 0x01000001, 0x01000100, 0x01000101,
0x01010000, 0x01010001, 0x01010100, 0x01010101
};
static const uint32_t RHs[16] =
{
0x00000000, 0x01000000, 0x00010000, 0x01010000,
0x00000100, 0x01000100, 0x00010100, 0x01010100,
0x00000001, 0x01000001, 0x00010001, 0x01010001,
0x00000101, 0x01000101, 0x00010101, 0x01010101,
};
/*
* Initial Permutation macro
*/
#define DES_IP(X,Y) \
do \
{ \
T = (((X) >> 4) ^ (Y)) & 0x0F0F0F0F; (Y) ^= T; (X) ^= (T << 4); \
T = (((X) >> 16) ^ (Y)) & 0x0000FFFF; (Y) ^= T; (X) ^= (T << 16); \
T = (((Y) >> 2) ^ (X)) & 0x33333333; (X) ^= T; (Y) ^= (T << 2); \
T = (((Y) >> 8) ^ (X)) & 0x00FF00FF; (X) ^= T; (Y) ^= (T << 8); \
(Y) = (((Y) << 1) | ((Y) >> 31)) & 0xFFFFFFFF; \
T = ((X) ^ (Y)) & 0xAAAAAAAA; (Y) ^= T; (X) ^= T; \
(X) = (((X) << 1) | ((X) >> 31)) & 0xFFFFFFFF; \
} while( 0 )
/*
* Final Permutation macro
*/
#define DES_FP(X,Y) \
do \
{ \
(X) = (((X) << 31) | ((X) >> 1)) & 0xFFFFFFFF; \
T = ((X) ^ (Y)) & 0xAAAAAAAA; (X) ^= T; (Y) ^= T; \
(Y) = (((Y) << 31) | ((Y) >> 1)) & 0xFFFFFFFF; \
T = (((Y) >> 8) ^ (X)) & 0x00FF00FF; (X) ^= T; (Y) ^= (T << 8); \
T = (((Y) >> 2) ^ (X)) & 0x33333333; (X) ^= T; (Y) ^= (T << 2); \
T = (((X) >> 16) ^ (Y)) & 0x0000FFFF; (Y) ^= T; (X) ^= (T << 16); \
T = (((X) >> 4) ^ (Y)) & 0x0F0F0F0F; (Y) ^= T; (X) ^= (T << 4); \
} while( 0 )
/*
* DES round macro
*/
#define DES_ROUND(X,Y) \
do \
{ \
T = *SK++ ^ (X); \
(Y) ^= SB8[ (T ) & 0x3F ] ^ \
SB6[ (T >> 8) & 0x3F ] ^ \
SB4[ (T >> 16) & 0x3F ] ^ \
SB2[ (T >> 24) & 0x3F ]; \
\
T = *SK++ ^ (((X) << 28) | ((X) >> 4)); \
(Y) ^= SB7[ (T ) & 0x3F ] ^ \
SB5[ (T >> 8) & 0x3F ] ^ \
SB3[ (T >> 16) & 0x3F ] ^ \
SB1[ (T >> 24) & 0x3F ]; \
} while( 0 )
#define SWAP(a,b) \
do \
{ \
uint32_t t = (a); (a) = (b); (b) = t; t = 0; \
} while( 0 )
void mbedtls_des_init( mbedtls_des_context *ctx )
{
memset( ctx, 0, sizeof( mbedtls_des_context ) );
}
void mbedtls_des_free( mbedtls_des_context *ctx )
{
if( ctx == NULL )
return;
mbedtls_platform_zeroize( ctx, sizeof( mbedtls_des_context ) );
}
void mbedtls_des3_init( mbedtls_des3_context *ctx )
{
memset( ctx, 0, sizeof( mbedtls_des3_context ) );
}
void mbedtls_des3_free( mbedtls_des3_context *ctx )
{
if( ctx == NULL )
return;
mbedtls_platform_zeroize( ctx, sizeof( mbedtls_des3_context ) );
}
static const unsigned char odd_parity_table[128] = { 1, 2, 4, 7, 8,
11, 13, 14, 16, 19, 21, 22, 25, 26, 28, 31, 32, 35, 37, 38, 41, 42, 44,
47, 49, 50, 52, 55, 56, 59, 61, 62, 64, 67, 69, 70, 73, 74, 76, 79, 81,
82, 84, 87, 88, 91, 93, 94, 97, 98, 100, 103, 104, 107, 109, 110, 112,
115, 117, 118, 121, 122, 124, 127, 128, 131, 133, 134, 137, 138, 140,
143, 145, 146, 148, 151, 152, 155, 157, 158, 161, 162, 164, 167, 168,
171, 173, 174, 176, 179, 181, 182, 185, 186, 188, 191, 193, 194, 196,
199, 200, 203, 205, 206, 208, 211, 213, 214, 217, 218, 220, 223, 224,
227, 229, 230, 233, 234, 236, 239, 241, 242, 244, 247, 248, 251, 253,
254 };
void mbedtls_des_key_set_parity( unsigned char key[MBEDTLS_DES_KEY_SIZE] )
{
int i;
for( i = 0; i < MBEDTLS_DES_KEY_SIZE; i++ )
key[i] = odd_parity_table[key[i] / 2];
}
/*
* Check the given key's parity, returns 1 on failure, 0 on SUCCESS
*/
int mbedtls_des_key_check_key_parity( const unsigned char key[MBEDTLS_DES_KEY_SIZE] )
{
int i;
for( i = 0; i < MBEDTLS_DES_KEY_SIZE; i++ )
if( key[i] != odd_parity_table[key[i] / 2] )
return( 1 );
return( 0 );
}
/*
* Table of weak and semi-weak keys
*
* Source: http://en.wikipedia.org/wiki/Weak_key
*
* Weak:
* Alternating ones + zeros (0x0101010101010101)
* Alternating 'F' + 'E' (0xFEFEFEFEFEFEFEFE)
* '0xE0E0E0E0F1F1F1F1'
* '0x1F1F1F1F0E0E0E0E'
*
* Semi-weak:
* 0x011F011F010E010E and 0x1F011F010E010E01
* 0x01E001E001F101F1 and 0xE001E001F101F101
* 0x01FE01FE01FE01FE and 0xFE01FE01FE01FE01
* 0x1FE01FE00EF10EF1 and 0xE01FE01FF10EF10E
* 0x1FFE1FFE0EFE0EFE and 0xFE1FFE1FFE0EFE0E
* 0xE0FEE0FEF1FEF1FE and 0xFEE0FEE0FEF1FEF1
*
*/
#define WEAK_KEY_COUNT 16
static const unsigned char weak_key_table[WEAK_KEY_COUNT][MBEDTLS_DES_KEY_SIZE] =
{
{ 0x01, 0x01, 0x01, 0x01, 0x01, 0x01, 0x01, 0x01 },
{ 0xFE, 0xFE, 0xFE, 0xFE, 0xFE, 0xFE, 0xFE, 0xFE },
{ 0x1F, 0x1F, 0x1F, 0x1F, 0x0E, 0x0E, 0x0E, 0x0E },
{ 0xE0, 0xE0, 0xE0, 0xE0, 0xF1, 0xF1, 0xF1, 0xF1 },
{ 0x01, 0x1F, 0x01, 0x1F, 0x01, 0x0E, 0x01, 0x0E },
{ 0x1F, 0x01, 0x1F, 0x01, 0x0E, 0x01, 0x0E, 0x01 },
{ 0x01, 0xE0, 0x01, 0xE0, 0x01, 0xF1, 0x01, 0xF1 },
{ 0xE0, 0x01, 0xE0, 0x01, 0xF1, 0x01, 0xF1, 0x01 },
{ 0x01, 0xFE, 0x01, 0xFE, 0x01, 0xFE, 0x01, 0xFE },
{ 0xFE, 0x01, 0xFE, 0x01, 0xFE, 0x01, 0xFE, 0x01 },
{ 0x1F, 0xE0, 0x1F, 0xE0, 0x0E, 0xF1, 0x0E, 0xF1 },
{ 0xE0, 0x1F, 0xE0, 0x1F, 0xF1, 0x0E, 0xF1, 0x0E },
{ 0x1F, 0xFE, 0x1F, 0xFE, 0x0E, 0xFE, 0x0E, 0xFE },
{ 0xFE, 0x1F, 0xFE, 0x1F, 0xFE, 0x0E, 0xFE, 0x0E },
{ 0xE0, 0xFE, 0xE0, 0xFE, 0xF1, 0xFE, 0xF1, 0xFE },
{ 0xFE, 0xE0, 0xFE, 0xE0, 0xFE, 0xF1, 0xFE, 0xF1 }
};
int mbedtls_des_key_check_weak( const unsigned char key[MBEDTLS_DES_KEY_SIZE] )
{
int i;
for( i = 0; i < WEAK_KEY_COUNT; i++ )
if( memcmp( weak_key_table[i], key, MBEDTLS_DES_KEY_SIZE) == 0 )
return( 1 );
return( 0 );
}
#if !defined(MBEDTLS_DES_SETKEY_ALT)
void mbedtls_des_setkey( uint32_t SK[32], const unsigned char key[MBEDTLS_DES_KEY_SIZE] )
{
int i;
uint32_t X, Y, T;
GET_UINT32_BE( X, key, 0 );
GET_UINT32_BE( Y, key, 4 );
/*
* Permuted Choice 1
*/
T = ((Y >> 4) ^ X) & 0x0F0F0F0F; X ^= T; Y ^= (T << 4);
T = ((Y ) ^ X) & 0x10101010; X ^= T; Y ^= (T );
X = (LHs[ (X ) & 0xF] << 3) | (LHs[ (X >> 8) & 0xF ] << 2)
| (LHs[ (X >> 16) & 0xF] << 1) | (LHs[ (X >> 24) & 0xF ] )
| (LHs[ (X >> 5) & 0xF] << 7) | (LHs[ (X >> 13) & 0xF ] << 6)
| (LHs[ (X >> 21) & 0xF] << 5) | (LHs[ (X >> 29) & 0xF ] << 4);
Y = (RHs[ (Y >> 1) & 0xF] << 3) | (RHs[ (Y >> 9) & 0xF ] << 2)
| (RHs[ (Y >> 17) & 0xF] << 1) | (RHs[ (Y >> 25) & 0xF ] )
| (RHs[ (Y >> 4) & 0xF] << 7) | (RHs[ (Y >> 12) & 0xF ] << 6)
| (RHs[ (Y >> 20) & 0xF] << 5) | (RHs[ (Y >> 28) & 0xF ] << 4);
X &= 0x0FFFFFFF;
Y &= 0x0FFFFFFF;
/*
* calculate subkeys
*/
for( i = 0; i < 16; i++ )
{
if( i < 2 || i == 8 || i == 15 )
{
X = ((X << 1) | (X >> 27)) & 0x0FFFFFFF;
Y = ((Y << 1) | (Y >> 27)) & 0x0FFFFFFF;
}
else
{
X = ((X << 2) | (X >> 26)) & 0x0FFFFFFF;
Y = ((Y << 2) | (Y >> 26)) & 0x0FFFFFFF;
}
*SK++ = ((X << 4) & 0x24000000) | ((X << 28) & 0x10000000)
| ((X << 14) & 0x08000000) | ((X << 18) & 0x02080000)
| ((X << 6) & 0x01000000) | ((X << 9) & 0x00200000)
| ((X >> 1) & 0x00100000) | ((X << 10) & 0x00040000)
| ((X << 2) & 0x00020000) | ((X >> 10) & 0x00010000)
| ((Y >> 13) & 0x00002000) | ((Y >> 4) & 0x00001000)
| ((Y << 6) & 0x00000800) | ((Y >> 1) & 0x00000400)
| ((Y >> 14) & 0x00000200) | ((Y ) & 0x00000100)
| ((Y >> 5) & 0x00000020) | ((Y >> 10) & 0x00000010)
| ((Y >> 3) & 0x00000008) | ((Y >> 18) & 0x00000004)
| ((Y >> 26) & 0x00000002) | ((Y >> 24) & 0x00000001);
*SK++ = ((X << 15) & 0x20000000) | ((X << 17) & 0x10000000)
| ((X << 10) & 0x08000000) | ((X << 22) & 0x04000000)
| ((X >> 2) & 0x02000000) | ((X << 1) & 0x01000000)
| ((X << 16) & 0x00200000) | ((X << 11) & 0x00100000)
| ((X << 3) & 0x00080000) | ((X >> 6) & 0x00040000)
| ((X << 15) & 0x00020000) | ((X >> 4) & 0x00010000)
| ((Y >> 2) & 0x00002000) | ((Y << 8) & 0x00001000)
| ((Y >> 14) & 0x00000808) | ((Y >> 9) & 0x00000400)
| ((Y ) & 0x00000200) | ((Y << 7) & 0x00000100)
| ((Y >> 7) & 0x00000020) | ((Y >> 3) & 0x00000011)
| ((Y << 2) & 0x00000004) | ((Y >> 21) & 0x00000002);
}
}
#endif /* !MBEDTLS_DES_SETKEY_ALT */
/*
* DES key schedule (56-bit, encryption)
*/
int mbedtls_des_setkey_enc( mbedtls_des_context *ctx, const unsigned char key[MBEDTLS_DES_KEY_SIZE] )
{
mbedtls_des_setkey( ctx->sk, key );
return( 0 );
}
/*
* DES key schedule (56-bit, decryption)
*/
int mbedtls_des_setkey_dec( mbedtls_des_context *ctx, const unsigned char key[MBEDTLS_DES_KEY_SIZE] )
{
int i;
mbedtls_des_setkey( ctx->sk, key );
for( i = 0; i < 16; i += 2 )
{
SWAP( ctx->sk[i ], ctx->sk[30 - i] );
SWAP( ctx->sk[i + 1], ctx->sk[31 - i] );
}
return( 0 );
}
static void des3_set2key( uint32_t esk[96],
uint32_t dsk[96],
const unsigned char key[MBEDTLS_DES_KEY_SIZE*2] )
{
int i;
mbedtls_des_setkey( esk, key );
mbedtls_des_setkey( dsk + 32, key + 8 );
for( i = 0; i < 32; i += 2 )
{
dsk[i ] = esk[30 - i];
dsk[i + 1] = esk[31 - i];
esk[i + 32] = dsk[62 - i];
esk[i + 33] = dsk[63 - i];
esk[i + 64] = esk[i ];
esk[i + 65] = esk[i + 1];
dsk[i + 64] = dsk[i ];
dsk[i + 65] = dsk[i + 1];
}
}
/*
* Triple-DES key schedule (112-bit, encryption)
*/
int mbedtls_des3_set2key_enc( mbedtls_des3_context *ctx,
const unsigned char key[MBEDTLS_DES_KEY_SIZE * 2] )
{
uint32_t sk[96];
des3_set2key( ctx->sk, sk, key );
mbedtls_platform_zeroize( sk, sizeof( sk ) );
return( 0 );
}
/*
* Triple-DES key schedule (112-bit, decryption)
*/
int mbedtls_des3_set2key_dec( mbedtls_des3_context *ctx,
const unsigned char key[MBEDTLS_DES_KEY_SIZE * 2] )
{
uint32_t sk[96];
des3_set2key( sk, ctx->sk, key );
mbedtls_platform_zeroize( sk, sizeof( sk ) );
return( 0 );
}
static void des3_set3key( uint32_t esk[96],
uint32_t dsk[96],
const unsigned char key[24] )
{
int i;
mbedtls_des_setkey( esk, key );
mbedtls_des_setkey( dsk + 32, key + 8 );
mbedtls_des_setkey( esk + 64, key + 16 );
for( i = 0; i < 32; i += 2 )
{
dsk[i ] = esk[94 - i];
dsk[i + 1] = esk[95 - i];
esk[i + 32] = dsk[62 - i];
esk[i + 33] = dsk[63 - i];
dsk[i + 64] = esk[30 - i];
dsk[i + 65] = esk[31 - i];
}
}
/*
* Triple-DES key schedule (168-bit, encryption)
*/
int mbedtls_des3_set3key_enc( mbedtls_des3_context *ctx,
const unsigned char key[MBEDTLS_DES_KEY_SIZE * 3] )
{
uint32_t sk[96];
des3_set3key( ctx->sk, sk, key );
mbedtls_platform_zeroize( sk, sizeof( sk ) );
return( 0 );
}
/*
* Triple-DES key schedule (168-bit, decryption)
*/
int mbedtls_des3_set3key_dec( mbedtls_des3_context *ctx,
const unsigned char key[MBEDTLS_DES_KEY_SIZE * 3] )
{
uint32_t sk[96];
des3_set3key( sk, ctx->sk, key );
mbedtls_platform_zeroize( sk, sizeof( sk ) );
return( 0 );
}
/*
* DES-ECB block encryption/decryption
*/
#if !defined(MBEDTLS_DES_CRYPT_ECB_ALT)
int mbedtls_des_crypt_ecb( mbedtls_des_context *ctx,
const unsigned char input[8],
unsigned char output[8] )
{
int i;
uint32_t X, Y, T, *SK;
SK = ctx->sk;
GET_UINT32_BE( X, input, 0 );
GET_UINT32_BE( Y, input, 4 );
DES_IP( X, Y );
for( i = 0; i < 8; i++ )
{
DES_ROUND( Y, X );
DES_ROUND( X, Y );
}
DES_FP( Y, X );
PUT_UINT32_BE( Y, output, 0 );
PUT_UINT32_BE( X, output, 4 );
return( 0 );
}
#endif /* !MBEDTLS_DES_CRYPT_ECB_ALT */
#if defined(MBEDTLS_CIPHER_MODE_CBC)
/*
* DES-CBC buffer encryption/decryption
*/
int mbedtls_des_crypt_cbc( mbedtls_des_context *ctx,
int mode,
size_t length,
unsigned char iv[8],
const unsigned char *input,
unsigned char *output )
{
int i;
unsigned char temp[8];
if( length % 8 )
return( MBEDTLS_ERR_DES_INVALID_INPUT_LENGTH );
if( mode == MBEDTLS_DES_ENCRYPT )
{
while( length > 0 )
{
for( i = 0; i < 8; i++ )
output[i] = (unsigned char)( input[i] ^ iv[i] );
mbedtls_des_crypt_ecb( ctx, output, output );
memcpy( iv, output, 8 );
input += 8;
output += 8;
length -= 8;
}
}
else /* MBEDTLS_DES_DECRYPT */
{
while( length > 0 )
{
memcpy( temp, input, 8 );
mbedtls_des_crypt_ecb( ctx, input, output );
for( i = 0; i < 8; i++ )
output[i] = (unsigned char)( output[i] ^ iv[i] );
memcpy( iv, temp, 8 );
input += 8;
output += 8;
length -= 8;
}
}
return( 0 );
}
#endif /* MBEDTLS_CIPHER_MODE_CBC */
/*
* 3DES-ECB block encryption/decryption
*/
#if !defined(MBEDTLS_DES3_CRYPT_ECB_ALT)
int mbedtls_des3_crypt_ecb( mbedtls_des3_context *ctx,
const unsigned char input[8],
unsigned char output[8] )
{
int i;
uint32_t X, Y, T, *SK;
SK = ctx->sk;
GET_UINT32_BE( X, input, 0 );
GET_UINT32_BE( Y, input, 4 );
DES_IP( X, Y );
for( i = 0; i < 8; i++ )
{
DES_ROUND( Y, X );
DES_ROUND( X, Y );
}
for( i = 0; i < 8; i++ )
{
DES_ROUND( X, Y );
DES_ROUND( Y, X );
}
for( i = 0; i < 8; i++ )
{
DES_ROUND( Y, X );
DES_ROUND( X, Y );
}
DES_FP( Y, X );
PUT_UINT32_BE( Y, output, 0 );
PUT_UINT32_BE( X, output, 4 );
return( 0 );
}
#endif /* !MBEDTLS_DES3_CRYPT_ECB_ALT */
#if defined(MBEDTLS_CIPHER_MODE_CBC)
/*
* 3DES-CBC buffer encryption/decryption
*/
int mbedtls_des3_crypt_cbc( mbedtls_des3_context *ctx,
int mode,
size_t length,
unsigned char iv[8],
const unsigned char *input,
unsigned char *output )
{
int i;
unsigned char temp[8];
if( length % 8 )
return( MBEDTLS_ERR_DES_INVALID_INPUT_LENGTH );
if( mode == MBEDTLS_DES_ENCRYPT )
{
while( length > 0 )
{
for( i = 0; i < 8; i++ )
output[i] = (unsigned char)( input[i] ^ iv[i] );
mbedtls_des3_crypt_ecb( ctx, output, output );
memcpy( iv, output, 8 );
input += 8;
output += 8;
length -= 8;
}
}
else /* MBEDTLS_DES_DECRYPT */
{
while( length > 0 )
{
memcpy( temp, input, 8 );
mbedtls_des3_crypt_ecb( ctx, input, output );
for( i = 0; i < 8; i++ )
output[i] = (unsigned char)( output[i] ^ iv[i] );
memcpy( iv, temp, 8 );
input += 8;
output += 8;
length -= 8;
}
}
return( 0 );
}
#endif /* MBEDTLS_CIPHER_MODE_CBC */
#endif /* !MBEDTLS_DES_ALT */
#if defined(MBEDTLS_SELF_TEST)
/*
* DES and 3DES test vectors from:
*
* http://csrc.nist.gov/groups/STM/cavp/documents/des/tripledes-vectors.zip
*/
static const unsigned char des3_test_keys[24] =
{
0x01, 0x23, 0x45, 0x67, 0x89, 0xAB, 0xCD, 0xEF,
0x23, 0x45, 0x67, 0x89, 0xAB, 0xCD, 0xEF, 0x01,
0x45, 0x67, 0x89, 0xAB, 0xCD, 0xEF, 0x01, 0x23
};
static const unsigned char des3_test_buf[8] =
{
0x4E, 0x6F, 0x77, 0x20, 0x69, 0x73, 0x20, 0x74
};
static const unsigned char des3_test_ecb_dec[3][8] =
{
{ 0x37, 0x2B, 0x98, 0xBF, 0x52, 0x65, 0xB0, 0x59 },
{ 0xC2, 0x10, 0x19, 0x9C, 0x38, 0x5A, 0x65, 0xA1 },
{ 0xA2, 0x70, 0x56, 0x68, 0x69, 0xE5, 0x15, 0x1D }
};
static const unsigned char des3_test_ecb_enc[3][8] =
{
{ 0x1C, 0xD5, 0x97, 0xEA, 0x84, 0x26, 0x73, 0xFB },
{ 0xB3, 0x92, 0x4D, 0xF3, 0xC5, 0xB5, 0x42, 0x93 },
{ 0xDA, 0x37, 0x64, 0x41, 0xBA, 0x6F, 0x62, 0x6F }
};
#if defined(MBEDTLS_CIPHER_MODE_CBC)
static const unsigned char des3_test_iv[8] =
{
0x12, 0x34, 0x56, 0x78, 0x90, 0xAB, 0xCD, 0xEF,
};
static const unsigned char des3_test_cbc_dec[3][8] =
{
{ 0x58, 0xD9, 0x48, 0xEF, 0x85, 0x14, 0x65, 0x9A },
{ 0x5F, 0xC8, 0x78, 0xD4, 0xD7, 0x92, 0xD9, 0x54 },
{ 0x25, 0xF9, 0x75, 0x85, 0xA8, 0x1E, 0x48, 0xBF }
};
static const unsigned char des3_test_cbc_enc[3][8] =
{
{ 0x91, 0x1C, 0x6D, 0xCF, 0x48, 0xA7, 0xC3, 0x4D },
{ 0x60, 0x1A, 0x76, 0x8F, 0xA1, 0xF9, 0x66, 0xF1 },
{ 0xA1, 0x50, 0x0F, 0x99, 0xB2, 0xCD, 0x64, 0x76 }
};
#endif /* MBEDTLS_CIPHER_MODE_CBC */
/*
* Checkup routine
*/
int mbedtls_des_self_test( int verbose )
{
int i, j, u, v, ret = 0;
mbedtls_des_context ctx;
mbedtls_des3_context ctx3;
unsigned char buf[8];
#if defined(MBEDTLS_CIPHER_MODE_CBC)
unsigned char prv[8];
unsigned char iv[8];
#endif
mbedtls_des_init( &ctx );
mbedtls_des3_init( &ctx3 );
/*
* ECB mode
*/
for( i = 0; i < 6; i++ )
{
u = i >> 1;
v = i & 1;
if( verbose != 0 )
mbedtls_printf( " DES%c-ECB-%3d (%s): ",
( u == 0 ) ? ' ' : '3', 56 + u * 56,
( v == MBEDTLS_DES_DECRYPT ) ? "dec" : "enc" );
memcpy( buf, des3_test_buf, 8 );
switch( i )
{
case 0:
mbedtls_des_setkey_dec( &ctx, des3_test_keys );
break;
case 1:
mbedtls_des_setkey_enc( &ctx, des3_test_keys );
break;
case 2:
mbedtls_des3_set2key_dec( &ctx3, des3_test_keys );
break;
case 3:
mbedtls_des3_set2key_enc( &ctx3, des3_test_keys );
break;
case 4:
mbedtls_des3_set3key_dec( &ctx3, des3_test_keys );
break;
case 5:
mbedtls_des3_set3key_enc( &ctx3, des3_test_keys );
break;
default:
return( 1 );
}
for( j = 0; j < 100; j++ )
{
if( u == 0 )
mbedtls_des_crypt_ecb( &ctx, buf, buf );
else
mbedtls_des3_crypt_ecb( &ctx3, buf, buf );
}
if( ( v == MBEDTLS_DES_DECRYPT &&
memcmp( buf, des3_test_ecb_dec[u], 8 ) != 0 ) ||
( v != MBEDTLS_DES_DECRYPT &&
memcmp( buf, des3_test_ecb_enc[u], 8 ) != 0 ) )
{
if( verbose != 0 )
mbedtls_printf( "failed\n" );
ret = 1;
goto exit;
}
if( verbose != 0 )
mbedtls_printf( "passed\n" );
}
if( verbose != 0 )
mbedtls_printf( "\n" );
#if defined(MBEDTLS_CIPHER_MODE_CBC)
/*
* CBC mode
*/
for( i = 0; i < 6; i++ )
{
u = i >> 1;
v = i & 1;
if( verbose != 0 )
mbedtls_printf( " DES%c-CBC-%3d (%s): ",
( u == 0 ) ? ' ' : '3', 56 + u * 56,
( v == MBEDTLS_DES_DECRYPT ) ? "dec" : "enc" );
memcpy( iv, des3_test_iv, 8 );
memcpy( prv, des3_test_iv, 8 );
memcpy( buf, des3_test_buf, 8 );
switch( i )
{
case 0:
mbedtls_des_setkey_dec( &ctx, des3_test_keys );
break;
case 1:
mbedtls_des_setkey_enc( &ctx, des3_test_keys );
break;
case 2:
mbedtls_des3_set2key_dec( &ctx3, des3_test_keys );
break;
case 3:
mbedtls_des3_set2key_enc( &ctx3, des3_test_keys );
break;
case 4:
mbedtls_des3_set3key_dec( &ctx3, des3_test_keys );
break;
case 5:
mbedtls_des3_set3key_enc( &ctx3, des3_test_keys );
break;
default:
return( 1 );
}
if( v == MBEDTLS_DES_DECRYPT )
{
for( j = 0; j < 100; j++ )
{
if( u == 0 )
mbedtls_des_crypt_cbc( &ctx, v, 8, iv, buf, buf );
else
mbedtls_des3_crypt_cbc( &ctx3, v, 8, iv, buf, buf );
}
}
else
{
for( j = 0; j < 100; j++ )
{
unsigned char tmp[8];
if( u == 0 )
mbedtls_des_crypt_cbc( &ctx, v, 8, iv, buf, buf );
else
mbedtls_des3_crypt_cbc( &ctx3, v, 8, iv, buf, buf );
memcpy( tmp, prv, 8 );
memcpy( prv, buf, 8 );
memcpy( buf, tmp, 8 );
}
memcpy( buf, prv, 8 );
}
if( ( v == MBEDTLS_DES_DECRYPT &&
memcmp( buf, des3_test_cbc_dec[u], 8 ) != 0 ) ||
( v != MBEDTLS_DES_DECRYPT &&
memcmp( buf, des3_test_cbc_enc[u], 8 ) != 0 ) )
{
if( verbose != 0 )
mbedtls_printf( "failed\n" );
ret = 1;
goto exit;
}
if( verbose != 0 )
mbedtls_printf( "passed\n" );
}
#endif /* MBEDTLS_CIPHER_MODE_CBC */
if( verbose != 0 )
mbedtls_printf( "\n" );
exit:
mbedtls_des_free( &ctx );
mbedtls_des3_free( &ctx3 );
return( ret );
}
#endif /* MBEDTLS_SELF_TEST */
#endif /* MBEDTLS_DES_C */
|
0 | repos/gpt4all.zig/src/zig-libcurl/zig-mbedtls/mbedtls | repos/gpt4all.zig/src/zig-libcurl/zig-mbedtls/mbedtls/docs/getting_started.md | ## Getting started with Mbed Crypto
### What is Mbed Crypto?
Mbed Crypto is an open source cryptographic library that supports a wide range of cryptographic operations, including:
* Key management
* Hashing
* Symmetric cryptography
* Asymmetric cryptography
* Message authentication (MAC)
* Key generation and derivation
* Authenticated encryption with associated data (AEAD)
The Mbed Crypto library is a reference implementation of the cryptography interface of the Arm Platform Security Architecture (PSA). It is written in portable C.
The Mbed Crypto library is distributed under the Apache License, version 2.0.
#### Platform Security Architecture (PSA)
Arm's Platform Security Architecture (PSA) is a holistic set of threat models,
security analyses, hardware and firmware architecture specifications, and an open source firmware reference implementation. PSA provides a recipe, based on industry best practice, that enables you to design security into both hardware and firmware consistently. Part of the API provided by PSA is the cryptography interface, which provides access to a set of primitives.
### Using Mbed Crypto
* [Getting the Mbed Crypto library](#getting-the-mbed-crypto-library)
* [Building the Mbed Crypto library](#building-the-mbed-crypto-library)
* [Using the Mbed Crypto library](#using-the-mbed-crypto-library)
* [Importing a key](#importing-a-key)
* [Signing a message using RSA](#signing-a-message-using-RSA)
* [Encrypting or decrypting using symmetric ciphers](#encrypting-or-decrypting-using-symmetric-ciphers)
* [Hashing a message](#hashing-a-message)
* [Deriving a new key from an existing key](#deriving-a-new-key-from-an-existing-key)
* [Generating a random value](#generating-a-random-value)
* [Authenticating and encrypting or decrypting a message](#authenticating-and-encrypting-or-decrypting-a-message)
* [Generating and exporting keys](#generating-and-exporting-keys)
* [More about the Mbed Crypto library](#more-about-the-mbed-crypto-library)
### Getting the Mbed Crypto library
Mbed Crypto releases are available in the [public GitHub repository](https://github.com/ARMmbed/mbed-crypto).
### Building the Mbed Crypto library
**Prerequisites to building the library with the provided makefiles:**
* GNU Make.
* A C toolchain (compiler, linker, archiver).
* Python 2 or Python 3 (either works) to generate the test code.
* Perl to run the tests.
If you have a C compiler such as GCC or Clang, just run `make` in the top-level directory to build the library, a set of unit tests and some sample programs.
To select a different compiler, set the `CC` variable to the name or path of the compiler and linker (default: `cc`) and set `AR` to a compatible archiver (default: `ar`); for example:
```
make CC=arm-linux-gnueabi-gcc AR=arm-linux-gnueabi-ar
```
The provided makefiles pass options to the compiler that assume a GCC-like command line syntax. To use a different compiler, you may need to pass different values for `CFLAGS`, `WARNINGS_CFLAGS` and `LDFLAGS`.
To run the unit tests on the host machine, run `make test` from the top-level directory. If you are cross-compiling, copy the test executable from the `tests` directory to the target machine.
### Using the Mbed Crypto library
To use the Mbed Crypto APIs, call `psa_crypto_init()` before calling any other API. This initializes the library.
### Importing a key
To use a key for cryptography operations in Mbed Crypto, you need to first
import it. The import operation returns the identifier of the key for use
with other function calls.
**Prerequisites to importing keys:**
* Initialize the library with a successful call to `psa_crypto_init()`.
This example shows how to import a key:
```C
void import_a_key(const uint8_t *key, size_t key_len)
{
psa_status_t status;
psa_key_attributes_t attributes = PSA_KEY_ATTRIBUTES_INIT;
psa_key_id_t key;
printf("Import an AES key...\t");
fflush(stdout);
/* Initialize PSA Crypto */
status = psa_crypto_init();
if (status != PSA_SUCCESS) {
printf("Failed to initialize PSA Crypto\n");
return;
}
/* Set key attributes */
psa_set_key_usage_flags(&attributes, 0);
psa_set_key_algorithm(&attributes, 0);
psa_set_key_type(&attributes, PSA_KEY_TYPE_AES);
psa_set_key_bits(&attributes, 128);
/* Import the key */
status = psa_import_key(&attributes, key, key_len, &key);
if (status != PSA_SUCCESS) {
printf("Failed to import key\n");
return;
}
printf("Imported a key\n");
/* Free the attributes */
psa_reset_key_attributes(&attributes);
/* Destroy the key */
psa_destroy_key(key);
mbedtls_psa_crypto_free();
}
```
### Signing a message using RSA
Mbed Crypto supports encrypting, decrypting, signing and verifying messages using public key signature algorithms, such as RSA or ECDSA.
**Prerequisites to performing asymmetric signature operations:**
* Initialize the library with a successful call to `psa_crypto_init()`.
* Have a valid key with appropriate attributes set:
* Usage flag `PSA_KEY_USAGE_SIGN_HASH` to allow signing.
* Usage flag `PSA_KEY_USAGE_VERIFY_HASH` to allow signature verification.
* Algorithm set to the desired signature algorithm.
This example shows how to sign a hash that has already been calculated:
```C
void sign_a_message_using_rsa(const uint8_t *key, size_t key_len)
{
psa_status_t status;
psa_key_attributes_t attributes = PSA_KEY_ATTRIBUTES_INIT;
uint8_t hash[32] = {0x50, 0xd8, 0x58, 0xe0, 0x98, 0x5e, 0xcc, 0x7f,
0x60, 0x41, 0x8a, 0xaf, 0x0c, 0xc5, 0xab, 0x58,
0x7f, 0x42, 0xc2, 0x57, 0x0a, 0x88, 0x40, 0x95,
0xa9, 0xe8, 0xcc, 0xac, 0xd0, 0xf6, 0x54, 0x5c};
uint8_t signature[PSA_SIGNATURE_MAX_SIZE] = {0};
size_t signature_length;
psa_key_id_t key;
printf("Sign a message...\t");
fflush(stdout);
/* Initialize PSA Crypto */
status = psa_crypto_init();
if (status != PSA_SUCCESS) {
printf("Failed to initialize PSA Crypto\n");
return;
}
/* Set key attributes */
psa_set_key_usage_flags(&attributes, PSA_KEY_USAGE_SIGN_HASH);
psa_set_key_algorithm(&attributes, PSA_ALG_RSA_PKCS1V15_SIGN_RAW);
psa_set_key_type(&attributes, PSA_KEY_TYPE_RSA_KEY_PAIR);
psa_set_key_bits(&attributes, 1024);
/* Import the key */
status = psa_import_key(&attributes, key, key_len, &key);
if (status != PSA_SUCCESS) {
printf("Failed to import key\n");
return;
}
/* Sign message using the key */
status = psa_sign_hash(key, PSA_ALG_RSA_PKCS1V15_SIGN_RAW,
hash, sizeof(hash),
signature, sizeof(signature),
&signature_length);
if (status != PSA_SUCCESS) {
printf("Failed to sign\n");
return;
}
printf("Signed a message\n");
/* Free the attributes */
psa_reset_key_attributes(&attributes);
/* Destroy the key */
psa_destroy_key(key);
mbedtls_psa_crypto_free();
}
```
### Using symmetric ciphers
Mbed Crypto supports encrypting and decrypting messages using various symmetric cipher algorithms (both block and stream ciphers).
**Prerequisites to working with the symmetric cipher API:**
* Initialize the library with a successful call to `psa_crypto_init()`.
* Have a symmetric key. This key's usage flags must include `PSA_KEY_USAGE_ENCRYPT` to allow encryption or `PSA_KEY_USAGE_DECRYPT` to allow decryption.
**To encrypt a message with a symmetric cipher:**
1. Allocate an operation (`psa_cipher_operation_t`) structure to pass to the cipher functions.
1. Initialize the operation structure to zero or to `PSA_CIPHER_OPERATION_INIT`.
1. Call `psa_cipher_encrypt_setup()` to specify the algorithm and the key to be used.
1. Call either `psa_cipher_generate_iv()` or `psa_cipher_set_iv()` to generate or set the initialization vector (IV). We recommend calling `psa_cipher_generate_iv()`, unless you require a specific IV value.
1. Call `psa_cipher_update()` with the message to encrypt. You may call this function multiple times, passing successive fragments of the message on successive calls.
1. Call `psa_cipher_finish()` to end the operation and output the encrypted message.
This example shows how to encrypt data using an AES (Advanced Encryption Standard) key in CBC (Cipher Block Chaining) mode with no padding (assuming all prerequisites have been fulfilled):
```c
void encrypt_with_symmetric_ciphers(const uint8_t *key, size_t key_len)
{
enum {
block_size = PSA_BLOCK_CIPHER_BLOCK_LENGTH(PSA_KEY_TYPE_AES),
};
psa_status_t status;
psa_key_attributes_t attributes = PSA_KEY_ATTRIBUTES_INIT;
psa_algorithm_t alg = PSA_ALG_CBC_NO_PADDING;
uint8_t plaintext[block_size] = SOME_PLAINTEXT;
uint8_t iv[block_size];
size_t iv_len;
uint8_t output[block_size];
size_t output_len;
psa_key_id_t key;
psa_cipher_operation_t operation = PSA_CIPHER_OPERATION_INIT;
printf("Encrypt with cipher...\t");
fflush(stdout);
/* Initialize PSA Crypto */
status = psa_crypto_init();
if (status != PSA_SUCCESS)
{
printf("Failed to initialize PSA Crypto\n");
return;
}
/* Import a key */
psa_set_key_usage_flags(&attributes, PSA_KEY_USAGE_ENCRYPT);
psa_set_key_algorithm(&attributes, alg);
psa_set_key_type(&attributes, PSA_KEY_TYPE_AES);
psa_set_key_bits(&attributes, 128);
status = psa_import_key(&attributes, key, key_len, &key);
if (status != PSA_SUCCESS) {
printf("Failed to import a key\n");
return;
}
psa_reset_key_attributes(&attributes);
/* Encrypt the plaintext */
status = psa_cipher_encrypt_setup(&operation, key, alg);
if (status != PSA_SUCCESS) {
printf("Failed to begin cipher operation\n");
return;
}
status = psa_cipher_generate_iv(&operation, iv, sizeof(iv), &iv_len);
if (status != PSA_SUCCESS) {
printf("Failed to generate IV\n");
return;
}
status = psa_cipher_update(&operation, plaintext, sizeof(plaintext),
output, sizeof(output), &output_len);
if (status != PSA_SUCCESS) {
printf("Failed to update cipher operation\n");
return;
}
status = psa_cipher_finish(&operation, output + output_len,
sizeof(output) - output_len, &output_len);
if (status != PSA_SUCCESS) {
printf("Failed to finish cipher operation\n");
return;
}
printf("Encrypted plaintext\n");
/* Clean up cipher operation context */
psa_cipher_abort(&operation);
/* Destroy the key */
psa_destroy_key(key);
mbedtls_psa_crypto_free();
}
```
**To decrypt a message with a symmetric cipher:**
1. Allocate an operation (`psa_cipher_operation_t`) structure to pass to the cipher functions.
1. Initialize the operation structure to zero or to `PSA_CIPHER_OPERATION_INIT`.
1. Call `psa_cipher_decrypt_setup()` to specify the algorithm and the key to be used.
1. Call `psa_cipher_set_iv()` with the IV for the decryption.
1. Call `psa_cipher_update()` with the message to encrypt. You may call this function multiple times, passing successive fragments of the message on successive calls.
1. Call `psa_cipher_finish()` to end the operation and output the decrypted message.
This example shows how to decrypt encrypted data using an AES key in CBC mode with no padding
(assuming all prerequisites have been fulfilled):
```c
void decrypt_with_symmetric_ciphers(const uint8_t *key, size_t key_len)
{
enum {
block_size = PSA_BLOCK_CIPHER_BLOCK_LENGTH(PSA_KEY_TYPE_AES),
};
psa_status_t status;
psa_key_attributes_t attributes = PSA_KEY_ATTRIBUTES_INIT;
psa_algorithm_t alg = PSA_ALG_CBC_NO_PADDING;
psa_cipher_operation_t operation = PSA_CIPHER_OPERATION_INIT;
uint8_t ciphertext[block_size] = SOME_CIPHERTEXT;
uint8_t iv[block_size] = ENCRYPTED_WITH_IV;
uint8_t output[block_size];
size_t output_len;
psa_key_id_t key;
printf("Decrypt with cipher...\t");
fflush(stdout);
/* Initialize PSA Crypto */
status = psa_crypto_init();
if (status != PSA_SUCCESS)
{
printf("Failed to initialize PSA Crypto\n");
return;
}
/* Import a key */
psa_set_key_usage_flags(&attributes, PSA_KEY_USAGE_DECRYPT);
psa_set_key_algorithm(&attributes, alg);
psa_set_key_type(&attributes, PSA_KEY_TYPE_AES);
psa_set_key_bits(&attributes, 128);
status = psa_import_key(&attributes, key, key_len, &key);
if (status != PSA_SUCCESS) {
printf("Failed to import a key\n");
return;
}
psa_reset_key_attributes(&attributes);
/* Decrypt the ciphertext */
status = psa_cipher_decrypt_setup(&operation, key, alg);
if (status != PSA_SUCCESS) {
printf("Failed to begin cipher operation\n");
return;
}
status = psa_cipher_set_iv(&operation, iv, sizeof(iv));
if (status != PSA_SUCCESS) {
printf("Failed to set IV\n");
return;
}
status = psa_cipher_update(&operation, ciphertext, sizeof(ciphertext),
output, sizeof(output), &output_len);
if (status != PSA_SUCCESS) {
printf("Failed to update cipher operation\n");
return;
}
status = psa_cipher_finish(&operation, output + output_len,
sizeof(output) - output_len, &output_len);
if (status != PSA_SUCCESS) {
printf("Failed to finish cipher operation\n");
return;
}
printf("Decrypted ciphertext\n");
/* Clean up cipher operation context */
psa_cipher_abort(&operation);
/* Destroy the key */
psa_destroy_key(key);
mbedtls_psa_crypto_free();
}
```
#### Handling cipher operation contexts
After you've initialized the operation structure with a successful call to `psa_cipher_encrypt_setup()` or `psa_cipher_decrypt_setup()`, you can terminate the operation at any time by calling `psa_cipher_abort()`.
The call to `psa_cipher_abort()` frees any resources associated with the operation, except for the operation structure itself.
Mbed Crypto implicitly calls `psa_cipher_abort()` when:
* A call to `psa_cipher_generate_iv()`, `psa_cipher_set_iv()` or `psa_cipher_update()` fails (returning any status other than `PSA_SUCCESS`).
* A call to `psa_cipher_finish()` succeeds or fails.
After an implicit or explicit call to `psa_cipher_abort()`, the operation structure is invalidated; in other words, you cannot reuse the operation structure for the same operation. You can, however, reuse the operation structure for a different operation by calling either `psa_cipher_encrypt_setup()` or `psa_cipher_decrypt_setup()` again.
You must call `psa_cipher_abort()` at some point for any operation that is initialized successfully (by a successful call to `psa_cipher_encrypt_setup()` or `psa_cipher_decrypt_setup()`).
Making multiple sequential calls to `psa_cipher_abort()` on an operation that is terminated (either implicitly or explicitly) is safe and has no effect.
### Hashing a message
Mbed Crypto lets you compute and verify hashes using various hashing
algorithms.
**Prerequisites to working with the hash APIs:**
* Initialize the library with a successful call to `psa_crypto_init()`.
**To calculate a hash:**
1. Allocate an operation structure (`psa_hash_operation_t`) to pass to the hash functions.
1. Initialize the operation structure to zero or to `PSA_HASH_OPERATION_INIT`.
1. Call `psa_hash_setup()` to specify the hash algorithm.
1. Call `psa_hash_update()` with the message to encrypt. You may call this function multiple times, passing successive fragments of the message on successive calls.
1. Call `psa_hash_finish()` to calculate the hash, or `psa_hash_verify()` to compare the computed hash with an expected hash value.
This example shows how to calculate the SHA-256 hash of a message:
```c
psa_status_t status;
psa_algorithm_t alg = PSA_ALG_SHA_256;
psa_hash_operation_t operation = PSA_HASH_OPERATION_INIT;
unsigned char input[] = { 'a', 'b', 'c' };
unsigned char actual_hash[PSA_HASH_MAX_SIZE];
size_t actual_hash_len;
printf("Hash a message...\t");
fflush(stdout);
/* Initialize PSA Crypto */
status = psa_crypto_init();
if (status != PSA_SUCCESS) {
printf("Failed to initialize PSA Crypto\n");
return;
}
/* Compute hash of message */
status = psa_hash_setup(&operation, alg);
if (status != PSA_SUCCESS) {
printf("Failed to begin hash operation\n");
return;
}
status = psa_hash_update(&operation, input, sizeof(input));
if (status != PSA_SUCCESS) {
printf("Failed to update hash operation\n");
return;
}
status = psa_hash_finish(&operation, actual_hash, sizeof(actual_hash),
&actual_hash_len);
if (status != PSA_SUCCESS) {
printf("Failed to finish hash operation\n");
return;
}
printf("Hashed a message\n");
/* Clean up hash operation context */
psa_hash_abort(&operation);
mbedtls_psa_crypto_free();
```
This example shows how to verify the SHA-256 hash of a message:
```c
psa_status_t status;
psa_algorithm_t alg = PSA_ALG_SHA_256;
psa_hash_operation_t operation = PSA_HASH_OPERATION_INIT;
unsigned char input[] = { 'a', 'b', 'c' };
unsigned char expected_hash[] = {
0xba, 0x78, 0x16, 0xbf, 0x8f, 0x01, 0xcf, 0xea, 0x41, 0x41, 0x40, 0xde,
0x5d, 0xae, 0x22, 0x23, 0xb0, 0x03, 0x61, 0xa3, 0x96, 0x17, 0x7a, 0x9c,
0xb4, 0x10, 0xff, 0x61, 0xf2, 0x00, 0x15, 0xad
};
size_t expected_hash_len = PSA_HASH_LENGTH(alg);
printf("Verify a hash...\t");
fflush(stdout);
/* Initialize PSA Crypto */
status = psa_crypto_init();
if (status != PSA_SUCCESS) {
printf("Failed to initialize PSA Crypto\n");
return;
}
/* Verify message hash */
status = psa_hash_setup(&operation, alg);
if (status != PSA_SUCCESS) {
printf("Failed to begin hash operation\n");
return;
}
status = psa_hash_update(&operation, input, sizeof(input));
if (status != PSA_SUCCESS) {
printf("Failed to update hash operation\n");
return;
}
status = psa_hash_verify(&operation, expected_hash, expected_hash_len);
if (status != PSA_SUCCESS) {
printf("Failed to verify hash\n");
return;
}
printf("Verified a hash\n");
/* Clean up hash operation context */
psa_hash_abort(&operation);
mbedtls_psa_crypto_free();
```
The API provides the macro `PSA_HASH_LENGTH`, which returns the expected hash length (in bytes) for the specified algorithm.
#### Handling hash operation contexts
After a successful call to `psa_hash_setup()`, you can terminate the operation at any time by calling `psa_hash_abort()`. The call to `psa_hash_abort()` frees any resources associated with the operation, except for the operation structure itself.
Mbed Crypto implicitly calls `psa_hash_abort()` when:
1. A call to `psa_hash_update()` fails (returning any status other than `PSA_SUCCESS`).
1. A call to `psa_hash_finish()` succeeds or fails.
1. A call to `psa_hash_verify()` succeeds or fails.
After an implicit or explicit call to `psa_hash_abort()`, the operation structure is invalidated; in other words, you cannot reuse the operation structure for the same operation. You can, however, reuse the operation structure for a different operation by calling `psa_hash_setup()` again.
You must call `psa_hash_abort()` at some point for any operation that is initialized successfully (by a successful call to `psa_hash_setup()`) .
Making multiple sequential calls to `psa_hash_abort()` on an operation that has already been terminated (either implicitly or explicitly) is safe and has no effect.
### Generating a random value
Mbed Crypto can generate random data.
**Prerequisites to generating random data:**
* Initialize the library with a successful call to `psa_crypto_init()`.
<span class="notes">**Note:** To generate a random key, use `psa_generate_key()` instead of `psa_generate_random()`.</span>
This example shows how to generate ten bytes of random data by calling `psa_generate_random()`:
```C
psa_status_t status;
uint8_t random[10] = { 0 };
printf("Generate random...\t");
fflush(stdout);
/* Initialize PSA Crypto */
status = psa_crypto_init();
if (status != PSA_SUCCESS) {
printf("Failed to initialize PSA Crypto\n");
return;
}
status = psa_generate_random(random, sizeof(random));
if (status != PSA_SUCCESS) {
printf("Failed to generate a random value\n");
return;
}
printf("Generated random data\n");
/* Clean up */
mbedtls_psa_crypto_free();
```
### Deriving a new key from an existing key
Mbed Crypto provides a key derivation API that lets you derive new keys from
existing ones. The key derivation API has functions to take inputs, including
other keys and data, and functions to generate outputs, such as new keys or
other data.
You must first initialize and set up a key derivation context,
provided with a key and, optionally, other data. Then, use the key derivation context to either read derived data to a buffer or send derived data directly to a key slot.
See the documentation for the particular algorithm (such as HKDF or the TLS1.2 PRF) for
information about which inputs to pass when, and when you can obtain which outputs.
**Prerequisites to working with the key derivation APIs:**
* Initialize the library with a successful call to `psa_crypto_init()`.
* Use a key with the appropriate attributes set:
* Usage flags set for key derivation (`PSA_KEY_USAGE_DERIVE`)
* Key type set to `PSA_KEY_TYPE_DERIVE`.
* Algorithm set to a key derivation algorithm
(for example, `PSA_ALG_HKDF(PSA_ALG_SHA_256)`).
**To derive a new AES-CTR 128-bit encryption key into a given key slot using HKDF
with a given key, salt and info:**
1. Set up the key derivation context using the `psa_key_derivation_setup()`
function, specifying the derivation algorithm `PSA_ALG_HKDF(PSA_ALG_SHA_256)`.
1. Provide an optional salt with `psa_key_derivation_input_bytes()`.
1. Provide info with `psa_key_derivation_input_bytes()`.
1. Provide a secret with `psa_key_derivation_input_key()`, referencing a key that
can be used for key derivation.
1. Set the key attributes desired for the new derived key. We'll set
the `PSA_KEY_USAGE_ENCRYPT` usage flag and the `PSA_ALG_CTR` algorithm for this
example.
1. Derive the key by calling `psa_key_derivation_output_key()`.
1. Clean up the key derivation context.
At this point, the derived key slot holds a new 128-bit AES-CTR encryption key
derived from the key, salt and info provided:
```C
psa_status_t status;
psa_key_attributes_t attributes = PSA_KEY_ATTRIBUTES_INIT;
static const unsigned char key[] = {
0x0b, 0x0b, 0x0b, 0x0b, 0x0b, 0x0b, 0x0b,
0x0b, 0x0b, 0x0b, 0x0b, 0x0b, 0x0b, 0x0b,
0x0b, 0x0b, 0x0b, 0x0b, 0x0b, 0x0b, 0x0b,
0x0b };
static const unsigned char salt[] = {
0x00, 0x01, 0x02, 0x03, 0x04, 0x05, 0x06,
0x07, 0x08, 0x09, 0x0a, 0x0b, 0x0c };
static const unsigned char info[] = {
0xf0, 0xf1, 0xf2, 0xf3, 0xf4, 0xf5, 0xf6,
0xf7, 0xf8, 0xf9 };
psa_algorithm_t alg = PSA_ALG_HKDF(PSA_ALG_SHA_256);
psa_key_derivation_operation_t operation =
PSA_KEY_DERIVATION_OPERATION_INIT;
size_t derived_bits = 128;
size_t capacity = PSA_BITS_TO_BYTES(derived_bits);
psa_key_id_t base_key;
psa_key_id_t derived_key;
printf("Derive a key (HKDF)...\t");
fflush(stdout);
/* Initialize PSA Crypto */
status = psa_crypto_init();
if (status != PSA_SUCCESS) {
printf("Failed to initialize PSA Crypto\n");
return;
}
/* Import a key for use in key derivation. If such a key has already been
* generated or imported, you can skip this part. */
psa_set_key_usage_flags(&attributes, PSA_KEY_USAGE_DERIVE);
psa_set_key_algorithm(&attributes, alg);
psa_set_key_type(&attributes, PSA_KEY_TYPE_DERIVE);
status = psa_import_key(&attributes, key, sizeof(key), &base_key);
if (status != PSA_SUCCESS) {
printf("Failed to import a key\n");
return;
}
psa_reset_key_attributes(&attributes);
/* Derive a key */
status = psa_key_derivation_setup(&operation, alg);
if (status != PSA_SUCCESS) {
printf("Failed to begin key derivation\n");
return;
}
status = psa_key_derivation_set_capacity(&operation, capacity);
if (status != PSA_SUCCESS) {
printf("Failed to set capacity\n");
return;
}
status = psa_key_derivation_input_bytes(&operation,
PSA_KEY_DERIVATION_INPUT_SALT,
salt, sizeof(salt));
if (status != PSA_SUCCESS) {
printf("Failed to input salt (extract)\n");
return;
}
status = psa_key_derivation_input_key(&operation,
PSA_KEY_DERIVATION_INPUT_SECRET,
base_key);
if (status != PSA_SUCCESS) {
printf("Failed to input key (extract)\n");
return;
}
status = psa_key_derivation_input_bytes(&operation,
PSA_KEY_DERIVATION_INPUT_INFO,
info, sizeof(info));
if (status != PSA_SUCCESS) {
printf("Failed to input info (expand)\n");
return;
}
psa_set_key_usage_flags(&attributes, PSA_KEY_USAGE_ENCRYPT);
psa_set_key_algorithm(&attributes, PSA_ALG_CTR);
psa_set_key_type(&attributes, PSA_KEY_TYPE_AES);
psa_set_key_bits(&attributes, 128);
status = psa_key_derivation_output_key(&attributes, &operation,
&derived_key);
if (status != PSA_SUCCESS) {
printf("Failed to derive key\n");
return;
}
psa_reset_key_attributes(&attributes);
printf("Derived key\n");
/* Clean up key derivation operation */
psa_key_derivation_abort(&operation);
/* Destroy the keys */
psa_destroy_key(derived_key);
psa_destroy_key(base_key);
mbedtls_psa_crypto_free();
```
### Authenticating and encrypting or decrypting a message
Mbed Crypto provides a simple way to authenticate and encrypt with associated data (AEAD), supporting the `PSA_ALG_CCM` algorithm.
**Prerequisites to working with the AEAD cipher APIs:**
* Initialize the library with a successful call to `psa_crypto_init()`.
* The key attributes for the key used for derivation must have the `PSA_KEY_USAGE_ENCRYPT` or `PSA_KEY_USAGE_DECRYPT` usage flags.
This example shows how to authenticate and encrypt a message:
```C
psa_status_t status;
static const uint8_t key[] = {
0xC0, 0xC1, 0xC2, 0xC3, 0xC4, 0xC5, 0xC6, 0xC7,
0xC8, 0xC9, 0xCA, 0xCB, 0xCC, 0xCD, 0xCE, 0xCF };
static const uint8_t nonce[] = {
0x00, 0x01, 0x02, 0x03, 0x04, 0x05, 0x06, 0x07,
0x08, 0x09, 0x0A, 0x0B };
static const uint8_t additional_data[] = {
0xEC, 0x46, 0xBB, 0x63, 0xB0, 0x25,
0x20, 0xC3, 0x3C, 0x49, 0xFD, 0x70 };
static const uint8_t input_data[] = {
0xB9, 0x6B, 0x49, 0xE2, 0x1D, 0x62, 0x17, 0x41,
0x63, 0x28, 0x75, 0xDB, 0x7F, 0x6C, 0x92, 0x43,
0xD2, 0xD7, 0xC2 };
uint8_t *output_data = NULL;
size_t output_size = 0;
size_t output_length = 0;
size_t tag_length = 16;
psa_key_attributes_t attributes = PSA_KEY_ATTRIBUTES_INIT;
psa_key_id_t key;
printf("Authenticate encrypt...\t");
fflush(stdout);
/* Initialize PSA Crypto */
status = psa_crypto_init();
if (status != PSA_SUCCESS) {
printf("Failed to initialize PSA Crypto\n");
return;
}
output_size = sizeof(input_data) + tag_length;
output_data = (uint8_t *)malloc(output_size);
if (!output_data) {
printf("Out of memory\n");
return;
}
/* Import a key */
psa_set_key_usage_flags(&attributes, PSA_KEY_USAGE_ENCRYPT);
psa_set_key_algorithm(&attributes, PSA_ALG_CCM);
psa_set_key_type(&attributes, PSA_KEY_TYPE_AES);
psa_set_key_bits(&attributes, 128);
status = psa_import_key(&attributes, key, sizeof(key), &key);
psa_reset_key_attributes(&attributes);
/* Authenticate and encrypt */
status = psa_aead_encrypt(key, PSA_ALG_CCM,
nonce, sizeof(nonce),
additional_data, sizeof(additional_data),
input_data, sizeof(input_data),
output_data, output_size,
&output_length);
if (status != PSA_SUCCESS) {
printf("Failed to authenticate and encrypt\n");
return;
}
printf("Authenticated and encrypted\n");
/* Clean up */
free(output_data);
/* Destroy the key */
psa_destroy_key(key);
mbedtls_psa_crypto_free();
```
This example shows how to authenticate and decrypt a message:
```C
psa_status_t status;
static const uint8_t key_data[] = {
0xC0, 0xC1, 0xC2, 0xC3, 0xC4, 0xC5, 0xC6, 0xC7,
0xC8, 0xC9, 0xCA, 0xCB, 0xCC, 0xCD, 0xCE, 0xCF };
static const uint8_t nonce[] = {
0x00, 0x01, 0x02, 0x03, 0x04, 0x05, 0x06, 0x07,
0x08, 0x09, 0x0A, 0x0B };
static const uint8_t additional_data[] = {
0xEC, 0x46, 0xBB, 0x63, 0xB0, 0x25,
0x20, 0xC3, 0x3C, 0x49, 0xFD, 0x70 };
static const uint8_t input_data[] = {
0x20, 0x30, 0xE0, 0x36, 0xED, 0x09, 0xA0, 0x45, 0xAF, 0x3C, 0xBA, 0xEE,
0x0F, 0xC8, 0x48, 0xAF, 0xCD, 0x89, 0x54, 0xF4, 0xF6, 0x3F, 0x28, 0x9A,
0xA1, 0xDD, 0xB2, 0xB8, 0x09, 0xCD, 0x7C, 0xE1, 0x46, 0xE9, 0x98 };
uint8_t *output_data = NULL;
size_t output_size = 0;
size_t output_length = 0;
psa_key_attributes_t attributes = PSA_KEY_ATTRIBUTES_INIT;
psa_key_id_t key;
printf("Authenticate decrypt...\t");
fflush(stdout);
/* Initialize PSA Crypto */
status = psa_crypto_init();
if (status != PSA_SUCCESS) {
printf("Failed to initialize PSA Crypto\n");
return;
}
output_size = sizeof(input_data);
output_data = (uint8_t *)malloc(output_size);
if (!output_data) {
printf("Out of memory\n");
return;
}
/* Import a key */
psa_set_key_usage_flags(&attributes, PSA_KEY_USAGE_DECRYPT);
psa_set_key_algorithm(&attributes, PSA_ALG_CCM);
psa_set_key_type(&attributes, PSA_KEY_TYPE_AES);
psa_set_key_bits(&attributes, 128);
status = psa_import_key(&attributes, key_data, sizeof(key_data), &key);
if (status != PSA_SUCCESS) {
printf("Failed to import a key\n");
return;
}
psa_reset_key_attributes(&attributes);
/* Authenticate and decrypt */
status = psa_aead_decrypt(key, PSA_ALG_CCM,
nonce, sizeof(nonce),
additional_data, sizeof(additional_data),
input_data, sizeof(input_data),
output_data, output_size,
&output_length);
if (status != PSA_SUCCESS) {
printf("Failed to authenticate and decrypt %ld\n", status);
return;
}
printf("Authenticated and decrypted\n");
/* Clean up */
free(output_data);
/* Destroy the key */
psa_destroy_key(key);
mbedtls_psa_crypto_free();
```
### Generating and exporting keys
Mbed Crypto provides a simple way to generate a key or key pair.
**Prerequisites to using key generation and export APIs:**
* Initialize the library with a successful call to `psa_crypto_init()`.
**To generate an ECDSA key:**
1. Set the desired key attributes for key generation by calling
`psa_set_key_algorithm()` with the chosen ECDSA algorithm (such as
`PSA_ALG_DETERMINISTIC_ECDSA(PSA_ALG_SHA_256)`). You only want to export the public key, not the key pair (or private key); therefore, do not set `PSA_KEY_USAGE_EXPORT`.
1. Generate a key by calling `psa_generate_key()`.
1. Export the generated public key by calling `psa_export_public_key()`:
```C
enum {
key_bits = 256,
};
psa_status_t status;
size_t exported_length = 0;
static uint8_t exported[PSA_KEY_EXPORT_ECC_PUBLIC_KEY_MAX_SIZE(key_bits)];
psa_key_attributes_t attributes = PSA_KEY_ATTRIBUTES_INIT;
psa_key_id_t key;
printf("Generate a key pair...\t");
fflush(stdout);
/* Initialize PSA Crypto */
status = psa_crypto_init();
if (status != PSA_SUCCESS) {
printf("Failed to initialize PSA Crypto\n");
return;
}
/* Generate a key */
psa_set_key_usage_flags(&attributes, PSA_KEY_USAGE_SIGN_HASH);
psa_set_key_algorithm(&attributes,
PSA_ALG_DETERMINISTIC_ECDSA(PSA_ALG_SHA_256));
psa_set_key_type(&attributes,
PSA_KEY_TYPE_ECC_KEY_PAIR(PSA_ECC_FAMILY_SECP_R1));
psa_set_key_bits(&attributes, key_bits);
status = psa_generate_key(&attributes, &key);
if (status != PSA_SUCCESS) {
printf("Failed to generate key\n");
return;
}
psa_reset_key_attributes(&attributes);
status = psa_export_public_key(key, exported, sizeof(exported),
&exported_length);
if (status != PSA_SUCCESS) {
printf("Failed to export public key %ld\n", status);
return;
}
printf("Exported a public key\n");
/* Destroy the key */
psa_destroy_key(key);
mbedtls_psa_crypto_free();
```
### More about the PSA Crypto API
For more information about the PSA Crypto API, please see the [PSA Cryptography API Specification](https://armmbed.github.io/mbed-crypto/html/index.html).
|
0 | repos/gpt4all.zig/src/zig-libcurl/zig-mbedtls/mbedtls/docs | repos/gpt4all.zig/src/zig-libcurl/zig-mbedtls/mbedtls/docs/architecture/psa-crypto-implementation-structure.md | PSA Cryptograpy API implementation and PSA driver interface
===========================================================
## Introduction
The [PSA Cryptography API specification](https://armmbed.github.io/mbed-crypto/psa/#application-programming-interface) defines an interface to cryptographic operations for which the Mbed TLS library provides a reference implementation. The PSA Cryptography API specification is complemented by the PSA driver interface specification which defines an interface for cryptoprocessor drivers.
This document describes the high level organization of the Mbed TLS PSA Cryptography API implementation which is tightly related to the PSA driver interface.
## High level organization of the Mbed TLS PSA Cryptography API implementation
In one sentence, the Mbed TLS PSA Cryptography API implementation is made of a core and PSA drivers as defined in the PSA driver interface. The key point is that software cryptographic operations are organized as PSA drivers: they interact with the core through the PSA driver interface.
### Rationale
* Addressing software and hardware cryptographic implementations through the same C interface reduces the core code size and its call graph complexity. The core and its dispatching to software and hardware implementations are consequently easier to test and validate.
* The organization of the software cryptographic implementations in drivers promotes modularization of those implementations.
* As hardware capabilities, software cryptographic functionalities can be described by a JSON driver description file as defined in the PSA driver interface.
* Along with JSON driver description files, the PSA driver specification defines the deliverables for a driver to be included into the Mbed TLS PSA Cryptography implementation. This provides a natural framework to integrate third party or alternative software implementations of cryptographic operations.
## The Mbed TLS PSA Cryptography API implementation core
The core implements all the APIs as defined in the PSA Cryptography API specification but does not perform on its own any cryptographic operation. The core relies on PSA drivers to actually
perform the cryptographic operations. The core is responsible for:
* the key store.
* checking PSA API arguments and translating them into valid arguments for the necessary calls to the PSA driver interface.
* dispatching the cryptographic operations to the appropriate PSA drivers.
The sketch of an Mbed TLS PSA cryptographic API implementation is thus:
```C
psa_status_t psa_api( ... )
{
psa_status_t status;
/* Pre driver interface call processing: validation of arguments, building
* of arguments for the call to the driver interface, ... */
...
/* Call to the driver interface */
status = psa_driver_wrapper_<entry_point>( ... );
if( status != PSA_SUCCESS )
return( status );
/* Post driver interface call processing: validation of the values returned
* by the driver, finalization of the values to return to the caller,
* clean-up in case of error ... */
}
```
The code of most PSA APIs is expected to match precisely the above layout. However, it is likely that the code structure of some APIs will be more complicated with several calls to the driver interface, mainly to encompass a larger variety of hardware designs. For example, to encompass hardware accelerators that are capable of verifying a MAC and those that are only capable of computing a MAC, the psa_mac_verify() API could call first psa_driver_wrapper_mac_verify() and then fallback to psa_driver_wrapper_mac_compute().
The implementations of `psa_driver_wrapper_<entry_point>` functions are generated by the build system based on the JSON driver description files of the various PSA drivers making up the Mbed TLS PSA Cryptography API implementation. The implementations are generated in a psa_crypto_driver_wrappers.c C file and the function prototypes declared in a psa_crypto_driver_wrappers.h header file.
The psa_driver_wrapper_<entry_point>() functions dispatch cryptographic operations to accelerator drivers, secure element drivers as well as to the software implementations of cryptographic operations.
Note that the implementation allows to build the library with only a C compiler by shipping a generated file corresponding to a pure software implementation. The driver entry points and their code in this generated file are guarded by pre-processor directives based on PSA_WANT_xyz macros (see [Conditional inclusion of cryptographic mechanism through the PSA API in Mbed TLS](psa-conditional-inclusion-c.html). That way, it is possible to compile and include in the library only the desired cryptographic operations.
### Key creation
Key creation implementation in Mbed TLS PSA core is articulated around three internal functions: psa_start_key_creation(), psa_finish_key_creation() and psa_fail_key_creation(). Implementations of key creation PSA APIs, namely psa_import_key(), psa_generate_key(), psa_key_derivation_output_key() and psa_copy_key() go by the following sequence:
1. Check the input parameters.
2. Call psa_start_key_creation() that allocates a key slot, prepares it with the specified key attributes, and in case of a volatile key assign it a volatile key identifier.
3. Generate or copy the key material into the key slot. This entails the allocation of the buffer to store the key material.
4. Call psa_finish_key_creation() that mostly saves persistent keys into persistent storage.
In case of any error occurring at step 3 or 4, psa_fail_key_creation() is called. It wipes and cleans the slot especially the key material: reset to zero of the RAM memory that contained the key material, free the allocated buffer.
## Mbed TLS PSA Cryptography API implementation drivers
A driver of the Mbed TLS PSA Cryptography API implementation (Mbed TLS PSA driver in the following) is a driver in the sense that it is compliant with the PSA driver interface specification. But it is not an actual driver that drives some hardware. It implements cryptographic operations purely in software.
An Mbed TLS PSA driver C file is named psa_crypto_<driver_name>.c and its associated header file psa_crypto_<driver_name>.h. The functions implementing a driver entry point as defined in the PSA driver interface specification are named as mbedtls_psa_<driver name>_<entry point>(). As an example, the psa_crypto_rsa.c and psa_crypto_rsa.h are the files containing the Mbed TLS PSA driver implementing RSA cryptographic operations. This RSA driver implements among other entry points the "import_key" entry point. The function implementing this entry point is named mbedtls_psa_rsa_import_key().
|
0 | repos/gpt4all.zig/src/zig-libcurl/zig-mbedtls/mbedtls/docs | repos/gpt4all.zig/src/zig-libcurl/zig-mbedtls/mbedtls/docs/architecture/mbed-crypto-storage-specification.md | Mbed Crypto storage specification
=================================
This document specifies how Mbed Crypto uses storage.
Mbed Crypto may be upgraded on an existing device with the storage preserved. Therefore:
1. Any change may break existing installations and may require an upgrade path.
1. This document retains historical information about all past released versions. Do not remove information from this document unless it has always been incorrect or it is about a version that you are sure was never released.
Mbed Crypto 0.1.0
-----------------
Tags: mbedcrypto-0.1.0b, mbedcrypto-0.1.0b2
Released in November 2018. <br>
Integrated in Mbed OS 5.11.
Supported backends:
* [PSA ITS](#file-namespace-on-its-for-0.1.0)
* [C stdio](#file-namespace-on-stdio-for-0.1.0)
Supported features:
* [Persistent transparent keys](#key-file-format-for-0.1.0) designated by a [slot number](#key-names-for-0.1.0).
* [Nonvolatile random seed](#nonvolatile-random-seed-file-format-for-0.1.0) on ITS only.
This is a beta release, and we do not promise backward compatibility, with one exception:
> On Mbed OS, if a device has a nonvolatile random seed file produced with Mbed OS 5.11.x and is upgraded to a later version of Mbed OS, the nonvolatile random seed file is preserved or upgraded.
We do not make any promises regarding key storage, or regarding the nonvolatile random seed file on other platforms.
### Key names for 0.1.0
Information about each key is stored in a dedicated file whose name is constructed from the key identifier. The way in which the file name is constructed depends on the storage backend. The content of the file is described [below](#key-file-format-for-0.1.0).
The valid values for a key identifier are the range from 1 to 0xfffeffff. This limitation on the range is not documented in user-facing documentation: according to the user-facing documentation, arbitrary 32-bit values are valid.
The code uses the following constant in an internal header (note that despite the name, this value is actually one plus the maximum permitted value):
#define PSA_MAX_PERSISTENT_KEY_IDENTIFIER 0xffff0000
There is a shared namespace for all callers.
### Key file format for 0.1.0
All integers are encoded in little-endian order in 8-bit bytes.
The layout of a key file is:
* magic (8 bytes): `"PSA\0KEY\0"`
* version (4 bytes): 0
* type (4 bytes): `psa_key_type_t` value
* policy usage flags (4 bytes): `psa_key_usage_t` value
* policy usage algorithm (4 bytes): `psa_algorithm_t` value
* key material length (4 bytes)
* key material: output of `psa_export_key`
* Any trailing data is rejected on load.
### Nonvolatile random seed file format for 0.1.0
The nonvolatile random seed file contains a seed for the random generator. If present, it is rewritten at each boot as part of the random generator initialization.
The file format is just the seed as a byte string with no metadata or encoding of any kind.
### File namespace on ITS for 0.1.0
Assumption: ITS provides a 32-bit file identifier namespace. The Crypto service can use arbitrary file identifiers and no other part of the system accesses the same file identifier namespace.
* File 0: unused.
* Files 1 through 0xfffeffff: [content](#key-file-format-for-0.1.0) of the [key whose identifier is the file identifier](#key-names-for-0.1.0).
* File 0xffffff52 (`PSA_CRYPTO_ITS_RANDOM_SEED_UID`): [nonvolatile random seed](#nonvolatile-random-seed-file-format-for-0.1.0).
* Files 0xffff0000 through 0xffffff51, 0xffffff53 through 0xffffffff: unused.
### File namespace on stdio for 0.1.0
Assumption: C stdio, allowing names containing lowercase letters, digits and underscores, of length up to 23.
An undocumented build-time configuration value `CRYPTO_STORAGE_FILE_LOCATION` allows storing the key files in a directory other than the current directory. This value is simply prepended to the file name (so it must end with a directory separator to put the keys in a different directory).
* `CRYPTO_STORAGE_FILE_LOCATION "psa_key_slot_0"`: used as a temporary file. Must be writable. May be overwritten or deleted if present.
* `sprintf(CRYPTO_STORAGE_FILE_LOCATION "psa_key_slot_%lu", key_id)` [content](#key-file-format-for-0.1.0) of the [key whose identifier](#key-names-for-0.1.0) is `key_id`.
* Other files: unused.
Mbed Crypto 1.0.0
-----------------
Tags: mbedcrypto-1.0.0d4, mbedcrypto-1.0.0
Released in February 2019. <br>
Integrated in Mbed OS 5.12.
Supported integrations:
* [PSA platform](#file-namespace-on-a-psa-platform-for-1.0.0)
* [library using PSA ITS](#file-namespace-on-its-as-a-library-for-1.0.0)
* [library using C stdio](#file-namespace-on-stdio-for-1.0.0)
Supported features:
* [Persistent transparent keys](#key-file-format-for-1.0.0) designated by a [key identifier and owner](#key-names-for-1.0.0).
* [Nonvolatile random seed](#nonvolatile-random-seed-file-format-for-1.0.0) on ITS only.
Backward compatibility commitments: TBD
### Key names for 1.0.0
Information about each key is stored in a dedicated file designated by the key identifier. In integrations where there is no concept of key owner (in particular, in library integrations), the key identifier is exactly the key identifier as defined in the PSA Cryptography API specification (`psa_key_id_t`). In integrations where there is a concept of key owner (integration into a service for example), the key identifier is made of an owner identifier (its semantics and type are integration specific) and of the key identifier (`psa_key_id_t`) from the key owner point of view.
The way in which the file name is constructed from the key identifier depends on the storage backend. The content of the file is described [below](#key-file-format-for-1.0.0).
* Library integration: the key file name is just the key identifier as defined in the PSA crypto specification. This is a 32-bit value.
* PSA service integration: the key file name is `(uint32_t)owner_uid << 32 | key_id` where `key_id` is the key identifier from the owner point of view and `owner_uid` (of type `int32_t`) is the calling partition identifier provided to the server by the partition manager. This is a 64-bit value.
### Key file format for 1.0.0
The layout is identical to [0.1.0](#key-file-format-for-0.1.0) so far. However note that the encoding of key types, algorithms and key material has changed, therefore the storage format is not compatible (despite using the same value in the version field so far).
### Nonvolatile random seed file format for 1.0.0
[Identical to 0.1.0](#nonvolatile-random-seed-file-format-for-0.1.0).
### File namespace on a PSA platform for 1.0.0
Assumption: ITS provides a 64-bit file identifier namespace. The Crypto service can use arbitrary file identifiers and no other part of the system accesses the same file identifier namespace.
Assumption: the owner identifier is a nonzero value of type `int32_t`.
* Files 0 through 0xffffff51, 0xffffff53 through 0xffffffff: unused, reserved for internal use of the crypto library or crypto service.
* File 0xffffff52 (`PSA_CRYPTO_ITS_RANDOM_SEED_UID`): [nonvolatile random seed](#nonvolatile-random-seed-file-format-for-0.1.0).
* Files 0x100000000 through 0xffffffffffff: [content](#key-file-format-for-1.0.0) of the [key whose identifier is the file identifier](#key-names-for-1.0.0). The upper 32 bits determine the owner.
### File namespace on ITS as a library for 1.0.0
Assumption: ITS provides a 64-bit file identifier namespace. The entity using the crypto library can use arbitrary file identifiers and no other part of the system accesses the same file identifier namespace.
This is a library integration, so there is no owner. The key file identifier is identical to the key identifier.
* File 0: unused.
* Files 1 through 0xfffeffff: [content](#key-file-format-for-1.0.0) of the [key whose identifier is the file identifier](#key-names-for-1.0.0).
* File 0xffffff52 (`PSA_CRYPTO_ITS_RANDOM_SEED_UID`): [nonvolatile random seed](#nonvolatile-random-seed-file-format-for-1.0.0).
* Files 0xffff0000 through 0xffffff51, 0xffffff53 through 0xffffffff, 0x100000000 through 0xffffffffffffffff: unused.
### File namespace on stdio for 1.0.0
This is a library integration, so there is no owner. The key file identifier is identical to the key identifier.
[Identical to 0.1.0](#file-namespace-on-stdio-for-0.1.0).
### Upgrade from 0.1.0 to 1.0.0.
* Delete files 1 through 0xfffeffff, which contain keys in a format that is no longer supported.
### Suggested changes to make before 1.0.0
The library integration and the PSA platform integration use different sets of file names. This is annoyingly non-uniform. For example, if we want to store non-key files, we have room in different ranges (0 through 0xffffffff on a PSA platform, 0xffff0000 through 0xffffffffffffffff in a library integration).
It would simplify things to always have a 32-bit owner, with a nonzero value, and thus reserve the range 0–0xffffffff for internal library use.
Mbed Crypto 1.1.0
-----------------
Tags: mbedcrypto-1.1.0
Released in early June 2019. <br>
Integrated in Mbed OS 5.13.
Identical to [1.0.0](#mbed-crypto-1.0.0) except for some changes in the key file format.
### Key file format for 1.1.0
The key file format is identical to [1.0.0](#key-file-format-for-1.0.0), except for the following changes:
* A new policy field, marked as [NEW:1.1.0] below.
* The encoding of key types, algorithms and key material has changed, therefore the storage format is not compatible (despite using the same value in the version field so far).
A self-contained description of the file layout follows.
All integers are encoded in little-endian order in 8-bit bytes.
The layout of a key file is:
* magic (8 bytes): `"PSA\0KEY\0"`
* version (4 bytes): 0
* type (4 bytes): `psa_key_type_t` value
* policy usage flags (4 bytes): `psa_key_usage_t` value
* policy usage algorithm (4 bytes): `psa_algorithm_t` value
* policy enrollment algorithm (4 bytes): `psa_algorithm_t` value [NEW:1.1.0]
* key material length (4 bytes)
* key material: output of `psa_export_key`
* Any trailing data is rejected on load.
Mbed Crypto TBD
---------------
Tags: TBD
Released in TBD 2019. <br>
Integrated in Mbed OS TBD.
### Changes introduced in TBD
* The layout of a key file now has a lifetime field before the type field.
* Key files can store references to keys in a secure element. In such key files, the key material contains the slot number.
### File namespace on a PSA platform on TBD
Assumption: ITS provides a 64-bit file identifier namespace. The Crypto service can use arbitrary file identifiers and no other part of the system accesses the same file identifier namespace.
Assumption: the owner identifier is a nonzero value of type `int32_t`.
* Files 0 through 0xfffeffff: unused.
* Files 0xffff0000 through 0xffffffff: reserved for internal use of the crypto library or crypto service. See [non-key files](#non-key-files-on-tbd).
* Files 0x100000000 through 0xffffffffffff: [content](#key-file-format-for-1.0.0) of the [key whose identifier is the file identifier](#key-names-for-1.0.0). The upper 32 bits determine the owner.
### File namespace on ITS as a library on TBD
Assumption: ITS provides a 64-bit file identifier namespace. The entity using the crypto library can use arbitrary file identifiers and no other part of the system accesses the same file identifier namespace.
This is a library integration, so there is no owner. The key file identifier is identical to the key identifier.
* File 0: unused.
* Files 1 through 0xfffeffff: [content](#key-file-format-for-1.0.0) of the [key whose identifier is the file identifier](#key-names-for-1.0.0).
* Files 0xffff0000 through 0xffffffff: reserved for internal use of the crypto library or crypto service. See [non-key files](#non-key-files-on-tbd).
* Files 0x100000000 through 0xffffffffffffffff: unused.
### Non-key files on TBD
File identifiers in the range 0xffff0000 through 0xffffffff are reserved for internal use in Mbed Crypto.
* Files 0xfffffe02 through 0xfffffeff (`PSA_CRYPTO_SE_DRIVER_ITS_UID_BASE + lifetime`): secure element driver storage. The content of the file is the secure element driver's persistent data.
* File 0xffffff52 (`PSA_CRYPTO_ITS_RANDOM_SEED_UID`): [nonvolatile random seed](#nonvolatile-random-seed-file-format-for-1.0.0).
* File 0xffffff54 (`PSA_CRYPTO_ITS_TRANSACTION_UID`): [transaction file](#transaction-file-format-for-tbd).
* Other files are unused and reserved for future use.
### Key file format for TBD
All integers are encoded in little-endian order in 8-bit bytes except where otherwise indicated.
The layout of a key file is:
* magic (8 bytes): `"PSA\0KEY\0"`.
* version (4 bytes): 0.
* lifetime (4 bytes): `psa_key_lifetime_t` value.
* type (4 bytes): `psa_key_type_t` value.
* policy usage flags (4 bytes): `psa_key_usage_t` value.
* policy usage algorithm (4 bytes): `psa_algorithm_t` value.
* policy enrollment algorithm (4 bytes): `psa_algorithm_t` value.
* key material length (4 bytes).
* key material:
* For a transparent key: output of `psa_export_key`.
* For an opaque key (unified driver interface): driver-specific opaque key blob.
* For an opaque key (key in a secure element): slot number (8 bytes), in platform endianness.
* Any trailing data is rejected on load.
### Transaction file format for TBD
The transaction file contains data about an ongoing action that cannot be completed atomically. It exists only if there is an ongoing transaction.
All integers are encoded in platform endianness.
All currently existing transactions concern a key in a secure element.
The layout of a transaction file is:
* type (2 bytes): the [transaction type](#transaction-types-on-tbd).
* unused (2 bytes)
* lifetime (4 bytes): `psa_key_lifetime_t` value that corresponds to a key in a secure element.
* slot number (8 bytes): `psa_key_slot_number_t` value. This is the unique designation of the key for the secure element driver.
* key identifier (4 bytes in a library integration, 8 bytes on a PSA platform): the internal representation of the key identifier. On a PSA platform, this encodes the key owner in the same way as [in file identifiers for key files](#file-namespace-on-a-psa-platform-on-tbd)).
#### Transaction types on TBD
* 0x0001: key creation. The following locations may or may not contain data about the key that is being created:
* The slot in the secure element designated by the slot number.
* The file containing the key metadata designated by the key identifier.
* The driver persistent data.
* 0x0002: key destruction. The following locations may or may not still contain data about the key that is being destroyed:
* The slot in the secure element designated by the slot number.
* The file containing the key metadata designated by the key identifier.
* The driver persistent data.
Mbed Crypto TBD
---------------
Tags: TBD
Released in TBD 2020. <br>
Integrated in Mbed OS TBD.
### Changes introduced in TBD
* The type field has been split into a type and a bits field of 2 bytes each.
### Key file format for TBD
All integers are encoded in little-endian order in 8-bit bytes except where otherwise indicated.
The layout of a key file is:
* magic (8 bytes): `"PSA\0KEY\0"`.
* version (4 bytes): 0.
* lifetime (4 bytes): `psa_key_lifetime_t` value.
* type (2 bytes): `psa_key_type_t` value.
* bits (2 bytes): `psa_key_bits_t` value.
* policy usage flags (4 bytes): `psa_key_usage_t` value.
* policy usage algorithm (4 bytes): `psa_algorithm_t` value.
* policy enrollment algorithm (4 bytes): `psa_algorithm_t` value.
* key material length (4 bytes).
* key material:
* For a transparent key: output of `psa_export_key`.
* For an opaque key (unified driver interface): driver-specific opaque key blob.
* For an opaque key (key in a secure element): slot number (8 bytes), in platform endianness.
* Any trailing data is rejected on load.
|
0 | repos/gpt4all.zig/src/zig-libcurl/zig-mbedtls/mbedtls/docs | repos/gpt4all.zig/src/zig-libcurl/zig-mbedtls/mbedtls/docs/architecture/tls13-experimental.md | TLS 1.3 Experimental Developments
=================================
Overview
--------
Mbed TLS doesn't support the TLS 1.3 protocol yet, but a prototype is in development.
Stable parts of this prototype that can be independently tested are being successively
upstreamed under the guard of the following macro:
```
MBEDTLS_SSL_PROTO_TLS1_3_EXPERIMENTAL
```
This macro will likely be renamed to `MBEDTLS_SSL_PROTO_TLS1_3` once a minimal viable
implementation of the TLS 1.3 protocol is available.
See the [documentation of `MBEDTLS_SSL_PROTO_TLS1_3_EXPERIMENTAL`](../../include/mbedtls/config.h)
for more information.
Status
------
The following lists which parts of the TLS 1.3 prototype have already been upstreamed
together with their level of testing:
* TLS 1.3 record protection mechanisms
The record protection routines `mbedtls_ssl_{encrypt|decrypt}_buf()` have been extended
to support the modified TLS 1.3 record protection mechanism, including modified computation
of AAD, IV, and the introduction of a flexible padding.
Those record protection routines have unit tests in `test_suite_ssl` alongside the
tests for the other record protection routines.
TODO: Add some test vectors from RFC 8448.
- The HKDF key derivation function on which the TLS 1.3 key schedule is based,
is already present as an independent module controlled by `MBEDTLS_HKDF_C`
independently of the development of the TLS 1.3 prototype.
- The TLS 1.3-specific HKDF-based key derivation functions (see RFC 8446):
* HKDF-Expand-Label
* Derive-Secret
- Secret evolution
* The traffic {Key,IV} generation from secret
Those functions are implemented in `library/ssl_tls13_keys.c` and
tested in `test_suite_ssl` using test vectors from RFC 8448 and
https://tls13.ulfheim.net/.
- New TLS Message Processing Stack (MPS)
The TLS 1.3 prototype is developed alongside a rewrite of the TLS messaging layer,
encompassing low-level details such as record parsing, handshake reassembly, and
DTLS retransmission state machine.
MPS has the following components:
- Layer 1 (Datagram handling)
- Layer 2 (Record handling)
- Layer 3 (Message handling)
- Layer 4 (Retransmission State Machine)
- Reader (Abstracted pointer arithmetic and reassembly logic for incoming data)
- Writer (Abstracted pointer arithmetic and fragmentation logic for outgoing data)
Of those components, the following have been upstreamed
as part of `MBEDTLS_SSL_PROTO_TLS1_3_EXPERIMENTAL`:
- Reader ([`library/mps_reader.h`](../../library/mps_reader.h))
|
0 | repos/gpt4all.zig/src/zig-libcurl/zig-mbedtls/mbedtls/docs/architecture | repos/gpt4all.zig/src/zig-libcurl/zig-mbedtls/mbedtls/docs/architecture/testing/invasive-testing.md | # Mbed TLS invasive testing strategy
## Introduction
In Mbed TLS, we use black-box testing as much as possible: test the documented behavior of the product, in a realistic environment. However this is not always sufficient.
The goal of this document is to identify areas where black-box testing is insufficient and to propose solutions.
This is a test strategy document, not a test plan. A description of exactly what is tested is out of scope.
This document is structured as follows:
* [“Rules”](#rules) gives general rules and is written for brevity.
* [“Requirements”](#requirements) explores the reasons why invasive testing is needed and how it should be done.
* [“Possible approaches”](#possible-approaches) discusses some general methods for non-black-box testing.
* [“Solutions”](#solutions) explains how we currently solve, or intend to solve, specific problems.
### TLS
This document currently focuses on data structure manipulation and storage, which is what the crypto/keystore and X.509 parts of the library are about. More work is needed to fully take TLS into account.
## Rules
Always follow these rules unless you have a good reason not to. If you deviate, document the rationale somewhere.
See the section [“Possible approaches”](#possible-approaches) for a rationale.
### Interface design for testing
Do not add test-specific interfaces if there's a practical way of doing it another way. All public interfaces should be useful in at least some configurations. Features with a significant impact on the code size or attack surface should have a compile-time guard.
### Reliance on internal details
In unit tests and in test programs, it's ok to include header files from `library/`. Do not define non-public interfaces in public headers (`include/mbedtls` has `*_internal.h` headers for legacy reasons, but this approach is deprecated). In contrast, sample programs must not include header files from `library/`.
Sometimes it makes sense to have unit tests on functions that aren't part of the public API. Declare such functions in `library/*.h` and include the corresponding header in the test code. If the function should be `static` for optimization but can't be `static` for testing, declare it as `MBEDTLS_STATIC_TESTABLE`, and make the tests that use it depend on `MBEDTLS_TEST_HOOKS` (see [“rules for compile-time options”](#rules-for-compile-time-options)).
If test code or test data depends on internal details of the library and not just on its documented behavior, add a comment in the code that explains the dependency. For example:
> ```
> /* This test file is specific to the ITS implementation in PSA Crypto
> * on top of stdio. It expects to know what the stdio name of a file is
> * based on its keystore name.
> */
> ```
> ```
> # This test assumes that PSA_MAX_KEY_BITS (currently 65536-8 bits = 8191 bytes
> # and not expected to be raised any time soon) is less than the maximum
> # output from HKDF-SHA512 (255*64 = 16320 bytes).
> ```
### Rules for compile-time options
If the most practical way to test something is to add code to the product that is only useful for testing, do so, but obey the following rules. For more information, see the [rationale](#guidelines-for-compile-time-options).
* **Only use test-specific code when necessary.** Anything that can be tested through the documented API must be tested through the documented API.
* **Test-specific code must be guarded by `#if defined(MBEDTLS_TEST_HOOKS)`**. Do not create fine-grained guards for test-specific code.
* **Do not use `MBEDTLS_TEST_HOOKS` for security checks or assertions.** Security checks belong in the product.
* **Merely defining `MBEDTLS_TEST_HOOKS` must not change the behavior**. It may define extra functions. It may add fields to structures, but if so, make it very clear that these fields have no impact on non-test-specific fields.
* **Where tests must be able to change the behavior, do it by function substitution.** See [“rules for function substitution”](#rules-for-function-substitution) for more details.
#### Rules for function substitution
This section explains how to replace a library function `mbedtls_foo()` by alternative code for test purposes. That is, library code calls `mbedtls_foo()`, and there is a mechanism to arrange for these calls to invoke different code.
Often `mbedtls_foo` is a macro which is defined to be a system function (like `mbedtls_calloc` or `mbedtls_fopen`), which we replace to mock or wrap the system function. This is useful to simulate I/O failure, for example. Note that if the macro can be replaced at compile time to support alternative platforms, the test code should be compatible with this compile-time configuration so that it works on these alternative platforms as well.
Sometimes the substitutable function is a `static inline` function that does nothing (not a macro, to avoid accidentally skipping side effects in its parameters), to provide a hook for test code; such functions should have a name that starts with the prefix `mbedtls_test_hook_`. In such cases, the function should generally not modify its parameters, so any pointer argument should be const. The function should return void.
With `MBEDTLS_TEST_HOOKS` set, `mbedtls_foo` is a global variable of function pointer type. This global variable is initialized to the system function, or to a function that does nothing. The global variable is defined in a header in the `library` directory such as `psa_crypto_invasive.h`. This is similar to the platform function configuration mechanism with `MBEDTLS_PLATFORM_xxx_ALT`.
In unit test code that needs to modify the internal behavior:
* The test function (or the whole test file) must depend on `MBEDTLS_TEST_HOOKS`.
* At the beginning of the test function, set the global function pointers to the desired value.
* In the test function's cleanup code, restore the global function pointers to their default value.
## Requirements
### General goals
We need to balance the following goals, which are sometimes contradictory.
* Coverage: we need to test behaviors which are not easy to trigger by using the API or which cannot be triggered deterministically, for example I/O failures.
* Correctness: we want to test the actual product, not a modified version, since conclusions drawn from a test of a modified product may not apply to the real product.
* Effacement: the product should not include features that are solely present for test purposes, since these increase the attack surface and the code size.
* Portability: tests should work on every platform. Skipping tests on certain platforms may hide errors that are only apparent on such platforms.
* Maintainability: tests should only enforce the documented behavior of the product, to avoid extra work when the product's internal or implementation-specific behavior changes. We should also not give the impression that whatever the tests check is guaranteed behavior of the product which cannot change in future versions.
Where those goals conflict, we should at least mitigate the goals that cannot be fulfilled, and document the architectural choices and their rationale.
### Problem areas
#### Allocation
Resource allocation can fail, but rarely does so in a typical test environment. How does the product cope if some allocations fail?
Resources include:
* Memory.
* Files in storage (PSA API only — in the Mbed TLS API, black-box unit tests are sufficient).
* Key slots (PSA API only).
* Key slots in a secure element (PSA SE HAL).
* Communication handles (PSA crypto service only).
#### Storage
Storage can fail, either due to hardware errors or to active attacks on trusted storage. How does the code cope if some storage accesses fail?
We also need to test resilience: if the system is reset during an operation, does it restart in a correct state?
#### Cleanup
When code should clean up resources, how do we know that they have truly been cleaned up?
* Zeroization of confidential data after use.
* Freeing memory.
* Freeing key slots.
* Freeing key slots in a secure element.
* Deleting files in storage (PSA API only).
#### Internal data
Sometimes it is useful to peek or poke internal data.
* Check consistency of internal data (e.g. output of key generation).
* Check the format of files (which matters so that the product can still read old files after an upgrade).
* Inject faults and test corruption checks inside the product.
## Possible approaches
Key to requirement tables:
* ++ requirement is fully met
* \+ requirement is mostly met
* ~ requirement is partially met but there are limitations
* ! requirement is somewhat problematic
* !! requirement is very problematic
### Fine-grained public interfaces
We can include all the features we want to test in the public interface. Then the tests can be truly black-box. The limitation of this approach is that this requires adding a lot of interfaces that are not useful in production. These interfaces have costs: they increase the code size, the attack surface, and the testing burden (exponentially, because we need to test all these interfaces in combination).
As a rule, we do not add public interfaces solely for testing purposes. We only add public interfaces if they are also useful in production, at least sometimes. For example, the main purpose of `mbedtls_psa_crypto_free` is to clean up all resources in tests, but this is also useful in production in some applications that only want to use PSA Crypto during part of their lifetime.
Mbed TLS traditionally has very fine-grained public interfaces, with many platform functions that can be substituted (`MBEDTLS_PLATFORM_xxx` macros). PSA Crypto has more opacity and less platform substitution macros.
| Requirement | Analysis |
| ----------- | -------- |
| Coverage | ~ Many useful tests are not reasonably achievable |
| Correctness | ++ Ideal |
| Effacement | !! Requires adding many otherwise-useless interfaces |
| Portability | ++ Ideal; the additional interfaces may be useful for portability beyond testing |
| Maintainability | !! Combinatorial explosion on the testing burden |
| | ! Public interfaces must remain for backward compatibility even if the test architecture changes |
### Fine-grained undocumented interfaces
We can include all the features we want to test in undocumented interfaces. Undocumented interfaces are described in public headers for the sake of the C compiler, but are described as “do not use” in comments (or not described at all) and are not included in Doxygen-rendered documentation. This mitigates some of the downsides of [fine-grained public interfaces](#fine-grained-public-interfaces), but not all. In particular, the extra interfaces do increase the code size, the attack surface and the test surface.
Mbed TLS traditionally has a few internal interfaces, mostly intended for cross-module abstraction leakage rather than for testing. For the PSA API, we favor [internal interfaces](#internal-interfaces).
| Requirement | Analysis |
| ----------- | -------- |
| Coverage | ~ Many useful tests are not reasonably achievable |
| Correctness | ++ Ideal |
| Effacement | !! Requires adding many otherwise-useless interfaces |
| Portability | ++ Ideal; the additional interfaces may be useful for portability beyond testing |
| Maintainability | ! Combinatorial explosion on the testing burden |
### Internal interfaces
We can write tests that call internal functions that are not exposed in the public interfaces. This is nice when it works, because it lets us test the unchanged product without compromising the design of the public interface.
A limitation is that these interfaces must exist in the first place. If they don't, this has mostly the same downside as public interfaces: the extra interfaces increase the code size and the attack surface for no direct benefit to the product.
Another limitation is that internal interfaces need to be used correctly. We may accidentally rely on internal details in the tests that are not necessarily always true (for example that are platform-specific). We may accidentally use these internal interfaces in ways that don't correspond to the actual product.
This approach is mostly portable since it only relies on C interfaces. A limitation is that the test-only interfaces must not be hidden at link time (but link-time hiding is not something we currently do). Another limitation is that this approach does not work for users who patch the library by replacing some modules; this is a secondary concern since we do not officially offer this as a feature.
| Requirement | Analysis |
| ----------- | -------- |
| Coverage | ~ Many useful tests require additional internal interfaces |
| Correctness | + Does not require a product change |
| | ~ The tests may call internal functions in a way that does not reflect actual usage inside the product |
| Effacement | ++ Fine as long as the internal interfaces aren't added solely for test purposes |
| Portability | + Fine as long as we control how the tests are linked |
| | ~ Doesn't work if the users rewrite an internal module |
| Maintainability | + Tests interfaces that are documented; dependencies in the tests are easily noticed when changing these interfaces |
### Static analysis
If we guarantee certain properties through static analysis, we don't need to test them. This puts some constraints on the properties:
* We need to have confidence in the specification (but we can gain this confidence by evaluating the specification on test data).
* This does not work for platform-dependent properties unless we have a formal model of the platform.
| Requirement | Analysis |
| ----------- | -------- |
| Coverage | ~ Good for platform-independent properties, if we can guarantee them statically |
| Correctness | + Good as long as we have confidence in the specification |
| Effacement | ++ Zero impact on the code |
| Portability | ++ Zero runtime burden |
| Maintainability | ~ Static analysis is hard, but it's also helpful |
### Compile-time options
If there's code that we want to have in the product for testing, but not in production, we can add a compile-time option to enable it. This is very powerful and usually easy to use, but comes with a major downside: we aren't testing the same code anymore.
| Requirement | Analysis |
| ----------- | -------- |
| Coverage | ++ Most things can be tested that way |
| Correctness | ! Difficult to ensure that what we test is what we run |
| Effacement | ++ No impact on the product when built normally or on the documentation, if done right |
| | ! Risk of getting “no impact” wrong |
| Portability | ++ It's just C code so it works everywhere |
| | ~ Doesn't work if the users rewrite an internal module |
| Maintainability | + Test interfaces impact the product source code, but at least they're clearly marked as such in the code |
#### Guidelines for compile-time options
* **Minimize the number of compile-time options.**<br>
Either we're testing or we're not. Fine-grained options for testing would require more test builds, especially if combinatorics enters the play.
* **Merely enabling the compile-time option should not change the behavior.**<br>
When building in test mode, the code should have exactly the same behavior. Changing the behavior should require some action at runtime (calling a function or changing a variable).
* **Minimize the impact on code**.<br>
We should not have test-specific conditional compilation littered through the code, as that makes the code hard to read.
### Runtime instrumentation
Some properties can be tested through runtime instrumentation: have the compiler or a similar tool inject something into the binary.
* Sanitizers check for certain bad usage patterns (ASan, MSan, UBSan, Valgrind).
* We can inject external libraries at link time. This can be a way to make system functions fail.
| Requirement | Analysis |
| ----------- | -------- |
| Coverage | ! Limited scope |
| Correctness | + Instrumentation generally does not affect the program's functional behavior |
| Effacement | ++ Zero impact on the code |
| Portability | ~ Depends on the method |
| Maintainability | ~ Depending on the instrumentation, this may require additional builds and scripts |
| | + Many properties come for free, but some require effort (e.g. the test code itself must be leak-free to avoid false positives in a leak detector) |
### Debugger-based testing
If we want to do something in a test that the product isn't capable of doing, we can use a debugger to read or modify the memory, or hook into the code at arbitrary points.
This is a very powerful approach, but it comes with limitations:
* The debugger may introduce behavior changes (e.g. timing). If we modify data structures in memory, we may do so in a way that the code doesn't expect.
* Due to compiler optimizations, the memory may not have the layout that we expect.
* Writing reliable debugger scripts is hard. We need to have confidence that we're testing what we mean to test, even in the face of compiler optimizations. Languages such as gdb make it hard to automate even relatively simple things such as finding the place(s) in the binary corresponding to some place in the source code.
* Debugger scripts are very much non-portable.
| Requirement | Analysis |
| ----------- | -------- |
| Coverage | ++ The sky is the limit |
| Correctness | ++ The code is unmodified, and tested as compiled (so we even detect compiler-induced bugs) |
| | ! Compiler optimizations may hinder |
| | ~ Modifying the execution may introduce divergence |
| Effacement | ++ Zero impact on the code |
| Portability | !! Not all environments have a debugger, and even if they do, we'd need completely different scripts for every debugger |
| Maintainability | ! Writing reliable debugger scripts is hard |
| | !! Very tight coupling with the details of the source code and even with the compiler |
## Solutions
This section lists some strategies that are currently used for invasive testing, or planned to be used. This list is not intended to be exhaustive.
### Memory management
#### Zeroization testing
Goal: test that `mbedtls_platform_zeroize` does wipe the memory buffer.
Solution ([debugger](#debugger-based-testing)): implemented in `tests/scripts/test_zeroize.gdb`.
Rationale: this cannot be tested by adding C code, because the danger is that the compiler optimizes the zeroization away, and any C code that observes the zeroization would cause the compiler not to optimize it away.
#### Memory cleanup
Goal: test the absence of memory leaks.
Solution ([instrumentation](#runtime-instrumentation)): run tests with ASan. (We also use Valgrind, but it's slower than ASan, so we favor ASan.)
Since we run many test jobs with a memory leak detector, each test function or test program must clean up after itself. Use the cleanup code (after the `exit` label in test functions) to free any memory that the function may have allocated.
#### Robustness against memory allocation failure
Solution: TODO. We don't test this at all at this point.
#### PSA key store memory cleanup
Goal: test the absence of resource leaks in the PSA key store code, in particular that `psa_close_key` and `psa_destroy_key` work correctly.
Solution ([internal interface](#internal-interfaces)): in most tests involving PSA functions, the cleanup code explicitly calls `PSA_DONE()` instead of `mbedtls_psa_crypto_free()`. `PSA_DONE` fails the test if the key store in memory is not empty.
Note there must also be tests that call `mbedtls_psa_crypto_free` with keys still open, to verify that it does close all keys.
`PSA_DONE` is a macro defined in `psa_crypto_helpers.h` which uses `mbedtls_psa_get_stats()` to get information about the keystore content before calling `mbedtls_psa_crypto_free()`. This feature is mostly but not exclusively useful for testing, and may be moved under `MBEDTLS_TEST_HOOKS`.
### PSA storage
#### PSA storage cleanup on success
Goal: test that no stray files are left over in the key store after a test that succeeded.
Solution: TODO. Currently the various test suites do it differently.
#### PSA storage cleanup on failure
Goal: ensure that no stray files are left over in the key store even if a test has failed (as that could cause other tests to fail).
Solution: TODO. Currently the various test suites do it differently.
#### PSA storage resilience
Goal: test the resilience of PSA storage against power failures.
Solution: TODO.
See the [secure element driver interface test strategy](driver-interface-test-strategy.html) for more information.
#### Corrupted storage
Goal: test the robustness against corrupted storage.
Solution ([internal interface](#internal-interfaces)): call `psa_its` functions to modify the storage.
#### Storage read failure
Goal: test the robustness against read errors.
Solution: TODO
#### Storage write failure
Goal: test the robustness against write errors (`STORAGE_FAILURE` or `INSUFFICIENT_STORAGE`).
Solution: TODO
#### Storage format stability
Goal: test that the storage format does not change between versions (or if it does, an upgrade path must be provided).
Solution ([internal interface](#internal-interfaces)): call internal functions to inspect the content of the file.
Note that the storage format is defined not only by the general layout, but also by the numerical values of encodings for key types and other metadata. For numerical values, there is a risk that we would accidentally modify a single value or a few values, so the tests should be exhaustive. This probably requires some compile-time analysis (perhaps the automation for `psa_constant_names` can be used here). TODO
### Other fault injection
#### PSA crypto init failure
Goal: test the failure of `psa_crypto_init`.
Solution ([compile-time option](#compile-time-options)): replace entropy initialization functions by functions that can fail. This is the only failure point for `psa_crypto_init` that is present in all builds.
When we implement the PSA entropy driver interface, this should be reworked to use the entropy driver interface.
#### PSA crypto data corruption
The PSA crypto subsystem has a few checks to detect corrupted data in memory. We currently don't have a way to exercise those checks.
Solution: TODO. To corrupt a multipart operation structure, we can do it by looking inside the structure content, but only when running without isolation. To corrupt the key store, we would need to add a function to the library or to use a debugger.
|
0 | repos/gpt4all.zig/src/zig-libcurl/zig-mbedtls/mbedtls/docs/architecture | repos/gpt4all.zig/src/zig-libcurl/zig-mbedtls/mbedtls/docs/architecture/testing/test-framework.md | # Mbed TLS test framework
This document is an overview of the Mbed TLS test framework and test tools.
This document is incomplete. You can help by expanding it.
## Unit tests
See <https://tls.mbed.org/kb/development/test_suites>
### Unit test descriptions
Each test case has a description which succinctly describes for a human audience what the test does. The first non-comment line of each paragraph in a `.data` file is the test description. The following rules and guidelines apply:
* Test descriptions may not contain semicolons, line breaks and other control characters, or non-ASCII characters. <br>
Rationale: keep the tools that process test descriptions (`generate_test_code.py`, [outcome file](#outcome-file) tools) simple.
* Test descriptions must be unique within a `.data` file. If you can't think of a better description, the convention is to append `#1`, `#2`, etc. <br>
Rationale: make it easy to relate a failure log to the test data. Avoid confusion between cases in the [outcome file](#outcome-file).
* Test descriptions should be a maximum of **66 characters**. <br>
Rationale: 66 characters is what our various tools assume (leaving room for 14 more characters on an 80-column line). Longer descriptions may be truncated or may break a visual alignment. <br>
We have a lot of test cases with longer descriptions, but they should be avoided. At least please make sure that the first 66 characters describe the test uniquely.
* Make the description descriptive. “foo: x=2, y=4” is more descriptive than “foo #2”. “foo: 0<x<y, both even” is even better if these inequalities and parities are why this particular test data was chosen.
* Avoid changing the description of an existing test case without a good reason. This breaks the tracking of failures across CI runs, since this tracking is based on the descriptions.
`tests/scripts/check_test_cases.py` enforces some rules and warns if some guidelines are violated.
## TLS tests
### SSL extension tests
#### SSL test case descriptions
Each test case in `ssl-opt.sh` has a description which succinctly describes for a human audience what the test does. The test description is the first parameter to `run_tests`.
The same rules and guidelines apply as for [unit test descriptions](#unit-test-descriptions). In addition, the description must be written on the same line as `run_test`, in double quotes, for the sake of `check_test_cases.py`.
## Running tests
### Outcome file
#### Generating an outcome file
Unit tests and `ssl-opt.sh` record the outcome of each test case in a **test outcome file**. This feature is enabled if the environment variable `MBEDTLS_TEST_OUTCOME_FILE` is set. Set it to the path of the desired file.
If you run `all.sh --outcome-file test-outcome.csv`, this collects the outcome of all the test cases in `test-outcome.csv`.
#### Outcome file format
The outcome file is in a CSV format using `;` (semicolon) as the delimiter and no quoting. This means that fields may not contain newlines or semicolons. There is no title line.
The outcome file has 6 fields:
* **Platform**: a description of the platform, e.g. `Linux-x86_64` or `Linux-x86_64-gcc7-msan`.
* **Configuration**: a unique description of the configuration (`config.h`).
* **Test suite**: `test_suite_xxx` or `ssl-opt`.
* **Test case**: the description of the test case.
* **Result**: one of `PASS`, `SKIP` or `FAIL`.
* **Cause**: more information explaining the result.
|
0 | repos/gpt4all.zig/src/zig-libcurl/zig-mbedtls/mbedtls/docs/architecture | repos/gpt4all.zig/src/zig-libcurl/zig-mbedtls/mbedtls/docs/architecture/testing/driver-interface-test-strategy.md | # Mbed Crypto driver interface test strategy
This document describes the test strategy for the driver interfaces in Mbed Crypto. Mbed Crypto has interfaces for secure element drivers, accelerator drivers and entropy drivers. This document is about testing Mbed Crypto itself; testing drivers is out of scope.
The driver interfaces are standardized through PSA Cryptography functional specifications.
## Secure element driver interface testing
### Secure element driver interfaces
#### Opaque driver interface
The [unified driver interface](../../proposed/psa-driver-interface.md) supports both transparent drivers (for accelerators) and opaque drivers (for secure elements).
Drivers exposing this interface need to be registered at compile time by declaring their JSON description file.
#### Dynamic secure element driver interface
The dynamic secure element driver interface (SE interface for short) is defined by [`psa/crypto_se_driver.h`](../../../include/psa/crypto_se_driver.h). This is an interface between Mbed Crypto and one or more third-party drivers.
The SE interface consists of one function provided by Mbed Crypto (`psa_register_se_driver`) and many functions that drivers must implement. To make a driver usable by Mbed Crypto, the initialization code must call `psa_register_se_driver` with a structure that describes the driver. The structure mostly contains function pointers, pointing to the driver's methods. All calls to a driver function are triggered by a call to a PSA crypto API function.
### SE driver interface unit tests
This section describes unit tests that must be implemented to validate the secure element driver interface. Note that a test case may cover multiple requirements; for example a “good case” test can validate that the proper function is called, that it receives the expected inputs and that it produces the expected outputs.
Many SE driver interface unit tests could be covered by running the existing API tests with a key in a secure element.
#### SE driver registration
This applies to dynamic drivers only.
* Test `psa_register_se_driver` with valid and with invalid arguments.
* Make at least one failing call to `psa_register_se_driver` followed by a successful call.
* Make at least one test that successfully registers the maximum number of drivers and fails to register one more.
#### Dispatch to SE driver
For each API function that can lead to a driver call (more precisely, for each driver method call site, but this is practically equivalent):
* Make at least one test with a key in a secure element that checks that the driver method is called. A few API functions involve multiple driver methods; these should validate that all the expected driver methods are called.
* Make at least one test with a key that is not in a secure element that checks that the driver method is not called.
* Make at least one test with a key in a secure element with a driver that does not have the requisite method (i.e. the method pointer is `NULL`) but has the substructure containing that method, and check that the return value is `PSA_ERROR_NOT_SUPPORTED`.
* Make at least one test with a key in a secure element with a driver that does not have the substructure containing that method (i.e. the pointer to the substructure is `NULL`), and check that the return value is `PSA_ERROR_NOT_SUPPORTED`.
* At least one test should register multiple drivers with a key in each driver and check that the expected driver is called. This does not need to be done for all operations (use a white-box approach to determine if operations may use different code paths to choose the driver).
* At least one test should register the same driver structure with multiple lifetime values and check that the driver receives the expected lifetime value.
Some methods only make sense as a group (for example a driver that provides the MAC methods must provide all or none). In those cases, test with all of them null and none of them null.
#### SE driver inputs
For each API function that can lead to a driver call (more precisely, for each driver method call site, but this is practically equivalent):
* Wherever the specification guarantees parameters that satisfy certain preconditions, check these preconditions whenever practical.
* If the API function can take parameters that are invalid and must not reach the driver, call the API function with such parameters and verify that the driver method is not called.
* Check that the expected inputs reach the driver. This may be implicit in a test that checks the outputs if the only realistic way to obtain the correct outputs is to start from the expected inputs (as is often the case for cryptographic material, but not for metadata).
#### SE driver outputs
For each API function that leads to a driver call, call it with parameters that cause a driver to be invoked and check how Mbed Crypto handles the outputs.
* Correct outputs.
* Incorrect outputs such as an invalid output length.
* Expected errors (e.g. `PSA_ERROR_INVALID_SIGNATURE` from a signature verification method).
* Unexpected errors. At least test that if the driver returns `PSA_ERROR_GENERIC_ERROR`, this is propagated correctly.
Key creation functions invoke multiple methods and need more complex error handling:
* Check the consequence of errors detected at each stage (slot number allocation or validation, key creation method, storage accesses).
* Check that the storage ends up in the expected state. At least make sure that no intermediate file remains after a failure.
#### Persistence of SE keys
The following tests must be performed at least one for each key creation method (import, generate, ...).
* Test that keys in a secure element survive `psa_close_key(); psa_open_key()`.
* Test that keys in a secure element survive `mbedtls_psa_crypto_free(); psa_crypto_init()`.
* Test that the driver's persistent data survives `mbedtls_psa_crypto_free(); psa_crypto_init()`.
* Test that `psa_destroy_key()` does not leave any trace of the key.
#### Resilience for SE drivers
Creating or removing a key in a secure element involves multiple storage modifications (M<sub>1</sub>, ..., M<sub>n</sub>). If the operation is interrupted by a reset at any point, it must be either rolled back or completed.
* For each potential interruption point (before M<sub>1</sub>, between M<sub>1</sub> and M<sub>2</sub>, ..., after M<sub>n</sub>), call `mbedtls_psa_crypto_free(); psa_crypto_init()` at that point and check that this either rolls back or completes the operation that was started.
* This must be done for each key creation method and for key destruction.
* This must be done for each possible flow, including error cases (e.g. a key creation that fails midway due to `OUT_OF_MEMORY`).
* The recovery during `psa_crypto_init` can itself be interrupted. Test those interruptions too.
* Two things need to be tested: the key that is being created or destroyed, and the driver's persistent storage.
* Check both that the storage has the expected content (this can be done by e.g. using a key that is supposed to be present) and does not have any unexpected content (for keys, this can be done by checking that `psa_open_key` fails with `PSA_ERRROR_DOES_NOT_EXIST`).
This requires instrumenting the storage implementation, either to force it to fail at each point or to record successive storage states and replay each of them. Each `psa_its_xxx` function call is assumed to be atomic.
### SE driver system tests
#### Real-world use case
We must have at least one driver that is close to real-world conditions:
* With its own source tree.
* Running on actual hardware.
* Run the full driver validation test suite (which does not yet exist).
* Run at least one test application (e.g. the Mbed OS TLS example).
This requirement shall be fulfilled by the [Microchip ATECC508A driver](https://github.com/ARMmbed/mbed-os-atecc608a/).
#### Complete driver
We should have at least one driver that covers the whole interface:
* With its own source tree.
* Implementing all the methods.
* Run the full driver validation test suite (which does not yet exist).
A PKCS#11 driver would be a good candidate. It would be useful as part of our product offering.
## Transparent driver interface testing
The [unified driver interface](../../proposed/psa-driver-interface.md) defines interfaces for accelerators.
### Test requirements
#### Requirements for transparent driver testing
Every cryptographic mechanism for which a transparent driver interface exists (key creation, cryptographic operations, …) must be exercised in at least one build. The test must verify that the driver code is called.
#### Requirements for fallback
The driver interface includes a fallback mechanism so that a driver can reject a request at runtime and let another driver handle the request. For each entry point, there must be at least three test runs with two or more drivers available with driver A configured to fall back to driver B, with one run where A returns `PSA_SUCCESS`, one where A returns `PSA_ERROR_NOT_SUPPORTED` and B is invoked, and one where A returns a different error and B is not invoked.
## Entropy and randomness interface testing
TODO
|
0 | repos/gpt4all.zig/src/zig-libcurl/zig-mbedtls/mbedtls/docs/architecture | repos/gpt4all.zig/src/zig-libcurl/zig-mbedtls/mbedtls/docs/architecture/testing/psa-storage-format-testing.md | # Mbed TLS PSA keystore format stability testing strategy
## Introduction
The PSA crypto subsystem includes a persistent key store. It is possible to create a persistent key and read it back later. This must work even if Mbed TLS has been upgraded in the meantime (except for deliberate breaks in the backward compatibility of the storage).
The goal of this document is to define a test strategy for the key store that not only validates that it's possible to load a key that was saved with the version of Mbed TLS under test, but also that it's possible to load a key that was saved with previous versions of Mbed TLS.
Interoperability is not a goal: PSA crypto implementations are not intended to have compatible storage formats. Downgrading is not required to work.
## General approach
### Limitations of a direct approach
The goal of storage format stability testing is: as a user of Mbed TLS, I want to store a key under version V and read it back under version W, with W ≥ V.
Doing the testing this way would be difficult because we'd need to have version V of Mbed TLS available when testing version W.
An alternative, semi-direct approach consists of generating test data under version V, and reading it back under version W. Done naively, this would require keeping a large amount of test data (full test coverage multiplied by the number of versions that we want to preserve backward compatibility with).
### Save-and-compare approach
Importing and saving a key is deterministic. Therefore we can ensure the stability of the storage format by creating test cases under a version V of Mbed TLS, where the test case parameters include both the parameters to pass to key creation and the expected state of the storage after the key is created. The test case creates a key as indicated by the parameters, then compares the actual state of the storage with the expected state. In addition, the test case also loads the key and checks that it has the expected data and metadata.
If the test passes with version V, this means that the test data is consistent with what the implementation does. When the test later runs under version W ≥ V, it creates and reads back a storage state which is known to be identical to the state that V would have produced. Thus, this approach validates that W can read storage states created by V.
Use a similar approach for files other than keys where possible and relevant.
### Keeping up with storage format evolution
Test cases should normally not be removed from the code base: if something has worked before, it should keep working in future versions, so we should keep testing it.
If the way certain keys are stored changes, and we don't deliberately decide to stop supporting old keys (which should only be done by retiring a version of the storage format), then we should keep the corresponding test cases in load-only mode: create a file with the expected content, load it and check the data that it contains.
## Storage architecture overview
The PSA subsystem provides storage on top of the PSA trusted storage interface. The state of the storage is a mapping from file identifer (a 64-bit number) to file content (a byte array). These files include:
* [Key files](#key-storage) (files containing one key's metadata and, except for some secure element keys, key material).
* The [random generator injected seed or state file](#random-generator-state) (`PSA_CRYPTO_ITS_RANDOM_SEED_UID`).
* [Storage transaction file](#storage-transaction-resumption).
* [Driver state files](#driver-state-files).
For a more detailed description, refer to the [Mbed Crypto storage specification](../mbed-crypto-storage-specification.md).
In addition, Mbed TLS includes an implementation of the PSA trusted storage interface on top of C stdio. This document addresses the test strategy for [PSA ITS over file](#psa-its-over-file) in a separate section below.
## Key storage testing
This section describes the desired test cases for keys created with the current storage format version. When the storage format changes, if backward compatibility is desired, old test data should be kept as described under [“Keeping up with storage format evolution”](#keeping-up-with-storage-format-evolution).
### Keystore layout
Objective: test that the key file name corresponds to the key identifier.
Method: Create a key with a given identifier (using `psa_import_key`) and verify that a file with the expected name is created, and no other. Repeat for different identifiers.
### General key format
Objective: test the format of the key file: which field goes where and how big it is.
Method: Create a key with certain metadata with `psa_import_key`. Read the file content and validate that it has the expected layout, deduced from the storage specification. Repeat with different metadata. Ensure that there are test cases covering all fields.
### Enumeration of test cases for keys
Objective: ensure that the coverage is sufficient to have assurance that all keys are stored correctly. This requires a sufficient selection of key types, sizes, policies, etc.
In particular, the tests must validate that each `PSA_xxx` constant that is stored in a key is covered by at least once test case:
* Usage flags: `PSA_KEY_USAGE_xxx`.
* Algorithms in policies: `PSA_ALG_xxx`.
* Key types: `PSA_KEY_TYPE_xxx`, `PSA_ECC_FAMILY_xxx`, `PSA_DH_FAMILY_xxx`.
Method: Each test case creates a key with `psa_import_key`, purges it from memory, then reads it back and exercises it. Generate test cases automatically based on an enumeration of available constants and some knowledge of what attributes (sizes, algorithms, …) and content to use for keys of a certain type. Note that the generated test cases will be checked into the repository (generating test cases at runtime would not allow us to test the stability of the format, only that a given version is internally consistent).
### Testing with alternative lifetime values
Objective: have test coverage for lifetimes other than the default persistent lifetime (`PSA_KEY_LIFETIME_PERSISTENT`).
Method:
* For alternative locations: have tests conditional on the presence of a driver for that location.
* For alternative persistence levels: TODO
## Random generator state
TODO
## Driver state files
Not yet implemented.
TODO
## Storage transaction resumption
Only relevant for secure element support. Not yet fully implemented.
TODO
## PSA ITS over file
TODO
|
0 | repos/gpt4all.zig/src/zig-libcurl/zig-mbedtls/mbedtls/docs | repos/gpt4all.zig/src/zig-libcurl/zig-mbedtls/mbedtls/docs/proposed/psa-driver-integration-guide.md | Building Mbed TLS with PSA cryptoprocessor drivers
==================================================
**This is a specification of work in progress. The implementation is not yet merged into Mbed TLS.**
This document describes how to build Mbed TLS with additional cryptoprocessor drivers that follow the PSA cryptoprocessor driver interface.
The interface is not fully implemented in Mbed TLS yet and is disabled by default. You can enable the experimental work in progress by setting `MBEDTLS_PSA_CRYPTO_DRIVERS` in the compile-time configuration. Please note that the interface may still change: until further notice, we do not guarantee backward compatibility with existing driver code when `MBEDTLS_PSA_CRYPTO_DRIVERS` is enabled.
## Introduction
The PSA cryptography driver interface provides a way to build Mbed TLS with additional code that implements certain cryptographic primitives. This is primarily intended to support platform-specific hardware.
Note that such drivers are only available through the PSA cryptography API (crypto functions beginning with `psa_`, and X.509 and TLS interfaces that reference PSA types).
Concretely speaking, a driver consists of one or more **driver description files** in JSON format and some code to include in the build. The driver code can either be provided in binary form as additional object file to link, or in source form.
## How to build Mbed TLS with drivers
To build Mbed TLS with drivers:
1. Activate `MBEDTLS_PSA_CRYPTO_DRIVERS` in the library configuration.
```
cd /path/to/mbedtls
scripts/config.py set MBEDTLS_PSA_CRYPTO_DRIVERS
```
2. Pass the driver description files through the Make variable `PSA_DRIVERS` when building the library.
```
cd /path/to/mbedtls
make PSA_DRIVERS="/path/to/acme/driver.json /path/to/nadir/driver.json" lib
```
3. Link your application with the implementation of the driver functions.
```
cd /path/to/application
ld myapp.o -L/path/to/acme -lacmedriver -L/path/to/nadir -lnadirdriver -L/path/to/mbedtls -lmbedcrypto
```
<!-- TODO: what if the driver is provided as C source code? -->
<!-- TODO: what about additional include files? -->
|
0 | repos/gpt4all.zig/src/zig-libcurl/zig-mbedtls/mbedtls/docs | repos/gpt4all.zig/src/zig-libcurl/zig-mbedtls/mbedtls/docs/proposed/psa-conditional-inclusion-c.md | Conditional inclusion of cryptographic mechanism through the PSA API in Mbed TLS
================================================================================
This document is a proposed interface for deciding at build time which cryptographic mechanisms to include in the PSA Cryptography interface.
This is currently a proposal for Mbed TLS. It is not currently on track for standardization in PSA.
## Introduction
### Purpose of this specification
The [PSA Cryptography API specification](https://armmbed.github.io/mbed-crypto/psa/#application-programming-interface) specifies the interface between a PSA Cryptography implementation and an application. The interface defines a number of categories of cryptographic algorithms (hashes, MAC, signatures, etc.). In each category, a typical implementation offers many algorithms (e.g. for signatures: RSA-PKCS#1v1.5, RSA-PSS, ECDSA). When building the implementation for a specific use case, it is often desirable to include only a subset of the available cryptographic mechanisms, primarily in order to reduce the code footprint of the compiled system.
The present document proposes a way for an application using the PSA cryptography interface to declare which mechanisms it requires.
### Conditional inclusion of legacy cryptography modules
Mbed TLS offers a way to select which cryptographic mechanisms are included in a build through its configuration file (`config.h`). This mechanism is based on two main sets of symbols: `MBEDTLS_xxx_C` controls the availability of the mechanism to the application, and `MBEDTLS_xxx_ALT` controls the availability of an alternative implementation, so the software implementation is only included if `MBEDTLS_xxx_C` is defined but not `MBEDTLS_xxx_ALT`.
### PSA evolution
In the PSA cryptography interface, the **core** (built-in implementations of cryptographic mechanisms) can be augmented with drivers. **Transparent drivers** replace the built-in implementation of a cryptographic mechanism (or, with **fallback**, the built-in implementation is tried if the driver only has partial support for the mechanism). **Opaque drivers** implement cryptographic mechanisms on keys which are stored in a separate domain such as a secure element, for which the core only does key management and dispatch using wrapped key blobs or key identifiers.
The current model is difficult to adapt to the PSA interface for several reasons. The `MBEDTLS_xxx_ALT` symbols are somewhat inconsistent, and in particular do not work well for asymmetric cryptography. For example, many parts of the ECC code have no `MBEDTLS_xxx_ALT` symbol, so a platform with ECC acceleration that can perform all ECDSA and ECDH operations in the accelerator would still embark the `bignum` module and large parts of the `ecp_curves`, `ecp` and `ecdsa` modules. Also the availability of a transparent driver for a mechanism does not translate directly to `MBEDTLS_xxx` symbols.
### Requirements
[Req.interface] The application can declare which cryptographic mechanisms it needs.
[Req.inclusion] If the application does not require a mechanism, a suitably configured Mbed TLS build must not include it. The granularity of mechanisms must work for typical use cases and has [acceptable limitations](#acceptable-limitations).
[Req.drivers] If a PSA driver is available in the build, a suitably configured Mbed TLS build must not include the corresponding software code (unless a software fallback is needed).
[Req.c] The configuration mechanism consists of C preprocessor definitions, and the build does not require tools other than a C compiler. This is necessary to allow building an application and Mbed TLS in development environments that do not allow third-party tools.
[Req.adaptability] The implementation of the mechanism must be adaptable with future evolution of the PSA cryptography specifications and Mbed TLS. Therefore the interface must remain sufficiently simple and abstract.
### Acceptable limitations
[Limitation.matrix] If a mechanism is defined by a combination of algorithms and key types, for example a block cipher mode (CBC, CTR, CFB, …) and a block permutation (AES, CAMELLIA, ARIA, …), there is no requirement to include only specific combinations.
[Limitation.direction] For mechanisms that have multiple directions (for example encrypt/decrypt, sign/verify), there is no requirement to include only one direction.
[Limitation.size] There is no requirement to include only support for certain key sizes.
[Limitation.multipart] Where there are multiple ways to perform an operation, for example single-part and multi-part, there is no mechanism to select only one or a subset of the possible ways.
## Interface
### PSA Crypto configuration file
The PSA Crypto configuration file `psa/crypto_config.h` defines a series of symbols of the form `PSA_WANT_xxx` where `xxx` describes the feature that the symbol enables. The symbols are documented in the section [“PSA Crypto configuration symbols”](#psa-crypto-configuration-symbols) below.
The symbol `MBEDTLS_PSA_CRYPTO_CONFIG` in `mbedtls/config.h` determines whether `psa/crypto_config.h` is used.
* If `MBEDTLS_PSA_CRYPTO_CONFIG` is unset, which is the default at least in Mbed TLS 2.x versions, things are as they are today: the PSA subsystem includes generic code unconditionally, and includes support for specific mechanisms conditionally based on the existing `MBEDTLS_xxx_` symbols.
* If `MBEDTLS_PSA_CRYPTO_CONFIG` is set, the necessary software implementations of cryptographic algorithms are included based on both the content of the PSA Crypto configuration file and the Mbed TLS configuration file. For example, the code in `aes.c` is enabled if either `mbedtls/config.h` contains `MBEDTLS_AES_C` or `psa/crypto_config.h` contains `PSA_WANT_KEY_TYPE_AES`.
### PSA Crypto configuration symbols
#### Configuration symbol syntax
A PSA Crypto configuration symbol is a C preprocessor symbol whose name starts with `PSA_WANT_`.
* If the symbol is not defined, the corresponding feature is not included.
* If the symbol is defined to a preprocessor expression with the value `1`, the corresponding feature is included.
* If the symbol is defined with a different value, the behavior is currently undefined and reserved for future use.
#### Configuration symbol usage
The presence of a symbol `PSA_WANT_xxx` in the Mbed TLS configuration determines whether a feature is available through the PSA API. These symbols should be used in any place that requires conditional compilation based on the availability of a cryptographic mechanism through the PSA API, including:
* In Mbed TLS test code.
* In Mbed TLS library code using `MBEDTLS_USE_PSA_CRYPTO`, for example in TLS to determine which cipher suites to enable.
* In application code that provides additional features based on cryptographic capabilities, for example additional key parsing and formatting functions, or cipher suite availability for network protocols.
#### Configuration symbol semantics
If a feature is not requested for inclusion in the PSA Crypto configuration file, it may still be included in the build, either because the feature has been requested in some other way, or because the library does not support the exclusion of this feature. Mbed TLS should make a best effort to support the exclusion of all features, but in some cases this may be judged too much effort for too little benefit.
#### Configuration symbols for key types
For each constant or constructor macro of the form `PSA_KEY_TYPE_xxx`, the symbol **`PSA_WANT_KEY_TYPE_xxx`** indicates that support for this key type is desired.
For asymmetric cryptography, `PSA_WANT_KEY_TYPE_xxx_KEY_PAIR` determines whether private-key operations are desired, and `PSA_WANT_KEY_TYPE_xxx_PUBLIC_KEY` determines whether public-key operations are desired. `PSA_WANT_KEY_TYPE_xxx_KEY_PAIR` implicitly enables `PSA_WANT_KEY_TYPE_xxx_PUBLIC_KEY`: there is no way to only include private-key operations (which typically saves little code).
#### Configuration symbols for elliptic curves
For elliptic curve key types, only the specified curves are included. To include a curve, include a symbol of the form **`PSA_WANT_ECC_family_size`**. For example: `PSA_WANT_ECC_SECP_R1_256` for secp256r1, `PSA_WANT_ECC_MONTGOMERY_255` for Curve25519. It is an error to require an ECC key type but no curve, and Mbed TLS will reject this at compile time.
Rationale: this is a deviation of the general principle that `PSA_ECC_FAMILY_xxx` would have a corresponding symbol `PSA_WANT_ECC_FAMILY_xxx`. This deviation is justified by the fact that it is very common to wish to include only certain curves in a family, and that can lead to a significant gain in code size.
#### Configuration symbols for Diffie-Hellman groups
There are no configuration symbols for Diffie-Hellman groups (`PSA_DH_GROUP_xxx`).
Rationale: Finite-field Diffie-Hellman code is usually not specialized for any particular group, so reducing the number of available groups at compile time only saves a little code space. Constrained implementations tend to omit FFDH anyway, so the small code size gain is not important.
#### Configuration symbols for algorithms
For each constant or constructor macro of the form `PSA_ALG_xxx`, the symbol **`PSA_WANT_ALG_xxx`** indicates that support for this algorithm is desired.
For parametrized algorithms, the `PSA_WANT_ALG_xxx` symbol indicates whether the base mechanism is supported. Parameters must themselves be included through their own `PSA_WANT_ALG_xxx` symbols. It is an error to include a base mechanism without at least one possible parameter, and Mbed TLS will reject this at compile time. For example, `PSA_WANT_ALG_ECDSA` requires the inclusion of randomized ECDSA for all hash algorithms whose corresponding symbol `PSA_WANT_ALG_xxx` is enabled.
## Implementation
### Additional non-public symbols
#### Accounting for transparent drivers
In addition to the [configuration symbols](#psa-crypto-configuration-symbols), we need two parallel or mostly parallel sets of symbols:
* **`MBEDTLS_PSA_ACCEL_xxx`** indicates whether a fully-featured, fallback-free transparent driver is available.
* **`MBEDTLS_PSA_BUILTIN_xxx`** indicates whether the software implementation is needed.
`MBEDTLS_PSA_ACCEL_xxx` is one of the outputs of the transpilation of a driver description, alongside the glue code for calling the drivers.
`MBEDTLS_PSA_BUILTIN_xxx` is enabled when `PSA_WANT_xxx` is enabled and `MBEDTLS_PSA_ACCEL_xxx` is disabled.
These symbols are not part of the public interface of Mbed TLS towards applications or to drivers, regardless of whether the symbols are actually visible.
### Architecture of symbol definitions
#### New-style definition of configuration symbols
When `MBEDTLS_PSA_CRYPTO_CONFIG` is set, the header file `mbedtls/config.h` needs to define all the `MBEDTLS_xxx_C` configuration symbols, including the ones deduced from the PSA Crypto configuration. It does this by including the new header file **`mbedtls/config_psa.h`**, which defines the `MBEDTLS_PSA_BUILTIN_xxx` symbols and deduces the corresponding `MBEDTLS_xxx_C` (and other) symbols.
`mbedtls/config_psa.h` includes `psa/crypto_config.h`, the user-editable file that defines application requirements.
#### Old-style definition of configuration symbols
When `MBEDTLS_PSA_CRYPTO_CONFIG` is not set, the configuration of Mbed TLS works as before, and the inclusion of non-PSA code only depends on `MBEDTLS_xxx` symbols defined (or not) in `mbedtls/config.h`. Furthermore, the new header file **`mbedtls/config_psa.h`** deduces PSA configuration symbols (`PSA_WANT_xxx`, `MBEDTLS_PSA_BUILTIN_xxx`) from classic configuration symbols (`MBEDTLS_xxx`).
The `PSA_WANT_xxx` definitions in `mbedtls/config_psa.h` are needed not only to build the PSA parts of the library, but also to build code that uses these parts. This includes structure definitions in `psa/crypto_struct.h`, size calculations in `psa/crypto_sizes.h`, and application code that's specific to a given cryptographic mechanism. In Mbed TLS itself, code under `MBEDTLS_USE_PSA_CRYPTO` and conditional compilation guards in tests and sample programs need `PSA_WANT_xxx`.
Since some existing applications use a handwritten `mbedtls/config.h` or an edited copy of `mbedtls/config.h` from an earlier version of Mbed TLS, `mbedtls/config_psa.h` must be included via an already existing header that is not `mbedtls/config.h`, so it is included via `psa/crypto.h` (for example from `psa/crypto_platform.h`).
#### Summary of definitions of configuration symbols
Whether `MBEDTLS_PSA_CRYPTO_CONFIG` is set or not, `mbedtls/config_psa.h` includes `mbedtls/crypto_drivers.h`, a header file generated by the transpilation of the driver descriptions. It defines `MBEDTLS_PSA_ACCEL_xxx` symbols according to the availability of transparent drivers without fallback.
The following table summarizes where symbols are defined depending on the configuration mode.
* (U) indicates a symbol that is defined by the user (application).
* (D) indicates a symbol that is deduced from other symbols by code that ships with Mbed TLS.
* (G) indicates a symbol that is generated from driver descriptions.
| Symbols | With `MBEDTLS_PSA_CRYPTO_CONFIG` | Without `MBEDTLS_PSA_CRYPTO_CONFIG` |
| ------------------------- | -------------------------------- | ----------------------------------- |
| `MBEDTLS_xxx_C` | `mbedtls/config.h` (U) or | `mbedtls/config.h` (U) |
| | `mbedtls/config_psa.h` (D) | |
| `PSA_WANT_xxx` | `psa/crypto_config.h` (U) | `mbedtls/config_psa.h` (D) |
| `MBEDTLS_PSA_BUILTIN_xxx` | `mbedtls/config_psa.h` (D) | `mbedtls/config_psa.h` (D) |
| `MBEDTLS_PSA_ACCEL_xxx` | `mbedtls/crypto_drivers.h` (G) | N/A |
#### Visibility of internal symbols
Ideally, the `MBEDTLS_PSA_ACCEL_xxx` and `MBEDTLS_PSA_BUILTIN_xxx` symbols should not be visible to application code or driver code, since they are not part of the public interface of the library. However these symbols are needed to deduce whether to include library modules (for example `MBEDTLS_AES_C` has to be enabled if `MBEDTLS_PSA_BUILTIN_KEY_TYPE_AES` is enabled), which makes it difficult to keep them private.
#### Compile-time checks
The header file **`library/psa_check_config.h`** applies sanity checks to the configuration, throwing `#error` if something is wrong.
A mechanism similar to `mbedtls/check_config.h` detects errors such as enabling ECDSA but no curve.
Since configuration symbols must be undefined or 1, any other value should trigger an `#error`.
#### Automatic generation of preprocessor symbol manipulations
A lot of the preprocessor symbol manipulation is systematic calculations that analyze the configuration. `mbedtls/config_psa.h` and `library/psa_check_config.h` should be generated automatically, in the same manner as `version_features.c`.
### Structure of PSA Crypto library code
#### Conditional inclusion of library entry points
An entry point can be eliminated entirely if no algorithm requires it.
#### Conditional inclusion of mechanism-specific code
Code that is specific to certain key types or to certain algorithms must be guarded by the applicable symbols: `PSA_WANT_xxx` for code that is independent of the application, and `MBEDTLS_PSA_BUILTIN_xxx` for code that calls an Mbed TLS software implementation.
## PSA standardization
### JSON configuration mechanism
At the time of writing, the preferred configuration mechanism for a PSA service is in JSON syntax. The translation from JSON to build instructions is not specified by PSA.
For PSA Crypto, the preferred configuration mechanism would be similar to capability specifications of transparent drivers. The same JSON properties that are used to mean “this driver can perform that mechanism” in a driver description would be used to mean “the application wants to perform that mechanism” in the application configuration.
### From JSON to C
The JSON capability language allows a more fine-grained selection than the C mechanism proposed here. For example, it allows requesting only single-part mechanisms, only certain key sizes, or only certain combinations of algorithms and key types.
The JSON capability language can be translated approximately to the boolean symbol mechanism proposed here. The approximation considers a feature to be enabled if any part of it is enabled. For example, if there is a capability for AES-CTR and one for CAMELLIA-GCM, the translation to boolean symbols will also include AES-GCM and CAMELLIA-CTR. If there is a capability for AES-128, the translation will also include AES-192 and AES-256.
The boolean symbol mechanism proposed here can be translated to a list of JSON capabilities: for each included algorithm, include a capability with that algorithm, the key types that apply to that algorithm, no size restriction, and all the entry points that apply to that algorithm.
## Open questions
### Open questions about the interface
#### Naming of symbols
The names of [elliptic curve symbols](#configuration-symbols-for-elliptic-curves) are a bit weird: `SECP_R1_256` instead of `SECP256R1`, `MONTGOMERY_255` instead of `CURVE25519`. Should we make them more classical, but less systematic?
#### Impossible combinations
What does it mean to have `PSA_WANT_ALG_ECDSA` enabled but with only Curve25519? Is it a mandatory error?
#### Diffie-Hellman
Way to request only specific groups? Not a priority: constrained devices don't do FFDH. Specify it as may change in future versions.
#### Coexistence with the current Mbed TLS configuration
The two mechanisms have very different designs. Is there serious potential for confusion? Do we understand how the combinations work?
### Open questions about the design
#### Algorithms without a key type or vice versa
Is it realistic to mandate a compile-time error if a key type is required, but no matching algorithm, or vice versa? Is it always the right thing, for example if there is an opaque driver that manipulates this key type?
#### Opaque-only mechanisms
If a mechanism should only be supported in an opaque driver, what does the core need to know about it? Do we have all the information we need?
This is especially relevant to suppress a mechanism completely if there is no matching algorithm. For example, if there is no transparent implementation of RSA or ECDSA, `psa_sign_hash` and `psa_verify_hash` may still be needed if there is an opaque signature driver.
### Open questions about the implementation
#### Testability
Is this proposal decently testable? There are a lot of combinations. What combinations should we test?
<!--
Local Variables:
time-stamp-line-limit: 40
time-stamp-start: "Time-stamp: *\""
time-stamp-end: "\""
time-stamp-format: "%04Y/%02m/%02d %02H:%02M:%02S %Z"
time-stamp-time-zone: "GMT"
End:
-->
|
0 | repos/gpt4all.zig/src/zig-libcurl/zig-mbedtls/mbedtls/docs | repos/gpt4all.zig/src/zig-libcurl/zig-mbedtls/mbedtls/docs/proposed/psa-driver-interface.md | PSA Cryptoprocessor Driver Interface
====================================
This document describes an interface for cryptoprocessor drivers in the PSA cryptography API. This interface complements the [PSA Cryptography API specification](https://armmbed.github.io/mbed-crypto/psa/#application-programming-interface), which describes the interface between a PSA Cryptography implementation and an application.
This specification is work in progress and should be considered to be in a beta stage. There is ongoing work to implement this interface in Mbed TLS, which is the reference implementation of the PSA Cryptography API. At this stage, Arm does not expect major changes, but minor changes are expected based on experience from the first implementation and on external feedback.
## Introduction
### Purpose of the driver interface
The PSA Cryptography API defines an interface that allows applications to perform cryptographic operations in a uniform way regardless of how the operations are performed. Under the hood, different keys may be stored and used in different hardware or in different logical partitions, and different algorithms may involve different hardware or software components.
The driver interface allows implementations of the PSA Cryptography API to be built compositionally. An implementation of the PSA Cryptography API is composed of a **core** and zero or more **drivers**. The core handles key management, enforces key usage policies, and dispatches cryptographic operations either to the applicable driver or to built-in code.
Functions in the PSA Cryptography API invoke functions in the core. Code from the core calls drivers as described in the present document.
### Types of drivers
The PSA Cryptography driver interface supports two types of cryptoprocessors, and accordingly two types of drivers.
* **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](#lifetimes-and-locations) that the driver is registered for: the dispatch is based on the key's lifetime.
### Requirements
The present specification was designed to fulfill the following high-level requirements.
[Req.plugins] It is possible to combine multiple drivers from different providers into the same implementation, without any prior arrangement other than choosing certain names and values from disjoint namespaces.
[Req.compile] It is possible to compile the code of each driver and of the core separately, and link them together. A small amount of glue code may need to be compiled once the list of drivers is available.
[Req.types] Support drivers for the following types of hardware: accelerators that operate on keys in cleartext; cryptoprocessors that can wrap keys with a built-in keys but not store user keys; and cryptoprocessors that store key material.
[Req.portable] The interface between drivers and the core does not involve any platform-specific consideration. Driver calls are simple C function calls. Interactions with platform-specific hardware happen only inside the driver (and in fact a driver need not involve any hardware at all).
[Req.location] Applications can tell which location values correspond to which secure element drivers.
[Req.fallback] Accelerator drivers can specify that they do not fully support a cryptographic mechanism and that a fallback to core code may be necessary. Conversely, if an accelerator fully supports cryptographic mechanism, the core must be able to omit code for this mechanism.
[Req.mechanisms] Drivers can specify which mechanisms they support. A driver's code will not be invoked for cryptographic mechanisms that it does not support.
## Overview of drivers
### Deliverables for a driver
To write a driver, you need to implement some functions with C linkage, and to declare these functions in a **driver description file**. The driver description file declares which functions the driver implements and what cryptographic mechanisms they support. If the driver description references custom types, macros or constants, you also need to provide C header files defining those elements.
The concrete syntax for a driver description file is JSON. The structure of this JSON file is specified in the section [“Driver description syntax”](#driver-description-syntax).
A driver therefore consists of:
* A driver description file (in JSON format).
* C header files defining the types required by the driver description. The names of these header files are declared in the driver description file.
* An object file compiled for the target platform defining the entry point functions specified by the driver description. Implementations may allow drivers to be provided as source files and compiled with the core instead of being pre-compiled.
How to provide the driver description file, the C header files and the object code is implementation-dependent.
### Driver description syntax
The concrete syntax for a driver description file is JSON.
#### Driver description list
PSA Cryptography core implementations should support multiple drivers. The driver description files are passed to the implementation as an ordered list in an unspecified manner. This may be, for example, a list of file names passed on a command line, or a JSON list whose elements are individual driver descriptions.
#### Driver description top-level element
A driver description is a JSON object containing the following properties:
* `"prefix"` (mandatory, string). This must be a valid prefix for a C identifier. All the types and functions provided by the driver have a name that starts with this prefix unless overridden with a `"name"` element in the applicable capability as described below.
* `"type"` (mandatory, string). One of `"transparent"` or `"opaque"`.
* `"headers"` (optional, array of strings). A list of header files. These header files must define the types, macros and constants referenced by the driver description. They may declare the entry point functions, but this is not required. They may include other PSA headers and standard headers of the platform. Whether they may include other headers is implementation-specific. If omitted, the list of headers is empty. The header files must be present at the specified location relative to a directory on the compiler's include path when compiling glue code between the core and the drivers.
* `"capabilities"` (mandatory, array of [capabilities](#driver-description-capability)).
A list of **capabilities**. Each capability describes a family of functions that the driver implements for a certain class of cryptographic mechanisms.
* `"key_context"` (not permitted for transparent drivers, mandatory for opaque drivers): information about the [representation of keys](#key-format-for-opaque-drivers).
* `"persistent_state_size"` (not permitted for transparent drivers, optional for opaque drivers, integer or string). The size in bytes of the [persistent state of the driver](#opaque-driver-persistent-state). This may be either a non-negative integer or a C constant expression of type `size_t`.
* `"location"` (not permitted for transparent drivers, optional for opaque drivers, integer or string). The [location value](#lifetimes-and-locations) for which this driver is invoked. In other words, this determines the lifetimes for which the driver is invoked. This may be either a non-negative integer or a C constant expression of type `psa_key_location_t`.
### Driver description capability
#### Capability syntax
A capability declares a family of functions that the driver implements for a certain class of cryptographic mechanisms. The capability specifies which key types and algorithms are covered and the names of the types and functions that implement it.
A capability is a JSON object containing the following properties:
* `"entry_points"` (mandatory, list of strings). Each element is the name of a [driver entry point](#driver-entry-points) or driver entry point family. An entry point is a function defined by the driver. If specified, the core will invoke this capability of the driver only when performing one of the specified operations. The driver must implement all the specified entry points, as well as the types if applicable.
* `"algorithms"` (optional, list of strings). Each element is an [algorithm specification](#algorithm-specifications). If specified, the core will invoke this capability of the driver only when performing one of the specified algorithms. If omitted, the core will invoke this capability for all applicable algorithms.
* `"key_types"` (optional, list of strings). Each element is a [key type specification](#key-type-specifications). If specified, the core will invoke this capability of the driver only for operations involving a key with one of the specified key types. If omitted, the core will invoke this capability of the driver for all applicable key types.
* `"key_sizes"` (optional, list of integers). If specified, the core will invoke this capability of the driver only for operations involving a key with one of the specified key sizes. If omitted, the core will invoke this capability of the driver for all applicable key sizes. Key sizes are expressed in bits.
* `"names"` (optional, object). A mapping from entry point names described by the `"entry_points"` property, to the name of the C function in the driver that implements the corresponding function. If a function is not listed here, name of the driver function that implements it is the driver's prefix followed by an underscore (`_`) followed by the function name. If this property is omitted, it is equivalent to an empty object (so each entry point *suffix* is implemented by a function called *prefix*`_`*suffix*).
* `"fallback"` (optional for transparent drivers, not permitted for opaque drivers, boolean). If present and true, the driver may return `PSA_ERROR_NOT_SUPPORTED`, in which case the core should call another driver or use built-in code to perform this operation. If absent or false, the driver is expected to fully support the mechanisms described by this capability. See the section “[Fallback](#fallback)” for more information.
#### Capability semantics
When the PSA Cryptography implementation performs a cryptographic mechanism, it invokes available driver entry points as described in the section [“Driver entry points”](#driver-entry-points).
A driver is considered available for a cryptographic mechanism that invokes a given entry point if all of the following conditions are met:
* The driver specification includes a capability whose `"entry_points"` list either includes the entry point or includes an entry point family that includes the entry point.
* If the mechanism involves an algorithm:
* either the capability does not have an `"algorithms"` property;
* or the value of the capability's `"algorithms"` property includes an [algorithm specification](#algorithm-specifications) that matches this algorithm.
* If the mechanism involves a key:
* either the key is transparent (its location is `PSA_KEY_LOCATION_LOCAL_STORAGE`) and the driver is transparent;
* or the key is opaque (its location is not `PSA_KEY_LOCATION_LOCAL_STORAGE`) and the driver is an opaque driver whose location is the key's location.
* If the mechanism involves a key:
* either the capability does not have a `"key_types"` property;
* or the value of the capability's `"key_types"` property includes a [key type specification](#key-type-specifications) that matches this algorithm.
* If the mechanism involves a key:
* either the capability does not have a `"key_sizes"` property;
* or the value of the capability's `"key_sizes"` property includes the key's size.
If a driver includes multiple applicable capabilities for a given combination of entry point, algorithm, key type and key size, and all the capabilities map the entry point to the same function name, the driver is considered available for this cryptographic mechanism. If a driver includes multiple applicable capabilities for a given combination of entry point, algorithm, key type and key size, and at least two of these capabilities map the entry point to the different function names, the driver specification is invalid.
If multiple transparent drivers have applicable capabilities for a given combination of entry point, algorithm, key type and key size, the first matching driver in the [specification list](#driver-description-list) is invoked. If the capability has [fallback](#fallback) enabled and the first driver returns `PSA_ERROR_NOT_SUPPORTED`, the next matching driver is invoked, and so on.
If multiple opaque drivers have the same location, the list of driver specifications is invalid.
#### Capability examples
Example 1: the following capability declares that the driver can perform deterministic ECDSA signatures (but not signature verification) using any hash algorithm and any curve that the core supports. If the prefix of this driver is `"acme"`, the function that performs the signature is called `acme_sign_hash`.
```
{
"entry_points": ["sign_hash"],
"algorithms": ["PSA_ALG_DETERMINISTIC_ECDSA(PSA_ALG_ANY_HASH)"],
}
```
Example 2: the following capability declares that the driver can perform deterministic ECDSA signatures using SHA-256 or SHA-384 with a SECP256R1 or SECP384R1 private key (with either hash being possible in combination with either curve). If the prefix of this driver is `"acme"`, the function that performs the signature is called `acme_sign_hash`.
```
{
"entry_points": ["sign_hash"],
"algorithms": ["PSA_ALG_DETERMINISTIC_ECDSA(PSA_ALG_SHA_256)",
"PSA_ALG_DETERMINISTIC_ECDSA(PSA_ALG_SHA_384)"],
"key_types": ["PSA_KEY_TYPE_ECC_KEY_PAIR(PSA_ECC_FAMILY_SECP_R1)"],
"key_sizes": [256, 384]
}
```
### Algorithm and key specifications
#### Algorithm specifications
An algorithm specification is a string consisting of a `PSA_ALG_xxx` macro that specifies a cryptographic algorithm or an algorithm wildcard policy defined by the PSA Cryptography API. If the macro takes arguments, the string must have the syntax of a C macro call and each argument must be an algorithm specification or a decimal or hexadecimal literal with no suffix, depending on the expected type of argument.
Spaces are optional after commas. Whether other whitespace is permitted is implementation-specific.
Valid examples:
```
PSA_ALG_SHA_256
PSA_ALG_HMAC(PSA_ALG_SHA_256)
PSA_ALG_KEY_AGREEMENT(PSA_ALG_ECDH, PSA_ALG_HKDF(PSA_ALG_SHA_256))
PSA_ALG_RSA_PSS(PSA_ALG_ANY_HASH)
```
#### Key type specifications
An algorithm specification is a string consisting of a `PSA_KEY_TYPE_xxx` macro that specifies a key type defined by the PSA Cryptography API. If the macro takes an argument, the string must have the syntax of a C macro call and each argument must be the name of a constant of suitable type (curve or group).
The name `_` may be used instead of a curve or group to indicate that the capability concerns all curves or groups.
Valid examples:
```
PSA_KEY_TYPE_AES
PSA_KEY_TYPE_ECC_KEY_PAIR(PSA_ECC_FAMILY_SECP_R1)
PSA_KEY_TYPE_ECC_KEY_PAIR(_)
```
### Driver entry points
#### Overview of driver entry points
Drivers define functions, each of which implements an aspect of a capability of a driver, such as a cryptographic operation, a part of a cryptographic operation, or a key management action. These functions are called the **entry points** of the driver. Most driver entry points correspond to a particular function in the PSA Cryptography API. For example, if a call to `psa_sign_hash()` is dispatched to a driver, it invokes the driver's `sign_hash` function.
All driver entry points return a status of type `psa_status_t` which should use the status codes documented for PSA services in general and for PSA Cryptography in particular: `PSA_SUCCESS` indicates that the function succeeded, and `PSA_ERROR_xxx` values indicate that an error occurred.
The signature of a driver entry point generally looks like the signature of the PSA Cryptography API that it implements, with some modifications. This section gives an overview of modifications that apply to whole classes of entry points. Refer to the reference section for each entry point or entry point family for details.
* For entry points that operate on an existing key, the `psa_key_id_t` parameter is replaced by a sequence of three parameters that describe the key:
1. `const psa_key_attributes_t *attributes`: the key attributes.
2. `const uint8_t *key_buffer`: a key material or key context buffer.
3. `size_t key_buffer_size`: the size of the key buffer in bytes.
For transparent drivers, the key buffer contains the key material, in the same format as defined for `psa_export_key()` and `psa_export_public_key()` in the PSA Cryptography API. For opaque drivers, the content of the key buffer is entirely up to the driver.
* For entry points that involve a multi-part operation, the operation state type (`psa_XXX_operation_t`) is replaced by a driver-specific operation state type (*prefix*`_XXX_operation_t`).
* For entry points that are involved in key creation, the `psa_key_id_t *` output parameter is replaced by a sequence of parameters that convey the key context:
1. `uint8_t *key_buffer`: a buffer for the key material or key context.
2. `size_t key_buffer_size`: the size of the key buffer in bytes.
2. `size_t *key_buffer_length`: the length of the data written to the key buffer in bytes.
Some entry points are grouped in families that must be implemented as a whole. If a driver supports an entry point family, it must provide all the entry points in the family.
Drivers can also have entry points related to random generation. A transparent driver can provide a [random generation interface](#random-generation-entry-points). Separately, transparent and opaque drivers can have [entropy collection entry points](#entropy-collection-entry-point).
#### General considerations on driver entry point parameters
Buffer parameters for driver entry points obey the following conventions:
* An input buffer has the type `const uint8_t *` and is immediately followed by a parameter of type `size_t` that indicates the buffer size.
* An output buffer has the type `uint8_t *` and is immediately followed by a parameter of type `size_t` that indicates the buffer size. A third parameter of type `size_t *` is provided to report the actual length of the data written in the buffer if the function succeeds.
* An in-out buffer has the type `uint8_t *` and is immediately followed by a parameter of type `size_t` that indicates the buffer size. In-out buffers are only used when the input and the output have the same length.
Buffers of size 0 may be represented with either a null pointer or a non-null pointer.
Input buffers and other input-only parameters (`const` pointers) may be in read-only memory. Overlap is possible between input buffers, and between an input buffer and an output buffer, but not between two output buffers or between a non-buffer parameter and another parameter.
#### Driver entry points for single-part cryptographic operations
The following driver entry points perform a cryptographic operation in one shot (single-part operation):
* `"hash_compute"` (transparent drivers only): calculation of a hash. Called by `psa_hash_compute()` and `psa_hash_compare()`. To verify a hash with `psa_hash_compare()`, the core calls the driver's `"hash_compute"` entry point and compares the result with the reference hash value.
* `"mac_compute"`: calculation of a MAC. Called by `psa_mac_compute()` and possibly `psa_mac_verify()`. To verify a mac with `psa_mac_verify()`, the core calls an applicable driver's `"mac_verify"` entry point if there is one, otherwise the core calls an applicable driver's `"mac_compute"` entry point and compares the result with the reference MAC value.
* `"mac_verify"`: verification of a MAC. Called by `psa_mac_verify()`. This entry point is mainly useful for drivers of secure elements that verify a MAC without revealing the correct MAC. Although transparent drivers may implement this entry point in addition to `"mac_compute"`, it is generally not useful because the core can call the `"mac_compute"` entry point and compare with the expected MAC value.
* `"cipher_encrypt"`: unauthenticated symmetric cipher encryption. Called by `psa_cipher_encrypt()`.
* `"cipher_decrypt"`: unauthenticated symmetric cipher decryption. Called by `psa_cipher_decrypt()`.
* `"aead_encrypt"`: authenticated encryption with associated data. Called by `psa_aead_encrypt()`.
* `"aead_decrypt"`: authenticated decryption with associated data. Called by `psa_aead_decrypt()`.
* `"asymmetric_encrypt"`: asymmetric encryption. Called by `psa_asymmetric_encrypt()`.
* `"asymmetric_decrypt"`: asymmetric decryption. Called by `psa_asymmetric_decrypt()`.
* `"sign_hash"`: signature of an already calculated hash. Called by `psa_sign_hash()` and possibly `psa_sign_message()`. To sign a message with `psa_sign_message()`, the core calls an applicable driver's `"sign_message"` entry point if there is one, otherwise the core calls an applicable driver's `"hash_compute"` entry point followed by an applicable driver's `"sign_hash"` entry point.
* `"verify_hash"`: verification of an already calculated hash. Called by `psa_verify_hash()` and possibly `psa_verify_message()`. To verify a message with `psa_verify_message()`, the core calls an applicable driver's `"verify_message"` entry point if there is one, otherwise the core calls an applicable driver's `"hash_compute"` entry point followed by an applicable driver's `"verify_hash"` entry point.
* `"sign_message"`: signature of a message. Called by `psa_sign_message()`.
* `"verify_message"`: verification of a message. Called by `psa_verify_message()`.
* `"key_agreement"`: key agreement without a subsequent key derivation. Called by `psa_raw_key_agreement()` and possibly `psa_key_derivation_key_agreement()`.
### Driver entry points for multi-part operations
#### General considerations on multi-part operations
The entry points that implement each step of a multi-part operation are grouped into a family. A driver that implements a multi-part operation must define all of the entry points in this family as well as a type that represents the operation context. The lifecycle of a driver operation context is similar to the lifecycle of an API operation context:
1. The core initializes operation context objects to either all-bits-zero or to logical zero (`{0}`), at its discretion.
1. The core calls the `xxx_setup` entry point for this operation family. If this fails, the core destroys the operation context object without calling any other driver entry point on it.
1. The core calls other entry points that manipulate the operation context object, respecting the constraints.
1. If any entry point fails, the core calls the driver's `xxx_abort` entry point for this operation family, then destroys the operation context object without calling any other driver entry point on it.
1. If a “finish” entry point fails, the core destroys the operation context object without calling any other driver entry point on it. The finish entry points are: *prefix*`_mac_sign_finish`, *prefix*`_mac_verify_finish`, *prefix*`_cipher_fnish`, *prefix*`_aead_finish`, *prefix*`_aead_verify`.
If a driver implements a multi-part operation but not the corresponding single-part operation, the core calls the driver's multipart operation entry points to perform the single-part operation.
#### Multi-part operation entry point family `"hash_multipart"`
This family corresponds to the calculation of a hash in multiple steps.
This family applies to transparent drivers only.
This family requires the following type and entry points:
* Type `"hash_operation_t"`: the type of a hash operation context. It must be possible to copy a hash operation context byte by byte, therefore hash operation contexts must not contain any embedded pointers (except pointers to global data that do not change after the setup step).
* `"hash_setup"`: called by `psa_hash_setup()`.
* `"hash_update"`: called by `psa_hash_update()`.
* `"hash_finish"`: called by `psa_hash_finish()` and `psa_hash_verify()`.
* `"hash_abort"`: called by all multi-part hash functions of the PSA Cryptography API.
To verify a hash with `psa_hash_verify()`, the core calls the driver's *prefix*`_hash_finish` entry point and compares the result with the reference hash value.
For example, a driver with the prefix `"acme"` that implements the `"hash_multipart"` entry point family must define the following type and entry points (assuming that the capability does not use the `"names"` property to declare different type and entry point names):
```
typedef ... acme_hash_operation_t;
psa_status_t acme_hash_setup(acme_hash_operation_t *operation,
psa_algorithm_t alg);
psa_status_t acme_hash_update(acme_hash_operation_t *operation,
const uint8_t *input,
size_t input_length);
psa_status_t acme_hash_finish(acme_hash_operation_t *operation,
uint8_t *hash,
size_t hash_size,
size_t *hash_length);
psa_status_t acme_hash_abort(acme_hash_operation_t *operation);
```
#### Operation family `"mac_multipart"`
TODO
#### Operation family `"mac_verify_multipart"`
TODO
#### Operation family `"cipher_encrypt_multipart"`
TODO
#### Operation family `"cipher_decrypt_multipart"`
TODO
#### Operation family `"aead_encrypt_multipart"`
TODO
#### Operation family `"aead_decrypt_multipart"`
TODO
#### Operation family `"key_derivation"`
This family requires the following type and entry points:
* Type `"key_derivation_operation_t"`: the type of a key derivation operation context.
* `"key_derivation_setup"`: called by `psa_key_derivation_setup()`.
* `"key_derivation_set_capacity"`: called by `psa_key_derivation_set_capacity()`. The core will always enforce the capacity, therefore this function does not need to do anything for algorithms where the output stream only depends on the effective generated length and not on the capacity.
* `"key_derivation_input_bytes"`: called by `psa_key_derivation_input_bytes()` and `psa_key_derivation_input_key()`. For transparent drivers, when processing a call to `psa_key_derivation_input_key()`, the core always calls the applicable driver's `"key_derivation_input_bytes"` entry point.
* `"key_derivation_input_key"` (opaque drivers only)
* `"key_derivation_output_bytes"`: called by `psa_key_derivation_output_bytes()`; also by `psa_key_derivation_output_key()` for transparent drivers.
* `"key_derivation_output_key"`: called by `psa_key_derivation_output_key()` for transparent drivers when deriving an asymmetric key pair, and also for opaque drivers.
* `"key_derivation_abort"`: called by all key derivation functions of the PSA Cryptography API.
TODO: key input and output for opaque drivers; deterministic key generation for transparent drivers
TODO
### Driver entry points for key management
The driver entry points for key management differ significantly between [transparent drivers](#key-management-with-transparent-drivers) and [opaque drivers](#key-management-with-opaque-drivers). This section describes common elements. Refer to the applicable section for each driver type for more information.
The entry points that create or format key data have the following prototypes for a driver with the prefix `"acme"`:
```
psa_status_t acme_import_key(const psa_key_attributes_t *attributes,
const uint8_t *data,
size_t data_length,
uint8_t *key_buffer,
size_t key_buffer_size,
size_t *key_buffer_length,
size_t *bits); // additional parameter, see below
psa_status_t acme_generate_key(const psa_key_attributes_t *attributes,
uint8_t *key_buffer,
size_t key_buffer_size,
size_t *key_buffer_length);
```
TODO: derivation, copy
* The key attributes (`attributes`) have the same semantics as in the PSA Cryptography application interface.
* For the `"import_key"` entry point, the input in the `data` buffer is either the export format or an implementation-specific format that the core documents as an acceptable input format for `psa_import_key()`.
* The size of the key data buffer `key_buffer` is sufficient for the internal representation of the key. For a transparent driver, this is the key's [export format](#key-format-for-transparent-drivers). For an opaque driver, this is the size determined from the driver description and the key attributes, as specified in the section [“Key format for opaque drivers”](#key-format-for-opaque-drivers).
* For an opaque driver with an `"allocate_key"` entry point, the content of the key data buffer on entry is the output of that entry point.
* The `"import_key"` entry point must determine or validate the key size and set `*bits` as described in the section [“Key size determination on import”](#key-size-determination-on-import) below.
All key creation entry points must ensure that the resulting key is valid as specified in the section [“Key validation”](#key-validation) below. This is primarily important for import entry points since the key data comes from the application.
#### Key size determination on import
The `"import_key"` entry point must determine or validate the key size.
The PSA Cryptography API exposes the key size as part of the key attributes.
When importing a key, the key size recorded in the key attributes can be either a size specified by the caller of the API (who may not be trusted), or `0` which indicates that the size must be calculated from the data.
When the core calls the `"import_key"` entry point to process a call to `psa_import_key`, it passes an `attributes` structure such that `psa_get_key_bits(attributes)` is the size passed by the caller of `psa_import_key`. If this size is `0`, the `"import_key"` entry point must set the `bits` input-output parameter to the correct key size. The semantics of `bits` is as follows:
* The core sets `*bits` to `psa_get_key_bits(attributes)` before calling the `"import_key"` entry point.
* If `*bits == 0`, the driver must determine the key size from the data and set `*bits` to this size. If the key size cannot be determined from the data, the driver must return `PSA_ERROR_INVALID_ARGUMENT` (as of version 1.0 of the PSA Cryptography API specification, it is possible to determine the key size for all standard key types).
* If `*bits != 0`, the driver must check the value of `*bits` against the data and return `PSA_ERROR_INVALID_ARGUMENT` if it does not match. If the driver entry point changes `*bits` to a different value but returns `PSA_SUCCESS`, the core will consider the key as invalid and the import will fail.
#### Key validation
Key creation entry points must produce valid key data. Key data is _valid_ if operations involving the key are guaranteed to work functionally and not to cause indirect security loss. Operation functions are supposed to receive valid keys, and should not have to check and report invalid keys. For example:
* If a cryptographic mechanism is defined as having keying material of a certain size, or if the keying material involves integers that have to be in a certain range, key creation must ensure that the keying material has an appropriate size and falls within an appropriate range.
* If a cryptographic operation involves a division by an integer which is provided as part of a key, key creation must ensure that this integer is nonzero.
* If a cryptographic operation involves two keys A and B (or more), then the creation of A must ensure that using it does not risk compromising B. This applies even if A's policy does not explicitly allow a problematic operation, but A is exportable. In particular, public keys that can potentially be used for key agreement are considered invalid and must not be created if they risk compromising the private key.
* On the other hand, it is acceptable for import to accept a key that cannot be verified as valid if using this key would at most compromise the key itself and material that is secured with this key. For example, RSA key import does not need to verify that the primes are actually prime. Key import may accept an insecure key if the consequences of the insecurity are no worse than a leak of the key prior to its import.
With opaque drivers, the key context can only be used by code from the same driver, so key validity is primarily intended to report key creation errors at creation time rather than during an operation. With transparent drivers, the key context can potentially be used by code from a different provider, so key validity is critical for interoperability.
This section describes some minimal validity requirements for standard key types.
* For symmetric key types, check that the key size is suitable for the type.
* For DES (`PSA_KEY_TYPE_DES`), additionally verify the parity bits.
* For RSA (`PSA_KEY_TYPE_RSA_PUBLIC_KEY`, `PSA_KEY_TYPE_RSA_KEY_PAIR`), check the syntax of the key and make sanity checks on its components. TODO: what sanity checks? Value ranges (e.g. p < n), sanity checks such as parity, minimum and maximum size, what else?
* For elliptic curve private keys (`PSA_KEY_TYPE_ECC_KEY_PAIR`), check the size and range. TODO: what else?
* For elliptic curve public keys (`PSA_KEY_TYPE_ECC_PUBLIC_KEY`), check the size and range, and that the point is on the curve. TODO: what else?
### Entropy collection entry point
A driver can declare an entropy source by providing a `"get_entropy"` entry point. This entry point has the following prototype for a driver with the prefix `"acme"`:
```
psa_status_t acme_get_entropy(uint32_t flags,
size_t *estimate_bits,
uint8_t *output,
size_t output_size);
```
The semantics of the parameters is as follows:
* `flags`: a bit-mask of [entropy collection flags](#entropy-collection-flags).
* `estimate_bits`: on success, an estimate of the amount of entropy that is present in the `output` buffer, in bits. This must be at least `1` on success. The value is ignored on failure. Drivers should return a conservative estimate, even in circumstances where the quality of the entropy source is degraded due to environmental conditions (e.g. undervolting, low temperature, etc.).
* `output`: on success, this buffer contains non-deterministic data with an estimated entropy of at least `*estimate_bits` bits. When the entropy is coming from a hardware peripheral, this should preferably be raw or lightly conditioned measurements from a physical process, such that statistical tests run over a sufficiently large amount of output can confirm the entropy estimates. But this specification also permits entropy sources that are fully conditioned, for example when the PSA Cryptography system is running as an application in an operating system and `"get_entropy"` returns data from the random generator in the operating system's kernel.
* `output_size`: the size of the `output` buffer in bytes. This size should be large enough to allow a driver to pass unconditioned data with a low density of entropy; for example a peripheral that returns eight bytes of data with an estimated one bit of entropy cannot provide meaningful output in less than 8 bytes.
Note that there is no output parameter indicating how many bytes the driver wrote to the buffer. Such an output length indication is not necessary because the entropy may be located anywhere in the buffer, so the driver may write less than `output_size` bytes but the core does not need to know this. The output parameter `estimate_bits` contains the amount of entropy, expressed in bits, which may be significantly less than `output_size * 8`.
The entry point may return the following statuses:
* `PSA_SUCCESS`: success. The output buffer contains some entropy.
* `PSA_ERROR_INSUFFICIENT_ENTROPY`: no entropy is available without blocking. This is only permitted if the `PSA_DRIVER_GET_ENTROPY_BLOCK` flag is clear. The core may call `get_entropy` again later, giving time for entropy to be gathered or for adverse environmental conditions to be rectified.
* Other error codes indicate a transient or permanent failure of the entropy source.
Unlike most other entry points, if multiple transparent drivers include a `"get_entropy"` point, the core will call all of them (as well as the entry points from opaque drivers). Fallback is not applicable to `"get_entropy"`.
#### Entropy collection flags
* `PSA_DRIVER_GET_ENTROPY_BLOCK`: If this flag is set, the driver should block until it has at least one bit of entropy. If this flag is clear, the driver should avoid blocking if no entropy is readily available.
* `PSA_DRIVER_GET_ENTROPY_KEEPALIVE`: This flag is intended to help with energy management for entropy-generating peripherals. If this flag is set, the driver should expect another call to `acme_get_entropy` after a short time. If this flag is clear, the core is not expecting to call the `"get_entropy"` entry point again within a short amount of time (but it may do so nonetheless).
#### Entropy collection and blocking
The intent of the `BLOCK` and `KEEPALIVE` [flags](#entropy-collection-flags) is to support drivers for TRNG (True Random Number Generator, i.e. an entropy source peripheral) that have a long ramp-up time, especially on platforms with multiple entropy sources.
Here is a suggested call sequence for entropy collection that leverages these flags:
1. The core makes a first round of calls to `"get_entropy"` on every source with the `BLOCK` flag clear and the `KEEPALIVE` flag set, so that drivers can prepare the TRNG peripheral.
2. The core makes a second round of calls with the `BLOCK` flag set and the `KEEPALIVE` flag clear to gather needed entropy.
3. If the second round does not collect enough entropy, the core makes more similar rounds, until the total amount of collected entropy is sufficient.
### Miscellaneous driver entry points
#### Driver initialization
A driver may declare an `"init"` entry point in a capability with no algorithm, key type or key size. If so, the core calls this entry point once during the initialization of the PSA Cryptography subsystem. If the init entry point of any driver fails, the initialization of the PSA Cryptography subsystem fails.
When multiple drivers have an init entry point, the order in which they are called is unspecified. It is also unspecified whether other drivers' `"init"` entry points are called if one or more init entry point fails.
On platforms where the PSA Cryptography implementation is a subsystem of a single application, the initialization of the PSA Cryptography subsystem takes place during the call to `psa_crypto_init()`. On platforms where the PSA Cryptography implementation is separate from the application or applications, the initialization of the PSA Cryptography subsystem takes place before or during the first time an application calls `psa_crypto_init()`.
The init entry point does not take any parameter.
### Combining multiple drivers
To declare a cryptoprocessor can handle both cleartext and wrapped keys, you need to provide two driver descriptions, one for a transparent driver and one for an opaque driver. You can use the mapping in capabilities' `"names"` property to arrange for multiple driver entry points to map to the same C function.
## Transparent drivers
### Key format for transparent drivers
The format of a key for transparent drivers is the same as in applications. Refer to the documentation of [`psa_export_key()`](https://armmbed.github.io/mbed-crypto/html/api/keys/management.html#c.psa_export_key) and [`psa_export_public_key()`](https://armmbed.github.io/mbed-crypto/html/api/keys/management.html#c.psa_export_public_key) in the PSA Cryptography API specification. For custom key types defined by an implementation, refer to the documentation of that implementation.
### Key management with transparent drivers
Transparent drivers may provide the following key management entry points:
* [`"import_key"`](#key-import-with-transparent-drivers): called by `psa_import_key()`, only when importing a key pair or a public key (key such that `PSA_KEY_TYPE_IS_ASYMMETRIC` is true).
* `"generate_key"`: called by `psa_generate_key()`, only when generating a key pair (key such that `PSA_KEY_TYPE_IS_KEY_PAIR` is true).
* `"key_derivation_output_key"`: called by `psa_key_derivation_output_key()`, only when deriving a key pair (key such that `PSA_KEY_TYPE_IS_KEY_PAIR` is true).
* `"export_public_key"`: called by the core to obtain the public key of a key pair. The core may call this function at any time to obtain the public key, which can be for `psa_export_public_key()` but also at other times, including during a cryptographic operation that requires the public key such as a call to `psa_verify_message()` on a key pair object.
Transparent drivers are not involved when exporting, copying or destroying keys, or when importing, generating or deriving symmetric keys.
#### Key import with transparent drivers
As discussed in [the general section about key management entry points](#driver-entry-points-for-key-management), the key import entry points has the following prototype for a driver with the prefix `"acme"`:
```
psa_status_t acme_import_key(const psa_key_attributes_t *attributes,
const uint8_t *data,
size_t data_length,
uint8_t *key_buffer,
size_t key_buffer_size,
size_t *key_buffer_length,
size_t *bits);
```
This entry point has several roles:
1. Parse the key data in the input buffer `data`. The driver must support the export format for the key types that the entry point is declared for. It may support additional formats as specified in the description of [`psa_import_key()`](https://armmbed.github.io/mbed-crypto/html/api/keys/management.html#c.psa_export_key) in the PSA Cryptography API specification.
2. Validate the key data. The necessary validation is described in the section [“Key validation with transparent drivers”](#key-validation-with-transparent-drivers) above.
3. [Determine the key size](#key-size-determination-on-import) and output it through `*bits`.
4. Copy the validated key data from `data` to `key_buffer`. The output must be in the canonical format documented for [`psa_export_key()`](https://armmbed.github.io/mbed-crypto/html/api/keys/management.html#c.psa_export_key) or [`psa_export_public_key()`](https://armmbed.github.io/mbed-crypto/html/api/keys/management.html#c.psa_export_public_key), so if the input is not in this format, the entry point must convert it.
### Random generation entry points
A transparent driver may provide an operation family that can be used as a cryptographic random number generator. The random generation mechanism must obey the following requirements:
* The random output must be of cryptographic quality, with a uniform distribution. Therefore, if the random generator includes an entropy source, this entropy source must be fed through a CSPRNG (cryptographically secure pseudo-random number generator).
* Random generation is expected to be fast. (If a device can provide entropy but is slow at generating random data, declare it as an [entropy driver](#entropy-collection-entry-point) instead.)
* The random generator should be able to incorporate entropy provided by an outside source. If it isn't, the random generator can only be used if it's the only entropy source on the platform. (A random generator peripheral can be declared as an [entropy source](#entropy-collection-entry-point) instead of a random generator; this way the core will combine it with other entropy sources.)
* The random generator may either be deterministic (in the sense that it always returns the same data when given the same entropy inputs) or non-deterministic (including its own entropy source). In other words, this interface is suitable both for PRNG (pseudo-random number generator, also known as DRBG (deterministic random bit generator)) and for NRBG (non-deterministic random bit generator).
If no driver implements the random generation entry point family, the core provides an unspecified random generation mechanism.
This operation family requires the following type, entry points and parameters (TODO: where exactly are the parameters in the JSON structure?):
* Type `"random_context_t"`: the type of a random generation context.
* `"init_random"` (entry point, optional): if this function is present, [the core calls it once](#random-generator-initialization) after allocating a `"random_context_t"` object.
* `"add_entropy"` (entry point, optional): the core calls this function to [inject entropy](#entropy-injection). This entry point is optional if the driver is for a peripheral that includes an entropy source of its own, however [random generator drivers without entropy injection](#random-generator-drivers-without-entropy-injection) have limited portability since they can only be used on platforms with no other entropy source. This entry point is mandatory if `"initial_entropy_size"` is nonzero.
* `"get_random"` (entry point, mandatory): the core calls this function whenever it needs to [obtain random data](#the-get_random-entry-point).
* `"initial_entropy_size"` (integer, mandatory): the minimum number of bytes of entropy that the core must supply before the driver can output random data. This can be `0` if the driver is for a peripheral that includes an entropy source of its own.
* `"reseed_entropy_size"` (integer, optional): the minimum number of bytes of entropy that the core should supply via [`"add_entropy"`](#entropy-injection) when the driver runs out of entropy. This value is also a hint for the size to supply if the core makes additional calls to `"add_entropy"`, for example to enforce prediction resistance. If omitted, the core should pass an amount of entropy corresponding to the expected security strength of the device (for example, pass 32 bytes of entropy when reseeding to achieve a security strength of 256 bits). If specified, the core should pass the larger of `"reseed_entropy_size"` and the amount corresponding to the security strength.
Random generation is not parametrized by an algorithm. The choice of algorithm is up to the driver.
#### Random generator initialization
The `"init_random"` entry point has the following prototype for a driver with the prefix `"acme"`:
```
psa_status_t acme_init_random(acme_random_context_t *context);
```
The core calls this entry point once after allocating a random generation context. Initially, the context object is all-bits-zero.
If a driver does not have an `"init_random"` entry point, the context object passed to the first call to `"add_entropy"` or `"get_random"` will be all-bits-zero.
#### Entropy injection
The `"add_entropy"` entry point has the following prototype for a driver with the prefix `"acme"`:
```
psa_status_t acme_add_entropy(acme_random_context_t *context,
const uint8_t *entropy,
size_t entropy_size);
```
The semantics of the parameters is as follows:
* `context`: a random generation context. On the first call to `"add_entropy"`, this object has been initialized by a call to the driver's `"init_random"` entry point if one is present, and to all-bits-zero otherwise.
* `entropy`: a buffer containing full-entropy data to seed the random generator. “Full-entropy” means that the data is uniformly distributed and independent of any other observable quantity.
* `entropy_size`: the size of the `entropy` buffer in bytes. It is guaranteed to be at least `1`, but it may be smaller than the amount of entropy that the driver needs to deliver random data, in which case the core will call the `"add_entropy"` entry point again to supply more entropy.
The core calls this function to supply entropy to the driver. The driver must mix this entropy into its internal state. The driver must mix the whole supplied entropy, even if there is more than what the driver requires, to ensure that all entropy sources are mixed into the random generator state. The driver may mix additional entropy of its own.
The core may call this function at any time. For example, to enforce prediction resistance, the core can call `"add_entropy"` immediately after each call to `"get_random"`. The core must call this function in two circumstances:
* Before the first call to the `"get_random"` entry point, to supply `"initial_entropy_size"` bytes of entropy.
* After a call to the `"get_random"` entry point returns less than the required amount of random data, to supply at least `"reseed_entropy_size"` bytes of entropy.
When the driver requires entropy, the core can supply it with one or more successive calls to the `"add_entropy"` entry point. If the required entropy size is zero, the core does not need to call `"add_entropy"`.
#### Combining entropy sources with a random generation driver
This section provides guidance on combining one or more [entropy sources](#entropy-collection-entry-point) (each having a `"get_entropy"` entry point) with a random generation driver (with an `"add_entropy"` entry point).
Note that `"get_entropy"` returns data with an estimated amount of entropy that is in general less than the buffer size. The core must apply a mixing algorithm to the output of `"get_entropy"` to obtain full-entropy data.
For example, the core may use a simple mixing scheme based on a pseudorandom function family $(F_k)$ with an $E$-bit output where $E = 8 \cdot \mathtt{entropy_size}$ and $\mathtt{entropy_size}$ is the desired amount of entropy in bytes (typically the random driver's `"initial_entropy_size"` property for the initial seeding and the `"reseed_entropy_size"` property for subsequent reseeding). The core calls the `"get_entropy"` points of the available entropy drivers, outputting a string $s_i$ and an entropy estimate $e_i$ on the $i$th call. It does so until the total entropy estimate $e_1 + e_2 + \ldots + e_n$ is at least $E$. The core then calculates $F_k(0)$ where $k = s_1 || s_2 || \ldots || s_n$. This value is a string of $\mathtt{entropy_size}$, and since $(F_k)$ is a pseudorandom function family, $F_k(0)$ is uniformly distributed over strings of $\mathtt{entropy_size}$ bytes. Therefore $F_k(0)$ is a suitable value to pass to `"add_entropy"`.
Note that the mechanism above is only given as an example. Implementations may choose a different mechanism, for example involving multiple pools or intermediate compression functions.
#### Random generator drivers without entropy injection
Random generator drivers should have the capability to inject additional entropy through the `"add_entropy"` entry point. This ensures that the random generator depends on all the entropy sources that are available on the platform. A driver where a call to `"add_entropy"` does not affect the state of the random generator is not compliant with this specification.
However, a driver may omit the `"add_entropy"` entry point. This limits the driver's portability: implementations of the PSA Cryptography specification may reject drivers without an `"add_entropy"` entry point, or only accept such drivers in certain configurations. In particular, the `"add_entropy"` entry point is required if:
* the integration of PSA Cryptography includes an entropy source that is outside the driver; or
* the core saves random data in persistent storage to be preserved across platform resets.
#### The `"get_random"` entry point
The `"get_random"` entry point has the following prototype for a driver with the prefix `"acme"`:
```
psa_status_t acme_get_random(acme_random_context_t *context,
uint8_t *output,
size_t output_size,
size_t *output_length);
```
The semantics of the parameters is as follows:
* `context`: a random generation context. If the driver's `"initial_entropy_size"` property is nonzero, the core must have called `"add_entropy"` at least once with a total of at least `"initial_entropy_size"` bytes of entropy before it calls `"get_random"`. Alternatively, if the driver's `"initial_entropy_size"` property is zero and the core did not call `"add_entropy"`, or if the driver has no `"add_entropy"` entry point, the core must have called `"init_random"` if present, and otherwise the context is all-bits zero.
* `output`: on success (including partial success), the first `*output_length` bytes of this buffer contain cryptographic-quality random data. The output is not used on error.
* `output_size`: the size of the `output` buffer in bytes.
* `*output_length`: on success (including partial success), the number of bytes of random data that the driver has written to the `output` buffer. This is preferably `output_size`, but the driver is allowed to return less data if it runs out of entropy as described below. The core sets this value to 0 on entry. The value is not used on error.
The driver may return the following status codes:
* `PSA_SUCCESS`: the `output` buffer contains `*output_length` bytes of cryptographic-quality random data. Note that this may be less than `output_size`; in this case the core should call the driver's `"add_entropy"` method to supply at least `"reseed_entropy_size"` bytes of entropy before calling `"get_random"` again.
* `PSA_ERROR_INSUFFICIENT_ENTROPY`: the core must supply additional entropy by calling the `"add_entropy"` entry point with at least `"reseed_entropy_size"` bytes.
* `PSA_ERROR_NOT_SUPPORTED`: the random generator is not available. This is only permitted if the driver specification for random generation has the [fallback property](#fallback) enabled.
* Other error codes such as `PSA_ERROR_COMMUNICATION_FAILURE` or `PSA_ERROR_HARDWARE_FAILURE` indicate a transient or permanent error.
### Fallback
Sometimes cryptographic accelerators only support certain cryptographic mechanisms partially. The capability description language allows specifying some restrictions, including restrictions on key sizes, but it cannot cover all the possibilities that may arise in practice. Furthermore, it may be desirable to deploy the same binary image on different devices, only some of which have a cryptographic accelerators.
For these purposes, a transparent driver can declare that it only supports a [capability](#driver-description-capability) partially, by setting the capability's `"fallback"` property to true.
If a transparent driver entry point is part of a capability which has a true `"fallback"` property and returns `PSA_ERROR_NOT_SUPPORTED`, the core will call the next transparent driver that supports the mechanism, if there is one. The core considers drivers in the order given by the [driver description list](#driver-description-list).
If all the available drivers have fallback enabled and return `PSA_ERROR_NOT_SUPPORTED`, the core will perform the operation using built-in code.
As soon as a driver returns any value other than `PSA_ERROR_NOT_SUPPORTED` (`PSA_SUCCESS` or a different error code), this value is returned to the application, without attempting to call any other driver or built-in code.
If a transparent driver entry point is part of a capability where the `"fallback"` property is false or omitted, the core should not include any other code for this capability, whether built in or in another transparent driver.
## Opaque drivers
Opaque drivers allow a PSA Cryptography implementation to delegate cryptographic operations to a separate environment that might not allow exporting key material in cleartext. The opaque driver interface is designed so that the core never inspects the representation of a key. The opaque driver interface is designed to support two subtypes of cryptoprocessors:
* Some cryptoprocessors do not have persistent storage for individual keys. The representation of a key is the key material wrapped with a master key which is located in the cryptoprocessor and never exported from it. The core stores this wrapped key material on behalf of the cryptoprocessor.
* Some cryptoprocessors have persistent storage for individual keys. The representation of a key is an identifier such as label or slot number. The core stores this identifier.
### Key format for opaque drivers
The format of a key for opaque drivers is an opaque blob. The content of this blob is fully up to the driver. The core merely stores this blob.
Note that since the core stores the key context blob as it is in memory, it must only contain data that is meaningful after a reboot. In particular, it must not contain any pointers or transient handles.
The `"key_context"` property in the [driver description](#driver-description-top-level-element) specifies how to calculate the size of the key context as a function of the key type and size. This is an object with the following properties:
* `"base_size"` (integer or string, optional): this many bytes are included in every key context. If omitted, this value defaults to 0.
* `"key_pair_size"` (integer or string, optional): this many bytes are included in every key context for a key pair. If omitted, this value defaults to 0.
* `"public_key_size"` (integer or string, optional): this many bytes are included in every key context for a public key. If omitted, this value defaults to 0.
* `"symmetric_factor"` (integer or string, optional): every key context for a symmetric key includes this many times the key size. If omitted, this value defaults to 0.
* `"store_public_key"` (boolean, optional): If specified and true, for a key pair, the key context includes space for the public key. If omitted or false, no additional space is added for the public key.
* `"size_function"` (string, optional): the name of a function that returns the number of bytes that the driver needs in a key context for a key. This may be a pointer to function. This must be a C identifier; more complex expressions are not permitted. If the core uses this function, it supersedes all the other properties except for `"builtin_key_size"` (where applicable, if present).
* `"builtin_key_size"` (integer or string, optional): If specified, this overrides all other methods (including the `"size_function"` entry point) to determine the size of the key context for [built-in keys](#built-in-keys). This allows drivers to efficiently represent application keys as wrapped key material, but built-in keys by an internal identifier that takes up less space.
The integer properties must be C language constants. A typical value for `"base_size"` is `sizeof(acme_key_context_t)` where `acme_key_context_t` is a type defined in a driver header file.
#### Size of a dynamically allocated key context
If the core supports dynamic allocation for the key context and chooses to use it, and the driver specification includes the `"size_function"` property, the size of the key context is at least
```
size_function(key_type, key_bits)
```
where `size_function` is the function named in the `"size_function"` property, `key_type` is the key type and `key_bits` is the key size in bits. The prototype of the size function is
```
size_t size_function(psa_key_type_t key_type, size_t key_bits);
```
#### Size of a statically allocated key context
If the core does not support dynamic allocation for the key context or chooses not to use it, or if the driver specification does not include the `"size_function"` property, the size of the key context for a key of type `key_type` and of size `key_bits` bits is:
* For a key pair (`PSA_KEY_TYPE_IS_KEY_PAIR(key_type)` is true):
```
base_size + key_pair_size + public_key_overhead
```
where `public_key_overhead = PSA_EXPORT_PUBLIC_KEY_MAX_SIZE(key_type, key_bits)` if the `"store_public_key"` property is true and `public_key_overhead = 0` otherwise.
* For a public key (`PSA_KEY_TYPE_IS_PUBLIC_KEY(key_type)` is true):
```
base_size + public_key_size
```
* For a symmetric key (not a key pair or public key):
```
base_size + symmetric_factor * key_bytes
```
where `key_bytes = ((key_bits + 7) / 8)` is the key size in bytes.
#### Key context size for a secure element with storage
If the key is stored in the secure element and the driver only needs to store a label for the key, use `"base_size"` as the size of the label plus any other metadata that the driver needs to store, and omit the other properties.
If the key is stored in the secure element, but the secure element does not store the public part of a key pair and cannot recompute it on demand, additionally use the `"store_public_key"` property with the value `true`. Note that this only influences the size of the key context: the driver code must copy the public key to the key context and retrieve it on demand in its `export_public_key` entry point.
#### Key context size for a secure element without storage
If the key is stored in wrapped form outside the secure element, and the wrapped form of the key plus any metadata has up to *N* bytes of overhead, use *N* as the value of the `"base_size"` property and set the `"symmetric_factor"` property to 1. Set the `"key_pair_size"` and `"public_key_size"` properties appropriately for the largest supported key pair and the largest supported public key respectively.
### Key management with opaque drivers
Opaque drivers may provide the following key management entry points:
* `"export_key"`: called by `psa_export_key()`, or by `psa_copy_key()` when copying a key from or to a different [location](#lifetimes-and-locations).
* `"export_public_key"`: called by the core to obtain the public key of a key pair. The core may call this entry point at any time to obtain the public key, which can be for `psa_export_public_key()` but also at other times, including during a cryptographic operation that requires the public key such as a call to `psa_verify_message()` on a key pair object.
* `"import_key"`: called by `psa_import_key()`, or by `psa_copy_key()` when copying a key from another location.
* `"generate_key"`: called by `psa_generate_key()`.
* `"key_derivation_output_key"`: called by `psa_key_derivation_output_key()`.
* `"copy_key"`: called by `psa_copy_key()` when copying a key within the same [location](#lifetimes-and-locations).
* `"get_builtin_key"`: called by functions that access a key to retrieve information about a [built-in key](#built-in-keys).
In addition, secure elements that store the key material internally must provide the following two entry points:
* `"allocate_key"`: called by `psa_import_key()`, `psa_generate_key()`, `psa_key_derivation_output_key()` or `psa_copy_key()` before creating a key in the location of this driver.
* `"destroy_key"`: called by `psa_destroy_key()`.
#### Key creation in a secure element without storage
This section describes the key creation process for secure elements that do not store the key material. The driver must obtain a wrapped form of the key material which the core will store. A driver for such a secure element has no `"allocate_key"` or `"destroy_key"` entry point.
When creating a key with an opaque driver which does not have an `"allocate_key"` or `"destroy_key"` entry point:
1. The core allocates memory for the key context.
2. The core calls the driver's import, generate, derive or copy entry point.
3. The core saves the resulting wrapped key material and any other data that the key context may contain.
To destroy a key, the core simply destroys the wrapped key material, without invoking driver code.
#### Key management in a secure element with storage
This section describes the key creation and key destruction processes for secure elements that have persistent storage for the key material. A driver for such a secure element has two mandatory entry points:
* `"allocate_key"`: this function obtains an internal identifier for the key. This may be, for example, a unique label or a slot number.
* `"destroy_key"`: this function invalidates the internal identifier and destroys the associated key material.
These functions have the following prototypes for a driver with the prefix `"acme"`:
```
psa_status_t acme_allocate_key(const psa_key_attributes_t *attributes,
uint8_t *key_buffer,
size_t key_buffer_size);
psa_status_t acme_destroy_key(const psa_key_attributes_t *attributes,
const uint8_t *key_buffer,
size_t key_buffer_size);
```
When creating a persistent key with an opaque driver which has an `"allocate_key"` entry point:
1. The core calls the driver's `"allocate_key"` entry point. This function typically allocates an internal identifier for the key without modifying the state of the secure element and stores the identifier in the key context. This function should not modify the state of the secure element. It may modify the copy of the persistent state of the driver in memory.
1. The core saves the key context to persistent storage.
1. The core calls the driver's key creation entry point.
1. The core saves the updated key context to persistent storage.
If a failure occurs after the `"allocate_key"` step but before the call to the second driver entry point, the core will do one of the following:
* Fail the creation of the key without indicating this to the driver. This can happen, in particular, if the device loses power immediately after the key allocation entry point returns.
* Call the driver's `"destroy_key"` entry point.
To destroy a key, the core calls the driver's `"destroy_key"` entry point.
Note that the key allocation and destruction entry points must not rely solely on the key identifier in the key attributes to identify a key. Some implementations of the PSA Cryptography API store keys on behalf of multiple clients, and different clients may use the same key identifier to designate different keys. The manner in which the core distinguishes keys that have the same identifier but are part of the key namespace for different clients is implementation-dependent and is not accessible to drivers. Some typical strategies to allocate an internal key identifier are:
* Maintain a set of free slot numbers which is stored either in the secure element or in the driver's persistent storage. To allocate a key slot, find a free slot number, mark it as occupied and store the number in the key context. When the key is destroyed, mark the slot number as free.
* Maintain a monotonic counter with a practically unbounded range in the secure element or in the driver's persistent storage. To allocate a key slot, increment the counter and store the current value in the key context. Destroying a key does not change the counter.
TODO: explain constraints on how the driver updates its persistent state for resilience
TODO: some of the above doesn't apply to volatile keys
#### Key creation entry points in opaque drivers
The key creation entry points have the following prototypes for a driver with the prefix `"acme"`:
```
psa_status_t acme_import_key(const psa_key_attributes_t *attributes,
const uint8_t *data,
size_t data_length,
uint8_t *key_buffer,
size_t key_buffer_size,
size_t *key_buffer_length,
size_t *bits);
psa_status_t acme_generate_key(const psa_key_attributes_t *attributes,
uint8_t *key_buffer,
size_t key_buffer_size,
size_t *key_buffer_length);
```
If the driver has an [`"allocate_key"` entry point](#key-management-in-a-secure-element-with-storage), the core calls the `"allocate_key"` entry point with the same attributes on the same key buffer before calling the key creation entry point.
TODO: derivation, copy
#### Key export entry points in opaque drivers
The key export entry points have the following prototypes for a driver with the prefix `"acme"`:
```
psa_status_t acme_export_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);
psa_status_t acme_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);
```
The core will only call `acme_export_public_key` on a private key. Drivers implementers may choose to store the public key in the key context buffer or to recalculate it on demand. If the key context includes the public key, it needs to have an adequate size; see [“Key format for opaque drivers”](#key-format-for-opaque-drivers).
The core guarantees that the size of the output buffer (`data_size`) is sufficient to export any key with the given attributes. The driver must set `*data_length` to the exact size of the exported key.
### Opaque driver persistent state
The core maintains persistent state on behalf of an opaque driver. This persistent state consists of a single byte array whose size is given by the `"persistent_state_size"` property in the [driver description](#driver-description-top-level-element).
The core loads the persistent state in memory before it calls the driver's [init entry point](#driver-initialization). It is adjusted to match the size declared by the driver, in case a driver upgrade changes the size:
* The first time the driver is loaded on a system, the persistent state is all-bits-zero.
* If the stored persistent state is smaller than the declared size, the core pads the persistent state with all-bits-zero at the end.
* If the stored persistent state is larger than the declared size, the core truncates the persistent state to the declared size.
The core provides the following callback functions, which an opaque driver may call while it is processing a call from the driver:
```
psa_status_t psa_crypto_driver_get_persistent_state(uint_8_t **persistent_state_ptr);
psa_status_t psa_crypto_driver_commit_persistent_state(size_t from, size_t length);
```
`psa_crypto_driver_get_persistent_state` sets `*persistent_state_ptr` to a pointer to the first byte of the persistent state. This pointer remains valid during a call to a driver entry point. Once the entry point returns, the pointer is no longer valid. The core guarantees that calls to `psa_crypto_driver_get_persistent_state` within the same entry point return the same address for the persistent state, but this address may change between calls to an entry point.
`psa_crypto_driver_commit_persistent_state` updates the persistent state in persistent storage. Only the portion at byte offsets `from` inclusive to `from + length` exclusive is guaranteed to be updated; it is unspecified whether changes made to other parts of the state are taken into account. The driver must call this function after updating the persistent state in memory and before returning from the entry point, otherwise it is unspecified whether the persistent state is updated.
The core will not update the persistent state in storage while an entry point is running except when the entry point calls `psa_crypto_driver_commit_persistent_state`. It may update the persistent state in storage after an entry point returns.
In a multithreaded environment, the driver may only call these two functions from the thread that is executing the entry point.
#### Built-in keys
Opaque drivers may declare built-in keys. Built-in keys can be accessed, but not created, through the PSA Cryptography API.
A built-in key is identified by its location and its **slot number**. Drivers that support built-in keys must provide a `"get_builtin_key"` entry point to retrieve the key data and metadata. The core calls this entry point when it needs to access the key, typically because the application requested an operation on the key. The core may keep information about the key in cache, and successive calls to access the same slot number should return the same data. This entry point has the following prototype:
```
psa_status_t acme_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);
```
If this function returns `PSA_SUCCESS` or `PSA_ERROR_BUFFER_TOO_SMALL`, it must fill `attributes` with the attributes of the key (except for the key identifier). On success, this function must also fill `key_buffer` with the key context.
On entry, `psa_get_key_lifetime(attributes)` is the location at which the driver was declared and a persistence level with which the platform is attempting to register the key. The driver entry point may choose to change the lifetime (`psa_set_key_lifetime(attributes, lifetime)`) of the reported key attributes to one with the same location but a different persistence level, in case the driver has more specific knowledge about the actual persistence level of the key which is being retrieved. For example, if a driver knows it cannot delete a key, it may override the persistence level in the lifetime to `PSA_KEY_PERSISTENCE_READ_ONLY`. The standard attributes other than the key identifier and lifetime have the value conveyed by `PSA_KEY_ATTRIBUTES_INIT`.
The output parameter `key_buffer` points to a writable buffer of `key_buffer_size` bytes. If the driver has a [`"builtin_key_size"` property](#key-format-for-opaque-drivers) property, `key_buffer_size` has this value, otherwise `key_buffer_size` has the value determined from the key type and size.
Typically, for a built-in key, the key context is a reference to key material that is kept inside the secure element, similar to the format returned by [`"allocate_key"`](#key-management-in-a-secure-element-with-storage). A driver may have built-in keys even if it doesn't have an `"allocate_key"` entry point.
This entry point may return the following status values:
* `PSA_SUCCESS`: the requested key exists, and the output parameters `attributes` and `key_buffer` contain the key metadata and key context respectively, and `*key_buffer_length` contains the length of the data written to `key_buffer`.
* `PSA_ERROR_BUFFER_TOO_SMALL`: `key_buffer_size` is insufficient. In this case, the driver must pass the key's attributes in `*attributes`. In particular, `get_builtin_key(slot_number, &attributes, NULL, 0)` is a way for the core to obtain the key's attributes.
* `PSA_ERROR_DOES_NOT_EXIST`: the requested key does not exist.
* Other error codes such as `PSA_ERROR_COMMUNICATION_FAILURE` or `PSA_ERROR_HARDWARE_FAILURE` indicate a transient or permanent error.
The core will pass authorized requests to destroy a built-in key to the [`"destroy_key"`](#key-management-in-a-secure-element-with-storage) entry point if there is one. If built-in keys must not be destroyed, it is up to the driver to reject such requests.
## How to use drivers from an application
### Using transparent drivers
Transparent drivers linked into the library are automatically used for the mechanisms that they implement.
### Using opaque drivers
Each opaque driver is assigned a [location](#lifetimes-and-locations). The driver is invoked for all actions that use a key in that location. A key's location is indicated by its lifetime. The application chooses the key's lifetime when it creates the key.
For example, the following snippet creates an AES-GCM key which is only accessible inside the secure element designated by the location `PSA_KEY_LOCATION_acme`.
```
psa_key_attributes_t attributes = PSA_KEY_ATTRIBUTES_INIT;
psa_set_key_lifetime(&attributes, PSA_KEY_LIFETIME_FROM_PERSISTENCE_AND_LOCATION(
PSA_KEY_PERSISTENCE_DEFAULT, PSA_KEY_LOCATION_acme));
psa_set_key_identifier(&attributes, 42);
psa_set_key_type(&attributes, PSA_KEY_TYPE_AES);
psa_set_key_size(&attributes, 128);
psa_set_key_algorithm(&attributes, PSA_ALG_GCM);
psa_set_key_usage_flags(&attributes, PSA_KEY_USAGE_ENCRYPT | PSA_KEY_USAGE_DECRYPT);
psa_key_id_t key;
psa_generate_key(&attributes, &key);
```
## Using opaque drivers from an application
### Lifetimes and locations
The PSA Cryptography API, version 1.0.0, defines [lifetimes](https://armmbed.github.io/mbed-crypto/html/api/keys/attributes.html?highlight=psa_key_lifetime_t#c.psa_key_lifetime_t) as an attribute of a key that indicates where the key is stored and which application and system actions will create and destroy it. The lifetime is expressed as a 32-bit value (`typedef uint32_t psa_key_lifetime_t`). An upcoming version of the PSA Cryptography API defines more structure for lifetime values to separate these two aspects of the lifetime:
* Bits 0–7 are a _persistence level_. This value indicates what device management actions can cause it to be destroyed. In particular, it indicates whether the key is volatile or persistent.
* Bits 8–31 are a _location indicator_. This value indicates where the key material is stored and where operations on the key are performed. Location values can be stored in a variable of type `psa_key_location_t`.
An opaque driver is attached to a specific location. Keys in the default location (`PSA_KEY_LOCATION_LOCAL_STORAGE = 0`) are transparent: the core has direct access to the key material. For keys in a location that is managed by an opaque driver, only the secure element has access to the key material and can perform operations on the key, while the core only manipulates a wrapped form of the key or an identifier of the key.
### Creating a key in a secure element
The core defines a compile-time constant for each opaque driver indicating its location called `PSA_KEY_LOCATION_`*prefix* where *prefix* is the value of the `"prefix"` property in the driver description. For convenience, Mbed TLS also declares a compile-time constant for the corresponding lifetime with the default persistence called `PSA_KEY_LIFETIME_`*prefix*. Therefore, to declare an opaque key in the location with the prefix `foo` with the default persistence, call `psa_set_key_lifetime` during the key creation as follows:
```
psa_set_key_lifetime(&attributes, PSA_KEY_LIFETIME_foo);
```
To declare a volatile key:
```
psa_set_key_lifetime(&attributes, PSA_KEY_LIFETIME_FROM_PERSISTENCE_AND_LOCATION(
PSA_KEY_LOCATION_foo,
PSA_KEY_PERSISTENCE_VOLATILE));
```
Generally speaking, to declare a key with a specified persistence:
```
psa_set_key_lifetime(&attributes, PSA_KEY_LIFETIME_FROM_PERSISTENCE_AND_LOCATION(
PSA_KEY_LOCATION_foo,
persistence));
```
## Open questions
### Value representation
#### Integers
It would be better if there was a uniform requirement on integer values. Do they have to be JSON integers? C preprocessor integers (which could be e.g. a macro defined in some header file)? C compile-time constants (allowing `sizeof`)?
This choice is partly driven by the use of the values, so they might not be uniform. Note that if the value can be zero and it's plausible that the core would want to statically allocate an array of the given size, the core needs to know whether the value is 0 so that it could use code like
```
#if ACME_FOO_SIZE != 0
uint8_t foo[ACME_FOO_SIZE];
#endif
```
### Driver declarations
#### Declaring driver entry points
The core may want to provide declarations for the driver entry points so that it can compile code using them. At the time of writing this paragraph, the driver headers must define types but there is no obligation for them to declare functions. The core knows what the function names and argument types are, so it can generate prototypes.
It should be ok for driver functions to be function-like macros or function pointers.
#### Driver location values
How does a driver author decide which location values to use? It should be possible to combine drivers from different sources. Use the same vendor assignment as for PSA services?
Can the driver assembly process generate distinct location values as needed? This can be convenient, but it's also risky: if you upgrade a device, you need the location values to be the same between builds.
The current plan is for Arm to maintain a registry of vendors and assign a location namespace to each vendor. Parts of the namespace would be reserved for implementations and integrators.
#### Multiple transparent drivers
When multiple transparent drivers implement the same mechanism, which one is called? The first one? The last one? Unspecified? Or is this an error (excluding capabilities with fallback enabled)?
The current choice is that the first one is used, which allows having a preference order on drivers, but may mask integration errors.
### Driver function interfaces
#### Driver function parameter conventions
Should 0-size buffers be guaranteed to have a non-null pointers?
Should drivers really have to cope with overlap?
Should the core guarantee that the output buffer size has the size indicated by the applicable buffer size macro (which may be an overestimation)?
### Partial computations in drivers
#### Substitution points
Earlier drafts of the driver interface had a concept of _substitution points_: places in the calculation where a driver may be called. Some hardware doesn't do the whole calculation, but only the “main” part. This goes both for transparent and opaque drivers. Some common examples:
* A processor that performs the RSA exponentiation, but not the padding. The driver should be able to leverage the padding code in the core.
* A processor that performs a block cipher operation only for a single block, or only in ECB mode, or only in CTR mode. The core would perform the block mode (CBC, CTR, CCM, ...).
This concept, or some other way to reuse portable code such as specifying inner functions like `psa_rsa_pad` in the core, should be added to the specification.
### Key management
#### Mixing drivers in key derivation
How does `psa_key_derivation_output_key` work when the extraction part and the expansion part use different drivers?
#### Public key calculation
ECC key pairs are represented as the private key value only. The public key needs to be calculated from that. Both transparent drivers and opaque drivers provide a function to calculate the public key (`"export_public_key"`).
The specification doesn't mention when the public key might be calculated. The core may calculate it on creation, on demand, or anything in between. Opaque drivers have a choice of storing the public key in the key context or calculating it on demand and can convey whether the core should store the public key with the `"store_public_key"` property. Is this good enough or should the specification include non-functional requirements?
#### Symmetric key validation with transparent drivers
Should the entry point be called for symmetric keys as well?
#### Support for custom import formats
[“Driver entry points for key management”](#driver-entry-points-for-key-management) states that the input to `"import_key"` can be an implementation-defined format. Is this a good idea? It reduces driver portability, since a core that accepts a custom format would not work with a driver that doesn't accept this format. On the other hand, if a driver accepts a custom format, the core should let it through because the driver presumably handles it more efficiently (in terms of speed and code size) than the core could.
Allowing custom formats also causes a problem with import: the core can't know the size of the key representation until it knows the bit-size of the key, but determining the bit-size of the key is part of the job of the `"import_key"` entry point. For standard key types, this could plausibly be an issue for RSA private keys, where an implementation might accept a custom format that omits the CRT parameters (or that omits *d*).
### Opaque drivers
#### Opaque driver persistent state
The driver is allowed to update the state at any time. Is this ok?
An example use case for updating the persistent state at arbitrary times is to renew a key that is used to encrypt communications between the application processor and the secure element.
`psa_crypto_driver_get_persistent_state` does not identify the calling driver, so the driver needs to remember which driver it's calling. This may require a thread-local variable in a multithreaded core. Is this ok?
### Randomness
#### Input to `"add_entropy"`
Should the input to the [`"add_entropy"` entry point](#entropy-injection) be a full-entropy buffer (with data from all entropy sources already mixed), raw entropy direct from the entropy sources, or give the core a choice?
* Raw data: drivers must implement entropy mixing. `"add_entropy"` needs an extra parameter to indicate the amount of entropy in the data. The core must not do any conditioning.
* Choice: drivers must implement entropy mixing. `"add_entropy"` needs an extra parameter to indicate the amount of entropy in the data. The core may do conditioning if it wants, but doesn't have to.
* Full entropy: drivers don't need to do entropy mixing.
#### Flags for `"get_entropy"`
Are the [entropy collection flags](#entropy-collection-flags) well-chosen?
#### Random generator instantiations
May the core instantiate a random generation context more than once? In other words, can there be multiple objects of type `acme_random_context_t`?
Functionally, one RNG is as good as any. If the core wants some parts of the system to use a deterministic generator for reproducibility, it can't use this interface anyway, since the RNG is not necessarily deterministic. However, for performance on multiprocessor systems, a multithreaded core could prefer to use one RNG instance per thread.
<!--
Local Variables:
time-stamp-line-limit: 40
time-stamp-start: "Time-stamp: *\""
time-stamp-end: "\""
time-stamp-format: "%04Y/%02m/%02d %02H:%02M:%02S %Z"
time-stamp-time-zone: "GMT"
End:
-->
|
0 | repos/gpt4all.zig/src/zig-libcurl/zig-mbedtls/mbedtls/docs | repos/gpt4all.zig/src/zig-libcurl/zig-mbedtls/mbedtls/docs/proposed/psa-driver-developer-guide.md | PSA Cryptoprocessor driver developer's guide
============================================
**This is a specification of work in progress. The implementation is not yet merged into Mbed TLS.**
This document describes how to write drivers of cryptoprocessors such as accelerators and secure elements for the PSA cryptography subsystem of Mbed TLS.
This document focuses on behavior that is specific to Mbed TLS. For a reference of the interface between Mbed TLS and drivers, refer to the [PSA Cryptoprocessor Driver Interface specification](psa-driver-interface.html).
The interface is not fully implemented in Mbed TLS yet and is disabled by default. You can enable the experimental work in progress by setting `MBEDTLS_PSA_CRYPTO_DRIVERS` in the compile-time configuration. Please note that the interface may still change: until further notice, we do not guarantee backward compatibility with existing driver code when `MBEDTLS_PSA_CRYPTO_DRIVERS` is enabled.
## Introduction
### Purpose
The PSA cryptography driver interface provides a way to build Mbed TLS with additional code that implements certain cryptographic primitives. This is primarily intended to support platform-specific hardware.
There are two types of drivers:
* **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 Crypto 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 that the driver is registered for: the dispatch is based on the key's lifetime.
### Deliverables for a driver
To write a driver, you need to implement some functions with C linkage, and to declare these functions in a **driver description file**. The driver description file declares which functions the driver implements and what cryptographic mechanisms they support. Depending on the driver type, you may also need to define some C types and macros in a header file.
The concrete syntax for a driver description file is JSON. The structure of this JSON file is specified in the section [“Driver description syntax”](psa-driver-interface.html#driver-description-syntax) of the PSA cryptography driver interface specification.
A driver therefore consists of:
* A driver description file (in JSON format).
* C header files defining the types required by the driver description. The names of these header files is declared in the driver description file.
* An object file compiled for the target platform defining the functions required by the driver description. Implementations may allow drivers to be provided as source files and compiled with the core instead of being pre-compiled.
## Driver C interfaces
Mbed TLS calls driver entry points [as specified in the PSA Cryptography Driver Interface specification](psa-driver-interface.html#driver-entry-points) except as otherwise indicated in this section.
## Building and testing your driver
<!-- TODO -->
## Dependencies on the Mbed TLS configuration
<!-- TODO -->
|
0 | repos/gpt4all.zig/src/zig-libcurl/zig-mbedtls/mbedtls | repos/gpt4all.zig/src/zig-libcurl/zig-mbedtls/mbedtls/3rdparty/CMakeLists.txt | list (APPEND thirdparty_src)
list (APPEND thirdparty_lib)
list (APPEND thirdparty_inc_public)
list (APPEND thirdparty_inc)
list (APPEND thirdparty_def)
execute_process(COMMAND ${MBEDTLS_PYTHON_EXECUTABLE} ${CMAKE_CURRENT_SOURCE_DIR}/../scripts/config.py -f ${CMAKE_CURRENT_SOURCE_DIR}/../include/mbedtls/config.h get MBEDTLS_ECDH_VARIANT_EVEREST_ENABLED RESULT_VARIABLE result)
if(${result} EQUAL 0)
add_subdirectory(everest)
endif()
set(thirdparty_src ${thirdparty_src} PARENT_SCOPE)
set(thirdparty_lib ${thirdparty_lib} PARENT_SCOPE)
set(thirdparty_inc_public ${thirdparty_inc_public} PARENT_SCOPE)
set(thirdparty_inc ${thirdparty_inc} PARENT_SCOPE)
set(thirdparty_def ${thirdparty_def} PARENT_SCOPE)
|
0 | repos/gpt4all.zig/src/zig-libcurl/zig-mbedtls/mbedtls | repos/gpt4all.zig/src/zig-libcurl/zig-mbedtls/mbedtls/3rdparty/Makefile.inc | THIRDPARTY_DIR = $(dir $(lastword $(MAKEFILE_LIST)))
include $(THIRDPARTY_DIR)/everest/Makefile.inc
|
0 | repos/gpt4all.zig/src/zig-libcurl/zig-mbedtls/mbedtls/3rdparty | repos/gpt4all.zig/src/zig-libcurl/zig-mbedtls/mbedtls/3rdparty/everest/CMakeLists.txt | list (APPEND everest_src)
list (APPEND everest_inc_public)
list (APPEND everest_inc)
list (APPEND everest_def)
set(everest_src
${CMAKE_CURRENT_SOURCE_DIR}/library/everest.c
${CMAKE_CURRENT_SOURCE_DIR}/library/x25519.c
${CMAKE_CURRENT_SOURCE_DIR}/library/Hacl_Curve25519_joined.c
)
list(APPEND everest_inc_public ${CMAKE_CURRENT_SOURCE_DIR}/include)
list(APPEND everest_inc ${CMAKE_CURRENT_SOURCE_DIR}/include/everest ${CMAKE_CURRENT_SOURCE_DIR}/include/everest/kremlib)
if(INSTALL_MBEDTLS_HEADERS)
install(DIRECTORY include/everest
DESTINATION include
FILE_PERMISSIONS OWNER_READ OWNER_WRITE GROUP_READ WORLD_READ
DIRECTORY_PERMISSIONS OWNER_READ OWNER_WRITE OWNER_EXECUTE GROUP_READ GROUP_EXECUTE WORLD_READ WORLD_EXECUTE
FILES_MATCHING PATTERN "*.h")
endif(INSTALL_MBEDTLS_HEADERS)
set(thirdparty_src ${thirdparty_src} ${everest_src} PARENT_SCOPE)
set(thirdparty_inc_public ${thirdparty_inc_public} ${everest_inc_public} PARENT_SCOPE)
set(thirdparty_inc ${thirdparty_inc} ${everest_inc} PARENT_SCOPE)
set(thirdparty_def ${thirdparty_def} ${everest_def} PARENT_SCOPE)
|
0 | repos/gpt4all.zig/src/zig-libcurl/zig-mbedtls/mbedtls/3rdparty | repos/gpt4all.zig/src/zig-libcurl/zig-mbedtls/mbedtls/3rdparty/everest/Makefile.inc | THIRDPARTY_INCLUDES+=-I../3rdparty/everest/include -I../3rdparty/everest/include/everest -I../3rdparty/everest/include/everest/kremlib
THIRDPARTY_CRYPTO_OBJECTS+= \
../3rdparty/everest/library/everest.o \
../3rdparty/everest/library/x25519.o \
../3rdparty/everest/library/Hacl_Curve25519_joined.o
|
0 | repos/gpt4all.zig/src/zig-libcurl/zig-mbedtls/mbedtls/3rdparty | repos/gpt4all.zig/src/zig-libcurl/zig-mbedtls/mbedtls/3rdparty/everest/README.md | The files in this directory stem from [Project Everest](https://project-everest.github.io/) and are distributed under the Apache 2.0 license.
This is a formally verified implementation of Curve25519-based handshakes. The C code is automatically derived from the (verified) [original implementation](https://github.com/project-everest/hacl-star/tree/master/code/curve25519) in the [F* language](https://github.com/fstarlang/fstar) by [KreMLin](https://github.com/fstarlang/kremlin). In addition to the improved safety and security of the implementation, it is also significantly faster than the default implementation of Curve25519 in mbedTLS.
The caveat is that not all platforms are supported, although the version in `everest/library/legacy` should work on most systems. The main issue is that some platforms do not provide a 128-bit integer type and KreMLin therefore has to use additional (also verified) code to simulate them, resulting in less of a performance gain overall. Explictly supported platforms are currently `x86` and `x86_64` using gcc or clang, and Visual C (2010 and later).
|
0 | repos/gpt4all.zig/src/zig-libcurl/zig-mbedtls/mbedtls/3rdparty/everest/include | repos/gpt4all.zig/src/zig-libcurl/zig-mbedtls/mbedtls/3rdparty/everest/include/everest/kremlib.h | /*
* Copyright 2016-2018 INRIA and Microsoft Corporation
*
* SPDX-License-Identifier: Apache-2.0
*
* 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.
*
* This file is part of Mbed TLS (https://tls.mbed.org) and
* originated from Project Everest (https://project-everest.github.io/)
*/
#ifndef __KREMLIB_H
#define __KREMLIB_H
#include "kremlin/internal/target.h"
#include "kremlin/internal/types.h"
#include "kremlin/c_endianness.h"
#endif /* __KREMLIB_H */
|
0 | repos/gpt4all.zig/src/zig-libcurl/zig-mbedtls/mbedtls/3rdparty/everest/include | repos/gpt4all.zig/src/zig-libcurl/zig-mbedtls/mbedtls/3rdparty/everest/include/everest/x25519.h | /*
* ECDH with curve-optimized implementation multiplexing
*
* Copyright 2016-2018 INRIA and Microsoft Corporation
* SPDX-License-Identifier: Apache-2.0
*
* 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.
*
* This file is part of mbed TLS (https://tls.mbed.org)
*/
#ifndef MBEDTLS_X25519_H
#define MBEDTLS_X25519_H
#ifdef __cplusplus
extern "C" {
#endif
#define MBEDTLS_ECP_TLS_CURVE25519 0x1d
#define MBEDTLS_X25519_KEY_SIZE_BYTES 32
/**
* Defines the source of the imported EC key.
*/
typedef enum
{
MBEDTLS_X25519_ECDH_OURS, /**< Our key. */
MBEDTLS_X25519_ECDH_THEIRS, /**< The key of the peer. */
} mbedtls_x25519_ecdh_side;
/**
* \brief The x25519 context structure.
*/
typedef struct
{
unsigned char our_secret[MBEDTLS_X25519_KEY_SIZE_BYTES];
unsigned char peer_point[MBEDTLS_X25519_KEY_SIZE_BYTES];
} mbedtls_x25519_context;
/**
* \brief This function initializes an x25519 context.
*
* \param ctx The x25519 context to initialize.
*/
void mbedtls_x25519_init( mbedtls_x25519_context *ctx );
/**
* \brief This function frees a context.
*
* \param ctx The context to free.
*/
void mbedtls_x25519_free( mbedtls_x25519_context *ctx );
/**
* \brief This function generates a public key and a TLS
* ServerKeyExchange payload.
*
* This is the first function used by a TLS server for x25519.
*
*
* \param ctx The x25519 context.
* \param olen The number of characters written.
* \param buf The destination buffer.
* \param blen The length of the destination buffer.
* \param f_rng The RNG function.
* \param p_rng The RNG context.
*
* \return \c 0 on success.
* \return An \c MBEDTLS_ERR_ECP_XXX error code on failure.
*/
int mbedtls_x25519_make_params( mbedtls_x25519_context *ctx, size_t *olen,
unsigned char *buf, size_t blen,
int( *f_rng )(void *, unsigned char *, size_t),
void *p_rng );
/**
* \brief This function parses and processes a TLS ServerKeyExchange
* payload.
*
*
* \param ctx The x25519 context.
* \param buf The pointer to the start of the input buffer.
* \param end The address for one Byte past the end of the buffer.
*
* \return \c 0 on success.
* \return An \c MBEDTLS_ERR_ECP_XXX error code on failure.
*
*/
int mbedtls_x25519_read_params( mbedtls_x25519_context *ctx,
const unsigned char **buf, const unsigned char *end );
/**
* \brief This function sets up an x25519 context from an EC key.
*
* It is used by clients and servers in place of the
* ServerKeyEchange for static ECDH, and imports ECDH
* parameters from the EC key information of a certificate.
*
* \see ecp.h
*
* \param ctx The x25519 context to set up.
* \param key The EC key to use.
* \param side Defines the source of the key: 1: Our key, or
* 0: The key of the peer.
*
* \return \c 0 on success.
* \return An \c MBEDTLS_ERR_ECP_XXX error code on failure.
*
*/
int mbedtls_x25519_get_params( mbedtls_x25519_context *ctx, const mbedtls_ecp_keypair *key,
mbedtls_x25519_ecdh_side side );
/**
* \brief This function derives and exports the shared secret.
*
* This is the last function used by both TLS client
* and servers.
*
*
* \param ctx The x25519 context.
* \param olen The number of Bytes written.
* \param buf The destination buffer.
* \param blen The length of the destination buffer.
* \param f_rng The RNG function.
* \param p_rng The RNG context.
*
* \return \c 0 on success.
* \return An \c MBEDTLS_ERR_ECP_XXX error code on failure.
*/
int mbedtls_x25519_calc_secret( mbedtls_x25519_context *ctx, size_t *olen,
unsigned char *buf, size_t blen,
int( *f_rng )(void *, unsigned char *, size_t),
void *p_rng );
/**
* \brief This function generates a public key and a TLS
* ClientKeyExchange payload.
*
* This is the second function used by a TLS client for x25519.
*
* \see ecp.h
*
* \param ctx The x25519 context.
* \param olen The number of Bytes written.
* \param buf The destination buffer.
* \param blen The size of the destination buffer.
* \param f_rng The RNG function.
* \param p_rng The RNG context.
*
* \return \c 0 on success.
* \return An \c MBEDTLS_ERR_ECP_XXX error code on failure.
*/
int mbedtls_x25519_make_public( mbedtls_x25519_context *ctx, size_t *olen,
unsigned char *buf, size_t blen,
int( *f_rng )(void *, unsigned char *, size_t),
void *p_rng );
/**
* \brief This function parses and processes a TLS ClientKeyExchange
* payload.
*
* This is the second function used by a TLS server for x25519.
*
* \see ecp.h
*
* \param ctx The x25519 context.
* \param buf The start of the input buffer.
* \param blen The length of the input buffer.
*
* \return \c 0 on success.
* \return An \c MBEDTLS_ERR_ECP_XXX error code on failure.
*/
int mbedtls_x25519_read_public( mbedtls_x25519_context *ctx,
const unsigned char *buf, size_t blen );
#ifdef __cplusplus
}
#endif
#endif /* x25519.h */
|
0 | repos/gpt4all.zig/src/zig-libcurl/zig-mbedtls/mbedtls/3rdparty/everest/include | repos/gpt4all.zig/src/zig-libcurl/zig-mbedtls/mbedtls/3rdparty/everest/include/everest/Hacl_Curve25519.h | /* Copyright (c) INRIA and Microsoft Corporation. All rights reserved.
Licensed under the Apache 2.0 License. */
/* This file was generated by KreMLin <https://github.com/FStarLang/kremlin>
* KreMLin invocation: /mnt/e/everest/verify/kremlin/krml -fc89 -fparentheses -fno-shadow -header /mnt/e/everest/verify/hdrcLh -minimal -fbuiltin-uint128 -fc89 -fparentheses -fno-shadow -header /mnt/e/everest/verify/hdrcLh -minimal -I /mnt/e/everest/verify/hacl-star/code/lib/kremlin -I /mnt/e/everest/verify/kremlin/kremlib/compat -I /mnt/e/everest/verify/hacl-star/specs -I /mnt/e/everest/verify/hacl-star/specs/old -I . -ccopt -march=native -verbose -ldopt -flto -tmpdir x25519-c -I ../bignum -bundle Hacl.Curve25519=* -minimal -add-include "kremlib.h" -skip-compilation x25519-c/out.krml -o x25519-c/Hacl_Curve25519.c
* F* version: 059db0c8
* KreMLin version: 916c37ac
*/
#ifndef __Hacl_Curve25519_H
#define __Hacl_Curve25519_H
#include "kremlib.h"
void Hacl_Curve25519_crypto_scalarmult(uint8_t *mypublic, uint8_t *secret, uint8_t *basepoint);
#define __Hacl_Curve25519_H_DEFINED
#endif
|
0 | repos/gpt4all.zig/src/zig-libcurl/zig-mbedtls/mbedtls/3rdparty/everest/include | repos/gpt4all.zig/src/zig-libcurl/zig-mbedtls/mbedtls/3rdparty/everest/include/everest/everest.h | /*
* Interface to code from Project Everest
*
* Copyright 2016-2018 INRIA and Microsoft Corporation
* SPDX-License-Identifier: Apache-2.0
*
* 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.
*
* This file is part of Mbed TLS (https://tls.mbed.org).
*/
#ifndef MBEDTLS_EVEREST_H
#define MBEDTLS_EVEREST_H
#include "everest/x25519.h"
#ifdef __cplusplus
extern "C" {
#endif
/**
* Defines the source of the imported EC key.
*/
typedef enum
{
MBEDTLS_EVEREST_ECDH_OURS, /**< Our key. */
MBEDTLS_EVEREST_ECDH_THEIRS, /**< The key of the peer. */
} mbedtls_everest_ecdh_side;
typedef struct {
mbedtls_x25519_context ctx;
} mbedtls_ecdh_context_everest;
/**
* \brief This function sets up the ECDH context with the information
* given.
*
* This function should be called after mbedtls_ecdh_init() but
* before mbedtls_ecdh_make_params(). There is no need to call
* this function before mbedtls_ecdh_read_params().
*
* This is the first function used by a TLS server for ECDHE
* ciphersuites.
*
* \param ctx The ECDH context to set up.
* \param grp_id The group id of the group to set up the context for.
*
* \return \c 0 on success.
*/
int mbedtls_everest_setup( mbedtls_ecdh_context_everest *ctx, int grp_id );
/**
* \brief This function frees a context.
*
* \param ctx The context to free.
*/
void mbedtls_everest_free( mbedtls_ecdh_context_everest *ctx );
/**
* \brief This function generates a public key and a TLS
* ServerKeyExchange payload.
*
* This is the second function used by a TLS server for ECDHE
* ciphersuites. (It is called after mbedtls_ecdh_setup().)
*
* \note This function assumes that the ECP group (grp) of the
* \p ctx context has already been properly set,
* for example, using mbedtls_ecp_group_load().
*
* \see ecp.h
*
* \param ctx The ECDH context.
* \param olen The number of characters written.
* \param buf The destination buffer.
* \param blen The length of the destination buffer.
* \param f_rng The RNG function.
* \param p_rng The RNG context.
*
* \return \c 0 on success.
* \return An \c MBEDTLS_ERR_ECP_XXX error code on failure.
*/
int mbedtls_everest_make_params( mbedtls_ecdh_context_everest *ctx, size_t *olen,
unsigned char *buf, size_t blen,
int( *f_rng )( void *, unsigned char *, size_t ),
void *p_rng );
/**
* \brief This function parses and processes a TLS ServerKeyExhange
* payload.
*
* This is the first function used by a TLS client for ECDHE
* ciphersuites.
*
* \see ecp.h
*
* \param ctx The ECDH context.
* \param buf The pointer to the start of the input buffer.
* \param end The address for one Byte past the end of the buffer.
*
* \return \c 0 on success.
* \return An \c MBEDTLS_ERR_ECP_XXX error code on failure.
*
*/
int mbedtls_everest_read_params( mbedtls_ecdh_context_everest *ctx,
const unsigned char **buf, const unsigned char *end );
/**
* \brief This function parses and processes a TLS ServerKeyExhange
* payload.
*
* This is the first function used by a TLS client for ECDHE
* ciphersuites.
*
* \see ecp.h
*
* \param ctx The ECDH context.
* \param buf The pointer to the start of the input buffer.
* \param end The address for one Byte past the end of the buffer.
*
* \return \c 0 on success.
* \return An \c MBEDTLS_ERR_ECP_XXX error code on failure.
*
*/
int mbedtls_everest_read_params( mbedtls_ecdh_context_everest *ctx,
const unsigned char **buf, const unsigned char *end );
/**
* \brief This function sets up an ECDH context from an EC key.
*
* It is used by clients and servers in place of the
* ServerKeyEchange for static ECDH, and imports ECDH
* parameters from the EC key information of a certificate.
*
* \see ecp.h
*
* \param ctx The ECDH context to set up.
* \param key The EC key to use.
* \param side Defines the source of the key: 1: Our key, or
* 0: The key of the peer.
*
* \return \c 0 on success.
* \return An \c MBEDTLS_ERR_ECP_XXX error code on failure.
*
*/
int mbedtls_everest_get_params( mbedtls_ecdh_context_everest *ctx, const mbedtls_ecp_keypair *key,
mbedtls_everest_ecdh_side side );
/**
* \brief This function generates a public key and a TLS
* ClientKeyExchange payload.
*
* This is the second function used by a TLS client for ECDH(E)
* ciphersuites.
*
* \see ecp.h
*
* \param ctx The ECDH context.
* \param olen The number of Bytes written.
* \param buf The destination buffer.
* \param blen The size of the destination buffer.
* \param f_rng The RNG function.
* \param p_rng The RNG context.
*
* \return \c 0 on success.
* \return An \c MBEDTLS_ERR_ECP_XXX error code on failure.
*/
int mbedtls_everest_make_public( mbedtls_ecdh_context_everest *ctx, size_t *olen,
unsigned char *buf, size_t blen,
int( *f_rng )( void *, unsigned char *, size_t ),
void *p_rng );
/**
* \brief This function parses and processes a TLS ClientKeyExchange
* payload.
*
* This is the third function used by a TLS server for ECDH(E)
* ciphersuites. (It is called after mbedtls_ecdh_setup() and
* mbedtls_ecdh_make_params().)
*
* \see ecp.h
*
* \param ctx The ECDH context.
* \param buf The start of the input buffer.
* \param blen The length of the input buffer.
*
* \return \c 0 on success.
* \return An \c MBEDTLS_ERR_ECP_XXX error code on failure.
*/
int mbedtls_everest_read_public( mbedtls_ecdh_context_everest *ctx,
const unsigned char *buf, size_t blen );
/**
* \brief This function derives and exports the shared secret.
*
* This is the last function used by both TLS client
* and servers.
*
* \note If \p f_rng is not NULL, it is used to implement
* countermeasures against side-channel attacks.
* For more information, see mbedtls_ecp_mul().
*
* \see ecp.h
*
* \param ctx The ECDH context.
* \param olen The number of Bytes written.
* \param buf The destination buffer.
* \param blen The length of the destination buffer.
* \param f_rng The RNG function.
* \param p_rng The RNG context.
*
* \return \c 0 on success.
* \return An \c MBEDTLS_ERR_ECP_XXX error code on failure.
*/
int mbedtls_everest_calc_secret( mbedtls_ecdh_context_everest *ctx, size_t *olen,
unsigned char *buf, size_t blen,
int( *f_rng )( void *, unsigned char *, size_t ),
void *p_rng );
#ifdef __cplusplus
}
#endif
#endif /* MBEDTLS_EVEREST_H */
|
0 | repos/gpt4all.zig/src/zig-libcurl/zig-mbedtls/mbedtls/3rdparty/everest/include/everest | repos/gpt4all.zig/src/zig-libcurl/zig-mbedtls/mbedtls/3rdparty/everest/include/everest/kremlib/FStar_UInt64_FStar_UInt32_FStar_UInt16_FStar_UInt8.h | /* Copyright (c) INRIA and Microsoft Corporation. All rights reserved.
Licensed under the Apache 2.0 License. */
/* This file was generated by KreMLin <https://github.com/FStarLang/kremlin>
* KreMLin invocation: ../krml -fc89 -fparentheses -fno-shadow -header /mnt/e/everest/verify/hdrB9w -minimal -fparentheses -fcurly-braces -fno-shadow -header copyright-header.txt -minimal -tmpdir dist/minimal -skip-compilation -extract-uints -add-include <inttypes.h> -add-include <stdbool.h> -add-include "kremlin/internal/compat.h" -add-include "kremlin/internal/types.h" -bundle FStar.UInt64+FStar.UInt32+FStar.UInt16+FStar.UInt8=* extracted/prims.krml extracted/FStar_Pervasives_Native.krml extracted/FStar_Pervasives.krml extracted/FStar_Mul.krml extracted/FStar_Squash.krml extracted/FStar_Classical.krml extracted/FStar_StrongExcludedMiddle.krml extracted/FStar_FunctionalExtensionality.krml extracted/FStar_List_Tot_Base.krml extracted/FStar_List_Tot_Properties.krml extracted/FStar_List_Tot.krml extracted/FStar_Seq_Base.krml extracted/FStar_Seq_Properties.krml extracted/FStar_Seq.krml extracted/FStar_Math_Lib.krml extracted/FStar_Math_Lemmas.krml extracted/FStar_BitVector.krml extracted/FStar_UInt.krml extracted/FStar_UInt32.krml extracted/FStar_Int.krml extracted/FStar_Int16.krml extracted/FStar_Preorder.krml extracted/FStar_Ghost.krml extracted/FStar_ErasedLogic.krml extracted/FStar_UInt64.krml extracted/FStar_Set.krml extracted/FStar_PropositionalExtensionality.krml extracted/FStar_PredicateExtensionality.krml extracted/FStar_TSet.krml extracted/FStar_Monotonic_Heap.krml extracted/FStar_Heap.krml extracted/FStar_Map.krml extracted/FStar_Monotonic_HyperHeap.krml extracted/FStar_Monotonic_HyperStack.krml extracted/FStar_HyperStack.krml extracted/FStar_Monotonic_Witnessed.krml extracted/FStar_HyperStack_ST.krml extracted/FStar_HyperStack_All.krml extracted/FStar_Date.krml extracted/FStar_Universe.krml extracted/FStar_GSet.krml extracted/FStar_ModifiesGen.krml extracted/LowStar_Monotonic_Buffer.krml extracted/LowStar_Buffer.krml extracted/Spec_Loops.krml extracted/LowStar_BufferOps.krml extracted/C_Loops.krml extracted/FStar_UInt8.krml extracted/FStar_Kremlin_Endianness.krml extracted/FStar_UInt63.krml extracted/FStar_Exn.krml extracted/FStar_ST.krml extracted/FStar_All.krml extracted/FStar_Dyn.krml extracted/FStar_Int63.krml extracted/FStar_Int64.krml extracted/FStar_Int32.krml extracted/FStar_Int8.krml extracted/FStar_UInt16.krml extracted/FStar_Int_Cast.krml extracted/FStar_UInt128.krml extracted/C_Endianness.krml extracted/FStar_List.krml extracted/FStar_Float.krml extracted/FStar_IO.krml extracted/C.krml extracted/FStar_Char.krml extracted/FStar_String.krml extracted/LowStar_Modifies.krml extracted/C_String.krml extracted/FStar_Bytes.krml extracted/FStar_HyperStack_IO.krml extracted/C_Failure.krml extracted/TestLib.krml extracted/FStar_Int_Cast_Full.krml
* F* version: 059db0c8
* KreMLin version: 916c37ac
*/
#ifndef __FStar_UInt64_FStar_UInt32_FStar_UInt16_FStar_UInt8_H
#define __FStar_UInt64_FStar_UInt32_FStar_UInt16_FStar_UInt8_H
#include <inttypes.h>
#include <stdbool.h>
#include "kremlin/internal/compat.h"
#include "kremlin/internal/types.h"
extern Prims_int FStar_UInt64_n;
extern Prims_int FStar_UInt64_v(uint64_t x0);
extern uint64_t FStar_UInt64_uint_to_t(Prims_int x0);
extern uint64_t FStar_UInt64_add(uint64_t x0, uint64_t x1);
extern uint64_t FStar_UInt64_add_underspec(uint64_t x0, uint64_t x1);
extern uint64_t FStar_UInt64_add_mod(uint64_t x0, uint64_t x1);
extern uint64_t FStar_UInt64_sub(uint64_t x0, uint64_t x1);
extern uint64_t FStar_UInt64_sub_underspec(uint64_t x0, uint64_t x1);
extern uint64_t FStar_UInt64_sub_mod(uint64_t x0, uint64_t x1);
extern uint64_t FStar_UInt64_mul(uint64_t x0, uint64_t x1);
extern uint64_t FStar_UInt64_mul_underspec(uint64_t x0, uint64_t x1);
extern uint64_t FStar_UInt64_mul_mod(uint64_t x0, uint64_t x1);
extern uint64_t FStar_UInt64_mul_div(uint64_t x0, uint64_t x1);
extern uint64_t FStar_UInt64_div(uint64_t x0, uint64_t x1);
extern uint64_t FStar_UInt64_rem(uint64_t x0, uint64_t x1);
extern uint64_t FStar_UInt64_logand(uint64_t x0, uint64_t x1);
extern uint64_t FStar_UInt64_logxor(uint64_t x0, uint64_t x1);
extern uint64_t FStar_UInt64_logor(uint64_t x0, uint64_t x1);
extern uint64_t FStar_UInt64_lognot(uint64_t x0);
extern uint64_t FStar_UInt64_shift_right(uint64_t x0, uint32_t x1);
extern uint64_t FStar_UInt64_shift_left(uint64_t x0, uint32_t x1);
extern bool FStar_UInt64_eq(uint64_t x0, uint64_t x1);
extern bool FStar_UInt64_gt(uint64_t x0, uint64_t x1);
extern bool FStar_UInt64_gte(uint64_t x0, uint64_t x1);
extern bool FStar_UInt64_lt(uint64_t x0, uint64_t x1);
extern bool FStar_UInt64_lte(uint64_t x0, uint64_t x1);
extern uint64_t FStar_UInt64_minus(uint64_t x0);
extern uint32_t FStar_UInt64_n_minus_one;
uint64_t FStar_UInt64_eq_mask(uint64_t a, uint64_t b);
uint64_t FStar_UInt64_gte_mask(uint64_t a, uint64_t b);
extern Prims_string FStar_UInt64_to_string(uint64_t x0);
extern uint64_t FStar_UInt64_of_string(Prims_string x0);
extern Prims_int FStar_UInt32_n;
extern Prims_int FStar_UInt32_v(uint32_t x0);
extern uint32_t FStar_UInt32_uint_to_t(Prims_int x0);
extern uint32_t FStar_UInt32_add(uint32_t x0, uint32_t x1);
extern uint32_t FStar_UInt32_add_underspec(uint32_t x0, uint32_t x1);
extern uint32_t FStar_UInt32_add_mod(uint32_t x0, uint32_t x1);
extern uint32_t FStar_UInt32_sub(uint32_t x0, uint32_t x1);
extern uint32_t FStar_UInt32_sub_underspec(uint32_t x0, uint32_t x1);
extern uint32_t FStar_UInt32_sub_mod(uint32_t x0, uint32_t x1);
extern uint32_t FStar_UInt32_mul(uint32_t x0, uint32_t x1);
extern uint32_t FStar_UInt32_mul_underspec(uint32_t x0, uint32_t x1);
extern uint32_t FStar_UInt32_mul_mod(uint32_t x0, uint32_t x1);
extern uint32_t FStar_UInt32_mul_div(uint32_t x0, uint32_t x1);
extern uint32_t FStar_UInt32_div(uint32_t x0, uint32_t x1);
extern uint32_t FStar_UInt32_rem(uint32_t x0, uint32_t x1);
extern uint32_t FStar_UInt32_logand(uint32_t x0, uint32_t x1);
extern uint32_t FStar_UInt32_logxor(uint32_t x0, uint32_t x1);
extern uint32_t FStar_UInt32_logor(uint32_t x0, uint32_t x1);
extern uint32_t FStar_UInt32_lognot(uint32_t x0);
extern uint32_t FStar_UInt32_shift_right(uint32_t x0, uint32_t x1);
extern uint32_t FStar_UInt32_shift_left(uint32_t x0, uint32_t x1);
extern bool FStar_UInt32_eq(uint32_t x0, uint32_t x1);
extern bool FStar_UInt32_gt(uint32_t x0, uint32_t x1);
extern bool FStar_UInt32_gte(uint32_t x0, uint32_t x1);
extern bool FStar_UInt32_lt(uint32_t x0, uint32_t x1);
extern bool FStar_UInt32_lte(uint32_t x0, uint32_t x1);
extern uint32_t FStar_UInt32_minus(uint32_t x0);
extern uint32_t FStar_UInt32_n_minus_one;
uint32_t FStar_UInt32_eq_mask(uint32_t a, uint32_t b);
uint32_t FStar_UInt32_gte_mask(uint32_t a, uint32_t b);
extern Prims_string FStar_UInt32_to_string(uint32_t x0);
extern uint32_t FStar_UInt32_of_string(Prims_string x0);
extern Prims_int FStar_UInt16_n;
extern Prims_int FStar_UInt16_v(uint16_t x0);
extern uint16_t FStar_UInt16_uint_to_t(Prims_int x0);
extern uint16_t FStar_UInt16_add(uint16_t x0, uint16_t x1);
extern uint16_t FStar_UInt16_add_underspec(uint16_t x0, uint16_t x1);
extern uint16_t FStar_UInt16_add_mod(uint16_t x0, uint16_t x1);
extern uint16_t FStar_UInt16_sub(uint16_t x0, uint16_t x1);
extern uint16_t FStar_UInt16_sub_underspec(uint16_t x0, uint16_t x1);
extern uint16_t FStar_UInt16_sub_mod(uint16_t x0, uint16_t x1);
extern uint16_t FStar_UInt16_mul(uint16_t x0, uint16_t x1);
extern uint16_t FStar_UInt16_mul_underspec(uint16_t x0, uint16_t x1);
extern uint16_t FStar_UInt16_mul_mod(uint16_t x0, uint16_t x1);
extern uint16_t FStar_UInt16_mul_div(uint16_t x0, uint16_t x1);
extern uint16_t FStar_UInt16_div(uint16_t x0, uint16_t x1);
extern uint16_t FStar_UInt16_rem(uint16_t x0, uint16_t x1);
extern uint16_t FStar_UInt16_logand(uint16_t x0, uint16_t x1);
extern uint16_t FStar_UInt16_logxor(uint16_t x0, uint16_t x1);
extern uint16_t FStar_UInt16_logor(uint16_t x0, uint16_t x1);
extern uint16_t FStar_UInt16_lognot(uint16_t x0);
extern uint16_t FStar_UInt16_shift_right(uint16_t x0, uint32_t x1);
extern uint16_t FStar_UInt16_shift_left(uint16_t x0, uint32_t x1);
extern bool FStar_UInt16_eq(uint16_t x0, uint16_t x1);
extern bool FStar_UInt16_gt(uint16_t x0, uint16_t x1);
extern bool FStar_UInt16_gte(uint16_t x0, uint16_t x1);
extern bool FStar_UInt16_lt(uint16_t x0, uint16_t x1);
extern bool FStar_UInt16_lte(uint16_t x0, uint16_t x1);
extern uint16_t FStar_UInt16_minus(uint16_t x0);
extern uint32_t FStar_UInt16_n_minus_one;
uint16_t FStar_UInt16_eq_mask(uint16_t a, uint16_t b);
uint16_t FStar_UInt16_gte_mask(uint16_t a, uint16_t b);
extern Prims_string FStar_UInt16_to_string(uint16_t x0);
extern uint16_t FStar_UInt16_of_string(Prims_string x0);
extern Prims_int FStar_UInt8_n;
extern Prims_int FStar_UInt8_v(uint8_t x0);
extern uint8_t FStar_UInt8_uint_to_t(Prims_int x0);
extern uint8_t FStar_UInt8_add(uint8_t x0, uint8_t x1);
extern uint8_t FStar_UInt8_add_underspec(uint8_t x0, uint8_t x1);
extern uint8_t FStar_UInt8_add_mod(uint8_t x0, uint8_t x1);
extern uint8_t FStar_UInt8_sub(uint8_t x0, uint8_t x1);
extern uint8_t FStar_UInt8_sub_underspec(uint8_t x0, uint8_t x1);
extern uint8_t FStar_UInt8_sub_mod(uint8_t x0, uint8_t x1);
extern uint8_t FStar_UInt8_mul(uint8_t x0, uint8_t x1);
extern uint8_t FStar_UInt8_mul_underspec(uint8_t x0, uint8_t x1);
extern uint8_t FStar_UInt8_mul_mod(uint8_t x0, uint8_t x1);
extern uint8_t FStar_UInt8_mul_div(uint8_t x0, uint8_t x1);
extern uint8_t FStar_UInt8_div(uint8_t x0, uint8_t x1);
extern uint8_t FStar_UInt8_rem(uint8_t x0, uint8_t x1);
extern uint8_t FStar_UInt8_logand(uint8_t x0, uint8_t x1);
extern uint8_t FStar_UInt8_logxor(uint8_t x0, uint8_t x1);
extern uint8_t FStar_UInt8_logor(uint8_t x0, uint8_t x1);
extern uint8_t FStar_UInt8_lognot(uint8_t x0);
extern uint8_t FStar_UInt8_shift_right(uint8_t x0, uint32_t x1);
extern uint8_t FStar_UInt8_shift_left(uint8_t x0, uint32_t x1);
extern bool FStar_UInt8_eq(uint8_t x0, uint8_t x1);
extern bool FStar_UInt8_gt(uint8_t x0, uint8_t x1);
extern bool FStar_UInt8_gte(uint8_t x0, uint8_t x1);
extern bool FStar_UInt8_lt(uint8_t x0, uint8_t x1);
extern bool FStar_UInt8_lte(uint8_t x0, uint8_t x1);
extern uint8_t FStar_UInt8_minus(uint8_t x0);
extern uint32_t FStar_UInt8_n_minus_one;
uint8_t FStar_UInt8_eq_mask(uint8_t a, uint8_t b);
uint8_t FStar_UInt8_gte_mask(uint8_t a, uint8_t b);
extern Prims_string FStar_UInt8_to_string(uint8_t x0);
extern uint8_t FStar_UInt8_of_string(Prims_string x0);
typedef uint8_t FStar_UInt8_byte;
#define __FStar_UInt64_FStar_UInt32_FStar_UInt16_FStar_UInt8_H_DEFINED
#endif
|
0 | repos/gpt4all.zig/src/zig-libcurl/zig-mbedtls/mbedtls/3rdparty/everest/include/everest | repos/gpt4all.zig/src/zig-libcurl/zig-mbedtls/mbedtls/3rdparty/everest/include/everest/kremlib/FStar_UInt128.h | /* Copyright (c) INRIA and Microsoft Corporation. All rights reserved.
Licensed under the Apache 2.0 License. */
/* This file was generated by KreMLin <https://github.com/FStarLang/kremlin>
* KreMLin invocation: ../krml -fc89 -fparentheses -fno-shadow -header /mnt/e/everest/verify/hdrB9w -minimal -fparentheses -fcurly-braces -fno-shadow -header copyright-header.txt -minimal -tmpdir dist/uint128 -skip-compilation -extract-uints -add-include <inttypes.h> -add-include <stdbool.h> -add-include "kremlin/internal/types.h" -bundle FStar.UInt128=* extracted/prims.krml extracted/FStar_Pervasives_Native.krml extracted/FStar_Pervasives.krml extracted/FStar_Mul.krml extracted/FStar_Squash.krml extracted/FStar_Classical.krml extracted/FStar_StrongExcludedMiddle.krml extracted/FStar_FunctionalExtensionality.krml extracted/FStar_List_Tot_Base.krml extracted/FStar_List_Tot_Properties.krml extracted/FStar_List_Tot.krml extracted/FStar_Seq_Base.krml extracted/FStar_Seq_Properties.krml extracted/FStar_Seq.krml extracted/FStar_Math_Lib.krml extracted/FStar_Math_Lemmas.krml extracted/FStar_BitVector.krml extracted/FStar_UInt.krml extracted/FStar_UInt32.krml extracted/FStar_Int.krml extracted/FStar_Int16.krml extracted/FStar_Preorder.krml extracted/FStar_Ghost.krml extracted/FStar_ErasedLogic.krml extracted/FStar_UInt64.krml extracted/FStar_Set.krml extracted/FStar_PropositionalExtensionality.krml extracted/FStar_PredicateExtensionality.krml extracted/FStar_TSet.krml extracted/FStar_Monotonic_Heap.krml extracted/FStar_Heap.krml extracted/FStar_Map.krml extracted/FStar_Monotonic_HyperHeap.krml extracted/FStar_Monotonic_HyperStack.krml extracted/FStar_HyperStack.krml extracted/FStar_Monotonic_Witnessed.krml extracted/FStar_HyperStack_ST.krml extracted/FStar_HyperStack_All.krml extracted/FStar_Date.krml extracted/FStar_Universe.krml extracted/FStar_GSet.krml extracted/FStar_ModifiesGen.krml extracted/LowStar_Monotonic_Buffer.krml extracted/LowStar_Buffer.krml extracted/Spec_Loops.krml extracted/LowStar_BufferOps.krml extracted/C_Loops.krml extracted/FStar_UInt8.krml extracted/FStar_Kremlin_Endianness.krml extracted/FStar_UInt63.krml extracted/FStar_Exn.krml extracted/FStar_ST.krml extracted/FStar_All.krml extracted/FStar_Dyn.krml extracted/FStar_Int63.krml extracted/FStar_Int64.krml extracted/FStar_Int32.krml extracted/FStar_Int8.krml extracted/FStar_UInt16.krml extracted/FStar_Int_Cast.krml extracted/FStar_UInt128.krml extracted/C_Endianness.krml extracted/FStar_List.krml extracted/FStar_Float.krml extracted/FStar_IO.krml extracted/C.krml extracted/FStar_Char.krml extracted/FStar_String.krml extracted/LowStar_Modifies.krml extracted/C_String.krml extracted/FStar_Bytes.krml extracted/FStar_HyperStack_IO.krml extracted/C_Failure.krml extracted/TestLib.krml extracted/FStar_Int_Cast_Full.krml
* F* version: 059db0c8
* KreMLin version: 916c37ac
*/
#ifndef __FStar_UInt128_H
#define __FStar_UInt128_H
#include <inttypes.h>
#include <stdbool.h>
#include "kremlin/internal/types.h"
uint64_t FStar_UInt128___proj__Mkuint128__item__low(FStar_UInt128_uint128 projectee);
uint64_t FStar_UInt128___proj__Mkuint128__item__high(FStar_UInt128_uint128 projectee);
typedef FStar_UInt128_uint128 FStar_UInt128_t;
FStar_UInt128_uint128 FStar_UInt128_add(FStar_UInt128_uint128 a, FStar_UInt128_uint128 b);
FStar_UInt128_uint128
FStar_UInt128_add_underspec(FStar_UInt128_uint128 a, FStar_UInt128_uint128 b);
FStar_UInt128_uint128 FStar_UInt128_add_mod(FStar_UInt128_uint128 a, FStar_UInt128_uint128 b);
FStar_UInt128_uint128 FStar_UInt128_sub(FStar_UInt128_uint128 a, FStar_UInt128_uint128 b);
FStar_UInt128_uint128
FStar_UInt128_sub_underspec(FStar_UInt128_uint128 a, FStar_UInt128_uint128 b);
FStar_UInt128_uint128 FStar_UInt128_sub_mod(FStar_UInt128_uint128 a, FStar_UInt128_uint128 b);
FStar_UInt128_uint128 FStar_UInt128_logand(FStar_UInt128_uint128 a, FStar_UInt128_uint128 b);
FStar_UInt128_uint128 FStar_UInt128_logxor(FStar_UInt128_uint128 a, FStar_UInt128_uint128 b);
FStar_UInt128_uint128 FStar_UInt128_logor(FStar_UInt128_uint128 a, FStar_UInt128_uint128 b);
FStar_UInt128_uint128 FStar_UInt128_lognot(FStar_UInt128_uint128 a);
FStar_UInt128_uint128 FStar_UInt128_shift_left(FStar_UInt128_uint128 a, uint32_t s);
FStar_UInt128_uint128 FStar_UInt128_shift_right(FStar_UInt128_uint128 a, uint32_t s);
bool FStar_UInt128_eq(FStar_UInt128_uint128 a, FStar_UInt128_uint128 b);
bool FStar_UInt128_gt(FStar_UInt128_uint128 a, FStar_UInt128_uint128 b);
bool FStar_UInt128_lt(FStar_UInt128_uint128 a, FStar_UInt128_uint128 b);
bool FStar_UInt128_gte(FStar_UInt128_uint128 a, FStar_UInt128_uint128 b);
bool FStar_UInt128_lte(FStar_UInt128_uint128 a, FStar_UInt128_uint128 b);
FStar_UInt128_uint128 FStar_UInt128_eq_mask(FStar_UInt128_uint128 a, FStar_UInt128_uint128 b);
FStar_UInt128_uint128 FStar_UInt128_gte_mask(FStar_UInt128_uint128 a, FStar_UInt128_uint128 b);
FStar_UInt128_uint128 FStar_UInt128_uint64_to_uint128(uint64_t a);
uint64_t FStar_UInt128_uint128_to_uint64(FStar_UInt128_uint128 a);
extern FStar_UInt128_uint128
(*FStar_UInt128_op_Plus_Hat)(FStar_UInt128_uint128 x0, FStar_UInt128_uint128 x1);
extern FStar_UInt128_uint128
(*FStar_UInt128_op_Plus_Question_Hat)(FStar_UInt128_uint128 x0, FStar_UInt128_uint128 x1);
extern FStar_UInt128_uint128
(*FStar_UInt128_op_Plus_Percent_Hat)(FStar_UInt128_uint128 x0, FStar_UInt128_uint128 x1);
extern FStar_UInt128_uint128
(*FStar_UInt128_op_Subtraction_Hat)(FStar_UInt128_uint128 x0, FStar_UInt128_uint128 x1);
extern FStar_UInt128_uint128
(*FStar_UInt128_op_Subtraction_Question_Hat)(
FStar_UInt128_uint128 x0,
FStar_UInt128_uint128 x1
);
extern FStar_UInt128_uint128
(*FStar_UInt128_op_Subtraction_Percent_Hat)(FStar_UInt128_uint128 x0, FStar_UInt128_uint128 x1);
extern FStar_UInt128_uint128
(*FStar_UInt128_op_Amp_Hat)(FStar_UInt128_uint128 x0, FStar_UInt128_uint128 x1);
extern FStar_UInt128_uint128
(*FStar_UInt128_op_Hat_Hat)(FStar_UInt128_uint128 x0, FStar_UInt128_uint128 x1);
extern FStar_UInt128_uint128
(*FStar_UInt128_op_Bar_Hat)(FStar_UInt128_uint128 x0, FStar_UInt128_uint128 x1);
extern FStar_UInt128_uint128
(*FStar_UInt128_op_Less_Less_Hat)(FStar_UInt128_uint128 x0, uint32_t x1);
extern FStar_UInt128_uint128
(*FStar_UInt128_op_Greater_Greater_Hat)(FStar_UInt128_uint128 x0, uint32_t x1);
extern bool (*FStar_UInt128_op_Equals_Hat)(FStar_UInt128_uint128 x0, FStar_UInt128_uint128 x1);
extern bool
(*FStar_UInt128_op_Greater_Hat)(FStar_UInt128_uint128 x0, FStar_UInt128_uint128 x1);
extern bool (*FStar_UInt128_op_Less_Hat)(FStar_UInt128_uint128 x0, FStar_UInt128_uint128 x1);
extern bool
(*FStar_UInt128_op_Greater_Equals_Hat)(FStar_UInt128_uint128 x0, FStar_UInt128_uint128 x1);
extern bool
(*FStar_UInt128_op_Less_Equals_Hat)(FStar_UInt128_uint128 x0, FStar_UInt128_uint128 x1);
FStar_UInt128_uint128 FStar_UInt128_mul32(uint64_t x, uint32_t y);
FStar_UInt128_uint128 FStar_UInt128_mul_wide(uint64_t x, uint64_t y);
#define __FStar_UInt128_H_DEFINED
#endif
|
0 | repos/gpt4all.zig/src/zig-libcurl/zig-mbedtls/mbedtls/3rdparty/everest/include/everest | repos/gpt4all.zig/src/zig-libcurl/zig-mbedtls/mbedtls/3rdparty/everest/include/everest/vs2010/inttypes.h | /*
* Custom inttypes.h for VS2010 KreMLin requires these definitions,
* but VS2010 doesn't provide them.
*
* Copyright 2016-2018 INRIA and Microsoft Corporation
* SPDX-License-Identifier: Apache-2.0
*
* 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.
*
* This file is part of mbed TLS (https://tls.mbed.org)
*/
#ifndef _INTTYPES_H_VS2010
#define _INTTYPES_H_VS2010
#include <stdint.h>
#ifdef _MSC_VER
#define inline __inline
#endif
/* VS2010 unsigned long == 8 bytes */
#define PRIu64 "I64u"
#endif
|
0 | repos/gpt4all.zig/src/zig-libcurl/zig-mbedtls/mbedtls/3rdparty/everest/include/everest | repos/gpt4all.zig/src/zig-libcurl/zig-mbedtls/mbedtls/3rdparty/everest/include/everest/vs2010/stdbool.h | /*
* Custom stdbool.h for VS2010 KreMLin requires these definitions,
* but VS2010 doesn't provide them.
*
* Copyright 2016-2018 INRIA and Microsoft Corporation
* SPDX-License-Identifier: Apache-2.0
*
* 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.
*
* This file is part of mbed TLS (https://tls.mbed.org)
*/
#ifndef _STDBOOL_H_VS2010
#define _STDBOOL_H_VS2010
typedef int bool;
static bool true = 1;
static bool false = 0;
#endif
|
0 | repos/gpt4all.zig/src/zig-libcurl/zig-mbedtls/mbedtls/3rdparty/everest/include/everest | repos/gpt4all.zig/src/zig-libcurl/zig-mbedtls/mbedtls/3rdparty/everest/include/everest/vs2010/Hacl_Curve25519.h | /* Copyright (c) INRIA and Microsoft Corporation. All rights reserved.
Licensed under the Apache 2.0 License. */
/* This file was generated by KreMLin <https://github.com/FStarLang/kremlin>
* KreMLin invocation: /mnt/e/everest/verify/kremlin/krml -fc89 -fparentheses -fno-shadow -header /mnt/e/everest/verify/hdrcLh -minimal -fc89 -fparentheses -fno-shadow -header /mnt/e/everest/verify/hdrcLh -minimal -I /mnt/e/everest/verify/hacl-star/code/lib/kremlin -I /mnt/e/everest/verify/kremlin/kremlib/compat -I /mnt/e/everest/verify/hacl-star/specs -I /mnt/e/everest/verify/hacl-star/specs/old -I . -ccopt -march=native -verbose -ldopt -flto -tmpdir x25519-c -I ../bignum -bundle Hacl.Curve25519=* -minimal -add-include "kremlib.h" -skip-compilation x25519-c/out.krml -o x25519-c/Hacl_Curve25519.c
* F* version: 059db0c8
* KreMLin version: 916c37ac
*/
#ifndef __Hacl_Curve25519_H
#define __Hacl_Curve25519_H
#include "kremlib.h"
void Hacl_Curve25519_crypto_scalarmult(uint8_t *mypublic, uint8_t *secret, uint8_t *basepoint);
#define __Hacl_Curve25519_H_DEFINED
#endif
|
0 | repos/gpt4all.zig/src/zig-libcurl/zig-mbedtls/mbedtls/3rdparty/everest/include/everest | repos/gpt4all.zig/src/zig-libcurl/zig-mbedtls/mbedtls/3rdparty/everest/include/everest/kremlin/c_endianness.h | /* Copyright (c) INRIA and Microsoft Corporation. All rights reserved.
Licensed under the Apache 2.0 License. */
#ifndef __KREMLIN_ENDIAN_H
#define __KREMLIN_ENDIAN_H
#include <string.h>
#include <inttypes.h>
/******************************************************************************/
/* Implementing C.fst (part 2: endian-ness macros) */
/******************************************************************************/
/* ... for Linux */
#if defined(__linux__) || defined(__CYGWIN__)
# include <endian.h>
/* ... for OSX */
#elif defined(__APPLE__)
# include <libkern/OSByteOrder.h>
# define htole64(x) OSSwapHostToLittleInt64(x)
# define le64toh(x) OSSwapLittleToHostInt64(x)
# define htobe64(x) OSSwapHostToBigInt64(x)
# define be64toh(x) OSSwapBigToHostInt64(x)
# define htole16(x) OSSwapHostToLittleInt16(x)
# define le16toh(x) OSSwapLittleToHostInt16(x)
# define htobe16(x) OSSwapHostToBigInt16(x)
# define be16toh(x) OSSwapBigToHostInt16(x)
# define htole32(x) OSSwapHostToLittleInt32(x)
# define le32toh(x) OSSwapLittleToHostInt32(x)
# define htobe32(x) OSSwapHostToBigInt32(x)
# define be32toh(x) OSSwapBigToHostInt32(x)
/* ... for Solaris */
#elif defined(__sun__)
# include <sys/byteorder.h>
# define htole64(x) LE_64(x)
# define le64toh(x) LE_64(x)
# define htobe64(x) BE_64(x)
# define be64toh(x) BE_64(x)
# define htole16(x) LE_16(x)
# define le16toh(x) LE_16(x)
# define htobe16(x) BE_16(x)
# define be16toh(x) BE_16(x)
# define htole32(x) LE_32(x)
# define le32toh(x) LE_32(x)
# define htobe32(x) BE_32(x)
# define be32toh(x) BE_32(x)
/* ... for the BSDs */
#elif defined(__FreeBSD__) || defined(__NetBSD__) || defined(__DragonFly__)
# include <sys/endian.h>
#elif defined(__OpenBSD__)
# include <endian.h>
/* ... for Windows (MSVC)... not targeting XBOX 360! */
#elif defined(_MSC_VER)
# include <stdlib.h>
# define htobe16(x) _byteswap_ushort(x)
# define htole16(x) (x)
# define be16toh(x) _byteswap_ushort(x)
# define le16toh(x) (x)
# define htobe32(x) _byteswap_ulong(x)
# define htole32(x) (x)
# define be32toh(x) _byteswap_ulong(x)
# define le32toh(x) (x)
# define htobe64(x) _byteswap_uint64(x)
# define htole64(x) (x)
# define be64toh(x) _byteswap_uint64(x)
# define le64toh(x) (x)
/* ... for Windows (GCC-like, e.g. mingw or clang) */
#elif (defined(_WIN32) || defined(_WIN64)) && \
(defined(__GNUC__) || defined(__clang__))
# define htobe16(x) __builtin_bswap16(x)
# define htole16(x) (x)
# define be16toh(x) __builtin_bswap16(x)
# define le16toh(x) (x)
# define htobe32(x) __builtin_bswap32(x)
# define htole32(x) (x)
# define be32toh(x) __builtin_bswap32(x)
# define le32toh(x) (x)
# define htobe64(x) __builtin_bswap64(x)
# define htole64(x) (x)
# define be64toh(x) __builtin_bswap64(x)
# define le64toh(x) (x)
/* ... generic big-endian fallback code */
#elif defined(__BYTE_ORDER__) && __BYTE_ORDER__ == __ORDER_BIG_ENDIAN__
/* byte swapping code inspired by:
* https://github.com/rweather/arduinolibs/blob/master/libraries/Crypto/utility/EndianUtil.h
* */
# define htobe32(x) (x)
# define be32toh(x) (x)
# define htole32(x) \
(__extension__({ \
uint32_t _temp = (x); \
((_temp >> 24) & 0x000000FF) | ((_temp >> 8) & 0x0000FF00) | \
((_temp << 8) & 0x00FF0000) | ((_temp << 24) & 0xFF000000); \
}))
# define le32toh(x) (htole32((x)))
# define htobe64(x) (x)
# define be64toh(x) (x)
# define htole64(x) \
(__extension__({ \
uint64_t __temp = (x); \
uint32_t __low = htobe32((uint32_t)__temp); \
uint32_t __high = htobe32((uint32_t)(__temp >> 32)); \
(((uint64_t)__low) << 32) | __high; \
}))
# define le64toh(x) (htole64((x)))
/* ... generic little-endian fallback code */
#elif defined(__BYTE_ORDER__) && __BYTE_ORDER__ == __ORDER_LITTLE_ENDIAN__
# define htole32(x) (x)
# define le32toh(x) (x)
# define htobe32(x) \
(__extension__({ \
uint32_t _temp = (x); \
((_temp >> 24) & 0x000000FF) | ((_temp >> 8) & 0x0000FF00) | \
((_temp << 8) & 0x00FF0000) | ((_temp << 24) & 0xFF000000); \
}))
# define be32toh(x) (htobe32((x)))
# define htole64(x) (x)
# define le64toh(x) (x)
# define htobe64(x) \
(__extension__({ \
uint64_t __temp = (x); \
uint32_t __low = htobe32((uint32_t)__temp); \
uint32_t __high = htobe32((uint32_t)(__temp >> 32)); \
(((uint64_t)__low) << 32) | __high; \
}))
# define be64toh(x) (htobe64((x)))
/* ... couldn't determine endian-ness of the target platform */
#else
# error "Please define __BYTE_ORDER__!"
#endif /* defined(__linux__) || ... */
/* Loads and stores. These avoid undefined behavior due to unaligned memory
* accesses, via memcpy. */
inline static uint16_t load16(uint8_t *b) {
uint16_t x;
memcpy(&x, b, 2);
return x;
}
inline static uint32_t load32(uint8_t *b) {
uint32_t x;
memcpy(&x, b, 4);
return x;
}
inline static uint64_t load64(uint8_t *b) {
uint64_t x;
memcpy(&x, b, 8);
return x;
}
inline static void store16(uint8_t *b, uint16_t i) {
memcpy(b, &i, 2);
}
inline static void store32(uint8_t *b, uint32_t i) {
memcpy(b, &i, 4);
}
inline static void store64(uint8_t *b, uint64_t i) {
memcpy(b, &i, 8);
}
#define load16_le(b) (le16toh(load16(b)))
#define store16_le(b, i) (store16(b, htole16(i)))
#define load16_be(b) (be16toh(load16(b)))
#define store16_be(b, i) (store16(b, htobe16(i)))
#define load32_le(b) (le32toh(load32(b)))
#define store32_le(b, i) (store32(b, htole32(i)))
#define load32_be(b) (be32toh(load32(b)))
#define store32_be(b, i) (store32(b, htobe32(i)))
#define load64_le(b) (le64toh(load64(b)))
#define store64_le(b, i) (store64(b, htole64(i)))
#define load64_be(b) (be64toh(load64(b)))
#define store64_be(b, i) (store64(b, htobe64(i)))
#endif
|
0 | repos/gpt4all.zig/src/zig-libcurl/zig-mbedtls/mbedtls/3rdparty/everest/include/everest/kremlin | repos/gpt4all.zig/src/zig-libcurl/zig-mbedtls/mbedtls/3rdparty/everest/include/everest/kremlin/internal/compat.h | /* Copyright (c) INRIA and Microsoft Corporation. All rights reserved.
Licensed under the Apache 2.0 License. */
#ifndef KRML_COMPAT_H
#define KRML_COMPAT_H
#include <inttypes.h>
/* A series of macros that define C implementations of types that are not Low*,
* to facilitate porting programs to Low*. */
typedef const char *Prims_string;
typedef struct {
uint32_t length;
const char *data;
} FStar_Bytes_bytes;
typedef int32_t Prims_pos, Prims_nat, Prims_nonzero, Prims_int,
krml_checked_int_t;
#define RETURN_OR(x) \
do { \
int64_t __ret = x; \
if (__ret < INT32_MIN || INT32_MAX < __ret) { \
KRML_HOST_PRINTF( \
"Prims.{int,nat,pos} integer overflow at %s:%d\n", __FILE__, \
__LINE__); \
KRML_HOST_EXIT(252); \
} \
return (int32_t)__ret; \
} while (0)
#endif
|
0 | repos/gpt4all.zig/src/zig-libcurl/zig-mbedtls/mbedtls/3rdparty/everest/include/everest/kremlin | repos/gpt4all.zig/src/zig-libcurl/zig-mbedtls/mbedtls/3rdparty/everest/include/everest/kremlin/internal/types.h | /* Copyright (c) INRIA and Microsoft Corporation. All rights reserved.
Licensed under the Apache 2.0 License. */
#ifndef KRML_TYPES_H
#define KRML_TYPES_H
#include <inttypes.h>
#include <stdio.h>
#include <stdlib.h>
/* Types which are either abstract, meaning that have to be implemented in C, or
* which are models, meaning that they are swapped out at compile-time for
* hand-written C types (in which case they're marked as noextract). */
typedef uint64_t FStar_UInt64_t, FStar_UInt64_t_;
typedef int64_t FStar_Int64_t, FStar_Int64_t_;
typedef uint32_t FStar_UInt32_t, FStar_UInt32_t_;
typedef int32_t FStar_Int32_t, FStar_Int32_t_;
typedef uint16_t FStar_UInt16_t, FStar_UInt16_t_;
typedef int16_t FStar_Int16_t, FStar_Int16_t_;
typedef uint8_t FStar_UInt8_t, FStar_UInt8_t_;
typedef int8_t FStar_Int8_t, FStar_Int8_t_;
/* Only useful when building Kremlib, because it's in the dependency graph of
* FStar.Int.Cast. */
typedef uint64_t FStar_UInt63_t, FStar_UInt63_t_;
typedef int64_t FStar_Int63_t, FStar_Int63_t_;
typedef double FStar_Float_float;
typedef uint32_t FStar_Char_char;
typedef FILE *FStar_IO_fd_read, *FStar_IO_fd_write;
typedef void *FStar_Dyn_dyn;
typedef const char *C_String_t, *C_String_t_;
typedef int exit_code;
typedef FILE *channel;
typedef unsigned long long TestLib_cycles;
typedef uint64_t FStar_Date_dateTime, FStar_Date_timeSpan;
/* The uint128 type is a special case since we offer several implementations of
* it, depending on the compiler and whether the user wants the verified
* implementation or not. */
#if !defined(KRML_VERIFIED_UINT128) && defined(_MSC_VER) && defined(_M_X64)
# include <emmintrin.h>
typedef __m128i FStar_UInt128_uint128;
#elif !defined(KRML_VERIFIED_UINT128) && !defined(_MSC_VER)
typedef unsigned __int128 FStar_UInt128_uint128;
#else
typedef struct FStar_UInt128_uint128_s {
uint64_t low;
uint64_t high;
} FStar_UInt128_uint128;
#endif
typedef FStar_UInt128_uint128 FStar_UInt128_t, FStar_UInt128_t_, uint128_t;
#endif
|
0 | repos/gpt4all.zig/src/zig-libcurl/zig-mbedtls/mbedtls/3rdparty/everest/include/everest/kremlin | repos/gpt4all.zig/src/zig-libcurl/zig-mbedtls/mbedtls/3rdparty/everest/include/everest/kremlin/internal/wasmsupport.h | /* Copyright (c) INRIA and Microsoft Corporation. All rights reserved.
Licensed under the Apache 2.0 License. */
/* This file is automatically included when compiling with -wasm -d force-c */
#define WasmSupport_check_buffer_size(X)
|
0 | repos/gpt4all.zig/src/zig-libcurl/zig-mbedtls/mbedtls/3rdparty/everest/include/everest/kremlin | repos/gpt4all.zig/src/zig-libcurl/zig-mbedtls/mbedtls/3rdparty/everest/include/everest/kremlin/internal/debug.h | /* Copyright (c) INRIA and Microsoft Corporation. All rights reserved.
Licensed under the Apache 2.0 License. */
#ifndef __KREMLIN_DEBUG_H
#define __KREMLIN_DEBUG_H
#include <inttypes.h>
#include "kremlin/internal/target.h"
/******************************************************************************/
/* Debugging helpers - intended only for KreMLin developers */
/******************************************************************************/
/* In support of "-wasm -d force-c": we might need this function to be
* forward-declared, because the dependency on WasmSupport appears very late,
* after SimplifyWasm, and sadly, after the topological order has been done. */
void WasmSupport_check_buffer_size(uint32_t s);
/* A series of GCC atrocities to trace function calls (kremlin's [-d c-calls]
* option). Useful when trying to debug, say, Wasm, to compare traces. */
/* clang-format off */
#ifdef __GNUC__
#define KRML_FORMAT(X) _Generic((X), \
uint8_t : "0x%08" PRIx8, \
uint16_t: "0x%08" PRIx16, \
uint32_t: "0x%08" PRIx32, \
uint64_t: "0x%08" PRIx64, \
int8_t : "0x%08" PRIx8, \
int16_t : "0x%08" PRIx16, \
int32_t : "0x%08" PRIx32, \
int64_t : "0x%08" PRIx64, \
default : "%s")
#define KRML_FORMAT_ARG(X) _Generic((X), \
uint8_t : X, \
uint16_t: X, \
uint32_t: X, \
uint64_t: X, \
int8_t : X, \
int16_t : X, \
int32_t : X, \
int64_t : X, \
default : "unknown")
/* clang-format on */
# define KRML_DEBUG_RETURN(X) \
({ \
__auto_type _ret = (X); \
KRML_HOST_PRINTF("returning: "); \
KRML_HOST_PRINTF(KRML_FORMAT(_ret), KRML_FORMAT_ARG(_ret)); \
KRML_HOST_PRINTF(" \n"); \
_ret; \
})
#endif
#endif
|
0 | repos/gpt4all.zig/src/zig-libcurl/zig-mbedtls/mbedtls/3rdparty/everest/include/everest/kremlin | repos/gpt4all.zig/src/zig-libcurl/zig-mbedtls/mbedtls/3rdparty/everest/include/everest/kremlin/internal/callconv.h | /* Copyright (c) INRIA and Microsoft Corporation. All rights reserved.
Licensed under the Apache 2.0 License. */
#ifndef __KREMLIN_CALLCONV_H
#define __KREMLIN_CALLCONV_H
/******************************************************************************/
/* Some macros to ease compatibility */
/******************************************************************************/
/* We want to generate __cdecl safely without worrying about it being undefined.
* When using MSVC, these are always defined. When using MinGW, these are
* defined too. They have no meaning for other platforms, so we define them to
* be empty macros in other situations. */
#ifndef _MSC_VER
#ifndef __cdecl
#define __cdecl
#endif
#ifndef __stdcall
#define __stdcall
#endif
#ifndef __fastcall
#define __fastcall
#endif
#endif
/* Since KreMLin emits the inline keyword unconditionally, we follow the
* guidelines at https://gcc.gnu.org/onlinedocs/gcc/Inline.html and make this
* __inline__ to ensure the code compiles with -std=c90 and earlier. */
#ifdef __GNUC__
# define inline __inline__
#endif
/* GCC-specific attribute syntax; everyone else gets the standard C inline
* attribute. */
#ifdef __GNU_C__
# ifndef __clang__
# define force_inline inline __attribute__((always_inline))
# else
# define force_inline inline
# endif
#else
# define force_inline inline
#endif
#endif
|
0 | repos/gpt4all.zig/src/zig-libcurl/zig-mbedtls/mbedtls/3rdparty/everest/include/everest/kremlin | repos/gpt4all.zig/src/zig-libcurl/zig-mbedtls/mbedtls/3rdparty/everest/include/everest/kremlin/internal/target.h | /* Copyright (c) INRIA and Microsoft Corporation. All rights reserved.
Licensed under the Apache 2.0 License. */
#ifndef __KREMLIN_TARGET_H
#define __KREMLIN_TARGET_H
#include <stdlib.h>
#include <stdio.h>
#include <stdbool.h>
#include <inttypes.h>
#include <limits.h>
#include "kremlin/internal/callconv.h"
/******************************************************************************/
/* Macros that KreMLin will generate. */
/******************************************************************************/
/* For "bare" targets that do not have a C stdlib, the user might want to use
* [-add-early-include '"mydefinitions.h"'] and override these. */
#ifndef KRML_HOST_PRINTF
# define KRML_HOST_PRINTF printf
#endif
#if ( \
(defined __STDC_VERSION__) && (__STDC_VERSION__ >= 199901L) && \
(!(defined KRML_HOST_EPRINTF)))
# define KRML_HOST_EPRINTF(...) fprintf(stderr, __VA_ARGS__)
#endif
#ifndef KRML_HOST_EXIT
# define KRML_HOST_EXIT exit
#endif
#ifndef KRML_HOST_MALLOC
# define KRML_HOST_MALLOC malloc
#endif
#ifndef KRML_HOST_CALLOC
# define KRML_HOST_CALLOC calloc
#endif
#ifndef KRML_HOST_FREE
# define KRML_HOST_FREE free
#endif
#ifndef KRML_HOST_TIME
# include <time.h>
/* Prims_nat not yet in scope */
inline static int32_t krml_time() {
return (int32_t)time(NULL);
}
# define KRML_HOST_TIME krml_time
#endif
/* In statement position, exiting is easy. */
#define KRML_EXIT \
do { \
KRML_HOST_PRINTF("Unimplemented function at %s:%d\n", __FILE__, __LINE__); \
KRML_HOST_EXIT(254); \
} while (0)
/* In expression position, use the comma-operator and a malloc to return an
* expression of the right size. KreMLin passes t as the parameter to the macro.
*/
#define KRML_EABORT(t, msg) \
(KRML_HOST_PRINTF("KreMLin abort at %s:%d\n%s\n", __FILE__, __LINE__, msg), \
KRML_HOST_EXIT(255), *((t *)KRML_HOST_MALLOC(sizeof(t))))
/* In FStar.Buffer.fst, the size of arrays is uint32_t, but it's a number of
* *elements*. Do an ugly, run-time check (some of which KreMLin can eliminate).
*/
#ifdef __GNUC__
# define _KRML_CHECK_SIZE_PRAGMA \
_Pragma("GCC diagnostic ignored \"-Wtype-limits\"")
#else
# define _KRML_CHECK_SIZE_PRAGMA
#endif
#define KRML_CHECK_SIZE(size_elt, sz) \
do { \
_KRML_CHECK_SIZE_PRAGMA \
if (((size_t)(sz)) > ((size_t)(SIZE_MAX / (size_elt)))) { \
KRML_HOST_PRINTF( \
"Maximum allocatable size exceeded, aborting before overflow at " \
"%s:%d\n", \
__FILE__, __LINE__); \
KRML_HOST_EXIT(253); \
} \
} while (0)
#if defined(_MSC_VER) && _MSC_VER < 1900
# define KRML_HOST_SNPRINTF(buf, sz, fmt, arg) _snprintf_s(buf, sz, _TRUNCATE, fmt, arg)
#else
# define KRML_HOST_SNPRINTF(buf, sz, fmt, arg) snprintf(buf, sz, fmt, arg)
#endif
#endif
|
0 | repos/gpt4all.zig/src/zig-libcurl/zig-mbedtls/mbedtls/3rdparty/everest/include/everest/kremlin | repos/gpt4all.zig/src/zig-libcurl/zig-mbedtls/mbedtls/3rdparty/everest/include/everest/kremlin/internal/builtin.h | /* Copyright (c) INRIA and Microsoft Corporation. All rights reserved.
Licensed under the Apache 2.0 License. */
#ifndef __KREMLIN_BUILTIN_H
#define __KREMLIN_BUILTIN_H
/* For alloca, when using KreMLin's -falloca */
#if (defined(_WIN32) || defined(_WIN64))
# include <malloc.h>
#endif
/* If some globals need to be initialized before the main, then kremlin will
* generate and try to link last a function with this type: */
void kremlinit_globals(void);
#endif
|
0 | repos/gpt4all.zig/src/zig-libcurl/zig-mbedtls/mbedtls/3rdparty/everest | repos/gpt4all.zig/src/zig-libcurl/zig-mbedtls/mbedtls/3rdparty/everest/library/everest.c | /*
* Interface to code from Project Everest
*
* Copyright 2016-2018 INRIA and Microsoft Corporation
* SPDX-License-Identifier: Apache-2.0
*
* 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.
*
* This file is part of Mbed TLS (https://tls.mbed.org).
*/
#include "common.h"
#include <string.h>
#include "mbedtls/ecdh.h"
#include "everest/x25519.h"
#include "everest/everest.h"
#if defined(MBEDTLS_PLATFORM_C)
#include "mbedtls/platform.h"
#else
#define mbedtls_calloc calloc
#define mbedtls_free free
#endif
#if defined(MBEDTLS_ECDH_VARIANT_EVEREST_ENABLED)
int mbedtls_everest_setup( mbedtls_ecdh_context_everest *ctx, int grp_id )
{
if( grp_id != MBEDTLS_ECP_DP_CURVE25519 )
return MBEDTLS_ERR_ECP_BAD_INPUT_DATA;
mbedtls_x25519_init( &ctx->ctx );
return 0;
}
void mbedtls_everest_free( mbedtls_ecdh_context_everest *ctx )
{
mbedtls_x25519_free( &ctx->ctx );
}
int mbedtls_everest_make_params( mbedtls_ecdh_context_everest *ctx, size_t *olen,
unsigned char *buf, size_t blen,
int( *f_rng )( void *, unsigned char *, size_t ),
void *p_rng )
{
mbedtls_x25519_context *x25519_ctx = &ctx->ctx;
return mbedtls_x25519_make_params( x25519_ctx, olen, buf, blen, f_rng, p_rng );
}
int mbedtls_everest_read_params( mbedtls_ecdh_context_everest *ctx,
const unsigned char **buf,
const unsigned char *end )
{
mbedtls_x25519_context *x25519_ctx = &ctx->ctx;
return mbedtls_x25519_read_params( x25519_ctx, buf, end );
}
int mbedtls_everest_get_params( mbedtls_ecdh_context_everest *ctx,
const mbedtls_ecp_keypair *key,
mbedtls_everest_ecdh_side side )
{
mbedtls_x25519_context *x25519_ctx = &ctx->ctx;
mbedtls_x25519_ecdh_side s = side == MBEDTLS_EVEREST_ECDH_OURS ?
MBEDTLS_X25519_ECDH_OURS :
MBEDTLS_X25519_ECDH_THEIRS;
return mbedtls_x25519_get_params( x25519_ctx, key, s );
}
int mbedtls_everest_make_public( mbedtls_ecdh_context_everest *ctx, size_t *olen,
unsigned char *buf, size_t blen,
int( *f_rng )( void *, unsigned char *, size_t ),
void *p_rng )
{
mbedtls_x25519_context *x25519_ctx = &ctx->ctx;
return mbedtls_x25519_make_public( x25519_ctx, olen, buf, blen, f_rng, p_rng );
}
int mbedtls_everest_read_public( mbedtls_ecdh_context_everest *ctx,
const unsigned char *buf, size_t blen )
{
mbedtls_x25519_context *x25519_ctx = &ctx->ctx;
return mbedtls_x25519_read_public ( x25519_ctx, buf, blen );
}
int mbedtls_everest_calc_secret( mbedtls_ecdh_context_everest *ctx, size_t *olen,
unsigned char *buf, size_t blen,
int( *f_rng )( void *, unsigned char *, size_t ),
void *p_rng )
{
mbedtls_x25519_context *x25519_ctx = &ctx->ctx;
return mbedtls_x25519_calc_secret( x25519_ctx, olen, buf, blen, f_rng, p_rng );
}
#endif /* MBEDTLS_ECDH_VARIANT_EVEREST_ENABLED */
|
0 | repos/gpt4all.zig/src/zig-libcurl/zig-mbedtls/mbedtls/3rdparty/everest | repos/gpt4all.zig/src/zig-libcurl/zig-mbedtls/mbedtls/3rdparty/everest/library/Hacl_Curve25519.c | /* Copyright (c) INRIA and Microsoft Corporation. All rights reserved.
Licensed under the Apache 2.0 License. */
/* This file was generated by KreMLin <https://github.com/FStarLang/kremlin>
* KreMLin invocation: /mnt/e/everest/verify/kremlin/krml -fc89 -fparentheses -fno-shadow -header /mnt/e/everest/verify/hdrcLh -minimal -fbuiltin-uint128 -fc89 -fparentheses -fno-shadow -header /mnt/e/everest/verify/hdrcLh -minimal -I /mnt/e/everest/verify/hacl-star/code/lib/kremlin -I /mnt/e/everest/verify/kremlin/kremlib/compat -I /mnt/e/everest/verify/hacl-star/specs -I /mnt/e/everest/verify/hacl-star/specs/old -I . -ccopt -march=native -verbose -ldopt -flto -tmpdir x25519-c -I ../bignum -bundle Hacl.Curve25519=* -minimal -add-include "kremlib.h" -skip-compilation x25519-c/out.krml -o x25519-c/Hacl_Curve25519.c
* F* version: 059db0c8
* KreMLin version: 916c37ac
*/
#include "Hacl_Curve25519.h"
extern uint64_t FStar_UInt64_eq_mask(uint64_t x0, uint64_t x1);
extern uint64_t FStar_UInt64_gte_mask(uint64_t x0, uint64_t x1);
extern uint128_t FStar_UInt128_add(uint128_t x0, uint128_t x1);
extern uint128_t FStar_UInt128_add_mod(uint128_t x0, uint128_t x1);
extern uint128_t FStar_UInt128_logand(uint128_t x0, uint128_t x1);
extern uint128_t FStar_UInt128_shift_right(uint128_t x0, uint32_t x1);
extern uint128_t FStar_UInt128_uint64_to_uint128(uint64_t x0);
extern uint64_t FStar_UInt128_uint128_to_uint64(uint128_t x0);
extern uint128_t FStar_UInt128_mul_wide(uint64_t x0, uint64_t x1);
static void Hacl_Bignum_Modulo_carry_top(uint64_t *b)
{
uint64_t b4 = b[4U];
uint64_t b0 = b[0U];
uint64_t b4_ = b4 & (uint64_t)0x7ffffffffffffU;
uint64_t b0_ = b0 + (uint64_t)19U * (b4 >> (uint32_t)51U);
b[4U] = b4_;
b[0U] = b0_;
}
inline static void Hacl_Bignum_Fproduct_copy_from_wide_(uint64_t *output, uint128_t *input)
{
uint32_t i;
for (i = (uint32_t)0U; i < (uint32_t)5U; i = i + (uint32_t)1U)
{
uint128_t xi = input[i];
output[i] = (uint64_t)xi;
}
}
inline static void
Hacl_Bignum_Fproduct_sum_scalar_multiplication_(uint128_t *output, uint64_t *input, uint64_t s)
{
uint32_t i;
for (i = (uint32_t)0U; i < (uint32_t)5U; i = i + (uint32_t)1U)
{
uint128_t xi = output[i];
uint64_t yi = input[i];
output[i] = xi + (uint128_t)yi * s;
}
}
inline static void Hacl_Bignum_Fproduct_carry_wide_(uint128_t *tmp)
{
uint32_t i;
for (i = (uint32_t)0U; i < (uint32_t)4U; i = i + (uint32_t)1U)
{
uint32_t ctr = i;
uint128_t tctr = tmp[ctr];
uint128_t tctrp1 = tmp[ctr + (uint32_t)1U];
uint64_t r0 = (uint64_t)tctr & (uint64_t)0x7ffffffffffffU;
uint128_t c = tctr >> (uint32_t)51U;
tmp[ctr] = (uint128_t)r0;
tmp[ctr + (uint32_t)1U] = tctrp1 + c;
}
}
inline static void Hacl_Bignum_Fmul_shift_reduce(uint64_t *output)
{
uint64_t tmp = output[4U];
uint64_t b0;
{
uint32_t i;
for (i = (uint32_t)0U; i < (uint32_t)4U; i = i + (uint32_t)1U)
{
uint32_t ctr = (uint32_t)5U - i - (uint32_t)1U;
uint64_t z = output[ctr - (uint32_t)1U];
output[ctr] = z;
}
}
output[0U] = tmp;
b0 = output[0U];
output[0U] = (uint64_t)19U * b0;
}
static void
Hacl_Bignum_Fmul_mul_shift_reduce_(uint128_t *output, uint64_t *input, uint64_t *input2)
{
uint32_t i;
uint64_t input2i;
{
uint32_t i0;
for (i0 = (uint32_t)0U; i0 < (uint32_t)4U; i0 = i0 + (uint32_t)1U)
{
uint64_t input2i0 = input2[i0];
Hacl_Bignum_Fproduct_sum_scalar_multiplication_(output, input, input2i0);
Hacl_Bignum_Fmul_shift_reduce(input);
}
}
i = (uint32_t)4U;
input2i = input2[i];
Hacl_Bignum_Fproduct_sum_scalar_multiplication_(output, input, input2i);
}
inline static void Hacl_Bignum_Fmul_fmul(uint64_t *output, uint64_t *input, uint64_t *input2)
{
uint64_t tmp[5U] = { 0U };
memcpy(tmp, input, (uint32_t)5U * sizeof input[0U]);
KRML_CHECK_SIZE(sizeof (uint128_t), (uint32_t)5U);
{
uint128_t t[5U];
{
uint32_t _i;
for (_i = 0U; _i < (uint32_t)5U; ++_i)
t[_i] = (uint128_t)(uint64_t)0U;
}
{
uint128_t b4;
uint128_t b0;
uint128_t b4_;
uint128_t b0_;
uint64_t i0;
uint64_t i1;
uint64_t i0_;
uint64_t i1_;
Hacl_Bignum_Fmul_mul_shift_reduce_(t, tmp, input2);
Hacl_Bignum_Fproduct_carry_wide_(t);
b4 = t[4U];
b0 = t[0U];
b4_ = b4 & (uint128_t)(uint64_t)0x7ffffffffffffU;
b0_ = b0 + (uint128_t)(uint64_t)19U * (uint64_t)(b4 >> (uint32_t)51U);
t[4U] = b4_;
t[0U] = b0_;
Hacl_Bignum_Fproduct_copy_from_wide_(output, t);
i0 = output[0U];
i1 = output[1U];
i0_ = i0 & (uint64_t)0x7ffffffffffffU;
i1_ = i1 + (i0 >> (uint32_t)51U);
output[0U] = i0_;
output[1U] = i1_;
}
}
}
inline static void Hacl_Bignum_Fsquare_fsquare__(uint128_t *tmp, uint64_t *output)
{
uint64_t r0 = output[0U];
uint64_t r1 = output[1U];
uint64_t r2 = output[2U];
uint64_t r3 = output[3U];
uint64_t r4 = output[4U];
uint64_t d0 = r0 * (uint64_t)2U;
uint64_t d1 = r1 * (uint64_t)2U;
uint64_t d2 = r2 * (uint64_t)2U * (uint64_t)19U;
uint64_t d419 = r4 * (uint64_t)19U;
uint64_t d4 = d419 * (uint64_t)2U;
uint128_t s0 = (uint128_t)r0 * r0 + (uint128_t)d4 * r1 + (uint128_t)d2 * r3;
uint128_t s1 = (uint128_t)d0 * r1 + (uint128_t)d4 * r2 + (uint128_t)(r3 * (uint64_t)19U) * r3;
uint128_t s2 = (uint128_t)d0 * r2 + (uint128_t)r1 * r1 + (uint128_t)d4 * r3;
uint128_t s3 = (uint128_t)d0 * r3 + (uint128_t)d1 * r2 + (uint128_t)r4 * d419;
uint128_t s4 = (uint128_t)d0 * r4 + (uint128_t)d1 * r3 + (uint128_t)r2 * r2;
tmp[0U] = s0;
tmp[1U] = s1;
tmp[2U] = s2;
tmp[3U] = s3;
tmp[4U] = s4;
}
inline static void Hacl_Bignum_Fsquare_fsquare_(uint128_t *tmp, uint64_t *output)
{
uint128_t b4;
uint128_t b0;
uint128_t b4_;
uint128_t b0_;
uint64_t i0;
uint64_t i1;
uint64_t i0_;
uint64_t i1_;
Hacl_Bignum_Fsquare_fsquare__(tmp, output);
Hacl_Bignum_Fproduct_carry_wide_(tmp);
b4 = tmp[4U];
b0 = tmp[0U];
b4_ = b4 & (uint128_t)(uint64_t)0x7ffffffffffffU;
b0_ = b0 + (uint128_t)(uint64_t)19U * (uint64_t)(b4 >> (uint32_t)51U);
tmp[4U] = b4_;
tmp[0U] = b0_;
Hacl_Bignum_Fproduct_copy_from_wide_(output, tmp);
i0 = output[0U];
i1 = output[1U];
i0_ = i0 & (uint64_t)0x7ffffffffffffU;
i1_ = i1 + (i0 >> (uint32_t)51U);
output[0U] = i0_;
output[1U] = i1_;
}
static void
Hacl_Bignum_Fsquare_fsquare_times_(uint64_t *input, uint128_t *tmp, uint32_t count1)
{
uint32_t i;
Hacl_Bignum_Fsquare_fsquare_(tmp, input);
for (i = (uint32_t)1U; i < count1; i = i + (uint32_t)1U)
Hacl_Bignum_Fsquare_fsquare_(tmp, input);
}
inline static void
Hacl_Bignum_Fsquare_fsquare_times(uint64_t *output, uint64_t *input, uint32_t count1)
{
KRML_CHECK_SIZE(sizeof (uint128_t), (uint32_t)5U);
{
uint128_t t[5U];
{
uint32_t _i;
for (_i = 0U; _i < (uint32_t)5U; ++_i)
t[_i] = (uint128_t)(uint64_t)0U;
}
memcpy(output, input, (uint32_t)5U * sizeof input[0U]);
Hacl_Bignum_Fsquare_fsquare_times_(output, t, count1);
}
}
inline static void Hacl_Bignum_Fsquare_fsquare_times_inplace(uint64_t *output, uint32_t count1)
{
KRML_CHECK_SIZE(sizeof (uint128_t), (uint32_t)5U);
{
uint128_t t[5U];
{
uint32_t _i;
for (_i = 0U; _i < (uint32_t)5U; ++_i)
t[_i] = (uint128_t)(uint64_t)0U;
}
Hacl_Bignum_Fsquare_fsquare_times_(output, t, count1);
}
}
inline static void Hacl_Bignum_Crecip_crecip(uint64_t *out, uint64_t *z)
{
uint64_t buf[20U] = { 0U };
uint64_t *a0 = buf;
uint64_t *t00 = buf + (uint32_t)5U;
uint64_t *b0 = buf + (uint32_t)10U;
uint64_t *t01;
uint64_t *b1;
uint64_t *c0;
uint64_t *a;
uint64_t *t0;
uint64_t *b;
uint64_t *c;
Hacl_Bignum_Fsquare_fsquare_times(a0, z, (uint32_t)1U);
Hacl_Bignum_Fsquare_fsquare_times(t00, a0, (uint32_t)2U);
Hacl_Bignum_Fmul_fmul(b0, t00, z);
Hacl_Bignum_Fmul_fmul(a0, b0, a0);
Hacl_Bignum_Fsquare_fsquare_times(t00, a0, (uint32_t)1U);
Hacl_Bignum_Fmul_fmul(b0, t00, b0);
Hacl_Bignum_Fsquare_fsquare_times(t00, b0, (uint32_t)5U);
t01 = buf + (uint32_t)5U;
b1 = buf + (uint32_t)10U;
c0 = buf + (uint32_t)15U;
Hacl_Bignum_Fmul_fmul(b1, t01, b1);
Hacl_Bignum_Fsquare_fsquare_times(t01, b1, (uint32_t)10U);
Hacl_Bignum_Fmul_fmul(c0, t01, b1);
Hacl_Bignum_Fsquare_fsquare_times(t01, c0, (uint32_t)20U);
Hacl_Bignum_Fmul_fmul(t01, t01, c0);
Hacl_Bignum_Fsquare_fsquare_times_inplace(t01, (uint32_t)10U);
Hacl_Bignum_Fmul_fmul(b1, t01, b1);
Hacl_Bignum_Fsquare_fsquare_times(t01, b1, (uint32_t)50U);
a = buf;
t0 = buf + (uint32_t)5U;
b = buf + (uint32_t)10U;
c = buf + (uint32_t)15U;
Hacl_Bignum_Fmul_fmul(c, t0, b);
Hacl_Bignum_Fsquare_fsquare_times(t0, c, (uint32_t)100U);
Hacl_Bignum_Fmul_fmul(t0, t0, c);
Hacl_Bignum_Fsquare_fsquare_times_inplace(t0, (uint32_t)50U);
Hacl_Bignum_Fmul_fmul(t0, t0, b);
Hacl_Bignum_Fsquare_fsquare_times_inplace(t0, (uint32_t)5U);
Hacl_Bignum_Fmul_fmul(out, t0, a);
}
inline static void Hacl_Bignum_fsum(uint64_t *a, uint64_t *b)
{
uint32_t i;
for (i = (uint32_t)0U; i < (uint32_t)5U; i = i + (uint32_t)1U)
{
uint64_t xi = a[i];
uint64_t yi = b[i];
a[i] = xi + yi;
}
}
inline static void Hacl_Bignum_fdifference(uint64_t *a, uint64_t *b)
{
uint64_t tmp[5U] = { 0U };
uint64_t b0;
uint64_t b1;
uint64_t b2;
uint64_t b3;
uint64_t b4;
memcpy(tmp, b, (uint32_t)5U * sizeof b[0U]);
b0 = tmp[0U];
b1 = tmp[1U];
b2 = tmp[2U];
b3 = tmp[3U];
b4 = tmp[4U];
tmp[0U] = b0 + (uint64_t)0x3fffffffffff68U;
tmp[1U] = b1 + (uint64_t)0x3ffffffffffff8U;
tmp[2U] = b2 + (uint64_t)0x3ffffffffffff8U;
tmp[3U] = b3 + (uint64_t)0x3ffffffffffff8U;
tmp[4U] = b4 + (uint64_t)0x3ffffffffffff8U;
{
uint32_t i;
for (i = (uint32_t)0U; i < (uint32_t)5U; i = i + (uint32_t)1U)
{
uint64_t xi = a[i];
uint64_t yi = tmp[i];
a[i] = yi - xi;
}
}
}
inline static void Hacl_Bignum_fscalar(uint64_t *output, uint64_t *b, uint64_t s)
{
KRML_CHECK_SIZE(sizeof (uint128_t), (uint32_t)5U);
{
uint128_t tmp[5U];
{
uint32_t _i;
for (_i = 0U; _i < (uint32_t)5U; ++_i)
tmp[_i] = (uint128_t)(uint64_t)0U;
}
{
uint128_t b4;
uint128_t b0;
uint128_t b4_;
uint128_t b0_;
{
uint32_t i;
for (i = (uint32_t)0U; i < (uint32_t)5U; i = i + (uint32_t)1U)
{
uint64_t xi = b[i];
tmp[i] = (uint128_t)xi * s;
}
}
Hacl_Bignum_Fproduct_carry_wide_(tmp);
b4 = tmp[4U];
b0 = tmp[0U];
b4_ = b4 & (uint128_t)(uint64_t)0x7ffffffffffffU;
b0_ = b0 + (uint128_t)(uint64_t)19U * (uint64_t)(b4 >> (uint32_t)51U);
tmp[4U] = b4_;
tmp[0U] = b0_;
Hacl_Bignum_Fproduct_copy_from_wide_(output, tmp);
}
}
}
inline static void Hacl_Bignum_fmul(uint64_t *output, uint64_t *a, uint64_t *b)
{
Hacl_Bignum_Fmul_fmul(output, a, b);
}
inline static void Hacl_Bignum_crecip(uint64_t *output, uint64_t *input)
{
Hacl_Bignum_Crecip_crecip(output, input);
}
static void
Hacl_EC_Point_swap_conditional_step(uint64_t *a, uint64_t *b, uint64_t swap1, uint32_t ctr)
{
uint32_t i = ctr - (uint32_t)1U;
uint64_t ai = a[i];
uint64_t bi = b[i];
uint64_t x = swap1 & (ai ^ bi);
uint64_t ai1 = ai ^ x;
uint64_t bi1 = bi ^ x;
a[i] = ai1;
b[i] = bi1;
}
static void
Hacl_EC_Point_swap_conditional_(uint64_t *a, uint64_t *b, uint64_t swap1, uint32_t ctr)
{
if (!(ctr == (uint32_t)0U))
{
uint32_t i;
Hacl_EC_Point_swap_conditional_step(a, b, swap1, ctr);
i = ctr - (uint32_t)1U;
Hacl_EC_Point_swap_conditional_(a, b, swap1, i);
}
}
static void Hacl_EC_Point_swap_conditional(uint64_t *a, uint64_t *b, uint64_t iswap)
{
uint64_t swap1 = (uint64_t)0U - iswap;
Hacl_EC_Point_swap_conditional_(a, b, swap1, (uint32_t)5U);
Hacl_EC_Point_swap_conditional_(a + (uint32_t)5U, b + (uint32_t)5U, swap1, (uint32_t)5U);
}
static void Hacl_EC_Point_copy(uint64_t *output, uint64_t *input)
{
memcpy(output, input, (uint32_t)5U * sizeof input[0U]);
memcpy(output + (uint32_t)5U,
input + (uint32_t)5U,
(uint32_t)5U * sizeof (input + (uint32_t)5U)[0U]);
}
static void Hacl_EC_Format_fexpand(uint64_t *output, uint8_t *input)
{
uint64_t i0 = load64_le(input);
uint8_t *x00 = input + (uint32_t)6U;
uint64_t i1 = load64_le(x00);
uint8_t *x01 = input + (uint32_t)12U;
uint64_t i2 = load64_le(x01);
uint8_t *x02 = input + (uint32_t)19U;
uint64_t i3 = load64_le(x02);
uint8_t *x0 = input + (uint32_t)24U;
uint64_t i4 = load64_le(x0);
uint64_t output0 = i0 & (uint64_t)0x7ffffffffffffU;
uint64_t output1 = i1 >> (uint32_t)3U & (uint64_t)0x7ffffffffffffU;
uint64_t output2 = i2 >> (uint32_t)6U & (uint64_t)0x7ffffffffffffU;
uint64_t output3 = i3 >> (uint32_t)1U & (uint64_t)0x7ffffffffffffU;
uint64_t output4 = i4 >> (uint32_t)12U & (uint64_t)0x7ffffffffffffU;
output[0U] = output0;
output[1U] = output1;
output[2U] = output2;
output[3U] = output3;
output[4U] = output4;
}
static void Hacl_EC_Format_fcontract_first_carry_pass(uint64_t *input)
{
uint64_t t0 = input[0U];
uint64_t t1 = input[1U];
uint64_t t2 = input[2U];
uint64_t t3 = input[3U];
uint64_t t4 = input[4U];
uint64_t t1_ = t1 + (t0 >> (uint32_t)51U);
uint64_t t0_ = t0 & (uint64_t)0x7ffffffffffffU;
uint64_t t2_ = t2 + (t1_ >> (uint32_t)51U);
uint64_t t1__ = t1_ & (uint64_t)0x7ffffffffffffU;
uint64_t t3_ = t3 + (t2_ >> (uint32_t)51U);
uint64_t t2__ = t2_ & (uint64_t)0x7ffffffffffffU;
uint64_t t4_ = t4 + (t3_ >> (uint32_t)51U);
uint64_t t3__ = t3_ & (uint64_t)0x7ffffffffffffU;
input[0U] = t0_;
input[1U] = t1__;
input[2U] = t2__;
input[3U] = t3__;
input[4U] = t4_;
}
static void Hacl_EC_Format_fcontract_first_carry_full(uint64_t *input)
{
Hacl_EC_Format_fcontract_first_carry_pass(input);
Hacl_Bignum_Modulo_carry_top(input);
}
static void Hacl_EC_Format_fcontract_second_carry_pass(uint64_t *input)
{
uint64_t t0 = input[0U];
uint64_t t1 = input[1U];
uint64_t t2 = input[2U];
uint64_t t3 = input[3U];
uint64_t t4 = input[4U];
uint64_t t1_ = t1 + (t0 >> (uint32_t)51U);
uint64_t t0_ = t0 & (uint64_t)0x7ffffffffffffU;
uint64_t t2_ = t2 + (t1_ >> (uint32_t)51U);
uint64_t t1__ = t1_ & (uint64_t)0x7ffffffffffffU;
uint64_t t3_ = t3 + (t2_ >> (uint32_t)51U);
uint64_t t2__ = t2_ & (uint64_t)0x7ffffffffffffU;
uint64_t t4_ = t4 + (t3_ >> (uint32_t)51U);
uint64_t t3__ = t3_ & (uint64_t)0x7ffffffffffffU;
input[0U] = t0_;
input[1U] = t1__;
input[2U] = t2__;
input[3U] = t3__;
input[4U] = t4_;
}
static void Hacl_EC_Format_fcontract_second_carry_full(uint64_t *input)
{
uint64_t i0;
uint64_t i1;
uint64_t i0_;
uint64_t i1_;
Hacl_EC_Format_fcontract_second_carry_pass(input);
Hacl_Bignum_Modulo_carry_top(input);
i0 = input[0U];
i1 = input[1U];
i0_ = i0 & (uint64_t)0x7ffffffffffffU;
i1_ = i1 + (i0 >> (uint32_t)51U);
input[0U] = i0_;
input[1U] = i1_;
}
static void Hacl_EC_Format_fcontract_trim(uint64_t *input)
{
uint64_t a0 = input[0U];
uint64_t a1 = input[1U];
uint64_t a2 = input[2U];
uint64_t a3 = input[3U];
uint64_t a4 = input[4U];
uint64_t mask0 = FStar_UInt64_gte_mask(a0, (uint64_t)0x7ffffffffffedU);
uint64_t mask1 = FStar_UInt64_eq_mask(a1, (uint64_t)0x7ffffffffffffU);
uint64_t mask2 = FStar_UInt64_eq_mask(a2, (uint64_t)0x7ffffffffffffU);
uint64_t mask3 = FStar_UInt64_eq_mask(a3, (uint64_t)0x7ffffffffffffU);
uint64_t mask4 = FStar_UInt64_eq_mask(a4, (uint64_t)0x7ffffffffffffU);
uint64_t mask = (((mask0 & mask1) & mask2) & mask3) & mask4;
uint64_t a0_ = a0 - ((uint64_t)0x7ffffffffffedU & mask);
uint64_t a1_ = a1 - ((uint64_t)0x7ffffffffffffU & mask);
uint64_t a2_ = a2 - ((uint64_t)0x7ffffffffffffU & mask);
uint64_t a3_ = a3 - ((uint64_t)0x7ffffffffffffU & mask);
uint64_t a4_ = a4 - ((uint64_t)0x7ffffffffffffU & mask);
input[0U] = a0_;
input[1U] = a1_;
input[2U] = a2_;
input[3U] = a3_;
input[4U] = a4_;
}
static void Hacl_EC_Format_fcontract_store(uint8_t *output, uint64_t *input)
{
uint64_t t0 = input[0U];
uint64_t t1 = input[1U];
uint64_t t2 = input[2U];
uint64_t t3 = input[3U];
uint64_t t4 = input[4U];
uint64_t o0 = t1 << (uint32_t)51U | t0;
uint64_t o1 = t2 << (uint32_t)38U | t1 >> (uint32_t)13U;
uint64_t o2 = t3 << (uint32_t)25U | t2 >> (uint32_t)26U;
uint64_t o3 = t4 << (uint32_t)12U | t3 >> (uint32_t)39U;
uint8_t *b0 = output;
uint8_t *b1 = output + (uint32_t)8U;
uint8_t *b2 = output + (uint32_t)16U;
uint8_t *b3 = output + (uint32_t)24U;
store64_le(b0, o0);
store64_le(b1, o1);
store64_le(b2, o2);
store64_le(b3, o3);
}
static void Hacl_EC_Format_fcontract(uint8_t *output, uint64_t *input)
{
Hacl_EC_Format_fcontract_first_carry_full(input);
Hacl_EC_Format_fcontract_second_carry_full(input);
Hacl_EC_Format_fcontract_trim(input);
Hacl_EC_Format_fcontract_store(output, input);
}
static void Hacl_EC_Format_scalar_of_point(uint8_t *scalar, uint64_t *point)
{
uint64_t *x = point;
uint64_t *z = point + (uint32_t)5U;
uint64_t buf[10U] = { 0U };
uint64_t *zmone = buf;
uint64_t *sc = buf + (uint32_t)5U;
Hacl_Bignum_crecip(zmone, z);
Hacl_Bignum_fmul(sc, x, zmone);
Hacl_EC_Format_fcontract(scalar, sc);
}
static void
Hacl_EC_AddAndDouble_fmonty(
uint64_t *pp,
uint64_t *ppq,
uint64_t *p,
uint64_t *pq,
uint64_t *qmqp
)
{
uint64_t *qx = qmqp;
uint64_t *x2 = pp;
uint64_t *z2 = pp + (uint32_t)5U;
uint64_t *x3 = ppq;
uint64_t *z3 = ppq + (uint32_t)5U;
uint64_t *x = p;
uint64_t *z = p + (uint32_t)5U;
uint64_t *xprime = pq;
uint64_t *zprime = pq + (uint32_t)5U;
uint64_t buf[40U] = { 0U };
uint64_t *origx = buf;
uint64_t *origxprime0 = buf + (uint32_t)5U;
uint64_t *xxprime0 = buf + (uint32_t)25U;
uint64_t *zzprime0 = buf + (uint32_t)30U;
uint64_t *origxprime;
uint64_t *xx0;
uint64_t *zz0;
uint64_t *xxprime;
uint64_t *zzprime;
uint64_t *zzzprime;
uint64_t *zzz;
uint64_t *xx;
uint64_t *zz;
uint64_t scalar;
memcpy(origx, x, (uint32_t)5U * sizeof x[0U]);
Hacl_Bignum_fsum(x, z);
Hacl_Bignum_fdifference(z, origx);
memcpy(origxprime0, xprime, (uint32_t)5U * sizeof xprime[0U]);
Hacl_Bignum_fsum(xprime, zprime);
Hacl_Bignum_fdifference(zprime, origxprime0);
Hacl_Bignum_fmul(xxprime0, xprime, z);
Hacl_Bignum_fmul(zzprime0, x, zprime);
origxprime = buf + (uint32_t)5U;
xx0 = buf + (uint32_t)15U;
zz0 = buf + (uint32_t)20U;
xxprime = buf + (uint32_t)25U;
zzprime = buf + (uint32_t)30U;
zzzprime = buf + (uint32_t)35U;
memcpy(origxprime, xxprime, (uint32_t)5U * sizeof xxprime[0U]);
Hacl_Bignum_fsum(xxprime, zzprime);
Hacl_Bignum_fdifference(zzprime, origxprime);
Hacl_Bignum_Fsquare_fsquare_times(x3, xxprime, (uint32_t)1U);
Hacl_Bignum_Fsquare_fsquare_times(zzzprime, zzprime, (uint32_t)1U);
Hacl_Bignum_fmul(z3, zzzprime, qx);
Hacl_Bignum_Fsquare_fsquare_times(xx0, x, (uint32_t)1U);
Hacl_Bignum_Fsquare_fsquare_times(zz0, z, (uint32_t)1U);
zzz = buf + (uint32_t)10U;
xx = buf + (uint32_t)15U;
zz = buf + (uint32_t)20U;
Hacl_Bignum_fmul(x2, xx, zz);
Hacl_Bignum_fdifference(zz, xx);
scalar = (uint64_t)121665U;
Hacl_Bignum_fscalar(zzz, zz, scalar);
Hacl_Bignum_fsum(zzz, xx);
Hacl_Bignum_fmul(z2, zzz, zz);
}
static void
Hacl_EC_Ladder_SmallLoop_cmult_small_loop_step(
uint64_t *nq,
uint64_t *nqpq,
uint64_t *nq2,
uint64_t *nqpq2,
uint64_t *q,
uint8_t byt
)
{
uint64_t bit0 = (uint64_t)(byt >> (uint32_t)7U);
uint64_t bit;
Hacl_EC_Point_swap_conditional(nq, nqpq, bit0);
Hacl_EC_AddAndDouble_fmonty(nq2, nqpq2, nq, nqpq, q);
bit = (uint64_t)(byt >> (uint32_t)7U);
Hacl_EC_Point_swap_conditional(nq2, nqpq2, bit);
}
static void
Hacl_EC_Ladder_SmallLoop_cmult_small_loop_double_step(
uint64_t *nq,
uint64_t *nqpq,
uint64_t *nq2,
uint64_t *nqpq2,
uint64_t *q,
uint8_t byt
)
{
uint8_t byt1;
Hacl_EC_Ladder_SmallLoop_cmult_small_loop_step(nq, nqpq, nq2, nqpq2, q, byt);
byt1 = byt << (uint32_t)1U;
Hacl_EC_Ladder_SmallLoop_cmult_small_loop_step(nq2, nqpq2, nq, nqpq, q, byt1);
}
static void
Hacl_EC_Ladder_SmallLoop_cmult_small_loop(
uint64_t *nq,
uint64_t *nqpq,
uint64_t *nq2,
uint64_t *nqpq2,
uint64_t *q,
uint8_t byt,
uint32_t i
)
{
if (!(i == (uint32_t)0U))
{
uint32_t i_ = i - (uint32_t)1U;
uint8_t byt_;
Hacl_EC_Ladder_SmallLoop_cmult_small_loop_double_step(nq, nqpq, nq2, nqpq2, q, byt);
byt_ = byt << (uint32_t)2U;
Hacl_EC_Ladder_SmallLoop_cmult_small_loop(nq, nqpq, nq2, nqpq2, q, byt_, i_);
}
}
static void
Hacl_EC_Ladder_BigLoop_cmult_big_loop(
uint8_t *n1,
uint64_t *nq,
uint64_t *nqpq,
uint64_t *nq2,
uint64_t *nqpq2,
uint64_t *q,
uint32_t i
)
{
if (!(i == (uint32_t)0U))
{
uint32_t i1 = i - (uint32_t)1U;
uint8_t byte = n1[i1];
Hacl_EC_Ladder_SmallLoop_cmult_small_loop(nq, nqpq, nq2, nqpq2, q, byte, (uint32_t)4U);
Hacl_EC_Ladder_BigLoop_cmult_big_loop(n1, nq, nqpq, nq2, nqpq2, q, i1);
}
}
static void Hacl_EC_Ladder_cmult(uint64_t *result, uint8_t *n1, uint64_t *q)
{
uint64_t point_buf[40U] = { 0U };
uint64_t *nq = point_buf;
uint64_t *nqpq = point_buf + (uint32_t)10U;
uint64_t *nq2 = point_buf + (uint32_t)20U;
uint64_t *nqpq2 = point_buf + (uint32_t)30U;
Hacl_EC_Point_copy(nqpq, q);
nq[0U] = (uint64_t)1U;
Hacl_EC_Ladder_BigLoop_cmult_big_loop(n1, nq, nqpq, nq2, nqpq2, q, (uint32_t)32U);
Hacl_EC_Point_copy(result, nq);
}
void Hacl_Curve25519_crypto_scalarmult(uint8_t *mypublic, uint8_t *secret, uint8_t *basepoint)
{
uint64_t buf0[10U] = { 0U };
uint64_t *x0 = buf0;
uint64_t *z = buf0 + (uint32_t)5U;
uint64_t *q;
Hacl_EC_Format_fexpand(x0, basepoint);
z[0U] = (uint64_t)1U;
q = buf0;
{
uint8_t e[32U] = { 0U };
uint8_t e0;
uint8_t e31;
uint8_t e01;
uint8_t e311;
uint8_t e312;
uint8_t *scalar;
memcpy(e, secret, (uint32_t)32U * sizeof secret[0U]);
e0 = e[0U];
e31 = e[31U];
e01 = e0 & (uint8_t)248U;
e311 = e31 & (uint8_t)127U;
e312 = e311 | (uint8_t)64U;
e[0U] = e01;
e[31U] = e312;
scalar = e;
{
uint64_t buf[15U] = { 0U };
uint64_t *nq = buf;
uint64_t *x = nq;
x[0U] = (uint64_t)1U;
Hacl_EC_Ladder_cmult(nq, scalar, q);
Hacl_EC_Format_scalar_of_point(mypublic, nq);
}
}
}
|
0 | repos/gpt4all.zig/src/zig-libcurl/zig-mbedtls/mbedtls/3rdparty/everest | repos/gpt4all.zig/src/zig-libcurl/zig-mbedtls/mbedtls/3rdparty/everest/library/Hacl_Curve25519_joined.c | /*
* Interface to code from Project Everest
*
* Copyright 2016-2018 INRIA and Microsoft Corporation
* SPDX-License-Identifier: Apache-2.0
*
* 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.
*
* This file is part of mbed TLS (https://tls.mbed.org)
*/
#include "common.h"
#if defined(MBEDTLS_ECDH_VARIANT_EVEREST_ENABLED)
#if defined(__SIZEOF_INT128__) && (__SIZEOF_INT128__ == 16)
#define MBEDTLS_HAVE_INT128
#endif
#if defined(MBEDTLS_HAVE_INT128)
#include "Hacl_Curve25519.c"
#else
#define KRML_VERIFIED_UINT128
#include "kremlib/FStar_UInt128_extracted.c"
#include "legacy/Hacl_Curve25519.c"
#endif
#include "kremlib/FStar_UInt64_FStar_UInt32_FStar_UInt16_FStar_UInt8.c"
#endif /* defined(MBEDTLS_ECDH_VARIANT_EVEREST_ENABLED) */
|
0 | repos/gpt4all.zig/src/zig-libcurl/zig-mbedtls/mbedtls/3rdparty/everest | repos/gpt4all.zig/src/zig-libcurl/zig-mbedtls/mbedtls/3rdparty/everest/library/x25519.c | /*
* ECDH with curve-optimized implementation multiplexing
*
* Copyright 2016-2018 INRIA and Microsoft Corporation
* SPDX-License-Identifier: Apache-2.0
*
* 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.
*
* This file is part of mbed TLS (https://tls.mbed.org)
*/
#include "common.h"
#if defined(MBEDTLS_ECDH_C) && defined(MBEDTLS_ECDH_VARIANT_EVEREST_ENABLED)
#include <mbedtls/ecdh.h>
#if !(defined(__SIZEOF_INT128__) && (__SIZEOF_INT128__ == 16))
#define KRML_VERIFIED_UINT128
#endif
#include <Hacl_Curve25519.h>
#include <mbedtls/platform_util.h>
#include "x25519.h"
#include <string.h>
/*
* Initialize context
*/
void mbedtls_x25519_init( mbedtls_x25519_context *ctx )
{
mbedtls_platform_zeroize( ctx, sizeof( mbedtls_x25519_context ) );
}
/*
* Free context
*/
void mbedtls_x25519_free( mbedtls_x25519_context *ctx )
{
if( ctx == NULL )
return;
mbedtls_platform_zeroize( ctx->our_secret, MBEDTLS_X25519_KEY_SIZE_BYTES );
mbedtls_platform_zeroize( ctx->peer_point, MBEDTLS_X25519_KEY_SIZE_BYTES );
}
int mbedtls_x25519_make_params( mbedtls_x25519_context *ctx, size_t *olen,
unsigned char *buf, size_t blen,
int( *f_rng )(void *, unsigned char *, size_t),
void *p_rng )
{
int ret = 0;
uint8_t base[MBEDTLS_X25519_KEY_SIZE_BYTES] = {0};
if( ( ret = f_rng( p_rng, ctx->our_secret, MBEDTLS_X25519_KEY_SIZE_BYTES ) ) != 0 )
return ret;
*olen = MBEDTLS_X25519_KEY_SIZE_BYTES + 4;
if( blen < *olen )
return( MBEDTLS_ERR_ECP_BUFFER_TOO_SMALL );
*buf++ = MBEDTLS_ECP_TLS_NAMED_CURVE;
*buf++ = MBEDTLS_ECP_TLS_CURVE25519 >> 8;
*buf++ = MBEDTLS_ECP_TLS_CURVE25519 & 0xFF;
*buf++ = MBEDTLS_X25519_KEY_SIZE_BYTES;
base[0] = 9;
Hacl_Curve25519_crypto_scalarmult( buf, ctx->our_secret, base );
base[0] = 0;
if( memcmp( buf, base, MBEDTLS_X25519_KEY_SIZE_BYTES) == 0 )
return MBEDTLS_ERR_ECP_RANDOM_FAILED;
return( 0 );
}
int mbedtls_x25519_read_params( mbedtls_x25519_context *ctx,
const unsigned char **buf, const unsigned char *end )
{
if( end - *buf < MBEDTLS_X25519_KEY_SIZE_BYTES + 1 )
return( MBEDTLS_ERR_ECP_BAD_INPUT_DATA );
if( ( *(*buf)++ != MBEDTLS_X25519_KEY_SIZE_BYTES ) )
return( MBEDTLS_ERR_ECP_BAD_INPUT_DATA );
memcpy( ctx->peer_point, *buf, MBEDTLS_X25519_KEY_SIZE_BYTES );
*buf += MBEDTLS_X25519_KEY_SIZE_BYTES;
return( 0 );
}
int mbedtls_x25519_get_params( mbedtls_x25519_context *ctx, const mbedtls_ecp_keypair *key,
mbedtls_x25519_ecdh_side side )
{
size_t olen = 0;
switch( side ) {
case MBEDTLS_X25519_ECDH_THEIRS:
return mbedtls_ecp_point_write_binary( &key->grp, &key->Q, MBEDTLS_ECP_PF_COMPRESSED, &olen, ctx->peer_point, MBEDTLS_X25519_KEY_SIZE_BYTES );
case MBEDTLS_X25519_ECDH_OURS:
return mbedtls_mpi_write_binary_le( &key->d, ctx->our_secret, MBEDTLS_X25519_KEY_SIZE_BYTES );
default:
return( MBEDTLS_ERR_ECP_BAD_INPUT_DATA );
}
}
int mbedtls_x25519_calc_secret( mbedtls_x25519_context *ctx, size_t *olen,
unsigned char *buf, size_t blen,
int( *f_rng )(void *, unsigned char *, size_t),
void *p_rng )
{
/* f_rng and p_rng are not used here because this implementation does not
need blinding since it has constant trace. */
(( void )f_rng);
(( void )p_rng);
*olen = MBEDTLS_X25519_KEY_SIZE_BYTES;
if( blen < *olen )
return( MBEDTLS_ERR_ECP_BUFFER_TOO_SMALL );
Hacl_Curve25519_crypto_scalarmult( buf, ctx->our_secret, ctx->peer_point);
/* Wipe the DH secret and don't let the peer chose a small subgroup point */
mbedtls_platform_zeroize( ctx->our_secret, MBEDTLS_X25519_KEY_SIZE_BYTES );
if( memcmp( buf, ctx->our_secret, MBEDTLS_X25519_KEY_SIZE_BYTES) == 0 )
return MBEDTLS_ERR_ECP_RANDOM_FAILED;
return( 0 );
}
int mbedtls_x25519_make_public( mbedtls_x25519_context *ctx, size_t *olen,
unsigned char *buf, size_t blen,
int( *f_rng )(void *, unsigned char *, size_t),
void *p_rng )
{
int ret = 0;
unsigned char base[MBEDTLS_X25519_KEY_SIZE_BYTES] = { 0 };
if( ctx == NULL )
return( MBEDTLS_ERR_ECP_BAD_INPUT_DATA );
if( ( ret = f_rng( p_rng, ctx->our_secret, MBEDTLS_X25519_KEY_SIZE_BYTES ) ) != 0 )
return ret;
*olen = MBEDTLS_X25519_KEY_SIZE_BYTES + 1;
if( blen < *olen )
return(MBEDTLS_ERR_ECP_BUFFER_TOO_SMALL);
*buf++ = MBEDTLS_X25519_KEY_SIZE_BYTES;
base[0] = 9;
Hacl_Curve25519_crypto_scalarmult( buf, ctx->our_secret, base );
base[0] = 0;
if( memcmp( buf, base, MBEDTLS_X25519_KEY_SIZE_BYTES ) == 0 )
return MBEDTLS_ERR_ECP_RANDOM_FAILED;
return( ret );
}
int mbedtls_x25519_read_public( mbedtls_x25519_context *ctx,
const unsigned char *buf, size_t blen )
{
if( blen < MBEDTLS_X25519_KEY_SIZE_BYTES + 1 )
return(MBEDTLS_ERR_ECP_BUFFER_TOO_SMALL);
if( (*buf++ != MBEDTLS_X25519_KEY_SIZE_BYTES) )
return(MBEDTLS_ERR_ECP_BAD_INPUT_DATA);
memcpy( ctx->peer_point, buf, MBEDTLS_X25519_KEY_SIZE_BYTES );
return( 0 );
}
#endif /* MBEDTLS_ECDH_C && MBEDTLS_ECDH_VARIANT_EVEREST_ENABLED */
|
0 | repos/gpt4all.zig/src/zig-libcurl/zig-mbedtls/mbedtls/3rdparty/everest/library | repos/gpt4all.zig/src/zig-libcurl/zig-mbedtls/mbedtls/3rdparty/everest/library/kremlib/FStar_UInt128_extracted.c | /* Copyright (c) INRIA and Microsoft Corporation. All rights reserved.
Licensed under the Apache 2.0 License. */
/* This file was generated by KreMLin <https://github.com/FStarLang/kremlin>
* KreMLin invocation: ../krml -fc89 -fparentheses -fno-shadow -header /mnt/e/everest/verify/hdrB9w -minimal -fparentheses -fcurly-braces -fno-shadow -header copyright-header.txt -minimal -tmpdir extracted -warn-error +9+11 -skip-compilation -extract-uints -add-include <inttypes.h> -add-include "kremlib.h" -add-include "kremlin/internal/compat.h" extracted/prims.krml extracted/FStar_Pervasives_Native.krml extracted/FStar_Pervasives.krml extracted/FStar_Mul.krml extracted/FStar_Squash.krml extracted/FStar_Classical.krml extracted/FStar_StrongExcludedMiddle.krml extracted/FStar_FunctionalExtensionality.krml extracted/FStar_List_Tot_Base.krml extracted/FStar_List_Tot_Properties.krml extracted/FStar_List_Tot.krml extracted/FStar_Seq_Base.krml extracted/FStar_Seq_Properties.krml extracted/FStar_Seq.krml extracted/FStar_Math_Lib.krml extracted/FStar_Math_Lemmas.krml extracted/FStar_BitVector.krml extracted/FStar_UInt.krml extracted/FStar_UInt32.krml extracted/FStar_Int.krml extracted/FStar_Int16.krml extracted/FStar_Preorder.krml extracted/FStar_Ghost.krml extracted/FStar_ErasedLogic.krml extracted/FStar_UInt64.krml extracted/FStar_Set.krml extracted/FStar_PropositionalExtensionality.krml extracted/FStar_PredicateExtensionality.krml extracted/FStar_TSet.krml extracted/FStar_Monotonic_Heap.krml extracted/FStar_Heap.krml extracted/FStar_Map.krml extracted/FStar_Monotonic_HyperHeap.krml extracted/FStar_Monotonic_HyperStack.krml extracted/FStar_HyperStack.krml extracted/FStar_Monotonic_Witnessed.krml extracted/FStar_HyperStack_ST.krml extracted/FStar_HyperStack_All.krml extracted/FStar_Date.krml extracted/FStar_Universe.krml extracted/FStar_GSet.krml extracted/FStar_ModifiesGen.krml extracted/LowStar_Monotonic_Buffer.krml extracted/LowStar_Buffer.krml extracted/Spec_Loops.krml extracted/LowStar_BufferOps.krml extracted/C_Loops.krml extracted/FStar_UInt8.krml extracted/FStar_Kremlin_Endianness.krml extracted/FStar_UInt63.krml extracted/FStar_Exn.krml extracted/FStar_ST.krml extracted/FStar_All.krml extracted/FStar_Dyn.krml extracted/FStar_Int63.krml extracted/FStar_Int64.krml extracted/FStar_Int32.krml extracted/FStar_Int8.krml extracted/FStar_UInt16.krml extracted/FStar_Int_Cast.krml extracted/FStar_UInt128.krml extracted/C_Endianness.krml extracted/FStar_List.krml extracted/FStar_Float.krml extracted/FStar_IO.krml extracted/C.krml extracted/FStar_Char.krml extracted/FStar_String.krml extracted/LowStar_Modifies.krml extracted/C_String.krml extracted/FStar_Bytes.krml extracted/FStar_HyperStack_IO.krml extracted/C_Failure.krml extracted/TestLib.krml extracted/FStar_Int_Cast_Full.krml
* F* version: 059db0c8
* KreMLin version: 916c37ac
*/
#include "FStar_UInt128.h"
#include "kremlin/c_endianness.h"
#include "FStar_UInt64_FStar_UInt32_FStar_UInt16_FStar_UInt8.h"
uint64_t FStar_UInt128___proj__Mkuint128__item__low(FStar_UInt128_uint128 projectee)
{
return projectee.low;
}
uint64_t FStar_UInt128___proj__Mkuint128__item__high(FStar_UInt128_uint128 projectee)
{
return projectee.high;
}
static uint64_t FStar_UInt128_constant_time_carry(uint64_t a, uint64_t b)
{
return (a ^ ((a ^ b) | ((a - b) ^ b))) >> (uint32_t)63U;
}
static uint64_t FStar_UInt128_carry(uint64_t a, uint64_t b)
{
return FStar_UInt128_constant_time_carry(a, b);
}
FStar_UInt128_uint128 FStar_UInt128_add(FStar_UInt128_uint128 a, FStar_UInt128_uint128 b)
{
FStar_UInt128_uint128
flat = { a.low + b.low, a.high + b.high + FStar_UInt128_carry(a.low + b.low, b.low) };
return flat;
}
FStar_UInt128_uint128
FStar_UInt128_add_underspec(FStar_UInt128_uint128 a, FStar_UInt128_uint128 b)
{
FStar_UInt128_uint128
flat = { a.low + b.low, a.high + b.high + FStar_UInt128_carry(a.low + b.low, b.low) };
return flat;
}
FStar_UInt128_uint128 FStar_UInt128_add_mod(FStar_UInt128_uint128 a, FStar_UInt128_uint128 b)
{
FStar_UInt128_uint128
flat = { a.low + b.low, a.high + b.high + FStar_UInt128_carry(a.low + b.low, b.low) };
return flat;
}
FStar_UInt128_uint128 FStar_UInt128_sub(FStar_UInt128_uint128 a, FStar_UInt128_uint128 b)
{
FStar_UInt128_uint128
flat = { a.low - b.low, a.high - b.high - FStar_UInt128_carry(a.low, a.low - b.low) };
return flat;
}
FStar_UInt128_uint128
FStar_UInt128_sub_underspec(FStar_UInt128_uint128 a, FStar_UInt128_uint128 b)
{
FStar_UInt128_uint128
flat = { a.low - b.low, a.high - b.high - FStar_UInt128_carry(a.low, a.low - b.low) };
return flat;
}
static FStar_UInt128_uint128
FStar_UInt128_sub_mod_impl(FStar_UInt128_uint128 a, FStar_UInt128_uint128 b)
{
FStar_UInt128_uint128
flat = { a.low - b.low, a.high - b.high - FStar_UInt128_carry(a.low, a.low - b.low) };
return flat;
}
FStar_UInt128_uint128 FStar_UInt128_sub_mod(FStar_UInt128_uint128 a, FStar_UInt128_uint128 b)
{
return FStar_UInt128_sub_mod_impl(a, b);
}
FStar_UInt128_uint128 FStar_UInt128_logand(FStar_UInt128_uint128 a, FStar_UInt128_uint128 b)
{
FStar_UInt128_uint128 flat = { a.low & b.low, a.high & b.high };
return flat;
}
FStar_UInt128_uint128 FStar_UInt128_logxor(FStar_UInt128_uint128 a, FStar_UInt128_uint128 b)
{
FStar_UInt128_uint128 flat = { a.low ^ b.low, a.high ^ b.high };
return flat;
}
FStar_UInt128_uint128 FStar_UInt128_logor(FStar_UInt128_uint128 a, FStar_UInt128_uint128 b)
{
FStar_UInt128_uint128 flat = { a.low | b.low, a.high | b.high };
return flat;
}
FStar_UInt128_uint128 FStar_UInt128_lognot(FStar_UInt128_uint128 a)
{
FStar_UInt128_uint128 flat = { ~a.low, ~a.high };
return flat;
}
static uint32_t FStar_UInt128_u32_64 = (uint32_t)64U;
static uint64_t FStar_UInt128_add_u64_shift_left(uint64_t hi, uint64_t lo, uint32_t s)
{
return (hi << s) + (lo >> (FStar_UInt128_u32_64 - s));
}
static uint64_t FStar_UInt128_add_u64_shift_left_respec(uint64_t hi, uint64_t lo, uint32_t s)
{
return FStar_UInt128_add_u64_shift_left(hi, lo, s);
}
static FStar_UInt128_uint128
FStar_UInt128_shift_left_small(FStar_UInt128_uint128 a, uint32_t s)
{
if (s == (uint32_t)0U)
{
return a;
}
else
{
FStar_UInt128_uint128
flat = { a.low << s, FStar_UInt128_add_u64_shift_left_respec(a.high, a.low, s) };
return flat;
}
}
static FStar_UInt128_uint128
FStar_UInt128_shift_left_large(FStar_UInt128_uint128 a, uint32_t s)
{
FStar_UInt128_uint128 flat = { (uint64_t)0U, a.low << (s - FStar_UInt128_u32_64) };
return flat;
}
FStar_UInt128_uint128 FStar_UInt128_shift_left(FStar_UInt128_uint128 a, uint32_t s)
{
if (s < FStar_UInt128_u32_64)
{
return FStar_UInt128_shift_left_small(a, s);
}
else
{
return FStar_UInt128_shift_left_large(a, s);
}
}
static uint64_t FStar_UInt128_add_u64_shift_right(uint64_t hi, uint64_t lo, uint32_t s)
{
return (lo >> s) + (hi << (FStar_UInt128_u32_64 - s));
}
static uint64_t FStar_UInt128_add_u64_shift_right_respec(uint64_t hi, uint64_t lo, uint32_t s)
{
return FStar_UInt128_add_u64_shift_right(hi, lo, s);
}
static FStar_UInt128_uint128
FStar_UInt128_shift_right_small(FStar_UInt128_uint128 a, uint32_t s)
{
if (s == (uint32_t)0U)
{
return a;
}
else
{
FStar_UInt128_uint128
flat = { FStar_UInt128_add_u64_shift_right_respec(a.high, a.low, s), a.high >> s };
return flat;
}
}
static FStar_UInt128_uint128
FStar_UInt128_shift_right_large(FStar_UInt128_uint128 a, uint32_t s)
{
FStar_UInt128_uint128 flat = { a.high >> (s - FStar_UInt128_u32_64), (uint64_t)0U };
return flat;
}
FStar_UInt128_uint128 FStar_UInt128_shift_right(FStar_UInt128_uint128 a, uint32_t s)
{
if (s < FStar_UInt128_u32_64)
{
return FStar_UInt128_shift_right_small(a, s);
}
else
{
return FStar_UInt128_shift_right_large(a, s);
}
}
bool FStar_UInt128_eq(FStar_UInt128_uint128 a, FStar_UInt128_uint128 b)
{
return a.low == b.low && a.high == b.high;
}
bool FStar_UInt128_gt(FStar_UInt128_uint128 a, FStar_UInt128_uint128 b)
{
return a.high > b.high || (a.high == b.high && a.low > b.low);
}
bool FStar_UInt128_lt(FStar_UInt128_uint128 a, FStar_UInt128_uint128 b)
{
return a.high < b.high || (a.high == b.high && a.low < b.low);
}
bool FStar_UInt128_gte(FStar_UInt128_uint128 a, FStar_UInt128_uint128 b)
{
return a.high > b.high || (a.high == b.high && a.low >= b.low);
}
bool FStar_UInt128_lte(FStar_UInt128_uint128 a, FStar_UInt128_uint128 b)
{
return a.high < b.high || (a.high == b.high && a.low <= b.low);
}
FStar_UInt128_uint128 FStar_UInt128_eq_mask(FStar_UInt128_uint128 a, FStar_UInt128_uint128 b)
{
FStar_UInt128_uint128
flat =
{
FStar_UInt64_eq_mask(a.low,
b.low)
& FStar_UInt64_eq_mask(a.high, b.high),
FStar_UInt64_eq_mask(a.low,
b.low)
& FStar_UInt64_eq_mask(a.high, b.high)
};
return flat;
}
FStar_UInt128_uint128 FStar_UInt128_gte_mask(FStar_UInt128_uint128 a, FStar_UInt128_uint128 b)
{
FStar_UInt128_uint128
flat =
{
(FStar_UInt64_gte_mask(a.high, b.high) & ~FStar_UInt64_eq_mask(a.high, b.high))
| (FStar_UInt64_eq_mask(a.high, b.high) & FStar_UInt64_gte_mask(a.low, b.low)),
(FStar_UInt64_gte_mask(a.high, b.high) & ~FStar_UInt64_eq_mask(a.high, b.high))
| (FStar_UInt64_eq_mask(a.high, b.high) & FStar_UInt64_gte_mask(a.low, b.low))
};
return flat;
}
FStar_UInt128_uint128 FStar_UInt128_uint64_to_uint128(uint64_t a)
{
FStar_UInt128_uint128 flat = { a, (uint64_t)0U };
return flat;
}
uint64_t FStar_UInt128_uint128_to_uint64(FStar_UInt128_uint128 a)
{
return a.low;
}
FStar_UInt128_uint128
(*FStar_UInt128_op_Plus_Hat)(FStar_UInt128_uint128 x0, FStar_UInt128_uint128 x1) =
FStar_UInt128_add;
FStar_UInt128_uint128
(*FStar_UInt128_op_Plus_Question_Hat)(FStar_UInt128_uint128 x0, FStar_UInt128_uint128 x1) =
FStar_UInt128_add_underspec;
FStar_UInt128_uint128
(*FStar_UInt128_op_Plus_Percent_Hat)(FStar_UInt128_uint128 x0, FStar_UInt128_uint128 x1) =
FStar_UInt128_add_mod;
FStar_UInt128_uint128
(*FStar_UInt128_op_Subtraction_Hat)(FStar_UInt128_uint128 x0, FStar_UInt128_uint128 x1) =
FStar_UInt128_sub;
FStar_UInt128_uint128
(*FStar_UInt128_op_Subtraction_Question_Hat)(
FStar_UInt128_uint128 x0,
FStar_UInt128_uint128 x1
) = FStar_UInt128_sub_underspec;
FStar_UInt128_uint128
(*FStar_UInt128_op_Subtraction_Percent_Hat)(FStar_UInt128_uint128 x0, FStar_UInt128_uint128 x1) =
FStar_UInt128_sub_mod;
FStar_UInt128_uint128
(*FStar_UInt128_op_Amp_Hat)(FStar_UInt128_uint128 x0, FStar_UInt128_uint128 x1) =
FStar_UInt128_logand;
FStar_UInt128_uint128
(*FStar_UInt128_op_Hat_Hat)(FStar_UInt128_uint128 x0, FStar_UInt128_uint128 x1) =
FStar_UInt128_logxor;
FStar_UInt128_uint128
(*FStar_UInt128_op_Bar_Hat)(FStar_UInt128_uint128 x0, FStar_UInt128_uint128 x1) =
FStar_UInt128_logor;
FStar_UInt128_uint128
(*FStar_UInt128_op_Less_Less_Hat)(FStar_UInt128_uint128 x0, uint32_t x1) =
FStar_UInt128_shift_left;
FStar_UInt128_uint128
(*FStar_UInt128_op_Greater_Greater_Hat)(FStar_UInt128_uint128 x0, uint32_t x1) =
FStar_UInt128_shift_right;
bool
(*FStar_UInt128_op_Equals_Hat)(FStar_UInt128_uint128 x0, FStar_UInt128_uint128 x1) =
FStar_UInt128_eq;
bool
(*FStar_UInt128_op_Greater_Hat)(FStar_UInt128_uint128 x0, FStar_UInt128_uint128 x1) =
FStar_UInt128_gt;
bool
(*FStar_UInt128_op_Less_Hat)(FStar_UInt128_uint128 x0, FStar_UInt128_uint128 x1) =
FStar_UInt128_lt;
bool
(*FStar_UInt128_op_Greater_Equals_Hat)(FStar_UInt128_uint128 x0, FStar_UInt128_uint128 x1) =
FStar_UInt128_gte;
bool
(*FStar_UInt128_op_Less_Equals_Hat)(FStar_UInt128_uint128 x0, FStar_UInt128_uint128 x1) =
FStar_UInt128_lte;
static uint64_t FStar_UInt128_u64_mod_32(uint64_t a)
{
return a & (uint64_t)0xffffffffU;
}
static uint32_t FStar_UInt128_u32_32 = (uint32_t)32U;
static uint64_t FStar_UInt128_u32_combine(uint64_t hi, uint64_t lo)
{
return lo + (hi << FStar_UInt128_u32_32);
}
FStar_UInt128_uint128 FStar_UInt128_mul32(uint64_t x, uint32_t y)
{
FStar_UInt128_uint128
flat =
{
FStar_UInt128_u32_combine((x >> FStar_UInt128_u32_32)
* (uint64_t)y
+ (FStar_UInt128_u64_mod_32(x) * (uint64_t)y >> FStar_UInt128_u32_32),
FStar_UInt128_u64_mod_32(FStar_UInt128_u64_mod_32(x) * (uint64_t)y)),
((x >> FStar_UInt128_u32_32)
* (uint64_t)y
+ (FStar_UInt128_u64_mod_32(x) * (uint64_t)y >> FStar_UInt128_u32_32))
>> FStar_UInt128_u32_32
};
return flat;
}
typedef struct K___uint64_t_uint64_t_uint64_t_uint64_t_s
{
uint64_t fst;
uint64_t snd;
uint64_t thd;
uint64_t f3;
}
K___uint64_t_uint64_t_uint64_t_uint64_t;
static K___uint64_t_uint64_t_uint64_t_uint64_t
FStar_UInt128_mul_wide_impl_t_(uint64_t x, uint64_t y)
{
K___uint64_t_uint64_t_uint64_t_uint64_t
flat =
{
FStar_UInt128_u64_mod_32(x),
FStar_UInt128_u64_mod_32(FStar_UInt128_u64_mod_32(x) * FStar_UInt128_u64_mod_32(y)),
x
>> FStar_UInt128_u32_32,
(x >> FStar_UInt128_u32_32)
* FStar_UInt128_u64_mod_32(y)
+ (FStar_UInt128_u64_mod_32(x) * FStar_UInt128_u64_mod_32(y) >> FStar_UInt128_u32_32)
};
return flat;
}
static uint64_t FStar_UInt128_u32_combine_(uint64_t hi, uint64_t lo)
{
return lo + (hi << FStar_UInt128_u32_32);
}
static FStar_UInt128_uint128 FStar_UInt128_mul_wide_impl(uint64_t x, uint64_t y)
{
K___uint64_t_uint64_t_uint64_t_uint64_t scrut = FStar_UInt128_mul_wide_impl_t_(x, y);
uint64_t u1 = scrut.fst;
uint64_t w3 = scrut.snd;
uint64_t x_ = scrut.thd;
uint64_t t_ = scrut.f3;
FStar_UInt128_uint128
flat =
{
FStar_UInt128_u32_combine_(u1 * (y >> FStar_UInt128_u32_32) + FStar_UInt128_u64_mod_32(t_),
w3),
x_
* (y >> FStar_UInt128_u32_32)
+ (t_ >> FStar_UInt128_u32_32)
+ ((u1 * (y >> FStar_UInt128_u32_32) + FStar_UInt128_u64_mod_32(t_)) >> FStar_UInt128_u32_32)
};
return flat;
}
FStar_UInt128_uint128 FStar_UInt128_mul_wide(uint64_t x, uint64_t y)
{
return FStar_UInt128_mul_wide_impl(x, y);
}
|
0 | repos/gpt4all.zig/src/zig-libcurl/zig-mbedtls/mbedtls/3rdparty/everest/library | repos/gpt4all.zig/src/zig-libcurl/zig-mbedtls/mbedtls/3rdparty/everest/library/kremlib/FStar_UInt64_FStar_UInt32_FStar_UInt16_FStar_UInt8.c | /* Copyright (c) INRIA and Microsoft Corporation. All rights reserved.
Licensed under the Apache 2.0 License. */
/* This file was generated by KreMLin <https://github.com/FStarLang/kremlin>
* KreMLin invocation: ../krml -fc89 -fparentheses -fno-shadow -header /mnt/e/everest/verify/hdrB9w -minimal -fparentheses -fcurly-braces -fno-shadow -header copyright-header.txt -minimal -tmpdir dist/minimal -skip-compilation -extract-uints -add-include <inttypes.h> -add-include <stdbool.h> -add-include "kremlin/internal/compat.h" -add-include "kremlin/internal/types.h" -bundle FStar.UInt64+FStar.UInt32+FStar.UInt16+FStar.UInt8=* extracted/prims.krml extracted/FStar_Pervasives_Native.krml extracted/FStar_Pervasives.krml extracted/FStar_Mul.krml extracted/FStar_Squash.krml extracted/FStar_Classical.krml extracted/FStar_StrongExcludedMiddle.krml extracted/FStar_FunctionalExtensionality.krml extracted/FStar_List_Tot_Base.krml extracted/FStar_List_Tot_Properties.krml extracted/FStar_List_Tot.krml extracted/FStar_Seq_Base.krml extracted/FStar_Seq_Properties.krml extracted/FStar_Seq.krml extracted/FStar_Math_Lib.krml extracted/FStar_Math_Lemmas.krml extracted/FStar_BitVector.krml extracted/FStar_UInt.krml extracted/FStar_UInt32.krml extracted/FStar_Int.krml extracted/FStar_Int16.krml extracted/FStar_Preorder.krml extracted/FStar_Ghost.krml extracted/FStar_ErasedLogic.krml extracted/FStar_UInt64.krml extracted/FStar_Set.krml extracted/FStar_PropositionalExtensionality.krml extracted/FStar_PredicateExtensionality.krml extracted/FStar_TSet.krml extracted/FStar_Monotonic_Heap.krml extracted/FStar_Heap.krml extracted/FStar_Map.krml extracted/FStar_Monotonic_HyperHeap.krml extracted/FStar_Monotonic_HyperStack.krml extracted/FStar_HyperStack.krml extracted/FStar_Monotonic_Witnessed.krml extracted/FStar_HyperStack_ST.krml extracted/FStar_HyperStack_All.krml extracted/FStar_Date.krml extracted/FStar_Universe.krml extracted/FStar_GSet.krml extracted/FStar_ModifiesGen.krml extracted/LowStar_Monotonic_Buffer.krml extracted/LowStar_Buffer.krml extracted/Spec_Loops.krml extracted/LowStar_BufferOps.krml extracted/C_Loops.krml extracted/FStar_UInt8.krml extracted/FStar_Kremlin_Endianness.krml extracted/FStar_UInt63.krml extracted/FStar_Exn.krml extracted/FStar_ST.krml extracted/FStar_All.krml extracted/FStar_Dyn.krml extracted/FStar_Int63.krml extracted/FStar_Int64.krml extracted/FStar_Int32.krml extracted/FStar_Int8.krml extracted/FStar_UInt16.krml extracted/FStar_Int_Cast.krml extracted/FStar_UInt128.krml extracted/C_Endianness.krml extracted/FStar_List.krml extracted/FStar_Float.krml extracted/FStar_IO.krml extracted/C.krml extracted/FStar_Char.krml extracted/FStar_String.krml extracted/LowStar_Modifies.krml extracted/C_String.krml extracted/FStar_Bytes.krml extracted/FStar_HyperStack_IO.krml extracted/C_Failure.krml extracted/TestLib.krml extracted/FStar_Int_Cast_Full.krml
* F* version: 059db0c8
* KreMLin version: 916c37ac
*/
#include "FStar_UInt64_FStar_UInt32_FStar_UInt16_FStar_UInt8.h"
uint64_t FStar_UInt64_eq_mask(uint64_t a, uint64_t b)
{
uint64_t x = a ^ b;
uint64_t minus_x = ~x + (uint64_t)1U;
uint64_t x_or_minus_x = x | minus_x;
uint64_t xnx = x_or_minus_x >> (uint32_t)63U;
return xnx - (uint64_t)1U;
}
uint64_t FStar_UInt64_gte_mask(uint64_t a, uint64_t b)
{
uint64_t x = a;
uint64_t y = b;
uint64_t x_xor_y = x ^ y;
uint64_t x_sub_y = x - y;
uint64_t x_sub_y_xor_y = x_sub_y ^ y;
uint64_t q = x_xor_y | x_sub_y_xor_y;
uint64_t x_xor_q = x ^ q;
uint64_t x_xor_q_ = x_xor_q >> (uint32_t)63U;
return x_xor_q_ - (uint64_t)1U;
}
uint32_t FStar_UInt32_eq_mask(uint32_t a, uint32_t b)
{
uint32_t x = a ^ b;
uint32_t minus_x = ~x + (uint32_t)1U;
uint32_t x_or_minus_x = x | minus_x;
uint32_t xnx = x_or_minus_x >> (uint32_t)31U;
return xnx - (uint32_t)1U;
}
uint32_t FStar_UInt32_gte_mask(uint32_t a, uint32_t b)
{
uint32_t x = a;
uint32_t y = b;
uint32_t x_xor_y = x ^ y;
uint32_t x_sub_y = x - y;
uint32_t x_sub_y_xor_y = x_sub_y ^ y;
uint32_t q = x_xor_y | x_sub_y_xor_y;
uint32_t x_xor_q = x ^ q;
uint32_t x_xor_q_ = x_xor_q >> (uint32_t)31U;
return x_xor_q_ - (uint32_t)1U;
}
uint16_t FStar_UInt16_eq_mask(uint16_t a, uint16_t b)
{
uint16_t x = a ^ b;
uint16_t minus_x = ~x + (uint16_t)1U;
uint16_t x_or_minus_x = x | minus_x;
uint16_t xnx = x_or_minus_x >> (uint32_t)15U;
return xnx - (uint16_t)1U;
}
uint16_t FStar_UInt16_gte_mask(uint16_t a, uint16_t b)
{
uint16_t x = a;
uint16_t y = b;
uint16_t x_xor_y = x ^ y;
uint16_t x_sub_y = x - y;
uint16_t x_sub_y_xor_y = x_sub_y ^ y;
uint16_t q = x_xor_y | x_sub_y_xor_y;
uint16_t x_xor_q = x ^ q;
uint16_t x_xor_q_ = x_xor_q >> (uint32_t)15U;
return x_xor_q_ - (uint16_t)1U;
}
uint8_t FStar_UInt8_eq_mask(uint8_t a, uint8_t b)
{
uint8_t x = a ^ b;
uint8_t minus_x = ~x + (uint8_t)1U;
uint8_t x_or_minus_x = x | minus_x;
uint8_t xnx = x_or_minus_x >> (uint32_t)7U;
return xnx - (uint8_t)1U;
}
uint8_t FStar_UInt8_gte_mask(uint8_t a, uint8_t b)
{
uint8_t x = a;
uint8_t y = b;
uint8_t x_xor_y = x ^ y;
uint8_t x_sub_y = x - y;
uint8_t x_sub_y_xor_y = x_sub_y ^ y;
uint8_t q = x_xor_y | x_sub_y_xor_y;
uint8_t x_xor_q = x ^ q;
uint8_t x_xor_q_ = x_xor_q >> (uint32_t)7U;
return x_xor_q_ - (uint8_t)1U;
}
|
0 | repos/gpt4all.zig/src/zig-libcurl/zig-mbedtls/mbedtls/3rdparty/everest/library | repos/gpt4all.zig/src/zig-libcurl/zig-mbedtls/mbedtls/3rdparty/everest/library/legacy/Hacl_Curve25519.c | /* Copyright (c) INRIA and Microsoft Corporation. All rights reserved.
Licensed under the Apache 2.0 License. */
/* This file was generated by KreMLin <https://github.com/FStarLang/kremlin>
* KreMLin invocation: /mnt/e/everest/verify/kremlin/krml -fc89 -fparentheses -fno-shadow -header /mnt/e/everest/verify/hdrcLh -minimal -fc89 -fparentheses -fno-shadow -header /mnt/e/everest/verify/hdrcLh -minimal -I /mnt/e/everest/verify/hacl-star/code/lib/kremlin -I /mnt/e/everest/verify/kremlin/kremlib/compat -I /mnt/e/everest/verify/hacl-star/specs -I /mnt/e/everest/verify/hacl-star/specs/old -I . -ccopt -march=native -verbose -ldopt -flto -tmpdir x25519-c -I ../bignum -bundle Hacl.Curve25519=* -minimal -add-include "kremlib.h" -skip-compilation x25519-c/out.krml -o x25519-c/Hacl_Curve25519.c
* F* version: 059db0c8
* KreMLin version: 916c37ac
*/
#include "Hacl_Curve25519.h"
extern uint64_t FStar_UInt64_eq_mask(uint64_t x0, uint64_t x1);
extern uint64_t FStar_UInt64_gte_mask(uint64_t x0, uint64_t x1);
extern FStar_UInt128_uint128
FStar_UInt128_add(FStar_UInt128_uint128 x0, FStar_UInt128_uint128 x1);
extern FStar_UInt128_uint128
FStar_UInt128_add_mod(FStar_UInt128_uint128 x0, FStar_UInt128_uint128 x1);
extern FStar_UInt128_uint128
FStar_UInt128_logand(FStar_UInt128_uint128 x0, FStar_UInt128_uint128 x1);
extern FStar_UInt128_uint128 FStar_UInt128_shift_right(FStar_UInt128_uint128 x0, uint32_t x1);
extern FStar_UInt128_uint128 FStar_UInt128_uint64_to_uint128(uint64_t x0);
extern uint64_t FStar_UInt128_uint128_to_uint64(FStar_UInt128_uint128 x0);
extern FStar_UInt128_uint128 FStar_UInt128_mul_wide(uint64_t x0, uint64_t x1);
static void Hacl_Bignum_Modulo_carry_top(uint64_t *b)
{
uint64_t b4 = b[4U];
uint64_t b0 = b[0U];
uint64_t b4_ = b4 & (uint64_t)0x7ffffffffffffU;
uint64_t b0_ = b0 + (uint64_t)19U * (b4 >> (uint32_t)51U);
b[4U] = b4_;
b[0U] = b0_;
}
inline static void
Hacl_Bignum_Fproduct_copy_from_wide_(uint64_t *output, FStar_UInt128_uint128 *input)
{
uint32_t i;
for (i = (uint32_t)0U; i < (uint32_t)5U; i = i + (uint32_t)1U)
{
FStar_UInt128_uint128 xi = input[i];
output[i] = FStar_UInt128_uint128_to_uint64(xi);
}
}
inline static void
Hacl_Bignum_Fproduct_sum_scalar_multiplication_(
FStar_UInt128_uint128 *output,
uint64_t *input,
uint64_t s
)
{
uint32_t i;
for (i = (uint32_t)0U; i < (uint32_t)5U; i = i + (uint32_t)1U)
{
FStar_UInt128_uint128 xi = output[i];
uint64_t yi = input[i];
output[i] = FStar_UInt128_add_mod(xi, FStar_UInt128_mul_wide(yi, s));
}
}
inline static void Hacl_Bignum_Fproduct_carry_wide_(FStar_UInt128_uint128 *tmp)
{
uint32_t i;
for (i = (uint32_t)0U; i < (uint32_t)4U; i = i + (uint32_t)1U)
{
uint32_t ctr = i;
FStar_UInt128_uint128 tctr = tmp[ctr];
FStar_UInt128_uint128 tctrp1 = tmp[ctr + (uint32_t)1U];
uint64_t r0 = FStar_UInt128_uint128_to_uint64(tctr) & (uint64_t)0x7ffffffffffffU;
FStar_UInt128_uint128 c = FStar_UInt128_shift_right(tctr, (uint32_t)51U);
tmp[ctr] = FStar_UInt128_uint64_to_uint128(r0);
tmp[ctr + (uint32_t)1U] = FStar_UInt128_add(tctrp1, c);
}
}
inline static void Hacl_Bignum_Fmul_shift_reduce(uint64_t *output)
{
uint64_t tmp = output[4U];
uint64_t b0;
{
uint32_t i;
for (i = (uint32_t)0U; i < (uint32_t)4U; i = i + (uint32_t)1U)
{
uint32_t ctr = (uint32_t)5U - i - (uint32_t)1U;
uint64_t z = output[ctr - (uint32_t)1U];
output[ctr] = z;
}
}
output[0U] = tmp;
b0 = output[0U];
output[0U] = (uint64_t)19U * b0;
}
static void
Hacl_Bignum_Fmul_mul_shift_reduce_(
FStar_UInt128_uint128 *output,
uint64_t *input,
uint64_t *input2
)
{
uint32_t i;
uint64_t input2i;
{
uint32_t i0;
for (i0 = (uint32_t)0U; i0 < (uint32_t)4U; i0 = i0 + (uint32_t)1U)
{
uint64_t input2i0 = input2[i0];
Hacl_Bignum_Fproduct_sum_scalar_multiplication_(output, input, input2i0);
Hacl_Bignum_Fmul_shift_reduce(input);
}
}
i = (uint32_t)4U;
input2i = input2[i];
Hacl_Bignum_Fproduct_sum_scalar_multiplication_(output, input, input2i);
}
inline static void Hacl_Bignum_Fmul_fmul(uint64_t *output, uint64_t *input, uint64_t *input2)
{
uint64_t tmp[5U] = { 0U };
memcpy(tmp, input, (uint32_t)5U * sizeof input[0U]);
KRML_CHECK_SIZE(sizeof (FStar_UInt128_uint128), (uint32_t)5U);
{
FStar_UInt128_uint128 t[5U];
{
uint32_t _i;
for (_i = 0U; _i < (uint32_t)5U; ++_i)
t[_i] = FStar_UInt128_uint64_to_uint128((uint64_t)0U);
}
{
FStar_UInt128_uint128 b4;
FStar_UInt128_uint128 b0;
FStar_UInt128_uint128 b4_;
FStar_UInt128_uint128 b0_;
uint64_t i0;
uint64_t i1;
uint64_t i0_;
uint64_t i1_;
Hacl_Bignum_Fmul_mul_shift_reduce_(t, tmp, input2);
Hacl_Bignum_Fproduct_carry_wide_(t);
b4 = t[4U];
b0 = t[0U];
b4_ = FStar_UInt128_logand(b4, FStar_UInt128_uint64_to_uint128((uint64_t)0x7ffffffffffffU));
b0_ =
FStar_UInt128_add(b0,
FStar_UInt128_mul_wide((uint64_t)19U,
FStar_UInt128_uint128_to_uint64(FStar_UInt128_shift_right(b4, (uint32_t)51U))));
t[4U] = b4_;
t[0U] = b0_;
Hacl_Bignum_Fproduct_copy_from_wide_(output, t);
i0 = output[0U];
i1 = output[1U];
i0_ = i0 & (uint64_t)0x7ffffffffffffU;
i1_ = i1 + (i0 >> (uint32_t)51U);
output[0U] = i0_;
output[1U] = i1_;
}
}
}
inline static void Hacl_Bignum_Fsquare_fsquare__(FStar_UInt128_uint128 *tmp, uint64_t *output)
{
uint64_t r0 = output[0U];
uint64_t r1 = output[1U];
uint64_t r2 = output[2U];
uint64_t r3 = output[3U];
uint64_t r4 = output[4U];
uint64_t d0 = r0 * (uint64_t)2U;
uint64_t d1 = r1 * (uint64_t)2U;
uint64_t d2 = r2 * (uint64_t)2U * (uint64_t)19U;
uint64_t d419 = r4 * (uint64_t)19U;
uint64_t d4 = d419 * (uint64_t)2U;
FStar_UInt128_uint128
s0 =
FStar_UInt128_add(FStar_UInt128_add(FStar_UInt128_mul_wide(r0, r0),
FStar_UInt128_mul_wide(d4, r1)),
FStar_UInt128_mul_wide(d2, r3));
FStar_UInt128_uint128
s1 =
FStar_UInt128_add(FStar_UInt128_add(FStar_UInt128_mul_wide(d0, r1),
FStar_UInt128_mul_wide(d4, r2)),
FStar_UInt128_mul_wide(r3 * (uint64_t)19U, r3));
FStar_UInt128_uint128
s2 =
FStar_UInt128_add(FStar_UInt128_add(FStar_UInt128_mul_wide(d0, r2),
FStar_UInt128_mul_wide(r1, r1)),
FStar_UInt128_mul_wide(d4, r3));
FStar_UInt128_uint128
s3 =
FStar_UInt128_add(FStar_UInt128_add(FStar_UInt128_mul_wide(d0, r3),
FStar_UInt128_mul_wide(d1, r2)),
FStar_UInt128_mul_wide(r4, d419));
FStar_UInt128_uint128
s4 =
FStar_UInt128_add(FStar_UInt128_add(FStar_UInt128_mul_wide(d0, r4),
FStar_UInt128_mul_wide(d1, r3)),
FStar_UInt128_mul_wide(r2, r2));
tmp[0U] = s0;
tmp[1U] = s1;
tmp[2U] = s2;
tmp[3U] = s3;
tmp[4U] = s4;
}
inline static void Hacl_Bignum_Fsquare_fsquare_(FStar_UInt128_uint128 *tmp, uint64_t *output)
{
FStar_UInt128_uint128 b4;
FStar_UInt128_uint128 b0;
FStar_UInt128_uint128 b4_;
FStar_UInt128_uint128 b0_;
uint64_t i0;
uint64_t i1;
uint64_t i0_;
uint64_t i1_;
Hacl_Bignum_Fsquare_fsquare__(tmp, output);
Hacl_Bignum_Fproduct_carry_wide_(tmp);
b4 = tmp[4U];
b0 = tmp[0U];
b4_ = FStar_UInt128_logand(b4, FStar_UInt128_uint64_to_uint128((uint64_t)0x7ffffffffffffU));
b0_ =
FStar_UInt128_add(b0,
FStar_UInt128_mul_wide((uint64_t)19U,
FStar_UInt128_uint128_to_uint64(FStar_UInt128_shift_right(b4, (uint32_t)51U))));
tmp[4U] = b4_;
tmp[0U] = b0_;
Hacl_Bignum_Fproduct_copy_from_wide_(output, tmp);
i0 = output[0U];
i1 = output[1U];
i0_ = i0 & (uint64_t)0x7ffffffffffffU;
i1_ = i1 + (i0 >> (uint32_t)51U);
output[0U] = i0_;
output[1U] = i1_;
}
static void
Hacl_Bignum_Fsquare_fsquare_times_(
uint64_t *input,
FStar_UInt128_uint128 *tmp,
uint32_t count1
)
{
uint32_t i;
Hacl_Bignum_Fsquare_fsquare_(tmp, input);
for (i = (uint32_t)1U; i < count1; i = i + (uint32_t)1U)
Hacl_Bignum_Fsquare_fsquare_(tmp, input);
}
inline static void
Hacl_Bignum_Fsquare_fsquare_times(uint64_t *output, uint64_t *input, uint32_t count1)
{
KRML_CHECK_SIZE(sizeof (FStar_UInt128_uint128), (uint32_t)5U);
{
FStar_UInt128_uint128 t[5U];
{
uint32_t _i;
for (_i = 0U; _i < (uint32_t)5U; ++_i)
t[_i] = FStar_UInt128_uint64_to_uint128((uint64_t)0U);
}
memcpy(output, input, (uint32_t)5U * sizeof input[0U]);
Hacl_Bignum_Fsquare_fsquare_times_(output, t, count1);
}
}
inline static void Hacl_Bignum_Fsquare_fsquare_times_inplace(uint64_t *output, uint32_t count1)
{
KRML_CHECK_SIZE(sizeof (FStar_UInt128_uint128), (uint32_t)5U);
{
FStar_UInt128_uint128 t[5U];
{
uint32_t _i;
for (_i = 0U; _i < (uint32_t)5U; ++_i)
t[_i] = FStar_UInt128_uint64_to_uint128((uint64_t)0U);
}
Hacl_Bignum_Fsquare_fsquare_times_(output, t, count1);
}
}
inline static void Hacl_Bignum_Crecip_crecip(uint64_t *out, uint64_t *z)
{
uint64_t buf[20U] = { 0U };
uint64_t *a0 = buf;
uint64_t *t00 = buf + (uint32_t)5U;
uint64_t *b0 = buf + (uint32_t)10U;
uint64_t *t01;
uint64_t *b1;
uint64_t *c0;
uint64_t *a;
uint64_t *t0;
uint64_t *b;
uint64_t *c;
Hacl_Bignum_Fsquare_fsquare_times(a0, z, (uint32_t)1U);
Hacl_Bignum_Fsquare_fsquare_times(t00, a0, (uint32_t)2U);
Hacl_Bignum_Fmul_fmul(b0, t00, z);
Hacl_Bignum_Fmul_fmul(a0, b0, a0);
Hacl_Bignum_Fsquare_fsquare_times(t00, a0, (uint32_t)1U);
Hacl_Bignum_Fmul_fmul(b0, t00, b0);
Hacl_Bignum_Fsquare_fsquare_times(t00, b0, (uint32_t)5U);
t01 = buf + (uint32_t)5U;
b1 = buf + (uint32_t)10U;
c0 = buf + (uint32_t)15U;
Hacl_Bignum_Fmul_fmul(b1, t01, b1);
Hacl_Bignum_Fsquare_fsquare_times(t01, b1, (uint32_t)10U);
Hacl_Bignum_Fmul_fmul(c0, t01, b1);
Hacl_Bignum_Fsquare_fsquare_times(t01, c0, (uint32_t)20U);
Hacl_Bignum_Fmul_fmul(t01, t01, c0);
Hacl_Bignum_Fsquare_fsquare_times_inplace(t01, (uint32_t)10U);
Hacl_Bignum_Fmul_fmul(b1, t01, b1);
Hacl_Bignum_Fsquare_fsquare_times(t01, b1, (uint32_t)50U);
a = buf;
t0 = buf + (uint32_t)5U;
b = buf + (uint32_t)10U;
c = buf + (uint32_t)15U;
Hacl_Bignum_Fmul_fmul(c, t0, b);
Hacl_Bignum_Fsquare_fsquare_times(t0, c, (uint32_t)100U);
Hacl_Bignum_Fmul_fmul(t0, t0, c);
Hacl_Bignum_Fsquare_fsquare_times_inplace(t0, (uint32_t)50U);
Hacl_Bignum_Fmul_fmul(t0, t0, b);
Hacl_Bignum_Fsquare_fsquare_times_inplace(t0, (uint32_t)5U);
Hacl_Bignum_Fmul_fmul(out, t0, a);
}
inline static void Hacl_Bignum_fsum(uint64_t *a, uint64_t *b)
{
uint32_t i;
for (i = (uint32_t)0U; i < (uint32_t)5U; i = i + (uint32_t)1U)
{
uint64_t xi = a[i];
uint64_t yi = b[i];
a[i] = xi + yi;
}
}
inline static void Hacl_Bignum_fdifference(uint64_t *a, uint64_t *b)
{
uint64_t tmp[5U] = { 0U };
uint64_t b0;
uint64_t b1;
uint64_t b2;
uint64_t b3;
uint64_t b4;
memcpy(tmp, b, (uint32_t)5U * sizeof b[0U]);
b0 = tmp[0U];
b1 = tmp[1U];
b2 = tmp[2U];
b3 = tmp[3U];
b4 = tmp[4U];
tmp[0U] = b0 + (uint64_t)0x3fffffffffff68U;
tmp[1U] = b1 + (uint64_t)0x3ffffffffffff8U;
tmp[2U] = b2 + (uint64_t)0x3ffffffffffff8U;
tmp[3U] = b3 + (uint64_t)0x3ffffffffffff8U;
tmp[4U] = b4 + (uint64_t)0x3ffffffffffff8U;
{
uint32_t i;
for (i = (uint32_t)0U; i < (uint32_t)5U; i = i + (uint32_t)1U)
{
uint64_t xi = a[i];
uint64_t yi = tmp[i];
a[i] = yi - xi;
}
}
}
inline static void Hacl_Bignum_fscalar(uint64_t *output, uint64_t *b, uint64_t s)
{
KRML_CHECK_SIZE(sizeof (FStar_UInt128_uint128), (uint32_t)5U);
{
FStar_UInt128_uint128 tmp[5U];
{
uint32_t _i;
for (_i = 0U; _i < (uint32_t)5U; ++_i)
tmp[_i] = FStar_UInt128_uint64_to_uint128((uint64_t)0U);
}
{
FStar_UInt128_uint128 b4;
FStar_UInt128_uint128 b0;
FStar_UInt128_uint128 b4_;
FStar_UInt128_uint128 b0_;
{
uint32_t i;
for (i = (uint32_t)0U; i < (uint32_t)5U; i = i + (uint32_t)1U)
{
uint64_t xi = b[i];
tmp[i] = FStar_UInt128_mul_wide(xi, s);
}
}
Hacl_Bignum_Fproduct_carry_wide_(tmp);
b4 = tmp[4U];
b0 = tmp[0U];
b4_ = FStar_UInt128_logand(b4, FStar_UInt128_uint64_to_uint128((uint64_t)0x7ffffffffffffU));
b0_ =
FStar_UInt128_add(b0,
FStar_UInt128_mul_wide((uint64_t)19U,
FStar_UInt128_uint128_to_uint64(FStar_UInt128_shift_right(b4, (uint32_t)51U))));
tmp[4U] = b4_;
tmp[0U] = b0_;
Hacl_Bignum_Fproduct_copy_from_wide_(output, tmp);
}
}
}
inline static void Hacl_Bignum_fmul(uint64_t *output, uint64_t *a, uint64_t *b)
{
Hacl_Bignum_Fmul_fmul(output, a, b);
}
inline static void Hacl_Bignum_crecip(uint64_t *output, uint64_t *input)
{
Hacl_Bignum_Crecip_crecip(output, input);
}
static void
Hacl_EC_Point_swap_conditional_step(uint64_t *a, uint64_t *b, uint64_t swap1, uint32_t ctr)
{
uint32_t i = ctr - (uint32_t)1U;
uint64_t ai = a[i];
uint64_t bi = b[i];
uint64_t x = swap1 & (ai ^ bi);
uint64_t ai1 = ai ^ x;
uint64_t bi1 = bi ^ x;
a[i] = ai1;
b[i] = bi1;
}
static void
Hacl_EC_Point_swap_conditional_(uint64_t *a, uint64_t *b, uint64_t swap1, uint32_t ctr)
{
if (!(ctr == (uint32_t)0U))
{
uint32_t i;
Hacl_EC_Point_swap_conditional_step(a, b, swap1, ctr);
i = ctr - (uint32_t)1U;
Hacl_EC_Point_swap_conditional_(a, b, swap1, i);
}
}
static void Hacl_EC_Point_swap_conditional(uint64_t *a, uint64_t *b, uint64_t iswap)
{
uint64_t swap1 = (uint64_t)0U - iswap;
Hacl_EC_Point_swap_conditional_(a, b, swap1, (uint32_t)5U);
Hacl_EC_Point_swap_conditional_(a + (uint32_t)5U, b + (uint32_t)5U, swap1, (uint32_t)5U);
}
static void Hacl_EC_Point_copy(uint64_t *output, uint64_t *input)
{
memcpy(output, input, (uint32_t)5U * sizeof input[0U]);
memcpy(output + (uint32_t)5U,
input + (uint32_t)5U,
(uint32_t)5U * sizeof (input + (uint32_t)5U)[0U]);
}
static void Hacl_EC_Format_fexpand(uint64_t *output, uint8_t *input)
{
uint64_t i0 = load64_le(input);
uint8_t *x00 = input + (uint32_t)6U;
uint64_t i1 = load64_le(x00);
uint8_t *x01 = input + (uint32_t)12U;
uint64_t i2 = load64_le(x01);
uint8_t *x02 = input + (uint32_t)19U;
uint64_t i3 = load64_le(x02);
uint8_t *x0 = input + (uint32_t)24U;
uint64_t i4 = load64_le(x0);
uint64_t output0 = i0 & (uint64_t)0x7ffffffffffffU;
uint64_t output1 = i1 >> (uint32_t)3U & (uint64_t)0x7ffffffffffffU;
uint64_t output2 = i2 >> (uint32_t)6U & (uint64_t)0x7ffffffffffffU;
uint64_t output3 = i3 >> (uint32_t)1U & (uint64_t)0x7ffffffffffffU;
uint64_t output4 = i4 >> (uint32_t)12U & (uint64_t)0x7ffffffffffffU;
output[0U] = output0;
output[1U] = output1;
output[2U] = output2;
output[3U] = output3;
output[4U] = output4;
}
static void Hacl_EC_Format_fcontract_first_carry_pass(uint64_t *input)
{
uint64_t t0 = input[0U];
uint64_t t1 = input[1U];
uint64_t t2 = input[2U];
uint64_t t3 = input[3U];
uint64_t t4 = input[4U];
uint64_t t1_ = t1 + (t0 >> (uint32_t)51U);
uint64_t t0_ = t0 & (uint64_t)0x7ffffffffffffU;
uint64_t t2_ = t2 + (t1_ >> (uint32_t)51U);
uint64_t t1__ = t1_ & (uint64_t)0x7ffffffffffffU;
uint64_t t3_ = t3 + (t2_ >> (uint32_t)51U);
uint64_t t2__ = t2_ & (uint64_t)0x7ffffffffffffU;
uint64_t t4_ = t4 + (t3_ >> (uint32_t)51U);
uint64_t t3__ = t3_ & (uint64_t)0x7ffffffffffffU;
input[0U] = t0_;
input[1U] = t1__;
input[2U] = t2__;
input[3U] = t3__;
input[4U] = t4_;
}
static void Hacl_EC_Format_fcontract_first_carry_full(uint64_t *input)
{
Hacl_EC_Format_fcontract_first_carry_pass(input);
Hacl_Bignum_Modulo_carry_top(input);
}
static void Hacl_EC_Format_fcontract_second_carry_pass(uint64_t *input)
{
uint64_t t0 = input[0U];
uint64_t t1 = input[1U];
uint64_t t2 = input[2U];
uint64_t t3 = input[3U];
uint64_t t4 = input[4U];
uint64_t t1_ = t1 + (t0 >> (uint32_t)51U);
uint64_t t0_ = t0 & (uint64_t)0x7ffffffffffffU;
uint64_t t2_ = t2 + (t1_ >> (uint32_t)51U);
uint64_t t1__ = t1_ & (uint64_t)0x7ffffffffffffU;
uint64_t t3_ = t3 + (t2_ >> (uint32_t)51U);
uint64_t t2__ = t2_ & (uint64_t)0x7ffffffffffffU;
uint64_t t4_ = t4 + (t3_ >> (uint32_t)51U);
uint64_t t3__ = t3_ & (uint64_t)0x7ffffffffffffU;
input[0U] = t0_;
input[1U] = t1__;
input[2U] = t2__;
input[3U] = t3__;
input[4U] = t4_;
}
static void Hacl_EC_Format_fcontract_second_carry_full(uint64_t *input)
{
uint64_t i0;
uint64_t i1;
uint64_t i0_;
uint64_t i1_;
Hacl_EC_Format_fcontract_second_carry_pass(input);
Hacl_Bignum_Modulo_carry_top(input);
i0 = input[0U];
i1 = input[1U];
i0_ = i0 & (uint64_t)0x7ffffffffffffU;
i1_ = i1 + (i0 >> (uint32_t)51U);
input[0U] = i0_;
input[1U] = i1_;
}
static void Hacl_EC_Format_fcontract_trim(uint64_t *input)
{
uint64_t a0 = input[0U];
uint64_t a1 = input[1U];
uint64_t a2 = input[2U];
uint64_t a3 = input[3U];
uint64_t a4 = input[4U];
uint64_t mask0 = FStar_UInt64_gte_mask(a0, (uint64_t)0x7ffffffffffedU);
uint64_t mask1 = FStar_UInt64_eq_mask(a1, (uint64_t)0x7ffffffffffffU);
uint64_t mask2 = FStar_UInt64_eq_mask(a2, (uint64_t)0x7ffffffffffffU);
uint64_t mask3 = FStar_UInt64_eq_mask(a3, (uint64_t)0x7ffffffffffffU);
uint64_t mask4 = FStar_UInt64_eq_mask(a4, (uint64_t)0x7ffffffffffffU);
uint64_t mask = (((mask0 & mask1) & mask2) & mask3) & mask4;
uint64_t a0_ = a0 - ((uint64_t)0x7ffffffffffedU & mask);
uint64_t a1_ = a1 - ((uint64_t)0x7ffffffffffffU & mask);
uint64_t a2_ = a2 - ((uint64_t)0x7ffffffffffffU & mask);
uint64_t a3_ = a3 - ((uint64_t)0x7ffffffffffffU & mask);
uint64_t a4_ = a4 - ((uint64_t)0x7ffffffffffffU & mask);
input[0U] = a0_;
input[1U] = a1_;
input[2U] = a2_;
input[3U] = a3_;
input[4U] = a4_;
}
static void Hacl_EC_Format_fcontract_store(uint8_t *output, uint64_t *input)
{
uint64_t t0 = input[0U];
uint64_t t1 = input[1U];
uint64_t t2 = input[2U];
uint64_t t3 = input[3U];
uint64_t t4 = input[4U];
uint64_t o0 = t1 << (uint32_t)51U | t0;
uint64_t o1 = t2 << (uint32_t)38U | t1 >> (uint32_t)13U;
uint64_t o2 = t3 << (uint32_t)25U | t2 >> (uint32_t)26U;
uint64_t o3 = t4 << (uint32_t)12U | t3 >> (uint32_t)39U;
uint8_t *b0 = output;
uint8_t *b1 = output + (uint32_t)8U;
uint8_t *b2 = output + (uint32_t)16U;
uint8_t *b3 = output + (uint32_t)24U;
store64_le(b0, o0);
store64_le(b1, o1);
store64_le(b2, o2);
store64_le(b3, o3);
}
static void Hacl_EC_Format_fcontract(uint8_t *output, uint64_t *input)
{
Hacl_EC_Format_fcontract_first_carry_full(input);
Hacl_EC_Format_fcontract_second_carry_full(input);
Hacl_EC_Format_fcontract_trim(input);
Hacl_EC_Format_fcontract_store(output, input);
}
static void Hacl_EC_Format_scalar_of_point(uint8_t *scalar, uint64_t *point)
{
uint64_t *x = point;
uint64_t *z = point + (uint32_t)5U;
uint64_t buf[10U] = { 0U };
uint64_t *zmone = buf;
uint64_t *sc = buf + (uint32_t)5U;
Hacl_Bignum_crecip(zmone, z);
Hacl_Bignum_fmul(sc, x, zmone);
Hacl_EC_Format_fcontract(scalar, sc);
}
static void
Hacl_EC_AddAndDouble_fmonty(
uint64_t *pp,
uint64_t *ppq,
uint64_t *p,
uint64_t *pq,
uint64_t *qmqp
)
{
uint64_t *qx = qmqp;
uint64_t *x2 = pp;
uint64_t *z2 = pp + (uint32_t)5U;
uint64_t *x3 = ppq;
uint64_t *z3 = ppq + (uint32_t)5U;
uint64_t *x = p;
uint64_t *z = p + (uint32_t)5U;
uint64_t *xprime = pq;
uint64_t *zprime = pq + (uint32_t)5U;
uint64_t buf[40U] = { 0U };
uint64_t *origx = buf;
uint64_t *origxprime0 = buf + (uint32_t)5U;
uint64_t *xxprime0 = buf + (uint32_t)25U;
uint64_t *zzprime0 = buf + (uint32_t)30U;
uint64_t *origxprime;
uint64_t *xx0;
uint64_t *zz0;
uint64_t *xxprime;
uint64_t *zzprime;
uint64_t *zzzprime;
uint64_t *zzz;
uint64_t *xx;
uint64_t *zz;
uint64_t scalar;
memcpy(origx, x, (uint32_t)5U * sizeof x[0U]);
Hacl_Bignum_fsum(x, z);
Hacl_Bignum_fdifference(z, origx);
memcpy(origxprime0, xprime, (uint32_t)5U * sizeof xprime[0U]);
Hacl_Bignum_fsum(xprime, zprime);
Hacl_Bignum_fdifference(zprime, origxprime0);
Hacl_Bignum_fmul(xxprime0, xprime, z);
Hacl_Bignum_fmul(zzprime0, x, zprime);
origxprime = buf + (uint32_t)5U;
xx0 = buf + (uint32_t)15U;
zz0 = buf + (uint32_t)20U;
xxprime = buf + (uint32_t)25U;
zzprime = buf + (uint32_t)30U;
zzzprime = buf + (uint32_t)35U;
memcpy(origxprime, xxprime, (uint32_t)5U * sizeof xxprime[0U]);
Hacl_Bignum_fsum(xxprime, zzprime);
Hacl_Bignum_fdifference(zzprime, origxprime);
Hacl_Bignum_Fsquare_fsquare_times(x3, xxprime, (uint32_t)1U);
Hacl_Bignum_Fsquare_fsquare_times(zzzprime, zzprime, (uint32_t)1U);
Hacl_Bignum_fmul(z3, zzzprime, qx);
Hacl_Bignum_Fsquare_fsquare_times(xx0, x, (uint32_t)1U);
Hacl_Bignum_Fsquare_fsquare_times(zz0, z, (uint32_t)1U);
zzz = buf + (uint32_t)10U;
xx = buf + (uint32_t)15U;
zz = buf + (uint32_t)20U;
Hacl_Bignum_fmul(x2, xx, zz);
Hacl_Bignum_fdifference(zz, xx);
scalar = (uint64_t)121665U;
Hacl_Bignum_fscalar(zzz, zz, scalar);
Hacl_Bignum_fsum(zzz, xx);
Hacl_Bignum_fmul(z2, zzz, zz);
}
static void
Hacl_EC_Ladder_SmallLoop_cmult_small_loop_step(
uint64_t *nq,
uint64_t *nqpq,
uint64_t *nq2,
uint64_t *nqpq2,
uint64_t *q,
uint8_t byt
)
{
uint64_t bit0 = (uint64_t)(byt >> (uint32_t)7U);
uint64_t bit;
Hacl_EC_Point_swap_conditional(nq, nqpq, bit0);
Hacl_EC_AddAndDouble_fmonty(nq2, nqpq2, nq, nqpq, q);
bit = (uint64_t)(byt >> (uint32_t)7U);
Hacl_EC_Point_swap_conditional(nq2, nqpq2, bit);
}
static void
Hacl_EC_Ladder_SmallLoop_cmult_small_loop_double_step(
uint64_t *nq,
uint64_t *nqpq,
uint64_t *nq2,
uint64_t *nqpq2,
uint64_t *q,
uint8_t byt
)
{
uint8_t byt1;
Hacl_EC_Ladder_SmallLoop_cmult_small_loop_step(nq, nqpq, nq2, nqpq2, q, byt);
byt1 = byt << (uint32_t)1U;
Hacl_EC_Ladder_SmallLoop_cmult_small_loop_step(nq2, nqpq2, nq, nqpq, q, byt1);
}
static void
Hacl_EC_Ladder_SmallLoop_cmult_small_loop(
uint64_t *nq,
uint64_t *nqpq,
uint64_t *nq2,
uint64_t *nqpq2,
uint64_t *q,
uint8_t byt,
uint32_t i
)
{
if (!(i == (uint32_t)0U))
{
uint32_t i_ = i - (uint32_t)1U;
uint8_t byt_;
Hacl_EC_Ladder_SmallLoop_cmult_small_loop_double_step(nq, nqpq, nq2, nqpq2, q, byt);
byt_ = byt << (uint32_t)2U;
Hacl_EC_Ladder_SmallLoop_cmult_small_loop(nq, nqpq, nq2, nqpq2, q, byt_, i_);
}
}
static void
Hacl_EC_Ladder_BigLoop_cmult_big_loop(
uint8_t *n1,
uint64_t *nq,
uint64_t *nqpq,
uint64_t *nq2,
uint64_t *nqpq2,
uint64_t *q,
uint32_t i
)
{
if (!(i == (uint32_t)0U))
{
uint32_t i1 = i - (uint32_t)1U;
uint8_t byte = n1[i1];
Hacl_EC_Ladder_SmallLoop_cmult_small_loop(nq, nqpq, nq2, nqpq2, q, byte, (uint32_t)4U);
Hacl_EC_Ladder_BigLoop_cmult_big_loop(n1, nq, nqpq, nq2, nqpq2, q, i1);
}
}
static void Hacl_EC_Ladder_cmult(uint64_t *result, uint8_t *n1, uint64_t *q)
{
uint64_t point_buf[40U] = { 0U };
uint64_t *nq = point_buf;
uint64_t *nqpq = point_buf + (uint32_t)10U;
uint64_t *nq2 = point_buf + (uint32_t)20U;
uint64_t *nqpq2 = point_buf + (uint32_t)30U;
Hacl_EC_Point_copy(nqpq, q);
nq[0U] = (uint64_t)1U;
Hacl_EC_Ladder_BigLoop_cmult_big_loop(n1, nq, nqpq, nq2, nqpq2, q, (uint32_t)32U);
Hacl_EC_Point_copy(result, nq);
}
void Hacl_Curve25519_crypto_scalarmult(uint8_t *mypublic, uint8_t *secret, uint8_t *basepoint)
{
uint64_t buf0[10U] = { 0U };
uint64_t *x0 = buf0;
uint64_t *z = buf0 + (uint32_t)5U;
uint64_t *q;
Hacl_EC_Format_fexpand(x0, basepoint);
z[0U] = (uint64_t)1U;
q = buf0;
{
uint8_t e[32U] = { 0U };
uint8_t e0;
uint8_t e31;
uint8_t e01;
uint8_t e311;
uint8_t e312;
uint8_t *scalar;
memcpy(e, secret, (uint32_t)32U * sizeof secret[0U]);
e0 = e[0U];
e31 = e[31U];
e01 = e0 & (uint8_t)248U;
e311 = e31 & (uint8_t)127U;
e312 = e311 | (uint8_t)64U;
e[0U] = e01;
e[31U] = e312;
scalar = e;
{
uint64_t buf[15U] = { 0U };
uint64_t *nq = buf;
uint64_t *x = nq;
x[0U] = (uint64_t)1U;
Hacl_EC_Ladder_cmult(nq, scalar, q);
Hacl_EC_Format_scalar_of_point(mypublic, nq);
}
}
}
|
0 | repos | repos/zig-ulid/ulid.zig | //! https://github.com/ulid/spec
const std = @import("std");
const string = []const u8;
const base32 = @import("./base32.zig");
const extras = @import("extras");
pub const Factory = struct {
epoch: i64,
rand: std.rand.Random,
pub fn init(epoch: i64, rand: std.rand.Random) Factory {
return Factory{
.epoch = epoch,
.rand = rand,
};
}
pub fn newULID(self: Factory) ULID {
const now = std.time.milliTimestamp();
return ULID{
.timestamp = std.math.cast(u48, now - self.epoch) orelse @panic("time.milliTimestamp() is higher than 281474976710655"), // this is Tue Aug 02 10889 05:31:50.655 UTC
.randomnes = self.rand.int(u80),
};
}
};
/// 01AN4Z07BY 79KA1307SR9X4MV3
///
/// |----------| |----------------|
/// Timestamp Randomness
/// 48bits 80bits
pub const ULID = packed struct {
timestamp: u48,
randomnes: u80,
pub const BaseType = string;
usingnamespace extras.StringerJsonStringifyMixin(@This());
pub fn parse(alloc: std.mem.Allocator, value: BaseType) !ULID {
if (value.len != 26) return error.Ulid;
return ULID{
.timestamp = std.math.cast(u48, try extras.sliceToInt(u50, u5, try base32.decode(alloc, value[0..10]))) orelse return error.Ulid,
.randomnes = try extras.sliceToInt(u80, u5, try base32.decode(alloc, value[10..26])),
};
}
pub fn toString(self: ULID, alloc: std.mem.Allocator) !BaseType {
var res = try std.ArrayList(u8).initCapacity(alloc, 26);
defer res.deinit();
try res.writer().print("{}", .{self});
return res.toOwnedSlice();
}
pub const readField = parse;
pub const bindField = toString;
pub fn bytes(self: ULID) [26]u8 {
var buf: [26]u8 = undefined;
base32.formatInt(u48, self.timestamp, buf[0..10]);
base32.formatInt(u80, self.randomnes, buf[10..26]);
return buf;
}
pub fn format(self: ULID, comptime fmt: []const u8, options: std.fmt.FormatOptions, writer: anytype) !void {
_ = fmt;
_ = options;
try writer.writeAll(&self.bytes());
}
};
|
0 | repos | repos/zig-ulid/base32.zig | //! https://www.crockford.com/base32.html
const std = @import("std");
const string = []const u8;
const alphabet = "0123456789ABCDEFGHJKMNPQRSTVWXYZ";
pub fn decode(alloc: std.mem.Allocator, input: string) ![]const u5 {
var list = std.ArrayList(u5).init(alloc);
errdefer list.deinit();
for (input) |c| {
for (alphabet, 0..) |d, i| {
if (c == d) {
try list.append(@intCast(i));
}
}
}
return list.toOwnedSlice();
}
pub fn formatInt(comptime T: type, n: T, buf: []u8) void {
const l: T = @intCast(alphabet.len);
var x = n;
var i = buf.len;
for (0..i) |j| {
buf[j] = alphabet[0];
}
while (true) {
const a: usize = @intCast(x % l);
x = x / l;
buf[i - 1] = alphabet[a];
i -= 1;
if (x == 0) break;
}
}
|
0 | repos | repos/zig-ulid/licenses.txt | MIT:
= https://spdx.org/licenses/MIT
- This
- git https://github.com/nektro/zig-extras
|
0 | repos | repos/zig-ulid/zig.mod | id: 1vu3948bgf52ytvq9u4skpj8es5hd30s0tfx2f15hjaa4tnl
name: ulid
main: ulid.zig
license: MIT
description: ULID implementation for Zig
min_zig_version: 0.10.0-dev.2431+0e6285c8f
dependencies:
- src: git https://github.com/nektro/zig-extras
|
0 | repos | repos/zig-ulid/test.zig | const std = @import("std");
const string = []const u8;
const ulid = @import("ulid");
// zig fmt: off
test { try ensureFromTo("001HX7QW7K2PP61CS28B4YF00X"); }
test { try ensureFromTo("0015KMZ1NDDFP4WRWSVA31N0CD"); }
test { try ensureFromTo("0015MFYM13K180VCNCACTFRJAB"); }
test { try ensureFromTo("0015RMHR0WVSCBE4CJWKPCC4GJ"); }
test { try ensureFromTo("0017NSY29QD0YYPB0H0W5GQJQX"); }
test { try ensureFromTo("0017TZRGVZYHK9C26FK5AP3HTG"); }
test { try ensureFromTo("0017Y302CVXHJABSPHNNEBE0R7"); }
test { try ensureFromTo("00183KTME6PJZ773Q9A1BWFJ3X"); }
test { try ensureFromTo("0018ZPQ92P0NDDKNVB3PBW7D18"); }
test { try ensureFromTo("00193A6YMTQR01XTY757XRRJKE"); }
test { try ensureFromTo("0019ABB5M0YK71B4ATA90A8F81"); }
test { try ensureFromTo("0019GFR7YK5HNTFPS2BAQNG0PX"); }
test { try ensureFromTo("001A2YPKW942R97BXRAJG2BD7S"); }
test { try ensureFromTo("001C38D808VW1EG3JS6XJHT4EQ"); }
test { try ensureFromTo("001C9DSQ8SC6SVEVHFK09XBFTC"); }
test { try ensureFromTo("001DEJXKVPDV7BZT1Q80ZEN2PF"); }
test { try ensureFromTo("001F1Z79BCKADWYPDCMZ8B8G0G"); }
// zig fmt: on
fn ensureFromTo(before: string) !void {
const alloc = std.heap.page_allocator;
const ul = try ulid.ULID.parse(alloc, before);
const after = try ul.toString(alloc);
try std.testing.expectEqualStrings(before, after);
}
|
0 | repos | repos/zig-ulid/README.md | # zig-ulid

[](https://github.com/nektro/zig-ulid/blob/master/LICENSE)
A binary implementation of ULID in Zig.
https://github.com/ulid/spec
## License
MIT
|
0 | repos | repos/zig-ulid/build.zig | const std = @import("std");
const deps = @import("./deps.zig");
pub fn build(b: *std.Build) void {
const target = b.standardTargetOptions(.{});
const mode = b.option(std.builtin.Mode, "mode", "") orelse .Debug;
const tests = b.addTest(.{
.root_source_file = b.path("./test.zig"),
.target = target,
.optimize = mode,
});
deps.addAllTo(tests);
const tests_run = b.addRunArtifact(tests);
const test_step = b.step("test", "dummy test step to pass CI checks");
test_step.dependOn(&tests_run.step);
}
|
0 | repos | repos/zig-bare-metal-microbit/lib_basics.zig | pub const lib = struct {
pub const Bss = struct {
pub fn prepare() void {
@memset(@ptrCast([*]u8, &__bss_start), 0, @ptrToInt(&__bss_end) - @ptrToInt(&__bss_start));
}
};
pub const Adc = struct {
pub const busy_registers = mmio(0x40007400, extern struct {
busy: u32,
});
pub const events = mmio(0x40007100, extern struct {
end: u32,
});
pub const registers = mmio(0x40007500, extern struct {
enable: u32,
config: u32,
result: u32,
});
pub const registers_config_masks = struct {
pub const extrefsel = 0x30000;
pub const inpsel = 0x001c;
pub const psel = 0xff00;
pub const refsel = 0x0060;
pub const resolution = 0x00003;
};
pub const tasks = mmio(0x40007000, extern struct {
start: u32,
stop: u32,
});
};
pub const ClockManagement = struct {
pub fn prepareHf() void {
crystal_registers.frequency_selector = 0xff;
tasks.start_hf_clock = 1;
while (events.hf_clock_started == 0) {}
}
pub const events = mmio(0x40000100, extern struct {
hf_clock_started: u32,
lf_clock_started: u32,
});
pub const crystal_registers = mmio(0x40000550, extern struct {
frequency_selector: u32,
});
pub const tasks = mmio(0x40000000, extern struct {
start_hf_clock: u32,
stop_hf_clock: u32,
start_lf_clock: u32,
stop_lf_clock: u32,
});
};
pub const Exceptions = struct {
var already_panicking: bool = undefined;
var panic_handler: ?fn (message: []const u8, trace: ?*builtin.StackTrace) noreturn = undefined;
pub fn handle(exception_number: u32) noreturn {
panicf("exception number {} ... now idle in arm exception handler", .{exception_number});
}
pub fn prepare() void {
already_panicking = false;
panic_handler = null;
}
pub fn setPanicHandler(new_panic_handler: ?fn (message: []const u8, trace: ?*builtin.StackTrace) noreturn) void {
panic_handler = new_panic_handler;
}
};
pub const Ficr = struct {
pub fn deviceId() u64 {
return @as(u64, contents[0x64 / 4]) << 32 | contents[0x60 / 4];
}
pub fn dump() void {
for (contents) |word, i| {
log("{x:2} {x:8}", .{ i * 4, word });
}
}
pub fn isQemu() bool {
return deviceId() == 0x1234567800000003;
}
pub const contents = @intToPtr(*[64]u32, 0x10000000);
pub const radio = @intToPtr(*extern struct {
device_address_type: u32,
device_address0: u32,
device_address1: u32,
}, 0x100000a0);
};
pub const Gpio = struct {
pub const config = mmio(0x50000700, [32]u32);
pub const config_masks = struct {
pub const input = 0x0;
pub const output = 0x1;
};
pub const led_anode_number_and_cathode_number_indexed_by_y_then_x = [5][5][2]u32{
.{ .{ 1, 1 }, .{ 2, 4 }, .{ 1, 2 }, .{ 2, 5 }, .{ 1, 3 } },
.{ .{ 3, 4 }, .{ 3, 5 }, .{ 3, 6 }, .{ 3, 7 }, .{ 3, 8 } },
.{ .{ 2, 2 }, .{ 1, 9 }, .{ 2, 3 }, .{ 3, 9 }, .{ 2, 1 } },
.{ .{ 1, 8 }, .{ 1, 7 }, .{ 1, 6 }, .{ 1, 5 }, .{ 1, 4 } },
.{ .{ 3, 3 }, .{ 2, 7 }, .{ 3, 1 }, .{ 2, 6 }, .{ 3, 2 } },
};
pub const registers = mmio(0x50000504, extern struct {
out: u32,
out_set: u32,
out_clear: u32,
in: u32,
direction: u32,
direction_set: u32,
direction_clear: u32,
});
pub const registers_masks = struct {
pub const button_a_active_low: u32 = 1 << 17;
pub const button_b_active_low: u32 = 1 << 26;
pub const i2c_scl: u32 = 1 << 0;
pub const i2c_sda: u32 = 1 << 30;
pub const nine_led_cathodes_active_low: u32 = 0x1ff << 4;
pub const ring0: u32 = 1 << 3;
pub const ring1: u32 = 1 << 2;
pub const ring2: u32 = 1 << 1;
pub const three_led_anodes: u32 = 0x7 << 13;
pub const uart_rx = 1 << 25;
pub const uart_tx = 1 << 24;
};
};
pub const Gpiote = struct {
pub const config = mmio(0x40006510, [4]u32);
pub const config_masks = struct {
pub const disable = 0x0;
};
pub const tasks = struct {
pub const out = mmio(0x40006000, [4]u32);
};
};
pub fn I2cInstance(instance_address: u32) type {
return struct {
pub fn prepare() void {
registers.enable = 0;
Gpio.registers.direction_set = Gpio.registers_masks.i2c_scl | Gpio.registers_masks.i2c_sda;
registers.pselscl = @ctz(u32, Gpio.registers_masks.i2c_scl);
registers.pselsda = @ctz(u32, Gpio.registers_masks.i2c_sda);
registers.frequency = frequencies.K400;
registers.enable = 5;
}
pub fn probe(device_address: u32) !void {
device_addresses.device_address = device_address;
tasks.startrx = 1;
defer tasks.stop = 1;
try wait(&events.byte_break);
}
pub fn readBlocking(device_address: u32, data: []u8, first: u32, last: u32) !void {
device_addresses.device_address = device_address;
tasks.starttx = 1;
registers.txd = first;
try wait(&events.txdsent);
tasks.startrx = 1;
var i = first;
while (i <= last) : (i += 1) {
if (i == last) {
tasks.stop = 1;
}
try wait(&events.rxready);
data[i] = @truncate(u8, registers.rxd);
}
}
pub fn readBlockingPanic(device_address: u32, data: []u8, first: u32, last: u32) void {
if (readBlocking(device_address, data, first, last)) |_| {} else |err| {
panicf("i2c device 0x{x} read {} errorsrc 0x{x}", .{ device_address, err, I2c0.errorsrc_registers.errorsrc });
}
}
fn wait(event: *volatile u32) !void {
const start = Timer0.capture();
while (true) {
if (event.* != 0) {
event.* = 0;
return;
}
if (errorsrc_registers.errorsrc != 0) {
return error.I2cErrorSourceRegister;
}
if (Timer0.capture() -% start > 500 * 1000) {
return error.I2cTimeExpired;
}
}
}
pub fn writeBlocking(device_address: u32, data: []u8, first: u32, last: u32) !void {
device_addresses.device_address = device_address;
tasks.starttx = 1;
registers.txd = first;
try wait(&events.txdsent);
var i = first;
while (i <= last) : (i += 1) {
registers.txd = data[i];
try wait(&events.txdsent);
}
tasks.stop = 1;
}
pub fn writeBlockingPanic(device_address: u32, data: []u8, first: u32, last: u32) void {
if (writeBlocking(device_address, data, first, last)) |_| {} else |err| {
panicf("i2c device 0x{x} write {} errorsrc 0x{x}", .{ device_address, err, I2c0.errorsrc_registers.errorsrc });
}
}
pub const device_addresses = mmio(instance_address + 0x588, extern struct {
device_address: u32,
});
pub const events = mmio(instance_address + 0x104, extern struct {
stopped: u32,
rxready: u32,
unused1: [4]u32,
txdsent: u32,
unused2: [1]u32,
error_event: u32,
unused3: [4]u32,
byte_break: u32,
});
pub const frequencies = struct {
pub const K100 = 0x01980000;
pub const K250 = 0x04000000;
pub const K400 = 0x06680000;
};
pub const errorsrc_registers = mmio(instance_address + 0x4c4, extern struct {
errorsrc: u32,
});
pub const errorsrc_masks = struct {
pub const overrun = 1 << 0;
pub const address_nack = 1 << 1;
pub const data_nack = 1 << 2;
};
pub const registers = mmio(instance_address + 0x500, extern struct {
enable: u32,
unused1: [1]u32,
pselscl: u32,
pselsda: u32,
unused2: [2]u32,
rxd: u32,
txd: u32,
unused3: [1]u32,
frequency: u32,
});
pub const short_cuts = mmio(instance_address + 0x200, extern struct {
shorts: u32,
});
pub const tasks = mmio(instance_address + 0x000, extern struct {
startrx: u32,
unused1: [1]u32,
starttx: u32,
unused2: [2]u32,
stop: u32,
unused3: [1]u32,
suspend_task: u32,
resume_task: u32,
});
};
}
pub const LedMatrix = struct {
pub var max_elapsed: u32 = undefined;
pub var image: u32 = undefined;
var scan_lines: [3]u32 = undefined;
var scan_lines_index: u32 = undefined;
var scan_timer: TimeKeeper = undefined;
pub fn prepare() void {
image = 0;
max_elapsed = 0;
Gpio.registers.direction_set = Gpio.registers_masks.three_led_anodes | Gpio.registers_masks.nine_led_cathodes_active_low;
for (scan_lines) |*scan_line| {
scan_line.* = 0;
}
scan_lines_index = 0;
putChar('Z');
scan_timer.prepare(3 * 1000);
}
pub fn putChar(byte: u8) void {
putImage(getImage(byte));
}
pub fn putImage(new_image: u32) void {
image = new_image;
var mask: u32 = 0x1;
var y: i32 = 4;
while (y >= 0) : (y -= 1) {
var x: i32 = 4;
while (x >= 0) : (x -= 1) {
putPixel(@intCast(u32, x), @intCast(u32, y), if (image & mask != 0) @as(u32, 1) else 0);
mask <<= 1;
}
}
}
fn putPixel(x: u32, y: u32, v: u32) void {
const anode_number_and_cathode_number = Gpio.led_anode_number_and_cathode_number_indexed_by_y_then_x[y][x];
const selected_scan_line_index = anode_number_and_cathode_number[0] - 1;
const col_mask = @as(u32, 0x10) << @truncate(u5, anode_number_and_cathode_number[1] - 1);
scan_lines[selected_scan_line_index] = scan_lines[selected_scan_line_index] & ~col_mask | v * col_mask;
}
pub fn update() void {
if (scan_timer.isFinished()) {
const elapsed = scan_timer.elapsed();
if (elapsed > max_elapsed) {
max_elapsed = elapsed;
}
scan_timer.reset();
const keep = Gpio.registers.out & ~(Gpio.registers_masks.three_led_anodes | Gpio.registers_masks.nine_led_cathodes_active_low);
const row_pins = @as(u32, 0x2000) << @truncate(u5, scan_lines_index);
const col_pins = ~scan_lines[scan_lines_index] & Gpio.registers_masks.nine_led_cathodes_active_low;
Gpio.registers.out = keep | row_pins | col_pins;
scan_lines_index = (scan_lines_index + 1) % scan_lines.len;
}
}
pub fn getImage(byte: u8) u32 {
return switch (byte) {
' ' => 0b0000000000000000000000000,
'0' => 0b1111110001100011000111111,
'1' => 0b0010001100001000010001110,
'2' => 0b1111100001111111000011111,
'3' => 0b1111100001001110000111111,
'4' => 0b1000110001111110000100001,
'5' => 0b1111110000111110000111111,
'6' => 0b1111110000111111000111111,
'7' => 0b1111100001000100010001000,
'8' => 0b1111110001111111000111111,
'9' => 0b1111110001111110000100001,
'A' => 0b0111010001111111000110001,
'B' => 0b1111010001111111000111110,
'Z' => 0b1111100010001000100011111,
else => 0b0000000000001000000000000,
};
}
};
pub const Power = struct {
pub const registers = mmio(0x40000400, extern struct {
reset_reason: u32,
});
};
pub const Ppi = struct {
pub fn setChannelEventAndTask(channel: u32, event: *volatile u32, task: *volatile u32) void {
channels[channel].event_end_point = @ptrToInt(event);
channels[channel].task_end_point = @ptrToInt(task);
}
pub const registers = mmio(0x4001f500, extern struct {
channel_enable: u32,
channel_enable_set: u32,
channel_enable_clear: u32,
});
const channels = mmio(0x4001f510, [16]struct {
event_end_point: u32,
task_end_point: u32,
});
};
pub const Radio = struct {
pub const events = mmio(0x40001100, extern struct {
ready: u32,
address_completed: u32,
payload_completed: u32,
packet_completed: u32,
disabled: u32,
});
pub const registers = mmio(0x40001504, struct {
packet_ptr: u32,
frequency: u32,
tx_power: u32,
mode: u32,
pcnf0: u32,
pcnf1: u32,
base0: u32,
base1: u32,
prefix0: u32,
prefix1: u32,
tx_address: u32,
rx_addresses: u32,
crc_config: u32,
crc_poly: u32,
crc_init: u32,
unused0x540: u32,
unused0x544: u32,
unused0x548: u32,
unused0x54c: u32,
state: u32,
datawhiteiv: u32,
});
pub const rx_registers = mmio(0x40001400, extern struct {
crc_status: u32,
unused0x404: u32,
unused0x408: u32,
rx_crc: u32,
});
pub const short_cuts = mmio(0x40001200, extern struct {
shorts: u32,
});
pub const tasks = mmio(0x40001000, extern struct {
tx_enable: u32,
rx_enable: u32,
start: u32,
stop: u32,
disable: u32,
});
};
pub const Rng = struct {
pub fn prepare() void {
registers.config = 0x1;
tasks.start = 1;
}
pub const events = mmio(0x4000d100, extern struct {
value_ready: u32,
});
pub const registers = mmio(0x4000d504, extern struct {
config: u32,
value: u32,
});
pub const tasks = mmio(0x4000d000, extern struct {
start: u32,
stop: u32,
});
};
pub const SystemControlBlock = struct {
pub fn requestSystemReset() void {
registers.aircr = 0x05fa0004;
}
pub const registers = mmio(0xe000ed00, extern struct {
cpuid: u32,
icsr: u32,
unused1: u32,
aircr: u32,
scr: u32,
ccr: u32,
unused2: u32,
shpr2: u32,
shpr3: u32,
});
};
pub const Temperature = struct {
pub const events = mmio(0x4000c100, extern struct {
data_ready: u32,
});
pub const registers = mmio(0x4000c508, extern struct {
temperature: u32,
});
pub const tasks = mmio(0x4000c000, extern struct {
start: u32,
stop: u32,
});
};
pub const Terminal = struct {
pub fn attribute(n: u32) void {
pair(n, 0, "m");
}
pub fn clearScreen() void {
pair(2, 0, "J");
}
pub fn hideCursor() void {
Uart.writeText(csi ++ "?25l");
}
pub fn line(comptime fmt: []const u8, args: var) void {
format(fmt, args);
pair(0, 0, "K");
Uart.writeText("\n");
}
pub fn move(row: u32, column: u32) void {
pair(row, column, "H");
}
pub fn pair(a: u32, b: u32, letter: []const u8) void {
if (a <= 1 and b <= 1) {
format("{}{}", .{ csi, letter });
} else if (b <= 1) {
format("{}{}{}", .{ csi, a, letter });
} else if (a <= 1) {
format("{};{}{}", .{ csi, b, letter });
} else {
format("{}{};{}{}", .{ csi, a, b, letter });
}
}
pub fn reportCursorPosition() void {
Uart.writeText(csi ++ "6n");
}
pub fn restoreCursor() void {
pair(0, 0, "u");
}
pub fn saveCursor() void {
pair(0, 0, "s");
}
pub fn setScrollingRegion(top: u32, bottom: u32) void {
pair(top, bottom, "r");
}
pub fn showCursor() void {
Uart.writeText(csi ++ "?25h");
}
const csi = "\x1b[";
};
pub const TimeKeeper = struct {
duration: u32,
start_time: u32,
fn capture(self: *TimeKeeper) u32 {
Timer0.capture_tasks[0] = 1;
return Timer0.capture_compare_registers[0];
}
fn elapsed(self: *TimeKeeper) u32 {
return self.capture() -% self.start_time;
}
fn prepare(self: *TimeKeeper, duration: u32) void {
self.duration = duration;
self.reset();
}
fn isFinished(self: *TimeKeeper) bool {
return self.elapsed() >= self.duration;
}
fn reset(self: *TimeKeeper) void {
self.start_time = self.capture();
}
fn wait(self: *TimeKeeper) void {
while (!self.isFinished()) {}
self.reset();
}
pub fn delay(duration: u32) void {
var time_keeper: TimeKeeper = undefined;
time_keeper.prepare(duration);
time_keeper.wait();
}
};
pub fn TimerInstance(instance_address: u32) type {
return struct {
pub fn capture() u32 {
capture_tasks[0] = 1;
return capture_compare_registers[0];
}
pub fn prepare() void {
registers.mode = 0x0;
registers.bit_mode = if (instance_address == 0x40008000) @as(u32, 0x3) else 0x0;
registers.prescaler = if (instance_address == 0x40008000) @as(u32, 4) else 9;
tasks.start = 1;
const now = capture();
var i: u32 = 0;
while (capture() == now) : (i += 1) {
if (i == 1000) {
panicf("timer {} is not responding", .{instance_address});
}
}
// panicf("timer {} responded {} now {} capture {}", .{instance_address, i, now, capture()});
}
pub const capture_compare_registers = mmio(instance_address + 0x540, [4]u32);
pub const capture_tasks = mmio(instance_address + 0x040, [4]u32);
pub const events = struct {
pub const compare = mmio(instance_address + 0x140, [4]u32);
};
pub const registers = mmio(instance_address + 0x504, extern struct {
mode: u32,
bit_mode: u32,
unused0x50c: u32,
prescaler: u32,
});
pub const short_cuts = mmio(instance_address + 0x200, extern struct {
shorts: u32,
});
pub const tasks = mmio(instance_address + 0x000, extern struct {
start: u32,
stop: u32,
count: u32,
clear: u32,
});
};
}
pub const Uart = struct {
var stream: std.io.OutStream(Uart, stream_error, writeTextError) = undefined;
var tx_busy: bool = undefined;
var tx_queue: [3]u8 = undefined;
var tx_queue_read: usize = undefined;
var tx_queue_write: usize = undefined;
var updater: ?fn () void = undefined;
pub fn drainTxQueue() void {
while (tx_queue_read != tx_queue_write) {
loadTxd();
}
}
pub fn prepare() void {
updater = null;
Gpio.registers.direction_set = Gpio.registers_masks.uart_tx;
registers.pin_select_rxd = @ctz(u32, Gpio.registers_masks.uart_rx);
registers.pin_select_txd = @ctz(u32, Gpio.registers_masks.uart_tx);
registers.enable = 0x04;
tasks.start_rx = 1;
tasks.start_tx = 1;
tx_busy = false;
tx_queue_read = 0;
tx_queue_write = 0;
}
pub fn isReadByteReady() bool {
return events.rx_ready == 1;
}
pub fn format(comptime fmt: []const u8, args: var) void {
std.fmt.format(stream, fmt, args) catch |_| {};
}
pub fn loadTxd() void {
if (tx_queue_read != tx_queue_write and (!tx_busy or events.tx_ready == 1)) {
events.tx_ready = 0;
registers.txd = tx_queue[tx_queue_read];
tx_queue_read = (tx_queue_read + 1) % tx_queue.len;
tx_busy = true;
if (updater) |an_updater| {
an_updater();
}
}
}
pub fn log(comptime fmt: []const u8, args: var) void {
format(fmt ++ "\n", args);
}
pub fn readByte() u8 {
events.rx_ready = 0;
return @truncate(u8, registers.rxd);
}
pub fn setUpdater(new_updater: fn () void) void {
updater = new_updater;
}
pub fn update() void {
loadTxd();
}
pub fn writeByteBlocking(byte: u8) void {
const next = (tx_queue_write + 1) % tx_queue.len;
while (next == tx_queue_read) {
loadTxd();
}
tx_queue[tx_queue_write] = byte;
tx_queue_write = next;
loadTxd();
}
pub fn writeText(buffer: []const u8) void {
for (buffer) |c| {
switch (c) {
'\n' => {
writeByteBlocking('\r');
writeByteBlocking('\n');
},
else => writeByteBlocking(c),
}
}
}
pub fn writeTextError(context: Uart, buffer: []const u8) stream_error!u32 {
writeText(buffer);
return buffer.len;
}
const stream_error = error{UartError};
const events = mmio(0x40002108, extern struct {
rx_ready: u32,
unused0x10c: u32,
unused0x110: u32,
unused0x114: u32,
unused0x118: u32,
tx_ready: u32,
unused0x120: u32,
error_detected: u32,
});
const error_registers = mmio(0x40002480, extern struct {
error_source: u32,
});
const registers = mmio(0x40002500, extern struct {
enable: u32,
unused0x504: u32,
pin_select_rts: u32,
pin_select_txd: u32,
pin_select_cts: u32,
pin_select_rxd: u32,
rxd: u32,
txd: u32,
unused0x520: u32,
baud_rate: u32,
});
const tasks = mmio(0x40002000, extern struct {
start_rx: u32,
stop_rx: u32,
start_tx: u32,
stop_tx: u32,
});
};
pub const Uicr = struct {
pub fn dump() void {
for (contents) |word, i| {
log("{x:2} {x:8}", .{ i * 4, word });
}
}
pub const contents = @intToPtr(*[64]u32, 0x10001000);
};
pub const Wdt = struct {
pub const reload_request_registers = mmio(0x40010600, extern struct {
reload_request: [8]u32,
});
pub const registers = mmio(0x40010504, extern struct {
counter_reset_value: u32,
reload_rewuest_enable: u32,
});
pub const tasks = mmio(0x40010000, extern struct {
start: u32,
});
};
pub fn hangf(comptime fmt: []const u8, args: var) noreturn {
log(fmt, args);
Uart.drainTxQueue();
while (true) {}
}
pub fn mmio(address: u32, comptime mmio_type: type) *volatile mmio_type {
return @intToPtr(*volatile mmio_type, address);
}
pub fn panic(message: []const u8, trace: ?*builtin.StackTrace) noreturn {
if (Exceptions.panic_handler) |handler| {
handler(message, trace);
} else {
panicf("panic(): {}", .{message});
}
}
pub fn panicf(comptime fmt: []const u8, args: var) noreturn {
@setCold(true);
if (Exceptions.already_panicking) {
hangf("\npanicked during panic", .{});
}
Exceptions.already_panicking = true;
log("\npanicf(): " ++ fmt, args);
var it = std.debug.StackIterator.init(null, null);
while (it.next()) |stacked_address| {
dumpReturnAddress(stacked_address - 1);
}
hangf("panic completed", .{});
}
fn dumpReturnAddress(return_address: usize) void {
var symbol_index: usize = 0;
var line: []const u8 = "";
var i: u32 = 0;
while (i < symbols.len) {
var j: u32 = i;
while (symbols[j] != '\n') {
j += 1;
}
const next_line = symbols[i..j];
const symbol_address = std.fmt.parseUnsigned(usize, next_line[0..8], 16) catch 0;
if (symbol_address >= return_address) {
break;
}
line = next_line;
i = j + 1;
}
if (line.len >= 3) {
log("{x:5} in {}", .{ return_address, line[3..] });
} else {
log("{x:5}", .{return_address});
}
}
fn typicalVectorTable(comptime mission_id: u32) []const u8 {
var buf: [1]u8 = undefined;
const mission_id_string = std.fmt.bufPrint(&buf, "{}", .{mission_id}) catch |_| panicf("", .{});
for (mission_id_string) |*space| {
if (space.* == ' ') {
space.* = '0';
} else {
break;
}
}
return ".section .text.start.mission" ++ mission_id_string ++ "\n" ++
".globl mission" ++ mission_id_string ++ "_vector_table\n" ++
".balign 0x80\n" ++
"mission" ++ mission_id_string ++ "_vector_table:\n" ++
" .long 0x20004000 // sp top of 16KB\n" ++
" .long mission" ++ mission_id_string ++ "_main\n" ++
\\ .long lib_exceptionNumber02
\\ .long lib_exceptionNumber03
\\ .long lib_exceptionNumber04
\\ .long lib_exceptionNumber05
\\ .long lib_exceptionNumber06
\\ .long lib_exceptionNumber07
\\ .long lib_exceptionNumber08
\\ .long lib_exceptionNumber09
\\ .long lib_exceptionNumber10
\\ .long lib_exceptionNumber11
\\ .long lib_exceptionNumber12
\\ .long lib_exceptionNumber13
\\ .long lib_exceptionNumber14
\\ .long lib_exceptionNumber15
;
}
export fn lib_exceptionNumber01() noreturn {
Exceptions.handle(01);
}
export fn lib_exceptionNumber02() noreturn {
Exceptions.handle(02);
}
export fn lib_exceptionNumber03() noreturn {
Exceptions.handle(03);
}
export fn lib_exceptionNumber04() noreturn {
Exceptions.handle(04);
}
export fn lib_exceptionNumber05() noreturn {
Exceptions.handle(05);
}
export fn lib_exceptionNumber06() noreturn {
Exceptions.handle(06);
}
export fn lib_exceptionNumber07() noreturn {
Exceptions.handle(07);
}
export fn lib_exceptionNumber08() noreturn {
Exceptions.handle(08);
}
export fn lib_exceptionNumber09() noreturn {
Exceptions.handle(09);
}
export fn lib_exceptionNumber10() noreturn {
Exceptions.handle(10);
}
export fn lib_exceptionNumber11() noreturn {
Exceptions.handle(11);
}
export fn lib_exceptionNumber12() noreturn {
Exceptions.handle(12);
}
export fn lib_exceptionNumber13() noreturn {
Exceptions.handle(13);
}
export fn lib_exceptionNumber14() noreturn {
Exceptions.handle(14);
}
export fn lib_exceptionNumber15() noreturn {
Exceptions.handle(15);
}
const builtin = std.builtin;
const format = Uart.format;
const std = @import("std");
const symbols = @embedFile("symbols.txt");
extern var __bss_start: u8;
extern var __bss_end: u8;
extern var __debug_info_start: u8;
extern var __debug_info_end: u8;
extern var __debug_abbrev_start: u8;
extern var __debug_abbrev_end: u8;
extern var __debug_str_start: u8;
extern var __debug_str_end: u8;
extern var __debug_line_start: u8;
extern var __debug_line_end: u8;
extern var __debug_ranges_start: u8;
extern var __debug_ranges_end: u8;
pub const log = Uart.log;
pub const ram_u32 = @intToPtr(*volatile [4096]u32, 0x20000000);
pub const I2c0 = I2cInstance(0x40003000);
pub const I2c1 = I2cInstance(0x40004000);
pub const Timer0 = TimerInstance(0x40008000);
pub const Timer1 = TimerInstance(0x40009000);
pub const Timer2 = TimerInstance(0x4000a000);
};
pub const typical = struct {
pub const Adc = lib.Adc;
pub const assert = std.debug.assert;
pub const Bss = lib.Bss;
pub const builtin = std.builtin;
pub const ClockManagement = lib.ClockManagement;
pub const Exceptions = lib.Exceptions;
pub const Ficr = lib.Ficr;
pub const format = Uart.format;
pub const Gpio = lib.Gpio;
pub const Gpiote = lib.Gpiote;
pub const I2c0 = lib.I2c0;
pub const lib_basics = lib;
pub const log = Uart.log;
pub const math = std.math;
pub const mem = std.mem;
pub const LedMatrix = lib.LedMatrix;
pub const panic = lib.panic;
pub const panicf = lib.panicf;
pub const Power = lib.Power;
pub const Ppi = lib.Ppi;
pub const std = @import("std");
pub const SystemControlBlock = lib.SystemControlBlock;
pub const Temperature = lib.Temperature;
pub const Terminal = lib.Terminal;
pub const TimeKeeper = lib.TimeKeeper;
pub const Timer0 = lib.Timer0;
pub const Timer1 = lib.Timer1;
pub const Timer2 = lib.Timer2;
pub const typicalVectorTable = lib.typicalVectorTable;
pub const Uart = lib.Uart;
pub const Uicr = lib.Uicr;
pub const Wdt = lib.Wdt;
};
|
0 | repos | repos/zig-bare-metal-microbit/qemu.sh | #!/bin/bash
set -e
export PATH=~/zig:$PATH
MISSION_NUMBER=${1:-00}
SOURCE=$(ls mission${MISSION_NUMBER}_*.zig)
ARCH=thumbv6m
echo $SOURCE
echo zig version $(zig version)
zig fmt $SOURCE
touch symbols.txt
zig build -Dmain=$SOURCE
qemu-system-arm -kernel zig-cache/bin/main.img -display none -serial stdio -M microbit
llvm-objdump -x --source zig-cache/bin/main > main.asm
grep '^00000000.*:$' main.asm | sed 's/^00000000//' > symbols.txt
ls -lt symbols.txt
zig build qemu -Dmain=$SOURCE
#ls -l zig-cache/bin/main.img main.hex symbols.txt
#set +e
#grep unknown main.asm | grep -v '00 00 00 00'
#grep 'q[0-9].*#' main.asm | egrep -v '#(-|)(16|32|48|64|80|96|112|128)'
#set -e
#cp main.hex ~/microbit1/ & cp main.hex ~/microbit2/
#sync
|
0 | repos | repos/zig-bare-metal-microbit/test.sh | #!/bin/bash
set -e
export PATH=~/zig:$PATH
MISSION_NUMBER=${1:-0}
SOURCE=$(ls mission${MISSION_NUMBER}_*.zig)
ARCH=thumbv6m
echo $SOURCE
echo zig version $(zig version)
zig fmt $SOURCE
touch symbols.txt
zig build -Dmain=$SOURCE
llvm-objdump -x --source zig-cache/bin/main > main.asm
grep '^00000000.*:$' main.asm | sed 's/^00000000//' > symbols.txt
ls -lt symbols.txt
echo did not use newest symbols.txt
#zig build -Dmain=$SOURCE
ls -l zig-cache/bin/main.img main.hex
#set +e
#grep unknown main.asm | grep -v '00 00 00 00'
#grep 'q[0-9].*#' main.asm | egrep -v '#(-|)(16|32|48|64|80|96|112|128)'
#set -e
cp main.hex ~/microbit1/ & cp main.hex ~/microbit2/
sync
|
0 | repos | repos/zig-bare-metal-microbit/build.sh | #!/bin/bash
set -e
ARCH=thumbv6m
SOURCE=$(ls mission0*.zig)
echo zig version $(zig version)
zig fmt *.zig
touch symbols.txt
zig build
llvm-objdump-6.0 --source zig-cache/bin/main > main.asm
grep '^00000000.*:$' main.asm | sed 's/^00000000//' > symbols.txt
zig build
#llvm-objdump -x --source main > asm.$ARCH
#set +e
#grep unknown asm.$ARCH | grep -v '00 00 00 00'
#grep 'q[0-9].*#' asm.$ARCH | egrep -v '#(-|)(16|32|48|64|80|96|112|128)'
#set -e
ls -l main.hex zig-cache/bin/main.img symbols.txt
|
0 | repos | repos/zig-bare-metal-microbit/mission3_sensors.zig | export fn mission3_main() noreturn {
Bss.prepare();
Exceptions.prepare();
Uart.prepare();
Timer0.prepare();
Timer1.prepare();
Timer2.prepare();
LedMatrix.prepare();
ClockManagement.prepareHf();
CycleActivity.prepare();
TerminalActivity.prepare();
I2c0.prepare();
Accel.prepare();
while (true) {
CycleActivity.update();
TerminalActivity.update();
}
}
const Accel = struct {
fn prepare() void {
var data_buf: [0x32]u8 = undefined;
data_buf[orientation_configuration_register] = orientation_configuration_register_mask_enable;
I2c0.writeBlockingPanic(device_address, &data_buf, orientation_configuration_register, orientation_configuration_register);
data_buf[control_register1] = control_register1_mask_active;
I2c0.writeBlockingPanic(device_address, &data_buf, control_register1, control_register1);
}
fn update() void {
var data_buf: [32]u8 = undefined;
I2c0.readBlockingPanic(device_address, &data_buf, orientation_register, orientation_register);
const orientation = data_buf[orientation_register];
if (orientation & orientation_register_mask_changed != 0) {
format("orientation: 0x{x} ", .{orientation});
if (orientation & orientation_register_mask_forward_backward != 0) {
format("forward ", .{});
} else {
format("backward ", .{});
}
if (orientation & orientation_register_mask_z_lock_out != 0) {
log("up/down/left/right is unknown", .{});
} else {
const direction = (orientation & orientation_register_mask_direction) >> @ctz(u5, orientation_register_mask_direction);
switch (direction) {
0 => {
log("up", .{});
},
1 => {
log("down", .{});
},
2 => {
log("right", .{});
},
3 => {
log("left", .{});
},
else => {
unreachable;
},
}
}
}
}
const control_register1 = 0x2a;
const control_register1_mask_active = 0x01;
const device_address = 0x1d;
const orientation_register = 0x10;
const orientation_register_mask_changed = 0x80;
const orientation_register_mask_direction = 0x06;
const orientation_register_mask_forward_backward = 0x01;
const orientation_register_mask_z_lock_out = 0x40;
const orientation_configuration_register = 0x11;
const orientation_configuration_register_mask_enable = 0x40;
};
const CycleActivity = struct {
var cycle_counter: u32 = undefined;
var cycle_time: u32 = undefined;
var last_cycle_start: ?u32 = undefined;
var max_cycle_time: u32 = undefined;
var up_time_seconds: u32 = undefined;
var up_timer: TimeKeeper = undefined;
fn prepare() void {
cycle_counter = 0;
cycle_time = 0;
last_cycle_start = null;
max_cycle_time = 0;
up_time_seconds = 0;
up_timer.prepare(1000 * 1000);
}
fn update() void {
cycle_counter += 1;
const new_cycle_start = Timer0.capture();
if (last_cycle_start) |start| {
cycle_time = new_cycle_start -% start;
max_cycle_time = math.max(cycle_time, max_cycle_time);
}
last_cycle_start = new_cycle_start;
if (up_timer.isFinished()) {
up_timer.reset();
up_time_seconds += 1;
Accel.update();
}
}
};
const TerminalActivity = struct {
var keyboard_column: u32 = undefined;
var prev_now: u32 = undefined;
var temperature: u32 = 0;
fn prepare() void {
keyboard_column = 1;
prev_now = CycleActivity.up_time_seconds;
Temperature.tasks.start = 1;
redraw();
}
fn redraw() void {
Terminal.clearScreen();
Terminal.setScrollingRegion(5, 99);
Terminal.move(5 - 1, 1);
log("keyboard input will be echoed below:", .{});
Terminal.move(99, keyboard_column);
}
fn update() void {
if (Uart.isReadByteReady()) {
const byte = Uart.readByte();
switch (byte) {
3 => {
SystemControlBlock.requestSystemReset();
},
12 => {
redraw();
},
27 => {
Uart.writeByteBlocking('$');
keyboard_column += 1;
},
'\r' => {
Uart.writeText("\n");
keyboard_column = 1;
},
else => {
Uart.writeByteBlocking(byte);
keyboard_column += 1;
},
}
}
Uart.update();
if (Temperature.events.data_ready != 0) {
Temperature.events.data_ready = 0;
temperature = Temperature.registers.temperature;
}
const now = CycleActivity.up_time_seconds;
if (now >= prev_now + 1) {
Terminal.hideCursor();
Terminal.move(1, 1);
Terminal.line("up {:3}s cycle {}us max {}us {}.{}C", .{ CycleActivity.up_time_seconds, CycleActivity.cycle_time, CycleActivity.max_cycle_time, temperature / 4, temperature % 4 * 25 });
Terminal.showCursor();
Terminal.move(99, keyboard_column);
prev_now = now;
}
}
};
comptime {
const mission_id = 3;
asm (typicalVectorTable(mission_id));
}
usingnamespace @import("lib_basics.zig").typical;
|
0 | repos | repos/zig-bare-metal-microbit/linker.ld | ENTRY(_start)
SECTIONS {
/DISCARD/ : {
*(.ARM.exidx)
}
. = 0x0;
.text : {
KEEP(*(.text.start.mission0))
KEEP(*(.text.start.*))
*(.text)
}
.rodata : {
*(.rodata)
# __debug_info_start = .;
# KEEP(*(.debug_info))
# __debug_info_end = .;
# __debug_abbrev_start = .;
# KEEP(*(.debug_abbrev))
# __debug_abbrev_end = .;
# __debug_str_start = .;
# KEEP(*(.debug_str))
# __debug_str_end = .;
# __debug_line_start = .;
# KEEP(*(.debug_line))
# __debug_line_end = .;
# __debug_ranges_start = .;
# KEEP(*(.debug_ranges))
# __debug_ranges_end = .;
}
. = 0x20000000;
.data : {
*(.data)
}
.bss : {
__bss_start = .;
*(COMMON)
*(.bss)
__bss_end = .;
}
}
|
0 | repos | repos/zig-bare-metal-microbit/makehex.zig | pub fn main() !void {
const cwd = fs.cwd();
const image = try cwd.openFile("zig-cache/bin/main.img", fs.File.OpenFlags{});
defer image.close();
const hex = try cwd.createFile("main.hex", fs.File.CreateFlags{});
defer hex.close();
var offset: usize = 0;
var read_buf: [4 * 1024 * 1024]u8 = undefined;
assert(read_buf.len % 32 == 0);
while (true) {
var n = try image.read(&read_buf);
if (n == 0) {
break;
}
while (offset < n) {
if (offset % 0x10000 == 0) {
try writeRecord(hex, 0, 0x04, &[_]u8{ @truncate(u8, offset >> 24), @truncate(u8, offset >> 16) });
}
const i = math.min(32, n - offset);
try writeRecord(hex, offset % 0x10000, 0x00, read_buf[offset .. offset + i]);
offset += i;
}
}
try writeRecord(hex, 0, 0x01, &[_]u8{});
}
fn writeRecord(file: fs.File, offset: usize, code: u8, bytes: []u8) !void {
var record_buf: [1 + 2 + 1 + 32 + 1]u8 = undefined;
var record: []u8 = record_buf[0 .. 1 + 2 + 1 + bytes.len + 1];
record[0] = @truncate(u8, bytes.len);
record[1] = @truncate(u8, offset >> 8);
record[2] = @truncate(u8, offset >> 0);
record[3] = code;
for (bytes) |b, i| {
record[4 + i] = b;
}
var checksum: u8 = 0;
for (record[0 .. record.len - 1]) |b| {
checksum = checksum -% b;
}
record[record.len - 1] = checksum;
var line_buf: [1 + record_buf.len * 2 + 1]u8 = undefined;
_ = try file.write(try fmt.bufPrint(&line_buf, ":{X}\n", .{record}));
}
const assert = std.debug.assert;
const fmt = std.fmt;
const fs = std.fs;
const math = std.math;
const std = @import("std");
|
0 | repos | repos/zig-bare-metal-microbit/mission2_model_railroad_pwm.zig | export fn mission2_main() noreturn {
Bss.prepare();
Uart.prepare();
Timer0.prepare();
Timer1.prepare();
Timer2.prepare();
LedMatrix.prepare();
CycleActivity.prepare();
TerminalActivity.prepare();
ThrottleActivity.prepare();
Uart.setUpdater(LedMatrix.update);
while (true) {
CycleActivity.update();
TerminalActivity.update();
ThrottleActivity.update();
}
}
const CycleActivity = struct {
var cycle_counter: u32 = undefined;
var cycle_time: u32 = undefined;
var cycles_per_second: u32 = undefined;
var last_cycle_counter: u32 = undefined;
var last_cycle_start: ?u32 = undefined;
var max_cycle_time: u32 = undefined;
var up_time_seconds: u32 = undefined;
var up_timer: TimeKeeper = undefined;
fn prepare() void {
cycle_counter = 0;
cycle_time = 0;
cycles_per_second = 1;
last_cycle_counter = 0;
last_cycle_start = null;
max_cycle_time = 0;
up_time_seconds = 0;
up_timer.prepare(1000 * 1000);
}
fn update() void {
LedMatrix.update();
cycle_counter += 1;
const new_cycle_start = Timer0.capture();
if (up_timer.isFinished()) {
up_timer.reset();
up_time_seconds += 1;
cycles_per_second = cycle_counter -% last_cycle_counter;
last_cycle_counter = cycle_counter;
}
if (last_cycle_start) |start| {
cycle_time = new_cycle_start -% start;
max_cycle_time = math.max(cycle_time, max_cycle_time);
}
last_cycle_start = new_cycle_start;
}
};
const ThrottleActivity = struct {
var buttons: [2]Button = undefined;
var pwm_loop_back_counter: u32 = undefined;
fn loopBackPercent() u32 {
return pwm_loop_back_counter * 100 * 1000 / CycleActivity.cycles_per_second / 1000;
}
fn prepare() void {
pwm_loop_back_counter = 0;
Throttle.prepare();
for (buttons) |*b, i| {
b.prepare(i);
}
LedScroller.prepare();
redraw();
update();
}
fn redraw() void {
for (buttons) |*b| {
b.draw();
}
}
fn releaseSimulatedButtons() void {
for (buttons) |*b| {
if (b.is_simulation_pressed) {
b.toggleSimulated();
}
}
}
fn update() void {
if (Gpio.registers.in & Gpio.registers_masks.ring0 != 0) {
pwm_loop_back_counter += 1;
}
for (buttons) |*button| {
button.update();
}
LedScroller.update();
}
const Button = struct {
down_count: u32,
index: u32,
is_pressed: bool,
is_simulation_pressed: bool,
mask: u32,
up_count: u32,
fn draw(self: *Button) void {
Terminal.hideCursor();
Terminal.move(6, 10 + self.index * 31);
if (self.is_pressed) {
Terminal.attribute(44);
Uart.writeText(self.name());
Uart.writeText(" down");
Terminal.attribute(0);
} else {
Uart.writeText(self.name());
Uart.writeText(" ");
}
}
fn name(self: *Button) []const u8 {
return if (self.index == 0) "A" else "B";
}
fn prepare(self: *Button, index: u32) void {
self.down_count = 0;
self.index = index;
self.is_pressed = false;
self.is_simulation_pressed = false;
self.up_count = 0;
if (index == 0) {
self.mask = Gpio.registers_masks.button_a_active_low;
} else if (index == 1) {
self.mask = Gpio.registers_masks.button_b_active_low;
}
Gpio.config[@ctz(u32, self.mask)] = Gpio.config_masks.input;
self.update();
}
fn toggleSimulated(self: *Button) void {
self.is_simulation_pressed = !self.is_simulation_pressed;
self.update();
}
fn update(self: *Button) void {
const new = Gpio.registers.in & self.mask == 0 or self.is_simulation_pressed;
if (new != self.is_pressed) {
self.is_pressed = new;
self.draw();
TerminalActivity.restoreInputLine();
if (self.is_pressed) {
self.down_count += 1;
if (self.index == 0 and !buttons[1].is_pressed) {
Throttle.movePercent("button A pressed", -5);
} else if (self.index == 1 and !buttons[0].is_pressed) {
Throttle.movePercent("button B pressed", 5);
} else {
Throttle.setPercent("Both buttons A and B pressed (reset throttle to 0%)", 0);
}
} else {
self.up_count += 1;
}
}
}
};
const LedScroller = struct {
var column: u32 = undefined;
var displayed_percent: u32 = undefined;
var text: []u8 = undefined;
var text_buf: [text_len_max]u8 = undefined;
const text_len_max = 4;
var timer: TimeKeeper = undefined;
fn prepare() void {
column = 0;
text = text_buf[0..0];
timer.prepare(100 * 1000);
}
fn update() void {
if (timer.isFinished()) {
timer.reset();
var index = column / 6;
if (column % 6 == 0) {
if (index == text.len) {
if (text.len == 0 or Throttle.percent != displayed_percent) {
displayed_percent = Throttle.percent;
text = text_buf[0..2];
text[0] = ' ';
if (displayed_percent < 10) {
text[1] = '0' + @truncate(u8, displayed_percent % 10);
} else if (displayed_percent < 100) {
text = text_buf[0..3];
text[1] = '0' + @truncate(u8, displayed_percent / 10);
text[2] = '0' + @truncate(u8, displayed_percent % 10);
} else {
text = text_buf[0..4];
text[1] = '1';
text[2] = '0';
text[3] = '0';
}
if (displayed_percent == 0) {
log("scrolling '0' just once", .{});
} else {
log("scrolling '{}' repeatedly", .{text});
}
} else if (displayed_percent == 0) {
return;
}
column = 0;
index = 0;
}
}
const mask: u32 = 0b1111011110111101111011110;
const right = if (column % 6 == 0) 0 else LedMatrix.getImage(text[index]) >> @truncate(u5, 5 - column % 6);
LedMatrix.putImage(LedMatrix.image << 1 & mask | (right & ~mask));
column += 1;
}
}
};
const Throttle = struct {
var pwm_width_ticks: u32 = undefined;
const pwm_width_ticks_max = 312;
var percent: u32 = undefined;
fn movePercent(message: []const u8, delta: i32) void {
setPercent(message, @intCast(i32, percent) + delta);
}
fn prepare() void {
percent = 0;
Gpio.config[02] = Gpio.config_masks.output;
Gpio.config[03] = Gpio.config_masks.input;
Ppi.setChannelEventAndTask(0, &Timer1.events.compare[0], &Gpiote.tasks.out[0]);
Ppi.setChannelEventAndTask(1, &Timer1.events.compare[1], &Gpiote.tasks.out[0]);
Timer1.short_cuts.shorts = 0x002;
Timer1.capture_compare_registers[1] = pwm_width_ticks_max;
}
fn setPercent(message: []const u8, new: i32) void {
const new_percent = @intCast(u32, math.min(math.max(new, 0), 100));
if (new_percent != percent) {
log("{}: throttle changed from {} to {}", .{ message, percent, new_percent });
} else {
log("{}: throttle remains at {}%", .{ message, percent });
}
percent = new_percent;
Timer1.tasks.stop = 1;
const ppi_channels_0_and_1_mask = 1 << 0 | 1 << 1;
Ppi.registers.channel_enable_clear = ppi_channels_0_and_1_mask;
Gpiote.config[0] = Gpiote.config_masks.disable;
Gpio.registers.out_clear = Gpio.registers_masks.ring1;
pwm_width_ticks = 0;
if (percent == 100) {
Gpio.registers.out_set = Gpio.registers_masks.ring1;
} else if (percent > 0) {
pwm_width_ticks = 1000 * (100 - percent) * pwm_width_ticks_max / (100 * 1000);
Timer1.capture_compare_registers[0] = pwm_width_ticks;
Gpio.registers.out_clear = Gpio.registers_masks.ring1;
Gpiote.config[0] = 0x30203;
Ppi.registers.channel_enable_set = ppi_channels_0_and_1_mask;
Timer1.tasks.clear = 1;
Timer1.tasks.start = 1;
}
}
};
};
const TerminalActivity = struct {
var keyboard_column: u32 = undefined;
var prev_led_image: u32 = undefined;
var prev_now: u32 = undefined;
fn prepare() void {
keyboard_column = 1;
prev_led_image = 0;
prev_now = CycleActivity.up_time_seconds;
redraw();
}
fn redraw() void {
Terminal.clearScreen();
Terminal.setScrollingRegion(status_display_lines, 99);
Terminal.move(status_display_lines - 1, 1);
log("keyboard input will be echoed below:", .{});
restoreInputLine();
}
fn restoreInputLine() void {
Terminal.move(999, TerminalActivity.keyboard_column);
}
fn update() void {
if (Uart.isReadByteReady()) {
const byte = Uart.readByte();
switch (byte) {
27 => {
Uart.writeByteBlocking('$');
keyboard_column += 1;
},
'a' => {
ThrottleActivity.releaseSimulatedButtons();
ThrottleActivity.buttons[0].toggleSimulated();
ThrottleActivity.buttons[0].toggleSimulated();
},
'b' => {
ThrottleActivity.releaseSimulatedButtons();
ThrottleActivity.buttons[1].toggleSimulated();
ThrottleActivity.buttons[1].toggleSimulated();
},
'c' => {
ThrottleActivity.releaseSimulatedButtons();
ThrottleActivity.buttons[0].toggleSimulated();
ThrottleActivity.buttons[1].toggleSimulated();
ThrottleActivity.buttons[0].toggleSimulated();
ThrottleActivity.buttons[1].toggleSimulated();
},
'A' => {
ThrottleActivity.buttons[0].toggleSimulated();
},
'B' => {
ThrottleActivity.buttons[1].toggleSimulated();
},
3 => {
SystemControlBlock.requestSystemReset();
},
12 => {
keyboard_column = 1;
TerminalActivity.prev_led_image = 0;
TerminalActivity.redraw();
ThrottleActivity.redraw();
},
'\r' => {
Uart.writeText("\n");
keyboard_column = 1;
},
else => {
Uart.writeByteBlocking(byte);
keyboard_column += 1;
},
}
}
Uart.update();
const now = CycleActivity.up_time_seconds;
if (now >= prev_now + 1) {
Terminal.hideCursor();
Terminal.move(1, 1);
Terminal.line("up {:3}s cycle {}Hz {}us max {}us led max {}us", .{ CycleActivity.up_time_seconds, CycleActivity.cycles_per_second, CycleActivity.cycle_time, CycleActivity.max_cycle_time, LedMatrix.max_elapsed });
Terminal.line("throttle {:2}% pwm {:2}% cc0 {} raw {}", .{ ThrottleActivity.Throttle.percent, ThrottleActivity.loopBackPercent(), ThrottleActivity.Throttle.pwm_width_ticks, ThrottleActivity.pwm_loop_back_counter });
Terminal.showCursor();
restoreInputLine();
prev_now = now;
ThrottleActivity.pwm_loop_back_counter = 0;
} else if (LedMatrix.image != prev_led_image) {
Terminal.hideCursor();
Terminal.attribute(33);
var mask: u32 = 0x1;
var y: i32 = 4;
while (y >= 0) : (y -= 1) {
var x: i32 = 4;
while (x >= 0) : (x -= 1) {
const v = LedMatrix.image & mask;
if (v != prev_led_image & mask) {
Terminal.move(@intCast(u32, 4 + y), @intCast(u32, 21 + 2 * x));
Uart.writeText(if (v != 0) "[]" else " ");
}
mask <<= 1;
}
}
prev_led_image = LedMatrix.image;
Terminal.attribute(0);
restoreInputLine();
}
}
};
comptime {
const mission_id = 2;
asm (typicalVectorTable(mission_id));
}
const status_display_lines = 6 + 5;
usingnamespace @import("lib_basics.zig").typical;
|
0 | repos | repos/zig-bare-metal-microbit/release-message.md | # Requires:
* a microbit and its usb cable
* a computer that has usb
# Steps:
* with the computer
* download the zip file and unzip it
* attach the microbit using its usb cable
* the microbit will present itself as a mass storage device
* copy main.hex to the microbit
# Operation:
* connect the microbit to the computer using the usb cable
* the microbit will present itself as a serial device
* use minicom or another terminal program to connent to the microbit
* you should observe log messages indicating the reception of ble advertisment packets
|
0 | repos | repos/zig-bare-metal-microbit/mission0_mission_selector.zig | export fn mission0_main() noreturn {
Bss.prepare();
Exceptions.prepare();
Mission.prepare();
Uart.prepare();
Timer0.prepare();
Timer1.prepare();
Timer2.prepare();
LedMatrix.prepare();
CycleActivity.prepare();
KeyboardActivity.prepare();
StatusActivity.prepare();
Mission.register(&mission1_vector_table, "turn on all leds without libraries", "mission1_turn_on_all_leds_without_libraries.zig");
Mission.register(&mission2_vector_table, "model railroad motor pwm controlled by buttons", "mission2_model_railroad_pwm.zig");
Mission.register(&mission3_vector_table, "sensors - temperature, orientation", "mission3_sensors.zig");
log("available missions:", .{});
for (Mission.missions) |*m, i| {
log("{}. {}", .{ i + 1, m.title });
}
while (true) {
CycleActivity.update();
KeyboardActivity.update();
StatusActivity.update();
}
}
const CycleActivity = struct {
var cycle_counter: u32 = undefined;
var cycle_time: u32 = undefined;
var last_cycle_start: ?u32 = undefined;
var last_second_ticks: u32 = undefined;
var max_cycle_time: u32 = undefined;
var up_time_seconds: u32 = undefined;
fn prepare() void {
cycle_counter = 0;
cycle_time = 0;
last_cycle_start = null;
last_second_ticks = 0;
max_cycle_time = 0;
up_time_seconds = 0;
}
fn update() void {
LedMatrix.update();
cycle_counter += 1;
const new_cycle_start = Timer0.capture();
if (new_cycle_start -% last_second_ticks >= 1000 * 1000) {
up_time_seconds += 1;
last_second_ticks = new_cycle_start;
}
if (last_cycle_start) |start| {
cycle_time = new_cycle_start -% start;
max_cycle_time = math.max(cycle_time, max_cycle_time);
}
last_cycle_start = new_cycle_start;
}
};
const KeyboardActivity = struct {
var column: u32 = undefined;
fn prepare() void {
column = 1;
}
fn update() void {
if (!Uart.isReadByteReady()) {
return;
}
const byte = Uart.readByte();
switch (byte) {
3 => {
SystemControlBlock.requestSystemReset();
},
12 => {
StatusActivity.redraw();
},
27 => {
Uart.writeByteBlocking('$');
column += 1;
},
'1', '2', '3', '4', '5', '6', '7', '8', '9' => {
Mission.missions[byte - '1'].activate();
},
'\r' => {
Uart.writeText("\n");
column = 1;
},
else => {
Uart.writeByteBlocking(byte);
column += 1;
},
}
}
};
const StatusActivity = struct {
var prev_now: u32 = undefined;
fn prepare() void {
prev_now = CycleActivity.up_time_seconds;
redraw();
}
fn redraw() void {
Terminal.clearScreen();
Terminal.setScrollingRegion(5, 99);
Terminal.move(5 - 1, 1);
log("keyboard input will be echoed below:", .{});
}
fn update() void {
Uart.loadTxd();
const now = CycleActivity.up_time_seconds;
if (now >= prev_now + 1) {
Terminal.hideCursor();
Terminal.move(1, 1);
Terminal.line("reset {x} up {:3}s cycle {}us max {}us", .{ Power.registers.reset_reason, CycleActivity.up_time_seconds, CycleActivity.cycle_time, CycleActivity.max_cycle_time });
Terminal.line("gpio.in {x:8}", .{Gpio.registers.in & ~@as(u32, 0x0300fff0)});
Terminal.line("", .{});
Terminal.showCursor();
restoreInputLine();
prev_now = now;
}
}
};
fn restoreInputLine() void {
Terminal.move(99, KeyboardActivity.column);
}
const Mission = struct {
title: []const u8,
panic: fn ([]const u8, ?*builtin.StackTrace) noreturn,
vector_table_address: *allowzero u32,
var missions: []Mission = undefined;
var missions_buf: [5]Mission = undefined;
fn activate(self: *Mission) void {
const reset_sp = @intToPtr(*allowzero u32, @ptrToInt(self.vector_table_address) + 0).*;
const reset_pc = @intToPtr(*allowzero u32, @ptrToInt(self.vector_table_address) + 4).*;
asm volatile (
\\ mov sp,%[reset_sp]
\\ bx %[reset_pc]
:
: [reset_pc] "{r0}" (reset_pc),
[reset_sp] "{r1}" (reset_sp)
);
}
fn prepare() void {
missions = missions_buf[0..0];
}
fn register(vector_table_address: *allowzero u32, comptime title: []const u8, comptime source_file: []const u8) void {
missions = missions_buf[0 .. missions.len + 1];
var m = &missions[missions.len - 1];
const import = @import(source_file);
m.title = title;
m.panic = import.panic;
m.vector_table_address = vector_table_address;
}
};
comptime {
const mission_id = 0;
asm (typicalVectorTable(mission_id));
}
const release_tag = "0.4";
const status_display_lines = 6 + 5;
extern var mission1_vector_table: u32;
extern var mission2_vector_table: u32;
extern var mission3_vector_table: u32;
usingnamespace @import("lib_basics.zig").typical;
|
0 | repos | repos/zig-bare-metal-microbit/README.md | # zig-bare-metal-microbit
See also [zig-bare-metal-raspberry-pi](https://github.com/markfirmware/zig-bare-metal-raspberry-pi) and [Awesome Zig Bootables](https://github.com/nrdmn/awesome-zig/blob/master/readme.md#Bootables)
* Displays "Z" on the leds
* Events from buttons A and B are broadcast on ble and when received are printed on the uart line
The goal is to replace the [ble buttons broadcaster](https://github.com/markfirmware/microbit-samples/blob/master/source/examples/blebuttonsbroadcaster/main.cpp) with zig on bare metal. This broadcaster is processed by [ultibo-ble-observer](https://github.com/markfirmware/ultibo-ble-observer/releases). Although it has no encryption, no privacy and no authentication, it is still useful for controlling a model railroad in a home or club setting, or at a demo.
* [microbit](https://tech.microbit.org)
* [runtime - not used in this bare-metal project](https://lancaster-university.github.io/microbit-docs/#)
* [led matrix display driver](https://github.com/lancaster-university/microbit-dal/blob/master/source/drivers/MicroBitDisplay.cpp)
* [nrf51822](https://infocenter.nordicsemi.com/pdf/nRF51822_PS_v3.1.pdf)
* [reference](https://infocenter.nordicsemi.com/pdf/nRF51_RM_v3.0.1.pdf)
* [arm cortex-m0](https://developer.arm.com/ip-products/processors/cortex-m/cortex-m0)
* [cortex m0 user's guide](https://static.docs.arm.com/dui0497/a/DUI0497A_cortex_m0_r0p0_generic_ug.pdf?_ga=2.60319917.1865497363.1577386349-160760379.1577386349)
* [armv6m](https://static.docs.arm.com/ddi0419/e/DDI0419E_armv6m_arm.pdf?_ga=2.152616249.101383920.1573135559-619929151.1573135559)
* [edge connector and pins](https://tech.microbit.org/hardware/edgeconnector)
* [pin assignments (sheet 5 of schematic)](https://github.com/bbcmicrobit/hardware/blob/master/SCH_BBC-Microbit_V1.3B.pdf)
|
0 | repos | repos/zig-bare-metal-microbit/build.zig | pub fn build(b: *std.build.Builder) !void {
const exec_name = "main";
const mode = b.standardReleaseOptions();
const main = b.option([]const u8, "main", "main file") orelse "mission0_mission_selector.zig";
const want_display = b.option(bool, "display", "graphics display for qemu") orelse false;
const exe = b.addExecutable(exec_name, main);
exe.install();
exe.installRaw("main.img");
exe.setBuildMode(mode);
exe.setLinkerScriptPath("linker.ld");
exe.setTarget(.{
.cpu_arch = .thumb,
.os_tag = .freestanding,
.abi = .none,
.cpu_model = .{ .explicit = &std.Target.arm.cpu.cortex_m0 },
});
const run_makehex = b.addSystemCommand(&[_][]const u8{
"zig", "run", "makehex.zig",
});
run_makehex.step.dependOn(&exe.step);
const qemu = b.step("qemu", "run in qemu");
const run_qemu = b.addSystemCommand(&[_][]const u8{
"qemu-system-arm",
"-kernel",
"zig-cache/bin/main.img",
"-M",
"microbit",
"-serial",
"stdio",
"-display",
if (want_display) "gtk" else "xnone",
});
qemu.dependOn(&run_qemu.step);
run_qemu.step.dependOn(&exe.step);
b.default_step.dependOn(&run_makehex.step);
}
const std = @import("std");
|
0 | repos | repos/zig-bare-metal-microbit/mission1_turn_on_all_leds_without_libraries.zig | export fn mission1_main() noreturn {
turnOnAllLeds();
while (true) {}
}
pub fn panic(message: []const u8, trace: ?*@import("std").builtin.StackTrace) noreturn {
while (true) {}
}
fn turnOnAllLeds() void {
const gpio_direction_set = @intToPtr(*volatile u32, 0x50000518);
const gpio_out_clear = @intToPtr(*volatile u32, 0x5000050c);
const gpio_out_set = @intToPtr(*volatile u32, 0x50000508);
const all_three_led_anode_pins_active_high: u32 = 0xe000;
const all_nine_led_cathode_pins_active_low: u32 = 0x1ff0;
gpio_direction_set.* = all_three_led_anode_pins_active_high | all_nine_led_cathode_pins_active_low;
gpio_out_set.* = all_three_led_anode_pins_active_high;
gpio_out_clear.* = all_nine_led_cathode_pins_active_low;
}
comptime {
asm (
\\.section .text.start.mission1
\\.globl mission1_vector_table
\\.balign 0x80
\\mission1_vector_table:
\\ .long 0x20004000 // sp top of 16KB ram
\\ .long mission1_main
);
}
|
0 | repos | repos/zig-tools/package.json | {
"name": "zig-tools",
"displayName": "Zig tools",
"description": "⚡ Zig tools for vscode",
"icon": "images/icon.png",
"publisher": "bwork",
"repository": {
"type": "git",
"url": "https://github.com/blockkwork/zig-tools"
},
"bugs": {
"url": "https://github.com/blockkwork/zig-tools/issues"
},
"version": "0.0.1",
"engines": {
"vscode": "^1.87.0"
},
"categories": [
"Snippets",
"Linters",
"Other"
],
"keywords": [
"zig",
"zls",
"zig formatter",
"zig snippets",
"zig linter",
"tools"
],
"activationEvents": [
"onLanguage:zig"
],
"main": "./out/extension.js",
"contributes": {
"configuration": {
"properties": {
"zig-tools.type hints": {
"type": "boolean",
"default": true,
"description": "Data type hints (ranges) on hover"
},
"zig-tools.type autocompletion": {
"type": "boolean",
"default": true,
"description": "Data type autocompletion"
},
"zig-tools.bitwise operation hints": {
"type": "boolean",
"default": true,
"markdownDescription": "Bitwise operation hints on hover (hover over the bitwise binary operator). Example:\n\n```zig\nconst _ = 2 << 10\nconst _ = 2 ^ 4\n```"
},
"zig-tools.hex hints": {
"type": "boolean",
"default": true,
"markdownDescription": "Converts a number from hexadecimal to decimal system. Hover over the number in hex system. Example: \n\n```zig\nconst _ = 0xf // hint: 15\n```"
}
}
}
},
"scripts": {
"vscode:prepublish": "npm run compile",
"compile": "tsc -p ./",
"watch": "tsc -watch -p ./",
"pretest": "npm run compile && npm run lint",
"lint": "eslint src --ext ts",
"test": "vscode-test"
},
"devDependencies": {
"@types/vscode": "^1.87.0",
"@types/mocha": "^10.0.6",
"@types/node": "18.x",
"@typescript-eslint/eslint-plugin": "^7.4.0",
"@typescript-eslint/parser": "^7.4.0",
"eslint": "^8.57.0",
"typescript": "^5.3.3",
"@vscode/test-cli": "^0.0.8",
"@vscode/test-electron": "^2.3.9"
}
} |
Subsets and Splits