From 1efa815db78808b70c7e0856a8ebb944376d82a2 Mon Sep 17 00:00:00 2001 From: Jerry Yu Date: Thu, 9 Sep 2021 15:42:32 +0800 Subject: [PATCH] tls13: add ecdh_read_public Signed-off-by: Jerry Yu --- library/ecdh.c | 58 +++++++++++++++++++++++++++++++++++++++++++++ library/ecdh_misc.h | 6 +++++ 2 files changed, 64 insertions(+) diff --git a/library/ecdh.c b/library/ecdh.c index b72bd1fe0..0067e0bd4 100644 --- a/library/ecdh.c +++ b/library/ecdh.c @@ -806,6 +806,64 @@ int mbedtls_ecdh_setup_no_everest( mbedtls_ecdh_context *ctx, #endif } +static int ecdh_tls1_3_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; + const unsigned char *end = buf + blen; + size_t data_len; + + if( end - p < 3 ) + return( MBEDTLS_ERR_ECP_BAD_INPUT_DATA ); + + data_len = MBEDTLS_GET_UINT16_BE( p, 0 ); + p += 2; + + if( data_len < 1 || data_len != ( blen - 2 ) ) + return( MBEDTLS_ERR_ECP_BAD_INPUT_DATA ); + + /* + * Save buffer start for read_binary and update buf + */ + if( ( ret = mbedtls_ecp_point_read_binary( &ctx->grp, + &ctx->Qp, p, data_len ) ) != 0) + { + return( ret ); + } + + return( 0 ); +} + +/* + * Parse and import the client's TLS 1.3 public value + */ +int mbedtls_ecdh_tls1_3_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_tls1_3_read_public_internal( ctx, buf, blen ) ); +#else + switch( ctx->var ) + { +#if defined(MBEDTLS_ECDH_VARIANT_EVEREST_ENABLED) + case MBEDTLS_ECDH_VARIANT_EVEREST: + return( MBEDTLS_ERR_ECP_FEATURE_UNAVAILABLE ); +#endif + case MBEDTLS_ECDH_VARIANT_MBEDTLS_2_0: + return( ecdh_tls1_3_read_public_internal( &ctx->ctx.mbed_ecdh, + buf, blen ) ); + default: + return MBEDTLS_ERR_ECP_BAD_INPUT_DATA; + } +#endif +} + #endif /* MBEDTLS_SSL_PROTO_TLS1_3_EXPERIMENTAL */ #endif /* MBEDTLS_ECDH_C */ diff --git a/library/ecdh_misc.h b/library/ecdh_misc.h index d1342f8b9..94d31394b 100644 --- a/library/ecdh_misc.h +++ b/library/ecdh_misc.h @@ -43,6 +43,12 @@ int mbedtls_ecdh_tls13_make_params( mbedtls_ecdh_context *ctx, size_t *olen, int ( *f_rng )( void *, unsigned char *, size_t ), void *p_rng ); +/* + * TLS 1.3 version of mbedtls_ecdh_read_public in ecdh.h + */ +int mbedtls_ecdh_tls1_3_read_public( mbedtls_ecdh_context *ctx, + const unsigned char *buf, + size_t blen ); #endif /* MBEDTLS_SSL_PROTO_TLS1_3_EXPERIMENTAL */