Commit 6e95d74f authored by Nathaniel Wesley Filardo's avatar Nathaniel Wesley Filardo Committed by Marcel Stör
Browse files

Update TLS protocol support (#2587)

* Update TLS protocol support

TLS1.0 is past PCI's EOL; BEAST is no more
Enable elliptic curve key exchanges
	Do not enable the smallest ECs for security
	Do not enable the largest ECs for computational time
	Do not enable 25519 (sad) because it doesn't go across the wire
Drop non-PFS key exchanges
Drop ARC4, Blowfish, DES, genprime, XTEA code
Drop renegotiation support completely
	It takes so much heap that it's not likely to work out well

Tidy handling of SSL_BUFFER_SIZE

Update docs
Drop mention of startcom, since they are no more, for letsencrypt

* Update mbedtls to 2.7.7

Preserve our vsnprintf and platform hacks

* Introduce TLS maximum fragment size knob

Reduce buffer size to 4Ki by default and advertize that.  That's the
largest we can advertize with the TLS MFL extension, so there's no
point in making them larger.  The truly adventurous can re-raise
SSL_BUFFER_SIZE and undefine the SSL_MAX_FRAGMENT_LENGTH_CODE and get
back to the earlier behavior.

* Default to mbedTLS debug with DEVELOP_VERSION
parent c6653b59
......@@ -38,9 +38,12 @@
#if defined(MBEDTLS_PKCS5_C)
#include "mbedtls/pkcs5.h"
#if defined(MBEDTLS_ASN1_PARSE_C)
#include "mbedtls/asn1.h"
#include "mbedtls/cipher.h"
#include "mbedtls/oid.h"
#endif /* MBEDTLS_ASN1_PARSE_C */
#include <string.h>
......@@ -51,6 +54,22 @@
#define mbedtls_printf printf
#endif
#if !defined(MBEDTLS_ASN1_PARSE_C)
int mbedtls_pkcs5_pbes2( const mbedtls_asn1_buf *pbe_params, int mode,
const unsigned char *pwd, size_t pwdlen,
const unsigned char *data, size_t datalen,
unsigned char *output )
{
((void) pbe_params);
((void) mode);
((void) pwd);
((void) pwdlen);
((void) data);
((void) datalen);
((void) output);
return( MBEDTLS_ERR_PKCS5_FEATURE_UNAVAILABLE );
}
#else
static int pkcs5_parse_pbkdf2_params( const mbedtls_asn1_buf *params,
mbedtls_asn1_buf *salt, int *iterations,
int *keylen, mbedtls_md_type_t *md_type )
......@@ -96,11 +115,9 @@ static int pkcs5_parse_pbkdf2_params( const mbedtls_asn1_buf *params,
if( ( ret = mbedtls_asn1_get_alg_null( &p, end, &prf_alg_oid ) ) != 0 )
return( MBEDTLS_ERR_PKCS5_INVALID_FORMAT + ret );
if( MBEDTLS_OID_CMP( MBEDTLS_OID_HMAC_SHA1, &prf_alg_oid ) != 0 )
if( mbedtls_oid_get_md_hmac( &prf_alg_oid, md_type ) != 0 )
return( MBEDTLS_ERR_PKCS5_FEATURE_UNAVAILABLE );
*md_type = MBEDTLS_MD_SHA1;
if( p != end )
return( MBEDTLS_ERR_PKCS5_INVALID_FORMAT +
MBEDTLS_ERR_ASN1_LENGTH_MISMATCH );
......@@ -213,6 +230,7 @@ exit:
return( ret );
}
#endif /* MBEDTLS_ASN1_PARSE_C */
int mbedtls_pkcs5_pbkdf2_hmac( mbedtls_md_context_t *ctx, const unsigned char *password,
size_t plen, const unsigned char *salt, size_t slen,
......@@ -231,8 +249,10 @@ int mbedtls_pkcs5_pbkdf2_hmac( mbedtls_md_context_t *ctx, const unsigned char *p
memset( counter, 0, 4 );
counter[3] = 1;
#if UINT_MAX > 0xFFFFFFFF
if( iteration_count > 0xFFFFFFFF )
return( MBEDTLS_ERR_PKCS5_BAD_INPUT_DATA );
#endif
while( key_length )
{
......
......@@ -181,6 +181,10 @@ static int pk_get_ecparams( unsigned char **p, const unsigned char *end,
{
int ret;
if ( end - *p < 1 )
return( 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
......@@ -857,7 +861,10 @@ static int pk_parse_key_sec1_der( mbedtls_ecp_keypair *eck,
mbedtls_ecp_keypair_free( eck );
return( 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.
......@@ -1261,7 +1268,6 @@ int mbedtls_pk_parse_key( mbedtls_pk_context *pk,
return( ret );
#endif /* MBEDTLS_PKCS12_C || MBEDTLS_PKCS5_C */
#else
((void) ret);
((void) pwd);
((void) pwdlen);
#endif /* MBEDTLS_PEM_PARSE_C */
......@@ -1277,6 +1283,9 @@ int mbedtls_pk_parse_key( mbedtls_pk_context *pk,
{
unsigned char *key_copy;
if( keylen == 0 )
return( MBEDTLS_ERR_PK_KEY_INVALID_FORMAT );
if( ( key_copy = mbedtls_calloc( 1, keylen ) ) == NULL )
return( MBEDTLS_ERR_PK_ALLOC_FAILED );
......@@ -1293,6 +1302,7 @@ int mbedtls_pk_parse_key( mbedtls_pk_context *pk,
return( 0 );
mbedtls_pk_free( pk );
mbedtls_pk_init( pk );
if( ret == MBEDTLS_ERR_PK_PASSWORD_MISMATCH )
{
......@@ -1304,39 +1314,42 @@ int mbedtls_pk_parse_key( mbedtls_pk_context *pk,
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( ( ret = mbedtls_pk_setup( pk, pk_info ) ) != 0 ||
( ret = pk_parse_key_pkcs1_der( mbedtls_pk_rsa( *pk ),
key, keylen ) ) != 0 )
{
mbedtls_pk_free( pk );
}
else
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( ( ret = mbedtls_pk_setup( pk, pk_info ) ) != 0 ||
( ret = pk_parse_key_sec1_der( mbedtls_pk_ec( *pk ),
key, keylen ) ) != 0 )
{
mbedtls_pk_free( pk );
}
else
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 );
}
......
......@@ -46,7 +46,14 @@ static void mbedtls_zeroize( void *v, size_t n ) {
}
#endif
#if defined(MBEDTLS_PLATFORM_MEMORY)
/* 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 )
{
......@@ -77,7 +84,9 @@ int mbedtls_platform_set_calloc_free( void * (*calloc_func)( size_t, size_t ),
mbedtls_free = free_func;
return( 0 );
}
#endif /* MBEDTLS_PLATFORM_MEMORY */
#endif /* MBEDTLS_PLATFORM_MEMORY &&
!( defined(MBEDTLS_PLATFORM_CALLOC_MACRO) &&
defined(MBEDTLS_PLATFORM_FREE_MACRO) ) */
#if defined(_WIN32)
#include <stdarg.h>
......@@ -91,7 +100,7 @@ int mbedtls_platform_win32_snprintf( char *s, size_t n, const char *fmt, ... )
return( -1 );
va_start( argp, fmt );
#if defined(_TRUNCATE)
#if defined(_TRUNCATE) && !defined(__MINGW32__)
ret = _vsnprintf_s( s, n, _TRUNCATE, fmt, argp );
#else
ret = _vsnprintf( s, n, fmt, argp );
......
......@@ -112,6 +112,13 @@ int mbedtls_ripemd160_starts_ret( mbedtls_ripemd160_context *ctx )
return( 0 );
}
#if !defined(MBEDTLS_DEPRECATED_REMOVED)
void mbedtls_ripemd160_starts( mbedtls_ripemd160_context *ctx )
{
mbedtls_ripemd160_starts_ret( ctx );
}
#endif
#if !defined(MBEDTLS_RIPEMD160_PROCESS_ALT)
/*
* Process one block
......@@ -295,6 +302,14 @@ int mbedtls_internal_ripemd160_process( mbedtls_ripemd160_context *ctx,
return( 0 );
}
#if !defined(MBEDTLS_DEPRECATED_REMOVED)
void mbedtls_ripemd160_process( mbedtls_ripemd160_context *ctx,
const unsigned char data[64] )
{
mbedtls_internal_ripemd160_process( ctx, data );
}
#endif
#endif /* !MBEDTLS_RIPEMD160_PROCESS_ALT */
/*
......@@ -349,6 +364,15 @@ int mbedtls_ripemd160_update_ret( mbedtls_ripemd160_context *ctx,
return( 0 );
}
#if !defined(MBEDTLS_DEPRECATED_REMOVED)
void mbedtls_ripemd160_update( mbedtls_ripemd160_context *ctx,
const unsigned char *input,
size_t ilen )
{
mbedtls_ripemd160_update_ret( ctx, input, ilen );
}
#endif
static const unsigned char ripemd160_padding[64] =
{
0x80, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
......@@ -395,6 +419,14 @@ int mbedtls_ripemd160_finish_ret( mbedtls_ripemd160_context *ctx,
return( 0 );
}
#if !defined(MBEDTLS_DEPRECATED_REMOVED)
void mbedtls_ripemd160_finish( mbedtls_ripemd160_context *ctx,
unsigned char output[20] )
{
mbedtls_ripemd160_finish_ret( ctx, output );
}
#endif
#endif /* ! MBEDTLS_RIPEMD160_ALT */
/*
......@@ -424,6 +456,15 @@ exit:
return( ret );
}
#if !defined(MBEDTLS_DEPRECATED_REMOVED)
void mbedtls_ripemd160( const unsigned char *input,
size_t ilen,
unsigned char output[20] )
{
mbedtls_ripemd160_ret( input, ilen, output );
}
#endif
#if defined(MBEDTLS_SELF_TEST)
/*
* Test vectors from the RIPEMD-160 paper and
......
......@@ -75,6 +75,7 @@ static void mbedtls_zeroize( void *v, size_t n ) {
volatile unsigned char *p = (unsigned char*)v; while( n-- ) *p++ = 0;
}
#if defined(MBEDTLS_PKCS1_V15)
/* constant-time buffer comparison */
static inline int mbedtls_safer_memcmp( const void *a, const void *b, size_t n )
{
......@@ -88,6 +89,7 @@ static inline int mbedtls_safer_memcmp( const void *a, const void *b, size_t n )
return( diff );
}
#endif /* MBEDTLS_PKCS1_V15 */
int mbedtls_rsa_import( mbedtls_rsa_context *ctx,
const mbedtls_mpi *N,
......@@ -773,16 +775,38 @@ int mbedtls_rsa_private( mbedtls_rsa_context *ctx,
{
int ret;
size_t olen;
mbedtls_mpi T, T1, T2;
/* Temporary holding the result */
mbedtls_mpi T;
/* Temporaries holding P-1, Q-1 and the
* exponent blinding factor, respectively. */
mbedtls_mpi P1, Q1, R;
#if defined(MBEDTLS_RSA_NO_CRT)
mbedtls_mpi D_blind;
mbedtls_mpi *D = &ctx->D;
#else
#if !defined(MBEDTLS_RSA_NO_CRT)
/* Temporaries holding the results mod p resp. mod q. */
mbedtls_mpi TP, TQ;
/* Temporaries holding the blinded exponents for
* the mod p resp. mod q computation (if used). */
mbedtls_mpi DP_blind, DQ_blind;
/* Pointers to actual exponents to be used - either the unblinded
* or the blinded ones, depending on the presence of a PRNG. */
mbedtls_mpi *DP = &ctx->DP;
mbedtls_mpi *DQ = &ctx->DQ;
#endif
#else
/* Temporary holding the blinded exponent (if used). */
mbedtls_mpi D_blind;
/* Pointer to actual exponent to be used - either the unblinded
* or the blinded one, depending on the presence of a PRNG. */
mbedtls_mpi *D = &ctx->D;
#endif /* MBEDTLS_RSA_NO_CRT */
/* Temporaries holding the initial input and the double
* checked result; should be the same in the end. */
mbedtls_mpi I, C;
if( rsa_check_context( ctx, 1 /* private key checks */,
f_rng != NULL /* blinding y/n */ ) != 0 )
......@@ -790,8 +814,17 @@ int mbedtls_rsa_private( mbedtls_rsa_context *ctx,
return( MBEDTLS_ERR_RSA_BAD_INPUT_DATA );
}
mbedtls_mpi_init( &T ); mbedtls_mpi_init( &T1 ); mbedtls_mpi_init( &T2 );
mbedtls_mpi_init( &P1 ); mbedtls_mpi_init( &Q1 ); mbedtls_mpi_init( &R );
#if defined(MBEDTLS_THREADING_C)
if( ( ret = mbedtls_mutex_lock( &ctx->mutex ) ) != 0 )
return( ret );
#endif
/* MPI Initialization */
mbedtls_mpi_init( &T );
mbedtls_mpi_init( &P1 );
mbedtls_mpi_init( &Q1 );
mbedtls_mpi_init( &R );
if( f_rng != NULL )
{
......@@ -803,12 +836,15 @@ int mbedtls_rsa_private( mbedtls_rsa_context *ctx,
#endif
}
#if defined(MBEDTLS_THREADING_C)
if( ( ret = mbedtls_mutex_lock( &ctx->mutex ) ) != 0 )
return( ret );
#if !defined(MBEDTLS_RSA_NO_CRT)
mbedtls_mpi_init( &TP ); mbedtls_mpi_init( &TQ );
#endif
mbedtls_mpi_init( &I );
mbedtls_mpi_init( &C );
/* End of MPI initialization */
MBEDTLS_MPI_CHK( mbedtls_mpi_read_binary( &T, input, ctx->len ) );
if( mbedtls_mpi_cmp_mpi( &T, &ctx->N ) >= 0 )
{
......@@ -816,6 +852,8 @@ int mbedtls_rsa_private( mbedtls_rsa_context *ctx,
goto cleanup;
}
MBEDTLS_MPI_CHK( mbedtls_mpi_copy( &I, &T ) );
if( f_rng != NULL )
{
/*
......@@ -874,24 +912,25 @@ int mbedtls_rsa_private( mbedtls_rsa_context *ctx,
/*
* Faster decryption using the CRT
*
* T1 = input ^ dP mod P
* T2 = input ^ dQ mod Q
* TP = input ^ dP mod P
* TQ = input ^ dQ mod Q
*/
MBEDTLS_MPI_CHK( mbedtls_mpi_exp_mod( &T1, &T, DP, &ctx->P, &ctx->RP ) );
MBEDTLS_MPI_CHK( mbedtls_mpi_exp_mod( &T2, &T, DQ, &ctx->Q, &ctx->RQ ) );
MBEDTLS_MPI_CHK( mbedtls_mpi_exp_mod( &TP, &T, DP, &ctx->P, &ctx->RP ) );
MBEDTLS_MPI_CHK( mbedtls_mpi_exp_mod( &TQ, &T, DQ, &ctx->Q, &ctx->RQ ) );
/*
* T = (T1 - T2) * (Q^-1 mod P) mod P
* T = (TP - TQ) * (Q^-1 mod P) mod P
*/
MBEDTLS_MPI_CHK( mbedtls_mpi_sub_mpi( &T, &T1, &T2 ) );
MBEDTLS_MPI_CHK( mbedtls_mpi_mul_mpi( &T1, &T, &ctx->QP ) );
MBEDTLS_MPI_CHK( mbedtls_mpi_mod_mpi( &T, &T1, &ctx->P ) );
MBEDTLS_MPI_CHK( mbedtls_mpi_sub_mpi( &T, &TP, &TQ ) );
MBEDTLS_MPI_CHK( mbedtls_mpi_mul_mpi( &TP, &T, &ctx->QP ) );
MBEDTLS_MPI_CHK( mbedtls_mpi_mod_mpi( &T, &TP, &ctx->P ) );
/*
* T = T2 + T * Q
* T = TQ + T * Q
*/
MBEDTLS_MPI_CHK( mbedtls_mpi_mul_mpi( &T1, &T, &ctx->Q ) );
MBEDTLS_MPI_CHK( mbedtls_mpi_add_mpi( &T, &T2, &T1 ) );
MBEDTLS_MPI_CHK( mbedtls_mpi_mul_mpi( &TP, &T, &ctx->Q ) );
MBEDTLS_MPI_CHK( mbedtls_mpi_add_mpi( &T, &TQ, &TP ) );
#endif /* MBEDTLS_RSA_NO_CRT */
if( f_rng != NULL )
......@@ -904,6 +943,15 @@ int mbedtls_rsa_private( mbedtls_rsa_context *ctx,
MBEDTLS_MPI_CHK( mbedtls_mpi_mod_mpi( &T, &T, &ctx->N ) );
}
/* Verify the result to prevent glitching attacks. */
MBEDTLS_MPI_CHK( mbedtls_mpi_exp_mod( &C, &T, &ctx->E,
&ctx->N, &ctx->RN ) );
if( mbedtls_mpi_cmp_mpi( &C, &I ) != 0 )
{
ret = MBEDTLS_ERR_RSA_VERIFY_FAILED;
goto cleanup;
}
olen = ctx->len;
MBEDTLS_MPI_CHK( mbedtls_mpi_write_binary( &T, output, olen ) );
......@@ -913,8 +961,9 @@ cleanup:
return( MBEDTLS_ERR_THREADING_MUTEX_ERROR );
#endif
mbedtls_mpi_free( &T ); mbedtls_mpi_free( &T1 ); mbedtls_mpi_free( &T2 );
mbedtls_mpi_free( &P1 ); mbedtls_mpi_free( &Q1 ); mbedtls_mpi_free( &R );
mbedtls_mpi_free( &P1 );
mbedtls_mpi_free( &Q1 );
mbedtls_mpi_free( &R );
if( f_rng != NULL )
{
......@@ -926,6 +975,15 @@ cleanup:
#endif
}
mbedtls_mpi_free( &T );
#if !defined(MBEDTLS_RSA_NO_CRT)
mbedtls_mpi_free( &TP ); mbedtls_mpi_free( &TQ );
#endif
mbedtls_mpi_free( &C );
mbedtls_mpi_free( &I );
if( ret != 0 )
return( MBEDTLS_ERR_RSA_PRIVATE_FAILED + ret );
......@@ -1306,6 +1364,97 @@ cleanup:
#endif /* MBEDTLS_PKCS1_V21 */
#if defined(MBEDTLS_PKCS1_V15)
/** Turn zero-or-nonzero into zero-or-all-bits-one, without branches.
*
* \param value The value to analyze.
* \return Zero if \p value is zero, otherwise all-bits-one.
*/
static unsigned all_or_nothing_int( unsigned value )
{
/* 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
return( - ( ( value | - value ) >> ( sizeof( value ) * 8 - 1 ) ) );
#if defined(_MSC_VER)
#pragma warning( pop )
#endif
}
/** Check whether a size is out of bounds, without branches.
*
* This is equivalent to `size > max`, but is likely to be compiled to
* to code using bitwise operation rather than a branch.
*
* \param size Size to check.
* \param max Maximum desired value for \p size.
* \return \c 0 if `size <= max`.
* \return \c 1 if `size > max`.
*/
static unsigned size_greater_than( size_t size, size_t max )
{
/* Return the sign bit (1 for negative) of (max - size). */
return( ( max - size ) >> ( sizeof( size_t ) * 8 - 1 ) );
}
/** Choose between two integer values, without branches.
*
* This is equivalent to `cond ? if1 : if0`, but is likely to be compiled
* to code using bitwise operation rather than a branch.
*
* \param cond Condition to test.
* \param if1 Value to use if \p cond is nonzero.
* \param if0 Value to use if \p cond is zero.
* \return \c if1 if \p cond is nonzero, otherwise \c if0.
*/
static unsigned if_int( unsigned cond, unsigned if1, unsigned if0 )
{
unsigned mask = all_or_nothing_int( cond );
return( ( mask & if1 ) | (~mask & if0 ) );
}
/** Shift some data towards the left inside a buffer without leaking
* the length of the data through side channels.
*
* `mem_move_to_left(start, total, offset)` is functionally equivalent to
* ```
* memmove(start, start + offset, total - offset);
* memset(start + offset, 0, total - offset);
* ```
* but it strives to use a memory access pattern (and thus total timing)
* that does not depend on \p offset. This timing independence comes at
* the expense of performance.
*
* \param start Pointer to the start of the buffer.
* \param total Total size of the buffer.
* \param offset Offset from which to copy \p total - \p offset bytes.
*/
static void mem_move_to_left( void *start,
size_t total,
size_t offset )
{
volatile unsigned char *buf = start;
size_t i, n;
if( total == 0 )
return;
for( i = 0; i < total; i++ )
{
unsigned no_op = size_greater_than( total - offset, i );
/* The first `total - offset` passes are a no-op. The last
* `offset` passes shift the data one byte to the left and
* zero out the last byte. */
for( n = 0; n < total - 1; n++ )
{
unsigned char current = buf[n];
unsigned char next = buf[n+1];
buf[n] = if_int( no_op, current, next );
}
buf[total-1] = if_int( no_op, buf[total-1], 0 );
}
}
/*
* Implementation of the PKCS#1 v2.1 RSAES-PKCS1-V1_5-DECRYPT function
*/
......@@ -1315,18 +1464,34 @@ int mbedtls_rsa_rsaes_pkcs1_v15_decrypt( mbedtls_rsa_context *ctx,
int mode, size_t *olen,
const unsigned char *input,
unsigned char *output,
size_t output_max_len)
size_t output_max_len )
{
int ret;
size_t ilen, pad_count = 0, i;
unsigned char *p, bad, pad_done = 0;
size_t ilen = ctx->len;
size_t i;
size_t plaintext_max_size = ( output_max_len > ilen - 11 ?
ilen - 11 :
output_max_len );
unsigned char buf[MBEDTLS_MPI_MAX_SIZE];
/* The following variables take sensitive values: their value must
* not leak into the observable behavior of the function other than
* the designated outputs (output, olen, return value). Otherwise
* this would open the execution of the function to
* side-channel-based variants of the Bleichenbacher padding oracle
* attack. Potential side channels include overall timing, memory
* access patterns (especially visible to an adversary who has access
* to a shared memory cache), and branches (especially visible to
* an adversary who has access to a shared code cache or to a shared
* branch predictor). */
size_t pad_count = 0;
unsigned bad = 0;
unsigned char pad_done = 0;
size_t plaintext_size = 0;
unsigned output_too_large;
if( mode == MBEDTLS_RSA_PRIVATE && ctx->padding != MBEDTLS_RSA_PKCS_V15 )
return( MBEDTLS_ERR_RSA_BAD_INPUT_DATA );
ilen = ctx->len;
if( ilen < 16 || ilen > sizeof( buf ) )
return( MBEDTLS_ERR_RSA_BAD_INPUT_DATA );
......@@ -1337,63 +1502,109 @@ int mbedtls_rsa_rsaes_pkcs1_v15_decrypt( mbedtls_rsa_context *ctx,
if( ret != 0 )
goto cleanup;
p = buf;
bad = 0;
/* Check and get padding length in constant time and constant
* memory trace. The first byte must be 0. */
bad |= buf[0];
/*
* Check and get padding len in "constant-time"
*/
bad |= *p++; /* First byte must be 0 */
/* This test does not depend on secret data */
if( mode == MBEDTLS_RSA_PRIVATE )
{
bad |= *p++ ^ MBEDTLS_RSA_CRYPT;
/* Decode EME-PKCS1-v1_5 padding: 0x00 || 0x02 || PS || 0x00
* where PS must be at least 8 nonzero bytes. */
bad |= buf[1] ^ MBEDTLS_RSA_CRYPT;
/* Get padding len, but always read till end of buffer
* (minus one, for the 00 byte) */
for( i = 0; i < ilen - 3; i++ )
/* Read the whole buffer. Set pad_done to nonzero if we find
* the 0x00 byte and remember the padding length in pad_count. */
for( i = 2; i < ilen; i++ )
{
pad_done |= ((p[i] | (unsigned char)-p[i]) >> 7) ^ 1;
pad_done |= ((buf[i] | (unsigned char)-buf[i]) >> 7) ^ 1;
pad_count += ((pad_done | (unsigned char)-pad_done) >> 7) ^ 1;
}
p += pad_count;
bad |= *p++; /* Must be zero */
}
else
{
bad |= *p++ ^ MBEDTLS_RSA_SIGN;
/* Decode EMSA-PKCS1-v1_5 padding: 0x00 || 0x01 || PS || 0x00
* where PS must be at least 8 bytes with the value 0xFF. */
bad |= buf[1] ^ MBEDTLS_RSA_SIGN;
/* Get padding len, but always read till end of buffer
* (minus one, for the 00 byte) */
for( i = 0; i < ilen - 3; i++ )
/* Read the whole buffer. Set pad_done to nonzero if we find
* the 0x00 byte and remember the padding length in pad_count.
* If there's a non-0xff byte in the padding, the padding is bad. */
for( i = 2; i < ilen; i++ )
{
pad_done |= ( p[i] != 0xFF );
pad_count += ( pad_done == 0 );
pad_done |= if_int( buf[i], 0, 1 );
pad_count += if_int( pad_done, 0, 1 );
bad |= if_int( pad_done, 0, buf[i] ^ 0xFF );
}
p += pad_count;
bad |= *p++; /* Must be zero */
}
bad |= ( pad_count < 8 );
if( bad )
{
ret = MBEDTLS_ERR_RSA_INVALID_PADDING;
goto cleanup;
}
if( ilen - ( p - buf ) > output_max_len )
{
ret = MBEDTLS_ERR_RSA_OUTPUT_TOO_LARGE;
goto cleanup;
}
*olen = ilen - (p - buf);
memcpy( output, p, *olen );
ret = 0;
/* If pad_done is still zero, there's no data, only unfinished padding. */
bad |= if_int( pad_done, 0, 1 );
/* There must be at least 8 bytes of padding. */
bad |= size_greater_than( 8, pad_count );
/* If the padding is valid, set plaintext_size to the number of
* remaining bytes after stripping the padding. If the padding
* is invalid, avoid leaking this fact through the size of the
* output: use the maximum message size that fits in the output
* buffer. Do it without branches to avoid leaking the padding
* validity through timing. RSA keys are small enough that all the
* size_t values involved fit in unsigned int. */
plaintext_size = if_int( bad,
(unsigned) plaintext_max_size,
(unsigned) ( ilen - pad_count - 3 ) );
/* Set output_too_large to 0 if the plaintext fits in the output
* buffer and to 1 otherwise. */
output_too_large = size_greater_than( plaintext_size,
plaintext_max_size );
/* Set ret without branches to avoid timing attacks. Return:
* - INVALID_PADDING if the padding is bad (bad != 0).
* - OUTPUT_TOO_LARGE if the padding is good but the decrypted
* plaintext does not fit in the output buffer.
* - 0 if the padding is correct. */
ret = - (int) if_int( bad, - MBEDTLS_ERR_RSA_INVALID_PADDING,
if_int( output_too_large, - MBEDTLS_ERR_RSA_OUTPUT_TOO_LARGE,
0 ) );
/* If the padding is bad or the plaintext is too large, zero the
* data that we're about to copy to the output buffer.
* We need to copy the same amount of data
* from the same buffer whether the padding is good or not to
* avoid leaking the padding validity through overall timing or
* through memory or cache access patterns. */
bad = all_or_nothing_int( bad | output_too_large );
for( i = 11; i < ilen; i++ )
buf[i] &= ~bad;
/* If the plaintext is too large, truncate it to the buffer size.
* Copy anyway to avoid revealing the length through timing, because
* revealing the length is as bad as revealing the padding validity
* for a Bleichenbacher attack. */
plaintext_size = if_int( output_too_large,
(unsigned) plaintext_max_size,
(unsigned) plaintext_size );
/* Move the plaintext to the leftmost position where it can start in
* the working buffer, i.e. make it start plaintext_max_size from
* the end of the buffer. Do this with a memory access trace that
* does not depend on the plaintext size. After this move, the
* starting location of the plaintext is no longer sensitive
* information. */
mem_move_to_left( buf + ilen - plaintext_max_size,
plaintext_max_size,
plaintext_max_size - plaintext_size );
/* Finally copy the decrypted plaintext plus trailing zeros
* into the output buffer. */
memcpy( output, buf + ilen - plaintext_max_size, plaintext_max_size );
/* Report the amount of data we copied to the output buffer. In case
* of errors (bad padding or output too large), the value of *olen
* when this function returns is not specified. Making it equivalent
* to the good case limits the risks of leaking the padding validity. */
*olen = plaintext_size;
cleanup:
mbedtls_zeroize( buf, sizeof( buf ) );
......@@ -2222,7 +2433,8 @@ int mbedtls_rsa_self_test( int verbose )
if( verbose != 0 )
mbedtls_printf( "failed\n" );
return( 1 );
ret = 1;
goto cleanup;
}
if( verbose != 0 )
......@@ -2237,7 +2449,8 @@ int mbedtls_rsa_self_test( int verbose )
if( verbose != 0 )
mbedtls_printf( "failed\n" );
return( 1 );
ret = 1;
goto cleanup;
}
if( verbose != 0 )
......@@ -2250,7 +2463,8 @@ int mbedtls_rsa_self_test( int verbose )
if( verbose != 0 )
mbedtls_printf( "failed\n" );
return( 1 );
ret = 1;
goto cleanup;
}
if( memcmp( rsa_decrypted, rsa_plaintext, len ) != 0 )
......@@ -2258,7 +2472,8 @@ int mbedtls_rsa_self_test( int verbose )
if( verbose != 0 )
mbedtls_printf( "failed\n" );
return( 1 );
ret = 1;
goto cleanup;
}
if( verbose != 0 )
......@@ -2283,7 +2498,8 @@ int mbedtls_rsa_self_test( int verbose )
if( verbose != 0 )
mbedtls_printf( "failed\n" );
return( 1 );
ret = 1;
goto cleanup;
}
if( verbose != 0 )
......@@ -2296,7 +2512,8 @@ int mbedtls_rsa_self_test( int verbose )
if( verbose != 0 )
mbedtls_printf( "failed\n" );
return( 1 );
ret = 1;
goto cleanup;
}
if( verbose != 0 )
......
......@@ -111,6 +111,13 @@ int mbedtls_sha1_starts_ret( mbedtls_sha1_context *ctx )
return( 0 );
}
#if !defined(MBEDTLS_DEPRECATED_REMOVED)
void mbedtls_sha1_starts( mbedtls_sha1_context *ctx )
{
mbedtls_sha1_starts_ret( ctx );
}
#endif
#if !defined(MBEDTLS_SHA1_PROCESS_ALT)
int mbedtls_internal_sha1_process( mbedtls_sha1_context *ctx,
const unsigned char data[64] )
......@@ -270,6 +277,14 @@ int mbedtls_internal_sha1_process( mbedtls_sha1_context *ctx,
return( 0 );
}
#if !defined(MBEDTLS_DEPRECATED_REMOVED)
void mbedtls_sha1_process( mbedtls_sha1_context *ctx,
const unsigned char data[64] )
{
mbedtls_internal_sha1_process( ctx, data );
}
#endif
#endif /* !MBEDTLS_SHA1_PROCESS_ALT */
/*
......@@ -322,13 +337,14 @@ int mbedtls_sha1_update_ret( mbedtls_sha1_context *ctx,
return( 0 );
}
static const unsigned char sha1_padding[64] =
#if !defined(MBEDTLS_DEPRECATED_REMOVED)
void mbedtls_sha1_update( mbedtls_sha1_context *ctx,
const unsigned char *input,
size_t ilen )
{
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
};
mbedtls_sha1_update_ret( ctx, input, ilen );
}
#endif
/*
* SHA-1 final digest
......@@ -337,25 +353,48 @@ int mbedtls_sha1_finish_ret( mbedtls_sha1_context *ctx,
unsigned char output[20] )
{
int ret;
uint32_t last, padn;
uint32_t used;
uint32_t high, low;
unsigned char msglen[8];
/*
* Add padding: 0x80 then 0x00 until 8 bytes remain for the length
*/
used = ctx->total[0] & 0x3F;
ctx->buffer[used++] = 0x80;
if( used <= 56 )
{
/* Enough room for padding + length in current block */
memset( ctx->buffer + used, 0, 56 - used );
}
else
{
/* We'll need an extra block */
memset( ctx->buffer + used, 0, 64 - used );
if( ( ret = mbedtls_internal_sha1_process( ctx, ctx->buffer ) ) != 0 )
return( ret );
memset( ctx->buffer, 0, 56 );
}
/*
* Add message length
*/
high = ( ctx->total[0] >> 29 )
| ( ctx->total[1] << 3 );
low = ( ctx->total[0] << 3 );
PUT_UINT32_BE( high, msglen, 0 );
PUT_UINT32_BE( low, msglen, 4 );
last = ctx->total[0] & 0x3F;
padn = ( last < 56 ) ? ( 56 - last ) : ( 120 - last );
PUT_UINT32_BE( high, ctx->buffer, 56 );
PUT_UINT32_BE( low, ctx->buffer, 60 );
if( ( ret = mbedtls_sha1_update_ret( ctx, sha1_padding, padn ) ) != 0 )
return( ret );
if( ( ret = mbedtls_sha1_update_ret( ctx, msglen, 8 ) ) != 0 )
if( ( ret = mbedtls_internal_sha1_process( ctx, ctx->buffer ) ) != 0 )
return( ret );
/*
* Output final state
*/
PUT_UINT32_BE( ctx->state[0], output, 0 );
PUT_UINT32_BE( ctx->state[1], output, 4 );
PUT_UINT32_BE( ctx->state[2], output, 8 );
......@@ -365,6 +404,14 @@ int mbedtls_sha1_finish_ret( mbedtls_sha1_context *ctx,
return( 0 );
}
#if !defined(MBEDTLS_DEPRECATED_REMOVED)
void mbedtls_sha1_finish( mbedtls_sha1_context *ctx,
unsigned char output[20] )
{
mbedtls_sha1_finish_ret( ctx, output );
}
#endif
#endif /* !MBEDTLS_SHA1_ALT */
/*
......@@ -394,6 +441,15 @@ exit:
return( ret );
}
#if !defined(MBEDTLS_DEPRECATED_REMOVED)
void mbedtls_sha1( const unsigned char *input,
size_t ilen,
unsigned char output[20] )
{
mbedtls_sha1_ret( input, ilen, output );
}
#endif
#if defined(MBEDTLS_SELF_TEST)
/*
* FIPS-180-1 test vectors
......
......@@ -135,6 +135,14 @@ int mbedtls_sha256_starts_ret( mbedtls_sha256_context *ctx, int is224 )
return( 0 );
}
#if !defined(MBEDTLS_DEPRECATED_REMOVED)
void mbedtls_sha256_starts( mbedtls_sha256_context *ctx,
int is224 )
{
mbedtls_sha256_starts_ret( ctx, is224 );
}
#endif
#if !defined(MBEDTLS_SHA256_PROCESS_ALT)
static const uint32_t K[] =
{
......@@ -238,6 +246,14 @@ int mbedtls_internal_sha256_process( mbedtls_sha256_context *ctx,
return( 0 );
}
#if !defined(MBEDTLS_DEPRECATED_REMOVED)
void mbedtls_sha256_process( mbedtls_sha256_context *ctx,
const unsigned char data[64] )
{
mbedtls_internal_sha256_process( ctx, data );
}
#endif
#endif /* !MBEDTLS_SHA256_PROCESS_ALT */
/*
......@@ -290,13 +306,14 @@ int mbedtls_sha256_update_ret( mbedtls_sha256_context *ctx,
return( 0 );
}
static const unsigned char sha256_padding[64] =
#if !defined(MBEDTLS_DEPRECATED_REMOVED)
void mbedtls_sha256_update( mbedtls_sha256_context *ctx,
const unsigned char *input,
size_t ilen )
{
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
};
mbedtls_sha256_update_ret( ctx, input, ilen );
}
#endif
/*
* SHA-256 final digest
......@@ -305,26 +322,48 @@ int mbedtls_sha256_finish_ret( mbedtls_sha256_context *ctx,
unsigned char output[32] )
{
int ret;
uint32_t last, padn;
uint32_t used;
uint32_t high, low;
unsigned char msglen[8];
/*
* Add padding: 0x80 then 0x00 until 8 bytes remain for the length
*/
used = ctx->total[0] & 0x3F;
ctx->buffer[used++] = 0x80;
if( used <= 56 )
{
/* Enough room for padding + length in current block */
memset( ctx->buffer + used, 0, 56 - used );
}
else
{
/* We'll need an extra block */
memset( ctx->buffer + used, 0, 64 - used );
if( ( ret = mbedtls_internal_sha256_process( ctx, ctx->buffer ) ) != 0 )
return( ret );
memset( ctx->buffer, 0, 56 );
}
/*
* Add message length
*/
high = ( ctx->total[0] >> 29 )
| ( ctx->total[1] << 3 );
low = ( ctx->total[0] << 3 );
PUT_UINT32_BE( high, msglen, 0 );
PUT_UINT32_BE( low, msglen, 4 );
last = ctx->total[0] & 0x3F;
padn = ( last < 56 ) ? ( 56 - last ) : ( 120 - last );
if( ( ret = mbedtls_sha256_update_ret( ctx, sha256_padding, padn ) ) != 0 )
return( ret );
PUT_UINT32_BE( high, ctx->buffer, 56 );
PUT_UINT32_BE( low, ctx->buffer, 60 );
if( ( ret = mbedtls_sha256_update_ret( ctx, msglen, 8 ) ) != 0 )
if( ( ret = mbedtls_internal_sha256_process( ctx, ctx->buffer ) ) != 0 )
return( ret );
/*
* Output final state
*/
PUT_UINT32_BE( ctx->state[0], output, 0 );
PUT_UINT32_BE( ctx->state[1], output, 4 );
PUT_UINT32_BE( ctx->state[2], output, 8 );
......@@ -339,6 +378,14 @@ int mbedtls_sha256_finish_ret( mbedtls_sha256_context *ctx,
return( 0 );
}
#if !defined(MBEDTLS_DEPRECATED_REMOVED)
void mbedtls_sha256_finish( mbedtls_sha256_context *ctx,
unsigned char output[32] )
{
mbedtls_sha256_finish_ret( ctx, output );
}
#endif
#endif /* !MBEDTLS_SHA256_ALT */
/*
......@@ -369,6 +416,16 @@ exit:
return( ret );
}
#if !defined(MBEDTLS_DEPRECATED_REMOVED)
void mbedtls_sha256( const unsigned char *input,
size_t ilen,
unsigned char output[32],
int is224 )
{
mbedtls_sha256_ret( input, ilen, output, is224 );
}
#endif
#if defined(MBEDTLS_SELF_TEST)
/*
* FIPS-180-2 test vectors
......
......@@ -149,6 +149,14 @@ int mbedtls_sha512_starts_ret( mbedtls_sha512_context *ctx, int is384 )
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)
/*
......@@ -269,6 +277,14 @@ int mbedtls_internal_sha512_process( mbedtls_sha512_context *ctx,
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 */
/*
......@@ -320,17 +336,14 @@ int mbedtls_sha512_update_ret( mbedtls_sha512_context *ctx,
return( 0 );
}
static const unsigned char sha512_padding[128] =
#if !defined(MBEDTLS_DEPRECATED_REMOVED)
void mbedtls_sha512_update( mbedtls_sha512_context *ctx,
const unsigned char *input,
size_t ilen )
{
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,
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, 0
};
mbedtls_sha512_update_ret( ctx, input, ilen );
}
#endif
/*
* SHA-512 final digest
......@@ -339,26 +352,48 @@ int mbedtls_sha512_finish_ret( mbedtls_sha512_context *ctx,
unsigned char output[64] )
{
int ret;
size_t last, padn;
unsigned used;
uint64_t high, low;
unsigned char msglen[16];
high = ( ctx->total[0] >> 61 )
| ( ctx->total[1] << 3 );
low = ( ctx->total[0] << 3 );
/*
* Add padding: 0x80 then 0x00 until 16 bytes remain for the length
*/
used = ctx->total[0] & 0x7F;
PUT_UINT64_BE( high, msglen, 0 );
PUT_UINT64_BE( low, msglen, 8 );
ctx->buffer[used++] = 0x80;
last = (size_t)( ctx->total[0] & 0x7F );
padn = ( last < 112 ) ? ( 112 - last ) : ( 240 - last );
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_sha512_update_ret( ctx, sha512_padding, padn ) ) != 0 )
if( ( ret = mbedtls_internal_sha512_process( ctx, ctx->buffer ) ) != 0 )
return( ret );
if( ( ret = mbedtls_sha512_update_ret( ctx, msglen, 16 ) ) != 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 );
PUT_UINT64_BE( high, ctx->buffer, 112 );
PUT_UINT64_BE( low, ctx->buffer, 120 );
if( ( ret = mbedtls_internal_sha512_process( ctx, ctx->buffer ) ) != 0 )
return( ret );
/*
* Output final state
*/
PUT_UINT64_BE( ctx->state[0], output, 0 );
PUT_UINT64_BE( ctx->state[1], output, 8 );
PUT_UINT64_BE( ctx->state[2], output, 16 );
......@@ -375,6 +410,14 @@ int mbedtls_sha512_finish_ret( mbedtls_sha512_context *ctx,
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 */
/*
......@@ -405,6 +448,16 @@ exit:
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)
/*
......
......@@ -1837,7 +1837,8 @@ mbedtls_pk_type_t mbedtls_ssl_get_ciphersuite_sig_alg( const mbedtls_ssl_ciphers
#endif /* MBEDTLS_PK_C */
#if defined(MBEDTLS_ECDH_C) || defined(MBEDTLS_ECDSA_C)
#if defined(MBEDTLS_ECDH_C) || defined(MBEDTLS_ECDSA_C) || \
defined(MBEDTLS_KEY_EXCHANGE_ECJPAKE_ENABLED)
int mbedtls_ssl_ciphersuite_uses_ec( const mbedtls_ssl_ciphersuite_t *info )
{
switch( info->key_exchange )
......@@ -1847,13 +1848,14 @@ int mbedtls_ssl_ciphersuite_uses_ec( const mbedtls_ssl_ciphersuite_t *info )
case MBEDTLS_KEY_EXCHANGE_ECDHE_PSK:
case MBEDTLS_KEY_EXCHANGE_ECDH_RSA:
case MBEDTLS_KEY_EXCHANGE_ECDH_ECDSA:
case MBEDTLS_KEY_EXCHANGE_ECJPAKE:
return( 1 );
default:
return( 0 );
}
}
#endif /* MBEDTLS_ECDH_C || MBEDTLS_ECDSA_C */
#endif /* MBEDTLS_ECDH_C || MBEDTLS_ECDSA_C || MBEDTLS_KEY_EXCHANGE_ECJPAKE_ENABLED*/
#if defined(MBEDTLS_KEY_EXCHANGE__SOME__PSK_ENABLED)
int mbedtls_ssl_ciphersuite_uses_psk( const mbedtls_ssl_ciphersuite_t *info )
......
......@@ -355,7 +355,7 @@ static void ssl_write_supported_point_formats_ext( mbedtls_ssl_context *ssl,
*olen = 6;
}
#endif /* MBEDTLS_ECDH_C || MBEDTLS_ECDSA_C ||
#endif /* MBEDTLS_ECDH_C || MBEDTLS_ECDSA_C ||
MBEDTLS_KEY_EXCHANGE_ECJPAKE_ENABLED */
#if defined(MBEDTLS_KEY_EXCHANGE_ECJPAKE_ENABLED)
......@@ -717,6 +717,49 @@ static int ssl_generate_random( mbedtls_ssl_context *ssl )
return( 0 );
}
/**
* \brief Validate cipher suite against config in SSL context.
*
* \param suite_info cipher suite to validate
* \param ssl SSL context
* \param min_minor_ver Minimal minor version to accept a cipher suite
* \param max_minor_ver Maximal minor version to accept a cipher suite
*
* \return 0 if valid, else 1
*/
static int ssl_validate_ciphersuite( const mbedtls_ssl_ciphersuite_t * suite_info,
const mbedtls_ssl_context * ssl,
int min_minor_ver, int max_minor_ver )
{
(void) ssl;
if( suite_info == NULL )
return( 1 );
if( suite_info->min_minor_ver > max_minor_ver ||
suite_info->max_minor_ver < min_minor_ver )
return( 1 );
#if defined(MBEDTLS_SSL_PROTO_DTLS)
if( ssl->conf->transport == MBEDTLS_SSL_TRANSPORT_DATAGRAM &&
( suite_info->flags & MBEDTLS_CIPHERSUITE_NODTLS ) )
return( 1 );
#endif
#if defined(MBEDTLS_ARC4_C)
if( ssl->conf->arc4_disabled == MBEDTLS_SSL_ARC4_DISABLED &&
suite_info->cipher == MBEDTLS_CIPHER_ARC4_128 )
return( 1 );
#endif
#if defined(MBEDTLS_KEY_EXCHANGE_ECJPAKE_ENABLED)
if( suite_info->key_exchange == MBEDTLS_KEY_EXCHANGE_ECJPAKE &&
mbedtls_ecjpake_check( &ssl->handshake->ecjpake_ctx ) != 0 )
return( 1 );
#endif
return( 0 );
}
static int ssl_write_client_hello( mbedtls_ssl_context *ssl )
{
int ret;
......@@ -726,6 +769,10 @@ static int ssl_write_client_hello( mbedtls_ssl_context *ssl )
unsigned char offer_compress;
const int *ciphersuites;
const mbedtls_ssl_ciphersuite_t *ciphersuite_info;
#if defined(MBEDTLS_ECDH_C) || defined(MBEDTLS_ECDSA_C) || \
defined(MBEDTLS_KEY_EXCHANGE_ECJPAKE_ENABLED)
int uses_ec = 0;
#endif
MBEDTLS_SSL_DEBUG_MSG( 2, ( "=> write client hello" ) );
......@@ -869,39 +916,26 @@ static int ssl_write_client_hello( mbedtls_ssl_context *ssl )
{
ciphersuite_info = mbedtls_ssl_ciphersuite_from_id( ciphersuites[i] );
if( ciphersuite_info == NULL )
continue;
if( ciphersuite_info->min_minor_ver > ssl->conf->max_minor_ver ||
ciphersuite_info->max_minor_ver < ssl->conf->min_minor_ver )
if( ssl_validate_ciphersuite( ciphersuite_info, ssl,
ssl->conf->min_minor_ver,
ssl->conf->max_minor_ver ) != 0 )
continue;
#if defined(MBEDTLS_SSL_PROTO_DTLS)
if( ssl->conf->transport == MBEDTLS_SSL_TRANSPORT_DATAGRAM &&
( ciphersuite_info->flags & MBEDTLS_CIPHERSUITE_NODTLS ) )
continue;
#endif
#if defined(MBEDTLS_ARC4_C)
if( ssl->conf->arc4_disabled == MBEDTLS_SSL_ARC4_DISABLED &&
ciphersuite_info->cipher == MBEDTLS_CIPHER_ARC4_128 )
continue;
#endif
#if defined(MBEDTLS_KEY_EXCHANGE_ECJPAKE_ENABLED)
if( ciphersuite_info->key_exchange == MBEDTLS_KEY_EXCHANGE_ECJPAKE &&
mbedtls_ecjpake_check( &ssl->handshake->ecjpake_ctx ) != 0 )
continue;
#endif
MBEDTLS_SSL_DEBUG_MSG( 3, ( "client hello, add ciphersuite: %04x",
ciphersuites[i] ) );
#if defined(MBEDTLS_ECDH_C) || defined(MBEDTLS_ECDSA_C) || \
defined(MBEDTLS_KEY_EXCHANGE_ECJPAKE_ENABLED)
uses_ec |= mbedtls_ssl_ciphersuite_uses_ec( ciphersuite_info );
#endif
n++;
*p++ = (unsigned char)( ciphersuites[i] >> 8 );
*p++ = (unsigned char)( ciphersuites[i] );
}
MBEDTLS_SSL_DEBUG_MSG( 3, ( "client hello, got %d ciphersuites (excluding SCSVs)", n ) );
/*
* Add TLS_EMPTY_RENEGOTIATION_INFO_SCSV
*/
......@@ -909,6 +943,7 @@ static int ssl_write_client_hello( mbedtls_ssl_context *ssl )
if( ssl->renego_status == MBEDTLS_SSL_INITIAL_HANDSHAKE )
#endif
{
MBEDTLS_SSL_DEBUG_MSG( 3, ( "adding EMPTY_RENEGOTIATION_INFO_SCSV" ) );
*p++ = (unsigned char)( MBEDTLS_SSL_EMPTY_RENEGOTIATION_INFO >> 8 );
*p++ = (unsigned char)( MBEDTLS_SSL_EMPTY_RENEGOTIATION_INFO );
n++;
......@@ -928,8 +963,6 @@ static int ssl_write_client_hello( mbedtls_ssl_context *ssl )
*q++ = (unsigned char)( n >> 7 );
*q++ = (unsigned char)( n << 1 );
MBEDTLS_SSL_DEBUG_MSG( 3, ( "client hello, got %d ciphersuites", n ) );
#if defined(MBEDTLS_ZLIB_SUPPORT)
offer_compress = 1;
#else
......@@ -937,7 +970,7 @@ static int ssl_write_client_hello( mbedtls_ssl_context *ssl )
#endif
/*
* We don't support compression with DTLS right now: is many records come
* We don't support compression with DTLS right now: if many records come
* in the same datagram, uncompressing one could overwrite the next one.
* We don't want to add complexity for handling that case unless there is
* an actual need for it.
......@@ -989,11 +1022,14 @@ static int ssl_write_client_hello( mbedtls_ssl_context *ssl )
#if defined(MBEDTLS_ECDH_C) || defined(MBEDTLS_ECDSA_C) || \
defined(MBEDTLS_KEY_EXCHANGE_ECJPAKE_ENABLED)
ssl_write_supported_elliptic_curves_ext( ssl, p + 2 + ext_len, &olen );
ext_len += olen;
if( uses_ec )
{
ssl_write_supported_elliptic_curves_ext( ssl, p + 2 + ext_len, &olen );
ext_len += olen;
ssl_write_supported_point_formats_ext( ssl, p + 2 + ext_len, &olen );
ext_len += olen;
ssl_write_supported_point_formats_ext( ssl, p + 2 + ext_len, &olen );
ext_len += olen;
}
#endif
#if defined(MBEDTLS_KEY_EXCHANGE_ECJPAKE_ENABLED)
......@@ -1226,14 +1262,14 @@ static int ssl_parse_supported_point_formats_ext( mbedtls_ssl_context *ssl,
size_t list_size;
const unsigned char *p;
list_size = buf[0];
if( list_size + 1 != len )
if( len == 0 || (size_t)( buf[0] + 1 ) != len )
{
MBEDTLS_SSL_DEBUG_MSG( 1, ( "bad server 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_SERVER_HELLO );
}
list_size = buf[0];
p = buf + 1;
while( list_size > 0 )
......@@ -1260,7 +1296,7 @@ static int ssl_parse_supported_point_formats_ext( mbedtls_ssl_context *ssl,
MBEDTLS_SSL_ALERT_MSG_HANDSHAKE_FAILURE );
return( MBEDTLS_ERR_SSL_BAD_HS_SERVER_HELLO );
}
#endif /* MBEDTLS_ECDH_C || MBEDTLS_ECDSA_C ||
#endif /* MBEDTLS_ECDH_C || MBEDTLS_ECDSA_C ||
MBEDTLS_KEY_EXCHANGE_ECJPAKE_ENABLED */
#if defined(MBEDTLS_KEY_EXCHANGE_ECJPAKE_ENABLED)
......@@ -1689,22 +1725,9 @@ static int ssl_parse_server_hello( mbedtls_ssl_context *ssl )
MBEDTLS_SSL_DEBUG_MSG( 3, ( "server hello, chosen ciphersuite: %04x", i ) );
MBEDTLS_SSL_DEBUG_MSG( 3, ( "server hello, compress alg.: %d", buf[37 + n] ) );
suite_info = mbedtls_ssl_ciphersuite_from_id( ssl->session_negotiate->ciphersuite );
if( suite_info == NULL
#if defined(MBEDTLS_ARC4_C)
|| ( ssl->conf->arc4_disabled &&
suite_info->cipher == MBEDTLS_CIPHER_ARC4_128 )
#endif
)
{
MBEDTLS_SSL_DEBUG_MSG( 1, ( "bad server 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_SERVER_HELLO );
}
MBEDTLS_SSL_DEBUG_MSG( 3, ( "server hello, chosen ciphersuite: %s", suite_info->name ) );
/*
* Perform cipher suite validation in same way as in ssl_write_client_hello.
*/
i = 0;
while( 1 )
{
......@@ -1723,6 +1746,17 @@ static int ssl_parse_server_hello( mbedtls_ssl_context *ssl )
}
}
suite_info = mbedtls_ssl_ciphersuite_from_id( ssl->session_negotiate->ciphersuite );
if( ssl_validate_ciphersuite( suite_info, ssl, ssl->minor_ver, ssl->minor_ver ) != 0 )
{
MBEDTLS_SSL_DEBUG_MSG( 1, ( "bad server 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_SERVER_HELLO );
}
MBEDTLS_SSL_DEBUG_MSG( 3, ( "server hello, chosen ciphersuite: %s", suite_info->name ) );
if( comp != MBEDTLS_SSL_COMPRESS_NULL
#if defined(MBEDTLS_ZLIB_SUPPORT)
&& comp != MBEDTLS_SSL_COMPRESS_DEFLATE
......@@ -2057,10 +2091,16 @@ static int ssl_parse_server_psk_hint( mbedtls_ssl_context *ssl,
*
* opaque psk_identity_hint<0..2^16-1>;
*/
if( end - (*p) < 2 )
{
MBEDTLS_SSL_DEBUG_MSG( 1, ( "bad server key exchange message "
"(psk_identity_hint length)" ) );
return( MBEDTLS_ERR_SSL_BAD_HS_SERVER_KEY_EXCHANGE );
}
len = (*p)[0] << 8 | (*p)[1];
*p += 2;
if( (*p) + len > end )
if( end - (*p) < (int) len )
{
MBEDTLS_SSL_DEBUG_MSG( 1, ( "bad server key exchange message "
"(psk_identity_hint length)" ) );
......@@ -2478,10 +2518,17 @@ static int ssl_parse_server_key_exchange( mbedtls_ssl_context *ssl )
/*
* Read signature
*/
if( p > end - 2 )
{
MBEDTLS_SSL_DEBUG_MSG( 1, ( "bad server key exchange message" ) );
mbedtls_ssl_send_alert_message( ssl, MBEDTLS_SSL_ALERT_LEVEL_FATAL,
MBEDTLS_SSL_ALERT_MSG_DECODE_ERROR );
return( MBEDTLS_ERR_SSL_BAD_HS_SERVER_KEY_EXCHANGE );
}
sig_len = ( p[0] << 8 ) | p[1];
p += 2;
if( end != p + sig_len )
if( p != end - sig_len )
{
MBEDTLS_SSL_DEBUG_MSG( 1, ( "bad server key exchange message" ) );
mbedtls_ssl_send_alert_message( ssl, MBEDTLS_SSL_ALERT_LEVEL_FATAL,
......@@ -2658,10 +2705,27 @@ static int ssl_parse_certificate_request( mbedtls_ssl_context *ssl )
buf = ssl->in_msg;
/* certificate_types */
if( ssl->in_hslen <= mbedtls_ssl_hs_hdr_len( ssl ) )
{
MBEDTLS_SSL_DEBUG_MSG( 1, ( "bad certificate request message" ) );
mbedtls_ssl_send_alert_message( ssl, MBEDTLS_SSL_ALERT_LEVEL_FATAL,
MBEDTLS_SSL_ALERT_MSG_DECODE_ERROR );
return( MBEDTLS_ERR_SSL_BAD_HS_CERTIFICATE_REQUEST );
}
cert_type_len = buf[mbedtls_ssl_hs_hdr_len( ssl )];
n = cert_type_len;
if( ssl->in_hslen < mbedtls_ssl_hs_hdr_len( ssl ) + 2 + n )
/*
* In the subsequent code there are two paths that read from buf:
* * the length of the signature algorithms field (if minor version of
* SSL is 3),
* * distinguished name length otherwise.
* Both reach at most the index:
* ...hdr_len + 2 + n,
* therefore the buffer length at this point must be greater than that
* regardless of the actual code path.
*/
if( ssl->in_hslen <= mbedtls_ssl_hs_hdr_len( ssl ) + 2 + n )
{
MBEDTLS_SSL_DEBUG_MSG( 1, ( "bad certificate request message" ) );
mbedtls_ssl_send_alert_message( ssl, MBEDTLS_SSL_ALERT_LEVEL_FATAL,
......@@ -2676,9 +2740,32 @@ static int ssl_parse_certificate_request( mbedtls_ssl_context *ssl )
size_t sig_alg_len = ( ( buf[mbedtls_ssl_hs_hdr_len( ssl ) + 1 + n] << 8 )
| ( buf[mbedtls_ssl_hs_hdr_len( ssl ) + 2 + n] ) );
#if defined(MBEDTLS_DEBUG_C)
unsigned char* sig_alg = buf + mbedtls_ssl_hs_hdr_len( ssl ) + 3 + n;
unsigned char* sig_alg;
size_t i;
#endif
/*
* The furthest access in buf is in the loop few lines below:
* sig_alg[i + 1],
* where:
* sig_alg = buf + ...hdr_len + 3 + n,
* max(i) = sig_alg_len - 1.
* Therefore the furthest access is:
* buf[...hdr_len + 3 + n + sig_alg_len - 1 + 1],
* which reduces to:
* buf[...hdr_len + 3 + n + sig_alg_len],
* which is one less than we need the buf to be.
*/
if( ssl->in_hslen <= mbedtls_ssl_hs_hdr_len( ssl ) + 3 + n + sig_alg_len )
{
MBEDTLS_SSL_DEBUG_MSG( 1, ( "bad certificate request message" ) );
mbedtls_ssl_send_alert_message( ssl, MBEDTLS_SSL_ALERT_LEVEL_FATAL,
MBEDTLS_SSL_ALERT_MSG_DECODE_ERROR );
return( MBEDTLS_ERR_SSL_BAD_HS_CERTIFICATE_REQUEST );
}
#if defined(MBEDTLS_DEBUG_C)
sig_alg = buf + mbedtls_ssl_hs_hdr_len( ssl ) + 3 + n;
for( i = 0; i < sig_alg_len; i += 2 )
{
MBEDTLS_SSL_DEBUG_MSG( 3, ( "Supported Signature Algorithm found: %d"
......@@ -2687,14 +2774,6 @@ static int ssl_parse_certificate_request( mbedtls_ssl_context *ssl )
#endif
n += 2 + sig_alg_len;
if( ssl->in_hslen < mbedtls_ssl_hs_hdr_len( ssl ) + 2 + n )
{
MBEDTLS_SSL_DEBUG_MSG( 1, ( "bad certificate request message" ) );
mbedtls_ssl_send_alert_message( ssl, MBEDTLS_SSL_ALERT_LEVEL_FATAL,
MBEDTLS_SSL_ALERT_MSG_DECODE_ERROR );
return( MBEDTLS_ERR_SSL_BAD_HS_CERTIFICATE_REQUEST );
}
}
#endif /* MBEDTLS_SSL_PROTO_TLS1_2 */
......@@ -3248,8 +3327,8 @@ static int ssl_parse_new_session_ticket( mbedtls_ssl_context *ssl )
msg = ssl->in_msg + mbedtls_ssl_hs_hdr_len( ssl );
lifetime = ( msg[0] << 24 ) | ( msg[1] << 16 ) |
( msg[2] << 8 ) | ( msg[3] );
lifetime = ( ((uint32_t) msg[0]) << 24 ) | ( msg[1] << 16 ) |
( msg[2] << 8 ) | ( msg[3] );
ticket_len = ( msg[4] << 8 ) | ( msg[5] );
......
......@@ -97,6 +97,13 @@ static int ssl_parse_servername_ext( mbedtls_ssl_context *ssl,
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 )
{
......@@ -107,7 +114,7 @@ static int ssl_parse_servername_ext( mbedtls_ssl_context *ssl,
}
p = buf + 2;
while( servername_list_size > 0 )
while( servername_list_size > 2 )
{
hostname_len = ( ( p[1] << 8 ) | p[2] );
if( hostname_len + 3 > servername_list_size )
......@@ -211,6 +218,12 @@ static int ssl_parse_signature_algorithms_ext( mbedtls_ssl_context *ssl,
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 )
......@@ -279,6 +292,12 @@ static int ssl_parse_supported_elliptic_curves( mbedtls_ssl_context *ssl,
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 )
......@@ -338,14 +357,14 @@ static int ssl_parse_supported_point_formats( mbedtls_ssl_context *ssl,
size_t list_size;
const unsigned char *p;
list_size = buf[0];
if( list_size + 1 != len )
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 )
......@@ -793,7 +812,7 @@ static int ssl_ciphersuite_match( mbedtls_ssl_context *ssl, int suite_id,
const mbedtls_ssl_ciphersuite_t *suite_info;
#if defined(MBEDTLS_SSL_PROTO_TLS1_2) && \
defined(MBEDTLS_KEY_EXCHANGE__WITH_CERT__ENABLED)
defined(MBEDTLS_KEY_EXCHANGE__WITH_CERT__ENABLED)
mbedtls_pk_type_t sig_type;
#endif
......@@ -1662,10 +1681,16 @@ read_record_header:
while( ext_len != 0 )
{
unsigned int ext_id = ( ( ext[0] << 8 )
| ( ext[1] ) );
unsigned int ext_size = ( ( ext[2] << 8 )
| ( ext[3] ) );
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 )
{
......@@ -2570,8 +2595,12 @@ static int ssl_write_server_hello( mbedtls_ssl_context *ssl )
#if defined(MBEDTLS_ECDH_C) || defined(MBEDTLS_ECDSA_C) || \
defined(MBEDTLS_KEY_EXCHANGE_ECJPAKE_ENABLED)
ssl_write_supported_point_formats_ext( ssl, p + 2 + ext_len, &olen );
ext_len += olen;
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)
......@@ -2843,7 +2872,7 @@ static int ssl_write_server_key_exchange( mbedtls_ssl_context *ssl )
#if defined(MBEDTLS_KEY_EXCHANGE__SOME_PFS__ENABLED)
unsigned char *p = ssl->out_msg + 4;
size_t len;
size_t len = 0;
#if defined(MBEDTLS_KEY_EXCHANGE__WITH_SERVER_SIGNATURE__ENABLED)
unsigned char *dig_signed = p;
size_t dig_signed_len = 0;
......@@ -2961,7 +2990,7 @@ static int ssl_write_server_key_exchange( mbedtls_ssl_context *ssl )
return( ret );
}
#if defined(MBEDTLS_KEY_EXCHANGE__WITH_SERVER_SIGNATURE__ENABLED)
#if defined(MBEDTLS_KEY_EXCHANGE__WITH_SERVER_SIGNATURE__ENABLED)
dig_signed = p;
dig_signed_len = len;
#endif
......@@ -3050,7 +3079,7 @@ curve_matching_done:
/*
* 3.1: Choose hash algorithm:
* A: For TLS 1.2, obey signature-hash-algorithm extension
* 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)
......@@ -3071,7 +3100,7 @@ curve_matching_done:
sig_alg ) ) == MBEDTLS_MD_NONE )
{
MBEDTLS_SSL_DEBUG_MSG( 1, ( "should never happen" ) );
/* (... because we choose a cipher suite
/* (... because we choose a cipher suite
* only if there is a matching hash.) */
return( MBEDTLS_ERR_SSL_INTERNAL_ERROR );
}
......@@ -3305,6 +3334,10 @@ static int ssl_parse_encrypted_pms( mbedtls_ssl_context *ssl,
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 ) )
{
......
......@@ -101,7 +101,7 @@ static int ssl_ticket_update_keys( mbedtls_ssl_ticket_context *ctx )
uint32_t current_time = (uint32_t) mbedtls_time( NULL );
uint32_t key_time = ctx->keys[ctx->active].generation_time;
if( current_time > key_time &&
if( current_time >= key_time &&
current_time - key_time < ctx->ticket_lifetime )
{
return( 0 );
......@@ -192,9 +192,9 @@ static int ssl_save_session( const mbedtls_ssl_session *session,
if( left < 3 + cert_len )
return( MBEDTLS_ERR_SSL_BUFFER_TOO_SMALL );
*p++ = (unsigned char)( cert_len >> 16 & 0xFF );
*p++ = (unsigned char)( cert_len >> 8 & 0xFF );
*p++ = (unsigned char)( cert_len & 0xFF );
*p++ = (unsigned char)( ( cert_len >> 16 ) & 0xFF );
*p++ = (unsigned char)( ( cert_len >> 8 ) & 0xFF );
*p++ = (unsigned char)( ( cert_len ) & 0xFF );
if( session->peer_cert != NULL )
memcpy( p, session->peer_cert->raw.p, cert_len );
......@@ -219,14 +219,14 @@ static int ssl_load_session( mbedtls_ssl_session *session,
size_t cert_len;
#endif /* MBEDTLS_X509_CRT_PARSE_C */
if( p + sizeof( mbedtls_ssl_session ) > end )
if( sizeof( mbedtls_ssl_session ) > (size_t)( end - p ) )
return( MBEDTLS_ERR_SSL_BAD_INPUT_DATA );
memcpy( session, p, sizeof( mbedtls_ssl_session ) );
p += sizeof( mbedtls_ssl_session );
#if defined(MBEDTLS_X509_CRT_PARSE_C)
if( p + 3 > end )
if( 3 > (size_t)( end - p ) )
return( MBEDTLS_ERR_SSL_BAD_INPUT_DATA );
cert_len = ( p[0] << 16 ) | ( p[1] << 8 ) | p[2];
......@@ -240,7 +240,7 @@ static int ssl_load_session( mbedtls_ssl_session *session,
{
int ret;
if( p + cert_len > end )
if( cert_len > (size_t)( end - p ) )
return( MBEDTLS_ERR_SSL_BAD_INPUT_DATA );
session->peer_cert = mbedtls_calloc( 1, sizeof( mbedtls_x509_crt ) );
......@@ -251,7 +251,7 @@ static int ssl_load_session( mbedtls_ssl_session *session,
mbedtls_x509_crt_init( session->peer_cert );
if( ( ret = mbedtls_x509_crt_parse_der( session->peer_cert,
p, cert_len ) ) != 0 )
p, cert_len ) ) != 0 )
{
mbedtls_x509_crt_free( session->peer_cert );
mbedtls_free( session->peer_cert );
......
......@@ -501,6 +501,7 @@ int mbedtls_ssl_derive_keys( mbedtls_ssl_context *ssl )
unsigned char *key2;
unsigned char *mac_enc;
unsigned char *mac_dec;
size_t mac_key_len;
size_t iv_copy_len;
const mbedtls_cipher_info_t *cipher_info;
const mbedtls_md_info_t *md_info;
......@@ -692,6 +693,7 @@ int mbedtls_ssl_derive_keys( mbedtls_ssl_context *ssl )
cipher_info->mode == MBEDTLS_MODE_CCM )
{
transform->maclen = 0;
mac_key_len = 0;
transform->ivlen = 12;
transform->fixed_ivlen = 4;
......@@ -712,7 +714,8 @@ int mbedtls_ssl_derive_keys( mbedtls_ssl_context *ssl )
}
/* Get MAC length */
transform->maclen = mbedtls_md_get_size( md_info );
mac_key_len = mbedtls_md_get_size( md_info );
transform->maclen = mac_key_len;
#if defined(MBEDTLS_SSL_TRUNCATED_HMAC)
/*
......@@ -721,7 +724,16 @@ int mbedtls_ssl_derive_keys( mbedtls_ssl_context *ssl )
* so we only need to adjust the length here.
*/
if( session->trunc_hmac == MBEDTLS_SSL_TRUNC_HMAC_ENABLED )
{
transform->maclen = MBEDTLS_SSL_TRUNCATED_HMAC_LEN;
#if defined(MBEDTLS_SSL_TRUNCATED_HMAC_COMPAT)
/* Fall back to old, non-compliant version of the truncated
* HMAC implementation which also truncates the key
* (Mbed TLS versions from 1.3 to 2.6.0) */
mac_key_len = transform->maclen;
#endif
}
#endif /* MBEDTLS_SSL_TRUNCATED_HMAC */
/* IV length */
......@@ -783,11 +795,11 @@ int mbedtls_ssl_derive_keys( mbedtls_ssl_context *ssl )
#if defined(MBEDTLS_SSL_CLI_C)
if( ssl->conf->endpoint == MBEDTLS_SSL_IS_CLIENT )
{
key1 = keyblk + transform->maclen * 2;
key2 = keyblk + transform->maclen * 2 + transform->keylen;
key1 = keyblk + mac_key_len * 2;
key2 = keyblk + mac_key_len * 2 + transform->keylen;
mac_enc = keyblk;
mac_dec = keyblk + transform->maclen;
mac_dec = keyblk + mac_key_len;
/*
* This is not used in TLS v1.1.
......@@ -803,10 +815,10 @@ int mbedtls_ssl_derive_keys( mbedtls_ssl_context *ssl )
#if defined(MBEDTLS_SSL_SRV_C)
if( ssl->conf->endpoint == MBEDTLS_SSL_IS_SERVER )
{
key1 = keyblk + transform->maclen * 2 + transform->keylen;
key2 = keyblk + transform->maclen * 2;
key1 = keyblk + mac_key_len * 2 + transform->keylen;
key2 = keyblk + mac_key_len * 2;
mac_enc = keyblk + transform->maclen;
mac_enc = keyblk + mac_key_len;
mac_dec = keyblk;
/*
......@@ -828,14 +840,14 @@ int mbedtls_ssl_derive_keys( mbedtls_ssl_context *ssl )
#if defined(MBEDTLS_SSL_PROTO_SSL3)
if( ssl->minor_ver == MBEDTLS_SSL_MINOR_VERSION_0 )
{
if( transform->maclen > sizeof transform->mac_enc )
if( mac_key_len > sizeof transform->mac_enc )
{
MBEDTLS_SSL_DEBUG_MSG( 1, ( "should never happen" ) );
return( MBEDTLS_ERR_SSL_INTERNAL_ERROR );
}
memcpy( transform->mac_enc, mac_enc, transform->maclen );
memcpy( transform->mac_dec, mac_dec, transform->maclen );
memcpy( transform->mac_enc, mac_enc, mac_key_len );
memcpy( transform->mac_dec, mac_dec, mac_key_len );
}
else
#endif /* MBEDTLS_SSL_PROTO_SSL3 */
......@@ -843,8 +855,13 @@ int mbedtls_ssl_derive_keys( mbedtls_ssl_context *ssl )
defined(MBEDTLS_SSL_PROTO_TLS1_2)
if( ssl->minor_ver >= MBEDTLS_SSL_MINOR_VERSION_1 )
{
mbedtls_md_hmac_starts( &transform->md_ctx_enc, mac_enc, transform->maclen );
mbedtls_md_hmac_starts( &transform->md_ctx_dec, mac_dec, transform->maclen );
/* For HMAC-based ciphersuites, initialize the HMAC transforms.
For AEAD-based ciphersuites, there is nothing to do here. */
if( mac_key_len != 0 )
{
mbedtls_md_hmac_starts( &transform->md_ctx_enc, mac_enc, mac_key_len );
mbedtls_md_hmac_starts( &transform->md_ctx_dec, mac_dec, mac_key_len );
}
}
else
#endif
......@@ -864,7 +881,7 @@ int mbedtls_ssl_derive_keys( mbedtls_ssl_context *ssl )
transform->iv_enc, transform->iv_dec,
iv_copy_len,
mac_enc, mac_dec,
transform->maclen ) ) != 0 )
mac_key_len ) ) != 0 )
{
MBEDTLS_SSL_DEBUG_RET( 1, "mbedtls_ssl_hw_record_init", ret );
return( MBEDTLS_ERR_SSL_HW_ACCEL_FAILED );
......@@ -877,7 +894,7 @@ int mbedtls_ssl_derive_keys( mbedtls_ssl_context *ssl )
{
ssl->conf->f_export_keys( ssl->conf->p_export_keys,
session->master, keyblk,
transform->maclen, transform->keylen,
mac_key_len, transform->keylen,
iv_copy_len );
}
#endif
......@@ -1136,6 +1153,9 @@ int mbedtls_ssl_psk_derive_premaster( mbedtls_ssl_context *ssl, mbedtls_key_exch
* other_secret already set by the ClientKeyExchange message,
* and is 48 bytes long
*/
if( end - p < 2 )
return( MBEDTLS_ERR_SSL_BAD_INPUT_DATA );
*p++ = 0;
*p++ = 48;
p += 48;
......@@ -1261,6 +1281,27 @@ static void ssl_mac( mbedtls_md_context_t *md_ctx,
#define SSL_SOME_MODES_USE_MAC
#endif
/* The function below is only used in the Lucky 13 counter-measure in
* ssl_decrypt_buf(). These are the defines that guard the call site. */
#if defined(SSL_SOME_MODES_USE_MAC) && \
( defined(MBEDTLS_SSL_PROTO_TLS1) || \
defined(MBEDTLS_SSL_PROTO_TLS1_1) || \
defined(MBEDTLS_SSL_PROTO_TLS1_2) )
/* This function makes sure every byte in the memory region is accessed
* (in ascending addresses order) */
static void ssl_read_memory( unsigned char *p, size_t len )
{
unsigned char acc = 0;
volatile unsigned char force;
for( ; len != 0; p++, len-- )
acc ^= *p;
force = acc;
(void) force;
}
#endif /* SSL_SOME_MODES_USE_MAC && ( TLS1 || TLS1_1 || TLS1_2 ) */
/*
* Encryption/decryption functions
*/
......@@ -1541,6 +1582,8 @@ static int ssl_encrypt_buf( mbedtls_ssl_context *ssl )
#if defined(MBEDTLS_SSL_ENCRYPT_THEN_MAC)
if( auth_done == 0 )
{
unsigned char mac[MBEDTLS_SSL_MAC_ADD];
/*
* MAC(MAC_write_key, seq_num +
* TLSCipherText.type +
......@@ -1563,10 +1606,12 @@ static int ssl_encrypt_buf( mbedtls_ssl_context *ssl )
mbedtls_md_hmac_update( &ssl->transform_out->md_ctx_enc, pseudo_hdr, 13 );
mbedtls_md_hmac_update( &ssl->transform_out->md_ctx_enc,
ssl->out_iv, ssl->out_msglen );
mbedtls_md_hmac_finish( &ssl->transform_out->md_ctx_enc,
ssl->out_iv + ssl->out_msglen );
mbedtls_md_hmac_finish( &ssl->transform_out->md_ctx_enc, mac );
mbedtls_md_hmac_reset( &ssl->transform_out->md_ctx_enc );
memcpy( ssl->out_iv + ssl->out_msglen, mac,
ssl->transform_out->maclen );
ssl->out_msglen += ssl->transform_out->maclen;
auth_done++;
}
......@@ -1885,27 +1930,27 @@ static int ssl_decrypt_buf( mbedtls_ssl_context *ssl )
* and fake check up to 256 bytes of padding
*/
size_t pad_count = 0, real_count = 1;
size_t padding_idx = ssl->in_msglen - padlen - 1;
size_t padding_idx = ssl->in_msglen - padlen;
/*
* Padding is guaranteed to be incorrect if:
* 1. padlen >= ssl->in_msglen
* 1. padlen > ssl->in_msglen
*
* 2. padding_idx >= MBEDTLS_SSL_MAX_CONTENT_LEN +
* 2. padding_idx > MBEDTLS_SSL_MAX_CONTENT_LEN +
* ssl->transform_in->maclen
*
* In both cases we reset padding_idx to a safe value (0) to
* prevent out-of-buffer reads.
*/
correct &= ( ssl->in_msglen >= padlen + 1 );
correct &= ( padding_idx < MBEDTLS_SSL_MAX_CONTENT_LEN +
correct &= ( padlen <= ssl->in_msglen );
correct &= ( padding_idx <= MBEDTLS_SSL_MAX_CONTENT_LEN +
ssl->transform_in->maclen );
padding_idx *= correct;
for( i = 1; i <= 256; i++ )
for( i = 0; i < 256; i++ )
{
real_count &= ( i <= padlen );
real_count &= ( i < padlen );
pad_count += real_count *
( ssl->in_msg[padding_idx + i] == padlen - 1 );
}
......@@ -1936,8 +1981,10 @@ static int ssl_decrypt_buf( mbedtls_ssl_context *ssl )
return( MBEDTLS_ERR_SSL_INTERNAL_ERROR );
}
#if defined(MBEDTLS_SSL_DEBUG_ALL)
MBEDTLS_SSL_DEBUG_BUF( 4, "raw buffer after decryption",
ssl->in_msg, ssl->in_msglen );
#endif
/*
* Authenticate if not done yet.
......@@ -1970,20 +2017,69 @@ static int ssl_decrypt_buf( mbedtls_ssl_context *ssl )
{
/*
* Process MAC and always update for padlen afterwards to make
* total time independent of padlen
*
* extra_run compensates MAC check for padlen
* total time independent of padlen.
*
* Known timing attacks:
* - Lucky Thirteen (http://www.isg.rhul.ac.uk/tls/TLStiming.pdf)
*
* We use ( ( Lx + 8 ) / 64 ) to handle 'negative Lx' values
* correctly. (We round down instead of up, so -56 is the correct
* value for our calculations instead of -55)
* To compensate for different timings for the MAC calculation
* depending on how much padding was removed (which is determined
* by padlen), process extra_run more blocks through the hash
* function.
*
* The formula in the paper is
* extra_run = ceil( (L1-55) / 64 ) - ceil( (L2-55) / 64 )
* where L1 is the size of the header plus the decrypted message
* plus CBC padding and L2 is the size of the header plus the
* decrypted message. This is for an underlying hash function
* with 64-byte blocks.
* We use ( (Lx+8) / 64 ) to handle 'negative Lx' values
* correctly. We round down instead of up, so -56 is the correct
* value for our calculations instead of -55.
*
* Repeat the formula rather than defining a block_size variable.
* This avoids requiring division by a variable at runtime
* (which would be marginally less efficient and would require
* linking an extra division function in some builds).
*/
size_t j, extra_run = 0;
extra_run = ( 13 + ssl->in_msglen + padlen + 8 ) / 64 -
( 13 + ssl->in_msglen + 8 ) / 64;
/*
* The next two sizes are the minimum and maximum values of
* in_msglen over all padlen values.
*
* They're independent of padlen, since we previously did
* in_msglen -= padlen.
*
* Note that max_len + maclen is never more than the buffer
* length, as we previously did in_msglen -= maclen too.
*/
const size_t max_len = ssl->in_msglen + padlen;
const size_t min_len = ( max_len > 256 ) ? max_len - 256 : 0;
switch( ssl->transform_in->ciphersuite_info->mac )
{
#if defined(MBEDTLS_MD5_C) || defined(MBEDTLS_SHA1_C) || \
defined(MBEDTLS_SHA256_C)
case MBEDTLS_MD_MD5:
case MBEDTLS_MD_SHA1:
case MBEDTLS_MD_SHA256:
/* 8 bytes of message size, 64-byte compression blocks */
extra_run = ( 13 + ssl->in_msglen + padlen + 8 ) / 64 -
( 13 + ssl->in_msglen + 8 ) / 64;
break;
#endif
#if defined(MBEDTLS_SHA512_C)
case MBEDTLS_MD_SHA384:
/* 16 bytes of message size, 128-byte compression blocks */
extra_run = ( 13 + ssl->in_msglen + padlen + 16 ) / 128 -
( 13 + ssl->in_msglen + 16 ) / 128;
break;
#endif
default:
MBEDTLS_SSL_DEBUG_MSG( 1, ( "should never happen" ) );
return( MBEDTLS_ERR_SSL_INTERNAL_ERROR );
}
extra_run &= correct * 0xFF;
......@@ -1992,12 +2088,25 @@ static int ssl_decrypt_buf( mbedtls_ssl_context *ssl )
mbedtls_md_hmac_update( &ssl->transform_in->md_ctx_dec, ssl->in_len, 2 );
mbedtls_md_hmac_update( &ssl->transform_in->md_ctx_dec, ssl->in_msg,
ssl->in_msglen );
/* Make sure we access everything even when padlen > 0. This
* makes the synchronisation requirements for just-in-time
* Prime+Probe attacks much tighter and hopefully impractical. */
ssl_read_memory( ssl->in_msg + ssl->in_msglen, padlen );
mbedtls_md_hmac_finish( &ssl->transform_in->md_ctx_dec, mac_expect );
/* Call mbedtls_md_process at least once due to cache attacks */
/* Call mbedtls_md_process at least once due to cache attacks
* that observe whether md_process() was called of not */
for( j = 0; j < extra_run + 1; j++ )
mbedtls_md_process( &ssl->transform_in->md_ctx_dec, ssl->in_msg );
mbedtls_md_hmac_reset( &ssl->transform_in->md_ctx_dec );
/* Make sure we access all the memory that could contain the MAC,
* before we check it in the next code block. This makes the
* synchronisation requirements for just-in-time Prime+Probe
* attacks much tighter and hopefully impractical. */
ssl_read_memory( ssl->in_msg + min_len,
max_len - min_len + ssl->transform_in->maclen );
}
else
#endif /* MBEDTLS_SSL_PROTO_TLS1 || MBEDTLS_SSL_PROTO_TLS1_1 || \
......@@ -2007,9 +2116,11 @@ static int ssl_decrypt_buf( mbedtls_ssl_context *ssl )
return( MBEDTLS_ERR_SSL_INTERNAL_ERROR );
}
#if defined(MBEDTLS_SSL_DEBUG_ALL)
MBEDTLS_SSL_DEBUG_BUF( 4, "expected mac", mac_expect, ssl->transform_in->maclen );
MBEDTLS_SSL_DEBUG_BUF( 4, "message mac", ssl->in_msg + ssl->in_msglen,
ssl->transform_in->maclen );
#endif
if( mbedtls_ssl_safer_memcmp( ssl->in_msg + ssl->in_msglen, mac_expect,
ssl->transform_in->maclen ) != 0 )
......@@ -2020,13 +2131,13 @@ static int ssl_decrypt_buf( mbedtls_ssl_context *ssl )
correct = 0;
}
auth_done++;
/*
* Finally check the correct flag
*/
if( correct == 0 )
return( MBEDTLS_ERR_SSL_INVALID_MAC );
}
/*
* Finally check the correct flag
*/
if( correct == 0 )
return( MBEDTLS_ERR_SSL_INVALID_MAC );
#endif /* SSL_SOME_MODES_USE_MAC */
/* Make extra sure authentication was performed, exactly once */
......@@ -2038,6 +2149,16 @@ static int ssl_decrypt_buf( mbedtls_ssl_context *ssl )
if( ssl->in_msglen == 0 )
{
#if defined(MBEDTLS_SSL_PROTO_TLS1_2)
if( ssl->minor_ver == MBEDTLS_SSL_MINOR_VERSION_3
&& ssl->in_msgtype != MBEDTLS_SSL_MSG_APPLICATION_DATA )
{
/* TLS v1.2 explicitly disallows zero-length messages which are not application data */
MBEDTLS_SSL_DEBUG_MSG( 1, ( "invalid zero-length message type: %d", ssl->in_msgtype ) );
return( MBEDTLS_ERR_SSL_INVALID_RECORD );
}
#endif /* MBEDTLS_SSL_PROTO_TLS1_2 */
ssl->nb_zero++;
/*
......@@ -2091,6 +2212,7 @@ static int ssl_compress_buf( mbedtls_ssl_context *ssl )
{
int ret;
unsigned char *msg_post = ssl->out_msg;
ptrdiff_t bytes_written = ssl->out_msg - ssl->out_buf;
size_t len_pre = ssl->out_msglen;
unsigned char *msg_pre = ssl->compress_buf;
......@@ -2110,7 +2232,7 @@ static int ssl_compress_buf( mbedtls_ssl_context *ssl )
ssl->transform_out->ctx_deflate.next_in = msg_pre;
ssl->transform_out->ctx_deflate.avail_in = len_pre;
ssl->transform_out->ctx_deflate.next_out = msg_post;
ssl->transform_out->ctx_deflate.avail_out = MBEDTLS_SSL_BUFFER_LEN;
ssl->transform_out->ctx_deflate.avail_out = MBEDTLS_SSL_BUFFER_LEN - bytes_written;
ret = deflate( &ssl->transform_out->ctx_deflate, Z_SYNC_FLUSH );
if( ret != Z_OK )
......@@ -2120,7 +2242,7 @@ static int ssl_compress_buf( mbedtls_ssl_context *ssl )
}
ssl->out_msglen = MBEDTLS_SSL_BUFFER_LEN -
ssl->transform_out->ctx_deflate.avail_out;
ssl->transform_out->ctx_deflate.avail_out - bytes_written;
MBEDTLS_SSL_DEBUG_MSG( 3, ( "after compression: msglen = %d, ",
ssl->out_msglen ) );
......@@ -2137,6 +2259,7 @@ static int ssl_decompress_buf( mbedtls_ssl_context *ssl )
{
int ret;
unsigned char *msg_post = ssl->in_msg;
ptrdiff_t header_bytes = ssl->in_msg - ssl->in_buf;
size_t len_pre = ssl->in_msglen;
unsigned char *msg_pre = ssl->compress_buf;
......@@ -2156,7 +2279,8 @@ static int ssl_decompress_buf( mbedtls_ssl_context *ssl )
ssl->transform_in->ctx_inflate.next_in = msg_pre;
ssl->transform_in->ctx_inflate.avail_in = len_pre;
ssl->transform_in->ctx_inflate.next_out = msg_post;
ssl->transform_in->ctx_inflate.avail_out = MBEDTLS_SSL_MAX_CONTENT_LEN;
ssl->transform_in->ctx_inflate.avail_out = MBEDTLS_SSL_BUFFER_LEN -
header_bytes;
ret = inflate( &ssl->transform_in->ctx_inflate, Z_SYNC_FLUSH );
if( ret != Z_OK )
......@@ -2165,8 +2289,8 @@ static int ssl_decompress_buf( mbedtls_ssl_context *ssl )
return( MBEDTLS_ERR_SSL_COMPRESSION_FAILED );
}
ssl->in_msglen = MBEDTLS_SSL_MAX_CONTENT_LEN -
ssl->transform_in->ctx_inflate.avail_out;
ssl->in_msglen = MBEDTLS_SSL_BUFFER_LEN -
ssl->transform_in->ctx_inflate.avail_out - header_bytes;
MBEDTLS_SSL_DEBUG_MSG( 3, ( "after decompression: msglen = %d, ",
ssl->in_msglen ) );
......@@ -2422,6 +2546,14 @@ int mbedtls_ssl_fetch_input( mbedtls_ssl_context *ssl, size_t nb_want )
if( ret < 0 )
return( ret );
if ( (size_t)ret > len || ( INT_MAX > SIZE_MAX && ret > SIZE_MAX ) )
{
MBEDTLS_SSL_DEBUG_MSG( 1,
( "f_recv returned %d bytes but only %lu were requested",
ret, (unsigned long)len ) );
return( MBEDTLS_ERR_SSL_INTERNAL_ERROR );
}
ssl->in_left += ret;
}
}
......@@ -2469,6 +2601,14 @@ int mbedtls_ssl_flush_output( mbedtls_ssl_context *ssl )
if( ret <= 0 )
return( ret );
if( (size_t)ret > ssl->out_left || ( INT_MAX > SIZE_MAX && ret > SIZE_MAX ) )
{
MBEDTLS_SSL_DEBUG_MSG( 1,
( "f_send returned %d bytes but only %lu bytes were sent",
ret, (unsigned long)ssl->out_left ) );
return( MBEDTLS_ERR_SSL_INTERNAL_ERROR );
}
ssl->out_left -= ret;
}
......@@ -3095,6 +3235,7 @@ static int ssl_reassemble_dtls_handshake( mbedtls_ssl_context *ssl )
memcpy( ssl->in_msg, ssl->handshake->hs_msg, ssl->in_hslen );
mbedtls_zeroize( ssl->handshake->hs_msg, ssl->in_hslen );
mbedtls_free( ssl->handshake->hs_msg );
ssl->handshake->hs_msg = NULL;
......@@ -4091,6 +4232,16 @@ int mbedtls_ssl_handle_message_type( mbedtls_ssl_context *ssl )
if( ssl->in_msgtype == MBEDTLS_SSL_MSG_ALERT )
{
if( ssl->in_msglen != 2 )
{
/* Note: Standard allows for more than one 2 byte alert
to be packed in a single message, but Mbed TLS doesn't
currently support this. */
MBEDTLS_SSL_DEBUG_MSG( 1, ( "invalid alert message, len: %d",
ssl->in_msglen ) );
return( MBEDTLS_ERR_SSL_INVALID_RECORD );
}
MBEDTLS_SSL_DEBUG_MSG( 2, ( "got an alert message, type: [%d:%d]",
ssl->in_msg[0], ssl->in_msg[1] ) );
......@@ -4514,6 +4665,12 @@ int mbedtls_ssl_parse_certificate( mbedtls_ssl_context *ssl )
while( i < ssl->in_hslen )
{
if ( i + 3 > ssl->in_hslen ) {
MBEDTLS_SSL_DEBUG_MSG( 1, ( "bad certificate message" ) );
mbedtls_ssl_send_alert_message( ssl, MBEDTLS_SSL_ALERT_LEVEL_FATAL,
MBEDTLS_SSL_ALERT_MSG_DECODE_ERROR );
return( MBEDTLS_ERR_SSL_BAD_HS_CERTIFICATE );
}
if( ssl->in_msg[i] != 0 )
{
MBEDTLS_SSL_DEBUG_MSG( 1, ( "bad certificate message" ) );
......@@ -5655,13 +5812,14 @@ int mbedtls_ssl_setup( mbedtls_ssl_context *ssl,
/*
* Prepare base structures
*/
ssl->in_buf = NULL;
ssl->out_buf = NULL;
if( ( ssl-> in_buf = mbedtls_calloc( 1, len ) ) == NULL ||
( ssl->out_buf = mbedtls_calloc( 1, len ) ) == NULL )
{
MBEDTLS_SSL_DEBUG_MSG( 1, ( "alloc(%d bytes) failed", len ) );
mbedtls_free( ssl->in_buf );
ssl->in_buf = NULL;
return( MBEDTLS_ERR_SSL_ALLOC_FAILED );
ret = MBEDTLS_ERR_SSL_ALLOC_FAILED;
goto error;
}
#if defined(MBEDTLS_SSL_PROTO_DTLS)
......@@ -5696,9 +5854,32 @@ int mbedtls_ssl_setup( mbedtls_ssl_context *ssl,
}
if( ( ret = ssl_handshake_init( ssl ) ) != 0 )
return( ret );
goto error;
return( 0 );
error:
mbedtls_free( ssl->in_buf );
mbedtls_free( ssl->out_buf );
ssl->conf = NULL;
ssl->in_buf = NULL;
ssl->out_buf = NULL;
ssl->in_hdr = NULL;
ssl->in_ctr = NULL;
ssl->in_len = NULL;
ssl->in_iv = NULL;
ssl->in_msg = NULL;
ssl->out_hdr = NULL;
ssl->out_ctr = NULL;
ssl->out_len = NULL;
ssl->out_iv = NULL;
ssl->out_msg = NULL;
return( ret );
}
/*
......@@ -5759,7 +5940,11 @@ static int ssl_session_reset_int( mbedtls_ssl_context *ssl, int partial )
ssl->transform_in = NULL;
ssl->transform_out = NULL;
ssl->session_in = NULL;
ssl->session_out = NULL;
memset( ssl->out_buf, 0, MBEDTLS_SSL_BUFFER_LEN );
if( partial == 0 )
memset( ssl->in_buf, 0, MBEDTLS_SSL_BUFFER_LEN );
......@@ -5981,27 +6166,27 @@ static int ssl_append_key_cert( mbedtls_ssl_key_cert **head,
mbedtls_x509_crt *cert,
mbedtls_pk_context *key )
{
mbedtls_ssl_key_cert *new;
mbedtls_ssl_key_cert *new_cert;
new = mbedtls_calloc( 1, sizeof( mbedtls_ssl_key_cert ) );
if( new == NULL )
new_cert = mbedtls_calloc( 1, sizeof( mbedtls_ssl_key_cert ) );
if( new_cert == NULL )
return( MBEDTLS_ERR_SSL_ALLOC_FAILED );
new->cert = cert;
new->key = key;
new->next = NULL;
new_cert->cert = cert;
new_cert->key = key;
new_cert->next = NULL;
/* Update head is the list was null, else add to the end */
if( *head == NULL )
{
*head = new;
*head = new_cert;
}
else
{
mbedtls_ssl_key_cert *cur = *head;
while( cur->next != NULL )
cur = cur->next;
cur->next = new;
cur->next = new_cert;
}
return( 0 );
......@@ -6532,17 +6717,18 @@ const char *mbedtls_ssl_get_version( const mbedtls_ssl_context *ssl )
int mbedtls_ssl_get_record_expansion( const mbedtls_ssl_context *ssl )
{
size_t transform_expansion;
size_t transform_expansion = 0;
const mbedtls_ssl_transform *transform = ssl->transform_out;
unsigned block_size;
if( transform == NULL )
return( (int) mbedtls_ssl_hdr_len( ssl ) );
#if defined(MBEDTLS_ZLIB_SUPPORT)
if( ssl->session_out->compression != MBEDTLS_SSL_COMPRESS_NULL )
return( MBEDTLS_ERR_SSL_FEATURE_UNAVAILABLE );
#endif
if( transform == NULL )
return( (int) mbedtls_ssl_hdr_len( ssl ) );
switch( mbedtls_cipher_get_cipher_mode( &transform->cipher_ctx_enc ) )
{
case MBEDTLS_MODE_GCM:
......@@ -6552,8 +6738,25 @@ int mbedtls_ssl_get_record_expansion( const mbedtls_ssl_context *ssl )
break;
case MBEDTLS_MODE_CBC:
transform_expansion = transform->maclen
+ mbedtls_cipher_get_block_size( &transform->cipher_ctx_enc );
block_size = mbedtls_cipher_get_block_size(
&transform->cipher_ctx_enc );
/* Expansion due to the addition of the MAC. */
transform_expansion += transform->maclen;
/* Expansion due to the addition of CBC padding;
* Theoretically up to 256 bytes, but we never use
* more than the block size of the underlying cipher. */
transform_expansion += block_size;
/* For TLS 1.1 or higher, an explicit IV is added
* after the record header. */
#if defined(MBEDTLS_SSL_PROTO_TLS1_1) || defined(MBEDTLS_SSL_PROTO_TLS1_2)
if( ssl->minor_ver >= MBEDTLS_SSL_MINOR_VERSION_2 )
transform_expansion += block_size;
#endif /* MBEDTLS_SSL_PROTO_TLS1_1 || MBEDTLS_SSL_PROTO_TLS1_2 */
break;
default:
......@@ -6880,41 +7083,6 @@ int mbedtls_ssl_read( mbedtls_ssl_context *ssl, unsigned char *buf, size_t len )
}
}
/*
* TODO
*
* The logic should be streamlined here:
*
* Instead of
*
* - Manually checking whether ssl->in_offt is NULL
* - Fetching a new record if yes
* - Setting ssl->in_offt if one finds an application record
* - Resetting keep_current_message after handling the application data
*
* one should
*
* - Adapt read_record to set ssl->in_offt automatically
* when a new application data record is processed.
* - Always call mbedtls_ssl_read_record here.
*
* This way, the logic of ssl_read would be much clearer:
*
* (1) Always call record layer and see what kind of record is on
* and have it ready for consumption (in particular, in_offt
* properly set for application data records).
* (2) If it's application data (either freshly fetched
* or something already being partially processed),
* serve the read request from it.
* (3) If it's something different from application data,
* handle it accordingly, e.g. potentially start a
* renegotiation.
*
* This will also remove the need to manually reset
* ssl->keep_current_message = 0 below.
*
*/
if( ssl->in_offt == NULL )
{
/* Start timer if not already running */
......@@ -7136,8 +7304,16 @@ int mbedtls_ssl_read( mbedtls_ssl_context *ssl, unsigned char *buf, size_t len )
}
/*
* Send application data to be encrypted by the SSL layer,
* taking care of max fragment length and buffer size
* Send application data to be encrypted by the SSL layer, taking care of max
* fragment length and buffer size.
*
* According to RFC 5246 Section 6.2.1:
*
* Zero-length fragments of Application data MAY be sent as they are
* potentially useful as a traffic analysis countermeasure.
*
* Therefore, it is possible that the input message length is 0 and the
* corresponding return code is 0 on success.
*/
static int ssl_write_real( mbedtls_ssl_context *ssl,
const unsigned char *buf, size_t len )
......@@ -7165,6 +7341,12 @@ static int ssl_write_real( mbedtls_ssl_context *ssl,
if( ssl->out_left != 0 )
{
/*
* The user has previously tried to send the data and
* MBEDTLS_ERR_SSL_WANT_WRITE or the message was only partially
* written. In this case, we expect the high-level write function
* (e.g. mbedtls_ssl_write()) to be called with the same parameters
*/
if( ( ret = mbedtls_ssl_flush_output( ssl ) ) != 0 )
{
MBEDTLS_SSL_DEBUG_RET( 1, "mbedtls_ssl_flush_output", ret );
......@@ -7173,6 +7355,11 @@ static int ssl_write_real( mbedtls_ssl_context *ssl,
}
else
{
/*
* The user is trying to send a message the first time, so we need to
* copy the data into the internal buffers and setup the data structure
* to keep track of partial writes
*/
ssl->out_msglen = len;
ssl->out_msgtype = MBEDTLS_SSL_MSG_APPLICATION_DATA;
memcpy( ssl->out_msg, buf, len );
......@@ -7673,8 +7860,14 @@ int mbedtls_ssl_config_defaults( mbedtls_ssl_config *conf,
* Default
*/
default:
conf->min_major_ver = MBEDTLS_SSL_MAJOR_VERSION_3;
conf->min_minor_ver = MBEDTLS_SSL_MINOR_VERSION_1; /* TLS 1.0 */
conf->min_major_ver = ( MBEDTLS_SSL_MIN_MAJOR_VERSION >
MBEDTLS_SSL_MIN_VALID_MAJOR_VERSION ) ?
MBEDTLS_SSL_MIN_MAJOR_VERSION :
MBEDTLS_SSL_MIN_VALID_MAJOR_VERSION;
conf->min_minor_ver = ( MBEDTLS_SSL_MIN_MINOR_VERSION >
MBEDTLS_SSL_MIN_VALID_MINOR_VERSION ) ?
MBEDTLS_SSL_MIN_MINOR_VERSION :
MBEDTLS_SSL_MIN_VALID_MINOR_VERSION;
conf->max_major_ver = MBEDTLS_SSL_MAX_MAJOR_VERSION;
conf->max_minor_ver = MBEDTLS_SSL_MAX_MINOR_VERSION;
......
......@@ -111,8 +111,12 @@ void mbedtls_threading_set_alt( void (*mutex_init)( mbedtls_threading_mutex_t *
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(MBEDTLS_HAVE_TIME_DATE)
mbedtls_mutex_init( &mbedtls_threading_gmtime_mutex );
#endif
}
/*
......@@ -120,8 +124,12 @@ void mbedtls_threading_set_alt( void (*mutex_init)( mbedtls_threading_mutex_t *
*/
void mbedtls_threading_free_alt( void )
{
#if defined(MBEDTLS_FS_IO)
mbedtls_mutex_free( &mbedtls_threading_readdir_mutex );
#endif
#if defined(MBEDTLS_HAVE_TIME_DATE)
mbedtls_mutex_free( &mbedtls_threading_gmtime_mutex );
#endif
}
#endif /* MBEDTLS_THREADING_ALT */
......@@ -131,7 +139,11 @@ void mbedtls_threading_free_alt( void )
#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(MBEDTLS_HAVE_TIME_DATE)
mbedtls_threading_mutex_t mbedtls_threading_gmtime_mutex MUTEX_INIT;
#endif
#endif /* MBEDTLS_THREADING_C */
......@@ -51,6 +51,7 @@
#include <windows.h>
#include <winbase.h>
#include <process.h>
struct _hr_time
{
......@@ -266,18 +267,17 @@ unsigned long mbedtls_timing_get_timer( struct mbedtls_timing_hr_time *val, int
/* It's OK to use a global because alarm() is supposed to be global anyway */
static DWORD alarmMs;
static DWORD WINAPI TimerProc( LPVOID TimerContext )
static void TimerProc( void *TimerContext )
{
((void) TimerContext);
(void) TimerContext;
Sleep( alarmMs );
mbedtls_timing_alarmed = 1;
return( TRUE );
/* _endthread will be called implicitly on return
* That ensures execution of thread funcition's epilogue */
}
void mbedtls_set_alarm( int seconds )
{
DWORD ThreadId;
if( seconds == 0 )
{
/* No need to create a thread for this simple case.
......@@ -288,7 +288,7 @@ void mbedtls_set_alarm( int seconds )
mbedtls_timing_alarmed = 0;
alarmMs = seconds * 1000;
CloseHandle( CreateThread( NULL, 0, TimerProc, NULL, 0, &ThreadId ) );
(void) _beginthread( TimerProc, 0, NULL );
}
#else /* _WIN32 && !EFIX64 && !EFI32 */
......
......@@ -468,6 +468,9 @@ static const char *features[] = {
#if defined(MBEDTLS_SSL_TRUNCATED_HMAC)
"MBEDTLS_SSL_TRUNCATED_HMAC",
#endif /* MBEDTLS_SSL_TRUNCATED_HMAC */
#if defined(MBEDTLS_SSL_TRUNCATED_HMAC_COMPAT)
"MBEDTLS_SSL_TRUNCATED_HMAC_COMPAT",
#endif /* MBEDTLS_SSL_TRUNCATED_HMAC_COMPAT */
#if defined(MBEDTLS_THREADING_ALT)
"MBEDTLS_THREADING_ALT",
#endif /* MBEDTLS_THREADING_ALT */
......
......@@ -70,15 +70,6 @@
#include <time.h>
#endif
#if defined(MBEDTLS_FS_IO)
#include <stdio.h>
#if !defined(_WIN32)
#include <sys/types.h>
#include <sys/stat.h>
#include <dirent.h>
#endif
#endif
#define CHECK(code) if( ( ret = code ) != 0 ){ return( ret ); }
#define CHECK_RANGE(min, max, val) if( val < min || val > max ){ return( ret ); }
......
......@@ -95,17 +95,23 @@ static int x509_crl_get_version( unsigned char **p,
}
/*
* X.509 CRL v2 extensions (no extensions parsed yet.)
* X.509 CRL v2 extensions
*
* We currently don't parse any extension's content, but we do check that the
* list of extensions is well-formed and abort on critical extensions (that
* are unsupported as we don't support any extension so far)
*/
static int x509_get_crl_ext( unsigned char **p,
const unsigned char *end,
mbedtls_x509_buf *ext )
{
int ret;
size_t len = 0;
/* Get explicit tag */
if( ( ret = mbedtls_x509_get_ext( p, end, ext, 0) ) != 0 )
/*
* crlExtensions [0] EXPLICIT Extensions OPTIONAL
* -- if present, version MUST be v2
*/
if( ( ret = mbedtls_x509_get_ext( p, end, ext, 0 ) ) != 0 )
{
if( ret == MBEDTLS_ERR_ASN1_UNEXPECTED_TAG )
return( 0 );
......@@ -115,11 +121,54 @@ static int x509_get_crl_ext( unsigned char **p,
while( *p < end )
{
/*
* Extension ::= SEQUENCE {
* extnID OBJECT IDENTIFIER,
* critical BOOLEAN DEFAULT FALSE,
* extnValue OCTET STRING }
*/
int is_critical = 0;
const unsigned char *end_ext_data;
size_t len;
/* Get enclosing sequence tag */
if( ( ret = mbedtls_asn1_get_tag( p, end, &len,
MBEDTLS_ASN1_CONSTRUCTED | MBEDTLS_ASN1_SEQUENCE ) ) != 0 )
return( MBEDTLS_ERR_X509_INVALID_EXTENSIONS + ret );
end_ext_data = *p + len;
/* Get OID (currently ignored) */
if( ( ret = mbedtls_asn1_get_tag( p, end_ext_data, &len,
MBEDTLS_ASN1_OID ) ) != 0 )
{
return( MBEDTLS_ERR_X509_INVALID_EXTENSIONS + ret );
}
*p += len;
/* Get optional critical */
if( ( ret = mbedtls_asn1_get_bool( p, end_ext_data,
&is_critical ) ) != 0 &&
( ret != MBEDTLS_ERR_ASN1_UNEXPECTED_TAG ) )
{
return( MBEDTLS_ERR_X509_INVALID_EXTENSIONS + ret );
}
/* Data should be octet string type */
if( ( ret = mbedtls_asn1_get_tag( p, end_ext_data, &len,
MBEDTLS_ASN1_OCTET_STRING ) ) != 0 )
return( MBEDTLS_ERR_X509_INVALID_EXTENSIONS + ret );
/* Ignore data so far and just check its length */
*p += len;
if( *p != end_ext_data )
return( MBEDTLS_ERR_X509_INVALID_EXTENSIONS +
MBEDTLS_ERR_ASN1_LENGTH_MISMATCH );
/* Abort on (unsupported) critical extensions */
if( is_critical )
return( MBEDTLS_ERR_X509_INVALID_EXTENSIONS +
MBEDTLS_ERR_ASN1_UNEXPECTED_TAG );
}
if( *p != end )
......@@ -257,7 +306,7 @@ int mbedtls_x509_crl_parse_der( mbedtls_x509_crl *chain,
{
int ret;
size_t len;
unsigned char *p, *end;
unsigned char *p = NULL, *end = NULL;
mbedtls_x509_buf sig_params1, sig_params2, sig_oid2;
mbedtls_x509_crl *crl = chain;
......@@ -294,7 +343,11 @@ int mbedtls_x509_crl_parse_der( mbedtls_x509_crl *chain,
/*
* Copy raw DER-encoded CRL
*/
if( ( p = mbedtls_calloc( 1, buflen ) ) == NULL )
if( buflen == 0 )
return( MBEDTLS_ERR_X509_INVALID_FORMAT );
p = mbedtls_calloc( 1, buflen );
if( p == NULL )
return( MBEDTLS_ERR_X509_ALLOC_FAILED );
memcpy( p, buf, buflen );
......
......@@ -40,7 +40,6 @@
#include "mbedtls/x509_crt.h"
#include "mbedtls/oid.h"
#include <stdio.h>
#include <string.h>
#if defined(MBEDTLS_PEM_PARSE_C)
......@@ -50,6 +49,7 @@
#if defined(MBEDTLS_PLATFORM_C)
#include "mbedtls/platform.h"
#else
#include <stdio.h>
#include <stdlib.h>
#define mbedtls_free free
#define mbedtls_calloc calloc
......@@ -133,7 +133,8 @@ const mbedtls_x509_crt_profile mbedtls_x509_crt_profile_suiteb =
MBEDTLS_X509_ID_FLAG( MBEDTLS_MD_SHA256 ) |
MBEDTLS_X509_ID_FLAG( MBEDTLS_MD_SHA384 ),
/* Only ECDSA */
MBEDTLS_X509_ID_FLAG( MBEDTLS_PK_ECDSA ),
MBEDTLS_X509_ID_FLAG( MBEDTLS_PK_ECDSA ) |
MBEDTLS_X509_ID_FLAG( MBEDTLS_PK_ECKEY ),
#if defined(MBEDTLS_ECP_C)
/* Only NIST P-256 and P-384 */
MBEDTLS_X509_ID_FLAG( MBEDTLS_ECP_DP_SECP256R1 ) |
......@@ -151,6 +152,9 @@ const mbedtls_x509_crt_profile mbedtls_x509_crt_profile_suiteb =
static int x509_profile_check_md_alg( const mbedtls_x509_crt_profile *profile,
mbedtls_md_type_t md_alg )
{
if( md_alg == MBEDTLS_MD_NONE )
return( -1 );
if( ( profile->allowed_mds & MBEDTLS_X509_ID_FLAG( md_alg ) ) != 0 )
return( 0 );
......@@ -164,6 +168,9 @@ static int x509_profile_check_md_alg( const mbedtls_x509_crt_profile *profile,
static int x509_profile_check_pk_alg( const mbedtls_x509_crt_profile *profile,
mbedtls_pk_type_t pk_alg )
{
if( pk_alg == MBEDTLS_PK_NONE )
return( -1 );
if( ( profile->allowed_pks & MBEDTLS_X509_ID_FLAG( pk_alg ) ) != 0 )
return( 0 );
......@@ -195,6 +202,9 @@ static int x509_profile_check_key( const mbedtls_x509_crt_profile *profile,
{
mbedtls_ecp_group_id gid = mbedtls_pk_ec( *pk )->grp.id;
if( gid == MBEDTLS_ECP_DP_NONE )
return( -1 );
if( ( profile->allowed_curves & MBEDTLS_X509_ID_FLAG( gid ) ) != 0 )
return( 0 );
......@@ -472,9 +482,12 @@ static int x509_get_subject_alt_name( unsigned char **p,
if( ( ret = mbedtls_asn1_get_len( p, end, &tag_len ) ) != 0 )
return( MBEDTLS_ERR_X509_INVALID_EXTENSIONS + ret );
if( ( tag & MBEDTLS_ASN1_CONTEXT_SPECIFIC ) != MBEDTLS_ASN1_CONTEXT_SPECIFIC )
if( ( tag & MBEDTLS_ASN1_TAG_CLASS_MASK ) !=
MBEDTLS_ASN1_CONTEXT_SPECIFIC )
{
return( MBEDTLS_ERR_X509_INVALID_EXTENSIONS +
MBEDTLS_ERR_ASN1_UNEXPECTED_TAG );
}
/* Skip everything but DNS name */
if( tag != ( MBEDTLS_ASN1_CONTEXT_SPECIFIC | 2 ) )
......@@ -554,18 +567,14 @@ static int x509_get_crt_ext( unsigned char **p,
end_ext_data = *p + len;
/* Get extension ID */
extn_oid.tag = **p;
if( ( ret = mbedtls_asn1_get_tag( p, end, &extn_oid.len, MBEDTLS_ASN1_OID ) ) != 0 )
if( ( ret = mbedtls_asn1_get_tag( p, end_ext_data, &extn_oid.len,
MBEDTLS_ASN1_OID ) ) != 0 )
return( MBEDTLS_ERR_X509_INVALID_EXTENSIONS + ret );
extn_oid.tag = MBEDTLS_ASN1_OID;
extn_oid.p = *p;
*p += extn_oid.len;
if( ( end - *p ) < 1 )
return( MBEDTLS_ERR_X509_INVALID_EXTENSIONS +
MBEDTLS_ERR_ASN1_OUT_OF_DATA );
/* Get optional critical */
if( ( ret = mbedtls_asn1_get_bool( p, end_ext_data, &is_critical ) ) != 0 &&
( ret != MBEDTLS_ERR_ASN1_UNEXPECTED_TAG ) )
......@@ -713,7 +722,7 @@ static int x509_crt_parse_der_core( mbedtls_x509_crt *crt, const unsigned char *
memcpy( p, buf, crt->raw.len );
// Direct pointers to the new buffer
// Direct pointers to the new buffer
p += crt->raw.len - len;
end = crt_end = p + len;
......@@ -1354,6 +1363,135 @@ static int x509_info_ext_key_usage( char **buf, size_t *size,
return( 0 );
}
/*
* Like memcmp, but case-insensitive and always returns -1 if different
*/
static int x509_memcasecmp( const void *s1, const void *s2, size_t len )
{
size_t i;
unsigned char diff;
const unsigned char *n1 = s1, *n2 = s2;
for( i = 0; i < len; i++ )
{
diff = n1[i] ^ n2[i];
if( diff == 0 )
continue;
if( diff == 32 &&
( ( n1[i] >= 'a' && n1[i] <= 'z' ) ||
( n1[i] >= 'A' && n1[i] <= 'Z' ) ) )
{
continue;
}
return( -1 );
}
return( 0 );
}
/*
* Return 0 if name matches wildcard, -1 otherwise
*/
static int x509_check_wildcard( const char *cn, mbedtls_x509_buf *name )
{
size_t i;
size_t cn_idx = 0, cn_len = strlen( cn );
if( name->len < 3 || name->p[0] != '*' || name->p[1] != '.' )
return( 0 );
for( i = 0; i < cn_len; ++i )
{
if( cn[i] == '.' )
{
cn_idx = i;
break;
}
}
if( cn_idx == 0 )
return( -1 );
if( cn_len - cn_idx == name->len - 1 &&
x509_memcasecmp( name->p + 1, cn + cn_idx, name->len - 1 ) == 0 )
{
return( 0 );
}
return( -1 );
}
/*
* Compare two X.509 strings, case-insensitive, and allowing for some encoding
* variations (but not all).
*
* Return 0 if equal, -1 otherwise.
*/
static int x509_string_cmp( const mbedtls_x509_buf *a, const mbedtls_x509_buf *b )
{
if( a->tag == b->tag &&
a->len == b->len &&
memcmp( a->p, b->p, b->len ) == 0 )
{
return( 0 );
}
if( ( a->tag == MBEDTLS_ASN1_UTF8_STRING || a->tag == MBEDTLS_ASN1_PRINTABLE_STRING ) &&
( b->tag == MBEDTLS_ASN1_UTF8_STRING || b->tag == MBEDTLS_ASN1_PRINTABLE_STRING ) &&
a->len == b->len &&
x509_memcasecmp( a->p, b->p, b->len ) == 0 )
{
return( 0 );
}
return( -1 );
}
/*
* Compare two X.509 Names (aka rdnSequence).
*
* See RFC 5280 section 7.1, though we don't implement the whole algorithm:
* we sometimes return unequal when the full algorithm would return equal,
* but never the other way. (In particular, we don't do Unicode normalisation
* or space folding.)
*
* Return 0 if equal, -1 otherwise.
*/
static int x509_name_cmp( const mbedtls_x509_name *a, const mbedtls_x509_name *b )
{
/* Avoid recursion, it might not be optimised by the compiler */
while( a != NULL || b != NULL )
{
if( a == NULL || b == NULL )
return( -1 );
/* type */
if( a->oid.tag != b->oid.tag ||
a->oid.len != b->oid.len ||
memcmp( a->oid.p, b->oid.p, b->oid.len ) != 0 )
{
return( -1 );
}
/* value */
if( x509_string_cmp( &a->val, &b->val ) != 0 )
return( -1 );
/* structure of the list of sets */
if( a->next_merged != b->next_merged )
return( -1 );
a = a->next;
b = b->next;
}
/* a == NULL == b */
return( 0 );
}
/*
* Return an informational string about the certificate.
*/
......@@ -1630,7 +1768,7 @@ int mbedtls_x509_crt_is_revoked( const mbedtls_x509_crt *crt, const mbedtls_x509
/*
* Check that the given certificate is not revoked according to the CRL.
* Skip validation is no CRL for the given CA is present.
* Skip validation if no CRL for the given CA is present.
*/
static int x509_crt_verifycrl( mbedtls_x509_crt *crt, mbedtls_x509_crt *ca,
mbedtls_x509_crl *crl_list,
......@@ -1646,9 +1784,7 @@ static int x509_crt_verifycrl( mbedtls_x509_crt *crt, mbedtls_x509_crt *ca,
while( crl_list != NULL )
{
if( crl_list->version == 0 ||
crl_list->issuer_raw.len != ca->subject_raw.len ||
memcmp( crl_list->issuer_raw.p, ca->subject_raw.p,
crl_list->issuer_raw.len ) != 0 )
x509_name_cmp( &crl_list->issuer, &ca->subject ) != 0 )
{
crl_list = crl_list->next;
continue;
......@@ -1658,7 +1794,8 @@ static int x509_crt_verifycrl( mbedtls_x509_crt *crt, mbedtls_x509_crt *ca,
* Check if the CA is configured to sign CRLs
*/
#if defined(MBEDTLS_X509_CHECK_KEY_USAGE)
if( mbedtls_x509_crt_check_key_usage( ca, MBEDTLS_X509_KU_CRL_SIGN ) != 0 )
if( mbedtls_x509_crt_check_key_usage( ca,
MBEDTLS_X509_KU_CRL_SIGN ) != 0 )
{
flags |= MBEDTLS_X509_BADCRL_NOT_TRUSTED;
break;
......@@ -1675,17 +1812,13 @@ static int x509_crt_verifycrl( mbedtls_x509_crt *crt, mbedtls_x509_crt *ca,
flags |= MBEDTLS_X509_BADCRL_BAD_PK;
md_info = mbedtls_md_info_from_type( crl_list->sig_md );
if( md_info == NULL )
if( mbedtls_md( md_info, crl_list->tbs.p, crl_list->tbs.len, hash ) != 0 )
{
/*
* Cannot check 'unknown' hash
*/
/* Note: this can't happen except after an internal error */
flags |= MBEDTLS_X509_BADCRL_NOT_TRUSTED;
break;
}
mbedtls_md( md_info, crl_list->tbs.p, crl_list->tbs.len, hash );
if( x509_profile_check_key( profile, crl_list->sig_pk, &ca->pk ) != 0 )
flags |= MBEDTLS_X509_BADCERT_BAD_KEY;
......@@ -1722,135 +1855,6 @@ static int x509_crt_verifycrl( mbedtls_x509_crt *crt, mbedtls_x509_crt *ca,
}
#endif /* MBEDTLS_X509_CRL_PARSE_C */
/*
* Like memcmp, but case-insensitive and always returns -1 if different
*/
static int x509_memcasecmp( const void *s1, const void *s2, size_t len )
{
size_t i;
unsigned char diff;
const unsigned char *n1 = s1, *n2 = s2;
for( i = 0; i < len; i++ )
{
diff = n1[i] ^ n2[i];
if( diff == 0 )
continue;
if( diff == 32 &&
( ( n1[i] >= 'a' && n1[i] <= 'z' ) ||
( n1[i] >= 'A' && n1[i] <= 'Z' ) ) )
{
continue;
}
return( -1 );
}
return( 0 );
}
/*
* Return 0 if name matches wildcard, -1 otherwise
*/
static int x509_check_wildcard( const char *cn, mbedtls_x509_buf *name )
{
size_t i;
size_t cn_idx = 0, cn_len = strlen( cn );
if( name->len < 3 || name->p[0] != '*' || name->p[1] != '.' )
return( 0 );
for( i = 0; i < cn_len; ++i )
{
if( cn[i] == '.' )
{
cn_idx = i;
break;
}
}
if( cn_idx == 0 )
return( -1 );
if( cn_len - cn_idx == name->len - 1 &&
x509_memcasecmp( name->p + 1, cn + cn_idx, name->len - 1 ) == 0 )
{
return( 0 );
}
return( -1 );
}
/*
* Compare two X.509 strings, case-insensitive, and allowing for some encoding
* variations (but not all).
*
* Return 0 if equal, -1 otherwise.
*/
static int x509_string_cmp( const mbedtls_x509_buf *a, const mbedtls_x509_buf *b )
{
if( a->tag == b->tag &&
a->len == b->len &&
memcmp( a->p, b->p, b->len ) == 0 )
{
return( 0 );
}
if( ( a->tag == MBEDTLS_ASN1_UTF8_STRING || a->tag == MBEDTLS_ASN1_PRINTABLE_STRING ) &&
( b->tag == MBEDTLS_ASN1_UTF8_STRING || b->tag == MBEDTLS_ASN1_PRINTABLE_STRING ) &&
a->len == b->len &&
x509_memcasecmp( a->p, b->p, b->len ) == 0 )
{
return( 0 );
}
return( -1 );
}
/*
* Compare two X.509 Names (aka rdnSequence).
*
* See RFC 5280 section 7.1, though we don't implement the whole algorithm:
* we sometimes return unequal when the full algorithm would return equal,
* but never the other way. (In particular, we don't do Unicode normalisation
* or space folding.)
*
* Return 0 if equal, -1 otherwise.
*/
static int x509_name_cmp( const mbedtls_x509_name *a, const mbedtls_x509_name *b )
{
/* Avoid recursion, it might not be optimised by the compiler */
while( a != NULL || b != NULL )
{
if( a == NULL || b == NULL )
return( -1 );
/* type */
if( a->oid.tag != b->oid.tag ||
a->oid.len != b->oid.len ||
memcmp( a->oid.p, b->oid.p, b->oid.len ) != 0 )
{
return( -1 );
}
/* value */
if( x509_string_cmp( &a->val, &b->val ) != 0 )
return( -1 );
/* structure of the list of sets */
if( a->next_merged != b->next_merged )
return( -1 );
a = a->next;
b = b->next;
}
/* a == NULL == b */
return( 0 );
}
/*
* Check if 'parent' is a suitable parent (signing CA) for 'child'.
* Return 0 if yes, -1 if not.
......@@ -1897,6 +1901,27 @@ static int x509_crt_check_parent( const mbedtls_x509_crt *child,
return( 0 );
}
/*
* Verify a certificate with no parent inside the chain
* (either the parent is a trusted root, or there is no parent)
*
* See comments for mbedtls_x509_crt_verify_with_profile()
* (also for notation used below)
*
* This function is called in two cases:
* - child was found to have a parent in trusted roots, in which case we're
* called with trust_ca pointing directly to that parent (not the full list)
* - this is cases 1, 2 and 3 of the comment on verify_with_profile()
* - case 1 is special as child and trust_ca point to copies of the same
* certificate then
* - child was found to have no parent either in the chain or in trusted CAs
* - this is cases 4 and 5 of the comment on verify_with_profile()
*
* For historical reasons, the function currently does not assume that
* trust_ca points directly to the right root in the first case, and it
* doesn't know in which case it starts, so it always starts by searching for
* a parent in trust_ca.
*/
static int x509_crt_verify_top(
mbedtls_x509_crt *child, mbedtls_x509_crt *trust_ca,
mbedtls_x509_crl *ca_crl,
......@@ -1930,15 +1955,12 @@ static int x509_crt_verify_top(
*flags |= MBEDTLS_X509_BADCERT_NOT_TRUSTED;
md_info = mbedtls_md_info_from_type( child->sig_md );
if( md_info == NULL )
if( mbedtls_md( md_info, child->tbs.p, child->tbs.len, hash ) != 0 )
{
/*
* Cannot check 'unknown', no need to try any CA
*/
/* Note: this can't happen except after an internal error */
/* Cannot check signature, no need to try any CA */
trust_ca = NULL;
}
else
mbedtls_md( md_info, child->tbs.p, child->tbs.len, hash );
for( /* trust_ca */ ; trust_ca != NULL; trust_ca = trust_ca->next )
{
......@@ -1953,7 +1975,7 @@ static int x509_crt_verify_top(
*/
if( child->subject_raw.len == trust_ca->subject_raw.len &&
memcmp( child->subject_raw.p, trust_ca->subject_raw.p,
child->issuer_raw.len ) == 0 )
child->subject_raw.len ) == 0 )
{
check_path_cnt--;
}
......@@ -2003,7 +2025,7 @@ static int x509_crt_verify_top(
if( trust_ca != NULL &&
( child->subject_raw.len != trust_ca->subject_raw.len ||
memcmp( child->subject_raw.p, trust_ca->subject_raw.p,
child->issuer_raw.len ) != 0 ) )
child->subject_raw.len ) != 0 ) )
{
#if defined(MBEDTLS_X509_CRL_PARSE_C)
/* Check trusted CA's CRL for the chain's top crt */
......@@ -2040,6 +2062,11 @@ static int x509_crt_verify_top(
return( 0 );
}
/*
* Verify a certificate with a parent inside the chain
*
* See comments for mbedtls_x509_crt_verify_with_profile()
*/
static int x509_crt_verify_child(
mbedtls_x509_crt *child, mbedtls_x509_crt *parent,
mbedtls_x509_crt *trust_ca, mbedtls_x509_crl *ca_crl,
......@@ -2078,17 +2105,13 @@ static int x509_crt_verify_child(
*flags |= MBEDTLS_X509_BADCERT_BAD_PK;
md_info = mbedtls_md_info_from_type( child->sig_md );
if( md_info == NULL )
if( mbedtls_md( md_info, child->tbs.p, child->tbs.len, hash ) != 0 )
{
/*
* Cannot check 'unknown' hash
*/
/* Note: this can't happen except after an internal error */
*flags |= MBEDTLS_X509_BADCERT_NOT_TRUSTED;
}
else
{
mbedtls_md( md_info, child->tbs.p, child->tbs.len, hash );
if( x509_profile_check_key( profile, child->sig_pk, &parent->pk ) != 0 )
*flags |= MBEDTLS_X509_BADCERT_BAD_KEY;
......@@ -2189,6 +2212,34 @@ int mbedtls_x509_crt_verify( mbedtls_x509_crt *crt,
/*
* Verify the certificate validity, with profile
*
* The chain building/verification is spread accross 4 functions:
* - this one
* - x509_crt_verify_child()
* - x509_crt_verify_top()
* - x509_crt_check_parent()
*
* There are five main cases to consider. Let's introduce some notation:
* - E means the end-entity certificate
* - I an intermediate CA
* - R the trusted root CA this chain anchors to
* - T the list of trusted roots (R and possible some others)
*
* The main cases with the calling sequence of the crt_verify_xxx() are:
* 1. E = R (explicitly trusted EE cert)
* verify(E, T) -> verify_top(E, R)
* 2. E -> R (EE signed by trusted root)
* verify(E, T) -> verify_top(E, R)
* 3. E -> I -> R (EE signed by intermediate signed by trusted root)
* verify(E, T) -> verify_child(E, I, T) -> verify_top(I, R)
* (plus variant with multiple intermediates)
* 4. E -> I (EE signed by intermediate that's not trusted)
* verify(E, T) -> verify_child(E, I, T) -> verify_top(I, T)
* (plus variant with multiple intermediates)
* 5. E (EE not trusted)
* verify(E, T) -> verify_top(E, T)
*
* Note: this notation and case numbering is also used in x509_crt_verify_top()
*/
int mbedtls_x509_crt_verify_with_profile( mbedtls_x509_crt *crt,
mbedtls_x509_crt *trust_ca,
......
......@@ -278,34 +278,25 @@ int mbedtls_x509_csr_parse( mbedtls_x509_csr *csr, const unsigned char *buf, siz
return( MBEDTLS_ERR_X509_BAD_INPUT_DATA );
#if defined(MBEDTLS_PEM_PARSE_C)
mbedtls_pem_init( &pem );
/* Avoid calling mbedtls_pem_read_buffer() on non-null-terminated string */
if( buf[buflen - 1] != '\0' )
ret = MBEDTLS_ERR_PEM_NO_HEADER_FOOTER_PRESENT;
else
if( buf[buflen - 1] == '\0' )
{
mbedtls_pem_init( &pem );
ret = mbedtls_pem_read_buffer( &pem,
"-----BEGIN CERTIFICATE REQUEST-----",
"-----END CERTIFICATE REQUEST-----",
buf, NULL, 0, &use_len );
if( ret == 0 )
{
/*
* Was PEM encoded, parse the result
*/
if( ( ret = mbedtls_x509_csr_parse_der( csr, pem.buf, pem.buflen ) ) != 0 )
return( ret );
if( ret == 0 )
/*
* Was PEM encoded, parse the result
*/
ret = mbedtls_x509_csr_parse_der( csr, pem.buf, pem.buflen );
mbedtls_pem_free( &pem );
return( 0 );
}
else if( ret != MBEDTLS_ERR_PEM_NO_HEADER_FOOTER_PRESENT )
{
mbedtls_pem_free( &pem );
return( ret );
if( ret != MBEDTLS_ERR_PEM_NO_HEADER_FOOTER_PRESENT )
return( ret );
}
else
#endif /* MBEDTLS_PEM_PARSE_C */
return( mbedtls_x509_csr_parse_der( csr, buf, buflen ) );
}
......
Markdown is supported
0% or .
You are about to add 0 people to the discussion. Proceed with caution.
Finish editing this message first!
Please register or to comment